Fix some lint errors in url_request_context_adapter
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob14191f2273bf1042a61487c1c31e97fef86359e6
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 'ImageInternalFormat': {
1185 'type': 'GLenum',
1186 'valid': [
1187 'GL_RGB',
1188 'GL_RGBA',
1191 'ImageUsage': {
1192 'type': 'GLenum',
1193 'valid': [
1194 'GL_MAP_CHROMIUM',
1195 'GL_SCANOUT_CHROMIUM'
1198 'VertexAttribType': {
1199 'type': 'GLenum',
1200 'valid': [
1201 'GL_BYTE',
1202 'GL_UNSIGNED_BYTE',
1203 'GL_SHORT',
1204 'GL_UNSIGNED_SHORT',
1205 # 'GL_FIXED', // This is not available on Desktop GL.
1206 'GL_FLOAT',
1208 'invalid': [
1209 'GL_DOUBLE',
1212 'TextureBorder': {
1213 'type': 'GLint',
1214 'is_complete': True,
1215 'valid': [
1216 '0',
1218 'invalid': [
1219 '1',
1222 'VertexAttribSize': {
1223 'type': 'GLint',
1224 'valid': [
1225 '1',
1226 '2',
1227 '3',
1228 '4',
1230 'invalid': [
1231 '0',
1232 '5',
1235 'ZeroOnly': {
1236 'type': 'GLint',
1237 'is_complete': True,
1238 'valid': [
1239 '0',
1241 'invalid': [
1242 '1',
1245 'FalseOnly': {
1246 'type': 'GLboolean',
1247 'is_complete': True,
1248 'valid': [
1249 'false',
1251 'invalid': [
1252 'true',
1255 'ResetStatus': {
1256 'type': 'GLenum',
1257 'valid': [
1258 'GL_GUILTY_CONTEXT_RESET_ARB',
1259 'GL_INNOCENT_CONTEXT_RESET_ARB',
1260 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1265 # This table specifies the different pepper interfaces that are supported for
1266 # GL commands. 'dev' is true if it's a dev interface.
1267 _PEPPER_INTERFACES = [
1268 {'name': '', 'dev': False},
1269 {'name': 'InstancedArrays', 'dev': False},
1270 {'name': 'FramebufferBlit', 'dev': False},
1271 {'name': 'FramebufferMultisample', 'dev': False},
1272 {'name': 'ChromiumEnableFeature', 'dev': False},
1273 {'name': 'ChromiumMapSub', 'dev': False},
1274 {'name': 'Query', 'dev': False},
1275 {'name': 'VertexArrayObject', 'dev': False},
1276 {'name': 'DrawBuffers', 'dev': True},
1279 # A function info object specifies the type and other special data for the
1280 # command that will be generated. A base function info object is generated by
1281 # parsing the "cmd_buffer_functions.txt", one for each function in the
1282 # file. These function info objects can be augmented and their values can be
1283 # overridden by adding an object to the table below.
1285 # Must match function names specified in "cmd_buffer_functions.txt".
1287 # cmd_comment: A comment added to the cmd format.
1288 # type: defines which handler will be used to generate code.
1289 # decoder_func: defines which function to call in the decoder to execute the
1290 # corresponding GL command. If not specified the GL command will
1291 # be called directly.
1292 # gl_test_func: GL function that is expected to be called when testing.
1293 # cmd_args: The arguments to use for the command. This overrides generating
1294 # them based on the GL function arguments.
1295 # gen_cmd: Whether or not this function geneates a command. Default = True.
1296 # data_transfer_methods: Array of methods that are used for transfering the
1297 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1298 # The default is 'immediate' if the command has one pointer
1299 # argument, otherwise 'shm'. One command is generated for each
1300 # transfer method. Affects only commands which are not of type
1301 # 'HandWritten', 'GETn' or 'GLcharN'.
1302 # Note: the command arguments that affect this are the final args,
1303 # taking cmd_args override into consideration.
1304 # impl_func: Whether or not to generate the GLES2Implementation part of this
1305 # command.
1306 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1307 # for this command.
1308 # needs_size: If true a data_size field is added to the command.
1309 # count: The number of units per element. For PUTn or PUT types.
1310 # unit_test: If False no service side unit test will be generated.
1311 # client_test: If False no client side unit test will be generated.
1312 # expectation: If False the unit test will have no expected calls.
1313 # gen_func: Name of function that generates GL resource for corresponding
1314 # bind function.
1315 # states: array of states that get set by this function corresponding to
1316 # the given arguments
1317 # state_flag: name of flag that is set to true when function is called.
1318 # no_gl: no GL function is called.
1319 # valid_args: A dictionary of argument indices to args to use in unit tests
1320 # when they can not be automatically determined.
1321 # pepper_interface: The pepper interface that is used for this extension
1322 # pepper_name: The name of the function as exposed to pepper.
1323 # pepper_args: A string representing the argument list (what would appear in
1324 # C/C++ between the parentheses for the function declaration)
1325 # that the Pepper API expects for this function. Use this only if
1326 # the stable Pepper API differs from the GLES2 argument list.
1327 # invalid_test: False if no invalid test needed.
1328 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1329 # first_element_only: For PUT types, True if only the first element of an
1330 # array is used and we end up calling the single value
1331 # corresponding function. eg. TexParameteriv -> TexParameteri
1332 # extension: Function is an extension to GL and should not be exposed to
1333 # pepper unless pepper_interface is defined.
1334 # extension_flag: Function is an extension and should be enabled only when
1335 # the corresponding feature info flag is enabled. Implies
1336 # 'extension': True.
1337 # not_shared: For GENn types, True if objects can't be shared between contexts
1339 _FUNCTION_INFO = {
1340 'ActiveTexture': {
1341 'decoder_func': 'DoActiveTexture',
1342 'unit_test': False,
1343 'impl_func': False,
1344 'client_test': False,
1346 'AttachShader': {'decoder_func': 'DoAttachShader'},
1347 'BindAttribLocation': {
1348 'type': 'GLchar',
1349 'data_transfer_methods': ['bucket'],
1350 'needs_size': True,
1352 'BindBuffer': {
1353 'type': 'Bind',
1354 'decoder_func': 'DoBindBuffer',
1355 'gen_func': 'GenBuffersARB',
1357 'BindFramebuffer': {
1358 'type': 'Bind',
1359 'decoder_func': 'DoBindFramebuffer',
1360 'gl_test_func': 'glBindFramebufferEXT',
1361 'gen_func': 'GenFramebuffersEXT',
1362 'trace_level': 1,
1364 'BindRenderbuffer': {
1365 'type': 'Bind',
1366 'decoder_func': 'DoBindRenderbuffer',
1367 'gl_test_func': 'glBindRenderbufferEXT',
1368 'gen_func': 'GenRenderbuffersEXT',
1370 'BindTexture': {
1371 'type': 'Bind',
1372 'decoder_func': 'DoBindTexture',
1373 'gen_func': 'GenTextures',
1374 # TODO(gman): remove this once client side caching works.
1375 'client_test': False,
1376 'trace_level': 1,
1378 'BlitFramebufferCHROMIUM': {
1379 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1380 'unit_test': False,
1381 'extension_flag': 'chromium_framebuffer_multisample',
1382 'pepper_interface': 'FramebufferBlit',
1383 'pepper_name': 'BlitFramebufferEXT',
1384 'defer_reads': True,
1385 'defer_draws': True,
1386 'trace_level': 1,
1388 'BufferData': {
1389 'type': 'Manual',
1390 'data_transfer_methods': ['shm'],
1391 'client_test': False,
1393 'BufferSubData': {
1394 'type': 'Data',
1395 'client_test': False,
1396 'decoder_func': 'DoBufferSubData',
1397 'data_transfer_methods': ['shm'],
1399 'CheckFramebufferStatus': {
1400 'type': 'Is',
1401 'decoder_func': 'DoCheckFramebufferStatus',
1402 'gl_test_func': 'glCheckFramebufferStatusEXT',
1403 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1404 'result': ['GLenum'],
1406 'Clear': {
1407 'decoder_func': 'DoClear',
1408 'defer_draws': True,
1409 'trace_level': 1,
1411 'ClearColor': {
1412 'type': 'StateSet',
1413 'state': 'ClearColor',
1415 'ClearDepthf': {
1416 'type': 'StateSet',
1417 'state': 'ClearDepthf',
1418 'decoder_func': 'glClearDepth',
1419 'gl_test_func': 'glClearDepth',
1420 'valid_args': {
1421 '0': '0.5f'
1424 'ColorMask': {
1425 'type': 'StateSet',
1426 'state': 'ColorMask',
1427 'no_gl': True,
1428 'expectation': False,
1430 'ConsumeTextureCHROMIUM': {
1431 'decoder_func': 'DoConsumeTextureCHROMIUM',
1432 'impl_func': False,
1433 'type': 'PUT',
1434 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1435 'unit_test': False,
1436 'client_test': False,
1437 'extension': "CHROMIUM_texture_mailbox",
1438 'chromium': True,
1439 'trace_level': 1,
1441 'CreateAndConsumeTextureCHROMIUM': {
1442 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1443 'impl_func': False,
1444 'type': 'HandWritten',
1445 'data_transfer_methods': ['immediate'],
1446 'unit_test': False,
1447 'client_test': False,
1448 'extension': "CHROMIUM_texture_mailbox",
1449 'chromium': True,
1451 'ClearStencil': {
1452 'type': 'StateSet',
1453 'state': 'ClearStencil',
1455 'EnableFeatureCHROMIUM': {
1456 'type': 'Custom',
1457 'data_transfer_methods': ['shm'],
1458 'decoder_func': 'DoEnableFeatureCHROMIUM',
1459 'expectation': False,
1460 'cmd_args': 'GLuint bucket_id, GLint* result',
1461 'result': ['GLint'],
1462 'extension': True,
1463 'chromium': True,
1464 'pepper_interface': 'ChromiumEnableFeature',
1466 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1467 'CompressedTexImage2D': {
1468 'type': 'Manual',
1469 'data_transfer_methods': ['bucket', 'shm'],
1471 'CompressedTexSubImage2D': {
1472 'type': 'Data',
1473 'data_transfer_methods': ['bucket', 'shm'],
1474 'decoder_func': 'DoCompressedTexSubImage2D',
1476 'CopyTexImage2D': {
1477 'decoder_func': 'DoCopyTexImage2D',
1478 'unit_test': False,
1479 'defer_reads': True,
1481 'CopyTexSubImage2D': {
1482 'decoder_func': 'DoCopyTexSubImage2D',
1483 'defer_reads': True,
1485 'CreateImageCHROMIUM': {
1486 'type': 'Manual',
1487 'cmd_args':
1488 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1489 'GLenum internalformat',
1490 'result': ['GLuint'],
1491 'client_test': False,
1492 'gen_cmd': False,
1493 'expectation': False,
1494 'extension': True,
1495 'chromium': True,
1497 'DestroyImageCHROMIUM': {
1498 'type': 'Manual',
1499 'client_test': False,
1500 'gen_cmd': False,
1501 'extension': True,
1502 'chromium': True,
1504 'CreateGpuMemoryBufferImageCHROMIUM': {
1505 'type': 'Manual',
1506 'cmd_args':
1507 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1508 'result': ['GLuint'],
1509 'client_test': False,
1510 'gen_cmd': False,
1511 'expectation': False,
1512 'extension': True,
1513 'chromium': True,
1515 'CreateProgram': {
1516 'type': 'Create',
1517 'client_test': False,
1519 'CreateShader': {
1520 'type': 'Create',
1521 'client_test': False,
1523 'BlendColor': {
1524 'type': 'StateSet',
1525 'state': 'BlendColor',
1527 'BlendEquation': {
1528 'type': 'StateSetRGBAlpha',
1529 'state': 'BlendEquation',
1530 'valid_args': {
1531 '0': 'GL_FUNC_SUBTRACT'
1534 'BlendEquationSeparate': {
1535 'type': 'StateSet',
1536 'state': 'BlendEquation',
1537 'valid_args': {
1538 '0': 'GL_FUNC_SUBTRACT'
1541 'BlendFunc': {
1542 'type': 'StateSetRGBAlpha',
1543 'state': 'BlendFunc',
1545 'BlendFuncSeparate': {
1546 'type': 'StateSet',
1547 'state': 'BlendFunc',
1549 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1550 'StencilFunc': {
1551 'type': 'StateSetFrontBack',
1552 'state': 'StencilFunc',
1554 'StencilFuncSeparate': {
1555 'type': 'StateSetFrontBackSeparate',
1556 'state': 'StencilFunc',
1558 'StencilOp': {
1559 'type': 'StateSetFrontBack',
1560 'state': 'StencilOp',
1561 'valid_args': {
1562 '1': 'GL_INCR'
1565 'StencilOpSeparate': {
1566 'type': 'StateSetFrontBackSeparate',
1567 'state': 'StencilOp',
1568 'valid_args': {
1569 '1': 'GL_INCR'
1572 'Hint': {
1573 'type': 'StateSetNamedParameter',
1574 'state': 'Hint',
1576 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1577 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1578 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1579 'LineWidth': {
1580 'type': 'StateSet',
1581 'state': 'LineWidth',
1582 'valid_args': {
1583 '0': '0.5f'
1586 'PolygonOffset': {
1587 'type': 'StateSet',
1588 'state': 'PolygonOffset',
1590 'DeleteBuffers': {
1591 'type': 'DELn',
1592 'gl_test_func': 'glDeleteBuffersARB',
1593 'resource_type': 'Buffer',
1594 'resource_types': 'Buffers',
1596 'DeleteFramebuffers': {
1597 'type': 'DELn',
1598 'gl_test_func': 'glDeleteFramebuffersEXT',
1599 'resource_type': 'Framebuffer',
1600 'resource_types': 'Framebuffers',
1602 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1603 'DeleteRenderbuffers': {
1604 'type': 'DELn',
1605 'gl_test_func': 'glDeleteRenderbuffersEXT',
1606 'resource_type': 'Renderbuffer',
1607 'resource_types': 'Renderbuffers',
1609 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1610 'DeleteTextures': {
1611 'type': 'DELn',
1612 'resource_type': 'Texture',
1613 'resource_types': 'Textures',
1615 'DepthRangef': {
1616 'decoder_func': 'DoDepthRangef',
1617 'gl_test_func': 'glDepthRange',
1619 'DepthMask': {
1620 'type': 'StateSet',
1621 'state': 'DepthMask',
1622 'no_gl': True,
1623 'expectation': False,
1625 'DetachShader': {'decoder_func': 'DoDetachShader'},
1626 'Disable': {
1627 'decoder_func': 'DoDisable',
1628 'impl_func': False,
1629 'client_test': False,
1631 'DisableVertexAttribArray': {
1632 'decoder_func': 'DoDisableVertexAttribArray',
1633 'impl_decl': False,
1635 'DrawArrays': {
1636 'type': 'Manual',
1637 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1638 'defer_draws': True,
1639 'trace_level': 2,
1641 'DrawElements': {
1642 'type': 'Manual',
1643 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1644 'GLenumIndexType type, GLuint index_offset',
1645 'client_test': False,
1646 'defer_draws': True,
1647 'trace_level': 2,
1649 'Enable': {
1650 'decoder_func': 'DoEnable',
1651 'impl_func': False,
1652 'client_test': False,
1654 'EnableVertexAttribArray': {
1655 'decoder_func': 'DoEnableVertexAttribArray',
1656 'impl_decl': False,
1658 'Finish': {
1659 'impl_func': False,
1660 'client_test': False,
1661 'decoder_func': 'DoFinish',
1662 'defer_reads': True,
1664 'Flush': {
1665 'impl_func': False,
1666 'decoder_func': 'DoFlush',
1668 'FramebufferRenderbuffer': {
1669 'decoder_func': 'DoFramebufferRenderbuffer',
1670 'gl_test_func': 'glFramebufferRenderbufferEXT',
1672 'FramebufferTexture2D': {
1673 'decoder_func': 'DoFramebufferTexture2D',
1674 'gl_test_func': 'glFramebufferTexture2DEXT',
1675 'trace_level': 1,
1677 'FramebufferTexture2DMultisampleEXT': {
1678 'decoder_func': 'DoFramebufferTexture2DMultisample',
1679 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1680 'expectation': False,
1681 'unit_test': False,
1682 'extension_flag': 'multisampled_render_to_texture',
1683 'trace_level': 1,
1685 'GenerateMipmap': {
1686 'decoder_func': 'DoGenerateMipmap',
1687 'gl_test_func': 'glGenerateMipmapEXT',
1689 'GenBuffers': {
1690 'type': 'GENn',
1691 'gl_test_func': 'glGenBuffersARB',
1692 'resource_type': 'Buffer',
1693 'resource_types': 'Buffers',
1695 'GenMailboxCHROMIUM': {
1696 'type': 'HandWritten',
1697 'impl_func': False,
1698 'extension': "CHROMIUM_texture_mailbox",
1699 'chromium': True,
1701 'GenFramebuffers': {
1702 'type': 'GENn',
1703 'gl_test_func': 'glGenFramebuffersEXT',
1704 'resource_type': 'Framebuffer',
1705 'resource_types': 'Framebuffers',
1707 'GenRenderbuffers': {
1708 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1709 'resource_type': 'Renderbuffer',
1710 'resource_types': 'Renderbuffers',
1712 'GenTextures': {
1713 'type': 'GENn',
1714 'gl_test_func': 'glGenTextures',
1715 'resource_type': 'Texture',
1716 'resource_types': 'Textures',
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 'MapTexSubImage2DCHROMIUM': {
1989 'gen_cmd': False,
1990 'extension': True,
1991 'chromium': True,
1992 'client_test': False,
1993 'pepper_interface': 'ChromiumMapSub',
1995 'PixelStorei': {'type': 'Manual'},
1996 'PostSubBufferCHROMIUM': {
1997 'type': 'Custom',
1998 'impl_func': False,
1999 'unit_test': False,
2000 'client_test': False,
2001 'extension': True,
2002 'chromium': True,
2004 'ProduceTextureCHROMIUM': {
2005 'decoder_func': 'DoProduceTextureCHROMIUM',
2006 'impl_func': False,
2007 'type': 'PUT',
2008 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2009 'unit_test': False,
2010 'client_test': False,
2011 'extension': "CHROMIUM_texture_mailbox",
2012 'chromium': True,
2013 'trace_level': 1,
2015 'ProduceTextureDirectCHROMIUM': {
2016 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2017 'impl_func': False,
2018 'type': 'PUT',
2019 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2020 'unit_test': False,
2021 'client_test': False,
2022 'extension': "CHROMIUM_texture_mailbox",
2023 'chromium': True,
2024 'trace_level': 1,
2026 'RenderbufferStorage': {
2027 'decoder_func': 'DoRenderbufferStorage',
2028 'gl_test_func': 'glRenderbufferStorageEXT',
2029 'expectation': False,
2031 'RenderbufferStorageMultisampleCHROMIUM': {
2032 'cmd_comment':
2033 '// GL_CHROMIUM_framebuffer_multisample\n',
2034 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2035 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2036 'expectation': False,
2037 'unit_test': False,
2038 'extension_flag': 'chromium_framebuffer_multisample',
2039 'pepper_interface': 'FramebufferMultisample',
2040 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2042 'RenderbufferStorageMultisampleEXT': {
2043 'cmd_comment':
2044 '// GL_EXT_multisampled_render_to_texture\n',
2045 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2046 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2047 'expectation': False,
2048 'unit_test': False,
2049 'extension_flag': 'multisampled_render_to_texture',
2051 'ReadPixels': {
2052 'cmd_comment':
2053 '// ReadPixels has the result separated from the pixel buffer so that\n'
2054 '// it is easier to specify the result going to some specific place\n'
2055 '// that exactly fits the rectangle of pixels.\n',
2056 'type': 'Custom',
2057 'data_transfer_methods': ['shm'],
2058 'impl_func': False,
2059 'client_test': False,
2060 'cmd_args':
2061 'GLint x, GLint y, GLsizei width, GLsizei height, '
2062 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2063 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2064 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2065 'GLboolean async',
2066 'result': ['uint32_t'],
2067 'defer_reads': True,
2069 'ReleaseShaderCompiler': {
2070 'decoder_func': 'DoReleaseShaderCompiler',
2071 'unit_test': False,
2073 'ShaderBinary': {
2074 'type': 'Custom',
2075 'client_test': False,
2077 'ShaderSource': {
2078 'type': 'Manual',
2079 'data_transfer_methods': ['bucket'],
2080 'needs_size': True,
2081 'client_test': False,
2082 'cmd_args':
2083 'GLuint shader, const char* data',
2084 'pepper_args':
2085 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2087 'StencilMask': {
2088 'type': 'StateSetFrontBack',
2089 'state': 'StencilMask',
2090 'no_gl': True,
2091 'expectation': False,
2093 'StencilMaskSeparate': {
2094 'type': 'StateSetFrontBackSeparate',
2095 'state': 'StencilMask',
2096 'no_gl': True,
2097 'expectation': False,
2099 'SwapBuffers': {
2100 'impl_func': False,
2101 'decoder_func': 'DoSwapBuffers',
2102 'unit_test': False,
2103 'client_test': False,
2104 'extension': True,
2105 'trace_level': 1,
2107 'TexImage2D': {
2108 'type': 'Manual',
2109 'data_transfer_methods': ['shm'],
2110 'client_test': False,
2112 'TexParameterf': {
2113 'decoder_func': 'DoTexParameterf',
2114 'valid_args': {
2115 '2': 'GL_NEAREST'
2118 'TexParameteri': {
2119 'decoder_func': 'DoTexParameteri',
2120 'valid_args': {
2121 '2': 'GL_NEAREST'
2124 'TexParameterfv': {
2125 'type': 'PUT',
2126 'data_value': 'GL_NEAREST',
2127 'count': 1,
2128 'decoder_func': 'DoTexParameterfv',
2129 'gl_test_func': 'glTexParameterf',
2130 'first_element_only': True,
2132 'TexParameteriv': {
2133 'type': 'PUT',
2134 'data_value': 'GL_NEAREST',
2135 'count': 1,
2136 'decoder_func': 'DoTexParameteriv',
2137 'gl_test_func': 'glTexParameteri',
2138 'first_element_only': True,
2140 'TexSubImage2D': {
2141 'type': 'Manual',
2142 'data_transfer_methods': ['shm'],
2143 'client_test': False,
2144 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2145 'GLint xoffset, GLint yoffset, '
2146 'GLsizei width, GLsizei height, '
2147 'GLenumTextureFormat format, GLenumPixelType type, '
2148 'const void* pixels, GLboolean internal'
2150 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2151 'Uniform1fv': {
2152 'type': 'PUTn',
2153 'count': 1,
2154 'decoder_func': 'DoUniform1fv',
2156 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2157 'Uniform1iv': {
2158 'type': 'PUTn',
2159 'count': 1,
2160 'decoder_func': 'DoUniform1iv',
2161 'unit_test': False,
2163 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2164 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2165 'Uniform2fv': {
2166 'type': 'PUTn',
2167 'count': 2,
2168 'decoder_func': 'DoUniform2fv',
2170 'Uniform2iv': {
2171 'type': 'PUTn',
2172 'count': 2,
2173 'decoder_func': 'DoUniform2iv',
2175 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2176 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2177 'Uniform3fv': {
2178 'type': 'PUTn',
2179 'count': 3,
2180 'decoder_func': 'DoUniform3fv',
2182 'Uniform3iv': {
2183 'type': 'PUTn',
2184 'count': 3,
2185 'decoder_func': 'DoUniform3iv',
2187 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2188 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2189 'Uniform4fv': {
2190 'type': 'PUTn',
2191 'count': 4,
2192 'decoder_func': 'DoUniform4fv',
2194 'Uniform4iv': {
2195 'type': 'PUTn',
2196 'count': 4,
2197 'decoder_func': 'DoUniform4iv',
2199 'UniformMatrix2fv': {
2200 'type': 'PUTn',
2201 'count': 4,
2202 'decoder_func': 'DoUniformMatrix2fv',
2204 'UniformMatrix3fv': {
2205 'type': 'PUTn',
2206 'count': 9,
2207 'decoder_func': 'DoUniformMatrix3fv',
2209 'UniformMatrix4fv': {
2210 'type': 'PUTn',
2211 'count': 16,
2212 'decoder_func': 'DoUniformMatrix4fv',
2214 'UnmapBufferCHROMIUM': {
2215 'gen_cmd': False,
2216 'extension': True,
2217 'chromium': True,
2218 'client_test': False,
2220 'UnmapBufferSubDataCHROMIUM': {
2221 'gen_cmd': False,
2222 'extension': True,
2223 'chromium': True,
2224 'client_test': False,
2225 'pepper_interface': 'ChromiumMapSub',
2227 'UnmapTexSubImage2DCHROMIUM': {
2228 'gen_cmd': False,
2229 'extension': True,
2230 'chromium': True,
2231 'client_test': False,
2232 'pepper_interface': 'ChromiumMapSub',
2234 'UseProgram': {
2235 'type': 'Bind',
2236 'decoder_func': 'DoUseProgram',
2238 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2239 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2240 'VertexAttrib1fv': {
2241 'type': 'PUT',
2242 'count': 1,
2243 'decoder_func': 'DoVertexAttrib1fv',
2245 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2246 'VertexAttrib2fv': {
2247 'type': 'PUT',
2248 'count': 2,
2249 'decoder_func': 'DoVertexAttrib2fv',
2251 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2252 'VertexAttrib3fv': {
2253 'type': 'PUT',
2254 'count': 3,
2255 'decoder_func': 'DoVertexAttrib3fv',
2257 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2258 'VertexAttrib4fv': {
2259 'type': 'PUT',
2260 'count': 4,
2261 'decoder_func': 'DoVertexAttrib4fv',
2263 'VertexAttribPointer': {
2264 'type': 'Manual',
2265 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2266 'GLenumVertexAttribType type, GLboolean normalized, '
2267 'GLsizei stride, GLuint offset',
2268 'client_test': False,
2270 'Scissor': {
2271 'type': 'StateSet',
2272 'state': 'Scissor',
2274 'Viewport': {
2275 'decoder_func': 'DoViewport',
2277 'ResizeCHROMIUM': {
2278 'type': 'Custom',
2279 'impl_func': False,
2280 'unit_test': False,
2281 'extension': True,
2282 'chromium': True,
2284 'GetRequestableExtensionsCHROMIUM': {
2285 'type': 'Custom',
2286 'impl_func': False,
2287 'cmd_args': 'uint32_t bucket_id',
2288 'extension': True,
2289 'chromium': True,
2291 'RequestExtensionCHROMIUM': {
2292 'type': 'Custom',
2293 'impl_func': False,
2294 'client_test': False,
2295 'cmd_args': 'uint32_t bucket_id',
2296 'extension': True,
2297 'chromium': True,
2299 'RateLimitOffscreenContextCHROMIUM': {
2300 'gen_cmd': False,
2301 'extension': True,
2302 'chromium': True,
2303 'client_test': False,
2305 'CreateStreamTextureCHROMIUM': {
2306 'type': 'HandWritten',
2307 'impl_func': False,
2308 'gen_cmd': False,
2309 'extension': True,
2310 'chromium': True,
2312 'TexImageIOSurface2DCHROMIUM': {
2313 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2314 'unit_test': False,
2315 'extension': True,
2316 'chromium': True,
2318 'CopyTextureCHROMIUM': {
2319 'decoder_func': 'DoCopyTextureCHROMIUM',
2320 'unit_test': False,
2321 'extension': True,
2322 'chromium': True,
2324 'TexStorage2DEXT': {
2325 'unit_test': False,
2326 'extension': True,
2327 'decoder_func': 'DoTexStorage2DEXT',
2329 'DrawArraysInstancedANGLE': {
2330 'type': 'Manual',
2331 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2332 'GLsizei primcount',
2333 'extension': True,
2334 'unit_test': False,
2335 'pepper_interface': 'InstancedArrays',
2336 'defer_draws': True,
2338 'DrawBuffersEXT': {
2339 'type': 'PUTn',
2340 'decoder_func': 'DoDrawBuffersEXT',
2341 'count': 1,
2342 'client_test': False,
2343 'unit_test': False,
2344 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2345 # work without.
2346 'extension': True,
2347 'pepper_interface': 'DrawBuffers',
2349 'DrawElementsInstancedANGLE': {
2350 'type': 'Manual',
2351 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2352 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2353 'extension': True,
2354 'unit_test': False,
2355 'client_test': False,
2356 'pepper_interface': 'InstancedArrays',
2357 'defer_draws': True,
2359 'VertexAttribDivisorANGLE': {
2360 'type': 'Manual',
2361 'cmd_args': 'GLuint index, GLuint divisor',
2362 'extension': True,
2363 'unit_test': False,
2364 'pepper_interface': 'InstancedArrays',
2366 'GenQueriesEXT': {
2367 'type': 'GENn',
2368 'gl_test_func': 'glGenQueriesARB',
2369 'resource_type': 'Query',
2370 'resource_types': 'Queries',
2371 'unit_test': False,
2372 'pepper_interface': 'Query',
2373 'not_shared': 'True',
2375 'DeleteQueriesEXT': {
2376 'type': 'DELn',
2377 'gl_test_func': 'glDeleteQueriesARB',
2378 'resource_type': 'Query',
2379 'resource_types': 'Queries',
2380 'unit_test': False,
2381 'pepper_interface': 'Query',
2383 'IsQueryEXT': {
2384 'gen_cmd': False,
2385 'client_test': False,
2386 'pepper_interface': 'Query',
2388 'BeginQueryEXT': {
2389 'type': 'Manual',
2390 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2391 'data_transfer_methods': ['shm'],
2392 'gl_test_func': 'glBeginQuery',
2393 'pepper_interface': 'Query',
2395 'EndQueryEXT': {
2396 'type': 'Manual',
2397 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2398 'gl_test_func': 'glEndnQuery',
2399 'client_test': False,
2400 'pepper_interface': 'Query',
2402 'GetQueryivEXT': {
2403 'gen_cmd': False,
2404 'client_test': False,
2405 'gl_test_func': 'glGetQueryiv',
2406 'pepper_interface': 'Query',
2408 'GetQueryObjectuivEXT': {
2409 'gen_cmd': False,
2410 'client_test': False,
2411 'gl_test_func': 'glGetQueryObjectuiv',
2412 'pepper_interface': 'Query',
2414 'BindUniformLocationCHROMIUM': {
2415 'type': 'GLchar',
2416 'extension': True,
2417 'data_transfer_methods': ['bucket'],
2418 'needs_size': True,
2419 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2421 'InsertEventMarkerEXT': {
2422 'type': 'GLcharN',
2423 'decoder_func': 'DoInsertEventMarkerEXT',
2424 'expectation': False,
2425 'extension': True,
2427 'PushGroupMarkerEXT': {
2428 'type': 'GLcharN',
2429 'decoder_func': 'DoPushGroupMarkerEXT',
2430 'expectation': False,
2431 'extension': True,
2433 'PopGroupMarkerEXT': {
2434 'decoder_func': 'DoPopGroupMarkerEXT',
2435 'expectation': False,
2436 'extension': True,
2437 'impl_func': False,
2440 'GenVertexArraysOES': {
2441 'type': 'GENn',
2442 'extension': True,
2443 'gl_test_func': 'glGenVertexArraysOES',
2444 'resource_type': 'VertexArray',
2445 'resource_types': 'VertexArrays',
2446 'unit_test': False,
2447 'pepper_interface': 'VertexArrayObject',
2449 'BindVertexArrayOES': {
2450 'type': 'Bind',
2451 'extension': True,
2452 'gl_test_func': 'glBindVertexArrayOES',
2453 'decoder_func': 'DoBindVertexArrayOES',
2454 'gen_func': 'GenVertexArraysOES',
2455 'unit_test': False,
2456 'client_test': False,
2457 'pepper_interface': 'VertexArrayObject',
2459 'DeleteVertexArraysOES': {
2460 'type': 'DELn',
2461 'extension': True,
2462 'gl_test_func': 'glDeleteVertexArraysOES',
2463 'resource_type': 'VertexArray',
2464 'resource_types': 'VertexArrays',
2465 'unit_test': False,
2466 'pepper_interface': 'VertexArrayObject',
2468 'IsVertexArrayOES': {
2469 'type': 'Is',
2470 'extension': True,
2471 'gl_test_func': 'glIsVertexArrayOES',
2472 'decoder_func': 'DoIsVertexArrayOES',
2473 'expectation': False,
2474 'unit_test': False,
2475 'pepper_interface': 'VertexArrayObject',
2477 'BindTexImage2DCHROMIUM': {
2478 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2479 'unit_test': False,
2480 'extension': True,
2481 'chromium': True,
2483 'ReleaseTexImage2DCHROMIUM': {
2484 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2485 'unit_test': False,
2486 'extension': True,
2487 'chromium': True,
2489 'ShallowFinishCHROMIUM': {
2490 'impl_func': False,
2491 'gen_cmd': False,
2492 'extension': True,
2493 'chromium': True,
2494 'client_test': False,
2496 'ShallowFlushCHROMIUM': {
2497 'impl_func': False,
2498 'gen_cmd': False,
2499 'extension': True,
2500 'chromium': True,
2501 'client_test': False,
2503 'TraceBeginCHROMIUM': {
2504 'type': 'Custom',
2505 'impl_func': False,
2506 'client_test': False,
2507 'cmd_args': 'GLuint bucket_id',
2508 'extension': True,
2509 'chromium': True,
2511 'TraceEndCHROMIUM': {
2512 'impl_func': False,
2513 'client_test': False,
2514 'decoder_func': 'DoTraceEndCHROMIUM',
2515 'unit_test': False,
2516 'extension': True,
2517 'chromium': True,
2519 'AsyncTexImage2DCHROMIUM': {
2520 'type': 'Manual',
2521 'data_transfer_methods': ['shm'],
2522 'client_test': False,
2523 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2524 'GLintTextureInternalFormat internalformat, '
2525 'GLsizei width, GLsizei height, '
2526 'GLintTextureBorder border, '
2527 'GLenumTextureFormat format, GLenumPixelType type, '
2528 'const void* pixels, '
2529 'uint32_t async_upload_token, '
2530 'void* sync_data',
2531 'extension': True,
2532 'chromium': True,
2534 'AsyncTexSubImage2DCHROMIUM': {
2535 'type': 'Manual',
2536 'data_transfer_methods': ['shm'],
2537 'client_test': False,
2538 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2539 'GLint xoffset, GLint yoffset, '
2540 'GLsizei width, GLsizei height, '
2541 'GLenumTextureFormat format, GLenumPixelType type, '
2542 'const void* data, '
2543 'uint32_t async_upload_token, '
2544 'void* sync_data',
2545 'extension': True,
2546 'chromium': True,
2548 'WaitAsyncTexImage2DCHROMIUM': {
2549 'type': 'Manual',
2550 'client_test': False,
2551 'extension': True,
2552 'chromium': True,
2554 'WaitAllAsyncTexImage2DCHROMIUM': {
2555 'type': 'Manual',
2556 'client_test': False,
2557 'extension': True,
2558 'chromium': True,
2560 'DiscardFramebufferEXT': {
2561 'type': 'PUTn',
2562 'count': 1,
2563 'cmd_args': 'GLenum target, GLsizei count, '
2564 'const GLenum* attachments',
2565 'decoder_func': 'DoDiscardFramebufferEXT',
2566 'unit_test': False,
2567 'client_test': False,
2568 'extension_flag': 'ext_discard_framebuffer',
2570 'LoseContextCHROMIUM': {
2571 'decoder_func': 'DoLoseContextCHROMIUM',
2572 'unit_test': False,
2573 'extension': True,
2574 'chromium': True,
2576 'InsertSyncPointCHROMIUM': {
2577 'type': 'HandWritten',
2578 'impl_func': False,
2579 'extension': "CHROMIUM_sync_point",
2580 'chromium': True,
2582 'WaitSyncPointCHROMIUM': {
2583 'type': 'Custom',
2584 'impl_func': True,
2585 'extension': "CHROMIUM_sync_point",
2586 'chromium': True,
2587 'trace_level': 1,
2589 'DiscardBackbufferCHROMIUM': {
2590 'type': 'Custom',
2591 'impl_func': True,
2592 'extension': True,
2593 'chromium': True,
2595 'ScheduleOverlayPlaneCHROMIUM': {
2596 'type': 'Custom',
2597 'impl_func': True,
2598 'unit_test': False,
2599 'client_test': False,
2600 'extension': True,
2601 'chromium': True,
2603 'MatrixLoadfCHROMIUM': {
2604 'type': 'PUT',
2605 'count': 16,
2606 'data_type': 'GLfloat',
2607 'decoder_func': 'DoMatrixLoadfCHROMIUM',
2608 'gl_test_func': 'glMatrixLoadfEXT',
2609 'chromium': True,
2610 'extension': True,
2611 'extension_flag': 'chromium_path_rendering',
2613 'MatrixLoadIdentityCHROMIUM': {
2614 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
2615 'gl_test_func': 'glMatrixLoadIdentityEXT',
2616 'chromium': True,
2617 'extension': True,
2618 'extension_flag': 'chromium_path_rendering',
2623 def Grouper(n, iterable, fillvalue=None):
2624 """Collect data into fixed-length chunks or blocks"""
2625 args = [iter(iterable)] * n
2626 return itertools.izip_longest(fillvalue=fillvalue, *args)
2629 def SplitWords(input_string):
2630 """Transforms a input_string into a list of lower-case components.
2632 Args:
2633 input_string: the input string.
2635 Returns:
2636 a list of lower-case words.
2638 if input_string.find('_') > -1:
2639 # 'some_TEXT_' -> 'some text'
2640 return input_string.replace('_', ' ').strip().lower().split()
2641 else:
2642 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2643 # mixed case.
2644 # look for capitalization to cut input_strings
2645 # 'SomeText' -> 'Some Text'
2646 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2647 # 'Vector3' -> 'Vector 3'
2648 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2649 return input_string.lower().split()
2652 def Lower(words):
2653 """Makes a lower-case identifier from words.
2655 Args:
2656 words: a list of lower-case words.
2658 Returns:
2659 the lower-case identifier.
2661 return '_'.join(words)
2664 def ToUnderscore(input_string):
2665 """converts CamelCase to camel_case."""
2666 words = SplitWords(input_string)
2667 return Lower(words)
2669 def CachedStateName(item):
2670 if item.get('cached', False):
2671 return 'cached_' + item['name']
2672 return item['name']
2674 def ToGLExtensionString(extension_flag):
2675 """Returns GL-type extension string of a extension flag."""
2676 if extension_flag == "oes_compressed_etc1_rgb8_texture":
2677 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
2678 # unfortunate.
2679 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
2680 'egl', 'atc', 'etc1', 'angle']
2681 parts = extension_flag.split('_')
2682 return "_".join(
2683 [part.upper() if part in uppercase_words else part for part in parts])
2685 def ToCamelCase(input_string):
2686 """converts ABC_underscore_case to ABCUnderscoreCase."""
2687 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
2689 def GetGLGetTypeConversion(result_type, value_type, value):
2690 """Makes a gl compatible type conversion string for accessing state variables.
2692 Useful when accessing state variables through glGetXXX calls.
2693 glGet documetation (for example, the manual pages):
2694 [...] If glGetIntegerv is called, [...] most floating-point values are
2695 rounded to the nearest integer value. [...]
2697 Args:
2698 result_type: the gl type to be obtained
2699 value_type: the GL type of the state variable
2700 value: the name of the state variable
2702 Returns:
2703 String that converts the state variable to desired GL type according to GL
2704 rules.
2707 if result_type == 'GLint':
2708 if value_type == 'GLfloat':
2709 return 'static_cast<GLint>(round(%s))' % value
2710 return 'static_cast<%s>(%s)' % (result_type, value)
2712 class CWriter(object):
2713 """Writes to a file formatting it for Google's style guidelines."""
2715 def __init__(self, filename):
2716 self.filename = filename
2717 self.content = []
2719 def Write(self, string):
2720 """Writes a string to a file spliting if it's > 80 characters."""
2721 lines = string.splitlines()
2722 num_lines = len(lines)
2723 for ii in range(0, num_lines):
2724 self.content.append(lines[ii])
2725 if ii < (num_lines - 1) or string[-1] == '\n':
2726 self.content.append('\n')
2728 def Close(self):
2729 """Close the file."""
2730 content = "".join(self.content)
2731 write_file = True
2732 if os.path.exists(self.filename):
2733 old_file = open(self.filename, "rb");
2734 old_content = old_file.read()
2735 old_file.close();
2736 if content == old_content:
2737 write_file = False
2738 if write_file:
2739 file = open(self.filename, "wb")
2740 file.write(content)
2741 file.close()
2744 class CHeaderWriter(CWriter):
2745 """Writes a C Header file."""
2747 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2749 def __init__(self, filename, file_comment = None):
2750 CWriter.__init__(self, filename)
2752 base = os.path.abspath(filename)
2753 while os.path.basename(base) != 'src':
2754 new_base = os.path.dirname(base)
2755 assert new_base != base # Prevent infinite loop.
2756 base = new_base
2758 hpath = os.path.relpath(filename, base)
2759 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2761 self.Write(_LICENSE)
2762 self.Write(_DO_NOT_EDIT_WARNING)
2763 if not file_comment == None:
2764 self.Write(file_comment)
2765 self.Write("#ifndef %s\n" % self.guard)
2766 self.Write("#define %s\n\n" % self.guard)
2768 def Close(self):
2769 self.Write("#endif // %s\n\n" % self.guard)
2770 CWriter.Close(self)
2772 class TypeHandler(object):
2773 """This class emits code for a particular type of function."""
2775 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2777 def __init__(self):
2778 pass
2780 def InitFunction(self, func):
2781 """Add or adjust anything type specific for this function."""
2782 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2783 func.AddCmdArg(DataSizeArgument('data_size'))
2785 def NeedsDataTransferFunction(self, func):
2786 """Overriden from TypeHandler."""
2787 return func.num_pointer_args >= 1
2789 def WriteStruct(self, func, file):
2790 """Writes a structure that matches the arguments to a function."""
2791 comment = func.GetInfo('cmd_comment')
2792 if not comment == None:
2793 file.Write(comment)
2794 file.Write("struct %s {\n" % func.name)
2795 file.Write(" typedef %s ValueType;\n" % func.name)
2796 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2797 func.WriteCmdArgFlag(file)
2798 func.WriteCmdFlag(file)
2799 file.Write("\n")
2800 result = func.GetInfo('result')
2801 if not result == None:
2802 if len(result) == 1:
2803 file.Write(" typedef %s Result;\n\n" % result[0])
2804 else:
2805 file.Write(" struct Result {\n")
2806 for line in result:
2807 file.Write(" %s;\n" % line)
2808 file.Write(" };\n\n")
2810 func.WriteCmdComputeSize(file)
2811 func.WriteCmdSetHeader(file)
2812 func.WriteCmdInit(file)
2813 func.WriteCmdSet(file)
2815 file.Write(" gpu::CommandHeader header;\n")
2816 args = func.GetCmdArgs()
2817 for arg in args:
2818 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2820 consts = func.GetCmdConstants()
2821 for const in consts:
2822 file.Write(" static const %s %s = %s;\n" %
2823 (const.cmd_type, const.name, const.GetConstantValue()))
2825 file.Write("};\n")
2826 file.Write("\n")
2828 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2829 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2830 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2831 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2832 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2833 offset = _SIZE_OF_COMMAND_HEADER
2834 for arg in args:
2835 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2836 (func.name, arg.name, offset))
2837 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2838 (func.name, arg.name, offset))
2839 offset += _SIZE_OF_UINT32
2840 if not result == None and len(result) > 1:
2841 offset = 0;
2842 for line in result:
2843 parts = line.split()
2844 name = parts[-1]
2845 check = """
2846 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2847 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2849 file.Write((check.strip() + "\n") % {
2850 'cmd_name': func.name,
2851 'field_name': name,
2852 'offset': offset,
2854 offset += _SIZE_OF_UINT32
2855 file.Write("\n")
2857 def WriteHandlerImplementation(self, func, file):
2858 """Writes the handler implementation for this command."""
2859 file.Write(" %s(%s);\n" %
2860 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2862 def WriteCmdSizeTest(self, func, file):
2863 """Writes the size test for a command."""
2864 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2866 def WriteFormatTest(self, func, file):
2867 """Writes a format test for a command."""
2868 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2869 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2870 (func.name, func.name))
2871 file.Write(" void* next_cmd = cmd.Set(\n")
2872 file.Write(" &cmd")
2873 args = func.GetCmdArgs()
2874 for value, arg in enumerate(args):
2875 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2876 file.Write(");\n")
2877 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
2878 func.name)
2879 file.Write(" cmd.header.command);\n")
2880 func.type_handler.WriteCmdSizeTest(func, file)
2881 for value, arg in enumerate(args):
2882 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2883 (arg.type, value + 11, arg.name))
2884 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2885 file.Write(" next_cmd, sizeof(cmd));\n")
2886 file.Write("}\n")
2887 file.Write("\n")
2889 def WriteImmediateFormatTest(self, func, file):
2890 """Writes a format test for an immediate version of a command."""
2891 pass
2893 def WriteBucketFormatTest(self, func, file):
2894 """Writes a format test for a bucket version of a command."""
2895 pass
2897 def WriteGetDataSizeCode(self, func, file):
2898 """Writes the code to set data_size used in validation"""
2899 pass
2901 def WriteImmediateCmdSizeTest(self, func, file):
2902 """Writes a size test for an immediate version of a command."""
2903 file.Write(" // TODO(gman): Compute correct size.\n")
2904 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2906 def WriteImmediateHandlerImplementation (self, func, file):
2907 """Writes the handler impl for the immediate version of a command."""
2908 file.Write(" %s(%s);\n" %
2909 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2911 def WriteBucketHandlerImplementation (self, func, file):
2912 """Writes the handler impl for the bucket version of a command."""
2913 file.Write(" %s(%s);\n" %
2914 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2916 def WriteServiceHandlerFunctionHeader(self, func, file):
2917 """Writes function header for service implementation handlers."""
2918 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
2919 uint32_t immediate_data_size, const void* cmd_data) {
2920 const gles2::cmds::%(name)s& c =
2921 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
2922 (void)c;
2923 """ % {'name': func.name})
2925 def WriteServiceImplementation(self, func, file):
2926 """Writes the service implementation for a command."""
2927 self.WriteServiceHandlerFunctionHeader(func, file)
2928 self.WriteHandlerExtensionCheck(func, file)
2929 self.WriteHandlerDeferReadWrite(func, file);
2930 if len(func.GetOriginalArgs()) > 0:
2931 last_arg = func.GetLastOriginalArg()
2932 all_but_last_arg = func.GetOriginalArgs()[:-1]
2933 for arg in all_but_last_arg:
2934 arg.WriteGetCode(file)
2935 self.WriteGetDataSizeCode(func, file)
2936 last_arg.WriteGetCode(file)
2937 func.WriteHandlerValidation(file)
2938 func.WriteHandlerImplementation(file)
2939 file.Write(" return error::kNoError;\n")
2940 file.Write("}\n")
2941 file.Write("\n")
2943 def WriteImmediateServiceImplementation(self, func, file):
2944 """Writes the service implementation for an immediate version of command."""
2945 self.WriteServiceHandlerFunctionHeader(func, file)
2946 self.WriteHandlerExtensionCheck(func, file)
2947 self.WriteHandlerDeferReadWrite(func, file);
2948 last_arg = func.GetLastOriginalArg()
2949 all_but_last_arg = func.GetOriginalArgs()[:-1]
2950 for arg in all_but_last_arg:
2951 arg.WriteGetCode(file)
2952 self.WriteGetDataSizeCode(func, file)
2953 last_arg.WriteGetCode(file)
2954 func.WriteHandlerValidation(file)
2955 func.WriteHandlerImplementation(file)
2956 file.Write(" return error::kNoError;\n")
2957 file.Write("}\n")
2958 file.Write("\n")
2960 def WriteBucketServiceImplementation(self, func, file):
2961 """Writes the service implementation for a bucket version of command."""
2962 self.WriteServiceHandlerFunctionHeader(func, file)
2963 self.WriteHandlerExtensionCheck(func, file)
2964 self.WriteHandlerDeferReadWrite(func, file);
2965 last_arg = func.GetLastOriginalArg()
2966 all_but_last_arg = func.GetOriginalArgs()[:-1]
2967 for arg in all_but_last_arg:
2968 arg.WriteGetCode(file)
2969 self.WriteGetDataSizeCode(func, file)
2970 last_arg.WriteGetCode(file)
2971 func.WriteHandlerValidation(file)
2972 func.WriteHandlerImplementation(file)
2973 file.Write(" return error::kNoError;\n")
2974 file.Write("}\n")
2975 file.Write("\n")
2977 def WriteHandlerExtensionCheck(self, func, file):
2978 if func.GetInfo('extension_flag'):
2979 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
2980 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
2981 " \"function not available\");\n" % func.original_name)
2982 file.Write(" return error::kNoError;")
2983 file.Write(" }\n\n")
2985 def WriteHandlerDeferReadWrite(self, func, file):
2986 """Writes the code to handle deferring reads or writes."""
2987 defer_draws = func.GetInfo('defer_draws')
2988 defer_reads = func.GetInfo('defer_reads')
2989 if defer_draws or defer_reads:
2990 file.Write(" error::Error error;\n")
2991 if defer_draws:
2992 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2993 file.Write(" if (error != error::kNoError)\n")
2994 file.Write(" return error;\n")
2995 if defer_reads:
2996 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2997 file.Write(" if (error != error::kNoError)\n")
2998 file.Write(" return error;\n")
3000 def WriteValidUnitTest(self, func, file, test, *extras):
3001 """Writes a valid unit test for the service implementation."""
3002 if func.GetInfo('expectation') == False:
3003 test = self._remove_expected_call_re.sub('', test)
3004 name = func.name
3005 arg_strings = [
3006 arg.GetValidArg(func) \
3007 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3009 gl_arg_strings = [
3010 arg.GetValidGLArg(func) \
3011 for arg in func.GetOriginalArgs()
3013 gl_func_name = func.GetGLTestFunctionName()
3014 vars = {
3015 'name':name,
3016 'gl_func_name': gl_func_name,
3017 'args': ", ".join(arg_strings),
3018 'gl_args': ", ".join(gl_arg_strings),
3020 for extra in extras:
3021 vars.update(extra)
3022 old_test = ""
3023 while (old_test != test):
3024 old_test = test
3025 test = test % vars
3026 file.Write(test % vars)
3028 def WriteInvalidUnitTest(self, func, file, test, *extras):
3029 """Writes an invalid unit test for the service implementation."""
3030 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
3031 # Service implementation does not test constants, as they are not part of
3032 # the call in the service side.
3033 if invalid_arg.IsConstant():
3034 continue
3036 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
3037 for value_index in range(0, num_invalid_values):
3038 arg_strings = []
3039 parse_result = "kNoError"
3040 gl_error = None
3041 for arg in func.GetOriginalArgs():
3042 if arg.IsConstant():
3043 continue
3044 if invalid_arg is arg:
3045 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
3046 value_index)
3047 else:
3048 arg_string = arg.GetValidArg(func)
3049 arg_strings.append(arg_string)
3050 gl_arg_strings = []
3051 for arg in func.GetOriginalArgs():
3052 gl_arg_strings.append("_")
3053 gl_func_name = func.GetGLTestFunctionName()
3054 gl_error_test = ''
3055 if not gl_error == None:
3056 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3058 vars = {
3059 'name': func.name,
3060 'arg_index': invalid_arg_index,
3061 'value_index': value_index,
3062 'gl_func_name': gl_func_name,
3063 'args': ", ".join(arg_strings),
3064 'all_but_last_args': ", ".join(arg_strings[:-1]),
3065 'gl_args': ", ".join(gl_arg_strings),
3066 'parse_result': parse_result,
3067 'gl_error_test': gl_error_test,
3069 for extra in extras:
3070 vars.update(extra)
3071 file.Write(test % vars)
3073 def WriteServiceUnitTest(self, func, file, *extras):
3074 """Writes the service unit test for a command."""
3076 if func.name == 'Enable':
3077 valid_test = """
3078 TEST_P(%(test_name)s, %(name)sValidArgs) {
3079 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3080 SpecializedSetup<cmds::%(name)s, 0>(true);
3081 cmds::%(name)s cmd;
3082 cmd.Init(%(args)s);
3083 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3084 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3087 elif func.name == 'Disable':
3088 valid_test = """
3089 TEST_P(%(test_name)s, %(name)sValidArgs) {
3090 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3091 SpecializedSetup<cmds::%(name)s, 0>(true);
3092 cmds::%(name)s cmd;
3093 cmd.Init(%(args)s);
3094 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3095 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3098 else:
3099 valid_test = """
3100 TEST_P(%(test_name)s, %(name)sValidArgs) {
3101 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3102 SpecializedSetup<cmds::%(name)s, 0>(true);
3103 cmds::%(name)s cmd;
3104 cmd.Init(%(args)s);
3105 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3106 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3109 self.WriteValidUnitTest(func, file, valid_test, *extras)
3111 invalid_test = """
3112 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3113 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3114 SpecializedSetup<cmds::%(name)s, 0>(false);
3115 cmds::%(name)s cmd;
3116 cmd.Init(%(args)s);
3117 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3120 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
3122 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3123 """Writes the service unit test for an immediate command."""
3124 file.Write("// TODO(gman): %s\n" % func.name)
3126 def WriteImmediateValidationCode(self, func, file):
3127 """Writes the validation code for an immediate version of a command."""
3128 pass
3130 def WriteBucketServiceUnitTest(self, func, file, *extras):
3131 """Writes the service unit test for a bucket command."""
3132 file.Write("// TODO(gman): %s\n" % func.name)
3134 def WriteBucketValidationCode(self, func, file):
3135 """Writes the validation code for a bucket version of a command."""
3136 file.Write("// TODO(gman): %s\n" % func.name)
3138 def WriteGLES2ImplementationDeclaration(self, func, file):
3139 """Writes the GLES2 Implemention declaration."""
3140 impl_decl = func.GetInfo('impl_decl')
3141 if impl_decl == None or impl_decl == True:
3142 file.Write("virtual %s %s(%s) override;\n" %
3143 (func.return_type, func.original_name,
3144 func.MakeTypedOriginalArgString("")))
3145 file.Write("\n")
3147 def WriteGLES2CLibImplementation(self, func, file):
3148 file.Write("%s GLES2%s(%s) {\n" %
3149 (func.return_type, func.name,
3150 func.MakeTypedOriginalArgString("")))
3151 result_string = "return "
3152 if func.return_type == "void":
3153 result_string = ""
3154 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3155 (result_string, func.original_name,
3156 func.MakeOriginalArgString("")))
3157 file.Write("}\n")
3159 def WriteGLES2Header(self, func, file):
3160 """Writes a re-write macro for GLES"""
3161 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3163 def WriteClientGLCallLog(self, func, file):
3164 """Writes a logging macro for the client side code."""
3165 comma = ""
3166 if len(func.GetOriginalArgs()):
3167 comma = " << "
3168 file.Write(
3169 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3170 (func.original_name, comma, func.MakeLogArgString()))
3172 def WriteClientGLReturnLog(self, func, file):
3173 """Writes the return value logging code."""
3174 if func.return_type != "void":
3175 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3177 def WriteGLES2ImplementationHeader(self, func, file):
3178 """Writes the GLES2 Implemention."""
3179 self.WriteGLES2ImplementationDeclaration(func, file)
3181 def WriteGLES2TraceImplementationHeader(self, func, file):
3182 """Writes the GLES2 Trace Implemention header."""
3183 file.Write("virtual %s %s(%s) override;\n" %
3184 (func.return_type, func.original_name,
3185 func.MakeTypedOriginalArgString("")))
3187 def WriteGLES2TraceImplementation(self, func, file):
3188 """Writes the GLES2 Trace Implemention."""
3189 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3190 (func.return_type, func.original_name,
3191 func.MakeTypedOriginalArgString("")))
3192 result_string = "return "
3193 if func.return_type == "void":
3194 result_string = ""
3195 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3196 func.name)
3197 file.Write(" %sgl_->%s(%s);\n" %
3198 (result_string, func.name, func.MakeOriginalArgString("")))
3199 file.Write("}\n")
3200 file.Write("\n")
3202 def WriteGLES2Implementation(self, func, file):
3203 """Writes the GLES2 Implemention."""
3204 impl_func = func.GetInfo('impl_func')
3205 impl_decl = func.GetInfo('impl_decl')
3206 gen_cmd = func.GetInfo('gen_cmd')
3207 if (func.can_auto_generate and
3208 (impl_func == None or impl_func == True) and
3209 (impl_decl == None or impl_decl == True) and
3210 (gen_cmd == None or gen_cmd == True)):
3211 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3212 (func.return_type, func.original_name,
3213 func.MakeTypedOriginalArgString("")))
3214 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3215 self.WriteClientGLCallLog(func, file)
3216 func.WriteDestinationInitalizationValidation(file)
3217 for arg in func.GetOriginalArgs():
3218 arg.WriteClientSideValidationCode(file, func)
3219 file.Write(" helper_->%s(%s);\n" %
3220 (func.name, func.MakeHelperArgString("")))
3221 file.Write(" CheckGLError();\n")
3222 self.WriteClientGLReturnLog(func, file)
3223 file.Write("}\n")
3224 file.Write("\n")
3226 def WriteGLES2InterfaceHeader(self, func, file):
3227 """Writes the GLES2 Interface."""
3228 file.Write("virtual %s %s(%s) = 0;\n" %
3229 (func.return_type, func.original_name,
3230 func.MakeTypedOriginalArgString("")))
3232 def WriteGLES2InterfaceStub(self, func, file):
3233 """Writes the GLES2 Interface stub declaration."""
3234 file.Write("virtual %s %s(%s) override;\n" %
3235 (func.return_type, func.original_name,
3236 func.MakeTypedOriginalArgString("")))
3238 def WriteGLES2InterfaceStubImpl(self, func, file):
3239 """Writes the GLES2 Interface stub declaration."""
3240 args = func.GetOriginalArgs()
3241 arg_string = ", ".join(
3242 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3243 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3244 (func.return_type, func.original_name, arg_string))
3245 if func.return_type != "void":
3246 file.Write(" return 0;\n")
3247 file.Write("}\n")
3249 def WriteGLES2ImplementationUnitTest(self, func, file):
3250 """Writes the GLES2 Implemention unit test."""
3251 client_test = func.GetInfo('client_test')
3252 if (func.can_auto_generate and
3253 (client_test == None or client_test == True)):
3254 code = """
3255 TEST_F(GLES2ImplementationTest, %(name)s) {
3256 struct Cmds {
3257 cmds::%(name)s cmd;
3259 Cmds expected;
3260 expected.cmd.Init(%(cmd_args)s);
3262 gl_->%(name)s(%(args)s);
3263 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3266 cmd_arg_strings = [
3267 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
3270 gl_arg_strings = [
3271 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
3274 file.Write(code % {
3275 'name': func.name,
3276 'args': ", ".join(gl_arg_strings),
3277 'cmd_args': ", ".join(cmd_arg_strings),
3280 # Test constants for invalid values, as they are not tested by the
3281 # service.
3282 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
3283 if constants:
3284 code = """
3285 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3286 gl_->%(name)s(%(args)s);
3287 EXPECT_TRUE(NoCommandsWritten());
3288 EXPECT_EQ(%(gl_error)s, CheckError());
3291 for invalid_arg in constants:
3292 gl_arg_strings = []
3293 invalid = invalid_arg.GetInvalidArg(func)
3294 for arg in func.GetOriginalArgs():
3295 if arg is invalid_arg:
3296 gl_arg_strings.append(invalid[0])
3297 else:
3298 gl_arg_strings.append(arg.GetValidClientSideArg(func))
3300 file.Write(code % {
3301 'name': func.name,
3302 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
3303 'args': ", ".join(gl_arg_strings),
3304 'gl_error': invalid[2],
3306 else:
3307 if client_test != False:
3308 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3310 def WriteDestinationInitalizationValidation(self, func, file):
3311 """Writes the client side destintion initialization validation."""
3312 for arg in func.GetOriginalArgs():
3313 arg.WriteDestinationInitalizationValidation(file, func)
3315 def WriteTraceEvent(self, func, file):
3316 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3317 func.original_name)
3319 def WriteImmediateCmdComputeSize(self, func, file):
3320 """Writes the size computation code for the immediate version of a cmd."""
3321 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3322 file.Write(" return static_cast<uint32_t>(\n")
3323 file.Write(" sizeof(ValueType) + // NOLINT\n")
3324 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3325 file.Write(" }\n")
3326 file.Write("\n")
3328 def WriteImmediateCmdSetHeader(self, func, file):
3329 """Writes the SetHeader function for the immediate version of a cmd."""
3330 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3331 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3332 file.Write(" }\n")
3333 file.Write("\n")
3335 def WriteImmediateCmdInit(self, func, file):
3336 """Writes the Init function for the immediate version of a command."""
3337 raise NotImplementedError(func.name)
3339 def WriteImmediateCmdSet(self, func, file):
3340 """Writes the Set function for the immediate version of a command."""
3341 raise NotImplementedError(func.name)
3343 def WriteCmdHelper(self, func, file):
3344 """Writes the cmd helper definition for a cmd."""
3345 code = """ void %(name)s(%(typed_args)s) {
3346 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3347 if (c) {
3348 c->Init(%(args)s);
3353 file.Write(code % {
3354 "name": func.name,
3355 "typed_args": func.MakeTypedCmdArgString(""),
3356 "args": func.MakeCmdArgString(""),
3359 def WriteImmediateCmdHelper(self, func, file):
3360 """Writes the cmd helper definition for the immediate version of a cmd."""
3361 code = """ void %(name)s(%(typed_args)s) {
3362 const uint32_t s = 0; // TODO(gman): compute correct size
3363 gles2::cmds::%(name)s* c =
3364 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3365 if (c) {
3366 c->Init(%(args)s);
3371 file.Write(code % {
3372 "name": func.name,
3373 "typed_args": func.MakeTypedCmdArgString(""),
3374 "args": func.MakeCmdArgString(""),
3378 class StateSetHandler(TypeHandler):
3379 """Handler for commands that simply set state."""
3381 def __init__(self):
3382 TypeHandler.__init__(self)
3384 def WriteHandlerImplementation(self, func, file):
3385 """Overrriden from TypeHandler."""
3386 state_name = func.GetInfo('state')
3387 state = _STATES[state_name]
3388 states = state['states']
3389 args = func.GetOriginalArgs()
3390 for ndx,item in enumerate(states):
3391 code = []
3392 if 'range_checks' in item:
3393 for range_check in item['range_checks']:
3394 code.append("%s %s" % (args[ndx].name, range_check['check']))
3395 if 'nan_check' in item:
3396 # Drivers might generate an INVALID_VALUE error when a value is set
3397 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3398 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3399 # Make this behavior consistent within Chromium, and avoid leaking GL
3400 # errors by generating the error in the command buffer instead of
3401 # letting the GL driver generate it.
3402 code.append("base::IsNaN(%s)" % args[ndx].name)
3403 if len(code):
3404 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3405 file.Write(
3406 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3407 ' "%s", "%s out of range");\n' %
3408 (func.name, args[ndx].name))
3409 file.Write(" return error::kNoError;\n")
3410 file.Write(" }\n")
3411 code = []
3412 for ndx,item in enumerate(states):
3413 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3414 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3415 for ndx,item in enumerate(states):
3416 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3417 if 'state_flag' in state:
3418 file.Write(" %s = true;\n" % state['state_flag'])
3419 if not func.GetInfo("no_gl"):
3420 for ndx,item in enumerate(states):
3421 if item.get('cached', False):
3422 file.Write(" state_.%s = %s;\n" %
3423 (CachedStateName(item), args[ndx].name))
3424 file.Write(" %s(%s);\n" %
3425 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3426 file.Write(" }\n")
3428 def WriteServiceUnitTest(self, func, file, *extras):
3429 """Overrriden from TypeHandler."""
3430 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
3431 state_name = func.GetInfo('state')
3432 state = _STATES[state_name]
3433 states = state['states']
3434 for ndx,item in enumerate(states):
3435 if 'range_checks' in item:
3436 for check_ndx, range_check in enumerate(item['range_checks']):
3437 valid_test = """
3438 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3439 SpecializedSetup<cmds::%(name)s, 0>(false);
3440 cmds::%(name)s cmd;
3441 cmd.Init(%(args)s);
3442 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3443 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3446 name = func.name
3447 arg_strings = [
3448 arg.GetValidArg(func) \
3449 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3452 arg_strings[ndx] = range_check['test_value']
3453 vars = {
3454 'name': name,
3455 'ndx': ndx,
3456 'check_ndx': check_ndx,
3457 'args': ", ".join(arg_strings),
3459 for extra in extras:
3460 vars.update(extra)
3461 file.Write(valid_test % vars)
3462 if 'nan_check' in item:
3463 valid_test = """
3464 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
3465 SpecializedSetup<cmds::%(name)s, 0>(false);
3466 cmds::%(name)s cmd;
3467 cmd.Init(%(args)s);
3468 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3469 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3472 name = func.name
3473 arg_strings = [
3474 arg.GetValidArg(func) \
3475 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3478 arg_strings[ndx] = 'nanf("")'
3479 vars = {
3480 'name': name,
3481 'ndx': ndx,
3482 'args': ", ".join(arg_strings),
3484 for extra in extras:
3485 vars.update(extra)
3486 file.Write(valid_test % vars)
3489 class StateSetRGBAlphaHandler(TypeHandler):
3490 """Handler for commands that simply set state that have rgb/alpha."""
3492 def __init__(self):
3493 TypeHandler.__init__(self)
3495 def WriteHandlerImplementation(self, func, file):
3496 """Overrriden from TypeHandler."""
3497 state_name = func.GetInfo('state')
3498 state = _STATES[state_name]
3499 states = state['states']
3500 args = func.GetOriginalArgs()
3501 num_args = len(args)
3502 code = []
3503 for ndx,item in enumerate(states):
3504 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3505 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3506 for ndx, item in enumerate(states):
3507 file.Write(" state_.%s = %s;\n" %
3508 (item['name'], args[ndx % num_args].name))
3509 if 'state_flag' in state:
3510 file.Write(" %s = true;\n" % state['state_flag'])
3511 if not func.GetInfo("no_gl"):
3512 file.Write(" %s(%s);\n" %
3513 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3514 file.Write(" }\n")
3517 class StateSetFrontBackSeparateHandler(TypeHandler):
3518 """Handler for commands that simply set state that have front/back."""
3520 def __init__(self):
3521 TypeHandler.__init__(self)
3523 def WriteHandlerImplementation(self, func, file):
3524 """Overrriden from TypeHandler."""
3525 state_name = func.GetInfo('state')
3526 state = _STATES[state_name]
3527 states = state['states']
3528 args = func.GetOriginalArgs()
3529 face = args[0].name
3530 num_args = len(args)
3531 file.Write(" bool changed = false;\n")
3532 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3533 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3534 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3535 code = []
3536 for ndx, item in enumerate(group):
3537 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3538 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3539 file.Write(" }\n")
3540 file.Write(" if (changed) {\n")
3541 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3542 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3543 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3544 for ndx, item in enumerate(group):
3545 file.Write(" state_.%s = %s;\n" %
3546 (item['name'], args[ndx + 1].name))
3547 file.Write(" }\n")
3548 if 'state_flag' in state:
3549 file.Write(" %s = true;\n" % state['state_flag'])
3550 if not func.GetInfo("no_gl"):
3551 file.Write(" %s(%s);\n" %
3552 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3553 file.Write(" }\n")
3556 class StateSetFrontBackHandler(TypeHandler):
3557 """Handler for commands that simply set state that set both front/back."""
3559 def __init__(self):
3560 TypeHandler.__init__(self)
3562 def WriteHandlerImplementation(self, func, file):
3563 """Overrriden from TypeHandler."""
3564 state_name = func.GetInfo('state')
3565 state = _STATES[state_name]
3566 states = state['states']
3567 args = func.GetOriginalArgs()
3568 num_args = len(args)
3569 code = []
3570 for group_ndx, group in enumerate(Grouper(num_args, states)):
3571 for ndx, item in enumerate(group):
3572 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3573 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3574 for group_ndx, group in enumerate(Grouper(num_args, states)):
3575 for ndx, item in enumerate(group):
3576 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3577 if 'state_flag' in state:
3578 file.Write(" %s = true;\n" % state['state_flag'])
3579 if not func.GetInfo("no_gl"):
3580 file.Write(" %s(%s);\n" %
3581 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3582 file.Write(" }\n")
3585 class StateSetNamedParameter(TypeHandler):
3586 """Handler for commands that set a state chosen with an enum parameter."""
3588 def __init__(self):
3589 TypeHandler.__init__(self)
3591 def WriteHandlerImplementation(self, func, file):
3592 """Overridden from TypeHandler."""
3593 state_name = func.GetInfo('state')
3594 state = _STATES[state_name]
3595 states = state['states']
3596 args = func.GetOriginalArgs()
3597 num_args = len(args)
3598 assert num_args == 2
3599 file.Write(" switch (%s) {\n" % args[0].name)
3600 for state in states:
3601 file.Write(" case %s:\n" % state['enum'])
3602 file.Write(" if (state_.%s != %s) {\n" %
3603 (state['name'], args[1].name))
3604 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3605 if not func.GetInfo("no_gl"):
3606 file.Write(" %s(%s);\n" %
3607 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3608 file.Write(" }\n")
3609 file.Write(" break;\n")
3610 file.Write(" default:\n")
3611 file.Write(" NOTREACHED();\n")
3612 file.Write(" }\n")
3615 class CustomHandler(TypeHandler):
3616 """Handler for commands that are auto-generated but require minor tweaks."""
3618 def __init__(self):
3619 TypeHandler.__init__(self)
3621 def WriteServiceImplementation(self, func, file):
3622 """Overrriden from TypeHandler."""
3623 pass
3625 def WriteImmediateServiceImplementation(self, func, file):
3626 """Overrriden from TypeHandler."""
3627 pass
3629 def WriteBucketServiceImplementation(self, func, file):
3630 """Overrriden from TypeHandler."""
3631 pass
3633 def WriteServiceUnitTest(self, func, file, *extras):
3634 """Overrriden from TypeHandler."""
3635 file.Write("// TODO(gman): %s\n\n" % func.name)
3637 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3638 """Overrriden from TypeHandler."""
3639 file.Write("// TODO(gman): %s\n\n" % func.name)
3641 def WriteImmediateCmdGetTotalSize(self, func, file):
3642 """Overrriden from TypeHandler."""
3643 file.Write(
3644 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
3646 def WriteImmediateCmdInit(self, func, file):
3647 """Overrriden from TypeHandler."""
3648 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3649 self.WriteImmediateCmdGetTotalSize(func, file)
3650 file.Write(" SetHeader(total_size);\n")
3651 args = func.GetCmdArgs()
3652 for arg in args:
3653 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3654 file.Write(" }\n")
3655 file.Write("\n")
3657 def WriteImmediateCmdSet(self, func, file):
3658 """Overrriden from TypeHandler."""
3659 copy_args = func.MakeCmdArgString("_", False)
3660 file.Write(" void* Set(void* cmd%s) {\n" %
3661 func.MakeTypedCmdArgString("_", True))
3662 self.WriteImmediateCmdGetTotalSize(func, file)
3663 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3664 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3665 "cmd, total_size);\n")
3666 file.Write(" }\n")
3667 file.Write("\n")
3670 class TodoHandler(CustomHandler):
3671 """Handle for commands that are not yet implemented."""
3673 def NeedsDataTransferFunction(self, func):
3674 """Overriden from TypeHandler."""
3675 return False
3677 def WriteImmediateFormatTest(self, func, file):
3678 """Overrriden from TypeHandler."""
3679 pass
3681 def WriteGLES2ImplementationUnitTest(self, func, file):
3682 """Overrriden from TypeHandler."""
3683 pass
3685 def WriteGLES2Implementation(self, func, file):
3686 """Overrriden from TypeHandler."""
3687 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3688 (func.return_type, func.original_name,
3689 func.MakeTypedOriginalArgString("")))
3690 file.Write(" // TODO: for now this is a no-op\n")
3691 file.Write(
3692 " SetGLError("
3693 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3694 func.name)
3695 if func.return_type != "void":
3696 file.Write(" return 0;\n")
3697 file.Write("}\n")
3698 file.Write("\n")
3700 def WriteServiceImplementation(self, func, file):
3701 """Overrriden from TypeHandler."""
3702 self.WriteServiceHandlerFunctionHeader(func, file)
3703 file.Write(" // TODO: for now this is a no-op\n")
3704 file.Write(
3705 " LOCAL_SET_GL_ERROR("
3706 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3707 func.name)
3708 file.Write(" return error::kNoError;\n")
3709 file.Write("}\n")
3710 file.Write("\n")
3713 class HandWrittenHandler(CustomHandler):
3714 """Handler for comands where everything must be written by hand."""
3716 def InitFunction(self, func):
3717 """Add or adjust anything type specific for this function."""
3718 CustomHandler.InitFunction(self, func)
3719 func.can_auto_generate = False
3721 def NeedsDataTransferFunction(self, func):
3722 """Overriden from TypeHandler."""
3723 # If specified explicitly, force the data transfer method.
3724 if func.GetInfo('data_transfer_methods'):
3725 return True
3726 return False
3728 def WriteStruct(self, func, file):
3729 """Overrriden from TypeHandler."""
3730 pass
3732 def WriteDocs(self, func, file):
3733 """Overrriden from TypeHandler."""
3734 pass
3736 def WriteServiceUnitTest(self, func, file, *extras):
3737 """Overrriden from TypeHandler."""
3738 file.Write("// TODO(gman): %s\n\n" % func.name)
3740 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3741 """Overrriden from TypeHandler."""
3742 file.Write("// TODO(gman): %s\n\n" % func.name)
3744 def WriteBucketServiceUnitTest(self, func, file, *extras):
3745 """Overrriden from TypeHandler."""
3746 file.Write("// TODO(gman): %s\n\n" % func.name)
3748 def WriteServiceImplementation(self, func, file):
3749 """Overrriden from TypeHandler."""
3750 pass
3752 def WriteImmediateServiceImplementation(self, func, file):
3753 """Overrriden from TypeHandler."""
3754 pass
3756 def WriteBucketServiceImplementation(self, func, file):
3757 """Overrriden from TypeHandler."""
3758 pass
3760 def WriteImmediateCmdHelper(self, func, file):
3761 """Overrriden from TypeHandler."""
3762 pass
3764 def WriteBucketCmdHelper(self, func, file):
3765 """Overrriden from TypeHandler."""
3766 pass
3768 def WriteCmdHelper(self, func, file):
3769 """Overrriden from TypeHandler."""
3770 pass
3772 def WriteFormatTest(self, func, file):
3773 """Overrriden from TypeHandler."""
3774 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3776 def WriteImmediateFormatTest(self, func, file):
3777 """Overrriden from TypeHandler."""
3778 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3780 def WriteBucketFormatTest(self, func, file):
3781 """Overrriden from TypeHandler."""
3782 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3786 class ManualHandler(CustomHandler):
3787 """Handler for commands who's handlers must be written by hand."""
3789 def __init__(self):
3790 CustomHandler.__init__(self)
3792 def InitFunction(self, func):
3793 """Overrriden from TypeHandler."""
3794 if (func.name == 'CompressedTexImage2DBucket'):
3795 func.cmd_args = func.cmd_args[:-1]
3796 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3797 else:
3798 CustomHandler.InitFunction(self, func)
3800 def WriteServiceImplementation(self, func, file):
3801 """Overrriden from TypeHandler."""
3802 pass
3804 def WriteBucketServiceImplementation(self, func, file):
3805 """Overrriden from TypeHandler."""
3806 pass
3808 def WriteServiceUnitTest(self, func, file, *extras):
3809 """Overrriden from TypeHandler."""
3810 file.Write("// TODO(gman): %s\n\n" % func.name)
3812 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3813 """Overrriden from TypeHandler."""
3814 file.Write("// TODO(gman): %s\n\n" % func.name)
3816 def WriteImmediateServiceImplementation(self, func, file):
3817 """Overrriden from TypeHandler."""
3818 pass
3820 def WriteImmediateFormatTest(self, func, file):
3821 """Overrriden from TypeHandler."""
3822 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3824 def WriteGLES2Implementation(self, func, file):
3825 """Overrriden from TypeHandler."""
3826 if func.GetInfo('impl_func'):
3827 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3829 def WriteGLES2ImplementationHeader(self, func, file):
3830 """Overrriden from TypeHandler."""
3831 file.Write("virtual %s %s(%s) override;\n" %
3832 (func.return_type, func.original_name,
3833 func.MakeTypedOriginalArgString("")))
3834 file.Write("\n")
3836 def WriteImmediateCmdGetTotalSize(self, func, file):
3837 """Overrriden from TypeHandler."""
3838 # TODO(gman): Move this data to _FUNCTION_INFO?
3839 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3842 class DataHandler(TypeHandler):
3843 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3844 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3845 def __init__(self):
3846 TypeHandler.__init__(self)
3848 def InitFunction(self, func):
3849 """Overrriden from TypeHandler."""
3850 if func.name == 'CompressedTexSubImage2DBucket':
3851 func.cmd_args = func.cmd_args[:-1]
3852 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3854 def WriteGetDataSizeCode(self, func, file):
3855 """Overrriden from TypeHandler."""
3856 # TODO(gman): Move this data to _FUNCTION_INFO?
3857 name = func.name
3858 if name.endswith("Immediate"):
3859 name = name[0:-9]
3860 if name == 'BufferData' or name == 'BufferSubData':
3861 file.Write(" uint32_t data_size = size;\n")
3862 elif (name == 'CompressedTexImage2D' or
3863 name == 'CompressedTexSubImage2D'):
3864 file.Write(" uint32_t data_size = imageSize;\n")
3865 elif (name == 'CompressedTexSubImage2DBucket'):
3866 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3867 file.Write(" uint32_t data_size = bucket->size();\n")
3868 file.Write(" GLsizei imageSize = data_size;\n")
3869 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3870 code = """ uint32_t data_size;
3871 if (!GLES2Util::ComputeImageDataSize(
3872 width, height, format, type, unpack_alignment_, &data_size)) {
3873 return error::kOutOfBounds;
3876 file.Write(code)
3877 else:
3878 file.Write(
3879 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
3881 def WriteImmediateCmdGetTotalSize(self, func, file):
3882 """Overrriden from TypeHandler."""
3883 pass
3885 def WriteImmediateCmdSizeTest(self, func, file):
3886 """Overrriden from TypeHandler."""
3887 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3889 def WriteImmediateCmdInit(self, func, file):
3890 """Overrriden from TypeHandler."""
3891 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3892 self.WriteImmediateCmdGetTotalSize(func, file)
3893 file.Write(" SetHeader(total_size);\n")
3894 args = func.GetCmdArgs()
3895 for arg in args:
3896 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3897 file.Write(" }\n")
3898 file.Write("\n")
3900 def WriteImmediateCmdSet(self, func, file):
3901 """Overrriden from TypeHandler."""
3902 copy_args = func.MakeCmdArgString("_", False)
3903 file.Write(" void* Set(void* cmd%s) {\n" %
3904 func.MakeTypedCmdArgString("_", True))
3905 self.WriteImmediateCmdGetTotalSize(func, file)
3906 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3907 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3908 "cmd, total_size);\n")
3909 file.Write(" }\n")
3910 file.Write("\n")
3912 def WriteImmediateFormatTest(self, func, file):
3913 """Overrriden from TypeHandler."""
3914 # TODO(gman): Remove this exception.
3915 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3916 return
3918 def WriteServiceUnitTest(self, func, file, *extras):
3919 """Overrriden from TypeHandler."""
3920 file.Write("// TODO(gman): %s\n\n" % func.name)
3922 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3923 """Overrriden from TypeHandler."""
3924 file.Write("// TODO(gman): %s\n\n" % func.name)
3926 def WriteBucketServiceImplementation(self, func, file):
3927 """Overrriden from TypeHandler."""
3928 if not func.name == 'CompressedTexSubImage2DBucket':
3929 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3932 class BindHandler(TypeHandler):
3933 """Handler for glBind___ type functions."""
3935 def __init__(self):
3936 TypeHandler.__init__(self)
3938 def WriteServiceUnitTest(self, func, file, *extras):
3939 """Overrriden from TypeHandler."""
3941 if len(func.GetOriginalArgs()) == 1:
3942 valid_test = """
3943 TEST_P(%(test_name)s, %(name)sValidArgs) {
3944 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3945 SpecializedSetup<cmds::%(name)s, 0>(true);
3946 cmds::%(name)s cmd;
3947 cmd.Init(%(args)s);
3948 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3949 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3952 if func.GetInfo("gen_func"):
3953 valid_test += """
3954 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3955 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3956 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3957 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3958 SpecializedSetup<cmds::%(name)s, 0>(true);
3959 cmds::%(name)s cmd;
3960 cmd.Init(kNewClientId);
3961 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3962 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3963 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3966 self.WriteValidUnitTest(func, file, valid_test, {
3967 'resource_type': func.GetOriginalArgs()[0].resource_type,
3968 'gl_gen_func_name': func.GetInfo("gen_func"),
3969 }, *extras)
3970 else:
3971 valid_test = """
3972 TEST_P(%(test_name)s, %(name)sValidArgs) {
3973 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3974 SpecializedSetup<cmds::%(name)s, 0>(true);
3975 cmds::%(name)s cmd;
3976 cmd.Init(%(args)s);
3977 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3978 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3981 if func.GetInfo("gen_func"):
3982 valid_test += """
3983 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3985 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3986 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3987 SpecializedSetup<cmds::%(name)s, 0>(true);
3988 cmds::%(name)s cmd;
3989 cmd.Init(%(first_arg)s, kNewClientId);
3990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3992 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3995 self.WriteValidUnitTest(func, file, valid_test, {
3996 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func),
3997 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func),
3998 'resource_type': func.GetOriginalArgs()[1].resource_type,
3999 'gl_gen_func_name': func.GetInfo("gen_func"),
4000 }, *extras)
4002 invalid_test = """
4003 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4004 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4005 SpecializedSetup<cmds::%(name)s, 0>(false);
4006 cmds::%(name)s cmd;
4007 cmd.Init(%(args)s);
4008 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4011 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4013 def WriteGLES2Implementation(self, func, file):
4014 """Writes the GLES2 Implemention."""
4016 impl_func = func.GetInfo('impl_func')
4017 impl_decl = func.GetInfo('impl_decl')
4019 if (func.can_auto_generate and
4020 (impl_func == None or impl_func == True) and
4021 (impl_decl == None or impl_decl == True)):
4023 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4024 (func.return_type, func.original_name,
4025 func.MakeTypedOriginalArgString("")))
4026 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4027 func.WriteDestinationInitalizationValidation(file)
4028 self.WriteClientGLCallLog(func, file)
4029 for arg in func.GetOriginalArgs():
4030 arg.WriteClientSideValidationCode(file, func)
4032 code = """ if (Is%(type)sReservedId(%(id)s)) {
4033 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4034 return;
4036 if (%(name)sHelper(%(arg_string)s)) {
4037 helper_->%(name)s(%(arg_string)s);
4039 CheckGLError();
4043 name_arg = None
4044 if len(func.GetOriginalArgs()) == 1:
4045 # Bind functions that have no target (like BindVertexArrayOES)
4046 name_arg = func.GetOriginalArgs()[0]
4047 else:
4048 # Bind functions that have both a target and a name (like BindTexture)
4049 name_arg = func.GetOriginalArgs()[1]
4051 file.Write(code % {
4052 'name': func.name,
4053 'arg_string': func.MakeOriginalArgString(""),
4054 'id': name_arg.name,
4055 'type': name_arg.resource_type,
4056 'lc_type': name_arg.resource_type.lower(),
4059 def WriteGLES2ImplementationUnitTest(self, func, file):
4060 """Overrriden from TypeHandler."""
4061 client_test = func.GetInfo('client_test')
4062 if client_test == False:
4063 return
4064 code = """
4065 TEST_F(GLES2ImplementationTest, %(name)s) {
4066 struct Cmds {
4067 cmds::%(name)s cmd;
4069 Cmds expected;
4070 expected.cmd.Init(%(cmd_args)s);
4072 gl_->%(name)s(%(args)s);
4073 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4074 ClearCommands();
4075 gl_->%(name)s(%(args)s);
4076 EXPECT_TRUE(NoCommandsWritten());
4079 cmd_arg_strings = [
4080 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4082 gl_arg_strings = [
4083 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4086 file.Write(code % {
4087 'name': func.name,
4088 'args': ", ".join(gl_arg_strings),
4089 'cmd_args': ", ".join(cmd_arg_strings),
4093 class GENnHandler(TypeHandler):
4094 """Handler for glGen___ type functions."""
4096 def __init__(self):
4097 TypeHandler.__init__(self)
4099 def InitFunction(self, func):
4100 """Overrriden from TypeHandler."""
4101 pass
4103 def WriteGetDataSizeCode(self, func, file):
4104 """Overrriden from TypeHandler."""
4105 code = """ uint32_t data_size;
4106 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4107 return error::kOutOfBounds;
4110 file.Write(code)
4112 def WriteHandlerImplementation (self, func, file):
4113 """Overrriden from TypeHandler."""
4114 file.Write(" if (!%sHelper(n, %s)) {\n"
4115 " return error::kInvalidArguments;\n"
4116 " }\n" %
4117 (func.name, func.GetLastOriginalArg().name))
4119 def WriteImmediateHandlerImplementation(self, func, file):
4120 """Overrriden from TypeHandler."""
4121 file.Write(" if (!%sHelper(n, %s)) {\n"
4122 " return error::kInvalidArguments;\n"
4123 " }\n" %
4124 (func.original_name, func.GetLastOriginalArg().name))
4126 def WriteGLES2Implementation(self, func, file):
4127 """Overrriden from TypeHandler."""
4128 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
4129 for (GLsizei i = 0; i < n; ++i) {
4130 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4132 });""" % func.GetOriginalArgs()[1].name)
4133 args = {
4134 'log_code': log_code,
4135 'return_type': func.return_type,
4136 'name': func.original_name,
4137 'typed_args': func.MakeTypedOriginalArgString(""),
4138 'args': func.MakeOriginalArgString(""),
4139 'resource_types': func.GetInfo('resource_types'),
4140 'count_name': func.GetOriginalArgs()[0].name,
4142 file.Write(
4143 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4144 args)
4145 func.WriteDestinationInitalizationValidation(file)
4146 self.WriteClientGLCallLog(func, file)
4147 for arg in func.GetOriginalArgs():
4148 arg.WriteClientSideValidationCode(file, func)
4149 not_shared = func.GetInfo('not_shared')
4150 if not_shared:
4151 alloc_code = (
4153 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4154 for (GLsizei ii = 0; ii < n; ++ii)
4155 %s[ii] = id_allocator->AllocateID();""" %
4156 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
4157 else:
4158 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4159 MakeIds(this, 0, %(args)s);""" % args)
4160 args['alloc_code'] = alloc_code
4162 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4163 %(alloc_code)s
4164 %(name)sHelper(%(args)s);
4165 helper_->%(name)sImmediate(%(args)s);
4166 if (share_group_->bind_generates_resource())
4167 helper_->CommandBufferHelper::Flush();
4168 %(log_code)s
4169 CheckGLError();
4173 file.Write(code % args)
4175 def WriteGLES2ImplementationUnitTest(self, func, file):
4176 """Overrriden from TypeHandler."""
4177 code = """
4178 TEST_F(GLES2ImplementationTest, %(name)s) {
4179 GLuint ids[2] = { 0, };
4180 struct Cmds {
4181 cmds::%(name)sImmediate gen;
4182 GLuint data[2];
4184 Cmds expected;
4185 expected.gen.Init(arraysize(ids), &ids[0]);
4186 expected.data[0] = k%(types)sStartId;
4187 expected.data[1] = k%(types)sStartId + 1;
4188 gl_->%(name)s(arraysize(ids), &ids[0]);
4189 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4190 EXPECT_EQ(k%(types)sStartId, ids[0]);
4191 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4194 file.Write(code % {
4195 'name': func.name,
4196 'types': func.GetInfo('resource_types'),
4199 def WriteServiceUnitTest(self, func, file, *extras):
4200 """Overrriden from TypeHandler."""
4201 valid_test = """
4202 TEST_P(%(test_name)s, %(name)sValidArgs) {
4203 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4204 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4205 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4206 SpecializedSetup<cmds::%(name)s, 0>(true);
4207 cmds::%(name)s cmd;
4208 cmd.Init(%(args)s);
4209 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4210 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4211 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4214 self.WriteValidUnitTest(func, file, valid_test, {
4215 'resource_name': func.GetInfo('resource_type'),
4216 }, *extras)
4217 invalid_test = """
4218 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4219 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4220 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4221 SpecializedSetup<cmds::%(name)s, 0>(false);
4222 cmds::%(name)s cmd;
4223 cmd.Init(%(args)s);
4224 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4227 self.WriteValidUnitTest(func, file, invalid_test, {
4228 'resource_name': func.GetInfo('resource_type').lower(),
4229 }, *extras)
4231 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4232 """Overrriden from TypeHandler."""
4233 valid_test = """
4234 TEST_P(%(test_name)s, %(name)sValidArgs) {
4235 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4236 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4237 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4238 GLuint temp = kNewClientId;
4239 SpecializedSetup<cmds::%(name)s, 0>(true);
4240 cmd->Init(1, &temp);
4241 EXPECT_EQ(error::kNoError,
4242 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4243 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4244 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4247 self.WriteValidUnitTest(func, file, valid_test, {
4248 'resource_name': func.GetInfo('resource_type'),
4249 }, *extras)
4250 invalid_test = """
4251 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4252 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4253 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4254 SpecializedSetup<cmds::%(name)s, 0>(false);
4255 cmd->Init(1, &client_%(resource_name)s_id_);
4256 EXPECT_EQ(error::kInvalidArguments,
4257 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4260 self.WriteValidUnitTest(func, file, invalid_test, {
4261 'resource_name': func.GetInfo('resource_type').lower(),
4262 }, *extras)
4264 def WriteImmediateCmdComputeSize(self, func, file):
4265 """Overrriden from TypeHandler."""
4266 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4267 file.Write(
4268 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4269 file.Write(" }\n")
4270 file.Write("\n")
4271 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4272 file.Write(" return static_cast<uint32_t>(\n")
4273 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4274 file.Write(" }\n")
4275 file.Write("\n")
4277 def WriteImmediateCmdSetHeader(self, func, file):
4278 """Overrriden from TypeHandler."""
4279 file.Write(" void SetHeader(GLsizei n) {\n")
4280 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4281 file.Write(" }\n")
4282 file.Write("\n")
4284 def WriteImmediateCmdInit(self, func, file):
4285 """Overrriden from TypeHandler."""
4286 last_arg = func.GetLastOriginalArg()
4287 file.Write(" void Init(%s, %s _%s) {\n" %
4288 (func.MakeTypedCmdArgString("_"),
4289 last_arg.type, last_arg.name))
4290 file.Write(" SetHeader(_n);\n")
4291 args = func.GetCmdArgs()
4292 for arg in args:
4293 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4294 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4295 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4296 file.Write(" }\n")
4297 file.Write("\n")
4299 def WriteImmediateCmdSet(self, func, file):
4300 """Overrriden from TypeHandler."""
4301 last_arg = func.GetLastOriginalArg()
4302 copy_args = func.MakeCmdArgString("_", False)
4303 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4304 (func.MakeTypedCmdArgString("_", True),
4305 last_arg.type, last_arg.name))
4306 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4307 (copy_args, last_arg.name))
4308 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4309 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4310 "cmd, size);\n")
4311 file.Write(" }\n")
4312 file.Write("\n")
4314 def WriteImmediateCmdHelper(self, func, file):
4315 """Overrriden from TypeHandler."""
4316 code = """ void %(name)s(%(typed_args)s) {
4317 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4318 gles2::cmds::%(name)s* c =
4319 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4320 if (c) {
4321 c->Init(%(args)s);
4326 file.Write(code % {
4327 "name": func.name,
4328 "typed_args": func.MakeTypedOriginalArgString(""),
4329 "args": func.MakeOriginalArgString(""),
4332 def WriteImmediateFormatTest(self, func, file):
4333 """Overrriden from TypeHandler."""
4334 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4335 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4336 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4337 (func.name, func.name))
4338 file.Write(" void* next_cmd = cmd.Set(\n")
4339 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4340 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4341 func.name)
4342 file.Write(" cmd.header.command);\n")
4343 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4344 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4345 file.Write(" cmd.header.size * 4u);\n")
4346 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4347 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4348 file.Write(" next_cmd, sizeof(cmd) +\n")
4349 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4350 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4351 file.Write("}\n")
4352 file.Write("\n")
4355 class CreateHandler(TypeHandler):
4356 """Handler for glCreate___ type functions."""
4358 def __init__(self):
4359 TypeHandler.__init__(self)
4361 def InitFunction(self, func):
4362 """Overrriden from TypeHandler."""
4363 func.AddCmdArg(Argument("client_id", 'uint32_t'))
4365 def WriteServiceUnitTest(self, func, file, *extras):
4366 """Overrriden from TypeHandler."""
4367 valid_test = """
4368 TEST_P(%(test_name)s, %(name)sValidArgs) {
4369 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4370 .WillOnce(Return(kNewServiceId));
4371 SpecializedSetup<cmds::%(name)s, 0>(true);
4372 cmds::%(name)s cmd;
4373 cmd.Init(%(args)s%(comma)skNewClientId);
4374 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4375 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4376 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4379 comma = ""
4380 if len(func.GetOriginalArgs()):
4381 comma =", "
4382 self.WriteValidUnitTest(func, file, valid_test, {
4383 'comma': comma,
4384 'resource_type': func.name[6:],
4385 }, *extras)
4386 invalid_test = """
4387 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4388 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4389 SpecializedSetup<cmds::%(name)s, 0>(false);
4390 cmds::%(name)s cmd;
4391 cmd.Init(%(args)s%(comma)skNewClientId);
4392 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4395 self.WriteInvalidUnitTest(func, file, invalid_test, {
4396 'comma': comma,
4397 }, *extras)
4399 def WriteHandlerImplementation (self, func, file):
4400 """Overrriden from TypeHandler."""
4401 file.Write(" uint32_t client_id = c.client_id;\n")
4402 file.Write(" if (!%sHelper(%s)) {\n" %
4403 (func.name, func.MakeCmdArgString("")))
4404 file.Write(" return error::kInvalidArguments;\n")
4405 file.Write(" }\n")
4407 def WriteGLES2Implementation(self, func, file):
4408 """Overrriden from TypeHandler."""
4409 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4410 (func.return_type, func.original_name,
4411 func.MakeTypedOriginalArgString("")))
4412 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4413 func.WriteDestinationInitalizationValidation(file)
4414 self.WriteClientGLCallLog(func, file)
4415 for arg in func.GetOriginalArgs():
4416 arg.WriteClientSideValidationCode(file, func)
4417 file.Write(" GLuint client_id;\n")
4418 file.Write(
4419 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4420 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4421 file.Write(" helper_->%s(%s);\n" %
4422 (func.name, func.MakeCmdArgString("")))
4423 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4424 file.Write(" CheckGLError();\n")
4425 file.Write(" return client_id;\n")
4426 file.Write("}\n")
4427 file.Write("\n")
4430 class DeleteHandler(TypeHandler):
4431 """Handler for glDelete___ single resource type functions."""
4433 def __init__(self):
4434 TypeHandler.__init__(self)
4436 def WriteServiceImplementation(self, func, file):
4437 """Overrriden from TypeHandler."""
4438 pass
4440 def WriteGLES2Implementation(self, func, file):
4441 """Overrriden from TypeHandler."""
4442 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4443 (func.return_type, func.original_name,
4444 func.MakeTypedOriginalArgString("")))
4445 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4446 func.WriteDestinationInitalizationValidation(file)
4447 self.WriteClientGLCallLog(func, file)
4448 for arg in func.GetOriginalArgs():
4449 arg.WriteClientSideValidationCode(file, func)
4450 file.Write(
4451 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4452 file.Write(" %sHelper(%s);\n" %
4453 (func.original_name, func.GetOriginalArgs()[-1].name))
4454 file.Write(" CheckGLError();\n")
4455 file.Write("}\n")
4456 file.Write("\n")
4459 class DELnHandler(TypeHandler):
4460 """Handler for glDelete___ type functions."""
4462 def __init__(self):
4463 TypeHandler.__init__(self)
4465 def WriteGetDataSizeCode(self, func, file):
4466 """Overrriden from TypeHandler."""
4467 code = """ uint32_t data_size;
4468 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4469 return error::kOutOfBounds;
4472 file.Write(code)
4474 def WriteGLES2ImplementationUnitTest(self, func, file):
4475 """Overrriden from TypeHandler."""
4476 code = """
4477 TEST_F(GLES2ImplementationTest, %(name)s) {
4478 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4479 struct Cmds {
4480 cmds::%(name)sImmediate del;
4481 GLuint data[2];
4483 Cmds expected;
4484 expected.del.Init(arraysize(ids), &ids[0]);
4485 expected.data[0] = k%(types)sStartId;
4486 expected.data[1] = k%(types)sStartId + 1;
4487 gl_->%(name)s(arraysize(ids), &ids[0]);
4488 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4491 file.Write(code % {
4492 'name': func.name,
4493 'types': func.GetInfo('resource_types'),
4496 def WriteServiceUnitTest(self, func, file, *extras):
4497 """Overrriden from TypeHandler."""
4498 valid_test = """
4499 TEST_P(%(test_name)s, %(name)sValidArgs) {
4500 EXPECT_CALL(
4501 *gl_,
4502 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4503 .Times(1);
4504 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4505 SpecializedSetup<cmds::%(name)s, 0>(true);
4506 cmds::%(name)s cmd;
4507 cmd.Init(%(args)s);
4508 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4509 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4510 EXPECT_TRUE(
4511 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4514 self.WriteValidUnitTest(func, file, valid_test, {
4515 'resource_name': func.GetInfo('resource_type').lower(),
4516 'upper_resource_name': func.GetInfo('resource_type'),
4517 }, *extras)
4518 invalid_test = """
4519 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4520 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4521 SpecializedSetup<cmds::%(name)s, 0>(false);
4522 cmds::%(name)s cmd;
4523 cmd.Init(%(args)s);
4524 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4527 self.WriteValidUnitTest(func, file, invalid_test, *extras)
4529 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4530 """Overrriden from TypeHandler."""
4531 valid_test = """
4532 TEST_P(%(test_name)s, %(name)sValidArgs) {
4533 EXPECT_CALL(
4534 *gl_,
4535 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4536 .Times(1);
4537 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4538 SpecializedSetup<cmds::%(name)s, 0>(true);
4539 cmd.Init(1, &client_%(resource_name)s_id_);
4540 EXPECT_EQ(error::kNoError,
4541 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4542 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4543 EXPECT_TRUE(
4544 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4547 self.WriteValidUnitTest(func, file, valid_test, {
4548 'resource_name': func.GetInfo('resource_type').lower(),
4549 'upper_resource_name': func.GetInfo('resource_type'),
4550 }, *extras)
4551 invalid_test = """
4552 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4553 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4554 SpecializedSetup<cmds::%(name)s, 0>(false);
4555 GLuint temp = kInvalidClientId;
4556 cmd.Init(1, &temp);
4557 EXPECT_EQ(error::kNoError,
4558 ExecuteImmediateCmd(cmd, sizeof(temp)));
4561 self.WriteValidUnitTest(func, file, invalid_test, *extras)
4563 def WriteHandlerImplementation (self, func, file):
4564 """Overrriden from TypeHandler."""
4565 file.Write(" %sHelper(n, %s);\n" %
4566 (func.name, func.GetLastOriginalArg().name))
4568 def WriteImmediateHandlerImplementation (self, func, file):
4569 """Overrriden from TypeHandler."""
4570 file.Write(" %sHelper(n, %s);\n" %
4571 (func.original_name, func.GetLastOriginalArg().name))
4573 def WriteGLES2Implementation(self, func, file):
4574 """Overrriden from TypeHandler."""
4575 impl_decl = func.GetInfo('impl_decl')
4576 if impl_decl == None or impl_decl == True:
4577 args = {
4578 'return_type': func.return_type,
4579 'name': func.original_name,
4580 'typed_args': func.MakeTypedOriginalArgString(""),
4581 'args': func.MakeOriginalArgString(""),
4582 'resource_type': func.GetInfo('resource_type').lower(),
4583 'count_name': func.GetOriginalArgs()[0].name,
4585 file.Write(
4586 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4587 args)
4588 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4589 func.WriteDestinationInitalizationValidation(file)
4590 self.WriteClientGLCallLog(func, file)
4591 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4592 for (GLsizei i = 0; i < n; ++i) {
4593 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4596 """ % func.GetOriginalArgs()[1].name)
4597 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4598 for (GLsizei i = 0; i < n; ++i) {
4599 DCHECK(%s[i] != 0);
4602 """ % func.GetOriginalArgs()[1].name)
4603 for arg in func.GetOriginalArgs():
4604 arg.WriteClientSideValidationCode(file, func)
4605 code = """ %(name)sHelper(%(args)s);
4606 CheckGLError();
4610 file.Write(code % args)
4612 def WriteImmediateCmdComputeSize(self, func, file):
4613 """Overrriden from TypeHandler."""
4614 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4615 file.Write(
4616 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4617 file.Write(" }\n")
4618 file.Write("\n")
4619 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4620 file.Write(" return static_cast<uint32_t>(\n")
4621 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4622 file.Write(" }\n")
4623 file.Write("\n")
4625 def WriteImmediateCmdSetHeader(self, func, file):
4626 """Overrriden from TypeHandler."""
4627 file.Write(" void SetHeader(GLsizei n) {\n")
4628 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4629 file.Write(" }\n")
4630 file.Write("\n")
4632 def WriteImmediateCmdInit(self, func, file):
4633 """Overrriden from TypeHandler."""
4634 last_arg = func.GetLastOriginalArg()
4635 file.Write(" void Init(%s, %s _%s) {\n" %
4636 (func.MakeTypedCmdArgString("_"),
4637 last_arg.type, last_arg.name))
4638 file.Write(" SetHeader(_n);\n")
4639 args = func.GetCmdArgs()
4640 for arg in args:
4641 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4642 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4643 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4644 file.Write(" }\n")
4645 file.Write("\n")
4647 def WriteImmediateCmdSet(self, func, file):
4648 """Overrriden from TypeHandler."""
4649 last_arg = func.GetLastOriginalArg()
4650 copy_args = func.MakeCmdArgString("_", False)
4651 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4652 (func.MakeTypedCmdArgString("_", True),
4653 last_arg.type, last_arg.name))
4654 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4655 (copy_args, last_arg.name))
4656 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4657 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4658 "cmd, size);\n")
4659 file.Write(" }\n")
4660 file.Write("\n")
4662 def WriteImmediateCmdHelper(self, func, file):
4663 """Overrriden from TypeHandler."""
4664 code = """ void %(name)s(%(typed_args)s) {
4665 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4666 gles2::cmds::%(name)s* c =
4667 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4668 if (c) {
4669 c->Init(%(args)s);
4674 file.Write(code % {
4675 "name": func.name,
4676 "typed_args": func.MakeTypedOriginalArgString(""),
4677 "args": func.MakeOriginalArgString(""),
4680 def WriteImmediateFormatTest(self, func, file):
4681 """Overrriden from TypeHandler."""
4682 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4683 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4684 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4685 (func.name, func.name))
4686 file.Write(" void* next_cmd = cmd.Set(\n")
4687 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4688 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4689 func.name)
4690 file.Write(" cmd.header.command);\n")
4691 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4692 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4693 file.Write(" cmd.header.size * 4u);\n")
4694 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4695 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4696 file.Write(" next_cmd, sizeof(cmd) +\n")
4697 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4698 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4699 file.Write("}\n")
4700 file.Write("\n")
4703 class GETnHandler(TypeHandler):
4704 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4706 def __init__(self):
4707 TypeHandler.__init__(self)
4709 def NeedsDataTransferFunction(self, func):
4710 """Overriden from TypeHandler."""
4711 return False
4713 def WriteServiceImplementation(self, func, file):
4714 """Overrriden from TypeHandler."""
4715 self.WriteServiceHandlerFunctionHeader(func, file)
4716 last_arg = func.GetLastOriginalArg()
4718 all_but_last_args = func.GetOriginalArgs()[:-1]
4719 for arg in all_but_last_args:
4720 arg.WriteGetCode(file)
4722 code = """ typedef cmds::%(func_name)s::Result Result;
4723 GLsizei num_values = 0;
4724 GetNumValuesReturnedForGLGet(pname, &num_values);
4725 Result* result = GetSharedMemoryAs<Result*>(
4726 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4727 %(last_arg_type)s params = result ? result->GetData() : NULL;
4729 file.Write(code % {
4730 'last_arg_type': last_arg.type,
4731 'func_name': func.name,
4733 func.WriteHandlerValidation(file)
4734 code = """ // Check that the client initialized the result.
4735 if (result->size != 0) {
4736 return error::kInvalidArguments;
4739 shadowed = func.GetInfo('shadowed')
4740 if not shadowed:
4741 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4742 file.Write(code)
4743 func.WriteHandlerImplementation(file)
4744 if shadowed:
4745 code = """ result->SetNumResults(num_values);
4746 return error::kNoError;
4749 else:
4750 code = """ GLenum error = glGetError();
4751 if (error == GL_NO_ERROR) {
4752 result->SetNumResults(num_values);
4753 } else {
4754 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4756 return error::kNoError;
4760 file.Write(code % {'func_name': func.name})
4762 def WriteGLES2Implementation(self, func, file):
4763 """Overrriden from TypeHandler."""
4764 impl_decl = func.GetInfo('impl_decl')
4765 if impl_decl == None or impl_decl == True:
4766 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4767 (func.return_type, func.original_name,
4768 func.MakeTypedOriginalArgString("")))
4769 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4770 func.WriteDestinationInitalizationValidation(file)
4771 self.WriteClientGLCallLog(func, file)
4772 for arg in func.GetOriginalArgs():
4773 arg.WriteClientSideValidationCode(file, func)
4774 all_but_last_args = func.GetOriginalArgs()[:-1]
4775 arg_string = (
4776 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4777 all_arg_string = (
4778 ", ".join([
4779 "%s" % arg.name
4780 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
4781 self.WriteTraceEvent(func, file)
4782 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4783 return;
4785 typedef cmds::%(func_name)s::Result Result;
4786 Result* result = GetResultAs<Result*>();
4787 if (!result) {
4788 return;
4790 result->SetNumResults(0);
4791 helper_->%(func_name)s(%(arg_string)s,
4792 GetResultShmId(), GetResultShmOffset());
4793 WaitForCmd();
4794 result->CopyResult(params);
4795 GPU_CLIENT_LOG_CODE_BLOCK({
4796 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
4797 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4800 CheckGLError();
4803 file.Write(code % {
4804 'func_name': func.name,
4805 'arg_string': arg_string,
4806 'all_arg_string': all_arg_string,
4809 def WriteGLES2ImplementationUnitTest(self, func, file):
4810 """Writes the GLES2 Implemention unit test."""
4811 code = """
4812 TEST_F(GLES2ImplementationTest, %(name)s) {
4813 struct Cmds {
4814 cmds::%(name)s cmd;
4816 typedef cmds::%(name)s::Result Result;
4817 Result::Type result = 0;
4818 Cmds expected;
4819 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4820 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4821 EXPECT_CALL(*command_buffer(), OnFlush())
4822 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4823 .RetiresOnSaturation();
4824 gl_->%(name)s(%(args)s, &result);
4825 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4826 EXPECT_EQ(static_cast<Result::Type>(1), result);
4829 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
4830 if not first_cmd_arg:
4831 return
4833 first_gl_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func)
4834 cmd_arg_strings = [first_cmd_arg]
4835 for arg in func.GetCmdArgs()[1:-2]:
4836 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
4837 gl_arg_strings = [first_gl_arg]
4838 for arg in func.GetOriginalArgs()[1:-1]:
4839 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4841 file.Write(code % {
4842 'name': func.name,
4843 'args': ", ".join(gl_arg_strings),
4844 'cmd_args': ", ".join(cmd_arg_strings),
4847 def WriteServiceUnitTest(self, func, file, *extras):
4848 """Overrriden from TypeHandler."""
4849 valid_test = """
4850 TEST_P(%(test_name)s, %(name)sValidArgs) {
4851 EXPECT_CALL(*gl_, GetError())
4852 .WillOnce(Return(GL_NO_ERROR))
4853 .WillOnce(Return(GL_NO_ERROR))
4854 .RetiresOnSaturation();
4855 SpecializedSetup<cmds::%(name)s, 0>(true);
4856 typedef cmds::%(name)s::Result Result;
4857 Result* result = static_cast<Result*>(shared_memory_address_);
4858 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4859 result->size = 0;
4860 cmds::%(name)s cmd;
4861 cmd.Init(%(args)s);
4862 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4863 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4864 %(valid_pname)s),
4865 result->GetNumResults());
4866 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4869 gl_arg_strings = []
4870 valid_pname = ''
4871 for arg in func.GetOriginalArgs()[:-1]:
4872 arg_value = arg.GetValidGLArg(func)
4873 gl_arg_strings.append(arg_value)
4874 if arg.name == 'pname':
4875 valid_pname = arg_value
4876 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4877 gl_arg_strings.append("_")
4878 else:
4879 gl_arg_strings.append("result->GetData()")
4881 self.WriteValidUnitTest(func, file, valid_test, {
4882 'local_gl_args': ", ".join(gl_arg_strings),
4883 'valid_pname': valid_pname,
4884 }, *extras)
4886 invalid_test = """
4887 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4888 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4889 SpecializedSetup<cmds::%(name)s, 0>(false);
4890 cmds::%(name)s::Result* result =
4891 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4892 result->size = 0;
4893 cmds::%(name)s cmd;
4894 cmd.Init(%(args)s);
4895 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4896 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4899 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4901 class ArrayArgTypeHandler(TypeHandler):
4902 """Base class for type handlers that handle args that are arrays"""
4904 def __init__(self):
4905 TypeHandler.__init__(self)
4907 def GetArrayType(self, func):
4908 """Returns the type of the element in the element array being PUT to."""
4909 for arg in func.GetOriginalArgs():
4910 if arg.IsPointer():
4911 element_type = arg.GetPointedType()
4912 return element_type
4914 # Special case: array type handler is used for a function that is forwarded
4915 # to the actual array type implementation
4916 element_type = func.GetOriginalArgs()[-1].type
4917 assert all(arg.type == element_type \
4918 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
4919 return element_type
4921 def GetArrayCount(self, func):
4922 """Returns the count of the elements in the array being PUT to."""
4923 return func.GetInfo('count')
4925 class PUTHandler(ArrayArgTypeHandler):
4926 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4928 def __init__(self):
4929 ArrayArgTypeHandler.__init__(self)
4931 def WriteServiceUnitTest(self, func, file, *extras):
4932 """Writes the service unit test for a command."""
4933 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4934 if func.GetInfo("first_element_only"):
4935 gl_arg_strings = [
4936 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
4938 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4939 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4940 ", ".join(gl_arg_strings))
4941 valid_test = """
4942 TEST_P(%(test_name)s, %(name)sValidArgs) {
4943 SpecializedSetup<cmds::%(name)s, 0>(true);
4944 cmds::%(name)s cmd;
4945 cmd.Init(%(args)s);
4946 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4947 %(expected_call)s
4948 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4949 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4952 extra = {
4953 'data_type': self.GetArrayType(func),
4954 'data_value': func.GetInfo('data_value') or '0',
4955 'expected_call': expected_call,
4957 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
4959 invalid_test = """
4960 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4962 SpecializedSetup<cmds::%(name)s, 0>(false);
4963 cmds::%(name)s cmd;
4964 cmd.Init(%(args)s);
4965 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4966 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4969 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
4971 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4972 """Writes the service unit test for a command."""
4973 valid_test = """
4974 TEST_P(%(test_name)s, %(name)sValidArgs) {
4975 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4976 SpecializedSetup<cmds::%(name)s, 0>(true);
4977 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4978 cmd.Init(%(gl_args)s, &temp[0]);
4979 EXPECT_CALL(
4980 *gl_,
4981 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4982 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4983 EXPECT_EQ(error::kNoError,
4984 ExecuteImmediateCmd(cmd, sizeof(temp)));
4985 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4988 gl_arg_strings = [
4989 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
4991 gl_any_strings = ["_"] * len(gl_arg_strings)
4993 extra = {
4994 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4995 'data_type': self.GetArrayType(func),
4996 'data_count': self.GetArrayCount(func),
4997 'data_value': func.GetInfo('data_value') or '0',
4998 'gl_args': ", ".join(gl_arg_strings),
4999 'gl_any_args': ", ".join(gl_any_strings),
5001 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5003 invalid_test = """
5004 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5005 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5006 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5007 SpecializedSetup<cmds::%(name)s, 0>(false);
5008 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5009 cmd.Init(%(all_but_last_args)s, &temp[0]);
5010 EXPECT_EQ(error::%(parse_result)s,
5011 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5014 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5016 def WriteGetDataSizeCode(self, func, file):
5017 """Overrriden from TypeHandler."""
5018 code = """ uint32_t data_size;
5019 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5020 return error::kOutOfBounds;
5023 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
5024 if func.IsImmediate():
5025 file.Write(" if (data_size > immediate_data_size) {\n")
5026 file.Write(" return error::kOutOfBounds;\n")
5027 file.Write(" }\n")
5029 def WriteGLES2Implementation(self, func, file):
5030 """Overrriden from TypeHandler."""
5031 impl_func = func.GetInfo('impl_func')
5032 if (impl_func != None and impl_func != True):
5033 return;
5034 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5035 (func.return_type, func.original_name,
5036 func.MakeTypedOriginalArgString("")))
5037 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5038 func.WriteDestinationInitalizationValidation(file)
5039 self.WriteClientGLCallLog(func, file)
5040 last_arg_name = func.GetLastOriginalArg().name
5041 values_str = ' << ", " << '.join(
5042 ["%s[%d]" % (last_arg_name, ndx) \
5043 for ndx in range(0, self.GetArrayCount(func))])
5044 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
5045 for arg in func.GetOriginalArgs():
5046 arg.WriteClientSideValidationCode(file, func)
5047 file.Write(" helper_->%sImmediate(%s);\n" %
5048 (func.name, func.MakeOriginalArgString("")))
5049 file.Write(" CheckGLError();\n")
5050 file.Write("}\n")
5051 file.Write("\n")
5053 def WriteGLES2ImplementationUnitTest(self, func, file):
5054 """Writes the GLES2 Implemention unit test."""
5055 client_test = func.GetInfo('client_test')
5056 if (client_test != None and client_test != True):
5057 return;
5058 code = """
5059 TEST_F(GLES2ImplementationTest, %(name)s) {
5060 %(type)s data[%(count)d] = {0};
5061 struct Cmds {
5062 cmds::%(name)sImmediate cmd;
5063 %(type)s data[%(count)d];
5066 for (int jj = 0; jj < %(count)d; ++jj) {
5067 data[jj] = static_cast<%(type)s>(jj);
5069 Cmds expected;
5070 expected.cmd.Init(%(cmd_args)s, &data[0]);
5071 gl_->%(name)s(%(args)s, &data[0]);
5072 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5075 cmd_arg_strings = [
5076 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
5078 gl_arg_strings = [
5079 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
5082 file.Write(code % {
5083 'name': func.name,
5084 'type': self.GetArrayType(func),
5085 'count': self.GetArrayCount(func),
5086 'args': ", ".join(gl_arg_strings),
5087 'cmd_args': ", ".join(cmd_arg_strings),
5090 def WriteImmediateCmdComputeSize(self, func, file):
5091 """Overrriden from TypeHandler."""
5092 file.Write(" static uint32_t ComputeDataSize() {\n")
5093 file.Write(" return static_cast<uint32_t>(\n")
5094 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
5095 (self.GetArrayType(func), self.GetArrayCount(func)))
5096 file.Write(" }\n")
5097 file.Write("\n")
5098 file.Write(" static uint32_t ComputeSize() {\n")
5099 file.Write(" return static_cast<uint32_t>(\n")
5100 file.Write(
5101 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
5102 file.Write(" }\n")
5103 file.Write("\n")
5105 def WriteImmediateCmdSetHeader(self, func, file):
5106 """Overrriden from TypeHandler."""
5107 file.Write(" void SetHeader() {\n")
5108 file.Write(
5109 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5110 file.Write(" }\n")
5111 file.Write("\n")
5113 def WriteImmediateCmdInit(self, func, file):
5114 """Overrriden from TypeHandler."""
5115 last_arg = func.GetLastOriginalArg()
5116 file.Write(" void Init(%s, %s _%s) {\n" %
5117 (func.MakeTypedCmdArgString("_"),
5118 last_arg.type, last_arg.name))
5119 file.Write(" SetHeader();\n")
5120 args = func.GetCmdArgs()
5121 for arg in args:
5122 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5123 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5124 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
5125 file.Write(" }\n")
5126 file.Write("\n")
5128 def WriteImmediateCmdSet(self, func, file):
5129 """Overrriden from TypeHandler."""
5130 last_arg = func.GetLastOriginalArg()
5131 copy_args = func.MakeCmdArgString("_", False)
5132 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5133 (func.MakeTypedCmdArgString("_", True),
5134 last_arg.type, last_arg.name))
5135 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5136 (copy_args, last_arg.name))
5137 file.Write(" const uint32_t size = ComputeSize();\n")
5138 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5139 "cmd, size);\n")
5140 file.Write(" }\n")
5141 file.Write("\n")
5143 def WriteImmediateCmdHelper(self, func, file):
5144 """Overrriden from TypeHandler."""
5145 code = """ void %(name)s(%(typed_args)s) {
5146 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5147 gles2::cmds::%(name)s* c =
5148 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5149 if (c) {
5150 c->Init(%(args)s);
5155 file.Write(code % {
5156 "name": func.name,
5157 "typed_args": func.MakeTypedOriginalArgString(""),
5158 "args": func.MakeOriginalArgString(""),
5161 def WriteImmediateFormatTest(self, func, file):
5162 """Overrriden from TypeHandler."""
5163 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5164 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5165 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
5166 for v in range(0, self.GetArrayCount(func)):
5167 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5168 (self.GetArrayType(func), v))
5169 file.Write(" };\n")
5170 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5171 (func.name, func.name))
5172 file.Write(" void* next_cmd = cmd.Set(\n")
5173 file.Write(" &cmd")
5174 args = func.GetCmdArgs()
5175 for value, arg in enumerate(args):
5176 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
5177 file.Write(",\n data);\n")
5178 args = func.GetCmdArgs()
5179 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5180 % func.name)
5181 file.Write(" cmd.header.command);\n")
5182 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5183 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5184 file.Write(" cmd.header.size * 4u);\n")
5185 for value, arg in enumerate(args):
5186 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5187 (arg.type, value + 11, arg.name))
5188 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5189 file.Write(" next_cmd, sizeof(cmd) +\n")
5190 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5191 file.Write(" // TODO(gman): Check that data was inserted;\n")
5192 file.Write("}\n")
5193 file.Write("\n")
5196 class PUTnHandler(ArrayArgTypeHandler):
5197 """Handler for PUTn 'glUniform__v' type functions."""
5199 def __init__(self):
5200 ArrayArgTypeHandler.__init__(self)
5202 def WriteServiceUnitTest(self, func, file, *extras):
5203 """Overridden from TypeHandler."""
5204 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
5206 valid_test = """
5207 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
5208 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5209 SpecializedSetup<cmds::%(name)s, 0>(true);
5210 cmds::%(name)s cmd;
5211 cmd.Init(%(args)s);
5212 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5213 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5216 gl_arg_strings = []
5217 arg_strings = []
5218 for count, arg in enumerate(func.GetOriginalArgs()):
5219 # hardcoded to match unit tests.
5220 if count == 0:
5221 # the location of the second element of the 2nd uniform.
5222 # defined in GLES2DecoderBase::SetupShaderForUniform
5223 gl_arg_strings.append("3")
5224 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
5225 elif count == 1:
5226 # the number of elements that gl will be called with.
5227 gl_arg_strings.append("3")
5228 # the number of elements requested in the command.
5229 arg_strings.append("5")
5230 else:
5231 gl_arg_strings.append(arg.GetValidGLArg(func))
5232 if not arg.IsConstant():
5233 arg_strings.append(arg.GetValidArg(func))
5234 extra = {
5235 'gl_args': ", ".join(gl_arg_strings),
5236 'args': ", ".join(arg_strings),
5238 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5240 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5241 """Overridden from TypeHandler."""
5242 valid_test = """
5243 TEST_P(%(test_name)s, %(name)sValidArgs) {
5244 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5245 EXPECT_CALL(
5246 *gl_,
5247 %(gl_func_name)s(%(gl_args)s,
5248 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5249 SpecializedSetup<cmds::%(name)s, 0>(true);
5250 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5251 cmd.Init(%(args)s, &temp[0]);
5252 EXPECT_EQ(error::kNoError,
5253 ExecuteImmediateCmd(cmd, sizeof(temp)));
5254 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5257 gl_arg_strings = []
5258 gl_any_strings = []
5259 arg_strings = []
5260 for arg in func.GetOriginalArgs()[0:-1]:
5261 gl_arg_strings.append(arg.GetValidGLArg(func))
5262 gl_any_strings.append("_")
5263 if not arg.IsConstant():
5264 arg_strings.append(arg.GetValidArg(func))
5265 extra = {
5266 'data_type': self.GetArrayType(func),
5267 'data_count': self.GetArrayCount(func),
5268 'args': ", ".join(arg_strings),
5269 'gl_args': ", ".join(gl_arg_strings),
5270 'gl_any_args': ", ".join(gl_any_strings),
5272 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5274 invalid_test = """
5275 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5276 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5277 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5278 SpecializedSetup<cmds::%(name)s, 0>(false);
5279 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5280 cmd.Init(%(all_but_last_args)s, &temp[0]);
5281 EXPECT_EQ(error::%(parse_result)s,
5282 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5285 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5287 def WriteGetDataSizeCode(self, func, file):
5288 """Overrriden from TypeHandler."""
5289 code = """ uint32_t data_size;
5290 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5291 return error::kOutOfBounds;
5294 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
5295 if func.IsImmediate():
5296 file.Write(" if (data_size > immediate_data_size) {\n")
5297 file.Write(" return error::kOutOfBounds;\n")
5298 file.Write(" }\n")
5300 def WriteGLES2Implementation(self, func, file):
5301 """Overrriden from TypeHandler."""
5302 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5303 (func.return_type, func.original_name,
5304 func.MakeTypedOriginalArgString("")))
5305 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5306 func.WriteDestinationInitalizationValidation(file)
5307 self.WriteClientGLCallLog(func, file)
5308 last_arg_name = func.GetLastOriginalArg().name
5309 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5310 for (GLsizei i = 0; i < count; ++i) {
5311 """)
5312 values_str = ' << ", " << '.join(
5313 ["%s[%d + i * %d]" % (
5314 last_arg_name, ndx, self.GetArrayCount(func)) for ndx in range(
5315 0, self.GetArrayCount(func))])
5316 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5317 file.Write(" }\n });\n")
5318 for arg in func.GetOriginalArgs():
5319 arg.WriteClientSideValidationCode(file, func)
5320 file.Write(" helper_->%sImmediate(%s);\n" %
5321 (func.name, func.MakeInitString("")))
5322 file.Write(" CheckGLError();\n")
5323 file.Write("}\n")
5324 file.Write("\n")
5326 def WriteGLES2ImplementationUnitTest(self, func, file):
5327 """Writes the GLES2 Implemention unit test."""
5328 code = """
5329 TEST_F(GLES2ImplementationTest, %(name)s) {
5330 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5331 struct Cmds {
5332 cmds::%(name)sImmediate cmd;
5333 %(type)s data[%(count_param)d][%(count)d];
5336 Cmds expected;
5337 for (int ii = 0; ii < %(count_param)d; ++ii) {
5338 for (int jj = 0; jj < %(count)d; ++jj) {
5339 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5342 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5343 gl_->%(name)s(%(args)s, &data[0][0]);
5344 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5347 cmd_arg_strings = [
5348 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
5350 gl_arg_strings = []
5351 count_param = 0
5352 for arg in func.GetOriginalArgs()[0:-1]:
5353 valid_value = arg.GetValidClientSideArg(func)
5354 gl_arg_strings.append(valid_value)
5355 if arg.name == "count":
5356 count_param = int(valid_value)
5357 file.Write(code % {
5358 'name': func.name,
5359 'type': self.GetArrayType(func),
5360 'count': self.GetArrayCount(func),
5361 'args': ", ".join(gl_arg_strings),
5362 'cmd_args': ", ".join(cmd_arg_strings),
5363 'count_param': count_param,
5366 # Test constants for invalid values, as they are not tested by the
5367 # service.
5368 constants = [
5369 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
5371 if not constants:
5372 return
5374 code = """
5375 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
5376 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5377 for (int ii = 0; ii < %(count_param)d; ++ii) {
5378 for (int jj = 0; jj < %(count)d; ++jj) {
5379 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5382 gl_->%(name)s(%(args)s, &data[0][0]);
5383 EXPECT_TRUE(NoCommandsWritten());
5384 EXPECT_EQ(%(gl_error)s, CheckError());
5387 for invalid_arg in constants:
5388 gl_arg_strings = []
5389 invalid = invalid_arg.GetInvalidArg(func)
5390 for arg in func.GetOriginalArgs()[0:-1]:
5391 if arg is invalid_arg:
5392 gl_arg_strings.append(invalid[0])
5393 else:
5394 valid_value = arg.GetValidClientSideArg(func)
5395 gl_arg_strings.append(valid_value)
5396 if arg.name == "count":
5397 count_param = int(valid_value)
5399 file.Write(code % {
5400 'name': func.name,
5401 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
5402 'type': self.GetArrayType(func),
5403 'count': self.GetArrayCount(func),
5404 'args': ", ".join(gl_arg_strings),
5405 'gl_error': invalid[2],
5406 'count_param': count_param,
5410 def WriteImmediateCmdComputeSize(self, func, file):
5411 """Overrriden from TypeHandler."""
5412 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
5413 file.Write(" return static_cast<uint32_t>(\n")
5414 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5415 (self.GetArrayType(func), self.GetArrayCount(func)))
5416 file.Write(" }\n")
5417 file.Write("\n")
5418 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
5419 file.Write(" return static_cast<uint32_t>(\n")
5420 file.Write(
5421 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5422 file.Write(" }\n")
5423 file.Write("\n")
5425 def WriteImmediateCmdSetHeader(self, func, file):
5426 """Overrriden from TypeHandler."""
5427 file.Write(" void SetHeader(GLsizei count) {\n")
5428 file.Write(
5429 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5430 file.Write(" }\n")
5431 file.Write("\n")
5433 def WriteImmediateCmdInit(self, func, file):
5434 """Overrriden from TypeHandler."""
5435 last_arg = func.GetLastOriginalArg()
5436 file.Write(" void Init(%s, %s _%s) {\n" %
5437 (func.MakeTypedCmdArgString("_"),
5438 last_arg.type, last_arg.name))
5439 file.Write(" SetHeader(_count);\n")
5440 args = func.GetCmdArgs()
5441 for arg in args:
5442 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5443 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5444 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5445 file.Write(" }\n")
5446 file.Write("\n")
5448 def WriteImmediateCmdSet(self, func, file):
5449 """Overrriden from TypeHandler."""
5450 last_arg = func.GetLastOriginalArg()
5451 copy_args = func.MakeCmdArgString("_", False)
5452 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5453 (func.MakeTypedCmdArgString("_", True),
5454 last_arg.type, last_arg.name))
5455 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5456 (copy_args, last_arg.name))
5457 file.Write(" const uint32_t size = ComputeSize(_count);\n")
5458 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5459 "cmd, size);\n")
5460 file.Write(" }\n")
5461 file.Write("\n")
5463 def WriteImmediateCmdHelper(self, func, file):
5464 """Overrriden from TypeHandler."""
5465 code = """ void %(name)s(%(typed_args)s) {
5466 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
5467 gles2::cmds::%(name)s* c =
5468 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5469 if (c) {
5470 c->Init(%(args)s);
5475 file.Write(code % {
5476 "name": func.name,
5477 "typed_args": func.MakeTypedInitString(""),
5478 "args": func.MakeInitString("")
5481 def WriteImmediateFormatTest(self, func, file):
5482 """Overrriden from TypeHandler."""
5483 args = func.GetCmdArgs()
5484 count_param = 0
5485 for arg in args:
5486 if arg.name == "count":
5487 count_param = int(arg.GetValidClientSideCmdArg(func))
5488 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5489 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5490 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
5491 for v in range(0, self.GetArrayCount(func) * count_param):
5492 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5493 (self.GetArrayType(func), v))
5494 file.Write(" };\n")
5495 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5496 (func.name, func.name))
5497 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5498 file.Write(" const size_t kExpectedCmdSize =\n")
5499 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5500 (self.GetArrayType(func), self.GetArrayCount(func)))
5501 file.Write(" void* next_cmd = cmd.Set(\n")
5502 file.Write(" &cmd")
5503 for value, arg in enumerate(args):
5504 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5505 file.Write(",\n data);\n")
5506 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5507 func.name)
5508 file.Write(" cmd.header.command);\n")
5509 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5510 for value, arg in enumerate(args):
5511 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5512 (arg.type, value + 1, arg.name))
5513 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5514 file.Write(" next_cmd, sizeof(cmd) +\n")
5515 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5516 file.Write(" // TODO(gman): Check that data was inserted;\n")
5517 file.Write("}\n")
5518 file.Write("\n")
5521 class PUTXnHandler(ArrayArgTypeHandler):
5522 """Handler for glUniform?f functions."""
5523 def __init__(self):
5524 ArrayArgTypeHandler.__init__(self)
5526 def WriteHandlerImplementation(self, func, file):
5527 """Overrriden from TypeHandler."""
5528 code = """ %(type)s temp[%(count)s] = { %(values)s};
5529 Do%(name)sv(%(location)s, 1, &temp[0]);
5531 values = ""
5532 args = func.GetOriginalArgs()
5533 count = int(self.GetArrayCount(func))
5534 num_args = len(args)
5535 for ii in range(count):
5536 values += "%s, " % args[len(args) - count + ii].name
5538 file.Write(code % {
5539 'name': func.name,
5540 'count': self.GetArrayCount(func),
5541 'type': self.GetArrayType(func),
5542 'location': args[0].name,
5543 'args': func.MakeOriginalArgString(""),
5544 'values': values,
5547 def WriteServiceUnitTest(self, func, file, *extras):
5548 """Overrriden from TypeHandler."""
5549 valid_test = """
5550 TEST_P(%(test_name)s, %(name)sValidArgs) {
5551 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5552 SpecializedSetup<cmds::%(name)s, 0>(true);
5553 cmds::%(name)s cmd;
5554 cmd.Init(%(args)s);
5555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5556 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5559 args = func.GetOriginalArgs()
5560 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
5561 self.WriteValidUnitTest(func, file, valid_test, {
5562 'name': func.name,
5563 'count': self.GetArrayCount(func),
5564 'local_args': local_args,
5565 }, *extras)
5567 invalid_test = """
5568 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5569 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5570 SpecializedSetup<cmds::%(name)s, 0>(false);
5571 cmds::%(name)s cmd;
5572 cmd.Init(%(args)s);
5573 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5576 self.WriteInvalidUnitTest(func, file, invalid_test, {
5577 'name': func.GetInfo('name'),
5578 'count': self.GetArrayCount(func),
5582 class GLcharHandler(CustomHandler):
5583 """Handler for functions that pass a single string ."""
5585 def __init__(self):
5586 CustomHandler.__init__(self)
5588 def WriteImmediateCmdComputeSize(self, func, file):
5589 """Overrriden from TypeHandler."""
5590 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
5591 file.Write(" return static_cast<uint32_t>(\n")
5592 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5593 file.Write(" }\n")
5595 def WriteImmediateCmdSetHeader(self, func, file):
5596 """Overrriden from TypeHandler."""
5597 code = """
5598 void SetHeader(uint32_t data_size) {
5599 header.SetCmdBySize<ValueType>(data_size);
5602 file.Write(code)
5604 def WriteImmediateCmdInit(self, func, file):
5605 """Overrriden from TypeHandler."""
5606 last_arg = func.GetLastOriginalArg()
5607 args = func.GetCmdArgs()
5608 set_code = []
5609 for arg in args:
5610 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5611 code = """
5612 void Init(%(typed_args)s, uint32_t _data_size) {
5613 SetHeader(_data_size);
5614 %(set_code)s
5615 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5619 file.Write(code % {
5620 "typed_args": func.MakeTypedArgString("_"),
5621 "set_code": "\n".join(set_code),
5622 "last_arg": last_arg.name
5625 def WriteImmediateCmdSet(self, func, file):
5626 """Overrriden from TypeHandler."""
5627 last_arg = func.GetLastOriginalArg()
5628 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
5629 func.MakeTypedCmdArgString("_", True))
5630 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5631 func.MakeCmdArgString("_"))
5632 file.Write(" return NextImmediateCmdAddress<ValueType>("
5633 "cmd, _data_size);\n")
5634 file.Write(" }\n")
5635 file.Write("\n")
5637 def WriteImmediateCmdHelper(self, func, file):
5638 """Overrriden from TypeHandler."""
5639 code = """ void %(name)s(%(typed_args)s) {
5640 const uint32_t data_size = strlen(name);
5641 gles2::cmds::%(name)s* c =
5642 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5643 if (c) {
5644 c->Init(%(args)s, data_size);
5649 file.Write(code % {
5650 "name": func.name,
5651 "typed_args": func.MakeTypedOriginalArgString(""),
5652 "args": func.MakeOriginalArgString(""),
5656 def WriteImmediateFormatTest(self, func, file):
5657 """Overrriden from TypeHandler."""
5658 init_code = []
5659 check_code = []
5660 all_but_last_arg = func.GetCmdArgs()[:-1]
5661 for value, arg in enumerate(all_but_last_arg):
5662 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5663 for value, arg in enumerate(all_but_last_arg):
5664 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5665 (arg.type, value + 11, arg.name))
5666 code = """
5667 TEST_F(GLES2FormatTest, %(func_name)s) {
5668 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5669 static const char* const test_str = \"test string\";
5670 void* next_cmd = cmd.Set(
5671 &cmd,
5672 %(init_code)s
5673 test_str,
5674 strlen(test_str));
5675 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
5676 cmd.header.command);
5677 EXPECT_EQ(sizeof(cmd) +
5678 RoundSizeToMultipleOfEntries(strlen(test_str)),
5679 cmd.header.size * 4u);
5680 EXPECT_EQ(static_cast<char*>(next_cmd),
5681 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5682 RoundSizeToMultipleOfEntries(strlen(test_str)));
5683 %(check_code)s
5684 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
5685 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5686 CheckBytesWritten(
5687 next_cmd,
5688 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5689 sizeof(cmd) + strlen(test_str));
5693 file.Write(code % {
5694 'func_name': func.name,
5695 'init_code': "\n".join(init_code),
5696 'check_code': "\n".join(check_code),
5700 class GLcharNHandler(CustomHandler):
5701 """Handler for functions that pass a single string with an optional len."""
5703 def __init__(self):
5704 CustomHandler.__init__(self)
5706 def InitFunction(self, func):
5707 """Overrriden from TypeHandler."""
5708 func.cmd_args = []
5709 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5711 def NeedsDataTransferFunction(self, func):
5712 """Overriden from TypeHandler."""
5713 return False
5715 def AddBucketFunction(self, generator, func):
5716 """Overrriden from TypeHandler."""
5717 pass
5719 def WriteServiceImplementation(self, func, file):
5720 """Overrriden from TypeHandler."""
5721 self.WriteServiceHandlerFunctionHeader(func, file)
5722 file.Write("""
5723 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5724 Bucket* bucket = GetBucket(bucket_id);
5725 if (!bucket || bucket->size() == 0) {
5726 return error::kInvalidArguments;
5728 std::string str;
5729 if (!bucket->GetAsString(&str)) {
5730 return error::kInvalidArguments;
5732 %(gl_func_name)s(0, str.c_str());
5733 return error::kNoError;
5736 """ % {
5737 'name': func.name,
5738 'gl_func_name': func.GetGLFunctionName(),
5739 'bucket_id': func.cmd_args[0].name,
5743 class IsHandler(TypeHandler):
5744 """Handler for glIs____ type and glGetError functions."""
5746 def __init__(self):
5747 TypeHandler.__init__(self)
5749 def InitFunction(self, func):
5750 """Overrriden from TypeHandler."""
5751 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
5752 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
5753 if func.GetInfo('result') == None:
5754 func.AddInfo('result', ['uint32_t'])
5756 def WriteServiceUnitTest(self, func, file, *extras):
5757 """Overrriden from TypeHandler."""
5758 valid_test = """
5759 TEST_P(%(test_name)s, %(name)sValidArgs) {
5760 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5761 SpecializedSetup<cmds::%(name)s, 0>(true);
5762 cmds::%(name)s cmd;
5763 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5764 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5765 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5768 comma = ""
5769 if len(func.GetOriginalArgs()):
5770 comma =", "
5771 self.WriteValidUnitTest(func, file, valid_test, {
5772 'comma': comma,
5773 }, *extras)
5775 invalid_test = """
5776 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5778 SpecializedSetup<cmds::%(name)s, 0>(false);
5779 cmds::%(name)s cmd;
5780 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5781 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5784 self.WriteInvalidUnitTest(func, file, invalid_test, {
5785 'comma': comma,
5786 }, *extras)
5788 invalid_test = """
5789 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5790 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5791 SpecializedSetup<cmds::%(name)s, 0>(false);
5792 cmds::%(name)s cmd;
5793 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5794 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5795 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5796 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5799 self.WriteValidUnitTest(func, file, invalid_test, {
5800 'comma': comma,
5801 }, *extras)
5803 def WriteServiceImplementation(self, func, file):
5804 """Overrriden from TypeHandler."""
5805 self.WriteServiceHandlerFunctionHeader(func, file)
5806 args = func.GetOriginalArgs()
5807 for arg in args:
5808 arg.WriteGetCode(file)
5810 code = """ typedef cmds::%(func_name)s::Result Result;
5811 Result* result_dst = GetSharedMemoryAs<Result*>(
5812 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5813 if (!result_dst) {
5814 return error::kOutOfBounds;
5817 file.Write(code % {'func_name': func.name})
5818 func.WriteHandlerValidation(file)
5819 file.Write(" *result_dst = %s(%s);\n" %
5820 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5821 file.Write(" return error::kNoError;\n")
5822 file.Write("}\n")
5823 file.Write("\n")
5825 def WriteGLES2Implementation(self, func, file):
5826 """Overrriden from TypeHandler."""
5827 impl_func = func.GetInfo('impl_func')
5828 if impl_func == None or impl_func == True:
5829 error_value = func.GetInfo("error_value") or "GL_FALSE"
5830 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5831 (func.return_type, func.original_name,
5832 func.MakeTypedOriginalArgString("")))
5833 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5834 self.WriteTraceEvent(func, file)
5835 func.WriteDestinationInitalizationValidation(file)
5836 self.WriteClientGLCallLog(func, file)
5837 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5838 file.Write(" Result* result = GetResultAs<Result*>();\n")
5839 file.Write(" if (!result) {\n")
5840 file.Write(" return %s;\n" % error_value)
5841 file.Write(" }\n")
5842 file.Write(" *result = 0;\n")
5843 arg_string = func.MakeOriginalArgString("")
5844 comma = ""
5845 if len(arg_string) > 0:
5846 comma = ", "
5847 file.Write(
5848 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5849 (func.name, arg_string, comma))
5850 file.Write(" WaitForCmd();\n")
5851 file.Write(" %s result_value = *result" % func.return_type)
5852 if func.return_type == "GLboolean":
5853 file.Write(" != 0")
5854 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
5855 file.Write(" CheckGLError();\n")
5856 file.Write(" return result_value;\n")
5857 file.Write("}\n")
5858 file.Write("\n")
5860 def WriteGLES2ImplementationUnitTest(self, func, file):
5861 """Overrriden from TypeHandler."""
5862 client_test = func.GetInfo('client_test')
5863 if client_test == None or client_test == True:
5864 code = """
5865 TEST_F(GLES2ImplementationTest, %(name)s) {
5866 struct Cmds {
5867 cmds::%(name)s cmd;
5870 Cmds expected;
5871 ExpectedMemoryInfo result1 =
5872 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5873 expected.cmd.Init(1, result1.id, result1.offset);
5875 EXPECT_CALL(*command_buffer(), OnFlush())
5876 .WillOnce(SetMemory(result1.ptr, uint32_t(1)))
5877 .RetiresOnSaturation();
5879 GLboolean result = gl_->%(name)s(1);
5880 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5881 EXPECT_TRUE(result);
5884 file.Write(code % {
5885 'name': func.name,
5889 class STRnHandler(TypeHandler):
5890 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5891 GetTranslatedShaderSourceANGLE."""
5893 def __init__(self):
5894 TypeHandler.__init__(self)
5896 def InitFunction(self, func):
5897 """Overrriden from TypeHandler."""
5898 # remove all but the first cmd args.
5899 cmd_args = func.GetCmdArgs()
5900 func.ClearCmdArgs()
5901 func.AddCmdArg(cmd_args[0])
5902 # add on a bucket id.
5903 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
5905 def WriteGLES2Implementation(self, func, file):
5906 """Overrriden from TypeHandler."""
5907 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5908 GPU_CLIENT_SINGLE_THREAD_CHECK();
5910 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5911 << "] gl%(func_name)s" << "("
5912 << %(arg0)s << ", "
5913 << %(arg1)s << ", "
5914 << static_cast<void*>(%(arg2)s) << ", "
5915 << static_cast<void*>(%(arg3)s) << ")");
5916 helper_->SetBucketSize(kResultBucketId, 0);
5917 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5918 std::string str;
5919 GLsizei max_size = 0;
5920 if (GetBucketAsString(kResultBucketId, &str)) {
5921 if (bufsize > 0) {
5922 max_size =
5923 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5924 memcpy(%(dest_name)s, str.c_str(), max_size);
5925 %(dest_name)s[max_size] = '\\0';
5926 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5929 if (%(length_name)s != NULL) {
5930 *%(length_name)s = max_size;
5932 CheckGLError();
5935 args = func.GetOriginalArgs()
5936 str_args = {
5937 'return_type': func.return_type,
5938 'func_name': func.original_name,
5939 'args': func.MakeTypedOriginalArgString(""),
5940 'id_name': args[0].name,
5941 'bufsize_name': args[1].name,
5942 'length_name': args[2].name,
5943 'dest_name': args[3].name,
5944 'arg0': args[0].name,
5945 'arg1': args[1].name,
5946 'arg2': args[2].name,
5947 'arg3': args[3].name,
5949 file.Write(code_1 % str_args)
5950 func.WriteDestinationInitalizationValidation(file)
5951 file.Write(code_2 % str_args)
5953 def WriteServiceUnitTest(self, func, file, *extras):
5954 """Overrriden from TypeHandler."""
5955 valid_test = """
5956 TEST_P(%(test_name)s, %(name)sValidArgs) {
5957 const char* kInfo = "hello";
5958 const uint32_t kBucketId = 123;
5959 SpecializedSetup<cmds::%(name)s, 0>(true);
5960 %(expect_len_code)s
5961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5962 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5963 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5964 cmds::%(name)s cmd;
5965 cmd.Init(%(args)s);
5966 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5967 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5968 ASSERT_TRUE(bucket != NULL);
5969 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5970 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5971 bucket->size()));
5972 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5975 args = func.GetOriginalArgs()
5976 id_name = args[0].GetValidGLArg(func)
5977 get_len_func = func.GetInfo('get_len_func')
5978 get_len_enum = func.GetInfo('get_len_enum')
5979 sub = {
5980 'id_name': id_name,
5981 'get_len_func': get_len_func,
5982 'get_len_enum': get_len_enum,
5983 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5984 args[0].GetValidGLArg(func),
5985 'args': '%s, kBucketId' % args[0].GetValidArg(func),
5986 'expect_len_code': '',
5988 if get_len_func and get_len_func[0:2] == 'gl':
5989 sub['expect_len_code'] = (
5990 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5991 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5992 get_len_func[2:], id_name, get_len_enum)
5993 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
5995 invalid_test = """
5996 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5997 const uint32_t kBucketId = 123;
5998 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5999 .Times(0);
6000 cmds::%(name)s cmd;
6001 cmd.Init(kInvalidClientId, kBucketId);
6002 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6003 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6006 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6008 def WriteServiceImplementation(self, func, file):
6009 """Overrriden from TypeHandler."""
6010 pass
6012 class NamedType(object):
6013 """A class that represents a type of an argument in a client function.
6015 A type of an argument that is to be passed through in the command buffer
6016 command. Currently used only for the arguments that are specificly named in
6017 the 'cmd_buffer_functions.txt' file, mostly enums.
6020 def __init__(self, info):
6021 assert not 'is_complete' in info or info['is_complete'] == True
6022 self.info = info
6023 self.valid = info['valid']
6024 if 'invalid' in info:
6025 self.invalid = info['invalid']
6026 else:
6027 self.invalid = []
6029 def GetType(self):
6030 return self.info['type']
6032 def GetInvalidValues(self):
6033 return self.invalid
6035 def GetValidValues(self):
6036 return self.valid
6038 def IsConstant(self):
6039 if not 'is_complete' in self.info:
6040 return False
6042 return len(self.GetValidValues()) == 1
6044 def GetConstantValue(self):
6045 return self.GetValidValues()[0]
6047 class Argument(object):
6048 """A class that represents a function argument."""
6050 cmd_type_map_ = {
6051 'GLenum': 'uint32_t',
6052 'GLint': 'int32_t',
6053 'GLintptr': 'int32_t',
6054 'GLsizei': 'int32_t',
6055 'GLsizeiptr': 'int32_t',
6056 'GLfloat': 'float',
6057 'GLclampf': 'float',
6059 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
6061 def __init__(self, name, type):
6062 self.name = name
6063 self.optional = type.endswith("Optional*")
6064 if self.optional:
6065 type = type[:-9] + "*"
6066 self.type = type
6068 if type in self.cmd_type_map_:
6069 self.cmd_type = self.cmd_type_map_[type]
6070 else:
6071 self.cmd_type = 'uint32_t'
6073 def IsPointer(self):
6074 """Returns true if argument is a pointer."""
6075 return False
6077 def IsConstant(self):
6078 """Returns true if the argument has only one valid value."""
6079 return False
6081 def AddCmdArgs(self, args):
6082 """Adds command arguments for this argument to the given list."""
6083 if not self.IsConstant():
6084 return args.append(self)
6086 def AddInitArgs(self, args):
6087 """Adds init arguments for this argument to the given list."""
6088 if not self.IsConstant():
6089 return args.append(self)
6091 def GetValidArg(self, func):
6092 """Gets a valid value for this argument."""
6093 valid_arg = func.GetValidArg(self)
6094 if valid_arg != None:
6095 return valid_arg
6097 index = func.GetOriginalArgs().index(self)
6098 return str(index + 1)
6100 def GetValidClientSideArg(self, func):
6101 """Gets a valid value for this argument."""
6102 valid_arg = func.GetValidArg(self)
6103 if valid_arg != None:
6104 return valid_arg
6106 index = func.GetOriginalArgs().index(self)
6107 return str(index + 1)
6109 def GetValidClientSideCmdArg(self, func):
6110 """Gets a valid value for this argument."""
6111 valid_arg = func.GetValidArg(self)
6112 if valid_arg != None:
6113 return valid_arg
6114 try:
6115 index = func.GetOriginalArgs().index(self)
6116 return str(index + 1)
6117 except ValueError:
6118 pass
6119 index = func.GetCmdArgs().index(self)
6120 return str(index + 1)
6122 def GetValidGLArg(self, func):
6123 """Gets a valid GL value for this argument."""
6124 return self.GetValidArg(func)
6126 def GetValidNonCachedClientSideArg(self, func):
6127 """Returns a valid value for this argument in a GL call.
6128 Using the value will produce a command buffer service invocation.
6129 Returns None if there is no such value."""
6130 return '123'
6132 def GetValidNonCachedClientSideCmdArg(self, func):
6133 """Returns a valid value for this argument in a command buffer command.
6134 Calling the GL function with the value returned by
6135 GetValidNonCachedClientSideArg will result in a command buffer command
6136 that contains the value returned by this function. """
6137 return '123'
6139 def GetNumInvalidValues(self, func):
6140 """returns the number of invalid values to be tested."""
6141 return 0
6143 def GetInvalidArg(self, index):
6144 """returns an invalid value and expected parse result by index."""
6145 return ("---ERROR0---", "---ERROR2---", None)
6147 def GetLogArg(self):
6148 """Get argument appropriate for LOG macro."""
6149 if self.type == 'GLboolean':
6150 return 'GLES2Util::GetStringBool(%s)' % self.name
6151 if self.type == 'GLenum':
6152 return 'GLES2Util::GetStringEnum(%s)' % self.name
6153 return self.name
6155 def WriteGetCode(self, file):
6156 """Writes the code to get an argument from a command structure."""
6157 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
6158 (self.type, self.name, self.type, self.name))
6160 def WriteValidationCode(self, file, func):
6161 """Writes the validation code for an argument."""
6162 pass
6164 def WriteClientSideValidationCode(self, file, func):
6165 """Writes the validation code for an argument."""
6166 pass
6168 def WriteDestinationInitalizationValidation(self, file, func):
6169 """Writes the client side destintion initialization validation."""
6170 pass
6172 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
6173 """Writes the client side destintion initialization validation if needed."""
6174 parts = self.type.split(" ")
6175 if len(parts) > 1:
6176 return
6177 if parts[0] in self.need_validation_:
6178 file.Write(
6179 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
6180 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
6183 def WriteGetAddress(self, file):
6184 """Writes the code to get the address this argument refers to."""
6185 pass
6187 def GetImmediateVersion(self):
6188 """Gets the immediate version of this argument."""
6189 return self
6191 def GetBucketVersion(self):
6192 """Gets the bucket version of this argument."""
6193 return self
6196 class BoolArgument(Argument):
6197 """class for GLboolean"""
6199 def __init__(self, name, type):
6200 Argument.__init__(self, name, 'GLboolean')
6202 def GetValidArg(self, func):
6203 """Gets a valid value for this argument."""
6204 return 'true'
6206 def GetValidClientSideArg(self, func):
6207 """Gets a valid value for this argument."""
6208 return 'true'
6210 def GetValidClientSideCmdArg(self, func):
6211 """Gets a valid value for this argument."""
6212 return 'true'
6214 def GetValidGLArg(self, func):
6215 """Gets a valid GL value for this argument."""
6216 return 'true'
6219 class UniformLocationArgument(Argument):
6220 """class for uniform locations."""
6222 def __init__(self, name):
6223 Argument.__init__(self, name, "GLint")
6225 def WriteGetCode(self, file):
6226 """Writes the code to get an argument from a command structure."""
6227 code = """ %s %s = static_cast<%s>(c.%s);
6229 file.Write(code % (self.type, self.name, self.type, self.name))
6231 class DataSizeArgument(Argument):
6232 """class for data_size which Bucket commands do not need."""
6234 def __init__(self, name):
6235 Argument.__init__(self, name, "uint32_t")
6237 def GetBucketVersion(self):
6238 return None
6241 class SizeArgument(Argument):
6242 """class for GLsizei and GLsizeiptr."""
6244 def __init__(self, name, type):
6245 Argument.__init__(self, name, type)
6247 def GetNumInvalidValues(self, func):
6248 """overridden from Argument."""
6249 if func.IsImmediate():
6250 return 0
6251 return 1
6253 def GetInvalidArg(self, index):
6254 """overridden from Argument."""
6255 return ("-1", "kNoError", "GL_INVALID_VALUE")
6257 def WriteValidationCode(self, file, func):
6258 """overridden from Argument."""
6259 file.Write(" if (%s < 0) {\n" % self.name)
6260 file.Write(
6261 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6262 (func.original_name, self.name))
6263 file.Write(" return error::kNoError;\n")
6264 file.Write(" }\n")
6266 def WriteClientSideValidationCode(self, file, func):
6267 """overridden from Argument."""
6268 file.Write(" if (%s < 0) {\n" % self.name)
6269 file.Write(
6270 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6271 (func.original_name, self.name))
6272 file.Write(" return;\n")
6273 file.Write(" }\n")
6276 class SizeNotNegativeArgument(SizeArgument):
6277 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
6279 def __init__(self, name, type, gl_type):
6280 SizeArgument.__init__(self, name, gl_type)
6282 def GetInvalidArg(self, index):
6283 """overridden from SizeArgument."""
6284 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
6286 def WriteValidationCode(self, file, func):
6287 """overridden from SizeArgument."""
6288 pass
6291 class EnumBaseArgument(Argument):
6292 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
6294 def __init__(self, name, gl_type, type, gl_error):
6295 Argument.__init__(self, name, gl_type)
6297 self.local_type = type
6298 self.gl_error = gl_error
6299 name = type[len(gl_type):]
6300 self.type_name = name
6301 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
6303 def IsConstant(self):
6304 return self.named_type.IsConstant()
6306 def GetConstantValue(self):
6307 return self.named_type.GetConstantValue()
6309 def WriteValidationCode(self, file, func):
6310 if self.named_type.IsConstant():
6311 return
6312 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
6313 (ToUnderscore(self.type_name), self.name))
6314 if self.gl_error == "GL_INVALID_ENUM":
6315 file.Write(
6316 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
6317 (func.original_name, self.name, self.name))
6318 else:
6319 file.Write(
6320 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
6321 (self.gl_error, func.original_name, self.name, self.gl_error))
6322 file.Write(" return error::kNoError;\n")
6323 file.Write(" }\n")
6325 def WriteClientSideValidationCode(self, file, func):
6326 if not self.named_type.IsConstant():
6327 return
6328 file.Write(" if (%s != %s) {" % (self.name,
6329 self.GetConstantValue()))
6330 file.Write(
6331 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
6332 (self.gl_error, func.original_name, self.name, self.gl_error))
6333 if func.return_type == "void":
6334 file.Write(" return;\n")
6335 else:
6336 file.Write(" return %s;\n" % func.GetErrorReturnString())
6337 file.Write(" }\n")
6339 def GetValidArg(self, func):
6340 valid_arg = func.GetValidArg(self)
6341 if valid_arg != None:
6342 return valid_arg
6343 valid = self.named_type.GetValidValues()
6344 if valid:
6345 num_valid = len(valid)
6346 return valid[0]
6348 index = func.GetOriginalArgs().index(self)
6349 return str(index + 1)
6351 def GetValidClientSideArg(self, func):
6352 """Gets a valid value for this argument."""
6353 return self.GetValidArg(func)
6355 def GetValidClientSideCmdArg(self, func):
6356 """Gets a valid value for this argument."""
6357 valid_arg = func.GetValidArg(self)
6358 if valid_arg != None:
6359 return valid_arg
6361 valid = self.named_type.GetValidValues()
6362 if valid:
6363 num_valid = len(valid)
6364 return valid[0]
6366 try:
6367 index = func.GetOriginalArgs().index(self)
6368 return str(index + 1)
6369 except ValueError:
6370 pass
6371 index = func.GetCmdArgs().index(self)
6372 return str(index + 1)
6374 def GetValidGLArg(self, func):
6375 """Gets a valid value for this argument."""
6376 return self.GetValidArg(func)
6378 def GetNumInvalidValues(self, func):
6379 """returns the number of invalid values to be tested."""
6380 return len(self.named_type.GetInvalidValues())
6382 def GetInvalidArg(self, index):
6383 """returns an invalid value by index."""
6384 invalid = self.named_type.GetInvalidValues()
6385 if invalid:
6386 num_invalid = len(invalid)
6387 if index >= num_invalid:
6388 index = num_invalid - 1
6389 return (invalid[index], "kNoError", self.gl_error)
6390 return ("---ERROR1---", "kNoError", self.gl_error)
6393 class EnumArgument(EnumBaseArgument):
6394 """A class that represents a GLenum argument"""
6396 def __init__(self, name, type):
6397 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6399 def GetLogArg(self):
6400 """Overridden from Argument."""
6401 return ("GLES2Util::GetString%s(%s)" %
6402 (self.type_name, self.name))
6405 class IntArgument(EnumBaseArgument):
6406 """A class for a GLint argument that can only except specific values.
6408 For example glTexImage2D takes a GLint for its internalformat
6409 argument instead of a GLenum.
6412 def __init__(self, name, type):
6413 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6416 class ValidatedBoolArgument(EnumBaseArgument):
6417 """A class for a GLboolean argument that can only except specific values.
6419 For example glUniformMatrix takes a GLboolean for it's transpose but it
6420 must be false.
6423 def __init__(self, name, type):
6424 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6426 def GetLogArg(self):
6427 """Overridden from Argument."""
6428 return 'GLES2Util::GetStringBool(%s)' % self.name
6431 class ImmediatePointerArgument(Argument):
6432 """A class that represents an immediate argument to a function.
6434 An immediate argument is one where the data follows the command.
6437 def __init__(self, name, type):
6438 Argument.__init__(self, name, type)
6440 def IsPointer(self):
6441 return True
6443 def GetPointedType(self):
6444 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
6445 assert match
6446 return match.groupdict()['element_type']
6448 def AddCmdArgs(self, args):
6449 """Overridden from Argument."""
6450 pass
6452 def WriteGetCode(self, file):
6453 """Overridden from Argument."""
6454 file.Write(
6455 " %s %s = GetImmediateDataAs<%s>(\n" %
6456 (self.type, self.name, self.type))
6457 file.Write(" c, data_size, immediate_data_size);\n")
6459 def WriteValidationCode(self, file, func):
6460 """Overridden from Argument."""
6461 file.Write(" if (%s == NULL) {\n" % self.name)
6462 file.Write(" return error::kOutOfBounds;\n")
6463 file.Write(" }\n")
6465 def GetImmediateVersion(self):
6466 """Overridden from Argument."""
6467 return None
6469 def WriteDestinationInitalizationValidation(self, file, func):
6470 """Overridden from Argument."""
6471 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6473 def GetLogArg(self):
6474 """Overridden from Argument."""
6475 return "static_cast<const void*>(%s)" % self.name
6478 class BucketPointerArgument(Argument):
6479 """A class that represents an bucket argument to a function."""
6481 def __init__(self, name, type):
6482 Argument.__init__(self, name, type)
6484 def AddCmdArgs(self, args):
6485 """Overridden from Argument."""
6486 pass
6488 def WriteGetCode(self, file):
6489 """Overridden from Argument."""
6490 file.Write(
6491 " %s %s = bucket->GetData(0, data_size);\n" %
6492 (self.type, self.name))
6494 def WriteValidationCode(self, file, func):
6495 """Overridden from Argument."""
6496 pass
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 PointerArgument(Argument):
6512 """A class that represents a pointer argument to a function."""
6514 def __init__(self, name, type):
6515 Argument.__init__(self, name, type)
6517 def IsPointer(self):
6518 """Returns true if argument is a pointer."""
6519 return True
6521 def GetPointedType(self):
6522 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
6523 assert match
6524 return match.groupdict()['element_type']
6526 def GetValidArg(self, func):
6527 """Overridden from Argument."""
6528 return "shared_memory_id_, shared_memory_offset_"
6530 def GetValidGLArg(self, func):
6531 """Overridden from Argument."""
6532 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6534 def GetNumInvalidValues(self, func):
6535 """Overridden from Argument."""
6536 return 2
6538 def GetInvalidArg(self, index):
6539 """Overridden from Argument."""
6540 if index == 0:
6541 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6542 else:
6543 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6544 "kOutOfBounds", None)
6546 def GetLogArg(self):
6547 """Overridden from Argument."""
6548 return "static_cast<const void*>(%s)" % self.name
6550 def AddCmdArgs(self, args):
6551 """Overridden from Argument."""
6552 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
6553 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
6555 def WriteGetCode(self, file):
6556 """Overridden from Argument."""
6557 file.Write(
6558 " %s %s = GetSharedMemoryAs<%s>(\n" %
6559 (self.type, self.name, self.type))
6560 file.Write(
6561 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6562 (self.name, self.name))
6564 def WriteGetAddress(self, file):
6565 """Overridden from Argument."""
6566 file.Write(
6567 " %s %s = GetSharedMemoryAs<%s>(\n" %
6568 (self.type, self.name, self.type))
6569 file.Write(
6570 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6571 (self.name, self.name, self.name))
6573 def WriteValidationCode(self, file, func):
6574 """Overridden from Argument."""
6575 file.Write(" if (%s == NULL) {\n" % self.name)
6576 file.Write(" return error::kOutOfBounds;\n")
6577 file.Write(" }\n")
6579 def GetImmediateVersion(self):
6580 """Overridden from Argument."""
6581 return ImmediatePointerArgument(self.name, self.type)
6583 def GetBucketVersion(self):
6584 """Overridden from Argument."""
6585 if self.type == "const char*":
6586 return InputStringBucketArgument(self.name, self.type)
6587 return BucketPointerArgument(self.name, self.type)
6589 def WriteDestinationInitalizationValidation(self, file, func):
6590 """Overridden from Argument."""
6591 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6594 class InputStringBucketArgument(Argument):
6595 """An string input argument where the string is passed in a bucket."""
6597 def __init__(self, name, type):
6598 Argument.__init__(self, name + "_bucket_id", "uint32_t")
6600 def WriteGetCode(self, file):
6601 """Overridden from Argument."""
6602 code = """
6603 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6604 if (!%(name)s_bucket) {
6605 return error::kInvalidArguments;
6607 std::string %(name)s_str;
6608 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6609 return error::kInvalidArguments;
6611 const char* %(name)s = %(name)s_str.c_str();
6613 file.Write(code % {
6614 'name': self.name,
6617 def GetValidArg(self, func):
6618 return "kNameBucketId"
6620 def GetValidGLArg(self, func):
6621 return "_"
6624 class ResourceIdArgument(Argument):
6625 """A class that represents a resource id argument to a function."""
6627 def __init__(self, name, type):
6628 match = re.match("(GLid\w+)", type)
6629 self.resource_type = match.group(1)[4:]
6630 type = type.replace(match.group(1), "GLuint")
6631 Argument.__init__(self, name, type)
6633 def WriteGetCode(self, file):
6634 """Overridden from Argument."""
6635 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6637 def GetValidArg(self, func):
6638 return "client_%s_id_" % self.resource_type.lower()
6640 def GetValidGLArg(self, func):
6641 return "kService%sId" % self.resource_type
6644 class ResourceIdBindArgument(Argument):
6645 """Represents a resource id argument to a bind function."""
6647 def __init__(self, name, type):
6648 match = re.match("(GLidBind\w+)", type)
6649 self.resource_type = match.group(1)[8:]
6650 type = type.replace(match.group(1), "GLuint")
6651 Argument.__init__(self, name, type)
6653 def WriteGetCode(self, file):
6654 """Overridden from Argument."""
6655 code = """ %(type)s %(name)s = c.%(name)s;
6657 file.Write(code % {'type': self.type, 'name': self.name})
6659 def GetValidArg(self, func):
6660 return "client_%s_id_" % self.resource_type.lower()
6662 def GetValidGLArg(self, func):
6663 return "kService%sId" % self.resource_type
6666 class ResourceIdZeroArgument(Argument):
6667 """Represents a resource id argument to a function that can be zero."""
6669 def __init__(self, name, type):
6670 match = re.match("(GLidZero\w+)", type)
6671 self.resource_type = match.group(1)[8:]
6672 type = type.replace(match.group(1), "GLuint")
6673 Argument.__init__(self, name, type)
6675 def WriteGetCode(self, file):
6676 """Overridden from Argument."""
6677 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6679 def GetValidArg(self, func):
6680 return "client_%s_id_" % self.resource_type.lower()
6682 def GetValidGLArg(self, func):
6683 return "kService%sId" % self.resource_type
6685 def GetNumInvalidValues(self, func):
6686 """returns the number of invalid values to be tested."""
6687 return 1
6689 def GetInvalidArg(self, index):
6690 """returns an invalid value by index."""
6691 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6694 class Function(object):
6695 """A class that represents a function."""
6697 type_handlers = {
6698 '': TypeHandler(),
6699 'Bind': BindHandler(),
6700 'Create': CreateHandler(),
6701 'Custom': CustomHandler(),
6702 'Data': DataHandler(),
6703 'Delete': DeleteHandler(),
6704 'DELn': DELnHandler(),
6705 'GENn': GENnHandler(),
6706 'GETn': GETnHandler(),
6707 'GLchar': GLcharHandler(),
6708 'GLcharN': GLcharNHandler(),
6709 'HandWritten': HandWrittenHandler(),
6710 'Is': IsHandler(),
6711 'Manual': ManualHandler(),
6712 'PUT': PUTHandler(),
6713 'PUTn': PUTnHandler(),
6714 'PUTXn': PUTXnHandler(),
6715 'StateSet': StateSetHandler(),
6716 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6717 'StateSetFrontBack': StateSetFrontBackHandler(),
6718 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6719 'StateSetNamedParameter': StateSetNamedParameter(),
6720 'STRn': STRnHandler(),
6721 'Todo': TodoHandler(),
6724 def __init__(self, name, info):
6725 self.name = name
6726 self.original_name = info['original_name']
6728 self.original_args = self.ParseArgs(info['original_args'])
6730 if 'cmd_args' in info:
6731 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
6732 else:
6733 self.args_for_cmds = self.original_args[:]
6735 self.return_type = info['return_type']
6736 if self.return_type != 'void':
6737 self.return_arg = CreateArg(info['return_type'] + " result")
6738 else:
6739 self.return_arg = None
6741 self.num_pointer_args = sum(
6742 [1 for arg in self.args_for_cmds if arg.IsPointer()])
6743 self.info = info
6744 self.type_handler = self.type_handlers[info['type']]
6745 self.can_auto_generate = (self.num_pointer_args == 0 and
6746 info['return_type'] == "void")
6747 self.InitFunction()
6749 def ParseArgs(self, arg_string):
6750 """Parses a function arg string."""
6751 args = []
6752 parts = arg_string.split(',')
6753 for arg_string in parts:
6754 arg = CreateArg(arg_string)
6755 if arg:
6756 args.append(arg)
6757 return args
6759 def IsType(self, type_name):
6760 """Returns true if function is a certain type."""
6761 return self.info['type'] == type_name
6763 def InitFunction(self):
6764 """Creates command args and calls the init function for the type handler.
6766 Creates argument lists for command buffer commands, eg. self.cmd_args and
6767 self.init_args.
6768 Calls the type function initialization.
6769 Override to create different kind of command buffer command argument lists.
6771 self.cmd_args = []
6772 for arg in self.args_for_cmds:
6773 arg.AddCmdArgs(self.cmd_args)
6775 self.init_args = []
6776 for arg in self.args_for_cmds:
6777 arg.AddInitArgs(self.init_args)
6779 if self.return_arg:
6780 self.init_args.append(self.return_arg)
6782 self.type_handler.InitFunction(self)
6784 def IsImmediate(self):
6785 """Returns whether the function is immediate data function or not."""
6786 return False
6788 def GetInfo(self, name, default = None):
6789 """Returns a value from the function info for this function."""
6790 if name in self.info:
6791 return self.info[name]
6792 return default
6794 def GetValidArg(self, arg):
6795 """Gets a valid argument value for the parameter arg from the function info
6796 if one exists."""
6797 try:
6798 index = self.GetOriginalArgs().index(arg)
6799 except ValueError:
6800 return None
6802 valid_args = self.GetInfo('valid_args')
6803 if valid_args and str(index) in valid_args:
6804 return valid_args[str(index)]
6805 return None
6807 def AddInfo(self, name, value):
6808 """Adds an info."""
6809 self.info[name] = value
6811 def IsExtension(self):
6812 return self.GetInfo('extension') or self.GetInfo('extension_flag')
6814 def IsCoreGLFunction(self):
6815 return (not self.IsExtension() and
6816 not self.GetInfo('pepper_interface'))
6818 def InPepperInterface(self, interface):
6819 ext = self.GetInfo('pepper_interface')
6820 if not interface.GetName():
6821 return self.IsCoreGLFunction()
6822 return ext == interface.GetName()
6824 def InAnyPepperExtension(self):
6825 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6827 def GetErrorReturnString(self):
6828 if self.GetInfo("error_return"):
6829 return self.GetInfo("error_return")
6830 elif self.return_type == "GLboolean":
6831 return "GL_FALSE"
6832 elif "*" in self.return_type:
6833 return "NULL"
6834 return "0"
6836 def GetGLFunctionName(self):
6837 """Gets the function to call to execute GL for this command."""
6838 if self.GetInfo('decoder_func'):
6839 return self.GetInfo('decoder_func')
6840 return "gl%s" % self.original_name
6842 def GetGLTestFunctionName(self):
6843 gl_func_name = self.GetInfo('gl_test_func')
6844 if gl_func_name == None:
6845 gl_func_name = self.GetGLFunctionName()
6846 if gl_func_name.startswith("gl"):
6847 gl_func_name = gl_func_name[2:]
6848 else:
6849 gl_func_name = self.original_name
6850 return gl_func_name
6852 def GetDataTransferMethods(self):
6853 return self.GetInfo('data_transfer_methods',
6854 ['immediate' if self.num_pointer_args == 1 else 'shm'])
6856 def AddCmdArg(self, arg):
6857 """Adds a cmd argument to this function."""
6858 self.cmd_args.append(arg)
6860 def GetCmdArgs(self):
6861 """Gets the command args for this function."""
6862 return self.cmd_args
6864 def ClearCmdArgs(self):
6865 """Clears the command args for this function."""
6866 self.cmd_args = []
6868 def GetCmdConstants(self):
6869 """Gets the constants for this function."""
6870 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
6872 def GetInitArgs(self):
6873 """Gets the init args for this function."""
6874 return self.init_args
6876 def GetOriginalArgs(self):
6877 """Gets the original arguments to this function."""
6878 return self.original_args
6880 def GetLastOriginalArg(self):
6881 """Gets the last original argument to this function."""
6882 return self.original_args[len(self.original_args) - 1]
6884 def __MaybePrependComma(self, arg_string, add_comma):
6885 """Adds a comma if arg_string is not empty and add_comma is true."""
6886 comma = ""
6887 if add_comma and len(arg_string):
6888 comma = ", "
6889 return "%s%s" % (comma, arg_string)
6891 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6892 """Gets a list of arguments as they are in GL."""
6893 args = self.GetOriginalArgs()
6894 arg_string = ", ".join(
6895 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6896 return self.__MaybePrependComma(arg_string, add_comma)
6898 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6899 """Gets the list of arguments as they are in GL."""
6900 args = self.GetOriginalArgs()
6901 arg_string = separator.join(
6902 ["%s%s" % (prefix, arg.name) for arg in args])
6903 return self.__MaybePrependComma(arg_string, add_comma)
6905 def MakeTypedHelperArgString(self, prefix, add_comma = False):
6906 """Gets a list of typed GL arguments after removing unneeded arguments."""
6907 args = self.GetOriginalArgs()
6908 arg_string = ", ".join(
6909 ["%s %s%s" % (
6910 arg.type,
6911 prefix,
6912 arg.name,
6913 ) for arg in args if not arg.IsConstant()])
6914 return self.__MaybePrependComma(arg_string, add_comma)
6916 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
6917 """Gets a list of GL arguments after removing unneeded arguments."""
6918 args = self.GetOriginalArgs()
6919 arg_string = separator.join(
6920 ["%s%s" % (prefix, arg.name)
6921 for arg in args if not arg.IsConstant()])
6922 return self.__MaybePrependComma(arg_string, add_comma)
6924 def MakeTypedPepperArgString(self, prefix):
6925 """Gets a list of arguments as they need to be for Pepper."""
6926 if self.GetInfo("pepper_args"):
6927 return self.GetInfo("pepper_args")
6928 else:
6929 return self.MakeTypedOriginalArgString(prefix, False)
6931 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
6932 """Converts a C type name to the corresponding Pepper IDL type."""
6933 idltype = {
6934 'char*': '[out] str_t',
6935 'const GLchar* const*': '[out] cstr_t',
6936 'const char*': 'cstr_t',
6937 'const void*': 'mem_t',
6938 'void*': '[out] mem_t',
6939 'void**': '[out] mem_ptr_t',
6940 }.get(ctype, ctype)
6941 # We use "GLxxx_ptr_t" for "GLxxx*".
6942 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
6943 if matched:
6944 idltype = matched.group(2) + '_ptr_t'
6945 if not matched.group(1):
6946 idltype = '[out] ' + idltype
6947 # If an in/out specifier is not specified yet, prepend [in].
6948 if idltype[0] != '[':
6949 idltype = '[in] ' + idltype
6950 # Strip the in/out specifier for a return type.
6951 if is_for_return_type:
6952 idltype = re.sub(r'\[\w+\] ', '', idltype)
6953 return idltype
6955 def MakeTypedPepperIdlArgStrings(self):
6956 """Gets a list of arguments as they need to be for Pepper IDL."""
6957 args = self.GetOriginalArgs()
6958 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
6959 for arg in args]
6961 def GetPepperName(self):
6962 if self.GetInfo("pepper_name"):
6963 return self.GetInfo("pepper_name")
6964 return self.name
6966 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6967 """Gets a typed list of arguments as they need to be for command buffers."""
6968 args = self.GetCmdArgs()
6969 arg_string = ", ".join(
6970 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6971 return self.__MaybePrependComma(arg_string, add_comma)
6973 def MakeCmdArgString(self, prefix, add_comma = False):
6974 """Gets the list of arguments as they need to be for command buffers."""
6975 args = self.GetCmdArgs()
6976 arg_string = ", ".join(
6977 ["%s%s" % (prefix, arg.name) for arg in args])
6978 return self.__MaybePrependComma(arg_string, add_comma)
6980 def MakeTypedInitString(self, prefix, add_comma = False):
6981 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6982 args = self.GetInitArgs()
6983 arg_string = ", ".join(
6984 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6985 return self.__MaybePrependComma(arg_string, add_comma)
6987 def MakeInitString(self, prefix, add_comma = False):
6988 """Gets the list of arguments as they need to be for cmd Init/Set."""
6989 args = self.GetInitArgs()
6990 arg_string = ", ".join(
6991 ["%s%s" % (prefix, arg.name) for arg in args])
6992 return self.__MaybePrependComma(arg_string, add_comma)
6994 def MakeLogArgString(self):
6995 """Makes a string of the arguments for the LOG macros"""
6996 args = self.GetOriginalArgs()
6997 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6999 def WriteCommandDescription(self, file):
7000 """Writes a description of the command."""
7001 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
7003 def WriteHandlerValidation(self, file):
7004 """Writes validation code for the function."""
7005 for arg in self.GetOriginalArgs():
7006 arg.WriteValidationCode(file, self)
7007 self.WriteValidationCode(file)
7009 def WriteHandlerImplementation(self, file):
7010 """Writes the handler implementation for this command."""
7011 self.type_handler.WriteHandlerImplementation(self, file)
7013 def WriteValidationCode(self, file):
7014 """Writes the validation code for a command."""
7015 pass
7017 def WriteCmdFlag(self, file):
7018 """Writes the cmd cmd_flags constant."""
7019 flags = []
7020 # By default trace only at the highest level 3.
7021 trace_level = int(self.GetInfo('trace_level', default = 3))
7022 if trace_level not in xrange(0, 4):
7023 raise KeyError("Unhandled trace_level: %d" % trace_level)
7025 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
7027 if len(flags) > 0:
7028 cmd_flags = ' | '.join(flags)
7029 else:
7030 cmd_flags = 0
7032 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
7035 def WriteCmdArgFlag(self, file):
7036 """Writes the cmd kArgFlags constant."""
7037 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
7039 def WriteCmdComputeSize(self, file):
7040 """Writes the ComputeSize function for the command."""
7041 file.Write(" static uint32_t ComputeSize() {\n")
7042 file.Write(
7043 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
7044 file.Write(" }\n")
7045 file.Write("\n")
7047 def WriteCmdSetHeader(self, file):
7048 """Writes the cmd's SetHeader function."""
7049 file.Write(" void SetHeader() {\n")
7050 file.Write(" header.SetCmd<ValueType>();\n")
7051 file.Write(" }\n")
7052 file.Write("\n")
7054 def WriteCmdInit(self, file):
7055 """Writes the cmd's Init function."""
7056 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
7057 file.Write(" SetHeader();\n")
7058 args = self.GetCmdArgs()
7059 for arg in args:
7060 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7061 file.Write(" }\n")
7062 file.Write("\n")
7064 def WriteCmdSet(self, file):
7065 """Writes the cmd's Set function."""
7066 copy_args = self.MakeCmdArgString("_", False)
7067 file.Write(" void* Set(void* cmd%s) {\n" %
7068 self.MakeTypedCmdArgString("_", True))
7069 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
7070 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
7071 file.Write(" }\n")
7072 file.Write("\n")
7074 def WriteStruct(self, file):
7075 self.type_handler.WriteStruct(self, file)
7077 def WriteDocs(self, file):
7078 self.type_handler.WriteDocs(self, file)
7080 def WriteCmdHelper(self, file):
7081 """Writes the cmd's helper."""
7082 self.type_handler.WriteCmdHelper(self, file)
7084 def WriteServiceImplementation(self, file):
7085 """Writes the service implementation for a command."""
7086 self.type_handler.WriteServiceImplementation(self, file)
7088 def WriteServiceUnitTest(self, file, *extras):
7089 """Writes the service implementation for a command."""
7090 self.type_handler.WriteServiceUnitTest(self, file, *extras)
7092 def WriteGLES2CLibImplementation(self, file):
7093 """Writes the GLES2 C Lib Implemention."""
7094 self.type_handler.WriteGLES2CLibImplementation(self, file)
7096 def WriteGLES2InterfaceHeader(self, file):
7097 """Writes the GLES2 Interface declaration."""
7098 self.type_handler.WriteGLES2InterfaceHeader(self, file)
7100 def WriteGLES2InterfaceStub(self, file):
7101 """Writes the GLES2 Interface Stub declaration."""
7102 self.type_handler.WriteGLES2InterfaceStub(self, file)
7104 def WriteGLES2InterfaceStubImpl(self, file):
7105 """Writes the GLES2 Interface Stub declaration."""
7106 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
7108 def WriteGLES2ImplementationHeader(self, file):
7109 """Writes the GLES2 Implemention declaration."""
7110 self.type_handler.WriteGLES2ImplementationHeader(self, file)
7112 def WriteGLES2Implementation(self, file):
7113 """Writes the GLES2 Implemention definition."""
7114 self.type_handler.WriteGLES2Implementation(self, file)
7116 def WriteGLES2TraceImplementationHeader(self, file):
7117 """Writes the GLES2 Trace Implemention declaration."""
7118 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
7120 def WriteGLES2TraceImplementation(self, file):
7121 """Writes the GLES2 Trace Implemention definition."""
7122 self.type_handler.WriteGLES2TraceImplementation(self, file)
7124 def WriteGLES2Header(self, file):
7125 """Writes the GLES2 Implemention unit test."""
7126 self.type_handler.WriteGLES2Header(self, file)
7128 def WriteGLES2ImplementationUnitTest(self, file):
7129 """Writes the GLES2 Implemention unit test."""
7130 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
7132 def WriteDestinationInitalizationValidation(self, file):
7133 """Writes the client side destintion initialization validation."""
7134 self.type_handler.WriteDestinationInitalizationValidation(self, file)
7136 def WriteFormatTest(self, file):
7137 """Writes the cmd's format test."""
7138 self.type_handler.WriteFormatTest(self, file)
7141 class PepperInterface(object):
7142 """A class that represents a function."""
7144 def __init__(self, info):
7145 self.name = info["name"]
7146 self.dev = info["dev"]
7148 def GetName(self):
7149 return self.name
7151 def GetInterfaceName(self):
7152 upperint = ""
7153 dev = ""
7154 if self.name:
7155 upperint = "_" + self.name.upper()
7156 if self.dev:
7157 dev = "_DEV"
7158 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
7160 def GetInterfaceString(self):
7161 dev = ""
7162 if self.dev:
7163 dev = "(Dev)"
7164 return "PPB_OpenGLES2%s%s" % (self.name, dev)
7166 def GetStructName(self):
7167 dev = ""
7168 if self.dev:
7169 dev = "_Dev"
7170 return "PPB_OpenGLES2%s%s" % (self.name, dev)
7173 class ImmediateFunction(Function):
7174 """A class that represnets an immediate function command."""
7176 def __init__(self, func):
7177 Function.__init__(
7178 self,
7179 "%sImmediate" % func.name,
7180 func.info)
7182 def InitFunction(self):
7183 # Override args in original_args and args_for_cmds with immediate versions
7184 # of the args.
7186 new_original_args = []
7187 for arg in self.original_args:
7188 new_arg = arg.GetImmediateVersion()
7189 if new_arg:
7190 new_original_args.append(new_arg)
7191 self.original_args = new_original_args
7193 new_args_for_cmds = []
7194 for arg in self.args_for_cmds:
7195 new_arg = arg.GetImmediateVersion()
7196 if new_arg:
7197 new_args_for_cmds.append(new_arg)
7199 self.args_for_cmds = new_args_for_cmds
7201 Function.InitFunction(self)
7203 def IsImmediate(self):
7204 return True
7206 def WriteCommandDescription(self, file):
7207 """Overridden from Function"""
7208 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
7209 self.original_name)
7211 def WriteServiceImplementation(self, file):
7212 """Overridden from Function"""
7213 self.type_handler.WriteImmediateServiceImplementation(self, file)
7215 def WriteHandlerImplementation(self, file):
7216 """Overridden from Function"""
7217 self.type_handler.WriteImmediateHandlerImplementation(self, file)
7219 def WriteServiceUnitTest(self, file, *extras):
7220 """Writes the service implementation for a command."""
7221 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
7223 def WriteValidationCode(self, file):
7224 """Overridden from Function"""
7225 self.type_handler.WriteImmediateValidationCode(self, file)
7227 def WriteCmdArgFlag(self, file):
7228 """Overridden from Function"""
7229 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
7231 def WriteCmdComputeSize(self, file):
7232 """Overridden from Function"""
7233 self.type_handler.WriteImmediateCmdComputeSize(self, file)
7235 def WriteCmdSetHeader(self, file):
7236 """Overridden from Function"""
7237 self.type_handler.WriteImmediateCmdSetHeader(self, file)
7239 def WriteCmdInit(self, file):
7240 """Overridden from Function"""
7241 self.type_handler.WriteImmediateCmdInit(self, file)
7243 def WriteCmdSet(self, file):
7244 """Overridden from Function"""
7245 self.type_handler.WriteImmediateCmdSet(self, file)
7247 def WriteCmdHelper(self, file):
7248 """Overridden from Function"""
7249 self.type_handler.WriteImmediateCmdHelper(self, file)
7251 def WriteFormatTest(self, file):
7252 """Overridden from Function"""
7253 self.type_handler.WriteImmediateFormatTest(self, file)
7256 class BucketFunction(Function):
7257 """A class that represnets a bucket version of a function command."""
7259 def __init__(self, func):
7260 Function.__init__(
7261 self,
7262 "%sBucket" % func.name,
7263 func.info)
7265 def InitFunction(self):
7266 # Override args in original_args and args_for_cmds with bucket versions
7267 # of the args.
7269 new_original_args = []
7270 for arg in self.original_args:
7271 new_arg = arg.GetBucketVersion()
7272 if new_arg:
7273 new_original_args.append(new_arg)
7274 self.original_args = new_original_args
7276 new_args_for_cmds = []
7277 for arg in self.args_for_cmds:
7278 new_arg = arg.GetBucketVersion()
7279 if new_arg:
7280 new_args_for_cmds.append(new_arg)
7282 self.args_for_cmds = new_args_for_cmds
7284 Function.InitFunction(self)
7286 def WriteCommandDescription(self, file):
7287 """Overridden from Function"""
7288 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
7289 self.original_name)
7291 def WriteServiceImplementation(self, file):
7292 """Overridden from Function"""
7293 self.type_handler.WriteBucketServiceImplementation(self, file)
7295 def WriteHandlerImplementation(self, file):
7296 """Overridden from Function"""
7297 self.type_handler.WriteBucketHandlerImplementation(self, file)
7299 def WriteServiceUnitTest(self, file, *extras):
7300 """Writes the service implementation for a command."""
7301 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
7304 def CreateArg(arg_string):
7305 """Creates an Argument."""
7306 arg_parts = arg_string.split()
7307 if len(arg_parts) == 1 and arg_parts[0] == 'void':
7308 return None
7309 # Is this a pointer argument?
7310 elif arg_string.find('*') >= 0:
7311 return PointerArgument(
7312 arg_parts[-1],
7313 " ".join(arg_parts[0:-1]))
7314 # Is this a resource argument? Must come after pointer check.
7315 elif arg_parts[0].startswith('GLidBind'):
7316 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7317 elif arg_parts[0].startswith('GLidZero'):
7318 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7319 elif arg_parts[0].startswith('GLid'):
7320 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7321 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
7322 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7323 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
7324 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7325 elif arg_parts[0].startswith('GLboolean'):
7326 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7327 elif arg_parts[0].startswith('GLintUniformLocation'):
7328 return UniformLocationArgument(arg_parts[-1])
7329 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
7330 not arg_parts[0].startswith('GLintptr')):
7331 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7332 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
7333 arg_parts[0].startswith('GLintptrNotNegative')):
7334 return SizeNotNegativeArgument(arg_parts[-1],
7335 " ".join(arg_parts[0:-1]),
7336 arg_parts[0][0:-11])
7337 elif arg_parts[0].startswith('GLsize'):
7338 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7339 else:
7340 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7343 class GLGenerator(object):
7344 """A class to generate GL command buffers."""
7346 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
7348 def __init__(self, verbose):
7349 self.original_functions = []
7350 self.functions = []
7351 self.verbose = verbose
7352 self.errors = 0
7353 self.pepper_interfaces = []
7354 self.interface_info = {}
7355 self.generated_cpp_filenames = []
7357 for interface in _PEPPER_INTERFACES:
7358 interface = PepperInterface(interface)
7359 self.pepper_interfaces.append(interface)
7360 self.interface_info[interface.GetName()] = interface
7362 def AddFunction(self, func):
7363 """Adds a function."""
7364 self.functions.append(func)
7366 def GetFunctionInfo(self, name):
7367 """Gets a type info for the given function name."""
7368 if name in _FUNCTION_INFO:
7369 func_info = _FUNCTION_INFO[name].copy()
7370 else:
7371 func_info = {}
7373 if not 'type' in func_info:
7374 func_info['type'] = ''
7376 return func_info
7378 def Log(self, msg):
7379 """Prints something if verbose is true."""
7380 if self.verbose:
7381 print msg
7383 def Error(self, msg):
7384 """Prints an error."""
7385 print "Error: %s" % msg
7386 self.errors += 1
7388 def WriteLicense(self, file):
7389 """Writes the license."""
7390 file.Write(_LICENSE)
7392 def WriteNamespaceOpen(self, file):
7393 """Writes the code for the namespace."""
7394 file.Write("namespace gpu {\n")
7395 file.Write("namespace gles2 {\n")
7396 file.Write("\n")
7398 def WriteNamespaceClose(self, file):
7399 """Writes the code to close the namespace."""
7400 file.Write("} // namespace gles2\n")
7401 file.Write("} // namespace gpu\n")
7402 file.Write("\n")
7404 def ParseGLH(self, filename):
7405 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
7406 f = open(filename, "r")
7407 functions = f.read()
7408 f.close()
7409 for line in functions.splitlines():
7410 match = self._function_re.match(line)
7411 if match:
7412 func_name = match.group(2)[2:]
7413 func_info = self.GetFunctionInfo(func_name)
7414 if func_info['type'] == 'Noop':
7415 continue
7417 parsed_func_info = {
7418 'original_name': func_name,
7419 'original_args': match.group(3),
7420 'return_type': match.group(1).strip(),
7423 for k in parsed_func_info.keys():
7424 if not k in func_info:
7425 func_info[k] = parsed_func_info[k]
7427 f = Function(func_name, func_info)
7428 self.original_functions.append(f)
7430 #for arg in f.GetOriginalArgs():
7431 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
7432 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
7434 gen_cmd = f.GetInfo('gen_cmd')
7435 if gen_cmd == True or gen_cmd == None:
7436 if f.type_handler.NeedsDataTransferFunction(f):
7437 methods = f.GetDataTransferMethods()
7438 if 'immediate' in methods:
7439 self.AddFunction(ImmediateFunction(f))
7440 if 'bucket' in methods:
7441 self.AddFunction(BucketFunction(f))
7442 if 'shm' in methods:
7443 self.AddFunction(f)
7444 else:
7445 self.AddFunction(f)
7447 self.Log("Auto Generated Functions : %d" %
7448 len([f for f in self.functions if f.can_auto_generate or
7449 (not f.IsType('') and not f.IsType('Custom') and
7450 not f.IsType('Todo'))]))
7452 funcs = [f for f in self.functions if not f.can_auto_generate and
7453 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
7454 self.Log("Non Auto Generated Functions: %d" % len(funcs))
7456 for f in funcs:
7457 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
7459 def WriteCommandIds(self, filename):
7460 """Writes the command buffer format"""
7461 file = CHeaderWriter(filename)
7462 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7463 id = 256
7464 for func in self.functions:
7465 file.Write(" %-60s /* %d */ \\\n" %
7466 ("OP(%s)" % func.name, id))
7467 id += 1
7468 file.Write("\n")
7470 file.Write("enum CommandId {\n")
7471 file.Write(" kStartPoint = cmd::kLastCommonId, "
7472 "// All GLES2 commands start after this.\n")
7473 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7474 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7475 file.Write("#undef GLES2_CMD_OP\n")
7476 file.Write(" kNumCommands\n")
7477 file.Write("};\n")
7478 file.Write("\n")
7479 file.Close()
7480 self.generated_cpp_filenames.append(file.filename)
7482 def WriteFormat(self, filename):
7483 """Writes the command buffer format"""
7484 file = CHeaderWriter(filename)
7485 for func in self.functions:
7486 if True:
7487 #gen_cmd = func.GetInfo('gen_cmd')
7488 #if gen_cmd == True or gen_cmd == None:
7489 func.WriteStruct(file)
7490 file.Write("\n")
7491 file.Close()
7492 self.generated_cpp_filenames.append(file.filename)
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()
7504 self.generated_cpp_filenames.append(file.filename)
7506 def WriteFormatTest(self, filename):
7507 """Writes the command buffer format test."""
7508 file = CHeaderWriter(
7509 filename,
7510 "// This file contains unit tests for gles2 commmands\n"
7511 "// It is included by gles2_cmd_format_test.cc\n"
7512 "\n")
7514 for func in self.functions:
7515 if True:
7516 #gen_cmd = func.GetInfo('gen_cmd')
7517 #if gen_cmd == True or gen_cmd == None:
7518 func.WriteFormatTest(file)
7520 file.Close()
7521 self.generated_cpp_filenames.append(file.filename)
7523 def WriteCmdHelperHeader(self, filename):
7524 """Writes the gles2 command helper."""
7525 file = CHeaderWriter(filename)
7527 for func in self.functions:
7528 if True:
7529 #gen_cmd = func.GetInfo('gen_cmd')
7530 #if gen_cmd == True or gen_cmd == None:
7531 func.WriteCmdHelper(file)
7533 file.Close()
7534 self.generated_cpp_filenames.append(file.filename)
7536 def WriteServiceContextStateHeader(self, filename):
7537 """Writes the service context state header."""
7538 file = CHeaderWriter(
7539 filename,
7540 "// It is included by context_state.h\n")
7541 file.Write("struct EnableFlags {\n")
7542 file.Write(" EnableFlags();\n")
7543 for capability in _CAPABILITY_FLAGS:
7544 file.Write(" bool %s;\n" % capability['name'])
7545 file.Write(" bool cached_%s;\n" % capability['name'])
7546 file.Write("};\n\n")
7548 for state_name in sorted(_STATES.keys()):
7549 state = _STATES[state_name]
7550 for item in state['states']:
7551 if isinstance(item['default'], list):
7552 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
7553 len(item['default'])))
7554 else:
7555 file.Write("%s %s;\n" % (item['type'], item['name']))
7557 if item.get('cached', False):
7558 if isinstance(item['default'], list):
7559 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
7560 len(item['default'])))
7561 else:
7562 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
7564 file.Write("\n")
7566 file.Write("""
7567 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
7568 switch (cap) {
7569 """)
7570 for capability in _CAPABILITY_FLAGS:
7571 file.Write("""\
7572 case GL_%s:
7573 """ % capability['name'].upper())
7574 file.Write("""\
7575 if (enable_flags.cached_%(name)s == enable &&
7576 !ignore_cached_state)
7577 return;
7578 enable_flags.cached_%(name)s = enable;
7579 break;
7580 """ % capability)
7582 file.Write("""\
7583 default:
7584 NOTREACHED();
7585 return;
7587 if (enable)
7588 glEnable(cap);
7589 else
7590 glDisable(cap);
7592 """)
7594 file.Close()
7595 self.generated_cpp_filenames.append(file.filename)
7597 def WriteClientContextStateHeader(self, filename):
7598 """Writes the client context state header."""
7599 file = CHeaderWriter(
7600 filename,
7601 "// It is included by client_context_state.h\n")
7602 file.Write("struct EnableFlags {\n")
7603 file.Write(" EnableFlags();\n")
7604 for capability in _CAPABILITY_FLAGS:
7605 file.Write(" bool %s;\n" % capability['name'])
7606 file.Write("};\n\n")
7608 file.Close()
7609 self.generated_cpp_filenames.append(file.filename)
7611 def WriteContextStateGetters(self, file, class_name):
7612 """Writes the state getters."""
7613 for gl_type in ["GLint", "GLfloat"]:
7614 file.Write("""
7615 bool %s::GetStateAs%s(
7616 GLenum pname, %s* params, GLsizei* num_written) const {
7617 switch (pname) {
7618 """ % (class_name, gl_type, gl_type))
7619 for state_name in sorted(_STATES.keys()):
7620 state = _STATES[state_name]
7621 if 'enum' in state:
7622 file.Write(" case %s:\n" % state['enum'])
7623 file.Write(" *num_written = %d;\n" % len(state['states']))
7624 file.Write(" if (params) {\n")
7625 for ndx,item in enumerate(state['states']):
7626 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7627 (ndx, gl_type, item['name']))
7628 file.Write(" }\n")
7629 file.Write(" return true;\n")
7630 else:
7631 for item in state['states']:
7632 file.Write(" case %s:\n" % item['enum'])
7633 if isinstance(item['default'], list):
7634 item_len = len(item['default'])
7635 file.Write(" *num_written = %d;\n" % item_len)
7636 file.Write(" if (params) {\n")
7637 if item['type'] == gl_type:
7638 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
7639 (item['name'], item['type'], item_len))
7640 else:
7641 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
7642 item_len)
7643 file.Write(" params[i] = %s;\n" %
7644 (GetGLGetTypeConversion(gl_type, item['type'],
7645 "%s[i]" % item['name'])))
7646 file.Write(" }\n");
7647 else:
7648 file.Write(" *num_written = 1;\n")
7649 file.Write(" if (params) {\n")
7650 file.Write(" params[0] = %s;\n" %
7651 (GetGLGetTypeConversion(gl_type, item['type'],
7652 item['name'])))
7653 file.Write(" }\n")
7654 file.Write(" return true;\n")
7655 for capability in _CAPABILITY_FLAGS:
7656 file.Write(" case GL_%s:\n" % capability['name'].upper())
7657 file.Write(" *num_written = 1;\n")
7658 file.Write(" if (params) {\n")
7659 file.Write(
7660 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7661 (gl_type, capability['name']))
7662 file.Write(" }\n")
7663 file.Write(" return true;\n")
7664 file.Write(""" default:
7665 return false;
7668 """)
7670 def WriteServiceContextStateImpl(self, filename):
7671 """Writes the context state service implementation."""
7672 file = CHeaderWriter(
7673 filename,
7674 "// It is included by context_state.cc\n")
7675 code = []
7676 for capability in _CAPABILITY_FLAGS:
7677 code.append("%s(%s)" %
7678 (capability['name'],
7679 ('false', 'true')['default' in capability]))
7680 code.append("cached_%s(%s)" %
7681 (capability['name'],
7682 ('false', 'true')['default' in capability]))
7683 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7684 ",\n ".join(code))
7685 file.Write("\n")
7687 file.Write("void ContextState::Initialize() {\n")
7688 for state_name in sorted(_STATES.keys()):
7689 state = _STATES[state_name]
7690 for item in state['states']:
7691 if isinstance(item['default'], list):
7692 for ndx, value in enumerate(item['default']):
7693 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
7694 else:
7695 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7696 if item.get('cached', False):
7697 if isinstance(item['default'], list):
7698 for ndx, value in enumerate(item['default']):
7699 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
7700 else:
7701 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
7702 file.Write("}\n")
7704 file.Write("""
7705 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7706 """)
7707 def WriteCapabilities(test_prev):
7708 for capability in _CAPABILITY_FLAGS:
7709 capability_name = capability['name']
7710 if test_prev:
7711 file.Write(""" if (prev_state->enable_flags.cached_%s !=
7712 enable_flags.cached_%s)\n""" %
7713 (capability_name, capability_name))
7714 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
7715 (capability_name.upper(), capability_name))
7717 file.Write(" if (prev_state) {")
7718 WriteCapabilities(True)
7719 file.Write(" } else {")
7720 WriteCapabilities(False)
7721 file.Write(" }")
7723 file.Write("""}
7725 void ContextState::InitState(const ContextState *prev_state) const {
7726 """)
7728 def WriteStates(test_prev):
7729 # We need to sort the keys so the expectations match
7730 for state_name in sorted(_STATES.keys()):
7731 state = _STATES[state_name]
7732 if state['type'] == 'FrontBack':
7733 num_states = len(state['states'])
7734 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7735 if test_prev:
7736 file.Write(" if (")
7737 args = []
7738 for place, item in enumerate(group):
7739 item_name = CachedStateName(item)
7740 args.append('%s' % item_name)
7741 if test_prev:
7742 if place > 0:
7743 file.Write(' ||\n')
7744 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
7745 if test_prev:
7746 file.Write(")\n")
7747 file.Write(
7748 " gl%s(%s, %s);\n" %
7749 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7750 elif state['type'] == 'NamedParameter':
7751 for item in state['states']:
7752 item_name = CachedStateName(item)
7754 if 'extension_flag' in item:
7755 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
7756 item['extension_flag'])
7757 if test_prev:
7758 if isinstance(item['default'], list):
7759 file.Write(" if (memcmp(prev_state->%s, %s, "
7760 "sizeof(%s) * %d)) {\n" %
7761 (item_name, item_name, item['type'],
7762 len(item['default'])))
7763 else:
7764 file.Write(" if (prev_state->%s != %s) {\n " %
7765 (item_name, item_name))
7766 file.Write(" gl%s(%s, %s);\n" %
7767 (state['func'],
7768 (item['enum_set']
7769 if 'enum_set' in item else item['enum']),
7770 item['name']))
7771 if test_prev:
7772 if 'extension_flag' in item:
7773 file.Write(" ")
7774 file.Write(" }")
7775 if 'extension_flag' in item:
7776 file.Write(" }")
7777 else:
7778 if 'extension_flag' in state:
7779 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7780 state['extension_flag'])
7781 if test_prev:
7782 file.Write(" if (")
7783 args = []
7784 for place, item in enumerate(state['states']):
7785 item_name = CachedStateName(item)
7786 args.append('%s' % item_name)
7787 if test_prev:
7788 if place > 0:
7789 file.Write(' ||\n')
7790 file.Write("(%s != prev_state->%s)" %
7791 (item_name, item_name))
7792 if test_prev:
7793 file.Write(" )\n")
7794 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7796 file.Write(" if (prev_state) {")
7797 WriteStates(True)
7798 file.Write(" } else {")
7799 WriteStates(False)
7800 file.Write(" }")
7801 file.Write("}\n")
7803 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7804 switch (cap) {
7805 """)
7806 for capability in _CAPABILITY_FLAGS:
7807 file.Write(" case GL_%s:\n" % capability['name'].upper())
7808 file.Write(" return enable_flags.%s;\n" % capability['name'])
7809 file.Write(""" default:
7810 NOTREACHED();
7811 return false;
7814 """)
7816 self.WriteContextStateGetters(file, "ContextState")
7817 file.Close()
7818 self.generated_cpp_filenames.append(file.filename)
7820 def WriteClientContextStateImpl(self, filename):
7821 """Writes the context state client side implementation."""
7822 file = CHeaderWriter(
7823 filename,
7824 "// It is included by client_context_state.cc\n")
7825 code = []
7826 for capability in _CAPABILITY_FLAGS:
7827 code.append("%s(%s)" %
7828 (capability['name'],
7829 ('false', 'true')['default' in capability]))
7830 file.Write(
7831 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7832 ",\n ".join(code))
7833 file.Write("\n")
7835 file.Write("""
7836 bool ClientContextState::SetCapabilityState(
7837 GLenum cap, bool enabled, bool* changed) {
7838 *changed = false;
7839 switch (cap) {
7840 """)
7841 for capability in _CAPABILITY_FLAGS:
7842 file.Write(" case GL_%s:\n" % capability['name'].upper())
7843 file.Write(""" if (enable_flags.%(name)s != enabled) {
7844 *changed = true;
7845 enable_flags.%(name)s = enabled;
7847 return true;
7848 """ % capability)
7849 file.Write(""" default:
7850 return false;
7853 """)
7854 file.Write("""bool ClientContextState::GetEnabled(
7855 GLenum cap, bool* enabled) const {
7856 switch (cap) {
7857 """)
7858 for capability in _CAPABILITY_FLAGS:
7859 file.Write(" case GL_%s:\n" % capability['name'].upper())
7860 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7861 file.Write(" return true;\n")
7862 file.Write(""" default:
7863 return false;
7866 """)
7867 file.Close()
7868 self.generated_cpp_filenames.append(file.filename)
7870 def WriteServiceImplementation(self, filename):
7871 """Writes the service decorder implementation."""
7872 file = CHeaderWriter(
7873 filename,
7874 "// It is included by gles2_cmd_decoder.cc\n")
7876 for func in self.functions:
7877 if True:
7878 #gen_cmd = func.GetInfo('gen_cmd')
7879 #if gen_cmd == True or gen_cmd == None:
7880 func.WriteServiceImplementation(file)
7882 file.Write("""
7883 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7884 switch (cap) {
7885 """)
7886 for capability in _CAPABILITY_FLAGS:
7887 file.Write(" case GL_%s:\n" % capability['name'].upper())
7888 if 'state_flag' in capability:
7890 file.Write("""\
7891 state_.enable_flags.%(name)s = enabled;
7892 if (state_.enable_flags.cached_%(name)s != enabled
7893 || state_.ignore_cached_state) {
7894 %(state_flag)s = true;
7896 return false;
7897 """ % capability)
7898 else:
7899 file.Write("""\
7900 state_.enable_flags.%(name)s = enabled;
7901 if (state_.enable_flags.cached_%(name)s != enabled
7902 || state_.ignore_cached_state) {
7903 state_.enable_flags.cached_%(name)s = enabled;
7904 return true;
7906 return false;
7907 """ % capability)
7908 file.Write(""" default:
7909 NOTREACHED();
7910 return false;
7913 """)
7914 file.Close()
7915 self.generated_cpp_filenames.append(file.filename)
7917 def WriteServiceUnitTests(self, filename):
7918 """Writes the service decorder unit tests."""
7919 num_tests = len(self.functions)
7920 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7921 count = 0
7922 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7923 count += 1
7924 name = filename % count
7925 file = CHeaderWriter(
7926 name,
7927 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7928 test_name = 'GLES2DecoderTest%d' % count
7929 end = test_num + FUNCTIONS_PER_FILE
7930 if end > num_tests:
7931 end = num_tests
7932 for idx in range(test_num, end):
7933 func = self.functions[idx]
7935 # Do any filtering of the functions here, so that the functions
7936 # will not move between the numbered files if filtering properties
7937 # are changed.
7938 if func.GetInfo('extension_flag'):
7939 continue
7941 if True:
7942 #gen_cmd = func.GetInfo('gen_cmd')
7943 #if gen_cmd == True or gen_cmd == None:
7944 if func.GetInfo('unit_test') == False:
7945 file.Write("// TODO(gman): %s\n" % func.name)
7946 else:
7947 func.WriteServiceUnitTest(file, {
7948 'test_name': test_name
7950 file.Close()
7951 self.generated_cpp_filenames.append(file.filename)
7952 file = CHeaderWriter(
7953 filename % 0,
7954 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7955 file.Write(
7956 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7957 """)
7958 for capability in _CAPABILITY_FLAGS:
7959 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7960 (capability['name'].upper(),
7961 ('false', 'true')['default' in capability]))
7962 file.Write("""}
7964 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7965 """)
7967 # We need to sort the keys so the expectations match
7968 for state_name in sorted(_STATES.keys()):
7969 state = _STATES[state_name]
7970 if state['type'] == 'FrontBack':
7971 num_states = len(state['states'])
7972 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7973 args = []
7974 for item in group:
7975 if 'expected' in item:
7976 args.append(item['expected'])
7977 else:
7978 args.append(item['default'])
7979 file.Write(
7980 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7981 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7982 file.Write(" .Times(1)\n")
7983 file.Write(" .RetiresOnSaturation();\n")
7984 elif state['type'] == 'NamedParameter':
7985 for item in state['states']:
7986 if 'extension_flag' in item:
7987 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
7988 item['extension_flag'])
7989 file.Write(" ")
7990 expect_value = item['default']
7991 if isinstance(expect_value, list):
7992 # TODO: Currently we do not check array values.
7993 expect_value = "_"
7995 file.Write(
7996 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7997 (state['func'],
7998 (item['enum_set']
7999 if 'enum_set' in item else item['enum']),
8000 expect_value))
8001 file.Write(" .Times(1)\n")
8002 file.Write(" .RetiresOnSaturation();\n")
8003 if 'extension_flag' in item:
8004 file.Write(" }\n")
8005 else:
8006 if 'extension_flag' in state:
8007 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
8008 state['extension_flag'])
8009 file.Write(" ")
8010 args = []
8011 for item in state['states']:
8012 if 'expected' in item:
8013 args.append(item['expected'])
8014 else:
8015 args.append(item['default'])
8016 # TODO: Currently we do not check array values.
8017 args = ["_" if isinstance(arg, list) else arg for arg in args]
8018 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
8019 (state['func'], ", ".join(args)))
8020 file.Write(" .Times(1)\n")
8021 file.Write(" .RetiresOnSaturation();\n")
8022 if 'extension_flag' in state:
8023 file.Write(" }\n")
8024 file.Write("""}
8025 """)
8026 file.Close()
8027 self.generated_cpp_filenames.append(file.filename)
8029 def WriteServiceUnitTestsForExtensions(self, filename):
8030 """Writes the service decorder unit tests for functions with extension_flag.
8032 The functions are special in that they need a specific unit test
8033 baseclass to turn on the extension.
8035 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
8036 file = CHeaderWriter(
8037 filename,
8038 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
8039 for func in functions:
8040 if True:
8041 if func.GetInfo('unit_test') == False:
8042 file.Write("// TODO(gman): %s\n" % func.name)
8043 else:
8044 extension = ToCamelCase(
8045 ToGLExtensionString(func.GetInfo('extension_flag')))
8046 func.WriteServiceUnitTest(file, {
8047 'test_name': 'GLES2DecoderTestWith%s' % extension
8050 file.Close()
8051 self.generated_cpp_filenames.append(file.filename)
8053 def WriteGLES2Header(self, filename):
8054 """Writes the GLES2 header."""
8055 file = CHeaderWriter(
8056 filename,
8057 "// This file contains Chromium-specific GLES2 declarations.\n\n")
8059 for func in self.original_functions:
8060 func.WriteGLES2Header(file)
8062 file.Write("\n")
8063 file.Close()
8064 self.generated_cpp_filenames.append(file.filename)
8066 def WriteGLES2CLibImplementation(self, filename):
8067 """Writes the GLES2 c lib implementation."""
8068 file = CHeaderWriter(
8069 filename,
8070 "// These functions emulate GLES2 over command buffers.\n")
8072 for func in self.original_functions:
8073 func.WriteGLES2CLibImplementation(file)
8075 file.Write("""
8076 namespace gles2 {
8078 extern const NameToFunc g_gles2_function_table[] = {
8079 """)
8080 for func in self.original_functions:
8081 file.Write(
8082 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
8083 (func.name, func.name))
8084 file.Write(""" { NULL, NULL, },
8087 } // namespace gles2
8088 """)
8089 file.Close()
8090 self.generated_cpp_filenames.append(file.filename)
8092 def WriteGLES2InterfaceHeader(self, filename):
8093 """Writes the GLES2 interface header."""
8094 file = CHeaderWriter(
8095 filename,
8096 "// This file is included by gles2_interface.h to declare the\n"
8097 "// GL api functions.\n")
8098 for func in self.original_functions:
8099 func.WriteGLES2InterfaceHeader(file)
8100 file.Close()
8101 self.generated_cpp_filenames.append(file.filename)
8103 def WriteGLES2InterfaceStub(self, filename):
8104 """Writes the GLES2 interface stub header."""
8105 file = CHeaderWriter(
8106 filename,
8107 "// This file is included by gles2_interface_stub.h.\n")
8108 for func in self.original_functions:
8109 func.WriteGLES2InterfaceStub(file)
8110 file.Close()
8111 self.generated_cpp_filenames.append(file.filename)
8113 def WriteGLES2InterfaceStubImpl(self, filename):
8114 """Writes the GLES2 interface header."""
8115 file = CHeaderWriter(
8116 filename,
8117 "// This file is included by gles2_interface_stub.cc.\n")
8118 for func in self.original_functions:
8119 func.WriteGLES2InterfaceStubImpl(file)
8120 file.Close()
8121 self.generated_cpp_filenames.append(file.filename)
8123 def WriteGLES2ImplementationHeader(self, filename):
8124 """Writes the GLES2 Implementation header."""
8125 file = CHeaderWriter(
8126 filename,
8127 "// This file is included by gles2_implementation.h to declare the\n"
8128 "// GL api functions.\n")
8129 for func in self.original_functions:
8130 func.WriteGLES2ImplementationHeader(file)
8131 file.Close()
8132 self.generated_cpp_filenames.append(file.filename)
8134 def WriteGLES2Implementation(self, filename):
8135 """Writes the GLES2 Implementation."""
8136 file = CHeaderWriter(
8137 filename,
8138 "// This file is included by gles2_implementation.cc to define the\n"
8139 "// GL api functions.\n")
8140 for func in self.original_functions:
8141 func.WriteGLES2Implementation(file)
8142 file.Close()
8143 self.generated_cpp_filenames.append(file.filename)
8145 def WriteGLES2TraceImplementationHeader(self, filename):
8146 """Writes the GLES2 Trace Implementation header."""
8147 file = CHeaderWriter(
8148 filename,
8149 "// This file is included by gles2_trace_implementation.h\n")
8150 for func in self.original_functions:
8151 func.WriteGLES2TraceImplementationHeader(file)
8152 file.Close()
8153 self.generated_cpp_filenames.append(file.filename)
8155 def WriteGLES2TraceImplementation(self, filename):
8156 """Writes the GLES2 Trace Implementation."""
8157 file = CHeaderWriter(
8158 filename,
8159 "// This file is included by gles2_trace_implementation.cc\n")
8160 for func in self.original_functions:
8161 func.WriteGLES2TraceImplementation(file)
8162 file.Close()
8163 self.generated_cpp_filenames.append(file.filename)
8165 def WriteGLES2ImplementationUnitTests(self, filename):
8166 """Writes the GLES2 helper header."""
8167 file = CHeaderWriter(
8168 filename,
8169 "// This file is included by gles2_implementation.h to declare the\n"
8170 "// GL api functions.\n")
8171 for func in self.original_functions:
8172 func.WriteGLES2ImplementationUnitTest(file)
8173 file.Close()
8174 self.generated_cpp_filenames.append(file.filename)
8176 def WriteServiceUtilsHeader(self, filename):
8177 """Writes the gles2 auto generated utility header."""
8178 file = CHeaderWriter(filename)
8179 for name in sorted(_NAMED_TYPE_INFO.keys()):
8180 named_type = NamedType(_NAMED_TYPE_INFO[name])
8181 if named_type.IsConstant():
8182 continue
8183 file.Write("ValueValidator<%s> %s;\n" %
8184 (named_type.GetType(), ToUnderscore(name)))
8185 file.Write("\n")
8186 file.Close()
8187 self.generated_cpp_filenames.append(file.filename)
8189 def WriteServiceUtilsImplementation(self, filename):
8190 """Writes the gles2 auto generated utility implementation."""
8191 file = CHeaderWriter(filename)
8192 names = sorted(_NAMED_TYPE_INFO.keys())
8193 for name in names:
8194 named_type = NamedType(_NAMED_TYPE_INFO[name])
8195 if named_type.IsConstant():
8196 continue
8197 if named_type.GetValidValues():
8198 file.Write("static const %s valid_%s_table[] = {\n" %
8199 (named_type.GetType(), ToUnderscore(name)))
8200 for value in named_type.GetValidValues():
8201 file.Write(" %s,\n" % value)
8202 file.Write("};\n")
8203 file.Write("\n")
8204 file.Write("Validators::Validators()")
8205 pre = ' : '
8206 for count, name in enumerate(names):
8207 named_type = NamedType(_NAMED_TYPE_INFO[name])
8208 if named_type.IsConstant():
8209 continue
8210 if named_type.GetValidValues():
8211 code = """%(pre)s%(name)s(
8212 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
8213 else:
8214 code = "%(pre)s%(name)s()"
8215 file.Write(code % {
8216 'name': ToUnderscore(name),
8217 'pre': pre,
8219 pre = ',\n '
8220 file.Write(" {\n");
8221 file.Write("}\n\n");
8222 file.Close()
8223 self.generated_cpp_filenames.append(file.filename)
8225 def WriteCommonUtilsHeader(self, filename):
8226 """Writes the gles2 common utility header."""
8227 file = CHeaderWriter(filename)
8228 type_infos = sorted(_NAMED_TYPE_INFO.keys())
8229 for type_info in type_infos:
8230 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
8231 file.Write("static std::string GetString%s(uint32_t value);\n" %
8232 type_info)
8233 file.Write("\n")
8234 file.Close()
8235 self.generated_cpp_filenames.append(file.filename)
8237 def WriteCommonUtilsImpl(self, filename):
8238 """Writes the gles2 common utility header."""
8239 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
8240 dict = {}
8241 for fname in ['third_party/khronos/GLES2/gl2.h',
8242 'third_party/khronos/GLES2/gl2ext.h',
8243 'gpu/GLES2/gl2chromium.h',
8244 'gpu/GLES2/gl2extchromium.h']:
8245 lines = open(fname).readlines()
8246 for line in lines:
8247 m = enum_re.match(line)
8248 if m:
8249 name = m.group(1)
8250 value = m.group(2)
8251 if len(value) <= 10 and not value in dict:
8252 dict[value] = name
8254 file = CHeaderWriter(filename)
8255 file.Write("static const GLES2Util::EnumToString "
8256 "enum_to_string_table[] = {\n")
8257 for value in dict:
8258 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
8259 file.Write("""};
8261 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
8262 enum_to_string_table;
8263 const size_t GLES2Util::enum_to_string_table_len_ =
8264 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
8266 """)
8268 enums = sorted(_NAMED_TYPE_INFO.keys())
8269 for enum in enums:
8270 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
8271 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
8272 enum)
8273 if len(_NAMED_TYPE_INFO[enum]['valid']) > 0:
8274 file.Write(" static const EnumToString string_table[] = {\n")
8275 for value in _NAMED_TYPE_INFO[enum]['valid']:
8276 file.Write(' { %s, "%s" },\n' % (value, value))
8277 file.Write(""" };
8278 return GLES2Util::GetQualifiedEnumString(
8279 string_table, arraysize(string_table), value);
8282 """)
8283 else:
8284 file.Write(""" return GLES2Util::GetQualifiedEnumString(
8285 NULL, 0, value);
8288 """)
8289 file.Close()
8290 self.generated_cpp_filenames.append(file.filename)
8292 def WritePepperGLES2Interface(self, filename, dev):
8293 """Writes the Pepper OpenGLES interface definition."""
8294 file = CWriter(filename)
8295 file.Write(_LICENSE)
8296 file.Write(_DO_NOT_EDIT_WARNING)
8298 file.Write("label Chrome {\n")
8299 file.Write(" M39 = 1.0\n")
8300 file.Write("};\n\n")
8302 if not dev:
8303 # Declare GL types.
8304 file.Write("[version=1.0]\n")
8305 file.Write("describe {\n")
8306 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
8307 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
8308 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
8309 'GLubyte', 'GLuint', 'GLushort']:
8310 file.Write(" %s;\n" % gltype)
8311 file.Write(" %s_ptr_t;\n" % gltype)
8312 file.Write("};\n\n")
8314 # C level typedefs.
8315 file.Write("#inline c\n")
8316 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
8317 if dev:
8318 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
8319 else:
8320 file.Write("\n#ifndef __gl2_h_\n")
8321 for (k, v) in _GL_TYPES.iteritems():
8322 file.Write("typedef %s %s;\n" % (v, k))
8323 file.Write("#ifdef _WIN64\n")
8324 for (k, v) in _GL_TYPES_64.iteritems():
8325 file.Write("typedef %s %s;\n" % (v, k))
8326 file.Write("#else\n")
8327 for (k, v) in _GL_TYPES_32.iteritems():
8328 file.Write("typedef %s %s;\n" % (v, k))
8329 file.Write("#endif // _WIN64\n")
8330 file.Write("#endif // __gl2_h_\n\n")
8331 file.Write("#endinl\n")
8333 for interface in self.pepper_interfaces:
8334 if interface.dev != dev:
8335 continue
8336 # Historically, we provide OpenGLES2 interfaces with struct
8337 # namespace. Not to break code which uses the interface as
8338 # "struct OpenGLES2", we put it in struct namespace.
8339 file.Write('\n[macro="%s", force_struct_namespace]\n' %
8340 interface.GetInterfaceName())
8341 file.Write("interface %s {\n" % interface.GetStructName())
8342 for func in self.original_functions:
8343 if not func.InPepperInterface(interface):
8344 continue
8346 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
8347 is_for_return_type=True)
8348 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
8349 file.Write(func_prefix)
8350 file.Write("[in] PP_Resource context")
8351 for arg in func.MakeTypedPepperIdlArgStrings():
8352 file.Write(",\n" + " " * len(func_prefix) + arg)
8353 file.Write(");\n")
8354 file.Write("};\n\n")
8357 file.Close()
8359 def WritePepperGLES2Implementation(self, filename):
8360 """Writes the Pepper OpenGLES interface implementation."""
8362 file = CWriter(filename)
8363 file.Write(_LICENSE)
8364 file.Write(_DO_NOT_EDIT_WARNING)
8366 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
8367 file.Write("#include \"base/logging.h\"\n")
8368 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
8369 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
8370 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
8372 file.Write("namespace ppapi {\n\n")
8373 file.Write("namespace {\n\n")
8375 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
8376 " Enter3D;\n\n")
8378 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
8379 " enter) {\n")
8380 file.Write(" DCHECK(enter);\n")
8381 file.Write(" DCHECK(enter->succeeded());\n")
8382 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
8383 "gles2_impl();\n");
8384 file.Write("}\n\n");
8386 for func in self.original_functions:
8387 if not func.InAnyPepperExtension():
8388 continue
8390 original_arg = func.MakeTypedPepperArgString("")
8391 context_arg = "PP_Resource context_id"
8392 if len(original_arg):
8393 arg = context_arg + ", " + original_arg
8394 else:
8395 arg = context_arg
8396 file.Write("%s %s(%s) {\n" %
8397 (func.return_type, func.GetPepperName(), arg))
8398 file.Write(" Enter3D enter(context_id, true);\n")
8399 file.Write(" if (enter.succeeded()) {\n")
8401 return_str = "" if func.return_type == "void" else "return "
8402 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
8403 (return_str, func.original_name,
8404 func.MakeOriginalArgString("")))
8405 file.Write(" }")
8406 if func.return_type == "void":
8407 file.Write("\n")
8408 else:
8409 file.Write(" else {\n")
8410 file.Write(" return %s;\n" % func.GetErrorReturnString())
8411 file.Write(" }\n")
8412 file.Write("}\n\n")
8414 file.Write("} // namespace\n")
8416 for interface in self.pepper_interfaces:
8417 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
8418 (interface.GetStructName(), interface.GetName()))
8419 file.Write(" static const struct %s "
8420 "ppb_opengles2 = {\n" % interface.GetStructName())
8421 file.Write(" &")
8422 file.Write(",\n &".join(
8423 f.GetPepperName() for f in self.original_functions
8424 if f.InPepperInterface(interface)))
8425 file.Write("\n")
8427 file.Write(" };\n")
8428 file.Write(" return &ppb_opengles2;\n")
8429 file.Write("}\n")
8431 file.Write("} // namespace ppapi\n")
8432 file.Close()
8433 self.generated_cpp_filenames.append(file.filename)
8435 def WriteGLES2ToPPAPIBridge(self, filename):
8436 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
8438 file = CWriter(filename)
8439 file.Write(_LICENSE)
8440 file.Write(_DO_NOT_EDIT_WARNING)
8442 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
8443 file.Write("#define GL_GLEXT_PROTOTYPES\n")
8444 file.Write("#endif\n")
8445 file.Write("#include <GLES2/gl2.h>\n")
8446 file.Write("#include <GLES2/gl2ext.h>\n")
8447 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
8449 for func in self.original_functions:
8450 if not func.InAnyPepperExtension():
8451 continue
8453 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
8455 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
8456 (func.return_type, func.GetPepperName(),
8457 func.MakeTypedPepperArgString("")))
8458 return_str = "" if func.return_type == "void" else "return "
8459 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
8460 original_arg = func.MakeOriginalArgString("")
8461 context_arg = "glGetCurrentContextPPAPI()"
8462 if len(original_arg):
8463 arg = context_arg + ", " + original_arg
8464 else:
8465 arg = context_arg
8466 if interface.GetName():
8467 file.Write(" const struct %s* ext = %s;\n" %
8468 (interface.GetStructName(), interface_str))
8469 file.Write(" if (ext)\n")
8470 file.Write(" %sext->%s(%s);\n" %
8471 (return_str, func.GetPepperName(), arg))
8472 if return_str:
8473 file.Write(" %s0;\n" % return_str)
8474 else:
8475 file.Write(" %s%s->%s(%s);\n" %
8476 (return_str, interface_str, func.GetPepperName(), arg))
8477 file.Write("}\n\n")
8478 file.Close()
8479 self.generated_cpp_filenames.append(file.filename)
8481 def WriteMojoGLCallVisitor(self, filename):
8482 """Provides the GL implementation for mojo"""
8483 file = CWriter(filename)
8484 file.Write(_LICENSE)
8485 file.Write(_DO_NOT_EDIT_WARNING)
8487 for func in self.original_functions:
8488 if not func.IsCoreGLFunction():
8489 continue
8490 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8491 (func.name, func.return_type,
8492 func.MakeTypedOriginalArgString(""),
8493 func.MakeOriginalArgString("")))
8495 file.Close()
8496 self.generated_cpp_filenames.append(file.filename)
8498 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
8499 """Provides the GL implementation for mojo for a particular extension"""
8500 file = CWriter(filename)
8501 file.Write(_LICENSE)
8502 file.Write(_DO_NOT_EDIT_WARNING)
8504 for func in self.original_functions:
8505 if func.GetInfo("extension") != extension:
8506 continue
8507 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8508 (func.name, func.return_type,
8509 func.MakeTypedOriginalArgString(""),
8510 func.MakeOriginalArgString("")))
8512 file.Close()
8513 self.generated_cpp_filenames.append(file.filename)
8515 def Format(generated_files):
8516 for filename in generated_files:
8517 call(["clang-format", "-i", "-style=chromium", filename])
8519 def main(argv):
8520 """This is the main function."""
8521 parser = OptionParser()
8522 parser.add_option(
8523 "--output-dir",
8524 help="base directory for resulting files, under chrome/src. default is "
8525 "empty. Use this if you want the result stored under gen.")
8526 parser.add_option(
8527 "-v", "--verbose", action="store_true",
8528 help="prints more output.")
8530 (options, args) = parser.parse_args(args=argv)
8532 # Add in states and capabilites to GLState
8533 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
8534 for state_name in sorted(_STATES.keys()):
8535 state = _STATES[state_name]
8536 if 'extension_flag' in state:
8537 continue
8538 if 'enum' in state:
8539 if not state['enum'] in gl_state_valid:
8540 gl_state_valid.append(state['enum'])
8541 else:
8542 for item in state['states']:
8543 if 'extension_flag' in item:
8544 continue
8545 if not item['enum'] in gl_state_valid:
8546 gl_state_valid.append(item['enum'])
8547 for capability in _CAPABILITY_FLAGS:
8548 valid_value = "GL_%s" % capability['name'].upper()
8549 if not valid_value in gl_state_valid:
8550 gl_state_valid.append(valid_value)
8552 # This script lives under gpu/command_buffer, cd to base directory.
8553 os.chdir(os.path.dirname(__file__) + "/../..")
8554 base_dir = os.getcwd()
8555 gen = GLGenerator(options.verbose)
8556 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
8558 # Support generating files under gen/
8559 if options.output_dir != None:
8560 os.chdir(options.output_dir)
8562 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
8563 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
8564 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
8565 gen.WritePepperGLES2Implementation(
8566 "ppapi/shared_impl/ppb_opengles2_shared.cc")
8567 os.chdir(base_dir)
8568 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
8569 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
8570 gen.WriteFormatTest(
8571 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
8572 gen.WriteGLES2InterfaceHeader(
8573 "gpu/command_buffer/client/gles2_interface_autogen.h")
8574 gen.WriteGLES2InterfaceStub(
8575 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
8576 gen.WriteGLES2InterfaceStubImpl(
8577 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
8578 gen.WriteGLES2ImplementationHeader(
8579 "gpu/command_buffer/client/gles2_implementation_autogen.h")
8580 gen.WriteGLES2Implementation(
8581 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
8582 gen.WriteGLES2ImplementationUnitTests(
8583 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
8584 gen.WriteGLES2TraceImplementationHeader(
8585 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
8586 gen.WriteGLES2TraceImplementation(
8587 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
8588 gen.WriteGLES2CLibImplementation(
8589 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
8590 gen.WriteCmdHelperHeader(
8591 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
8592 gen.WriteServiceImplementation(
8593 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
8594 gen.WriteServiceContextStateHeader(
8595 "gpu/command_buffer/service/context_state_autogen.h")
8596 gen.WriteServiceContextStateImpl(
8597 "gpu/command_buffer/service/context_state_impl_autogen.h")
8598 gen.WriteClientContextStateHeader(
8599 "gpu/command_buffer/client/client_context_state_autogen.h")
8600 gen.WriteClientContextStateImpl(
8601 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
8602 gen.WriteServiceUnitTests(
8603 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
8604 gen.WriteServiceUnitTestsForExtensions(
8605 "gpu/command_buffer/service/"
8606 "gles2_cmd_decoder_unittest_extensions_autogen.h")
8607 gen.WriteServiceUtilsHeader(
8608 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
8609 gen.WriteServiceUtilsImplementation(
8610 "gpu/command_buffer/service/"
8611 "gles2_cmd_validation_implementation_autogen.h")
8612 gen.WriteCommonUtilsHeader(
8613 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
8614 gen.WriteCommonUtilsImpl(
8615 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
8616 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
8617 mojo_gles2_prefix = "mojo/public/c/gles2/gles2_call_visitor"
8618 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
8619 gen.WriteMojoGLCallVisitorForExtension(
8620 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
8621 "CHROMIUM_texture_mailbox")
8622 gen.WriteMojoGLCallVisitorForExtension(
8623 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
8624 "CHROMIUM_sync_point")
8626 Format(gen.generated_cpp_filenames)
8628 if gen.errors > 0:
8629 print "%d errors" % gen.errors
8630 return 1
8631 return 0
8634 if __name__ == '__main__':
8635 sys.exit(main(sys.argv[1:]))