Convert Google Now's Authentication Manager to use Promises
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob8e779e3b776e58439ce80d9be7a35ee42b228da7
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
15 _SIZE_OF_UINT32 = 4
16 _SIZE_OF_COMMAND_HEADER = 4
17 _FIRST_SPECIFIC_COMMAND_ID = 256
19 _LICENSE = """// Copyright (c) 2014 The Chromium Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style license that can be
21 // found in the LICENSE file.
23 """
25 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
26 // gpu/command_buffer/build_gles2_cmd_buffer.py
27 // DO NOT EDIT!
29 """
31 # This string is copied directly out of the gl2.h file from GLES2.0
33 # Edits:
35 # *) Any argument that is a resourceID has been changed to GLid<Type>.
36 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
37 # If it's allowed to not exist it's GLidBind<Type>
39 # *) All GLenums have been changed to GLenumTypeOfEnum
41 _GL_TYPES = {
42 'GLenum': 'unsigned int',
43 'GLboolean': 'unsigned char',
44 'GLbitfield': 'unsigned int',
45 'GLbyte': 'signed char',
46 'GLshort': 'short',
47 'GLint': 'int',
48 'GLsizei': 'int',
49 'GLubyte': 'unsigned char',
50 'GLushort': 'unsigned short',
51 'GLuint': 'unsigned int',
52 'GLfloat': 'float',
53 'GLclampf': 'float',
54 'GLvoid': 'void',
55 'GLfixed': 'int',
56 'GLclampx': 'int'
59 _GL_TYPES_32 = {
60 'GLintptr': 'long int',
61 'GLsizeiptr': 'long int'
64 _GL_TYPES_64 = {
65 'GLintptr': 'long long int',
66 'GLsizeiptr': 'long long int'
69 # Capabilites selected with glEnable
70 _CAPABILITY_FLAGS = [
71 {'name': 'blend'},
72 {'name': 'cull_face'},
73 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
74 {'name': 'dither', 'default': True},
75 {'name': 'polygon_offset_fill'},
76 {'name': 'sample_alpha_to_coverage'},
77 {'name': 'sample_coverage'},
78 {'name': 'scissor_test',
79 'state_flag': 'framebuffer_state_.clear_state_dirty'},
80 {'name': 'stencil_test',
81 'state_flag': 'framebuffer_state_.clear_state_dirty'},
84 _STATES = {
85 'ClearColor': {
86 'type': 'Normal',
87 'func': 'ClearColor',
88 'enum': 'GL_COLOR_CLEAR_VALUE',
89 'states': [
90 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
91 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
92 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
96 'ClearDepthf': {
97 'type': 'Normal',
98 'func': 'ClearDepth',
99 'enum': 'GL_DEPTH_CLEAR_VALUE',
100 'states': [
101 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
104 'ColorMask': {
105 'type': 'Normal',
106 'func': 'ColorMask',
107 'enum': 'GL_COLOR_WRITEMASK',
108 'states': [
109 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
110 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
111 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
112 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
114 'state_flag': 'framebuffer_state_.clear_state_dirty',
116 'ClearStencil': {
117 'type': 'Normal',
118 'func': 'ClearStencil',
119 'enum': 'GL_STENCIL_CLEAR_VALUE',
120 'states': [
121 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
124 'BlendColor': {
125 'type': 'Normal',
126 'func': 'BlendColor',
127 'enum': 'GL_BLEND_COLOR',
128 'states': [
129 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
130 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
131 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
132 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
135 'BlendEquation': {
136 'type': 'SrcDst',
137 'func': 'BlendEquationSeparate',
138 'states': [
140 'name': 'blend_equation_rgb',
141 'type': 'GLenum',
142 'enum': 'GL_BLEND_EQUATION_RGB',
143 'default': 'GL_FUNC_ADD',
146 'name': 'blend_equation_alpha',
147 'type': 'GLenum',
148 'enum': 'GL_BLEND_EQUATION_ALPHA',
149 'default': 'GL_FUNC_ADD',
153 'BlendFunc': {
154 'type': 'SrcDst',
155 'func': 'BlendFuncSeparate',
156 'states': [
158 'name': 'blend_source_rgb',
159 'type': 'GLenum',
160 'enum': 'GL_BLEND_SRC_RGB',
161 'default': 'GL_ONE',
164 'name': 'blend_dest_rgb',
165 'type': 'GLenum',
166 'enum': 'GL_BLEND_DST_RGB',
167 'default': 'GL_ZERO',
170 'name': 'blend_source_alpha',
171 'type': 'GLenum',
172 'enum': 'GL_BLEND_SRC_ALPHA',
173 'default': 'GL_ONE',
176 'name': 'blend_dest_alpha',
177 'type': 'GLenum',
178 'enum': 'GL_BLEND_DST_ALPHA',
179 'default': 'GL_ZERO',
183 'PolygonOffset': {
184 'type': 'Normal',
185 'func': 'PolygonOffset',
186 'states': [
188 'name': 'polygon_offset_factor',
189 'type': 'GLfloat',
190 'enum': 'GL_POLYGON_OFFSET_FACTOR',
191 'default': '0.0f',
194 'name': 'polygon_offset_units',
195 'type': 'GLfloat',
196 'enum': 'GL_POLYGON_OFFSET_UNITS',
197 'default': '0.0f',
201 'CullFace': {
202 'type': 'Normal',
203 'func': 'CullFace',
204 'enum': 'GL_CULL_FACE_MODE',
205 'states': [
207 'name': 'cull_mode',
208 'type': 'GLenum',
209 'default': 'GL_BACK',
213 'FrontFace': {
214 'type': 'Normal',
215 'func': 'FrontFace',
216 'enum': 'GL_FRONT_FACE',
217 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
219 'DepthFunc': {
220 'type': 'Normal',
221 'func': 'DepthFunc',
222 'enum': 'GL_DEPTH_FUNC',
223 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
225 'DepthRange': {
226 'type': 'Normal',
227 'func': 'DepthRange',
228 'enum': 'GL_DEPTH_RANGE',
229 'states': [
230 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
231 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
234 'SampleCoverage': {
235 'type': 'Normal',
236 'func': 'SampleCoverage',
237 'states': [
239 'name': 'sample_coverage_value',
240 'type': 'GLclampf',
241 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
242 'default': '1.0f',
245 'name': 'sample_coverage_invert',
246 'type': 'GLboolean',
247 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
248 'default': 'false',
252 'StencilMask': {
253 'type': 'FrontBack',
254 'func': 'StencilMaskSeparate',
255 'state_flag': 'framebuffer_state_.clear_state_dirty',
256 'states': [
258 'name': 'stencil_front_writemask',
259 'type': 'GLuint',
260 'enum': 'GL_STENCIL_WRITEMASK',
261 'default': '0xFFFFFFFFU',
264 'name': 'stencil_back_writemask',
265 'type': 'GLuint',
266 'enum': 'GL_STENCIL_BACK_WRITEMASK',
267 'default': '0xFFFFFFFFU',
271 'StencilOp': {
272 'type': 'FrontBack',
273 'func': 'StencilOpSeparate',
274 'states': [
276 'name': 'stencil_front_fail_op',
277 'type': 'GLenum',
278 'enum': 'GL_STENCIL_FAIL',
279 'default': 'GL_KEEP',
282 'name': 'stencil_front_z_fail_op',
283 'type': 'GLenum',
284 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
285 'default': 'GL_KEEP',
288 'name': 'stencil_front_z_pass_op',
289 'type': 'GLenum',
290 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
291 'default': 'GL_KEEP',
294 'name': 'stencil_back_fail_op',
295 'type': 'GLenum',
296 'enum': 'GL_STENCIL_BACK_FAIL',
297 'default': 'GL_KEEP',
300 'name': 'stencil_back_z_fail_op',
301 'type': 'GLenum',
302 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_back_z_pass_op',
307 'type': 'GLenum',
308 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
309 'default': 'GL_KEEP',
313 'StencilFunc': {
314 'type': 'FrontBack',
315 'func': 'StencilFuncSeparate',
316 'states': [
318 'name': 'stencil_front_func',
319 'type': 'GLenum',
320 'enum': 'GL_STENCIL_FUNC',
321 'default': 'GL_ALWAYS',
324 'name': 'stencil_front_ref',
325 'type': 'GLint',
326 'enum': 'GL_STENCIL_REF',
327 'default': '0',
330 'name': 'stencil_front_mask',
331 'type': 'GLuint',
332 'enum': 'GL_STENCIL_VALUE_MASK',
333 'default': '0xFFFFFFFFU',
336 'name': 'stencil_back_func',
337 'type': 'GLenum',
338 'enum': 'GL_STENCIL_BACK_FUNC',
339 'default': 'GL_ALWAYS',
342 'name': 'stencil_back_ref',
343 'type': 'GLint',
344 'enum': 'GL_STENCIL_BACK_REF',
345 'default': '0',
348 'name': 'stencil_back_mask',
349 'type': 'GLuint',
350 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
351 'default': '0xFFFFFFFFU',
355 'Hint': {
356 'type': 'NamedParameter',
357 'func': 'Hint',
358 'states': [
360 'name': 'hint_generate_mipmap',
361 'type': 'GLenum',
362 'enum': 'GL_GENERATE_MIPMAP_HINT',
363 'default': 'GL_DONT_CARE'
366 'name': 'hint_fragment_shader_derivative',
367 'type': 'GLenum',
368 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
369 'default': 'GL_DONT_CARE',
370 'extension_flag': 'oes_standard_derivatives'
374 'PixelStore': {
375 'type': 'NamedParameter',
376 'func': 'PixelStorei',
377 'states': [
379 'name': 'pack_alignment',
380 'type': 'GLint',
381 'enum': 'GL_PACK_ALIGNMENT',
382 'default': '4'
385 'name': 'unpack_alignment',
386 'type': 'GLint',
387 'enum': 'GL_UNPACK_ALIGNMENT',
388 'default': '4'
392 # TODO: Consider implemenenting these states
393 # GL_ACTIVE_TEXTURE
394 'LineWidth': {
395 'type': 'Normal',
396 'func': 'LineWidth',
397 'enum': 'GL_LINE_WIDTH',
398 'states': [
400 'name': 'line_width',
401 'type': 'GLfloat',
402 'default': '1.0f',
403 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
406 'DepthMask': {
407 'type': 'Normal',
408 'func': 'DepthMask',
409 'enum': 'GL_DEPTH_WRITEMASK',
410 'states': [
411 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
413 'state_flag': 'framebuffer_state_.clear_state_dirty',
415 'Scissor': {
416 'type': 'Normal',
417 'func': 'Scissor',
418 'enum': 'GL_SCISSOR_BOX',
419 'states': [
420 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
422 'name': 'scissor_x',
423 'type': 'GLint',
424 'default': '0',
425 'expected': 'kViewportX',
428 'name': 'scissor_y',
429 'type': 'GLint',
430 'default': '0',
431 'expected': 'kViewportY',
434 'name': 'scissor_width',
435 'type': 'GLsizei',
436 'default': '1',
437 'expected': 'kViewportWidth',
440 'name': 'scissor_height',
441 'type': 'GLsizei',
442 'default': '1',
443 'expected': 'kViewportHeight',
447 'Viewport': {
448 'type': 'Normal',
449 'func': 'Viewport',
450 'enum': 'GL_VIEWPORT',
451 'states': [
452 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
454 'name': 'viewport_x',
455 'type': 'GLint',
456 'default': '0',
457 'expected': 'kViewportX',
460 'name': 'viewport_y',
461 'type': 'GLint',
462 'default': '0',
463 'expected': 'kViewportY',
466 'name': 'viewport_width',
467 'type': 'GLsizei',
468 'default': '1',
469 'expected': 'kViewportWidth',
472 'name': 'viewport_height',
473 'type': 'GLsizei',
474 'default': '1',
475 'expected': 'kViewportHeight',
481 # This is a list of enum names and their valid values. It is used to map
482 # GLenum arguments to a specific set of valid values.
483 _ENUM_LISTS = {
484 'BlitFilter': {
485 'type': 'GLenum',
486 'valid': [
487 'GL_NEAREST',
488 'GL_LINEAR',
490 'invalid': [
491 'GL_LINEAR_MIPMAP_LINEAR',
494 'FrameBufferTarget': {
495 'type': 'GLenum',
496 'valid': [
497 'GL_FRAMEBUFFER',
499 'invalid': [
500 'GL_DRAW_FRAMEBUFFER' ,
501 'GL_READ_FRAMEBUFFER' ,
504 'RenderBufferTarget': {
505 'type': 'GLenum',
506 'valid': [
507 'GL_RENDERBUFFER',
509 'invalid': [
510 'GL_FRAMEBUFFER',
513 'BufferTarget': {
514 'type': 'GLenum',
515 'valid': [
516 'GL_ARRAY_BUFFER',
517 'GL_ELEMENT_ARRAY_BUFFER',
519 'invalid': [
520 'GL_RENDERBUFFER',
523 'BufferUsage': {
524 'type': 'GLenum',
525 'valid': [
526 'GL_STREAM_DRAW',
527 'GL_STATIC_DRAW',
528 'GL_DYNAMIC_DRAW',
530 'invalid': [
531 'GL_STATIC_READ',
534 'CompressedTextureFormat': {
535 'type': 'GLenum',
536 'valid': [
539 'GLState': {
540 'type': 'GLenum',
541 'valid': [
542 # NOTE: State an Capability entries added later.
543 'GL_ACTIVE_TEXTURE',
544 'GL_ALIASED_LINE_WIDTH_RANGE',
545 'GL_ALIASED_POINT_SIZE_RANGE',
546 'GL_ALPHA_BITS',
547 'GL_ARRAY_BUFFER_BINDING',
548 'GL_BLUE_BITS',
549 'GL_COMPRESSED_TEXTURE_FORMATS',
550 'GL_CURRENT_PROGRAM',
551 'GL_DEPTH_BITS',
552 'GL_DEPTH_RANGE',
553 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
554 'GL_FRAMEBUFFER_BINDING',
555 'GL_GENERATE_MIPMAP_HINT',
556 'GL_GREEN_BITS',
557 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
558 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
559 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
561 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
562 'GL_MAX_RENDERBUFFER_SIZE',
563 'GL_MAX_TEXTURE_IMAGE_UNITS',
564 'GL_MAX_TEXTURE_SIZE',
565 'GL_MAX_VARYING_VECTORS',
566 'GL_MAX_VERTEX_ATTRIBS',
567 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
568 'GL_MAX_VERTEX_UNIFORM_VECTORS',
569 'GL_MAX_VIEWPORT_DIMS',
570 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
571 'GL_NUM_SHADER_BINARY_FORMATS',
572 'GL_PACK_ALIGNMENT',
573 'GL_RED_BITS',
574 'GL_RENDERBUFFER_BINDING',
575 'GL_SAMPLE_BUFFERS',
576 'GL_SAMPLE_COVERAGE_INVERT',
577 'GL_SAMPLE_COVERAGE_VALUE',
578 'GL_SAMPLES',
579 'GL_SCISSOR_BOX',
580 'GL_SHADER_BINARY_FORMATS',
581 'GL_SHADER_COMPILER',
582 'GL_SUBPIXEL_BITS',
583 'GL_STENCIL_BITS',
584 'GL_TEXTURE_BINDING_2D',
585 'GL_TEXTURE_BINDING_CUBE_MAP',
586 'GL_UNPACK_ALIGNMENT',
587 'GL_UNPACK_FLIP_Y_CHROMIUM',
588 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
589 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
590 # we can add this because we emulate it if the driver does not support it.
591 'GL_VERTEX_ARRAY_BINDING_OES',
592 'GL_VIEWPORT',
594 'invalid': [
595 'GL_FOG_HINT',
598 'GetTexParamTarget': {
599 'type': 'GLenum',
600 'valid': [
601 'GL_TEXTURE_2D',
602 'GL_TEXTURE_CUBE_MAP',
604 'invalid': [
605 'GL_PROXY_TEXTURE_CUBE_MAP',
608 'TextureTarget': {
609 'type': 'GLenum',
610 'valid': [
611 'GL_TEXTURE_2D',
612 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
613 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
614 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
615 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
619 'invalid': [
620 'GL_PROXY_TEXTURE_CUBE_MAP',
623 'TextureBindTarget': {
624 'type': 'GLenum',
625 'valid': [
626 'GL_TEXTURE_2D',
627 'GL_TEXTURE_CUBE_MAP',
629 'invalid': [
630 'GL_TEXTURE_1D',
631 'GL_TEXTURE_3D',
634 'ShaderType': {
635 'type': 'GLenum',
636 'valid': [
637 'GL_VERTEX_SHADER',
638 'GL_FRAGMENT_SHADER',
640 'invalid': [
641 'GL_GEOMETRY_SHADER',
644 'FaceType': {
645 'type': 'GLenum',
646 'valid': [
647 'GL_FRONT',
648 'GL_BACK',
649 'GL_FRONT_AND_BACK',
652 'FaceMode': {
653 'type': 'GLenum',
654 'valid': [
655 'GL_CW',
656 'GL_CCW',
659 'CmpFunction': {
660 'type': 'GLenum',
661 'valid': [
662 'GL_NEVER',
663 'GL_LESS',
664 'GL_EQUAL',
665 'GL_LEQUAL',
666 'GL_GREATER',
667 'GL_NOTEQUAL',
668 'GL_GEQUAL',
669 'GL_ALWAYS',
672 'Equation': {
673 'type': 'GLenum',
674 'valid': [
675 'GL_FUNC_ADD',
676 'GL_FUNC_SUBTRACT',
677 'GL_FUNC_REVERSE_SUBTRACT',
679 'invalid': [
680 'GL_MIN',
681 'GL_MAX',
684 'SrcBlendFactor': {
685 'type': 'GLenum',
686 'valid': [
687 'GL_ZERO',
688 'GL_ONE',
689 'GL_SRC_COLOR',
690 'GL_ONE_MINUS_SRC_COLOR',
691 'GL_DST_COLOR',
692 'GL_ONE_MINUS_DST_COLOR',
693 'GL_SRC_ALPHA',
694 'GL_ONE_MINUS_SRC_ALPHA',
695 'GL_DST_ALPHA',
696 'GL_ONE_MINUS_DST_ALPHA',
697 'GL_CONSTANT_COLOR',
698 'GL_ONE_MINUS_CONSTANT_COLOR',
699 'GL_CONSTANT_ALPHA',
700 'GL_ONE_MINUS_CONSTANT_ALPHA',
701 'GL_SRC_ALPHA_SATURATE',
704 'DstBlendFactor': {
705 'type': 'GLenum',
706 'valid': [
707 'GL_ZERO',
708 'GL_ONE',
709 'GL_SRC_COLOR',
710 'GL_ONE_MINUS_SRC_COLOR',
711 'GL_DST_COLOR',
712 'GL_ONE_MINUS_DST_COLOR',
713 'GL_SRC_ALPHA',
714 'GL_ONE_MINUS_SRC_ALPHA',
715 'GL_DST_ALPHA',
716 'GL_ONE_MINUS_DST_ALPHA',
717 'GL_CONSTANT_COLOR',
718 'GL_ONE_MINUS_CONSTANT_COLOR',
719 'GL_CONSTANT_ALPHA',
720 'GL_ONE_MINUS_CONSTANT_ALPHA',
723 'Capability': {
724 'type': 'GLenum',
725 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
726 'invalid': [
727 'GL_CLIP_PLANE0',
728 'GL_POINT_SPRITE',
731 'DrawMode': {
732 'type': 'GLenum',
733 'valid': [
734 'GL_POINTS',
735 'GL_LINE_STRIP',
736 'GL_LINE_LOOP',
737 'GL_LINES',
738 'GL_TRIANGLE_STRIP',
739 'GL_TRIANGLE_FAN',
740 'GL_TRIANGLES',
742 'invalid': [
743 'GL_QUADS',
744 'GL_POLYGON',
747 'IndexType': {
748 'type': 'GLenum',
749 'valid': [
750 'GL_UNSIGNED_BYTE',
751 'GL_UNSIGNED_SHORT',
753 'invalid': [
754 'GL_UNSIGNED_INT',
755 'GL_INT',
758 'GetMaxIndexType': {
759 'type': 'GLenum',
760 'valid': [
761 'GL_UNSIGNED_BYTE',
762 'GL_UNSIGNED_SHORT',
763 'GL_UNSIGNED_INT',
765 'invalid': [
766 'GL_INT',
769 'Attachment': {
770 'type': 'GLenum',
771 'valid': [
772 'GL_COLOR_ATTACHMENT0',
773 'GL_DEPTH_ATTACHMENT',
774 'GL_STENCIL_ATTACHMENT',
777 'BackbufferAttachment': {
778 'type': 'GLenum',
779 'valid': [
780 'GL_COLOR_EXT',
781 'GL_DEPTH_EXT',
782 'GL_STENCIL_EXT',
785 'BufferParameter': {
786 'type': 'GLenum',
787 'valid': [
788 'GL_BUFFER_SIZE',
789 'GL_BUFFER_USAGE',
791 'invalid': [
792 'GL_PIXEL_PACK_BUFFER',
795 'FrameBufferParameter': {
796 'type': 'GLenum',
797 'valid': [
798 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
799 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
800 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
801 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
804 'ProgramParameter': {
805 'type': 'GLenum',
806 'valid': [
807 'GL_DELETE_STATUS',
808 'GL_LINK_STATUS',
809 'GL_VALIDATE_STATUS',
810 'GL_INFO_LOG_LENGTH',
811 'GL_ATTACHED_SHADERS',
812 'GL_ACTIVE_ATTRIBUTES',
813 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
814 'GL_ACTIVE_UNIFORMS',
815 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
818 'QueryObjectParameter': {
819 'type': 'GLenum',
820 'valid': [
821 'GL_QUERY_RESULT_EXT',
822 'GL_QUERY_RESULT_AVAILABLE_EXT',
825 'QueryParameter': {
826 'type': 'GLenum',
827 'valid': [
828 'GL_CURRENT_QUERY_EXT',
831 'QueryTarget': {
832 'type': 'GLenum',
833 'valid': [
834 'GL_ANY_SAMPLES_PASSED_EXT',
835 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
836 'GL_COMMANDS_ISSUED_CHROMIUM',
837 'GL_LATENCY_QUERY_CHROMIUM',
838 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
839 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
842 'RenderBufferParameter': {
843 'type': 'GLenum',
844 'valid': [
845 'GL_RENDERBUFFER_RED_SIZE',
846 'GL_RENDERBUFFER_GREEN_SIZE',
847 'GL_RENDERBUFFER_BLUE_SIZE',
848 'GL_RENDERBUFFER_ALPHA_SIZE',
849 'GL_RENDERBUFFER_DEPTH_SIZE',
850 'GL_RENDERBUFFER_STENCIL_SIZE',
851 'GL_RENDERBUFFER_WIDTH',
852 'GL_RENDERBUFFER_HEIGHT',
853 'GL_RENDERBUFFER_INTERNAL_FORMAT',
856 'ShaderParameter': {
857 'type': 'GLenum',
858 'valid': [
859 'GL_SHADER_TYPE',
860 'GL_DELETE_STATUS',
861 'GL_COMPILE_STATUS',
862 'GL_INFO_LOG_LENGTH',
863 'GL_SHADER_SOURCE_LENGTH',
864 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
867 'ShaderPrecision': {
868 'type': 'GLenum',
869 'valid': [
870 'GL_LOW_FLOAT',
871 'GL_MEDIUM_FLOAT',
872 'GL_HIGH_FLOAT',
873 'GL_LOW_INT',
874 'GL_MEDIUM_INT',
875 'GL_HIGH_INT',
878 'StringType': {
879 'type': 'GLenum',
880 'valid': [
881 'GL_VENDOR',
882 'GL_RENDERER',
883 'GL_VERSION',
884 'GL_SHADING_LANGUAGE_VERSION',
885 'GL_EXTENSIONS',
888 'TextureParameter': {
889 'type': 'GLenum',
890 'valid': [
891 'GL_TEXTURE_MAG_FILTER',
892 'GL_TEXTURE_MIN_FILTER',
893 'GL_TEXTURE_POOL_CHROMIUM',
894 'GL_TEXTURE_WRAP_S',
895 'GL_TEXTURE_WRAP_T',
897 'invalid': [
898 'GL_GENERATE_MIPMAP',
901 'TexturePool': {
902 'type': 'GLenum',
903 'valid': [
904 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
905 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
908 'TextureWrapMode': {
909 'type': 'GLenum',
910 'valid': [
911 'GL_CLAMP_TO_EDGE',
912 'GL_MIRRORED_REPEAT',
913 'GL_REPEAT',
916 'TextureMinFilterMode': {
917 'type': 'GLenum',
918 'valid': [
919 'GL_NEAREST',
920 'GL_LINEAR',
921 'GL_NEAREST_MIPMAP_NEAREST',
922 'GL_LINEAR_MIPMAP_NEAREST',
923 'GL_NEAREST_MIPMAP_LINEAR',
924 'GL_LINEAR_MIPMAP_LINEAR',
927 'TextureMagFilterMode': {
928 'type': 'GLenum',
929 'valid': [
930 'GL_NEAREST',
931 'GL_LINEAR',
934 'TextureUsage': {
935 'type': 'GLenum',
936 'valid': [
937 'GL_NONE',
938 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
941 'VertexAttribute': {
942 'type': 'GLenum',
943 'valid': [
944 # some enum that the decoder actually passes through to GL needs
945 # to be the first listed here since it's used in unit tests.
946 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
947 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
948 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
949 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
950 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
951 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
952 'GL_CURRENT_VERTEX_ATTRIB',
955 'VertexPointer': {
956 'type': 'GLenum',
957 'valid': [
958 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
961 'HintTarget': {
962 'type': 'GLenum',
963 'valid': [
964 'GL_GENERATE_MIPMAP_HINT',
966 'invalid': [
967 'GL_PERSPECTIVE_CORRECTION_HINT',
970 'HintMode': {
971 'type': 'GLenum',
972 'valid': [
973 'GL_FASTEST',
974 'GL_NICEST',
975 'GL_DONT_CARE',
978 'PixelStore': {
979 'type': 'GLenum',
980 'valid': [
981 'GL_PACK_ALIGNMENT',
982 'GL_UNPACK_ALIGNMENT',
983 'GL_UNPACK_FLIP_Y_CHROMIUM',
984 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
985 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
987 'invalid': [
988 'GL_PACK_SWAP_BYTES',
989 'GL_UNPACK_SWAP_BYTES',
992 'PixelStoreAlignment': {
993 'type': 'GLint',
994 'valid': [
995 '1',
996 '2',
997 '4',
998 '8',
1000 'invalid': [
1001 '3',
1002 '9',
1005 'ReadPixelFormat': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_ALPHA',
1009 'GL_RGB',
1010 'GL_RGBA',
1013 'PixelType': {
1014 'type': 'GLenum',
1015 'valid': [
1016 'GL_UNSIGNED_BYTE',
1017 'GL_UNSIGNED_SHORT_5_6_5',
1018 'GL_UNSIGNED_SHORT_4_4_4_4',
1019 'GL_UNSIGNED_SHORT_5_5_5_1',
1021 'invalid': [
1022 'GL_SHORT',
1023 'GL_INT',
1026 'ReadPixelType': {
1027 'type': 'GLenum',
1028 'valid': [
1029 'GL_UNSIGNED_BYTE',
1030 'GL_UNSIGNED_SHORT_5_6_5',
1031 'GL_UNSIGNED_SHORT_4_4_4_4',
1032 'GL_UNSIGNED_SHORT_5_5_5_1',
1034 'invalid': [
1035 'GL_SHORT',
1036 'GL_INT',
1039 'RenderBufferFormat': {
1040 'type': 'GLenum',
1041 'valid': [
1042 'GL_RGBA4',
1043 'GL_RGB565',
1044 'GL_RGB5_A1',
1045 'GL_DEPTH_COMPONENT16',
1046 'GL_STENCIL_INDEX8',
1049 'ShaderBinaryFormat': {
1050 'type': 'GLenum',
1051 'valid': [
1054 'StencilOp': {
1055 'type': 'GLenum',
1056 'valid': [
1057 'GL_KEEP',
1058 'GL_ZERO',
1059 'GL_REPLACE',
1060 'GL_INCR',
1061 'GL_INCR_WRAP',
1062 'GL_DECR',
1063 'GL_DECR_WRAP',
1064 'GL_INVERT',
1067 'TextureFormat': {
1068 'type': 'GLenum',
1069 'valid': [
1070 'GL_ALPHA',
1071 'GL_LUMINANCE',
1072 'GL_LUMINANCE_ALPHA',
1073 'GL_RGB',
1074 'GL_RGBA',
1076 'invalid': [
1077 'GL_BGRA',
1078 'GL_BGR',
1081 'TextureInternalFormat': {
1082 'type': 'GLenum',
1083 'valid': [
1084 'GL_ALPHA',
1085 'GL_LUMINANCE',
1086 'GL_LUMINANCE_ALPHA',
1087 'GL_RGB',
1088 'GL_RGBA',
1090 'invalid': [
1091 'GL_BGRA',
1092 'GL_BGR',
1095 'TextureInternalFormatStorage': {
1096 'type': 'GLenum',
1097 'valid': [
1098 'GL_RGB565',
1099 'GL_RGBA4',
1100 'GL_RGB5_A1',
1101 'GL_ALPHA8_EXT',
1102 'GL_LUMINANCE8_EXT',
1103 'GL_LUMINANCE8_ALPHA8_EXT',
1104 'GL_RGB8_OES',
1105 'GL_RGBA8_OES',
1108 'VertexAttribType': {
1109 'type': 'GLenum',
1110 'valid': [
1111 'GL_BYTE',
1112 'GL_UNSIGNED_BYTE',
1113 'GL_SHORT',
1114 'GL_UNSIGNED_SHORT',
1115 # 'GL_FIXED', // This is not available on Desktop GL.
1116 'GL_FLOAT',
1118 'invalid': [
1119 'GL_DOUBLE',
1122 'TextureBorder': {
1123 'type': 'GLint',
1124 'valid': [
1125 '0',
1127 'invalid': [
1128 '1',
1131 'VertexAttribSize': {
1132 'type': 'GLint',
1133 'valid': [
1134 '1',
1135 '2',
1136 '3',
1137 '4',
1139 'invalid': [
1140 '0',
1141 '5',
1144 'ZeroOnly': {
1145 'type': 'GLint',
1146 'valid': [
1147 '0',
1149 'invalid': [
1150 '1',
1153 'FalseOnly': {
1154 'type': 'GLboolean',
1155 'valid': [
1156 'false',
1158 'invalid': [
1159 'true',
1162 'ResetStatus': {
1163 'type': 'GLenum',
1164 'valid': [
1165 'GL_GUILTY_CONTEXT_RESET_ARB',
1166 'GL_INNOCENT_CONTEXT_RESET_ARB',
1167 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1172 # This table specifies the different pepper interfaces that are supported for
1173 # GL commands. 'dev' is true if it's a dev interface.
1174 _PEPPER_INTERFACES = [
1175 {'name': '', 'dev': False},
1176 {'name': 'InstancedArrays', 'dev': False},
1177 {'name': 'FramebufferBlit', 'dev': False},
1178 {'name': 'FramebufferMultisample', 'dev': False},
1179 {'name': 'ChromiumEnableFeature', 'dev': False},
1180 {'name': 'ChromiumMapSub', 'dev': False},
1181 {'name': 'Query', 'dev': False},
1184 # This table specifies types and other special data for the commands that
1185 # will be generated.
1187 # Must match function names specified in "cmd_buffer_functions.txt".
1189 # cmd_comment: A comment added to the cmd format.
1190 # type: defines which handler will be used to generate code.
1191 # decoder_func: defines which function to call in the decoder to execute the
1192 # corresponding GL command. If not specified the GL command will
1193 # be called directly.
1194 # gl_test_func: GL function that is expected to be called when testing.
1195 # cmd_args: The arguments to use for the command. This overrides generating
1196 # them based on the GL function arguments.
1197 # a NonImmediate type is a type that stays a pointer even in
1198 # and immediate version of acommand.
1199 # gen_cmd: Whether or not this function geneates a command. Default = True.
1200 # immediate: Whether or not to generate an immediate command for the GL
1201 # function. The default is if there is exactly 1 pointer argument
1202 # in the GL function an immediate command is generated.
1203 # bucket: True to generate a bucket version of the command.
1204 # impl_func: Whether or not to generate the GLES2Implementation part of this
1205 # command.
1206 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1207 # for this command.
1208 # needs_size: If true a data_size field is added to the command.
1209 # data_type: The type of data the command uses. For PUTn or PUT types.
1210 # count: The number of units per element. For PUTn or PUT types.
1211 # unit_test: If False no service side unit test will be generated.
1212 # client_test: If False no client side unit test will be generated.
1213 # expectation: If False the unit test will have no expected calls.
1214 # gen_func: Name of function that generates GL resource for corresponding
1215 # bind function.
1216 # states: array of states that get set by this function corresponding to
1217 # the given arguments
1218 # state_flag: name of flag that is set to true when function is called.
1219 # no_gl: no GL function is called.
1220 # valid_args: A dictionary of argument indices to args to use in unit tests
1221 # when they can not be automatically determined.
1222 # pepper_interface: The pepper interface that is used for this extension
1223 # pepper_name: The name of the function as exposed to pepper.
1224 # pepper_args: A string representing the argument list (what would appear in
1225 # C/C++ between the parentheses for the function declaration)
1226 # that the Pepper API expects for this function. Use this only if
1227 # the stable Pepper API differs from the GLES2 argument list.
1228 # invalid_test: False if no invalid test needed.
1229 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1230 # first_element_only: For PUT types, True if only the first element of an
1231 # array is used and we end up calling the single value
1232 # corresponding function. eg. TexParameteriv -> TexParameteri
1234 _FUNCTION_INFO = {
1235 'ActiveTexture': {
1236 'decoder_func': 'DoActiveTexture',
1237 'unit_test': False,
1238 'impl_func': False,
1239 'client_test': False,
1241 'AttachShader': {'decoder_func': 'DoAttachShader'},
1242 'BindAttribLocation': {
1243 'type': 'GLchar',
1244 'bucket': True,
1245 'needs_size': True,
1246 'immediate': False,
1248 'BindBuffer': {
1249 'type': 'Bind',
1250 'decoder_func': 'DoBindBuffer',
1251 'gen_func': 'GenBuffersARB',
1253 'BindFramebuffer': {
1254 'type': 'Bind',
1255 'decoder_func': 'DoBindFramebuffer',
1256 'gl_test_func': 'glBindFramebufferEXT',
1257 'gen_func': 'GenFramebuffersEXT',
1258 'trace_level': 1,
1260 'BindRenderbuffer': {
1261 'type': 'Bind',
1262 'decoder_func': 'DoBindRenderbuffer',
1263 'gl_test_func': 'glBindRenderbufferEXT',
1264 'gen_func': 'GenRenderbuffersEXT',
1266 'BindTexture': {
1267 'type': 'Bind',
1268 'decoder_func': 'DoBindTexture',
1269 'gen_func': 'GenTextures',
1270 # TODO(gman): remove this once client side caching works.
1271 'client_test': False,
1272 'trace_level': 1,
1274 'BlitFramebufferCHROMIUM': {
1275 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1276 'unit_test': False,
1277 'extension': True,
1278 'pepper_interface': 'FramebufferBlit',
1279 'pepper_name': 'BlitFramebufferEXT',
1280 'defer_reads': True,
1281 'defer_draws': True,
1282 'trace_level': 1,
1284 'BufferData': {
1285 'type': 'Manual',
1286 'immediate': False,
1287 'client_test': False,
1289 'BufferSubData': {
1290 'type': 'Data',
1291 'client_test': False,
1292 'decoder_func': 'DoBufferSubData',
1293 'immediate': False,
1295 'CheckFramebufferStatus': {
1296 'type': 'Is',
1297 'decoder_func': 'DoCheckFramebufferStatus',
1298 'gl_test_func': 'glCheckFramebufferStatusEXT',
1299 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1300 'result': ['GLenum'],
1302 'Clear': {
1303 'decoder_func': 'DoClear',
1304 'defer_draws': True,
1305 'trace_level': 1,
1307 'ClearColor': {
1308 'type': 'StateSet',
1309 'state': 'ClearColor',
1311 'ClearDepthf': {
1312 'type': 'StateSet',
1313 'state': 'ClearDepthf',
1314 'decoder_func': 'glClearDepth',
1315 'gl_test_func': 'glClearDepth',
1316 'valid_args': {
1317 '0': '0.5f'
1320 'ColorMask': {
1321 'type': 'StateSet',
1322 'state': 'ColorMask',
1323 'no_gl': True,
1324 'expectation': False,
1326 'ConsumeTextureCHROMIUM': {
1327 'decoder_func': 'DoConsumeTextureCHROMIUM',
1328 'impl_func': False,
1329 'type': 'PUT',
1330 'data_type': 'GLbyte',
1331 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1332 'unit_test': False,
1333 'client_test': False,
1334 'extension': True,
1335 'chromium': True,
1336 'trace_level': 1,
1338 'ClearStencil': {
1339 'type': 'StateSet',
1340 'state': 'ClearStencil',
1342 'EnableFeatureCHROMIUM': {
1343 'type': 'Custom',
1344 'immediate': False,
1345 'decoder_func': 'DoEnableFeatureCHROMIUM',
1346 'expectation': False,
1347 'cmd_args': 'GLuint bucket_id, GLint* result',
1348 'result': ['GLint'],
1349 'extension': True,
1350 'chromium': True,
1351 'pepper_interface': 'ChromiumEnableFeature',
1353 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1354 'CompressedTexImage2D': {
1355 'type': 'Manual',
1356 'immediate': False,
1357 'bucket': True,
1359 'CompressedTexSubImage2D': {
1360 'type': 'Data',
1361 'bucket': True,
1362 'decoder_func': 'DoCompressedTexSubImage2D',
1363 'immediate': False,
1365 'CopyTexImage2D': {
1366 'decoder_func': 'DoCopyTexImage2D',
1367 'unit_test': False,
1368 'defer_reads': True,
1370 'CopyTexSubImage2D': {
1371 'decoder_func': 'DoCopyTexSubImage2D',
1372 'defer_reads': True,
1374 'CreateImageCHROMIUM': {
1375 'type': 'Manual',
1376 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1377 'result': ['GLuint'],
1378 'client_test': False,
1379 'gen_cmd': False,
1380 'expectation': False,
1381 'extension': True,
1382 'chromium': True,
1384 'DestroyImageCHROMIUM': {
1385 'type': 'Manual',
1386 'immediate': False,
1387 'client_test': False,
1388 'gen_cmd': False,
1389 'extension': True,
1390 'chromium': True,
1392 'GetImageParameterivCHROMIUM': {
1393 'type': 'Manual',
1394 'client_test': False,
1395 'gen_cmd': False,
1396 'expectation': False,
1397 'extension': True,
1398 'chromium': True,
1400 'CreateProgram': {
1401 'type': 'Create',
1402 'client_test': False,
1404 'CreateShader': {
1405 'type': 'Create',
1406 'client_test': False,
1408 'BlendColor': {
1409 'type': 'StateSet',
1410 'state': 'BlendColor',
1412 'BlendEquation': {
1413 'type': 'StateSetRGBAlpha',
1414 'state': 'BlendEquation',
1415 'valid_args': {
1416 '0': 'GL_FUNC_SUBTRACT'
1419 'BlendEquationSeparate': {
1420 'type': 'StateSet',
1421 'state': 'BlendEquation',
1422 'valid_args': {
1423 '0': 'GL_FUNC_SUBTRACT'
1426 'BlendFunc': {
1427 'type': 'StateSetRGBAlpha',
1428 'state': 'BlendFunc',
1430 'BlendFuncSeparate': {
1431 'type': 'StateSet',
1432 'state': 'BlendFunc',
1434 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1435 'StencilFunc': {
1436 'type': 'StateSetFrontBack',
1437 'state': 'StencilFunc',
1439 'StencilFuncSeparate': {
1440 'type': 'StateSetFrontBackSeparate',
1441 'state': 'StencilFunc',
1443 'StencilOp': {
1444 'type': 'StateSetFrontBack',
1445 'state': 'StencilOp',
1446 'valid_args': {
1447 '1': 'GL_INCR'
1450 'StencilOpSeparate': {
1451 'type': 'StateSetFrontBackSeparate',
1452 'state': 'StencilOp',
1453 'valid_args': {
1454 '1': 'GL_INCR'
1457 'Hint': {
1458 'type': 'StateSetNamedParameter',
1459 'state': 'Hint',
1461 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1462 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1463 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1464 'LineWidth': {
1465 'type': 'StateSet',
1466 'state': 'LineWidth',
1467 'valid_args': {
1468 '0': '0.5f'
1471 'PolygonOffset': {
1472 'type': 'StateSet',
1473 'state': 'PolygonOffset',
1475 'DeleteBuffers': {
1476 'type': 'DELn',
1477 'gl_test_func': 'glDeleteBuffersARB',
1478 'resource_type': 'Buffer',
1479 'resource_types': 'Buffers',
1481 'DeleteFramebuffers': {
1482 'type': 'DELn',
1483 'gl_test_func': 'glDeleteFramebuffersEXT',
1484 'resource_type': 'Framebuffer',
1485 'resource_types': 'Framebuffers',
1487 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1488 'DeleteRenderbuffers': {
1489 'type': 'DELn',
1490 'gl_test_func': 'glDeleteRenderbuffersEXT',
1491 'resource_type': 'Renderbuffer',
1492 'resource_types': 'Renderbuffers',
1494 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1495 'DeleteSharedIdsCHROMIUM': {
1496 'type': 'Custom',
1497 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1498 'impl_func': False,
1499 'expectation': False,
1500 'immediate': False,
1501 'extension': True,
1502 'chromium': True,
1504 'DeleteTextures': {
1505 'type': 'DELn',
1506 'resource_type': 'Texture',
1507 'resource_types': 'Textures',
1509 'DepthRangef': {
1510 'decoder_func': 'DoDepthRangef',
1511 'gl_test_func': 'glDepthRange',
1513 'DepthMask': {
1514 'type': 'StateSet',
1515 'state': 'DepthMask',
1516 'no_gl': True,
1517 'expectation': False,
1519 'DetachShader': {'decoder_func': 'DoDetachShader'},
1520 'Disable': {
1521 'decoder_func': 'DoDisable',
1522 'impl_func': False,
1523 'client_test': False,
1525 'DisableVertexAttribArray': {
1526 'decoder_func': 'DoDisableVertexAttribArray',
1527 'impl_decl': False,
1529 'DrawArrays': {
1530 'type': 'Manual',
1531 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1532 'defer_draws': True,
1533 'trace_level': 2,
1535 'DrawElements': {
1536 'type': 'Manual',
1537 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1538 'GLenumIndexType type, GLuint index_offset',
1539 'client_test': False,
1540 'defer_draws': True,
1541 'trace_level': 2,
1543 'Enable': {
1544 'decoder_func': 'DoEnable',
1545 'impl_func': False,
1546 'client_test': False,
1548 'EnableVertexAttribArray': {
1549 'decoder_func': 'DoEnableVertexAttribArray',
1550 'impl_decl': False,
1552 'Finish': {
1553 'impl_func': False,
1554 'client_test': False,
1555 'decoder_func': 'DoFinish',
1556 'defer_reads': True,
1558 'Flush': {
1559 'impl_func': False,
1560 'decoder_func': 'DoFlush',
1562 'FramebufferRenderbuffer': {
1563 'decoder_func': 'DoFramebufferRenderbuffer',
1564 'gl_test_func': 'glFramebufferRenderbufferEXT',
1566 'FramebufferTexture2D': {
1567 'decoder_func': 'DoFramebufferTexture2D',
1568 'gl_test_func': 'glFramebufferTexture2DEXT',
1569 'trace_level': 1,
1571 'FramebufferTexture2DMultisampleEXT': {
1572 'decoder_func': 'DoFramebufferTexture2DMultisample',
1573 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1574 'expectation': False,
1575 'unit_test': False,
1576 'extension': True,
1577 'trace_level': 1,
1579 'GenerateMipmap': {
1580 'decoder_func': 'DoGenerateMipmap',
1581 'gl_test_func': 'glGenerateMipmapEXT',
1583 'GenBuffers': {
1584 'type': 'GENn',
1585 'gl_test_func': 'glGenBuffersARB',
1586 'resource_type': 'Buffer',
1587 'resource_types': 'Buffers',
1589 'GenMailboxCHROMIUM': {
1590 'type': 'HandWritten',
1591 'immediate': False,
1592 'impl_func': False,
1593 'extension': True,
1594 'chromium': True,
1596 'GenFramebuffers': {
1597 'type': 'GENn',
1598 'gl_test_func': 'glGenFramebuffersEXT',
1599 'resource_type': 'Framebuffer',
1600 'resource_types': 'Framebuffers',
1602 'GenRenderbuffers': {
1603 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1604 'resource_type': 'Renderbuffer',
1605 'resource_types': 'Renderbuffers',
1607 'GenTextures': {
1608 'type': 'GENn',
1609 'gl_test_func': 'glGenTextures',
1610 'resource_type': 'Texture',
1611 'resource_types': 'Textures',
1613 'GenSharedIdsCHROMIUM': {
1614 'type': 'Custom',
1615 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1616 'impl_func': False,
1617 'expectation': False,
1618 'immediate': False,
1619 'extension': True,
1620 'chromium': True,
1622 'GetActiveAttrib': {
1623 'type': 'Custom',
1624 'immediate': False,
1625 'cmd_args':
1626 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1627 'void* result',
1628 'result': [
1629 'int32 success',
1630 'int32 size',
1631 'uint32 type',
1634 'GetActiveUniform': {
1635 'type': 'Custom',
1636 'immediate': False,
1637 'cmd_args':
1638 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1639 'void* result',
1640 'result': [
1641 'int32 success',
1642 'int32 size',
1643 'uint32 type',
1646 'GetAttachedShaders': {
1647 'type': 'Custom',
1648 'immediate': False,
1649 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1650 'result': ['SizedResult<GLuint>'],
1652 'GetAttribLocation': {
1653 'type': 'HandWritten',
1654 'immediate': False,
1655 'bucket': True,
1656 'needs_size': True,
1657 'cmd_args':
1658 'GLidProgram program, const char* name, NonImmediate GLint* location',
1659 'result': ['GLint'],
1660 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1662 'GetBooleanv': {
1663 'type': 'GETn',
1664 'result': ['SizedResult<GLboolean>'],
1665 'decoder_func': 'DoGetBooleanv',
1666 'gl_test_func': 'glGetBooleanv',
1668 'GetBufferParameteriv': {
1669 'type': 'GETn',
1670 'result': ['SizedResult<GLint>'],
1671 'decoder_func': 'DoGetBufferParameteriv',
1672 'expectation': False,
1673 'shadowed': True,
1675 'GetError': {
1676 'type': 'Is',
1677 'decoder_func': 'GetErrorState()->GetGLError',
1678 'impl_func': False,
1679 'result': ['GLenum'],
1680 'client_test': False,
1682 'GetFloatv': {
1683 'type': 'GETn',
1684 'result': ['SizedResult<GLfloat>'],
1685 'decoder_func': 'DoGetFloatv',
1686 'gl_test_func': 'glGetFloatv',
1688 'GetFramebufferAttachmentParameteriv': {
1689 'type': 'GETn',
1690 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1691 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1692 'result': ['SizedResult<GLint>'],
1694 'GetIntegerv': {
1695 'type': 'GETn',
1696 'result': ['SizedResult<GLint>'],
1697 'decoder_func': 'DoGetIntegerv',
1698 'client_test': False,
1700 'GetMaxValueInBufferCHROMIUM': {
1701 'type': 'Is',
1702 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1703 'result': ['GLuint'],
1704 'unit_test': False,
1705 'client_test': False,
1706 'extension': True,
1707 'chromium': True,
1708 'impl_func': False,
1710 'GetMultipleIntegervCHROMIUM': {
1711 'type': 'Custom',
1712 'immediate': False,
1713 'expectation': False,
1714 'extension': True,
1715 'chromium': True,
1716 'client_test': False,
1718 'GetProgramiv': {
1719 'type': 'GETn',
1720 'decoder_func': 'DoGetProgramiv',
1721 'result': ['SizedResult<GLint>'],
1722 'expectation': False,
1724 'GetProgramInfoCHROMIUM': {
1725 'type': 'Custom',
1726 'immediate': False,
1727 'expectation': False,
1728 'impl_func': False,
1729 'extension': True,
1730 'chromium': True,
1731 'client_test': False,
1732 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1733 'result': [
1734 'uint32 link_status',
1735 'uint32 num_attribs',
1736 'uint32 num_uniforms',
1739 'GetProgramInfoLog': {
1740 'type': 'STRn',
1741 'expectation': False,
1743 'GetRenderbufferParameteriv': {
1744 'type': 'GETn',
1745 'decoder_func': 'DoGetRenderbufferParameteriv',
1746 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1747 'result': ['SizedResult<GLint>'],
1749 'GetShaderiv': {
1750 'type': 'GETn',
1751 'decoder_func': 'DoGetShaderiv',
1752 'result': ['SizedResult<GLint>'],
1754 'GetShaderInfoLog': {
1755 'type': 'STRn',
1756 'get_len_func': 'glGetShaderiv',
1757 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1758 'unit_test': False,
1760 'GetShaderPrecisionFormat': {
1761 'type': 'Custom',
1762 'immediate': False,
1763 'cmd_args':
1764 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1765 'void* result',
1766 'result': [
1767 'int32 success',
1768 'int32 min_range',
1769 'int32 max_range',
1770 'int32 precision',
1773 'GetShaderSource': {
1774 'type': 'STRn',
1775 'get_len_func': 'DoGetShaderiv',
1776 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1777 'unit_test': False,
1778 'client_test': False,
1780 'GetString': {
1781 'type': 'Custom',
1782 'client_test': False,
1783 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1785 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1786 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1787 'GetTranslatedShaderSourceANGLE': {
1788 'type': 'STRn',
1789 'get_len_func': 'DoGetShaderiv',
1790 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1791 'unit_test': False,
1792 'extension': True,
1794 'GetUniformfv': {
1795 'type': 'Custom',
1796 'immediate': False,
1797 'result': ['SizedResult<GLfloat>'],
1799 'GetUniformiv': {
1800 'type': 'Custom',
1801 'immediate': False,
1802 'result': ['SizedResult<GLint>'],
1804 'GetUniformLocation': {
1805 'type': 'HandWritten',
1806 'immediate': False,
1807 'bucket': True,
1808 'needs_size': True,
1809 'cmd_args':
1810 'GLidProgram program, const char* name, NonImmediate GLint* location',
1811 'result': ['GLint'],
1812 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1814 'GetVertexAttribfv': {
1815 'type': 'GETn',
1816 'result': ['SizedResult<GLfloat>'],
1817 'impl_decl': False,
1818 'decoder_func': 'DoGetVertexAttribfv',
1819 'expectation': False,
1820 'client_test': False,
1822 'GetVertexAttribiv': {
1823 'type': 'GETn',
1824 'result': ['SizedResult<GLint>'],
1825 'impl_decl': False,
1826 'decoder_func': 'DoGetVertexAttribiv',
1827 'expectation': False,
1828 'client_test': False,
1830 'GetVertexAttribPointerv': {
1831 'type': 'Custom',
1832 'immediate': False,
1833 'result': ['SizedResult<GLuint>'],
1834 'client_test': False,
1836 'IsBuffer': {
1837 'type': 'Is',
1838 'decoder_func': 'DoIsBuffer',
1839 'expectation': False,
1841 'IsEnabled': {
1842 'type': 'Is',
1843 'decoder_func': 'DoIsEnabled',
1844 'impl_func': False,
1845 'expectation': False,
1847 'IsFramebuffer': {
1848 'type': 'Is',
1849 'decoder_func': 'DoIsFramebuffer',
1850 'expectation': False,
1852 'IsProgram': {
1853 'type': 'Is',
1854 'decoder_func': 'DoIsProgram',
1855 'expectation': False,
1857 'IsRenderbuffer': {
1858 'type': 'Is',
1859 'decoder_func': 'DoIsRenderbuffer',
1860 'expectation': False,
1862 'IsShader': {
1863 'type': 'Is',
1864 'decoder_func': 'DoIsShader',
1865 'expectation': False,
1867 'IsTexture': {
1868 'type': 'Is',
1869 'decoder_func': 'DoIsTexture',
1870 'expectation': False,
1872 'LinkProgram': {
1873 'decoder_func': 'DoLinkProgram',
1874 'impl_func': False,
1876 'MapBufferCHROMIUM': {
1877 'gen_cmd': False,
1878 'extension': True,
1879 'chromium': True,
1880 'client_test': False,
1882 'MapBufferSubDataCHROMIUM': {
1883 'gen_cmd': False,
1884 'extension': True,
1885 'chromium': True,
1886 'client_test': False,
1887 'pepper_interface': 'ChromiumMapSub',
1889 'MapImageCHROMIUM': {
1890 'gen_cmd': False,
1891 'extension': True,
1892 'chromium': True,
1893 'client_test': False,
1895 'MapTexSubImage2DCHROMIUM': {
1896 'gen_cmd': False,
1897 'extension': True,
1898 'chromium': True,
1899 'client_test': False,
1900 'pepper_interface': 'ChromiumMapSub',
1902 'PixelStorei': {'type': 'Manual'},
1903 'PostSubBufferCHROMIUM': {
1904 'type': 'Custom',
1905 'impl_func': False,
1906 'unit_test': False,
1907 'client_test': False,
1908 'extension': True,
1909 'chromium': True,
1911 'ProduceTextureCHROMIUM': {
1912 'decoder_func': 'DoProduceTextureCHROMIUM',
1913 'impl_func': False,
1914 'type': 'PUT',
1915 'data_type': 'GLbyte',
1916 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1917 'unit_test': False,
1918 'client_test': False,
1919 'extension': True,
1920 'chromium': True,
1921 'trace_level': 1,
1923 'RenderbufferStorage': {
1924 'decoder_func': 'DoRenderbufferStorage',
1925 'gl_test_func': 'glRenderbufferStorageEXT',
1926 'expectation': False,
1928 'RenderbufferStorageMultisampleCHROMIUM': {
1929 'cmd_comment':
1930 '// GL_CHROMIUM_framebuffer_multisample\n',
1931 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1932 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1933 'expectation': False,
1934 'unit_test': False,
1935 'extension': True,
1936 'pepper_interface': 'FramebufferMultisample',
1937 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1939 'RenderbufferStorageMultisampleEXT': {
1940 'cmd_comment':
1941 '// GL_EXT_multisampled_render_to_texture\n',
1942 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1943 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1944 'expectation': False,
1945 'unit_test': False,
1946 'extension': True,
1948 'ReadPixels': {
1949 'cmd_comment':
1950 '// ReadPixels has the result separated from the pixel buffer so that\n'
1951 '// it is easier to specify the result going to some specific place\n'
1952 '// that exactly fits the rectangle of pixels.\n',
1953 'type': 'Custom',
1954 'immediate': False,
1955 'impl_func': False,
1956 'client_test': False,
1957 'cmd_args':
1958 'GLint x, GLint y, GLsizei width, GLsizei height, '
1959 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1960 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1961 'uint32 result_shm_id, uint32 result_shm_offset, '
1962 'GLboolean async',
1963 'result': ['uint32'],
1964 'defer_reads': True,
1966 'RegisterSharedIdsCHROMIUM': {
1967 'type': 'Custom',
1968 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1969 'impl_func': False,
1970 'expectation': False,
1971 'immediate': False,
1972 'extension': True,
1973 'chromium': True,
1975 'ReleaseShaderCompiler': {
1976 'decoder_func': 'DoReleaseShaderCompiler',
1977 'unit_test': False,
1979 'ShaderBinary': {
1980 'type': 'Custom',
1981 'client_test': False,
1983 'ShaderSource': {
1984 'type': 'Manual',
1985 'immediate': False,
1986 'bucket': True,
1987 'needs_size': True,
1988 'client_test': False,
1989 'cmd_args':
1990 'GLuint shader, const char* data',
1991 'pepper_args':
1992 'GLuint shader, GLsizei count, const char** str, const GLint* length',
1994 'StencilMask': {
1995 'type': 'StateSetFrontBack',
1996 'state': 'StencilMask',
1997 'no_gl': True,
1998 'expectation': False,
2000 'StencilMaskSeparate': {
2001 'type': 'StateSetFrontBackSeparate',
2002 'state': 'StencilMask',
2003 'no_gl': True,
2004 'expectation': False,
2006 'SwapBuffers': {
2007 'impl_func': False,
2008 'decoder_func': 'DoSwapBuffers',
2009 'unit_test': False,
2010 'client_test': False,
2011 'extension': True,
2012 'trace_level': 1,
2014 'TexImage2D': {
2015 'type': 'Manual',
2016 'immediate': False,
2017 'client_test': False,
2019 'TexParameterf': {
2020 'decoder_func': 'DoTexParameterf',
2021 'gl_test_func': 'glTexParameteri',
2022 'valid_args': {
2023 '2': 'GL_NEAREST'
2026 'TexParameteri': {
2027 'decoder_func': 'DoTexParameteri',
2028 'valid_args': {
2029 '2': 'GL_NEAREST'
2032 'TexParameterfv': {
2033 'type': 'PUT',
2034 'data_type': 'GLfloat',
2035 'data_value': 'GL_NEAREST',
2036 'count': 1,
2037 'decoder_func': 'DoTexParameterfv',
2038 'gl_test_func': 'glTexParameteri',
2039 'first_element_only': True,
2041 'TexParameteriv': {
2042 'type': 'PUT',
2043 'data_type': 'GLint',
2044 'data_value': 'GL_NEAREST',
2045 'count': 1,
2046 'decoder_func': 'DoTexParameteriv',
2047 'gl_test_func': 'glTexParameteri',
2048 'first_element_only': True,
2050 'TexSubImage2D': {
2051 'type': 'Manual',
2052 'immediate': False,
2053 'client_test': False,
2054 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2055 'GLint xoffset, GLint yoffset, '
2056 'GLsizei width, GLsizei height, '
2057 'GLenumTextureFormat format, GLenumPixelType type, '
2058 'const void* pixels, GLboolean internal'
2060 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2061 'Uniform1fv': {
2062 'type': 'PUTn',
2063 'data_type': 'GLfloat',
2064 'count': 1,
2065 'decoder_func': 'DoUniform1fv',
2067 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2068 'Uniform1iv': {
2069 'type': 'PUTn',
2070 'data_type': 'GLint',
2071 'count': 1,
2072 'decoder_func': 'DoUniform1iv',
2073 'unit_test': False,
2075 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2076 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2077 'Uniform2fv': {
2078 'type': 'PUTn',
2079 'data_type': 'GLfloat',
2080 'count': 2,
2081 'decoder_func': 'DoUniform2fv',
2083 'Uniform2iv': {
2084 'type': 'PUTn',
2085 'data_type': 'GLint',
2086 'count': 2,
2087 'decoder_func': 'DoUniform2iv',
2089 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2090 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2091 'Uniform3fv': {
2092 'type': 'PUTn',
2093 'data_type': 'GLfloat',
2094 'count': 3,
2095 'decoder_func': 'DoUniform3fv',
2097 'Uniform3iv': {
2098 'type': 'PUTn',
2099 'data_type': 'GLint',
2100 'count': 3,
2101 'decoder_func': 'DoUniform3iv',
2103 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2104 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2105 'Uniform4fv': {
2106 'type': 'PUTn',
2107 'data_type': 'GLfloat',
2108 'count': 4,
2109 'decoder_func': 'DoUniform4fv',
2111 'Uniform4iv': {
2112 'type': 'PUTn',
2113 'data_type': 'GLint',
2114 'count': 4,
2115 'decoder_func': 'DoUniform4iv',
2117 'UniformMatrix2fv': {
2118 'type': 'PUTn',
2119 'data_type': 'GLfloat',
2120 'count': 4,
2121 'decoder_func': 'DoUniformMatrix2fv',
2123 'UniformMatrix3fv': {
2124 'type': 'PUTn',
2125 'data_type': 'GLfloat',
2126 'count': 9,
2127 'decoder_func': 'DoUniformMatrix3fv',
2129 'UniformMatrix4fv': {
2130 'type': 'PUTn',
2131 'data_type': 'GLfloat',
2132 'count': 16,
2133 'decoder_func': 'DoUniformMatrix4fv',
2135 'UnmapBufferCHROMIUM': {
2136 'gen_cmd': False,
2137 'extension': True,
2138 'chromium': True,
2139 'client_test': False,
2141 'UnmapBufferSubDataCHROMIUM': {
2142 'gen_cmd': False,
2143 'extension': True,
2144 'chromium': True,
2145 'client_test': False,
2146 'pepper_interface': 'ChromiumMapSub',
2148 'UnmapImageCHROMIUM': {
2149 'gen_cmd': False,
2150 'extension': True,
2151 'chromium': True,
2152 'client_test': False,
2154 'UnmapTexSubImage2DCHROMIUM': {
2155 'gen_cmd': False,
2156 'extension': True,
2157 'chromium': True,
2158 'client_test': False,
2159 'pepper_interface': 'ChromiumMapSub',
2161 'UseProgram': {
2162 'decoder_func': 'DoUseProgram',
2163 'impl_func': False,
2164 'unit_test': False,
2166 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2167 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2168 'VertexAttrib1fv': {
2169 'type': 'PUT',
2170 'data_type': 'GLfloat',
2171 'count': 1,
2172 'decoder_func': 'DoVertexAttrib1fv',
2174 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2175 'VertexAttrib2fv': {
2176 'type': 'PUT',
2177 'data_type': 'GLfloat',
2178 'count': 2,
2179 'decoder_func': 'DoVertexAttrib2fv',
2181 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2182 'VertexAttrib3fv': {
2183 'type': 'PUT',
2184 'data_type': 'GLfloat',
2185 'count': 3,
2186 'decoder_func': 'DoVertexAttrib3fv',
2188 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2189 'VertexAttrib4fv': {
2190 'type': 'PUT',
2191 'data_type': 'GLfloat',
2192 'count': 4,
2193 'decoder_func': 'DoVertexAttrib4fv',
2195 'VertexAttribPointer': {
2196 'type': 'Manual',
2197 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2198 'GLenumVertexAttribType type, GLboolean normalized, '
2199 'GLsizei stride, GLuint offset',
2200 'client_test': False,
2202 'Scissor': {
2203 'type': 'StateSet',
2204 'state': 'Scissor',
2206 'Viewport': {
2207 'decoder_func': 'DoViewport',
2209 'ResizeCHROMIUM': {
2210 'type': 'Custom',
2211 'impl_func': False,
2212 'unit_test': False,
2213 'extension': True,
2214 'chromium': True,
2216 'GetRequestableExtensionsCHROMIUM': {
2217 'type': 'Custom',
2218 'impl_func': False,
2219 'immediate': False,
2220 'cmd_args': 'uint32 bucket_id',
2221 'extension': True,
2222 'chromium': True,
2224 'RequestExtensionCHROMIUM': {
2225 'type': 'Custom',
2226 'impl_func': False,
2227 'immediate': False,
2228 'client_test': False,
2229 'cmd_args': 'uint32 bucket_id',
2230 'extension': True,
2231 'chromium': True,
2233 'RateLimitOffscreenContextCHROMIUM': {
2234 'gen_cmd': False,
2235 'extension': True,
2236 'chromium': True,
2237 'client_test': False,
2239 'CreateStreamTextureCHROMIUM': {
2240 'type': 'HandWritten',
2241 'impl_func': False,
2242 'gen_cmd': False,
2243 'immediate': False,
2244 'extension': True,
2245 'chromium': True,
2247 'TexImageIOSurface2DCHROMIUM': {
2248 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2249 'unit_test': False,
2250 'extension': True,
2251 'chromium': True,
2253 'CopyTextureCHROMIUM': {
2254 'decoder_func': 'DoCopyTextureCHROMIUM',
2255 'unit_test': False,
2256 'extension': True,
2257 'chromium': True,
2259 'TexStorage2DEXT': {
2260 'unit_test': False,
2261 'extension': True,
2262 'decoder_func': 'DoTexStorage2DEXT',
2264 'DrawArraysInstancedANGLE': {
2265 'type': 'Manual',
2266 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2267 'GLsizei primcount',
2268 'extension': True,
2269 'unit_test': False,
2270 'pepper_interface': 'InstancedArrays',
2271 'defer_draws': True,
2273 'DrawBuffersEXT': {
2274 'type': 'PUTn',
2275 'decoder_func': 'DoDrawBuffersEXT',
2276 'data_type': 'GLenum',
2277 'count': 1,
2278 'client_test': False,
2279 'unit_test': False,
2280 'extension': True,
2282 'DrawElementsInstancedANGLE': {
2283 'type': 'Manual',
2284 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2285 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2286 'extension': True,
2287 'unit_test': False,
2288 'client_test': False,
2289 'pepper_interface': 'InstancedArrays',
2290 'defer_draws': True,
2292 'VertexAttribDivisorANGLE': {
2293 'type': 'Manual',
2294 'cmd_args': 'GLuint index, GLuint divisor',
2295 'extension': True,
2296 'unit_test': False,
2297 'pepper_interface': 'InstancedArrays',
2299 'GenQueriesEXT': {
2300 'type': 'GENn',
2301 'gl_test_func': 'glGenQueriesARB',
2302 'resource_type': 'Query',
2303 'resource_types': 'Queries',
2304 'unit_test': False,
2305 'pepper_interface': 'Query',
2307 'DeleteQueriesEXT': {
2308 'type': 'DELn',
2309 'gl_test_func': 'glDeleteQueriesARB',
2310 'resource_type': 'Query',
2311 'resource_types': 'Queries',
2312 'unit_test': False,
2313 'pepper_interface': 'Query',
2315 'IsQueryEXT': {
2316 'gen_cmd': False,
2317 'client_test': False,
2318 'pepper_interface': 'Query',
2320 'BeginQueryEXT': {
2321 'type': 'Manual',
2322 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2323 'immediate': False,
2324 'gl_test_func': 'glBeginQuery',
2325 'pepper_interface': 'Query',
2327 'EndQueryEXT': {
2328 'type': 'Manual',
2329 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2330 'gl_test_func': 'glEndnQuery',
2331 'client_test': False,
2332 'pepper_interface': 'Query',
2334 'GetQueryivEXT': {
2335 'gen_cmd': False,
2336 'client_test': False,
2337 'gl_test_func': 'glGetQueryiv',
2338 'pepper_interface': 'Query',
2340 'GetQueryObjectuivEXT': {
2341 'gen_cmd': False,
2342 'client_test': False,
2343 'gl_test_func': 'glGetQueryObjectuiv',
2344 'pepper_interface': 'Query',
2346 'BindUniformLocationCHROMIUM': {
2347 'type': 'GLchar',
2348 'extension': True,
2349 'bucket': True,
2350 'needs_size': True,
2351 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2352 'immediate': False,
2354 'InsertEventMarkerEXT': {
2355 'type': 'GLcharN',
2356 'decoder_func': 'DoInsertEventMarkerEXT',
2357 'expectation': False,
2358 'extension': True,
2360 'PushGroupMarkerEXT': {
2361 'type': 'GLcharN',
2362 'decoder_func': 'DoPushGroupMarkerEXT',
2363 'expectation': False,
2364 'extension': True,
2366 'PopGroupMarkerEXT': {
2367 'decoder_func': 'DoPopGroupMarkerEXT',
2368 'expectation': False,
2369 'extension': True,
2370 'impl_func': False,
2373 'GenVertexArraysOES': {
2374 'type': 'GENn',
2375 'extension': True,
2376 'gl_test_func': 'glGenVertexArraysOES',
2377 'resource_type': 'VertexArray',
2378 'resource_types': 'VertexArrays',
2379 'unit_test': False,
2381 'BindVertexArrayOES': {
2382 'type': 'Bind',
2383 'extension': True,
2384 'gl_test_func': 'glBindVertexArrayOES',
2385 'decoder_func': 'DoBindVertexArrayOES',
2386 'gen_func': 'GenVertexArraysOES',
2387 'unit_test': False,
2388 'client_test': False,
2390 'DeleteVertexArraysOES': {
2391 'type': 'DELn',
2392 'extension': True,
2393 'gl_test_func': 'glDeleteVertexArraysOES',
2394 'resource_type': 'VertexArray',
2395 'resource_types': 'VertexArrays',
2396 'unit_test': False,
2398 'IsVertexArrayOES': {
2399 'type': 'Is',
2400 'extension': True,
2401 'gl_test_func': 'glIsVertexArrayOES',
2402 'decoder_func': 'DoIsVertexArrayOES',
2403 'expectation': False,
2404 'unit_test': False,
2406 'BindTexImage2DCHROMIUM': {
2407 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2408 'unit_test': False,
2409 'extension': True,
2410 'chromium': True,
2412 'ReleaseTexImage2DCHROMIUM': {
2413 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2414 'unit_test': False,
2415 'extension': True,
2416 'chromium': True,
2418 'ShallowFinishCHROMIUM': {
2419 'impl_func': False,
2420 'gen_cmd': False,
2421 'extension': True,
2422 'chromium': True,
2423 'client_test': False,
2425 'ShallowFlushCHROMIUM': {
2426 'impl_func': False,
2427 'gen_cmd': False,
2428 'extension': True,
2429 'chromium': True,
2430 'client_test': False,
2432 'TraceBeginCHROMIUM': {
2433 'type': 'Custom',
2434 'impl_func': False,
2435 'immediate': False,
2436 'client_test': False,
2437 'cmd_args': 'GLuint bucket_id',
2438 'extension': True,
2439 'chromium': True,
2441 'TraceEndCHROMIUM': {
2442 'impl_func': False,
2443 'immediate': False,
2444 'client_test': False,
2445 'decoder_func': 'DoTraceEndCHROMIUM',
2446 'unit_test': False,
2447 'extension': True,
2448 'chromium': True,
2450 'AsyncTexImage2DCHROMIUM': {
2451 'type': 'Manual',
2452 'immediate': False,
2453 'client_test': False,
2454 'extension': True,
2455 'chromium': True,
2457 'AsyncTexSubImage2DCHROMIUM': {
2458 'type': 'Manual',
2459 'immediate': False,
2460 'client_test': False,
2461 'extension': True,
2462 'chromium': True,
2464 'WaitAsyncTexImage2DCHROMIUM': {
2465 'type': 'Manual',
2466 'immediate': False,
2467 'client_test': False,
2468 'extension': True,
2469 'chromium': True,
2471 'DiscardFramebufferEXT': {
2472 'type': 'PUTn',
2473 'count': 1,
2474 'data_type': 'GLenum',
2475 'cmd_args': 'GLenum target, GLsizei count, '
2476 'const GLenum* attachments',
2477 'decoder_func': 'DoDiscardFramebufferEXT',
2478 'unit_test': False,
2479 'client_test': False,
2480 'extension': True,
2482 'LoseContextCHROMIUM': {
2483 'type': 'Manual',
2484 'impl_func': True,
2485 'extension': True,
2486 'chromium': True,
2488 'InsertSyncPointCHROMIUM': {
2489 'type': 'HandWritten',
2490 'impl_func': False,
2491 'extension': True,
2492 'chromium': True,
2494 'WaitSyncPointCHROMIUM': {
2495 'type': 'Custom',
2496 'impl_func': True,
2497 'extension': True,
2498 'chromium': True,
2499 'trace_level': 1,
2501 'DiscardBackbufferCHROMIUM': {
2502 'type': 'Custom',
2503 'impl_func': True,
2504 'extension': True,
2505 'chromium': True,
2510 def Grouper(n, iterable, fillvalue=None):
2511 """Collect data into fixed-length chunks or blocks"""
2512 args = [iter(iterable)] * n
2513 return itertools.izip_longest(fillvalue=fillvalue, *args)
2516 def SplitWords(input_string):
2517 """Transforms a input_string into a list of lower-case components.
2519 Args:
2520 input_string: the input string.
2522 Returns:
2523 a list of lower-case words.
2525 if input_string.find('_') > -1:
2526 # 'some_TEXT_' -> 'some text'
2527 return input_string.replace('_', ' ').strip().lower().split()
2528 else:
2529 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2530 # mixed case.
2531 # look for capitalization to cut input_strings
2532 # 'SomeText' -> 'Some Text'
2533 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2534 # 'Vector3' -> 'Vector 3'
2535 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2536 return input_string.lower().split()
2539 def Lower(words):
2540 """Makes a lower-case identifier from words.
2542 Args:
2543 words: a list of lower-case words.
2545 Returns:
2546 the lower-case identifier.
2548 return '_'.join(words)
2551 def ToUnderscore(input_string):
2552 """converts CamelCase to camel_case."""
2553 words = SplitWords(input_string)
2554 return Lower(words)
2557 class CWriter(object):
2558 """Writes to a file formatting it for Google's style guidelines."""
2560 def __init__(self, filename):
2561 self.filename = filename
2562 self.file_num = 0
2563 self.content = []
2565 def SetFileNum(self, num):
2566 """Used to help write number files and tests."""
2567 self.file_num = num
2569 def Write(self, string):
2570 """Writes a string to a file spliting if it's > 80 characters."""
2571 lines = string.splitlines()
2572 num_lines = len(lines)
2573 for ii in range(0, num_lines):
2574 self.__WriteLine(lines[ii], ii < (num_lines - 1) or string[-1] == '\n')
2576 def __FindSplit(self, string):
2577 """Finds a place to split a string."""
2578 splitter = string.find('=')
2579 if splitter >= 1 and not string[splitter + 1] == '=' and splitter < 80:
2580 return splitter
2581 # parts = string.split('(')
2582 parts = re.split("(?<=[^\"])\((?!\")", string)
2583 fptr = re.compile('\*\w*\)')
2584 if len(parts) > 1:
2585 splitter = len(parts[0])
2586 for ii in range(1, len(parts)):
2587 # Don't split on the dot in "if (.condition)".
2588 if (not parts[ii - 1][-3:] == "if " and
2589 # Don't split "(.)" or "(.*fptr)".
2590 (len(parts[ii]) > 0 and
2591 not parts[ii][0] == ")" and not fptr.match(parts[ii]))
2592 and splitter < 80):
2593 return splitter
2594 splitter += len(parts[ii]) + 1
2595 done = False
2596 end = len(string)
2597 last_splitter = -1
2598 while not done:
2599 splitter = string[0:end].rfind(',')
2600 if splitter < 0 or (splitter > 0 and string[splitter - 1] == '"'):
2601 return last_splitter
2602 elif splitter >= 80:
2603 end = splitter
2604 else:
2605 return splitter
2607 def __WriteLine(self, line, ends_with_eol):
2608 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2609 if len(line) >= 80:
2610 i = self.__FindSplit(line)
2611 if i > 0:
2612 line1 = line[0:i + 1]
2613 if line1[-1] == ' ':
2614 line1 = line1[:-1]
2615 lineend = ''
2616 if line1[0] == '#':
2617 lineend = ' \\'
2618 nolint = ''
2619 if len(line1) > 80:
2620 nolint = ' // NOLINT'
2621 self.__AddLine(line1 + nolint + lineend + '\n')
2622 match = re.match("( +)", line1)
2623 indent = ""
2624 if match:
2625 indent = match.group(1)
2626 splitter = line[i]
2627 if not splitter == ',':
2628 indent = " " + indent
2629 self.__WriteLine(indent + line[i + 1:].lstrip(), True)
2630 return
2631 nolint = ''
2632 if len(line) > 80:
2633 nolint = ' // NOLINT'
2634 self.__AddLine(line + nolint)
2635 if ends_with_eol:
2636 self.__AddLine('\n')
2638 def __AddLine(self, line):
2639 self.content.append(line)
2641 def Close(self):
2642 """Close the file."""
2643 content = "".join(self.content)
2644 write_file = True
2645 if os.path.exists(self.filename):
2646 old_file = open(self.filename, "rb");
2647 old_content = old_file.read()
2648 old_file.close();
2649 if content == old_content:
2650 write_file = False
2651 if write_file:
2652 file = open(self.filename, "wb")
2653 file.write(content)
2654 file.close()
2657 class CHeaderWriter(CWriter):
2658 """Writes a C Header file."""
2660 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2662 def __init__(self, filename, file_comment = None):
2663 CWriter.__init__(self, filename)
2665 base = os.path.abspath(filename)
2666 while os.path.basename(base) != 'src':
2667 new_base = os.path.dirname(base)
2668 assert new_base != base # Prevent infinite loop.
2669 base = new_base
2671 hpath = os.path.relpath(filename, base)
2672 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2674 self.Write(_LICENSE)
2675 self.Write(_DO_NOT_EDIT_WARNING)
2676 if not file_comment == None:
2677 self.Write(file_comment)
2678 self.Write("#ifndef %s\n" % self.guard)
2679 self.Write("#define %s\n\n" % self.guard)
2681 def Close(self):
2682 self.Write("#endif // %s\n\n" % self.guard)
2683 CWriter.Close(self)
2685 class TypeHandler(object):
2686 """This class emits code for a particular type of function."""
2688 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2690 def __init__(self):
2691 pass
2693 def InitFunction(self, func):
2694 """Add or adjust anything type specific for this function."""
2695 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2696 func.AddCmdArg(DataSizeArgument('data_size'))
2698 def AddImmediateFunction(self, generator, func):
2699 """Adds an immediate version of a function."""
2700 # Generate an immediate command if there is only 1 pointer arg.
2701 immediate = func.GetInfo('immediate') # can be True, False or None
2702 if immediate == True or immediate == None:
2703 if func.num_pointer_args == 1 or immediate:
2704 generator.AddFunction(ImmediateFunction(func))
2706 def AddBucketFunction(self, generator, func):
2707 """Adds a bucket version of a function."""
2708 # Generate an immediate command if there is only 1 pointer arg.
2709 bucket = func.GetInfo('bucket') # can be True, False or None
2710 if bucket:
2711 generator.AddFunction(BucketFunction(func))
2713 def WriteStruct(self, func, file):
2714 """Writes a structure that matches the arguments to a function."""
2715 comment = func.GetInfo('cmd_comment')
2716 if not comment == None:
2717 file.Write(comment)
2718 file.Write("struct %s {\n" % func.name)
2719 file.Write(" typedef %s ValueType;\n" % func.name)
2720 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2721 func.WriteCmdArgFlag(file)
2722 func.WriteCmdFlag(file)
2723 file.Write("\n")
2724 result = func.GetInfo('result')
2725 if not result == None:
2726 if len(result) == 1:
2727 file.Write(" typedef %s Result;\n\n" % result[0])
2728 else:
2729 file.Write(" struct Result {\n")
2730 for line in result:
2731 file.Write(" %s;\n" % line)
2732 file.Write(" };\n\n")
2734 func.WriteCmdComputeSize(file)
2735 func.WriteCmdSetHeader(file)
2736 func.WriteCmdInit(file)
2737 func.WriteCmdSet(file)
2739 file.Write(" gpu::CommandHeader header;\n")
2740 args = func.GetCmdArgs()
2741 for arg in args:
2742 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2743 file.Write("};\n")
2744 file.Write("\n")
2746 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2747 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2748 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2749 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2750 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2751 offset = _SIZE_OF_COMMAND_HEADER
2752 for arg in args:
2753 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2754 (func.name, arg.name, offset))
2755 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2756 (func.name, arg.name, offset))
2757 offset += _SIZE_OF_UINT32
2758 if not result == None and len(result) > 1:
2759 offset = 0;
2760 for line in result:
2761 parts = line.split()
2762 name = parts[-1]
2763 check = """
2764 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2765 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2767 file.Write((check.strip() + "\n") % {
2768 'cmd_name': func.name,
2769 'field_name': name,
2770 'offset': offset,
2772 offset += _SIZE_OF_UINT32
2773 file.Write("\n")
2775 def WriteHandlerImplementation(self, func, file):
2776 """Writes the handler implementation for this command."""
2777 file.Write(" %s(%s);\n" %
2778 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2780 def WriteCmdSizeTest(self, func, file):
2781 """Writes the size test for a command."""
2782 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2784 def WriteFormatTest(self, func, file):
2785 """Writes a format test for a command."""
2786 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2787 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2788 (func.name, func.name))
2789 file.Write(" void* next_cmd = cmd.Set(\n")
2790 file.Write(" &cmd")
2791 args = func.GetCmdArgs()
2792 for value, arg in enumerate(args):
2793 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2794 file.Write(");\n")
2795 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2796 func.name)
2797 file.Write(" cmd.header.command);\n")
2798 func.type_handler.WriteCmdSizeTest(func, file)
2799 for value, arg in enumerate(args):
2800 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2801 (arg.type, value + 11, arg.name))
2802 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2803 file.Write(" next_cmd, sizeof(cmd));\n")
2804 file.Write("}\n")
2805 file.Write("\n")
2807 def WriteImmediateFormatTest(self, func, file):
2808 """Writes a format test for an immediate version of a command."""
2809 pass
2811 def WriteBucketFormatTest(self, func, file):
2812 """Writes a format test for a bucket version of a command."""
2813 pass
2815 def WriteGetDataSizeCode(self, func, file):
2816 """Writes the code to set data_size used in validation"""
2817 pass
2819 def WriteImmediateCmdSizeTest(self, func, file):
2820 """Writes a size test for an immediate version of a command."""
2821 file.Write(" // TODO(gman): Compute correct size.\n")
2822 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2824 def WriteImmediateHandlerImplementation (self, func, file):
2825 """Writes the handler impl for the immediate version of a command."""
2826 file.Write(" %s(%s);\n" %
2827 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2829 def WriteBucketHandlerImplementation (self, func, file):
2830 """Writes the handler impl for the bucket version of a command."""
2831 file.Write(" %s(%s);\n" %
2832 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2834 def WriteServiceImplementation(self, func, file):
2835 """Writes the service implementation for a command."""
2836 file.Write(
2837 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2838 file.Write(
2839 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2840 func.name)
2841 self.WriteHandlerDeferReadWrite(func, file);
2842 if len(func.GetOriginalArgs()) > 0:
2843 last_arg = func.GetLastOriginalArg()
2844 all_but_last_arg = func.GetOriginalArgs()[:-1]
2845 for arg in all_but_last_arg:
2846 arg.WriteGetCode(file)
2847 self.WriteGetDataSizeCode(func, file)
2848 last_arg.WriteGetCode(file)
2849 func.WriteHandlerValidation(file)
2850 func.WriteHandlerImplementation(file)
2851 file.Write(" return error::kNoError;\n")
2852 file.Write("}\n")
2853 file.Write("\n")
2855 def WriteImmediateServiceImplementation(self, func, file):
2856 """Writes the service implementation for an immediate version of command."""
2857 file.Write(
2858 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2859 file.Write(
2860 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2861 func.name)
2862 self.WriteHandlerDeferReadWrite(func, file);
2863 last_arg = func.GetLastOriginalArg()
2864 all_but_last_arg = func.GetOriginalArgs()[:-1]
2865 for arg in all_but_last_arg:
2866 arg.WriteGetCode(file)
2867 self.WriteGetDataSizeCode(func, file)
2868 last_arg.WriteGetCode(file)
2869 func.WriteHandlerValidation(file)
2870 func.WriteHandlerImplementation(file)
2871 file.Write(" return error::kNoError;\n")
2872 file.Write("}\n")
2873 file.Write("\n")
2875 def WriteBucketServiceImplementation(self, func, file):
2876 """Writes the service implementation for a bucket version of command."""
2877 file.Write(
2878 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2879 file.Write(
2880 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2881 func.name)
2882 self.WriteHandlerDeferReadWrite(func, file);
2883 last_arg = func.GetLastOriginalArg()
2884 all_but_last_arg = func.GetOriginalArgs()[:-1]
2885 for arg in all_but_last_arg:
2886 arg.WriteGetCode(file)
2887 self.WriteGetDataSizeCode(func, file)
2888 last_arg.WriteGetCode(file)
2889 func.WriteHandlerValidation(file)
2890 func.WriteHandlerImplementation(file)
2891 file.Write(" return error::kNoError;\n")
2892 file.Write("}\n")
2893 file.Write("\n")
2895 def WriteHandlerDeferReadWrite(self, func, file):
2896 """Writes the code to handle deferring reads or writes."""
2897 defer_draws = func.GetInfo('defer_draws')
2898 defer_reads = func.GetInfo('defer_reads')
2899 if defer_draws or defer_reads:
2900 file.Write(" error::Error error;\n")
2901 if defer_draws:
2902 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2903 file.Write(" if (error != error::kNoError)\n")
2904 file.Write(" return error;\n")
2905 if defer_reads:
2906 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2907 file.Write(" if (error != error::kNoError)\n")
2908 file.Write(" return error;\n")
2910 def WriteValidUnitTest(self, func, file, test, extra = {}):
2911 """Writes a valid unit test."""
2912 if func.GetInfo('expectation') == False:
2913 test = self._remove_expected_call_re.sub('', test)
2914 name = func.name
2915 arg_strings = []
2916 for count, arg in enumerate(func.GetOriginalArgs()):
2917 arg_strings.append(arg.GetValidArg(func, count, 0))
2918 gl_arg_strings = []
2919 for count, arg in enumerate(func.GetOriginalArgs()):
2920 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2921 gl_func_name = func.GetGLTestFunctionName()
2922 vars = {
2923 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2924 'name':name,
2925 'gl_func_name': gl_func_name,
2926 'args': ", ".join(arg_strings),
2927 'gl_args': ", ".join(gl_arg_strings),
2929 vars.update(extra)
2930 old_test = ""
2931 while (old_test != test):
2932 old_test = test
2933 test = test % vars
2934 file.Write(test % vars)
2936 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2937 """Writes a invalid unit test."""
2938 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2939 num_invalid_values = arg.GetNumInvalidValues(func)
2940 for value_index in range(0, num_invalid_values):
2941 arg_strings = []
2942 parse_result = "kNoError"
2943 gl_error = None
2944 for count, arg in enumerate(func.GetOriginalArgs()):
2945 if count == arg_index:
2946 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2947 count, value_index)
2948 else:
2949 arg_string = arg.GetValidArg(func, count, 0)
2950 arg_strings.append(arg_string)
2951 gl_arg_strings = []
2952 for arg in func.GetOriginalArgs():
2953 gl_arg_strings.append("_")
2954 gl_func_name = func.GetGLTestFunctionName()
2955 gl_error_test = ''
2956 if not gl_error == None:
2957 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2959 vars = {
2960 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2961 'name': func.name,
2962 'arg_index': arg_index,
2963 'value_index': value_index,
2964 'gl_func_name': gl_func_name,
2965 'args': ", ".join(arg_strings),
2966 'all_but_last_args': ", ".join(arg_strings[:-1]),
2967 'gl_args': ", ".join(gl_arg_strings),
2968 'parse_result': parse_result,
2969 'gl_error_test': gl_error_test,
2971 vars.update(extra)
2972 file.Write(test % vars)
2974 def WriteServiceUnitTest(self, func, file):
2975 """Writes the service unit test for a command."""
2976 valid_test = """
2977 TEST_F(%(test_name)s, %(name)sValidArgs) {
2978 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2979 SpecializedSetup<cmds::%(name)s, 0>(true);
2980 cmds::%(name)s cmd;
2981 cmd.Init(%(args)s);
2982 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2983 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2986 self.WriteValidUnitTest(func, file, valid_test)
2988 invalid_test = """
2989 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2990 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2991 SpecializedSetup<cmds::%(name)s, 0>(false);
2992 cmds::%(name)s cmd;
2993 cmd.Init(%(args)s);
2994 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2997 self.WriteInvalidUnitTest(func, file, invalid_test)
2999 def WriteImmediateServiceUnitTest(self, func, file):
3000 """Writes the service unit test for an immediate command."""
3001 file.Write("// TODO(gman): %s\n" % func.name)
3003 def WriteImmediateValidationCode(self, func, file):
3004 """Writes the validation code for an immediate version of a command."""
3005 pass
3007 def WriteBucketServiceUnitTest(self, func, file):
3008 """Writes the service unit test for a bucket command."""
3009 file.Write("// TODO(gman): %s\n" % func.name)
3011 def WriteBucketValidationCode(self, func, file):
3012 """Writes the validation code for a bucket version of a command."""
3013 file.Write("// TODO(gman): %s\n" % func.name)
3015 def WriteGLES2ImplementationDeclaration(self, func, file):
3016 """Writes the GLES2 Implemention declaration."""
3017 impl_decl = func.GetInfo('impl_decl')
3018 if impl_decl == None or impl_decl == True:
3019 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3020 (func.return_type, func.original_name,
3021 func.MakeTypedOriginalArgString("")))
3022 file.Write("\n")
3024 def WriteGLES2CLibImplementation(self, func, file):
3025 file.Write("%s GLES2%s(%s) {\n" %
3026 (func.return_type, func.name,
3027 func.MakeTypedOriginalArgString("")))
3028 result_string = "return "
3029 if func.return_type == "void":
3030 result_string = ""
3031 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3032 (result_string, func.original_name,
3033 func.MakeOriginalArgString("")))
3034 file.Write("}\n")
3036 def WriteGLES2Header(self, func, file):
3037 """Writes a re-write macro for GLES"""
3038 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3040 def WriteClientGLCallLog(self, func, file):
3041 """Writes a logging macro for the client side code."""
3042 comma = ""
3043 if len(func.GetOriginalArgs()):
3044 comma = " << "
3045 file.Write(
3046 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3047 (func.original_name, comma, func.MakeLogArgString()))
3049 def WriteClientGLReturnLog(self, func, file):
3050 """Writes the return value logging code."""
3051 if func.return_type != "void":
3052 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3054 def WriteGLES2ImplementationHeader(self, func, file):
3055 """Writes the GLES2 Implemention."""
3056 self.WriteGLES2ImplementationDeclaration(func, file)
3058 def WriteGLES2TraceImplementationHeader(self, func, file):
3059 """Writes the GLES2 Trace Implemention header."""
3060 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3061 (func.return_type, func.original_name,
3062 func.MakeTypedOriginalArgString("")))
3064 def WriteGLES2TraceImplementation(self, func, file):
3065 """Writes the GLES2 Trace Implemention."""
3066 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3067 (func.return_type, func.original_name,
3068 func.MakeTypedOriginalArgString("")))
3069 result_string = "return "
3070 if func.return_type == "void":
3071 result_string = ""
3072 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3073 func.name)
3074 file.Write(" %sgl_->%s(%s);\n" %
3075 (result_string, func.name, func.MakeOriginalArgString("")))
3076 file.Write("}\n")
3077 file.Write("\n")
3079 def WriteGLES2Implementation(self, func, file):
3080 """Writes the GLES2 Implemention."""
3081 impl_func = func.GetInfo('impl_func')
3082 impl_decl = func.GetInfo('impl_decl')
3083 gen_cmd = func.GetInfo('gen_cmd')
3084 if (func.can_auto_generate and
3085 (impl_func == None or impl_func == True) and
3086 (impl_decl == None or impl_decl == True) and
3087 (gen_cmd == None or gen_cmd == True)):
3088 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3089 (func.return_type, func.original_name,
3090 func.MakeTypedOriginalArgString("")))
3091 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3092 self.WriteClientGLCallLog(func, file)
3093 func.WriteDestinationInitalizationValidation(file)
3094 for arg in func.GetOriginalArgs():
3095 arg.WriteClientSideValidationCode(file, func)
3096 file.Write(" helper_->%s(%s);\n" %
3097 (func.name, func.MakeOriginalArgString("")))
3098 file.Write(" CheckGLError();\n")
3099 self.WriteClientGLReturnLog(func, file)
3100 file.Write("}\n")
3101 file.Write("\n")
3103 def WriteGLES2InterfaceHeader(self, func, file):
3104 """Writes the GLES2 Interface."""
3105 file.Write("virtual %s %s(%s) = 0;\n" %
3106 (func.return_type, func.original_name,
3107 func.MakeTypedOriginalArgString("")))
3109 def WriteGLES2InterfaceStub(self, func, file):
3110 """Writes the GLES2 Interface stub declaration."""
3111 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3112 (func.return_type, func.original_name,
3113 func.MakeTypedOriginalArgString("")))
3115 def WriteGLES2InterfaceStubImpl(self, func, file):
3116 """Writes the GLES2 Interface stub declaration."""
3117 args = func.GetOriginalArgs()
3118 arg_string = ", ".join(
3119 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3120 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3121 (func.return_type, func.original_name, arg_string))
3122 if func.return_type != "void":
3123 file.Write(" return 0;\n")
3124 file.Write("}\n")
3126 def WriteGLES2ImplementationUnitTest(self, func, file):
3127 """Writes the GLES2 Implemention unit test."""
3128 client_test = func.GetInfo('client_test')
3129 if (func.can_auto_generate and
3130 (client_test == None or client_test == True)):
3131 code = """
3132 TEST_F(GLES2ImplementationTest, %(name)s) {
3133 struct Cmds {
3134 cmds::%(name)s cmd;
3136 Cmds expected;
3137 expected.cmd.Init(%(cmd_args)s);
3139 gl_->%(name)s(%(args)s);
3140 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3143 cmd_arg_strings = []
3144 for count, arg in enumerate(func.GetCmdArgs()):
3145 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3146 count += 1
3147 gl_arg_strings = []
3148 for count, arg in enumerate(func.GetOriginalArgs()):
3149 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3150 file.Write(code % {
3151 'name': func.name,
3152 'args': ", ".join(gl_arg_strings),
3153 'cmd_args': ", ".join(cmd_arg_strings),
3155 else:
3156 if client_test != False:
3157 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3159 def WriteDestinationInitalizationValidation(self, func, file):
3160 """Writes the client side destintion initialization validation."""
3161 for arg in func.GetOriginalArgs():
3162 arg.WriteDestinationInitalizationValidation(file, func)
3164 def WriteTraceEvent(self, func, file):
3165 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3166 func.original_name)
3168 def WriteImmediateCmdComputeSize(self, func, file):
3169 """Writes the size computation code for the immediate version of a cmd."""
3170 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3171 file.Write(" return static_cast<uint32>(\n")
3172 file.Write(" sizeof(ValueType) + // NOLINT\n")
3173 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3174 file.Write(" }\n")
3175 file.Write("\n")
3177 def WriteImmediateCmdSetHeader(self, func, file):
3178 """Writes the SetHeader function for the immediate version of a cmd."""
3179 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3180 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3181 file.Write(" }\n")
3182 file.Write("\n")
3184 def WriteImmediateCmdInit(self, func, file):
3185 """Writes the Init function for the immediate version of a command."""
3186 raise NotImplementedError(func.name)
3188 def WriteImmediateCmdSet(self, func, file):
3189 """Writes the Set function for the immediate version of a command."""
3190 raise NotImplementedError(func.name)
3192 def WriteCmdHelper(self, func, file):
3193 """Writes the cmd helper definition for a cmd."""
3194 code = """ void %(name)s(%(typed_args)s) {
3195 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3196 if (c) {
3197 c->Init(%(args)s);
3202 file.Write(code % {
3203 "name": func.name,
3204 "typed_args": func.MakeTypedCmdArgString(""),
3205 "args": func.MakeCmdArgString(""),
3208 def WriteImmediateCmdHelper(self, func, file):
3209 """Writes the cmd helper definition for the immediate version of a cmd."""
3210 code = """ void %(name)s(%(typed_args)s) {
3211 const uint32 s = 0; // TODO(gman): compute correct size
3212 gles2::cmds::%(name)s* c =
3213 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3214 if (c) {
3215 c->Init(%(args)s);
3220 file.Write(code % {
3221 "name": func.name,
3222 "typed_args": func.MakeTypedCmdArgString(""),
3223 "args": func.MakeCmdArgString(""),
3227 class StateSetHandler(TypeHandler):
3228 """Handler for commands that simply set state."""
3230 def __init__(self):
3231 TypeHandler.__init__(self)
3233 def WriteHandlerImplementation(self, func, file):
3234 """Overrriden from TypeHandler."""
3235 state_name = func.GetInfo('state')
3236 state = _STATES[state_name]
3237 states = state['states']
3238 args = func.GetOriginalArgs()
3239 code = []
3240 for ndx,item in enumerate(states):
3241 if 'range_checks' in item:
3242 for range_check in item['range_checks']:
3243 code.append("%s %s" % (args[ndx].name, range_check['check']))
3244 if len(code):
3245 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3246 file.Write(
3247 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3248 ' "%s", "%s out of range");\n' %
3249 (func.name, args[ndx].name))
3250 file.Write(" return error::kNoError;\n")
3251 file.Write(" }\n")
3252 code = []
3253 for ndx,item in enumerate(states):
3254 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3255 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3256 for ndx,item in enumerate(states):
3257 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3258 if 'state_flag' in state:
3259 file.Write(" %s = true;\n" % state['state_flag'])
3260 if not func.GetInfo("no_gl"):
3261 file.Write(" %s(%s);\n" %
3262 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3263 file.Write(" }\n")
3265 def WriteServiceUnitTest(self, func, file):
3266 """Overrriden from TypeHandler."""
3267 TypeHandler.WriteServiceUnitTest(self, func, file)
3268 state_name = func.GetInfo('state')
3269 state = _STATES[state_name]
3270 states = state['states']
3271 for ndx,item in enumerate(states):
3272 if 'range_checks' in item:
3273 for check_ndx, range_check in enumerate(item['range_checks']):
3274 valid_test = """
3275 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3276 SpecializedSetup<cmds::%(name)s, 0>(false);
3277 cmds::%(name)s cmd;
3278 cmd.Init(%(args)s);
3279 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3280 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3283 name = func.name
3284 arg_strings = []
3285 for count, arg in enumerate(func.GetOriginalArgs()):
3286 arg_strings.append(arg.GetValidArg(func, count, 0))
3287 arg_strings[ndx] = range_check['test_value']
3288 vars = {
3289 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3290 'name': name,
3291 'ndx': ndx,
3292 'check_ndx': check_ndx,
3293 'args': ", ".join(arg_strings),
3295 file.Write(valid_test % vars)
3298 class StateSetRGBAlphaHandler(TypeHandler):
3299 """Handler for commands that simply set state that have rgb/alpha."""
3301 def __init__(self):
3302 TypeHandler.__init__(self)
3304 def WriteHandlerImplementation(self, func, file):
3305 """Overrriden from TypeHandler."""
3306 state_name = func.GetInfo('state')
3307 state = _STATES[state_name]
3308 states = state['states']
3309 args = func.GetOriginalArgs()
3310 num_args = len(args)
3311 code = []
3312 for ndx,item in enumerate(states):
3313 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3314 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3315 for ndx, item in enumerate(states):
3316 file.Write(" state_.%s = %s;\n" %
3317 (item['name'], args[ndx % num_args].name))
3318 if 'state_flag' in state:
3319 file.Write(" %s = true;\n" % state['state_flag'])
3320 if not func.GetInfo("no_gl"):
3321 file.Write(" %s(%s);\n" %
3322 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3323 file.Write(" }\n")
3326 class StateSetFrontBackSeparateHandler(TypeHandler):
3327 """Handler for commands that simply set state that have front/back."""
3329 def __init__(self):
3330 TypeHandler.__init__(self)
3332 def WriteHandlerImplementation(self, func, file):
3333 """Overrriden from TypeHandler."""
3334 state_name = func.GetInfo('state')
3335 state = _STATES[state_name]
3336 states = state['states']
3337 args = func.GetOriginalArgs()
3338 face = args[0].name
3339 num_args = len(args)
3340 file.Write(" bool changed = false;\n")
3341 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3342 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3343 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3344 code = []
3345 for ndx, item in enumerate(group):
3346 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3347 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3348 file.Write(" }\n")
3349 file.Write(" if (changed) {\n")
3350 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3351 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3352 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3353 for ndx, item in enumerate(group):
3354 file.Write(" state_.%s = %s;\n" %
3355 (item['name'], args[ndx + 1].name))
3356 file.Write(" }\n")
3357 if 'state_flag' in state:
3358 file.Write(" %s = true;\n" % state['state_flag'])
3359 if not func.GetInfo("no_gl"):
3360 file.Write(" %s(%s);\n" %
3361 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3362 file.Write(" }\n")
3365 class StateSetFrontBackHandler(TypeHandler):
3366 """Handler for commands that simply set state that set both front/back."""
3368 def __init__(self):
3369 TypeHandler.__init__(self)
3371 def WriteHandlerImplementation(self, func, file):
3372 """Overrriden from TypeHandler."""
3373 state_name = func.GetInfo('state')
3374 state = _STATES[state_name]
3375 states = state['states']
3376 args = func.GetOriginalArgs()
3377 num_args = len(args)
3378 code = []
3379 for group_ndx, group in enumerate(Grouper(num_args, states)):
3380 for ndx, item in enumerate(group):
3381 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3382 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3383 for group_ndx, group in enumerate(Grouper(num_args, states)):
3384 for ndx, item in enumerate(group):
3385 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3386 if 'state_flag' in state:
3387 file.Write(" %s = true;\n" % state['state_flag'])
3388 if not func.GetInfo("no_gl"):
3389 file.Write(" %s(%s);\n" %
3390 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3391 file.Write(" }\n")
3394 class StateSetNamedParameter(TypeHandler):
3395 """Handler for commands that set a state chosen with an enum parameter."""
3397 def __init__(self):
3398 TypeHandler.__init__(self)
3400 def WriteHandlerImplementation(self, func, file):
3401 """Overridden from TypeHandler."""
3402 state_name = func.GetInfo('state')
3403 state = _STATES[state_name]
3404 states = state['states']
3405 args = func.GetOriginalArgs()
3406 num_args = len(args)
3407 assert num_args == 2
3408 file.Write(" switch (%s) {\n" % args[0].name)
3409 for state in states:
3410 file.Write(" case %s:\n" % state['enum'])
3411 file.Write(" if (state_.%s != %s) {\n" %
3412 (state['name'], args[1].name))
3413 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3414 if not func.GetInfo("no_gl"):
3415 file.Write(" %s(%s);\n" %
3416 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3417 file.Write(" }\n")
3418 file.Write(" break;\n")
3419 file.Write(" default:\n")
3420 file.Write(" NOTREACHED();\n")
3421 file.Write(" }\n")
3424 class CustomHandler(TypeHandler):
3425 """Handler for commands that are auto-generated but require minor tweaks."""
3427 def __init__(self):
3428 TypeHandler.__init__(self)
3430 def WriteServiceImplementation(self, func, file):
3431 """Overrriden from TypeHandler."""
3432 pass
3434 def WriteImmediateServiceImplementation(self, func, file):
3435 """Overrriden from TypeHandler."""
3436 pass
3438 def WriteBucketServiceImplementation(self, func, file):
3439 """Overrriden from TypeHandler."""
3440 pass
3442 def WriteServiceUnitTest(self, func, file):
3443 """Overrriden from TypeHandler."""
3444 file.Write("// TODO(gman): %s\n\n" % func.name)
3446 def WriteImmediateServiceUnitTest(self, func, file):
3447 """Overrriden from TypeHandler."""
3448 file.Write("// TODO(gman): %s\n\n" % func.name)
3450 def WriteImmediateCmdGetTotalSize(self, func, file):
3451 """Overrriden from TypeHandler."""
3452 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3454 def WriteImmediateCmdInit(self, func, file):
3455 """Overrriden from TypeHandler."""
3456 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3457 self.WriteImmediateCmdGetTotalSize(func, file)
3458 file.Write(" SetHeader(total_size);\n")
3459 args = func.GetCmdArgs()
3460 for arg in args:
3461 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3462 file.Write(" }\n")
3463 file.Write("\n")
3465 def WriteImmediateCmdSet(self, func, file):
3466 """Overrriden from TypeHandler."""
3467 copy_args = func.MakeCmdArgString("_", False)
3468 file.Write(" void* Set(void* cmd%s) {\n" %
3469 func.MakeTypedCmdArgString("_", True))
3470 self.WriteImmediateCmdGetTotalSize(func, file)
3471 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3472 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3473 "cmd, total_size);\n")
3474 file.Write(" }\n")
3475 file.Write("\n")
3478 class TodoHandler(CustomHandler):
3479 """Handle for commands that are not yet implemented."""
3481 def AddImmediateFunction(self, generator, func):
3482 """Overrriden from TypeHandler."""
3483 pass
3485 def WriteImmediateFormatTest(self, func, file):
3486 """Overrriden from TypeHandler."""
3487 pass
3489 def WriteGLES2ImplementationUnitTest(self, func, file):
3490 """Overrriden from TypeHandler."""
3491 pass
3493 def WriteGLES2Implementation(self, func, file):
3494 """Overrriden from TypeHandler."""
3495 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3496 (func.return_type, func.original_name,
3497 func.MakeTypedOriginalArgString("")))
3498 file.Write(" // TODO: for now this is a no-op\n")
3499 file.Write(
3500 " SetGLError("
3501 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3502 func.name)
3503 if func.return_type != "void":
3504 file.Write(" return 0;\n")
3505 file.Write("}\n")
3506 file.Write("\n")
3508 def WriteServiceImplementation(self, func, file):
3509 """Overrriden from TypeHandler."""
3510 file.Write(
3511 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3512 file.Write(
3513 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3514 func.name)
3515 file.Write(" // TODO: for now this is a no-op\n")
3516 file.Write(
3517 " LOCAL_SET_GL_ERROR("
3518 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3519 func.name)
3520 file.Write(" return error::kNoError;\n")
3521 file.Write("}\n")
3522 file.Write("\n")
3525 class HandWrittenHandler(CustomHandler):
3526 """Handler for comands where everything must be written by hand."""
3528 def InitFunction(self, func):
3529 """Add or adjust anything type specific for this function."""
3530 CustomHandler.InitFunction(self, func)
3531 func.can_auto_generate = False
3533 def WriteStruct(self, func, file):
3534 """Overrriden from TypeHandler."""
3535 pass
3537 def WriteDocs(self, func, file):
3538 """Overrriden from TypeHandler."""
3539 pass
3541 def WriteServiceUnitTest(self, func, file):
3542 """Overrriden from TypeHandler."""
3543 file.Write("// TODO(gman): %s\n\n" % func.name)
3545 def WriteImmediateServiceUnitTest(self, func, file):
3546 """Overrriden from TypeHandler."""
3547 file.Write("// TODO(gman): %s\n\n" % func.name)
3549 def WriteBucketServiceUnitTest(self, func, file):
3550 """Overrriden from TypeHandler."""
3551 file.Write("// TODO(gman): %s\n\n" % func.name)
3553 def WriteServiceImplementation(self, func, file):
3554 """Overrriden from TypeHandler."""
3555 pass
3557 def WriteImmediateServiceImplementation(self, func, file):
3558 """Overrriden from TypeHandler."""
3559 pass
3561 def WriteBucketServiceImplementation(self, func, file):
3562 """Overrriden from TypeHandler."""
3563 pass
3565 def WriteImmediateCmdHelper(self, func, file):
3566 """Overrriden from TypeHandler."""
3567 pass
3569 def WriteBucketCmdHelper(self, func, file):
3570 """Overrriden from TypeHandler."""
3571 pass
3573 def WriteCmdHelper(self, func, file):
3574 """Overrriden from TypeHandler."""
3575 pass
3577 def WriteFormatTest(self, func, file):
3578 """Overrriden from TypeHandler."""
3579 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3581 def WriteImmediateFormatTest(self, func, file):
3582 """Overrriden from TypeHandler."""
3583 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3585 def WriteBucketFormatTest(self, func, file):
3586 """Overrriden from TypeHandler."""
3587 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3591 class ManualHandler(CustomHandler):
3592 """Handler for commands who's handlers must be written by hand."""
3594 def __init__(self):
3595 CustomHandler.__init__(self)
3597 def InitFunction(self, func):
3598 """Overrriden from TypeHandler."""
3599 if (func.name == 'CompressedTexImage2DBucket'):
3600 func.cmd_args = func.cmd_args[:-1]
3601 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3602 else:
3603 CustomHandler.InitFunction(self, func)
3605 def WriteServiceImplementation(self, func, file):
3606 """Overrriden from TypeHandler."""
3607 pass
3609 def WriteBucketServiceImplementation(self, func, file):
3610 """Overrriden from TypeHandler."""
3611 pass
3613 def WriteServiceUnitTest(self, func, file):
3614 """Overrriden from TypeHandler."""
3615 file.Write("// TODO(gman): %s\n\n" % func.name)
3617 def WriteImmediateServiceUnitTest(self, func, file):
3618 """Overrriden from TypeHandler."""
3619 file.Write("// TODO(gman): %s\n\n" % func.name)
3621 def WriteImmediateServiceImplementation(self, func, file):
3622 """Overrriden from TypeHandler."""
3623 pass
3625 def WriteImmediateFormatTest(self, func, file):
3626 """Overrriden from TypeHandler."""
3627 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3629 def WriteGLES2Implementation(self, func, file):
3630 """Overrriden from TypeHandler."""
3631 if func.GetInfo('impl_func'):
3632 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3634 def WriteGLES2ImplementationHeader(self, func, file):
3635 """Overrriden from TypeHandler."""
3636 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3637 (func.return_type, func.original_name,
3638 func.MakeTypedOriginalArgString("")))
3639 file.Write("\n")
3641 def WriteImmediateCmdGetTotalSize(self, func, file):
3642 """Overrriden from TypeHandler."""
3643 # TODO(gman): Move this data to _FUNCTION_INFO?
3644 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3647 class DataHandler(TypeHandler):
3648 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3649 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3650 def __init__(self):
3651 TypeHandler.__init__(self)
3653 def InitFunction(self, func):
3654 """Overrriden from TypeHandler."""
3655 if func.name == 'CompressedTexSubImage2DBucket':
3656 func.cmd_args = func.cmd_args[:-1]
3657 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3659 def WriteGetDataSizeCode(self, func, file):
3660 """Overrriden from TypeHandler."""
3661 # TODO(gman): Move this data to _FUNCTION_INFO?
3662 name = func.name
3663 if name.endswith("Immediate"):
3664 name = name[0:-9]
3665 if name == 'BufferData' or name == 'BufferSubData':
3666 file.Write(" uint32 data_size = size;\n")
3667 elif (name == 'CompressedTexImage2D' or
3668 name == 'CompressedTexSubImage2D'):
3669 file.Write(" uint32 data_size = imageSize;\n")
3670 elif (name == 'CompressedTexSubImage2DBucket'):
3671 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3672 file.Write(" uint32 data_size = bucket->size();\n")
3673 file.Write(" GLsizei imageSize = data_size;\n")
3674 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3675 code = """ uint32 data_size;
3676 if (!GLES2Util::ComputeImageDataSize(
3677 width, height, format, type, unpack_alignment_, &data_size)) {
3678 return error::kOutOfBounds;
3681 file.Write(code)
3682 else:
3683 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3685 def WriteImmediateCmdGetTotalSize(self, func, file):
3686 """Overrriden from TypeHandler."""
3687 pass
3689 def WriteImmediateCmdSizeTest(self, func, file):
3690 """Overrriden from TypeHandler."""
3691 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3693 def WriteImmediateCmdInit(self, func, file):
3694 """Overrriden from TypeHandler."""
3695 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3696 self.WriteImmediateCmdGetTotalSize(func, file)
3697 file.Write(" SetHeader(total_size);\n")
3698 args = func.GetCmdArgs()
3699 for arg in args:
3700 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3701 file.Write(" }\n")
3702 file.Write("\n")
3704 def WriteImmediateCmdSet(self, func, file):
3705 """Overrriden from TypeHandler."""
3706 copy_args = func.MakeCmdArgString("_", False)
3707 file.Write(" void* Set(void* cmd%s) {\n" %
3708 func.MakeTypedCmdArgString("_", True))
3709 self.WriteImmediateCmdGetTotalSize(func, file)
3710 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3711 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3712 "cmd, total_size);\n")
3713 file.Write(" }\n")
3714 file.Write("\n")
3716 def WriteImmediateFormatTest(self, func, file):
3717 """Overrriden from TypeHandler."""
3718 # TODO(gman): Remove this exception.
3719 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3720 return
3722 def WriteServiceUnitTest(self, func, file):
3723 """Overrriden from TypeHandler."""
3724 file.Write("// TODO(gman): %s\n\n" % func.name)
3726 def WriteImmediateServiceUnitTest(self, func, file):
3727 """Overrriden from TypeHandler."""
3728 file.Write("// TODO(gman): %s\n\n" % func.name)
3730 def WriteBucketServiceImplementation(self, func, file):
3731 """Overrriden from TypeHandler."""
3732 if not func.name == 'CompressedTexSubImage2DBucket':
3733 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3736 class BindHandler(TypeHandler):
3737 """Handler for glBind___ type functions."""
3739 def __init__(self):
3740 TypeHandler.__init__(self)
3742 def WriteServiceUnitTest(self, func, file):
3743 """Overrriden from TypeHandler."""
3745 if len(func.GetOriginalArgs()) == 1:
3746 valid_test = """
3747 TEST_F(%(test_name)s, %(name)sValidArgs) {
3748 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3749 SpecializedSetup<cmds::%(name)s, 0>(true);
3750 cmds::%(name)s cmd;
3751 cmd.Init(%(args)s);
3752 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3753 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3756 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3757 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3758 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3759 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3760 SpecializedSetup<cmds::%(name)s, 0>(true);
3761 cmds::%(name)s cmd;
3762 cmd.Init(kNewClientId);
3763 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3764 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3765 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3768 gen_func_names = {
3770 self.WriteValidUnitTest(func, file, valid_test, {
3771 'resource_type': func.GetOriginalArgs()[0].resource_type,
3772 'gl_gen_func_name': func.GetInfo("gen_func"),
3774 else:
3775 valid_test = """
3776 TEST_F(%(test_name)s, %(name)sValidArgs) {
3777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3778 SpecializedSetup<cmds::%(name)s, 0>(true);
3779 cmds::%(name)s cmd;
3780 cmd.Init(%(args)s);
3781 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3782 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3785 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3786 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3787 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3788 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3789 SpecializedSetup<cmds::%(name)s, 0>(true);
3790 cmds::%(name)s cmd;
3791 cmd.Init(%(first_arg)s, kNewClientId);
3792 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3793 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3794 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3797 gen_func_names = {
3799 self.WriteValidUnitTest(func, file, valid_test, {
3800 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3801 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3802 'resource_type': func.GetOriginalArgs()[1].resource_type,
3803 'gl_gen_func_name': func.GetInfo("gen_func"),
3806 invalid_test = """
3807 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3808 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3809 SpecializedSetup<cmds::%(name)s, 0>(false);
3810 cmds::%(name)s cmd;
3811 cmd.Init(%(args)s);
3812 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3815 self.WriteInvalidUnitTest(func, file, invalid_test)
3817 def WriteGLES2Implementation(self, func, file):
3818 """Writes the GLES2 Implemention."""
3820 impl_func = func.GetInfo('impl_func')
3821 impl_decl = func.GetInfo('impl_decl')
3823 if (func.can_auto_generate and
3824 (impl_func == None or impl_func == True) and
3825 (impl_decl == None or impl_decl == True)):
3827 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3828 (func.return_type, func.original_name,
3829 func.MakeTypedOriginalArgString("")))
3830 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3831 func.WriteDestinationInitalizationValidation(file)
3832 self.WriteClientGLCallLog(func, file)
3833 for arg in func.GetOriginalArgs():
3834 arg.WriteClientSideValidationCode(file, func)
3836 code = """ if (Is%(type)sReservedId(%(id)s)) {
3837 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3838 return;
3840 if (Bind%(type)sHelper(%(arg_string)s)) {
3841 helper_->%(name)s(%(arg_string)s);
3843 CheckGLError();
3847 name_arg = None
3848 if len(func.GetOriginalArgs()) == 1:
3849 # Bind functions that have no target (like BindVertexArrayOES)
3850 name_arg = func.GetOriginalArgs()[0]
3851 else:
3852 # Bind functions that have both a target and a name (like BindTexture)
3853 name_arg = func.GetOriginalArgs()[1]
3855 file.Write(code % {
3856 'name': func.name,
3857 'arg_string': func.MakeOriginalArgString(""),
3858 'id': name_arg.name,
3859 'type': name_arg.resource_type,
3860 'lc_type': name_arg.resource_type.lower(),
3863 def WriteGLES2ImplementationUnitTest(self, func, file):
3864 """Overrriden from TypeHandler."""
3865 client_test = func.GetInfo('client_test')
3866 if client_test == False:
3867 return
3868 code = """
3869 TEST_F(GLES2ImplementationTest, %(name)s) {
3870 struct Cmds {
3871 cmds::%(name)s cmd;
3873 Cmds expected;
3874 expected.cmd.Init(%(cmd_args)s);
3876 gl_->%(name)s(%(args)s);
3877 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3878 ClearCommands();
3879 gl_->%(name)s(%(args)s);
3880 EXPECT_TRUE(NoCommandsWritten());
3883 cmd_arg_strings = []
3884 for count, arg in enumerate(func.GetCmdArgs()):
3885 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3886 count += 1
3887 gl_arg_strings = []
3888 for count, arg in enumerate(func.GetOriginalArgs()):
3889 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3890 file.Write(code % {
3891 'name': func.name,
3892 'args': ", ".join(gl_arg_strings),
3893 'cmd_args': ", ".join(cmd_arg_strings),
3897 class GENnHandler(TypeHandler):
3898 """Handler for glGen___ type functions."""
3900 def __init__(self):
3901 TypeHandler.__init__(self)
3903 def InitFunction(self, func):
3904 """Overrriden from TypeHandler."""
3905 pass
3907 def WriteGetDataSizeCode(self, func, file):
3908 """Overrriden from TypeHandler."""
3909 code = """ uint32 data_size;
3910 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3911 return error::kOutOfBounds;
3914 file.Write(code)
3916 def WriteHandlerImplementation (self, func, file):
3917 """Overrriden from TypeHandler."""
3918 file.Write(" if (!%sHelper(n, %s)) {\n"
3919 " return error::kInvalidArguments;\n"
3920 " }\n" %
3921 (func.name, func.GetLastOriginalArg().name))
3923 def WriteImmediateHandlerImplementation(self, func, file):
3924 """Overrriden from TypeHandler."""
3925 file.Write(" if (!%sHelper(n, %s)) {\n"
3926 " return error::kInvalidArguments;\n"
3927 " }\n" %
3928 (func.original_name, func.GetLastOriginalArg().name))
3930 def WriteGLES2Implementation(self, func, file):
3931 """Overrriden from TypeHandler."""
3932 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3933 for (GLsizei i = 0; i < n; ++i) {
3934 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3936 });""" % func.GetOriginalArgs()[1].name)
3937 args = {
3938 'log_code': log_code,
3939 'return_type': func.return_type,
3940 'name': func.original_name,
3941 'typed_args': func.MakeTypedOriginalArgString(""),
3942 'args': func.MakeOriginalArgString(""),
3943 'resource_types': func.GetInfo('resource_types'),
3944 'count_name': func.GetOriginalArgs()[0].name,
3946 file.Write(
3947 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3948 args)
3949 func.WriteDestinationInitalizationValidation(file)
3950 self.WriteClientGLCallLog(func, file)
3951 for arg in func.GetOriginalArgs():
3952 arg.WriteClientSideValidationCode(file, func)
3953 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3954 GetIdHandler(id_namespaces::k%(resource_types)s)->
3955 MakeIds(this, 0, %(args)s);
3956 %(name)sHelper(%(args)s);
3957 helper_->%(name)sImmediate(%(args)s);
3958 helper_->CommandBufferHelper::Flush();
3959 %(log_code)s
3960 CheckGLError();
3964 file.Write(code % args)
3966 def WriteGLES2ImplementationUnitTest(self, func, file):
3967 """Overrriden from TypeHandler."""
3968 code = """
3969 TEST_F(GLES2ImplementationTest, %(name)s) {
3970 GLuint ids[2] = { 0, };
3971 struct Cmds {
3972 cmds::%(name)sImmediate gen;
3973 GLuint data[2];
3975 Cmds expected;
3976 expected.gen.Init(arraysize(ids), &ids[0]);
3977 expected.data[0] = k%(types)sStartId;
3978 expected.data[1] = k%(types)sStartId + 1;
3979 gl_->%(name)s(arraysize(ids), &ids[0]);
3980 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3981 EXPECT_EQ(k%(types)sStartId, ids[0]);
3982 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3985 file.Write(code % {
3986 'name': func.name,
3987 'types': func.GetInfo('resource_types'),
3990 def WriteServiceUnitTest(self, func, file):
3991 """Overrriden from TypeHandler."""
3992 valid_test = """
3993 TEST_F(%(test_name)s, %(name)sValidArgs) {
3994 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3995 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3996 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3997 SpecializedSetup<cmds::%(name)s, 0>(true);
3998 cmds::%(name)s cmd;
3999 cmd.Init(%(args)s);
4000 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4001 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4002 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4005 self.WriteValidUnitTest(func, file, valid_test, {
4006 'resource_name': func.GetInfo('resource_type'),
4008 invalid_test = """
4009 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4010 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4011 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4012 SpecializedSetup<cmds::%(name)s, 0>(false);
4013 cmds::%(name)s cmd;
4014 cmd.Init(%(args)s);
4015 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4018 self.WriteValidUnitTest(func, file, invalid_test, {
4019 'resource_name': func.GetInfo('resource_type').lower(),
4022 def WriteImmediateServiceUnitTest(self, func, file):
4023 """Overrriden from TypeHandler."""
4024 valid_test = """
4025 TEST_F(%(test_name)s, %(name)sValidArgs) {
4026 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4027 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4028 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4029 GLuint temp = kNewClientId;
4030 SpecializedSetup<cmds::%(name)s, 0>(true);
4031 cmd->Init(1, &temp);
4032 EXPECT_EQ(error::kNoError,
4033 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4034 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4035 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4038 self.WriteValidUnitTest(func, file, valid_test, {
4039 'resource_name': func.GetInfo('resource_type'),
4041 invalid_test = """
4042 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4043 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4044 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4045 SpecializedSetup<cmds::%(name)s, 0>(false);
4046 cmd->Init(1, &client_%(resource_name)s_id_);
4047 EXPECT_EQ(error::kInvalidArguments,
4048 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4051 self.WriteValidUnitTest(func, file, invalid_test, {
4052 'resource_name': func.GetInfo('resource_type').lower(),
4055 def WriteImmediateCmdComputeSize(self, func, file):
4056 """Overrriden from TypeHandler."""
4057 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4058 file.Write(
4059 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4060 file.Write(" }\n")
4061 file.Write("\n")
4062 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4063 file.Write(" return static_cast<uint32>(\n")
4064 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4065 file.Write(" }\n")
4066 file.Write("\n")
4068 def WriteImmediateCmdSetHeader(self, func, file):
4069 """Overrriden from TypeHandler."""
4070 file.Write(" void SetHeader(GLsizei n) {\n")
4071 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4072 file.Write(" }\n")
4073 file.Write("\n")
4075 def WriteImmediateCmdInit(self, func, file):
4076 """Overrriden from TypeHandler."""
4077 last_arg = func.GetLastOriginalArg()
4078 file.Write(" void Init(%s, %s _%s) {\n" %
4079 (func.MakeTypedCmdArgString("_"),
4080 last_arg.type, last_arg.name))
4081 file.Write(" SetHeader(_n);\n")
4082 args = func.GetCmdArgs()
4083 for arg in args:
4084 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4085 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4086 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4087 file.Write(" }\n")
4088 file.Write("\n")
4090 def WriteImmediateCmdSet(self, func, file):
4091 """Overrriden from TypeHandler."""
4092 last_arg = func.GetLastOriginalArg()
4093 copy_args = func.MakeCmdArgString("_", False)
4094 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4095 (func.MakeTypedCmdArgString("_", True),
4096 last_arg.type, last_arg.name))
4097 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4098 (copy_args, last_arg.name))
4099 file.Write(" const uint32 size = ComputeSize(_n);\n")
4100 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4101 "cmd, size);\n")
4102 file.Write(" }\n")
4103 file.Write("\n")
4105 def WriteImmediateCmdHelper(self, func, file):
4106 """Overrriden from TypeHandler."""
4107 code = """ void %(name)s(%(typed_args)s) {
4108 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4109 gles2::cmds::%(name)s* c =
4110 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4111 if (c) {
4112 c->Init(%(args)s);
4117 file.Write(code % {
4118 "name": func.name,
4119 "typed_args": func.MakeTypedOriginalArgString(""),
4120 "args": func.MakeOriginalArgString(""),
4123 def WriteImmediateFormatTest(self, func, file):
4124 """Overrriden from TypeHandler."""
4125 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4126 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4127 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4128 (func.name, func.name))
4129 file.Write(" void* next_cmd = cmd.Set(\n")
4130 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4131 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4132 func.name)
4133 file.Write(" cmd.header.command);\n")
4134 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4135 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4136 file.Write(" cmd.header.size * 4u);\n")
4137 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4138 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4139 file.Write(" next_cmd, sizeof(cmd) +\n")
4140 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4141 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4142 file.Write("}\n")
4143 file.Write("\n")
4146 class CreateHandler(TypeHandler):
4147 """Handler for glCreate___ type functions."""
4149 def __init__(self):
4150 TypeHandler.__init__(self)
4152 def InitFunction(self, func):
4153 """Overrriden from TypeHandler."""
4154 func.AddCmdArg(Argument("client_id", 'uint32'))
4156 def WriteServiceUnitTest(self, func, file):
4157 """Overrriden from TypeHandler."""
4158 valid_test = """
4159 TEST_F(%(test_name)s, %(name)sValidArgs) {
4160 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4161 .WillOnce(Return(kNewServiceId));
4162 SpecializedSetup<cmds::%(name)s, 0>(true);
4163 cmds::%(name)s cmd;
4164 cmd.Init(%(args)s%(comma)skNewClientId);
4165 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4166 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4167 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4170 comma = ""
4171 if len(func.GetOriginalArgs()):
4172 comma =", "
4173 self.WriteValidUnitTest(func, file, valid_test, {
4174 'comma': comma,
4175 'resource_type': func.name[6:],
4177 invalid_test = """
4178 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4179 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4180 SpecializedSetup<cmds::%(name)s, 0>(false);
4181 cmds::%(name)s cmd;
4182 cmd.Init(%(args)s%(comma)skNewClientId);
4183 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4186 self.WriteInvalidUnitTest(func, file, invalid_test, {
4187 'comma': comma,
4190 def WriteHandlerImplementation (self, func, file):
4191 """Overrriden from TypeHandler."""
4192 file.Write(" uint32 client_id = c.client_id;\n")
4193 file.Write(" if (!%sHelper(%s)) {\n" %
4194 (func.name, func.MakeCmdArgString("")))
4195 file.Write(" return error::kInvalidArguments;\n")
4196 file.Write(" }\n")
4198 def WriteGLES2Implementation(self, func, file):
4199 """Overrriden from TypeHandler."""
4200 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4201 (func.return_type, func.original_name,
4202 func.MakeTypedOriginalArgString("")))
4203 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4204 func.WriteDestinationInitalizationValidation(file)
4205 self.WriteClientGLCallLog(func, file)
4206 for arg in func.GetOriginalArgs():
4207 arg.WriteClientSideValidationCode(file, func)
4208 file.Write(" GLuint client_id;\n")
4209 file.Write(
4210 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4211 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4212 file.Write(" helper_->%s(%s);\n" %
4213 (func.name, func.MakeCmdArgString("")))
4214 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4215 file.Write(" CheckGLError();\n")
4216 file.Write(" return client_id;\n")
4217 file.Write("}\n")
4218 file.Write("\n")
4221 class DeleteHandler(TypeHandler):
4222 """Handler for glDelete___ single resource type functions."""
4224 def __init__(self):
4225 TypeHandler.__init__(self)
4227 def WriteServiceImplementation(self, func, file):
4228 """Overrriden from TypeHandler."""
4229 pass
4231 def WriteGLES2Implementation(self, func, file):
4232 """Overrriden from TypeHandler."""
4233 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4234 (func.return_type, func.original_name,
4235 func.MakeTypedOriginalArgString("")))
4236 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4237 func.WriteDestinationInitalizationValidation(file)
4238 self.WriteClientGLCallLog(func, file)
4239 for arg in func.GetOriginalArgs():
4240 arg.WriteClientSideValidationCode(file, func)
4241 file.Write(
4242 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4243 file.Write(" %sHelper(%s);\n" %
4244 (func.original_name, func.GetOriginalArgs()[-1].name))
4245 file.Write(" CheckGLError();\n")
4246 file.Write("}\n")
4247 file.Write("\n")
4250 class DELnHandler(TypeHandler):
4251 """Handler for glDelete___ type functions."""
4253 def __init__(self):
4254 TypeHandler.__init__(self)
4256 def WriteGetDataSizeCode(self, func, file):
4257 """Overrriden from TypeHandler."""
4258 code = """ uint32 data_size;
4259 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4260 return error::kOutOfBounds;
4263 file.Write(code)
4265 def WriteGLES2ImplementationUnitTest(self, func, file):
4266 """Overrriden from TypeHandler."""
4267 code = """
4268 TEST_F(GLES2ImplementationTest, %(name)s) {
4269 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4270 struct Cmds {
4271 cmds::%(name)sImmediate del;
4272 GLuint data[2];
4274 Cmds expected;
4275 expected.del.Init(arraysize(ids), &ids[0]);
4276 expected.data[0] = k%(types)sStartId;
4277 expected.data[1] = k%(types)sStartId + 1;
4278 gl_->%(name)s(arraysize(ids), &ids[0]);
4279 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4282 file.Write(code % {
4283 'name': func.name,
4284 'types': func.GetInfo('resource_types'),
4287 def WriteServiceUnitTest(self, func, file):
4288 """Overrriden from TypeHandler."""
4289 valid_test = """
4290 TEST_F(%(test_name)s, %(name)sValidArgs) {
4291 EXPECT_CALL(
4292 *gl_,
4293 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4294 .Times(1);
4295 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4296 SpecializedSetup<cmds::%(name)s, 0>(true);
4297 cmds::%(name)s cmd;
4298 cmd.Init(%(args)s);
4299 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4300 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4301 EXPECT_TRUE(
4302 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4305 self.WriteValidUnitTest(func, file, valid_test, {
4306 'resource_name': func.GetInfo('resource_type').lower(),
4307 'upper_resource_name': func.GetInfo('resource_type'),
4309 invalid_test = """
4310 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4311 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4312 SpecializedSetup<cmds::%(name)s, 0>(false);
4313 cmds::%(name)s cmd;
4314 cmd.Init(%(args)s);
4315 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4318 self.WriteValidUnitTest(func, file, invalid_test)
4320 def WriteImmediateServiceUnitTest(self, func, file):
4321 """Overrriden from TypeHandler."""
4322 valid_test = """
4323 TEST_F(%(test_name)s, %(name)sValidArgs) {
4324 EXPECT_CALL(
4325 *gl_,
4326 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4327 .Times(1);
4328 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4329 SpecializedSetup<cmds::%(name)s, 0>(true);
4330 cmd.Init(1, &client_%(resource_name)s_id_);
4331 EXPECT_EQ(error::kNoError,
4332 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4333 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4334 EXPECT_TRUE(
4335 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4338 self.WriteValidUnitTest(func, file, valid_test, {
4339 'resource_name': func.GetInfo('resource_type').lower(),
4340 'upper_resource_name': func.GetInfo('resource_type'),
4342 invalid_test = """
4343 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4344 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4345 SpecializedSetup<cmds::%(name)s, 0>(false);
4346 GLuint temp = kInvalidClientId;
4347 cmd.Init(1, &temp);
4348 EXPECT_EQ(error::kNoError,
4349 ExecuteImmediateCmd(cmd, sizeof(temp)));
4352 self.WriteValidUnitTest(func, file, invalid_test)
4354 def WriteHandlerImplementation (self, func, file):
4355 """Overrriden from TypeHandler."""
4356 file.Write(" %sHelper(n, %s);\n" %
4357 (func.name, func.GetLastOriginalArg().name))
4359 def WriteImmediateHandlerImplementation (self, func, file):
4360 """Overrriden from TypeHandler."""
4361 file.Write(" %sHelper(n, %s);\n" %
4362 (func.original_name, func.GetLastOriginalArg().name))
4364 def WriteGLES2Implementation(self, func, file):
4365 """Overrriden from TypeHandler."""
4366 impl_decl = func.GetInfo('impl_decl')
4367 if impl_decl == None or impl_decl == True:
4368 args = {
4369 'return_type': func.return_type,
4370 'name': func.original_name,
4371 'typed_args': func.MakeTypedOriginalArgString(""),
4372 'args': func.MakeOriginalArgString(""),
4373 'resource_type': func.GetInfo('resource_type').lower(),
4374 'count_name': func.GetOriginalArgs()[0].name,
4376 file.Write(
4377 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4378 args)
4379 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4380 func.WriteDestinationInitalizationValidation(file)
4381 self.WriteClientGLCallLog(func, file)
4382 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4383 for (GLsizei i = 0; i < n; ++i) {
4384 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4387 """ % func.GetOriginalArgs()[1].name)
4388 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4389 for (GLsizei i = 0; i < n; ++i) {
4390 DCHECK(%s[i] != 0);
4393 """ % func.GetOriginalArgs()[1].name)
4394 for arg in func.GetOriginalArgs():
4395 arg.WriteClientSideValidationCode(file, func)
4396 code = """ %(name)sHelper(%(args)s);
4397 CheckGLError();
4401 file.Write(code % args)
4403 def WriteImmediateCmdComputeSize(self, func, file):
4404 """Overrriden from TypeHandler."""
4405 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4406 file.Write(
4407 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4408 file.Write(" }\n")
4409 file.Write("\n")
4410 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4411 file.Write(" return static_cast<uint32>(\n")
4412 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4413 file.Write(" }\n")
4414 file.Write("\n")
4416 def WriteImmediateCmdSetHeader(self, func, file):
4417 """Overrriden from TypeHandler."""
4418 file.Write(" void SetHeader(GLsizei n) {\n")
4419 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4420 file.Write(" }\n")
4421 file.Write("\n")
4423 def WriteImmediateCmdInit(self, func, file):
4424 """Overrriden from TypeHandler."""
4425 last_arg = func.GetLastOriginalArg()
4426 file.Write(" void Init(%s, %s _%s) {\n" %
4427 (func.MakeTypedCmdArgString("_"),
4428 last_arg.type, last_arg.name))
4429 file.Write(" SetHeader(_n);\n")
4430 args = func.GetCmdArgs()
4431 for arg in args:
4432 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4433 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4434 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4435 file.Write(" }\n")
4436 file.Write("\n")
4438 def WriteImmediateCmdSet(self, func, file):
4439 """Overrriden from TypeHandler."""
4440 last_arg = func.GetLastOriginalArg()
4441 copy_args = func.MakeCmdArgString("_", False)
4442 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4443 (func.MakeTypedCmdArgString("_", True),
4444 last_arg.type, last_arg.name))
4445 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4446 (copy_args, last_arg.name))
4447 file.Write(" const uint32 size = ComputeSize(_n);\n")
4448 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4449 "cmd, size);\n")
4450 file.Write(" }\n")
4451 file.Write("\n")
4453 def WriteImmediateCmdHelper(self, func, file):
4454 """Overrriden from TypeHandler."""
4455 code = """ void %(name)s(%(typed_args)s) {
4456 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4457 gles2::cmds::%(name)s* c =
4458 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4459 if (c) {
4460 c->Init(%(args)s);
4465 file.Write(code % {
4466 "name": func.name,
4467 "typed_args": func.MakeTypedOriginalArgString(""),
4468 "args": func.MakeOriginalArgString(""),
4471 def WriteImmediateFormatTest(self, func, file):
4472 """Overrriden from TypeHandler."""
4473 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4474 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4475 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4476 (func.name, func.name))
4477 file.Write(" void* next_cmd = cmd.Set(\n")
4478 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4479 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4480 func.name)
4481 file.Write(" cmd.header.command);\n")
4482 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4483 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4484 file.Write(" cmd.header.size * 4u);\n")
4485 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4486 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4487 file.Write(" next_cmd, sizeof(cmd) +\n")
4488 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4489 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4490 file.Write("}\n")
4491 file.Write("\n")
4494 class GETnHandler(TypeHandler):
4495 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4497 def __init__(self):
4498 TypeHandler.__init__(self)
4500 def AddImmediateFunction(self, generator, func):
4501 """Overrriden from TypeHandler."""
4502 pass
4504 def WriteServiceImplementation(self, func, file):
4505 """Overrriden from TypeHandler."""
4506 file.Write(
4507 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4508 file.Write(
4509 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4510 func.name)
4511 last_arg = func.GetLastOriginalArg()
4513 all_but_last_args = func.GetOriginalArgs()[:-1]
4514 for arg in all_but_last_args:
4515 arg.WriteGetCode(file)
4517 code = """ typedef cmds::%(func_name)s::Result Result;
4518 GLsizei num_values = 0;
4519 GetNumValuesReturnedForGLGet(pname, &num_values);
4520 Result* result = GetSharedMemoryAs<Result*>(
4521 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4522 %(last_arg_type)s params = result ? result->GetData() : NULL;
4524 file.Write(code % {
4525 'last_arg_type': last_arg.type,
4526 'func_name': func.name,
4528 func.WriteHandlerValidation(file)
4529 code = """ // Check that the client initialized the result.
4530 if (result->size != 0) {
4531 return error::kInvalidArguments;
4534 shadowed = func.GetInfo('shadowed')
4535 if not shadowed:
4536 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4537 file.Write(code)
4538 func.WriteHandlerImplementation(file)
4539 if shadowed:
4540 code = """ result->SetNumResults(num_values);
4541 return error::kNoError;
4544 else:
4545 code = """ GLenum error = glGetError();
4546 if (error == GL_NO_ERROR) {
4547 result->SetNumResults(num_values);
4548 } else {
4549 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4551 return error::kNoError;
4555 file.Write(code % {'func_name': func.name})
4557 def WriteGLES2Implementation(self, func, file):
4558 """Overrriden from TypeHandler."""
4559 impl_decl = func.GetInfo('impl_decl')
4560 if impl_decl == None or impl_decl == True:
4561 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4562 (func.return_type, func.original_name,
4563 func.MakeTypedOriginalArgString("")))
4564 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4565 func.WriteDestinationInitalizationValidation(file)
4566 self.WriteClientGLCallLog(func, file)
4567 for arg in func.GetOriginalArgs():
4568 arg.WriteClientSideValidationCode(file, func)
4569 all_but_last_args = func.GetOriginalArgs()[:-1]
4570 arg_string = (
4571 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4572 all_arg_string = (
4573 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4574 self.WriteTraceEvent(func, file)
4575 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4576 return;
4578 typedef cmds::%(func_name)s::Result Result;
4579 Result* result = GetResultAs<Result*>();
4580 if (!result) {
4581 return;
4583 result->SetNumResults(0);
4584 helper_->%(func_name)s(%(arg_string)s,
4585 GetResultShmId(), GetResultShmOffset());
4586 WaitForCmd();
4587 result->CopyResult(params);
4588 GPU_CLIENT_LOG_CODE_BLOCK({
4589 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4590 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4593 CheckGLError();
4596 file.Write(code % {
4597 'func_name': func.name,
4598 'arg_string': arg_string,
4599 'all_arg_string': all_arg_string,
4602 def WriteGLES2ImplementationUnitTest(self, func, file):
4603 """Writes the GLES2 Implemention unit test."""
4604 code = """
4605 TEST_F(GLES2ImplementationTest, %(name)s) {
4606 struct Cmds {
4607 cmds::%(name)s cmd;
4609 typedef cmds::%(name)s::Result Result;
4610 Result::Type result = 0;
4611 Cmds expected;
4612 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4613 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4614 EXPECT_CALL(*command_buffer(), OnFlush())
4615 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4616 .RetiresOnSaturation();
4617 gl_->%(name)s(%(args)s, &result);
4618 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4619 EXPECT_EQ(static_cast<Result::Type>(1), result);
4622 cmd_arg_strings = []
4623 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4624 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4625 cmd_arg_strings[0] = '123'
4626 gl_arg_strings = []
4627 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4628 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4629 gl_arg_strings[0] = '123'
4630 file.Write(code % {
4631 'name': func.name,
4632 'args': ", ".join(gl_arg_strings),
4633 'cmd_args': ", ".join(cmd_arg_strings),
4636 def WriteServiceUnitTest(self, func, file):
4637 """Overrriden from TypeHandler."""
4638 valid_test = """
4639 TEST_F(%(test_name)s, %(name)sValidArgs) {
4640 EXPECT_CALL(*gl_, GetError())
4641 .WillOnce(Return(GL_NO_ERROR))
4642 .WillOnce(Return(GL_NO_ERROR))
4643 .RetiresOnSaturation();
4644 SpecializedSetup<cmds::%(name)s, 0>(true);
4645 typedef cmds::%(name)s::Result Result;
4646 Result* result = static_cast<Result*>(shared_memory_address_);
4647 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4648 result->size = 0;
4649 cmds::%(name)s cmd;
4650 cmd.Init(%(args)s);
4651 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4652 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4653 %(valid_pname)s),
4654 result->GetNumResults());
4655 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4658 gl_arg_strings = []
4659 valid_pname = ''
4660 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4661 arg_value = arg.GetValidGLArg(func, count, 0)
4662 gl_arg_strings.append(arg_value)
4663 if arg.name == 'pname':
4664 valid_pname = arg_value
4665 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4666 gl_arg_strings.append("_")
4667 else:
4668 gl_arg_strings.append("result->GetData()")
4670 self.WriteValidUnitTest(func, file, valid_test, {
4671 'local_gl_args': ", ".join(gl_arg_strings),
4672 'valid_pname': valid_pname,
4675 invalid_test = """
4676 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4677 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4678 SpecializedSetup<cmds::%(name)s, 0>(false);
4679 cmds::%(name)s::Result* result =
4680 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4681 result->size = 0;
4682 cmds::%(name)s cmd;
4683 cmd.Init(%(args)s);
4684 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4685 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4688 self.WriteInvalidUnitTest(func, file, invalid_test)
4691 class PUTHandler(TypeHandler):
4692 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4694 def __init__(self):
4695 TypeHandler.__init__(self)
4697 def WriteServiceUnitTest(self, func, file):
4698 """Writes the service unit test for a command."""
4699 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4700 if func.GetInfo("first_element_only"):
4701 gl_arg_strings = []
4702 for count, arg in enumerate(func.GetOriginalArgs()):
4703 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4704 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4705 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4706 ", ".join(gl_arg_strings))
4707 valid_test = """
4708 TEST_F(%(test_name)s, %(name)sValidArgs) {
4709 SpecializedSetup<cmds::%(name)s, 0>(true);
4710 cmds::%(name)s cmd;
4711 cmd.Init(%(args)s);
4712 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4713 %(expected_call)s
4714 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4715 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4718 extra = {
4719 'data_type': func.GetInfo('data_type'),
4720 'data_value': func.GetInfo('data_value') or '0',
4721 'expected_call': expected_call,
4723 self.WriteValidUnitTest(func, file, valid_test, extra)
4725 invalid_test = """
4726 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4727 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4728 SpecializedSetup<cmds::%(name)s, 0>(false);
4729 cmds::%(name)s cmd;
4730 cmd.Init(%(args)s);
4731 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4732 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4735 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4737 def WriteImmediateServiceUnitTest(self, func, file):
4738 """Writes the service unit test for a command."""
4739 valid_test = """
4740 TEST_F(%(test_name)s, %(name)sValidArgs) {
4741 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4742 SpecializedSetup<cmds::%(name)s, 0>(true);
4743 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4744 cmd.Init(%(gl_args)s, &temp[0]);
4745 EXPECT_CALL(
4746 *gl_,
4747 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4748 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4749 EXPECT_EQ(error::kNoError,
4750 ExecuteImmediateCmd(cmd, sizeof(temp)));
4751 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4754 gl_arg_strings = []
4755 gl_any_strings = []
4756 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4757 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4758 gl_any_strings.append("_")
4759 extra = {
4760 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4761 'data_type': func.GetInfo('data_type'),
4762 'data_count': func.GetInfo('count'),
4763 'data_value': func.GetInfo('data_value') or '0',
4764 'gl_args': ", ".join(gl_arg_strings),
4765 'gl_any_args': ", ".join(gl_any_strings),
4767 self.WriteValidUnitTest(func, file, valid_test, extra)
4769 invalid_test = """
4770 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4771 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4772 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4773 SpecializedSetup<cmds::%(name)s, 0>(false);
4774 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4775 cmd.Init(%(all_but_last_args)s, &temp[0]);
4776 EXPECT_EQ(error::%(parse_result)s,
4777 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4780 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4782 def WriteGetDataSizeCode(self, func, file):
4783 """Overrriden from TypeHandler."""
4784 code = """ uint32 data_size;
4785 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4786 return error::kOutOfBounds;
4789 file.Write(code % (func.info.data_type, func.info.count))
4790 if func.is_immediate:
4791 file.Write(" if (data_size > immediate_data_size) {\n")
4792 file.Write(" return error::kOutOfBounds;\n")
4793 file.Write(" }\n")
4795 def WriteGLES2Implementation(self, func, file):
4796 """Overrriden from TypeHandler."""
4797 impl_func = func.GetInfo('impl_func')
4798 if (impl_func != None and impl_func != True):
4799 return;
4800 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4801 (func.return_type, func.original_name,
4802 func.MakeTypedOriginalArgString("")))
4803 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4804 func.WriteDestinationInitalizationValidation(file)
4805 self.WriteClientGLCallLog(func, file)
4806 last_arg_name = func.GetLastOriginalArg().name
4807 values_str = ' << ", " << '.join(
4808 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4809 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4810 for arg in func.GetOriginalArgs():
4811 arg.WriteClientSideValidationCode(file, func)
4812 file.Write(" helper_->%sImmediate(%s);\n" %
4813 (func.name, func.MakeOriginalArgString("")))
4814 file.Write(" CheckGLError();\n")
4815 file.Write("}\n")
4816 file.Write("\n")
4818 def WriteGLES2ImplementationUnitTest(self, func, file):
4819 """Writes the GLES2 Implemention unit test."""
4820 client_test = func.GetInfo('client_test')
4821 if (client_test != None and client_test != True):
4822 return;
4823 code = """
4824 TEST_F(GLES2ImplementationTest, %(name)s) {
4825 %(type)s data[%(count)d] = {0};
4826 struct Cmds {
4827 cmds::%(name)sImmediate cmd;
4828 %(type)s data[%(count)d];
4831 for (int jj = 0; jj < %(count)d; ++jj) {
4832 data[jj] = static_cast<%(type)s>(jj);
4834 Cmds expected;
4835 expected.cmd.Init(%(cmd_args)s, &data[0]);
4836 gl_->%(name)s(%(args)s, &data[0]);
4837 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4840 cmd_arg_strings = []
4841 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4842 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4843 gl_arg_strings = []
4844 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4845 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4846 file.Write(code % {
4847 'name': func.name,
4848 'type': func.GetInfo('data_type'),
4849 'count': func.GetInfo('count'),
4850 'args': ", ".join(gl_arg_strings),
4851 'cmd_args': ", ".join(cmd_arg_strings),
4854 def WriteImmediateCmdComputeSize(self, func, file):
4855 """Overrriden from TypeHandler."""
4856 file.Write(" static uint32 ComputeDataSize() {\n")
4857 file.Write(" return static_cast<uint32>(\n")
4858 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4859 (func.info.data_type, func.info.count))
4860 file.Write(" }\n")
4861 file.Write("\n")
4862 file.Write(" static uint32 ComputeSize() {\n")
4863 file.Write(" return static_cast<uint32>(\n")
4864 file.Write(
4865 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4866 file.Write(" }\n")
4867 file.Write("\n")
4869 def WriteImmediateCmdSetHeader(self, func, file):
4870 """Overrriden from TypeHandler."""
4871 file.Write(" void SetHeader() {\n")
4872 file.Write(
4873 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4874 file.Write(" }\n")
4875 file.Write("\n")
4877 def WriteImmediateCmdInit(self, func, file):
4878 """Overrriden from TypeHandler."""
4879 last_arg = func.GetLastOriginalArg()
4880 file.Write(" void Init(%s, %s _%s) {\n" %
4881 (func.MakeTypedCmdArgString("_"),
4882 last_arg.type, last_arg.name))
4883 file.Write(" SetHeader();\n")
4884 args = func.GetCmdArgs()
4885 for arg in args:
4886 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4887 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4888 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4889 file.Write(" }\n")
4890 file.Write("\n")
4892 def WriteImmediateCmdSet(self, func, file):
4893 """Overrriden from TypeHandler."""
4894 last_arg = func.GetLastOriginalArg()
4895 copy_args = func.MakeCmdArgString("_", False)
4896 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4897 (func.MakeTypedCmdArgString("_", True),
4898 last_arg.type, last_arg.name))
4899 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4900 (copy_args, last_arg.name))
4901 file.Write(" const uint32 size = ComputeSize();\n")
4902 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4903 "cmd, size);\n")
4904 file.Write(" }\n")
4905 file.Write("\n")
4907 def WriteImmediateCmdHelper(self, func, file):
4908 """Overrriden from TypeHandler."""
4909 code = """ void %(name)s(%(typed_args)s) {
4910 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4911 gles2::cmds::%(name)s* c =
4912 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4913 if (c) {
4914 c->Init(%(args)s);
4919 file.Write(code % {
4920 "name": func.name,
4921 "typed_args": func.MakeTypedOriginalArgString(""),
4922 "args": func.MakeOriginalArgString(""),
4925 def WriteImmediateFormatTest(self, func, file):
4926 """Overrriden from TypeHandler."""
4927 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4928 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4929 file.Write(" static %s data[] = {\n" % func.info.data_type)
4930 for v in range(0, func.info.count):
4931 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4932 (func.info.data_type, v))
4933 file.Write(" };\n")
4934 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4935 (func.name, func.name))
4936 file.Write(" void* next_cmd = cmd.Set(\n")
4937 file.Write(" &cmd")
4938 args = func.GetCmdArgs()
4939 for value, arg in enumerate(args):
4940 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4941 file.Write(",\n data);\n")
4942 args = func.GetCmdArgs()
4943 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4944 % func.name)
4945 file.Write(" cmd.header.command);\n")
4946 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4947 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4948 file.Write(" cmd.header.size * 4u);\n")
4949 for value, arg in enumerate(args):
4950 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4951 (arg.type, value + 11, arg.name))
4952 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4953 file.Write(" next_cmd, sizeof(cmd) +\n")
4954 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4955 file.Write(" // TODO(gman): Check that data was inserted;\n")
4956 file.Write("}\n")
4957 file.Write("\n")
4960 class PUTnHandler(TypeHandler):
4961 """Handler for PUTn 'glUniform__v' type functions."""
4963 def __init__(self):
4964 TypeHandler.__init__(self)
4966 def WriteServiceUnitTest(self, func, file):
4967 """Overridden from TypeHandler."""
4968 TypeHandler.WriteServiceUnitTest(self, func, file)
4970 valid_test = """
4971 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4972 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4973 SpecializedSetup<cmds::%(name)s, 0>(true);
4974 cmds::%(name)s cmd;
4975 cmd.Init(%(args)s);
4976 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4977 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4980 gl_arg_strings = []
4981 arg_strings = []
4982 for count, arg in enumerate(func.GetOriginalArgs()):
4983 # hardcoded to match unit tests.
4984 if count == 0:
4985 # the location of the second element of the 2nd uniform.
4986 # defined in GLES2DecoderBase::SetupShaderForUniform
4987 gl_arg_strings.append("3")
4988 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
4989 elif count == 1:
4990 # the number of elements that gl will be called with.
4991 gl_arg_strings.append("3")
4992 # the number of elements requested in the command.
4993 arg_strings.append("5")
4994 else:
4995 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4996 arg_strings.append(arg.GetValidArg(func, count, 0))
4997 extra = {
4998 'gl_args': ", ".join(gl_arg_strings),
4999 'args': ", ".join(arg_strings),
5001 self.WriteValidUnitTest(func, file, valid_test, extra)
5003 def WriteImmediateServiceUnitTest(self, func, file):
5004 """Overridden from TypeHandler."""
5005 valid_test = """
5006 TEST_F(%(test_name)s, %(name)sValidArgs) {
5007 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5008 EXPECT_CALL(
5009 *gl_,
5010 %(gl_func_name)s(%(gl_args)s,
5011 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5012 SpecializedSetup<cmds::%(name)s, 0>(true);
5013 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5014 cmd.Init(%(args)s, &temp[0]);
5015 EXPECT_EQ(error::kNoError,
5016 ExecuteImmediateCmd(cmd, sizeof(temp)));
5017 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5020 gl_arg_strings = []
5021 gl_any_strings = []
5022 arg_strings = []
5023 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5024 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5025 gl_any_strings.append("_")
5026 arg_strings.append(arg.GetValidArg(func, count, 0))
5027 extra = {
5028 'data_type': func.GetInfo('data_type'),
5029 'data_count': func.GetInfo('count'),
5030 'args': ", ".join(arg_strings),
5031 'gl_args': ", ".join(gl_arg_strings),
5032 'gl_any_args': ", ".join(gl_any_strings),
5034 self.WriteValidUnitTest(func, file, valid_test, extra)
5036 invalid_test = """
5037 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5038 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5039 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5040 SpecializedSetup<cmds::%(name)s, 0>(false);
5041 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5042 cmd.Init(%(all_but_last_args)s, &temp[0]);
5043 EXPECT_EQ(error::%(parse_result)s,
5044 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5047 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5049 def WriteGetDataSizeCode(self, func, file):
5050 """Overrriden from TypeHandler."""
5051 code = """ uint32 data_size;
5052 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5053 return error::kOutOfBounds;
5056 file.Write(code % (func.info.data_type, func.info.count))
5057 if func.is_immediate:
5058 file.Write(" if (data_size > immediate_data_size) {\n")
5059 file.Write(" return error::kOutOfBounds;\n")
5060 file.Write(" }\n")
5062 def WriteGLES2Implementation(self, func, file):
5063 """Overrriden from TypeHandler."""
5064 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5065 (func.return_type, func.original_name,
5066 func.MakeTypedOriginalArgString("")))
5067 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5068 func.WriteDestinationInitalizationValidation(file)
5069 self.WriteClientGLCallLog(func, file)
5070 last_arg_name = func.GetLastOriginalArg().name
5071 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5072 for (GLsizei i = 0; i < count; ++i) {
5073 """)
5074 values_str = ' << ", " << '.join(
5075 ["%s[%d + i * %d]" % (
5076 last_arg_name, ndx, func.info.count) for ndx in range(
5077 0, func.info.count)])
5078 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5079 file.Write(" }\n });\n")
5080 for arg in func.GetOriginalArgs():
5081 arg.WriteClientSideValidationCode(file, func)
5082 file.Write(" helper_->%sImmediate(%s);\n" %
5083 (func.name, func.MakeOriginalArgString("")))
5084 file.Write(" CheckGLError();\n")
5085 file.Write("}\n")
5086 file.Write("\n")
5088 def WriteGLES2ImplementationUnitTest(self, func, file):
5089 """Writes the GLES2 Implemention unit test."""
5090 code = """
5091 TEST_F(GLES2ImplementationTest, %(name)s) {
5092 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5093 struct Cmds {
5094 cmds::%(name)sImmediate cmd;
5095 %(type)s data[%(count_param)d][%(count)d];
5098 Cmds expected;
5099 for (int ii = 0; ii < %(count_param)d; ++ii) {
5100 for (int jj = 0; jj < %(count)d; ++jj) {
5101 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5104 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5105 gl_->%(name)s(%(args)s, &data[0][0]);
5106 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5109 cmd_arg_strings = []
5110 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5111 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5112 gl_arg_strings = []
5113 count_param = 0
5114 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5115 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5116 if arg.name == "count":
5117 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5118 file.Write(code % {
5119 'name': func.name,
5120 'type': func.GetInfo('data_type'),
5121 'count': func.GetInfo('count'),
5122 'args': ", ".join(gl_arg_strings),
5123 'cmd_args': ", ".join(cmd_arg_strings),
5124 'count_param': count_param,
5127 def WriteImmediateCmdComputeSize(self, func, file):
5128 """Overrriden from TypeHandler."""
5129 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5130 file.Write(" return static_cast<uint32>(\n")
5131 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5132 (func.info.data_type, func.info.count))
5133 file.Write(" }\n")
5134 file.Write("\n")
5135 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5136 file.Write(" return static_cast<uint32>(\n")
5137 file.Write(
5138 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5139 file.Write(" }\n")
5140 file.Write("\n")
5142 def WriteImmediateCmdSetHeader(self, func, file):
5143 """Overrriden from TypeHandler."""
5144 file.Write(" void SetHeader(GLsizei count) {\n")
5145 file.Write(
5146 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5147 file.Write(" }\n")
5148 file.Write("\n")
5150 def WriteImmediateCmdInit(self, func, file):
5151 """Overrriden from TypeHandler."""
5152 last_arg = func.GetLastOriginalArg()
5153 file.Write(" void Init(%s, %s _%s) {\n" %
5154 (func.MakeTypedCmdArgString("_"),
5155 last_arg.type, last_arg.name))
5156 file.Write(" SetHeader(_count);\n")
5157 args = func.GetCmdArgs()
5158 for arg in args:
5159 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5160 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5161 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5162 file.Write(" }\n")
5163 file.Write("\n")
5165 def WriteImmediateCmdSet(self, func, file):
5166 """Overrriden from TypeHandler."""
5167 last_arg = func.GetLastOriginalArg()
5168 copy_args = func.MakeCmdArgString("_", False)
5169 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5170 (func.MakeTypedCmdArgString("_", True),
5171 last_arg.type, last_arg.name))
5172 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5173 (copy_args, last_arg.name))
5174 file.Write(" const uint32 size = ComputeSize(_count);\n")
5175 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5176 "cmd, size);\n")
5177 file.Write(" }\n")
5178 file.Write("\n")
5180 def WriteImmediateCmdHelper(self, func, file):
5181 """Overrriden from TypeHandler."""
5182 code = """ void %(name)s(%(typed_args)s) {
5183 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5184 gles2::cmds::%(name)s* c =
5185 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5186 if (c) {
5187 c->Init(%(args)s);
5192 file.Write(code % {
5193 "name": func.name,
5194 "typed_args": func.MakeTypedOriginalArgString(""),
5195 "args": func.MakeOriginalArgString(""),
5198 def WriteImmediateFormatTest(self, func, file):
5199 """Overrriden from TypeHandler."""
5200 args = func.GetCmdArgs()
5201 count_param = 0
5202 for value, arg in enumerate(args):
5203 if arg.name == "count":
5204 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5205 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5206 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5207 file.Write(" static %s data[] = {\n" % func.info.data_type)
5208 for v in range(0, func.info.count * count_param):
5209 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5210 (func.info.data_type, v))
5211 file.Write(" };\n")
5212 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5213 (func.name, func.name))
5214 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5215 file.Write(" const size_t kExpectedCmdSize =\n")
5216 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5217 (func.info.data_type, func.info.count))
5218 file.Write(" void* next_cmd = cmd.Set(\n")
5219 file.Write(" &cmd")
5220 for value, arg in enumerate(args):
5221 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5222 file.Write(",\n data);\n")
5223 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5224 func.name)
5225 file.Write(" cmd.header.command);\n")
5226 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5227 for value, arg in enumerate(args):
5228 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5229 (arg.type, value + 1, arg.name))
5230 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5231 file.Write(" next_cmd, sizeof(cmd) +\n")
5232 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5233 file.Write(" // TODO(gman): Check that data was inserted;\n")
5234 file.Write("}\n")
5235 file.Write("\n")
5238 class PUTXnHandler(TypeHandler):
5239 """Handler for glUniform?f functions."""
5240 def __init__(self):
5241 TypeHandler.__init__(self)
5243 def WriteHandlerImplementation(self, func, file):
5244 """Overrriden from TypeHandler."""
5245 code = """ %(type)s temp[%(count)s] = { %(values)s};
5246 Do%(name)sv(%(location)s, 1, &temp[0]);
5248 values = ""
5249 args = func.GetOriginalArgs()
5250 count = int(func.GetInfo('count'))
5251 num_args = len(args)
5252 for ii in range(count):
5253 values += "%s, " % args[len(args) - count + ii].name
5255 file.Write(code % {
5256 'name': func.name,
5257 'count': func.GetInfo('count'),
5258 'type': func.GetInfo('data_type'),
5259 'location': args[0].name,
5260 'args': func.MakeOriginalArgString(""),
5261 'values': values,
5264 def WriteServiceUnitTest(self, func, file):
5265 """Overrriden from TypeHandler."""
5266 valid_test = """
5267 TEST_F(%(test_name)s, %(name)sValidArgs) {
5268 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5269 SpecializedSetup<cmds::%(name)s, 0>(true);
5270 cmds::%(name)s cmd;
5271 cmd.Init(%(args)s);
5272 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5273 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5276 args = func.GetOriginalArgs()
5277 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5278 self.WriteValidUnitTest(func, file, valid_test, {
5279 'name': func.name,
5280 'count': func.GetInfo('count'),
5281 'local_args': local_args,
5284 invalid_test = """
5285 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5286 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5287 SpecializedSetup<cmds::%(name)s, 0>(false);
5288 cmds::%(name)s cmd;
5289 cmd.Init(%(args)s);
5290 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5293 self.WriteInvalidUnitTest(func, file, invalid_test, {
5294 'name': func.GetInfo('name'),
5295 'count': func.GetInfo('count'),
5299 class GLcharHandler(CustomHandler):
5300 """Handler for functions that pass a single string ."""
5302 def __init__(self):
5303 CustomHandler.__init__(self)
5305 def WriteImmediateCmdComputeSize(self, func, file):
5306 """Overrriden from TypeHandler."""
5307 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5308 file.Write(" return static_cast<uint32>(\n")
5309 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5310 file.Write(" }\n")
5312 def WriteImmediateCmdSetHeader(self, func, file):
5313 """Overrriden from TypeHandler."""
5314 code = """
5315 void SetHeader(uint32 data_size) {
5316 header.SetCmdBySize<ValueType>(data_size);
5319 file.Write(code)
5321 def WriteImmediateCmdInit(self, func, file):
5322 """Overrriden from TypeHandler."""
5323 last_arg = func.GetLastOriginalArg()
5324 args = func.GetCmdArgs()
5325 set_code = []
5326 for arg in args:
5327 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5328 code = """
5329 void Init(%(typed_args)s, uint32 _data_size) {
5330 SetHeader(_data_size);
5331 %(set_code)s
5332 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5336 file.Write(code % {
5337 "typed_args": func.MakeTypedOriginalArgString("_"),
5338 "set_code": "\n".join(set_code),
5339 "last_arg": last_arg.name
5342 def WriteImmediateCmdSet(self, func, file):
5343 """Overrriden from TypeHandler."""
5344 last_arg = func.GetLastOriginalArg()
5345 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5346 func.MakeTypedOriginalArgString("_", True))
5347 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5348 func.MakeOriginalArgString("_"))
5349 file.Write(" return NextImmediateCmdAddress<ValueType>("
5350 "cmd, _data_size);\n")
5351 file.Write(" }\n")
5352 file.Write("\n")
5354 def WriteImmediateCmdHelper(self, func, file):
5355 """Overrriden from TypeHandler."""
5356 code = """ void %(name)s(%(typed_args)s) {
5357 const uint32 data_size = strlen(name);
5358 gles2::cmds::%(name)s* c =
5359 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5360 if (c) {
5361 c->Init(%(args)s, data_size);
5366 file.Write(code % {
5367 "name": func.name,
5368 "typed_args": func.MakeTypedOriginalArgString(""),
5369 "args": func.MakeOriginalArgString(""),
5373 def WriteImmediateFormatTest(self, func, file):
5374 """Overrriden from TypeHandler."""
5375 init_code = []
5376 check_code = []
5377 all_but_last_arg = func.GetCmdArgs()[:-1]
5378 for value, arg in enumerate(all_but_last_arg):
5379 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5380 for value, arg in enumerate(all_but_last_arg):
5381 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5382 (arg.type, value + 11, arg.name))
5383 code = """
5384 TEST_F(GLES2FormatTest, %(func_name)s) {
5385 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5386 static const char* const test_str = \"test string\";
5387 void* next_cmd = cmd.Set(
5388 &cmd,
5389 %(init_code)s
5390 test_str,
5391 strlen(test_str));
5392 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5393 cmd.header.command);
5394 EXPECT_EQ(sizeof(cmd) +
5395 RoundSizeToMultipleOfEntries(strlen(test_str)),
5396 cmd.header.size * 4u);
5397 EXPECT_EQ(static_cast<char*>(next_cmd),
5398 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5399 RoundSizeToMultipleOfEntries(strlen(test_str)));
5400 %(check_code)s
5401 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5402 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5403 CheckBytesWritten(
5404 next_cmd,
5405 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5406 sizeof(cmd) + strlen(test_str));
5410 file.Write(code % {
5411 'func_name': func.name,
5412 'init_code': "\n".join(init_code),
5413 'check_code': "\n".join(check_code),
5417 class GLcharNHandler(CustomHandler):
5418 """Handler for functions that pass a single string with an optional len."""
5420 def __init__(self):
5421 CustomHandler.__init__(self)
5423 def InitFunction(self, func):
5424 """Overrriden from TypeHandler."""
5425 func.cmd_args = []
5426 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5428 def AddImmediateFunction(self, generator, func):
5429 """Overrriden from TypeHandler."""
5430 pass
5432 def AddBucketFunction(self, generator, func):
5433 """Overrriden from TypeHandler."""
5434 pass
5436 def WriteServiceImplementation(self, func, file):
5437 """Overrriden from TypeHandler."""
5438 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5439 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5440 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5441 Bucket* bucket = GetBucket(bucket_id);
5442 if (!bucket || bucket->size() == 0) {
5443 return error::kInvalidArguments;
5445 std::string str;
5446 if (!bucket->GetAsString(&str)) {
5447 return error::kInvalidArguments;
5449 %(gl_func_name)s(0, str.c_str());
5450 return error::kNoError;
5453 """ % {
5454 'name': func.name,
5455 'gl_func_name': func.GetGLFunctionName(),
5456 'bucket_id': func.cmd_args[0].name,
5460 class IsHandler(TypeHandler):
5461 """Handler for glIs____ type and glGetError functions."""
5463 def __init__(self):
5464 TypeHandler.__init__(self)
5466 def InitFunction(self, func):
5467 """Overrriden from TypeHandler."""
5468 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5469 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5470 if func.GetInfo('result') == None:
5471 func.AddInfo('result', ['uint32'])
5473 def WriteServiceUnitTest(self, func, file):
5474 """Overrriden from TypeHandler."""
5475 valid_test = """
5476 TEST_F(%(test_name)s, %(name)sValidArgs) {
5477 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5478 SpecializedSetup<cmds::%(name)s, 0>(true);
5479 cmds::%(name)s cmd;
5480 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5481 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5482 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5485 comma = ""
5486 if len(func.GetOriginalArgs()):
5487 comma =", "
5488 self.WriteValidUnitTest(func, file, valid_test, {
5489 'comma': comma,
5492 invalid_test = """
5493 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5494 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5495 SpecializedSetup<cmds::%(name)s, 0>(false);
5496 cmds::%(name)s cmd;
5497 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5498 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5501 self.WriteInvalidUnitTest(func, file, invalid_test, {
5502 'comma': comma,
5505 invalid_test = """
5506 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5507 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5508 SpecializedSetup<cmds::%(name)s, 0>(false);
5509 cmds::%(name)s cmd;
5510 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5511 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5512 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5513 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5516 self.WriteValidUnitTest(func, file, invalid_test, {
5517 'comma': comma,
5520 def WriteServiceImplementation(self, func, file):
5521 """Overrriden from TypeHandler."""
5522 file.Write(
5523 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5524 file.Write(
5525 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5526 func.name)
5527 args = func.GetOriginalArgs()
5528 for arg in args:
5529 arg.WriteGetCode(file)
5531 code = """ typedef cmds::%(func_name)s::Result Result;
5532 Result* result_dst = GetSharedMemoryAs<Result*>(
5533 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5534 if (!result_dst) {
5535 return error::kOutOfBounds;
5538 file.Write(code % {'func_name': func.name})
5539 func.WriteHandlerValidation(file)
5540 file.Write(" *result_dst = %s(%s);\n" %
5541 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5542 file.Write(" return error::kNoError;\n")
5543 file.Write("}\n")
5544 file.Write("\n")
5546 def WriteGLES2Implementation(self, func, file):
5547 """Overrriden from TypeHandler."""
5548 impl_func = func.GetInfo('impl_func')
5549 if impl_func == None or impl_func == True:
5550 error_value = func.GetInfo("error_value") or "GL_FALSE"
5551 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5552 (func.return_type, func.original_name,
5553 func.MakeTypedOriginalArgString("")))
5554 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5555 self.WriteTraceEvent(func, file)
5556 func.WriteDestinationInitalizationValidation(file)
5557 self.WriteClientGLCallLog(func, file)
5558 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5559 file.Write(" Result* result = GetResultAs<Result*>();\n")
5560 file.Write(" if (!result) {\n")
5561 file.Write(" return %s;\n" % error_value)
5562 file.Write(" }\n")
5563 file.Write(" *result = 0;\n")
5564 arg_string = func.MakeOriginalArgString("")
5565 comma = ""
5566 if len(arg_string) > 0:
5567 comma = ", "
5568 file.Write(
5569 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5570 (func.name, arg_string, comma))
5571 file.Write(" WaitForCmd();\n")
5572 file.Write(" %s result_value = *result;\n" % func.return_type)
5573 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5574 file.Write(" CheckGLError();\n")
5575 file.Write(" return result_value;\n")
5576 file.Write("}\n")
5577 file.Write("\n")
5579 def WriteGLES2ImplementationUnitTest(self, func, file):
5580 """Overrriden from TypeHandler."""
5581 client_test = func.GetInfo('client_test')
5582 if client_test == None or client_test == True:
5583 code = """
5584 TEST_F(GLES2ImplementationTest, %(name)s) {
5585 struct Cmds {
5586 cmds::%(name)s cmd;
5589 typedef cmds::%(name)s::Result Result;
5590 Cmds expected;
5591 ExpectedMemoryInfo result1 =
5592 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5593 expected.cmd.Init(1, result1.id, result1.offset);
5595 EXPECT_CALL(*command_buffer(), OnFlush())
5596 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5597 .RetiresOnSaturation();
5599 GLboolean result = gl_->%(name)s(1);
5600 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5601 EXPECT_TRUE(result);
5604 file.Write(code % {
5605 'name': func.name,
5609 class STRnHandler(TypeHandler):
5610 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5611 GetTranslatedShaderSourceANGLE."""
5613 def __init__(self):
5614 TypeHandler.__init__(self)
5616 def InitFunction(self, func):
5617 """Overrriden from TypeHandler."""
5618 # remove all but the first cmd args.
5619 cmd_args = func.GetCmdArgs()
5620 func.ClearCmdArgs()
5621 func.AddCmdArg(cmd_args[0])
5622 # add on a bucket id.
5623 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5625 def WriteGLES2Implementation(self, func, file):
5626 """Overrriden from TypeHandler."""
5627 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5628 GPU_CLIENT_SINGLE_THREAD_CHECK();
5630 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5631 << "] gl%(func_name)s" << "("
5632 << %(arg0)s << ", "
5633 << %(arg1)s << ", "
5634 << static_cast<void*>(%(arg2)s) << ", "
5635 << static_cast<void*>(%(arg3)s) << ")");
5636 helper_->SetBucketSize(kResultBucketId, 0);
5637 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5638 std::string str;
5639 GLsizei max_size = 0;
5640 if (GetBucketAsString(kResultBucketId, &str)) {
5641 if (bufsize > 0) {
5642 max_size =
5643 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5644 memcpy(%(dest_name)s, str.c_str(), max_size);
5645 %(dest_name)s[max_size] = '\\0';
5646 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5649 if (%(length_name)s != NULL) {
5650 *%(length_name)s = max_size;
5652 CheckGLError();
5655 args = func.GetOriginalArgs()
5656 str_args = {
5657 'return_type': func.return_type,
5658 'func_name': func.original_name,
5659 'args': func.MakeTypedOriginalArgString(""),
5660 'id_name': args[0].name,
5661 'bufsize_name': args[1].name,
5662 'length_name': args[2].name,
5663 'dest_name': args[3].name,
5664 'arg0': args[0].name,
5665 'arg1': args[1].name,
5666 'arg2': args[2].name,
5667 'arg3': args[3].name,
5669 file.Write(code_1 % str_args)
5670 func.WriteDestinationInitalizationValidation(file)
5671 file.Write(code_2 % str_args)
5673 def WriteServiceUnitTest(self, func, file):
5674 """Overrriden from TypeHandler."""
5675 valid_test = """
5676 TEST_F(%(test_name)s, %(name)sValidArgs) {
5677 const char* kInfo = "hello";
5678 const uint32 kBucketId = 123;
5679 SpecializedSetup<cmds::%(name)s, 0>(true);
5680 %(expect_len_code)s
5681 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5682 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5683 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5684 cmds::%(name)s cmd;
5685 cmd.Init(%(args)s);
5686 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5687 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5688 ASSERT_TRUE(bucket != NULL);
5689 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5690 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5691 bucket->size()));
5692 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5695 args = func.GetOriginalArgs()
5696 id_name = args[0].GetValidGLArg(func, 0, 0)
5697 get_len_func = func.GetInfo('get_len_func')
5698 get_len_enum = func.GetInfo('get_len_enum')
5699 sub = {
5700 'id_name': id_name,
5701 'get_len_func': get_len_func,
5702 'get_len_enum': get_len_enum,
5703 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5704 args[0].GetValidGLArg(func, 0, 0),
5705 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5706 'expect_len_code': '',
5708 if get_len_func and get_len_func[0:2] == 'gl':
5709 sub['expect_len_code'] = (
5710 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5711 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5712 get_len_func[2:], id_name, get_len_enum)
5713 self.WriteValidUnitTest(func, file, valid_test, sub)
5715 invalid_test = """
5716 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5717 const uint32 kBucketId = 123;
5718 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5719 .Times(0);
5720 cmds::%(name)s cmd;
5721 cmd.Init(kInvalidClientId, kBucketId);
5722 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5723 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5726 self.WriteValidUnitTest(func, file, invalid_test)
5728 def WriteServiceImplementation(self, func, file):
5729 """Overrriden from TypeHandler."""
5730 pass
5733 class FunctionInfo(object):
5734 """Holds info about a function."""
5736 def __init__(self, info, type_handler):
5737 for key in info:
5738 setattr(self, key, info[key])
5739 self.type_handler = type_handler
5740 if not 'type' in info:
5741 self.type = ''
5744 class Argument(object):
5745 """A class that represents a function argument."""
5747 cmd_type_map_ = {
5748 'GLenum': 'uint32',
5749 'GLint': 'int32',
5750 'GLintptr': 'int32',
5751 'GLsizei': 'int32',
5752 'GLsizeiptr': 'int32',
5753 'GLfloat': 'float',
5754 'GLclampf': 'float',
5756 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5758 def __init__(self, name, type):
5759 self.name = name
5760 self.optional = type.endswith("Optional*")
5761 if self.optional:
5762 type = type[:-9] + "*"
5763 self.type = type
5765 if type in self.cmd_type_map_:
5766 self.cmd_type = self.cmd_type_map_[type]
5767 else:
5768 self.cmd_type = 'uint32'
5770 def IsPointer(self):
5771 """Returns true if argument is a pointer."""
5772 return False
5774 def AddCmdArgs(self, args):
5775 """Adds command arguments for this argument to the given list."""
5776 return args.append(self)
5778 def AddInitArgs(self, args):
5779 """Adds init arguments for this argument to the given list."""
5780 return args.append(self)
5782 def GetValidArg(self, func, offset, index):
5783 """Gets a valid value for this argument."""
5784 valid_arg = func.GetValidArg(offset)
5785 if valid_arg != None:
5786 return valid_arg
5787 return str(offset + 1)
5789 def GetValidClientSideArg(self, func, offset, index):
5790 """Gets a valid value for this argument."""
5791 return str(offset + 1)
5793 def GetValidClientSideCmdArg(self, func, offset, index):
5794 """Gets a valid value for this argument."""
5795 return str(offset + 1)
5797 def GetValidGLArg(self, func, offset, index):
5798 """Gets a valid GL value for this argument."""
5799 valid_arg = func.GetValidArg(offset)
5800 if valid_arg != None:
5801 return valid_arg
5802 return str(offset + 1)
5804 def GetNumInvalidValues(self, func):
5805 """returns the number of invalid values to be tested."""
5806 return 0
5808 def GetInvalidArg(self, offset, index):
5809 """returns an invalid value and expected parse result by index."""
5810 return ("---ERROR0---", "---ERROR2---", None)
5812 def GetLogArg(self):
5813 """Get argument appropriate for LOG macro."""
5814 if self.type == 'GLboolean':
5815 return 'GLES2Util::GetStringBool(%s)' % self.name
5816 if self.type == 'GLenum':
5817 return 'GLES2Util::GetStringEnum(%s)' % self.name
5818 return self.name
5820 def WriteGetCode(self, file):
5821 """Writes the code to get an argument from a command structure."""
5822 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5823 (self.type, self.name, self.type, self.name))
5825 def WriteValidationCode(self, file, func):
5826 """Writes the validation code for an argument."""
5827 pass
5829 def WriteClientSideValidationCode(self, file, func):
5830 """Writes the validation code for an argument."""
5831 pass
5833 def WriteDestinationInitalizationValidation(self, file, func):
5834 """Writes the client side destintion initialization validation."""
5835 pass
5837 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5838 """Writes the client side destintion initialization validation if needed."""
5839 parts = self.type.split(" ")
5840 if len(parts) > 1:
5841 return
5842 if parts[0] in self.need_validation_:
5843 file.Write(
5844 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5845 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5848 def WriteGetAddress(self, file):
5849 """Writes the code to get the address this argument refers to."""
5850 pass
5852 def GetImmediateVersion(self):
5853 """Gets the immediate version of this argument."""
5854 return self
5856 def GetBucketVersion(self):
5857 """Gets the bucket version of this argument."""
5858 return self
5861 class BoolArgument(Argument):
5862 """class for GLboolean"""
5864 def __init__(self, name, type):
5865 Argument.__init__(self, name, 'GLboolean')
5867 def GetValidArg(self, func, offset, index):
5868 """Gets a valid value for this argument."""
5869 return 'true'
5871 def GetValidClientSideArg(self, func, offset, index):
5872 """Gets a valid value for this argument."""
5873 return 'true'
5875 def GetValidClientSideCmdArg(self, func, offset, index):
5876 """Gets a valid value for this argument."""
5877 return 'true'
5879 def GetValidGLArg(self, func, offset, index):
5880 """Gets a valid GL value for this argument."""
5881 return 'true'
5884 class UniformLocationArgument(Argument):
5885 """class for uniform locations."""
5887 def __init__(self, name):
5888 Argument.__init__(self, name, "GLint")
5890 def WriteGetCode(self, file):
5891 """Writes the code to get an argument from a command structure."""
5892 code = """ %s %s = static_cast<%s>(c.%s);
5894 file.Write(code % (self.type, self.name, self.type, self.name))
5896 def GetValidArg(self, func, offset, index):
5897 """Gets a valid value for this argument."""
5898 return "%d" % (offset + 1)
5901 class DataSizeArgument(Argument):
5902 """class for data_size which Bucket commands do not need."""
5904 def __init__(self, name):
5905 Argument.__init__(self, name, "uint32")
5907 def GetBucketVersion(self):
5908 return None
5911 class SizeArgument(Argument):
5912 """class for GLsizei and GLsizeiptr."""
5914 def __init__(self, name, type):
5915 Argument.__init__(self, name, type)
5917 def GetNumInvalidValues(self, func):
5918 """overridden from Argument."""
5919 if func.is_immediate:
5920 return 0
5921 return 1
5923 def GetInvalidArg(self, offset, index):
5924 """overridden from Argument."""
5925 return ("-1", "kNoError", "GL_INVALID_VALUE")
5927 def WriteValidationCode(self, file, func):
5928 """overridden from Argument."""
5929 file.Write(" if (%s < 0) {\n" % self.name)
5930 file.Write(
5931 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5932 (func.original_name, self.name))
5933 file.Write(" return error::kNoError;\n")
5934 file.Write(" }\n")
5936 def WriteClientSideValidationCode(self, file, func):
5937 """overridden from Argument."""
5938 file.Write(" if (%s < 0) {\n" % self.name)
5939 file.Write(
5940 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5941 (func.original_name, self.name))
5942 file.Write(" return;\n")
5943 file.Write(" }\n")
5946 class SizeNotNegativeArgument(SizeArgument):
5947 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5949 def __init__(self, name, type, gl_type):
5950 SizeArgument.__init__(self, name, gl_type)
5952 def GetInvalidArg(self, offset, index):
5953 """overridden from SizeArgument."""
5954 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5956 def WriteValidationCode(self, file, func):
5957 """overridden from SizeArgument."""
5958 pass
5961 class EnumBaseArgument(Argument):
5962 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5964 def __init__(self, name, gl_type, type, gl_error):
5965 Argument.__init__(self, name, gl_type)
5967 self.local_type = type
5968 self.gl_error = gl_error
5969 name = type[len(gl_type):]
5970 self.type_name = name
5971 self.enum_info = _ENUM_LISTS[name]
5973 def WriteValidationCode(self, file, func):
5974 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5975 (ToUnderscore(self.type_name), self.name))
5976 if self.gl_error == "GL_INVALID_ENUM":
5977 file.Write(
5978 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5979 (func.original_name, self.name, self.name))
5980 else:
5981 file.Write(
5982 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5983 (self.gl_error, func.original_name, self.name, self.gl_error))
5984 file.Write(" return error::kNoError;\n")
5985 file.Write(" }\n")
5987 def GetValidArg(self, func, offset, index):
5988 valid_arg = func.GetValidArg(offset)
5989 if valid_arg != None:
5990 return valid_arg
5991 if 'valid' in self.enum_info:
5992 valid = self.enum_info['valid']
5993 num_valid = len(valid)
5994 if index >= num_valid:
5995 index = num_valid - 1
5996 return valid[index]
5997 return str(offset + 1)
5999 def GetValidClientSideArg(self, func, offset, index):
6000 """Gets a valid value for this argument."""
6001 return self.GetValidArg(func, offset, index)
6003 def GetValidClientSideCmdArg(self, func, offset, index):
6004 """Gets a valid value for this argument."""
6005 return self.GetValidArg(func, offset, index)
6007 def GetValidGLArg(self, func, offset, index):
6008 """Gets a valid value for this argument."""
6009 return self.GetValidArg(func, offset, index)
6011 def GetNumInvalidValues(self, func):
6012 """returns the number of invalid values to be tested."""
6013 if 'invalid' in self.enum_info:
6014 invalid = self.enum_info['invalid']
6015 return len(invalid)
6016 return 0
6018 def GetInvalidArg(self, offset, index):
6019 """returns an invalid value by index."""
6020 if 'invalid' in self.enum_info:
6021 invalid = self.enum_info['invalid']
6022 num_invalid = len(invalid)
6023 if index >= num_invalid:
6024 index = num_invalid - 1
6025 return (invalid[index], "kNoError", self.gl_error)
6026 return ("---ERROR1---", "kNoError", self.gl_error)
6029 class EnumArgument(EnumBaseArgument):
6030 """A class that represents a GLenum argument"""
6032 def __init__(self, name, type):
6033 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6035 def GetLogArg(self):
6036 """Overridden from Argument."""
6037 return ("GLES2Util::GetString%s(%s)" %
6038 (self.type_name, self.name))
6041 class IntArgument(EnumBaseArgument):
6042 """A class for a GLint argument that can only except specific values.
6044 For example glTexImage2D takes a GLint for its internalformat
6045 argument instead of a GLenum.
6048 def __init__(self, name, type):
6049 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6052 class ValidatedBoolArgument(EnumBaseArgument):
6053 """A class for a GLboolean argument that can only except specific values.
6055 For example glUniformMatrix takes a GLboolean for it's transpose but it
6056 must be false.
6059 def __init__(self, name, type):
6060 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6062 def GetLogArg(self):
6063 """Overridden from Argument."""
6064 return 'GLES2Util::GetStringBool(%s)' % self.name
6067 class ImmediatePointerArgument(Argument):
6068 """A class that represents an immediate argument to a function.
6070 An immediate argument is one where the data follows the command.
6073 def __init__(self, name, type):
6074 Argument.__init__(self, name, type)
6076 def AddCmdArgs(self, args):
6077 """Overridden from Argument."""
6078 pass
6080 def WriteGetCode(self, file):
6081 """Overridden from Argument."""
6082 file.Write(
6083 " %s %s = GetImmediateDataAs<%s>(\n" %
6084 (self.type, self.name, self.type))
6085 file.Write(" c, data_size, immediate_data_size);\n")
6087 def WriteValidationCode(self, file, func):
6088 """Overridden from Argument."""
6089 file.Write(" if (%s == NULL) {\n" % self.name)
6090 file.Write(" return error::kOutOfBounds;\n")
6091 file.Write(" }\n")
6093 def GetImmediateVersion(self):
6094 """Overridden from Argument."""
6095 return None
6097 def WriteDestinationInitalizationValidation(self, file, func):
6098 """Overridden from Argument."""
6099 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6101 def GetLogArg(self):
6102 """Overridden from Argument."""
6103 return "static_cast<const void*>(%s)" % self.name
6106 class BucketPointerArgument(Argument):
6107 """A class that represents an bucket argument to a function."""
6109 def __init__(self, name, type):
6110 Argument.__init__(self, name, type)
6112 def AddCmdArgs(self, args):
6113 """Overridden from Argument."""
6114 pass
6116 def WriteGetCode(self, file):
6117 """Overridden from Argument."""
6118 file.Write(
6119 " %s %s = bucket->GetData(0, data_size);\n" %
6120 (self.type, self.name))
6122 def WriteValidationCode(self, file, func):
6123 """Overridden from Argument."""
6124 pass
6126 def GetImmediateVersion(self):
6127 """Overridden from Argument."""
6128 return None
6130 def WriteDestinationInitalizationValidation(self, file, func):
6131 """Overridden from Argument."""
6132 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6134 def GetLogArg(self):
6135 """Overridden from Argument."""
6136 return "static_cast<const void*>(%s)" % self.name
6139 class PointerArgument(Argument):
6140 """A class that represents a pointer argument to a function."""
6142 def __init__(self, name, type):
6143 Argument.__init__(self, name, type)
6145 def IsPointer(self):
6146 """Returns true if argument is a pointer."""
6147 return True
6149 def GetValidArg(self, func, offset, index):
6150 """Overridden from Argument."""
6151 return "shared_memory_id_, shared_memory_offset_"
6153 def GetValidGLArg(self, func, offset, index):
6154 """Overridden from Argument."""
6155 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6157 def GetNumInvalidValues(self, func):
6158 """Overridden from Argument."""
6159 return 2
6161 def GetInvalidArg(self, offset, index):
6162 """Overridden from Argument."""
6163 if index == 0:
6164 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6165 else:
6166 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6167 "kOutOfBounds", None)
6169 def GetLogArg(self):
6170 """Overridden from Argument."""
6171 return "static_cast<const void*>(%s)" % self.name
6173 def AddCmdArgs(self, args):
6174 """Overridden from Argument."""
6175 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6176 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6178 def WriteGetCode(self, file):
6179 """Overridden from Argument."""
6180 file.Write(
6181 " %s %s = GetSharedMemoryAs<%s>(\n" %
6182 (self.type, self.name, self.type))
6183 file.Write(
6184 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6185 (self.name, self.name))
6187 def WriteGetAddress(self, file):
6188 """Overridden from Argument."""
6189 file.Write(
6190 " %s %s = GetSharedMemoryAs<%s>(\n" %
6191 (self.type, self.name, self.type))
6192 file.Write(
6193 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6194 (self.name, self.name, self.name))
6196 def WriteValidationCode(self, file, func):
6197 """Overridden from Argument."""
6198 file.Write(" if (%s == NULL) {\n" % self.name)
6199 file.Write(" return error::kOutOfBounds;\n")
6200 file.Write(" }\n")
6202 def GetImmediateVersion(self):
6203 """Overridden from Argument."""
6204 return ImmediatePointerArgument(self.name, self.type)
6206 def GetBucketVersion(self):
6207 """Overridden from Argument."""
6208 if self.type == "const char*":
6209 return InputStringBucketArgument(self.name, self.type)
6210 return BucketPointerArgument(self.name, self.type)
6212 def WriteDestinationInitalizationValidation(self, file, func):
6213 """Overridden from Argument."""
6214 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6217 class InputStringBucketArgument(Argument):
6218 """An string input argument where the string is passed in a bucket."""
6220 def __init__(self, name, type):
6221 Argument.__init__(self, name + "_bucket_id", "uint32")
6223 def WriteGetCode(self, file):
6224 """Overridden from Argument."""
6225 code = """
6226 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6227 if (!%(name)s_bucket) {
6228 return error::kInvalidArguments;
6230 std::string %(name)s_str;
6231 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6232 return error::kInvalidArguments;
6234 const char* %(name)s = %(name)s_str.c_str();
6236 file.Write(code % {
6237 'name': self.name,
6240 def GetValidArg(self, func, offset, index):
6241 return "kNameBucketId"
6243 def GetValidGLArg(self, func, offset, index):
6244 return "_"
6247 class NonImmediatePointerArgument(PointerArgument):
6248 """A pointer argument that stays a pointer even in an immediate cmd."""
6250 def __init__(self, name, type):
6251 PointerArgument.__init__(self, name, type)
6253 def IsPointer(self):
6254 """Returns true if argument is a pointer."""
6255 return False
6257 def GetImmediateVersion(self):
6258 """Overridden from Argument."""
6259 return self
6262 class ResourceIdArgument(Argument):
6263 """A class that represents a resource id argument to a function."""
6265 def __init__(self, name, type):
6266 match = re.match("(GLid\w+)", type)
6267 self.resource_type = match.group(1)[4:]
6268 type = type.replace(match.group(1), "GLuint")
6269 Argument.__init__(self, name, type)
6271 def WriteGetCode(self, file):
6272 """Overridden from Argument."""
6273 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6275 def GetValidArg(self, func, offset, index):
6276 return "client_%s_id_" % self.resource_type.lower()
6278 def GetValidGLArg(self, func, offset, index):
6279 return "kService%sId" % self.resource_type
6282 class ResourceIdBindArgument(Argument):
6283 """Represents a resource id argument to a bind function."""
6285 def __init__(self, name, type):
6286 match = re.match("(GLidBind\w+)", type)
6287 self.resource_type = match.group(1)[8:]
6288 type = type.replace(match.group(1), "GLuint")
6289 Argument.__init__(self, name, type)
6291 def WriteGetCode(self, file):
6292 """Overridden from Argument."""
6293 code = """ %(type)s %(name)s = c.%(name)s;
6295 file.Write(code % {'type': self.type, 'name': self.name})
6297 def GetValidArg(self, func, offset, index):
6298 return "client_%s_id_" % self.resource_type.lower()
6300 def GetValidGLArg(self, func, offset, index):
6301 return "kService%sId" % self.resource_type
6304 class ResourceIdZeroArgument(Argument):
6305 """Represents a resource id argument to a function that can be zero."""
6307 def __init__(self, name, type):
6308 match = re.match("(GLidZero\w+)", type)
6309 self.resource_type = match.group(1)[8:]
6310 type = type.replace(match.group(1), "GLuint")
6311 Argument.__init__(self, name, type)
6313 def WriteGetCode(self, file):
6314 """Overridden from Argument."""
6315 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6317 def GetValidArg(self, func, offset, index):
6318 return "client_%s_id_" % self.resource_type.lower()
6320 def GetValidGLArg(self, func, offset, index):
6321 return "kService%sId" % self.resource_type
6323 def GetNumInvalidValues(self, func):
6324 """returns the number of invalid values to be tested."""
6325 return 1
6327 def GetInvalidArg(self, offset, index):
6328 """returns an invalid value by index."""
6329 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6332 class Function(object):
6333 """A class that represents a function."""
6335 def __init__(self, original_name, name, info, return_type, original_args,
6336 args_for_cmds, cmd_args, init_args, num_pointer_args):
6337 self.name = name
6338 self.original_name = original_name
6339 self.info = info
6340 self.type_handler = info.type_handler
6341 self.return_type = return_type
6342 self.original_args = original_args
6343 self.num_pointer_args = num_pointer_args
6344 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6345 self.cmd_args = cmd_args
6346 self.init_args = init_args
6347 self.InitFunction()
6348 self.args_for_cmds = args_for_cmds
6349 self.is_immediate = False
6351 def IsType(self, type_name):
6352 """Returns true if function is a certain type."""
6353 return self.info.type == type_name
6355 def InitFunction(self):
6356 """Calls the init function for the type handler."""
6357 self.type_handler.InitFunction(self)
6359 def GetInfo(self, name):
6360 """Returns a value from the function info for this function."""
6361 if hasattr(self.info, name):
6362 return getattr(self.info, name)
6363 return None
6365 def GetValidArg(self, index):
6366 """Gets a valid arg from the function info if one exists."""
6367 valid_args = self.GetInfo('valid_args')
6368 if valid_args and str(index) in valid_args:
6369 return valid_args[str(index)]
6370 return None
6372 def AddInfo(self, name, value):
6373 """Adds an info."""
6374 setattr(self.info, name, value)
6376 def IsCoreGLFunction(self):
6377 return (not self.GetInfo('extension') and
6378 not self.GetInfo('pepper_interface'))
6380 def InPepperInterface(self, interface):
6381 ext = self.GetInfo('pepper_interface')
6382 if not interface.GetName():
6383 return self.IsCoreGLFunction()
6384 return ext == interface.GetName()
6386 def InAnyPepperExtension(self):
6387 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6389 def GetGLFunctionName(self):
6390 """Gets the function to call to execute GL for this command."""
6391 if self.GetInfo('decoder_func'):
6392 return self.GetInfo('decoder_func')
6393 return "gl%s" % self.original_name
6395 def GetGLTestFunctionName(self):
6396 gl_func_name = self.GetInfo('gl_test_func')
6397 if gl_func_name == None:
6398 gl_func_name = self.GetGLFunctionName()
6399 if gl_func_name.startswith("gl"):
6400 gl_func_name = gl_func_name[2:]
6401 else:
6402 gl_func_name = self.original_name
6403 return gl_func_name
6405 def AddCmdArg(self, arg):
6406 """Adds a cmd argument to this function."""
6407 self.cmd_args.append(arg)
6409 def GetCmdArgs(self):
6410 """Gets the command args for this function."""
6411 return self.cmd_args
6413 def ClearCmdArgs(self):
6414 """Clears the command args for this function."""
6415 self.cmd_args = []
6417 def GetInitArgs(self):
6418 """Gets the init args for this function."""
6419 return self.init_args
6421 def GetOriginalArgs(self):
6422 """Gets the original arguments to this function."""
6423 return self.original_args
6425 def GetLastOriginalArg(self):
6426 """Gets the last original argument to this function."""
6427 return self.original_args[len(self.original_args) - 1]
6429 def __MaybePrependComma(self, arg_string, add_comma):
6430 """Adds a comma if arg_string is not empty and add_comma is true."""
6431 comma = ""
6432 if add_comma and len(arg_string):
6433 comma = ", "
6434 return "%s%s" % (comma, arg_string)
6436 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6437 """Gets a list of arguments as they are in GL."""
6438 args = self.GetOriginalArgs()
6439 arg_string = ", ".join(
6440 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6441 return self.__MaybePrependComma(arg_string, add_comma)
6443 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6444 """Gets the list of arguments as they are in GL."""
6445 args = self.GetOriginalArgs()
6446 arg_string = separator.join(
6447 ["%s%s" % (prefix, arg.name) for arg in args])
6448 return self.__MaybePrependComma(arg_string, add_comma)
6450 def MakeTypedPepperArgString(self, prefix):
6451 """Gets a list of arguments as they need to be for Pepper."""
6452 if self.GetInfo("pepper_args"):
6453 return self.GetInfo("pepper_args")
6454 else:
6455 return self.MakeTypedOriginalArgString(prefix, False)
6457 def GetPepperName(self):
6458 if self.GetInfo("pepper_name"):
6459 return self.GetInfo("pepper_name")
6460 return self.name
6462 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6463 """Gets a typed list of arguments as they need to be for command buffers."""
6464 args = self.GetCmdArgs()
6465 arg_string = ", ".join(
6466 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6467 return self.__MaybePrependComma(arg_string, add_comma)
6469 def MakeCmdArgString(self, prefix, add_comma = False):
6470 """Gets the list of arguments as they need to be for command buffers."""
6471 args = self.GetCmdArgs()
6472 arg_string = ", ".join(
6473 ["%s%s" % (prefix, arg.name) for arg in args])
6474 return self.__MaybePrependComma(arg_string, add_comma)
6476 def MakeTypedInitString(self, prefix, add_comma = False):
6477 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6478 args = self.GetInitArgs()
6479 arg_string = ", ".join(
6480 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6481 return self.__MaybePrependComma(arg_string, add_comma)
6483 def MakeInitString(self, prefix, add_comma = False):
6484 """Gets the list of arguments as they need to be for cmd Init/Set."""
6485 args = self.GetInitArgs()
6486 arg_string = ", ".join(
6487 ["%s%s" % (prefix, arg.name) for arg in args])
6488 return self.__MaybePrependComma(arg_string, add_comma)
6490 def MakeLogArgString(self):
6491 """Makes a string of the arguments for the LOG macros"""
6492 args = self.GetOriginalArgs()
6493 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6495 def WriteCommandDescription(self, file):
6496 """Writes a description of the command."""
6497 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6499 def WriteHandlerValidation(self, file):
6500 """Writes validation code for the function."""
6501 for arg in self.GetOriginalArgs():
6502 arg.WriteValidationCode(file, self)
6503 self.WriteValidationCode(file)
6505 def WriteHandlerImplementation(self, file):
6506 """Writes the handler implementation for this command."""
6507 self.type_handler.WriteHandlerImplementation(self, file)
6509 def WriteValidationCode(self, file):
6510 """Writes the validation code for a command."""
6511 pass
6513 def WriteCmdFlag(self, file):
6514 """Writes the cmd cmd_flags constant."""
6515 flags = []
6516 trace_level = 3 # By default trace only at the highest level
6517 if hasattr(self.info, 'trace_level'):
6518 if (self.info.trace_level < 0) or (self.info.trace_level > 3):
6519 raise KeyError("Unhandled trace_level: %d" % self.info.trace_level)
6520 trace_level = self.info.trace_level
6522 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
6524 if len(flags) > 0:
6525 cmd_flags = ' | '.join(flags)
6526 else:
6527 cmd_flags = 0
6529 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
6532 def WriteCmdArgFlag(self, file):
6533 """Writes the cmd kArgFlags constant."""
6534 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6536 def WriteCmdComputeSize(self, file):
6537 """Writes the ComputeSize function for the command."""
6538 file.Write(" static uint32 ComputeSize() {\n")
6539 file.Write(
6540 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6541 file.Write(" }\n")
6542 file.Write("\n")
6544 def WriteCmdSetHeader(self, file):
6545 """Writes the cmd's SetHeader function."""
6546 file.Write(" void SetHeader() {\n")
6547 file.Write(" header.SetCmd<ValueType>();\n")
6548 file.Write(" }\n")
6549 file.Write("\n")
6551 def WriteCmdInit(self, file):
6552 """Writes the cmd's Init function."""
6553 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6554 file.Write(" SetHeader();\n")
6555 args = self.GetCmdArgs()
6556 for arg in args:
6557 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6558 file.Write(" }\n")
6559 file.Write("\n")
6561 def WriteCmdSet(self, file):
6562 """Writes the cmd's Set function."""
6563 copy_args = self.MakeCmdArgString("_", False)
6564 file.Write(" void* Set(void* cmd%s) {\n" %
6565 self.MakeTypedCmdArgString("_", True))
6566 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6567 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6568 file.Write(" }\n")
6569 file.Write("\n")
6571 def WriteStruct(self, file):
6572 self.type_handler.WriteStruct(self, file)
6574 def WriteDocs(self, file):
6575 self.type_handler.WriteDocs(self, file)
6577 def WriteCmdHelper(self, file):
6578 """Writes the cmd's helper."""
6579 self.type_handler.WriteCmdHelper(self, file)
6581 def WriteServiceImplementation(self, file):
6582 """Writes the service implementation for a command."""
6583 self.type_handler.WriteServiceImplementation(self, file)
6585 def WriteServiceUnitTest(self, file):
6586 """Writes the service implementation for a command."""
6587 self.type_handler.WriteServiceUnitTest(self, file)
6589 def WriteGLES2CLibImplementation(self, file):
6590 """Writes the GLES2 C Lib Implemention."""
6591 self.type_handler.WriteGLES2CLibImplementation(self, file)
6593 def WriteGLES2InterfaceHeader(self, file):
6594 """Writes the GLES2 Interface declaration."""
6595 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6597 def WriteGLES2InterfaceStub(self, file):
6598 """Writes the GLES2 Interface Stub declaration."""
6599 self.type_handler.WriteGLES2InterfaceStub(self, file)
6601 def WriteGLES2InterfaceStubImpl(self, file):
6602 """Writes the GLES2 Interface Stub declaration."""
6603 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6605 def WriteGLES2ImplementationHeader(self, file):
6606 """Writes the GLES2 Implemention declaration."""
6607 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6609 def WriteGLES2Implementation(self, file):
6610 """Writes the GLES2 Implemention definition."""
6611 self.type_handler.WriteGLES2Implementation(self, file)
6613 def WriteGLES2TraceImplementationHeader(self, file):
6614 """Writes the GLES2 Trace Implemention declaration."""
6615 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6617 def WriteGLES2TraceImplementation(self, file):
6618 """Writes the GLES2 Trace Implemention definition."""
6619 self.type_handler.WriteGLES2TraceImplementation(self, file)
6621 def WriteGLES2Header(self, file):
6622 """Writes the GLES2 Implemention unit test."""
6623 self.type_handler.WriteGLES2Header(self, file)
6625 def WriteGLES2ImplementationUnitTest(self, file):
6626 """Writes the GLES2 Implemention unit test."""
6627 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6629 def WriteDestinationInitalizationValidation(self, file):
6630 """Writes the client side destintion initialization validation."""
6631 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6633 def WriteFormatTest(self, file):
6634 """Writes the cmd's format test."""
6635 self.type_handler.WriteFormatTest(self, file)
6638 class PepperInterface(object):
6639 """A class that represents a function."""
6641 def __init__(self, info):
6642 self.name = info["name"]
6643 self.dev = info["dev"]
6645 def GetName(self):
6646 return self.name
6648 def GetInterfaceName(self):
6649 upperint = ""
6650 dev = ""
6651 if self.name:
6652 upperint = "_" + self.name.upper()
6653 if self.dev:
6654 dev = "_DEV"
6655 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6657 def GetInterfaceString(self):
6658 dev = ""
6659 if self.dev:
6660 dev = "(Dev)"
6661 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6663 def GetStructName(self):
6664 dev = ""
6665 if self.dev:
6666 dev = "_Dev"
6667 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6670 class ImmediateFunction(Function):
6671 """A class that represnets an immediate function command."""
6673 def __init__(self, func):
6674 new_args = []
6675 for arg in func.GetOriginalArgs():
6676 new_arg = arg.GetImmediateVersion()
6677 if new_arg:
6678 new_args.append(new_arg)
6680 cmd_args = []
6681 new_args_for_cmds = []
6682 for arg in func.args_for_cmds:
6683 new_arg = arg.GetImmediateVersion()
6684 if new_arg:
6685 new_args_for_cmds.append(new_arg)
6686 new_arg.AddCmdArgs(cmd_args)
6688 new_init_args = []
6689 for arg in new_args_for_cmds:
6690 arg.AddInitArgs(new_init_args)
6692 Function.__init__(
6693 self,
6694 func.original_name,
6695 "%sImmediate" % func.name,
6696 func.info,
6697 func.return_type,
6698 new_args,
6699 new_args_for_cmds,
6700 cmd_args,
6701 new_init_args,
6703 self.is_immediate = True
6705 def WriteCommandDescription(self, file):
6706 """Overridden from Function"""
6707 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6708 self.original_name)
6710 def WriteServiceImplementation(self, file):
6711 """Overridden from Function"""
6712 self.type_handler.WriteImmediateServiceImplementation(self, file)
6714 def WriteHandlerImplementation(self, file):
6715 """Overridden from Function"""
6716 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6718 def WriteServiceUnitTest(self, file):
6719 """Writes the service implementation for a command."""
6720 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6722 def WriteValidationCode(self, file):
6723 """Overridden from Function"""
6724 self.type_handler.WriteImmediateValidationCode(self, file)
6726 def WriteCmdArgFlag(self, file):
6727 """Overridden from Function"""
6728 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6730 def WriteCmdComputeSize(self, file):
6731 """Overridden from Function"""
6732 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6734 def WriteCmdSetHeader(self, file):
6735 """Overridden from Function"""
6736 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6738 def WriteCmdInit(self, file):
6739 """Overridden from Function"""
6740 self.type_handler.WriteImmediateCmdInit(self, file)
6742 def WriteCmdSet(self, file):
6743 """Overridden from Function"""
6744 self.type_handler.WriteImmediateCmdSet(self, file)
6746 def WriteCmdHelper(self, file):
6747 """Overridden from Function"""
6748 self.type_handler.WriteImmediateCmdHelper(self, file)
6750 def WriteFormatTest(self, file):
6751 """Overridden from Function"""
6752 self.type_handler.WriteImmediateFormatTest(self, file)
6755 class BucketFunction(Function):
6756 """A class that represnets a bucket version of a function command."""
6758 def __init__(self, func):
6759 new_args = []
6760 for arg in func.GetOriginalArgs():
6761 new_arg = arg.GetBucketVersion()
6762 if new_arg:
6763 new_args.append(new_arg)
6765 cmd_args = []
6766 new_args_for_cmds = []
6767 for arg in func.args_for_cmds:
6768 new_arg = arg.GetBucketVersion()
6769 if new_arg:
6770 new_args_for_cmds.append(new_arg)
6771 new_arg.AddCmdArgs(cmd_args)
6773 new_init_args = []
6774 for arg in new_args_for_cmds:
6775 arg.AddInitArgs(new_init_args)
6777 Function.__init__(
6778 self,
6779 func.original_name,
6780 "%sBucket" % func.name,
6781 func.info,
6782 func.return_type,
6783 new_args,
6784 new_args_for_cmds,
6785 cmd_args,
6786 new_init_args,
6789 # def InitFunction(self):
6790 # """Overridden from Function"""
6791 # pass
6793 def WriteCommandDescription(self, file):
6794 """Overridden from Function"""
6795 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6796 self.original_name)
6798 def WriteServiceImplementation(self, file):
6799 """Overridden from Function"""
6800 self.type_handler.WriteBucketServiceImplementation(self, file)
6802 def WriteHandlerImplementation(self, file):
6803 """Overridden from Function"""
6804 self.type_handler.WriteBucketHandlerImplementation(self, file)
6806 def WriteServiceUnitTest(self, file):
6807 """Writes the service implementation for a command."""
6808 self.type_handler.WriteBucketServiceUnitTest(self, file)
6811 def CreateArg(arg_string):
6812 """Creates an Argument."""
6813 arg_parts = arg_string.split()
6814 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6815 return None
6816 # Is this a pointer argument?
6817 elif arg_string.find('*') >= 0:
6818 if arg_parts[0] == 'NonImmediate':
6819 return NonImmediatePointerArgument(
6820 arg_parts[-1],
6821 " ".join(arg_parts[1:-1]))
6822 else:
6823 return PointerArgument(
6824 arg_parts[-1],
6825 " ".join(arg_parts[0:-1]))
6826 # Is this a resource argument? Must come after pointer check.
6827 elif arg_parts[0].startswith('GLidBind'):
6828 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6829 elif arg_parts[0].startswith('GLidZero'):
6830 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6831 elif arg_parts[0].startswith('GLid'):
6832 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6833 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6834 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6835 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6836 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6837 elif arg_parts[0].startswith('GLboolean'):
6838 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6839 elif arg_parts[0].startswith('GLintUniformLocation'):
6840 return UniformLocationArgument(arg_parts[-1])
6841 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6842 not arg_parts[0].startswith('GLintptr')):
6843 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6844 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6845 arg_parts[0].startswith('GLintptrNotNegative')):
6846 return SizeNotNegativeArgument(arg_parts[-1],
6847 " ".join(arg_parts[0:-1]),
6848 arg_parts[0][0:-11])
6849 elif arg_parts[0].startswith('GLsize'):
6850 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6851 else:
6852 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6855 class GLGenerator(object):
6856 """A class to generate GL command buffers."""
6858 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6860 def __init__(self, verbose):
6861 self.original_functions = []
6862 self.functions = []
6863 self.verbose = verbose
6864 self.errors = 0
6865 self._function_info = {}
6866 self._empty_type_handler = TypeHandler()
6867 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6868 self.pepper_interfaces = []
6869 self.interface_info = {}
6871 self._type_handlers = {
6872 'Bind': BindHandler(),
6873 'Create': CreateHandler(),
6874 'Custom': CustomHandler(),
6875 'Data': DataHandler(),
6876 'Delete': DeleteHandler(),
6877 'DELn': DELnHandler(),
6878 'GENn': GENnHandler(),
6879 'GETn': GETnHandler(),
6880 'GLchar': GLcharHandler(),
6881 'GLcharN': GLcharNHandler(),
6882 'HandWritten': HandWrittenHandler(),
6883 'Is': IsHandler(),
6884 'Manual': ManualHandler(),
6885 'PUT': PUTHandler(),
6886 'PUTn': PUTnHandler(),
6887 'PUTXn': PUTXnHandler(),
6888 'StateSet': StateSetHandler(),
6889 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6890 'StateSetFrontBack': StateSetFrontBackHandler(),
6891 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6892 'StateSetNamedParameter': StateSetNamedParameter(),
6893 'STRn': STRnHandler(),
6894 'Todo': TodoHandler(),
6897 for func_name in _FUNCTION_INFO:
6898 info = _FUNCTION_INFO[func_name]
6899 type = ''
6900 if 'type' in info:
6901 type = info['type']
6902 self._function_info[func_name] = FunctionInfo(info,
6903 self.GetTypeHandler(type))
6904 for interface in _PEPPER_INTERFACES:
6905 interface = PepperInterface(interface)
6906 self.pepper_interfaces.append(interface)
6907 self.interface_info[interface.GetName()] = interface
6909 def AddFunction(self, func):
6910 """Adds a function."""
6911 self.functions.append(func)
6913 def GetTypeHandler(self, name):
6914 """Gets a type info for the given type."""
6915 if len(name):
6916 if name in self._type_handlers:
6917 return self._type_handlers[name]
6918 else:
6919 raise KeyError("no such type handler: %s" % name)
6920 return self._empty_type_handler
6922 def GetFunctionInfo(self, name):
6923 """Gets a type info for the given function name."""
6924 if name in self._function_info:
6925 return self._function_info[name]
6926 return self._empty_function_info
6928 def Log(self, msg):
6929 """Prints something if verbose is true."""
6930 if self.verbose:
6931 print msg
6933 def Error(self, msg):
6934 """Prints an error."""
6935 print "Error: %s" % msg
6936 self.errors += 1
6938 def WriteLicense(self, file):
6939 """Writes the license."""
6940 file.Write(_LICENSE)
6942 def WriteNamespaceOpen(self, file):
6943 """Writes the code for the namespace."""
6944 file.Write("namespace gpu {\n")
6945 file.Write("namespace gles2 {\n")
6946 file.Write("\n")
6948 def WriteNamespaceClose(self, file):
6949 """Writes the code to close the namespace."""
6950 file.Write("} // namespace gles2\n")
6951 file.Write("} // namespace gpu\n")
6952 file.Write("\n")
6954 def ParseArgs(self, arg_string):
6955 """Parses a function arg string."""
6956 args = []
6957 num_pointer_args = 0
6958 parts = arg_string.split(',')
6959 is_gl_enum = False
6960 for arg_string in parts:
6961 if arg_string.startswith('GLenum '):
6962 is_gl_enum = True
6963 arg = CreateArg(arg_string)
6964 if arg:
6965 args.append(arg)
6966 if arg.IsPointer():
6967 num_pointer_args += 1
6968 return (args, num_pointer_args, is_gl_enum)
6970 def ParseGLH(self, filename):
6971 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6972 f = open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6973 functions = f.read()
6974 f.close()
6975 for line in functions.splitlines():
6976 match = self._function_re.match(line)
6977 if match:
6978 func_name = match.group(2)[2:]
6979 func_info = self.GetFunctionInfo(func_name)
6980 if func_info.type != 'Noop':
6981 return_type = match.group(1).strip()
6982 arg_string = match.group(3)
6983 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6984 # comment in to find out which functions use bare enums.
6985 # if is_gl_enum:
6986 # self.Log("%s uses bare GLenum" % func_name)
6987 args_for_cmds = args
6988 if hasattr(func_info, 'cmd_args'):
6989 (args_for_cmds, num_pointer_args, is_gl_enum) = (
6990 self.ParseArgs(getattr(func_info, 'cmd_args')))
6991 cmd_args = []
6992 for arg in args_for_cmds:
6993 arg.AddCmdArgs(cmd_args)
6994 init_args = []
6995 for arg in args_for_cmds:
6996 arg.AddInitArgs(init_args)
6997 return_arg = CreateArg(return_type + " result")
6998 if return_arg:
6999 init_args.append(return_arg)
7000 f = Function(func_name, func_name, func_info, return_type, args,
7001 args_for_cmds, cmd_args, init_args, num_pointer_args)
7002 self.original_functions.append(f)
7003 gen_cmd = f.GetInfo('gen_cmd')
7004 if gen_cmd == True or gen_cmd == None:
7005 self.AddFunction(f)
7006 f.type_handler.AddImmediateFunction(self, f)
7007 f.type_handler.AddBucketFunction(self, f)
7009 self.Log("Auto Generated Functions : %d" %
7010 len([f for f in self.functions if f.can_auto_generate or
7011 (not f.IsType('') and not f.IsType('Custom') and
7012 not f.IsType('Todo'))]))
7014 funcs = [f for f in self.functions if not f.can_auto_generate and
7015 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
7016 self.Log("Non Auto Generated Functions: %d" % len(funcs))
7018 for f in funcs:
7019 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
7021 def WriteCommandIds(self, filename):
7022 """Writes the command buffer format"""
7023 file = CHeaderWriter(filename)
7024 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7025 id = 256
7026 for func in self.functions:
7027 file.Write(" %-60s /* %d */ \\\n" %
7028 ("OP(%s)" % func.name, id))
7029 id += 1
7030 file.Write("\n")
7032 file.Write("enum CommandId {\n")
7033 file.Write(" kStartPoint = cmd::kLastCommonId, "
7034 "// All GLES2 commands start after this.\n")
7035 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7036 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7037 file.Write("#undef GLES2_CMD_OP\n")
7038 file.Write(" kNumCommands\n")
7039 file.Write("};\n")
7040 file.Write("\n")
7041 file.Close()
7043 def WriteFormat(self, filename):
7044 """Writes the command buffer format"""
7045 file = CHeaderWriter(filename)
7046 for func in self.functions:
7047 if True:
7048 #gen_cmd = func.GetInfo('gen_cmd')
7049 #if gen_cmd == True or gen_cmd == None:
7050 func.WriteStruct(file)
7051 file.Write("\n")
7052 file.Close()
7054 def WriteDocs(self, filename):
7055 """Writes the command buffer doc version of the commands"""
7056 file = CWriter(filename)
7057 for func in self.functions:
7058 if True:
7059 #gen_cmd = func.GetInfo('gen_cmd')
7060 #if gen_cmd == True or gen_cmd == None:
7061 func.WriteDocs(file)
7062 file.Write("\n")
7063 file.Close()
7065 def WriteFormatTest(self, filename):
7066 """Writes the command buffer format test."""
7067 file = CHeaderWriter(
7068 filename,
7069 "// This file contains unit tests for gles2 commmands\n"
7070 "// It is included by gles2_cmd_format_test.cc\n"
7071 "\n")
7073 for func in self.functions:
7074 if True:
7075 #gen_cmd = func.GetInfo('gen_cmd')
7076 #if gen_cmd == True or gen_cmd == None:
7077 func.WriteFormatTest(file)
7079 file.Close()
7081 def WriteCmdHelperHeader(self, filename):
7082 """Writes the gles2 command helper."""
7083 file = CHeaderWriter(filename)
7085 for func in self.functions:
7086 if True:
7087 #gen_cmd = func.GetInfo('gen_cmd')
7088 #if gen_cmd == True or gen_cmd == None:
7089 func.WriteCmdHelper(file)
7091 file.Close()
7093 def WriteServiceContextStateHeader(self, filename):
7094 """Writes the service context state header."""
7095 file = CHeaderWriter(
7096 filename,
7097 "// It is included by context_state.h\n")
7098 file.Write("struct EnableFlags {\n")
7099 file.Write(" EnableFlags();\n")
7100 for capability in _CAPABILITY_FLAGS:
7101 file.Write(" bool %s;\n" % capability['name'])
7102 file.Write("};\n\n")
7104 for state_name in sorted(_STATES.keys()):
7105 state = _STATES[state_name]
7106 for item in state['states']:
7107 file.Write("%s %s;\n" % (item['type'], item['name']))
7108 file.Write("\n")
7110 file.Close()
7112 def WriteClientContextStateHeader(self, filename):
7113 """Writes the client context state header."""
7114 file = CHeaderWriter(
7115 filename,
7116 "// It is included by client_context_state.h\n")
7117 file.Write("struct EnableFlags {\n")
7118 file.Write(" EnableFlags();\n")
7119 for capability in _CAPABILITY_FLAGS:
7120 file.Write(" bool %s;\n" % capability['name'])
7121 file.Write("};\n\n")
7123 file.Close()
7125 def WriteContextStateGetters(self, file, class_name):
7126 """Writes the state getters."""
7127 for gl_type in ["GLint", "GLfloat"]:
7128 file.Write("""
7129 bool %s::GetStateAs%s(
7130 GLenum pname, %s* params, GLsizei* num_written) const {
7131 switch (pname) {
7132 """ % (class_name, gl_type, gl_type))
7133 for state_name in sorted(_STATES.keys()):
7134 state = _STATES[state_name]
7135 if 'enum' in state:
7136 file.Write(" case %s:\n" % state['enum'])
7137 file.Write(" *num_written = %d;\n" % len(state['states']))
7138 file.Write(" if (params) {\n")
7139 for ndx,item in enumerate(state['states']):
7140 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7141 (ndx, gl_type, item['name']))
7142 file.Write(" }\n")
7143 file.Write(" return true;\n")
7144 else:
7145 for item in state['states']:
7146 file.Write(" case %s:\n" % item['enum'])
7147 file.Write(" *num_written = 1;\n")
7148 file.Write(" if (params) {\n")
7149 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7150 (gl_type, item['name']))
7151 file.Write(" }\n")
7152 file.Write(" return true;\n")
7153 for capability in _CAPABILITY_FLAGS:
7154 file.Write(" case GL_%s:\n" % capability['name'].upper())
7155 file.Write(" *num_written = 1;\n")
7156 file.Write(" if (params) {\n")
7157 file.Write(
7158 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7159 (gl_type, capability['name']))
7160 file.Write(" }\n")
7161 file.Write(" return true;\n")
7162 file.Write(""" default:
7163 return false;
7166 """)
7168 def WriteServiceContextStateImpl(self, filename):
7169 """Writes the context state service implementation."""
7170 file = CHeaderWriter(
7171 filename,
7172 "// It is included by context_state.cc\n")
7173 code = []
7174 for capability in _CAPABILITY_FLAGS:
7175 code.append("%s(%s)" %
7176 (capability['name'],
7177 ('false', 'true')['default' in capability]))
7178 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7179 ",\n ".join(code))
7180 file.Write("\n")
7182 file.Write("void ContextState::Initialize() {\n")
7183 for state_name in sorted(_STATES.keys()):
7184 state = _STATES[state_name]
7185 for item in state['states']:
7186 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7187 file.Write("}\n")
7189 file.Write("""
7190 void ContextState::InitCapabilities() const {
7191 """)
7192 for capability in _CAPABILITY_FLAGS:
7193 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7194 (capability['name'].upper(), capability['name']))
7195 file.Write("""}
7197 void ContextState::InitState() const {
7198 """)
7200 # We need to sort the keys so the expectations match
7201 for state_name in sorted(_STATES.keys()):
7202 state = _STATES[state_name]
7203 if state['type'] == 'FrontBack':
7204 num_states = len(state['states'])
7205 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7206 args = []
7207 for item in group:
7208 args.append('%s' % item['name'])
7209 file.Write(
7210 " gl%s(%s, %s);\n" %
7211 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7212 elif state['type'] == 'NamedParameter':
7213 for item in state['states']:
7214 if 'extension_flag' in item:
7215 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7216 item['extension_flag'])
7217 file.Write(" gl%s(%s, %s);\n" %
7218 (state['func'], item['enum'], item['name']))
7219 else:
7220 args = []
7221 for item in state['states']:
7222 args.append('%s' % item['name'])
7223 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7224 file.Write("}\n")
7226 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7227 switch (cap) {
7228 """)
7229 for capability in _CAPABILITY_FLAGS:
7230 file.Write(" case GL_%s:\n" % capability['name'].upper())
7231 file.Write(" return enable_flags.%s;\n" % capability['name'])
7232 file.Write(""" default:
7233 NOTREACHED();
7234 return false;
7237 """)
7239 self.WriteContextStateGetters(file, "ContextState")
7240 file.Close()
7242 def WriteClientContextStateImpl(self, filename):
7243 """Writes the context state client side implementation."""
7244 file = CHeaderWriter(
7245 filename,
7246 "// It is included by client_context_state.cc\n")
7247 code = []
7248 for capability in _CAPABILITY_FLAGS:
7249 code.append("%s(%s)" %
7250 (capability['name'],
7251 ('false', 'true')['default' in capability]))
7252 file.Write(
7253 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7254 ",\n ".join(code))
7255 file.Write("\n")
7257 file.Write("""
7258 bool ClientContextState::SetCapabilityState(
7259 GLenum cap, bool enabled, bool* changed) {
7260 *changed = false;
7261 switch (cap) {
7262 """)
7263 for capability in _CAPABILITY_FLAGS:
7264 file.Write(" case GL_%s:\n" % capability['name'].upper())
7265 file.Write(""" if (enable_flags.%(name)s != enabled) {
7266 *changed = true;
7267 enable_flags.%(name)s = enabled;
7269 return true;
7270 """ % capability)
7271 file.Write(""" default:
7272 return false;
7275 """)
7276 file.Write("""bool ClientContextState::GetEnabled(
7277 GLenum cap, bool* enabled) const {
7278 switch (cap) {
7279 """)
7280 for capability in _CAPABILITY_FLAGS:
7281 file.Write(" case GL_%s:\n" % capability['name'].upper())
7282 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7283 file.Write(" return true;\n")
7284 file.Write(""" default:
7285 return false;
7288 """)
7289 file.Close()
7291 def WriteServiceImplementation(self, filename):
7292 """Writes the service decorder implementation."""
7293 file = CHeaderWriter(
7294 filename,
7295 "// It is included by gles2_cmd_decoder.cc\n")
7297 for func in self.functions:
7298 if True:
7299 #gen_cmd = func.GetInfo('gen_cmd')
7300 #if gen_cmd == True or gen_cmd == None:
7301 func.WriteServiceImplementation(file)
7303 file.Write("""
7304 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7305 switch (cap) {
7306 """)
7307 for capability in _CAPABILITY_FLAGS:
7308 file.Write(" case GL_%s:\n" % capability['name'].upper())
7309 if 'state_flag' in capability:
7310 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7311 state_.enable_flags.%(name)s = enabled;
7312 %(state_flag)s = true;
7314 return false;
7315 """ % capability)
7316 else:
7317 file.Write(""" state_.enable_flags.%(name)s = enabled;
7318 return true;
7319 """ % capability)
7320 file.Write(""" default:
7321 NOTREACHED();
7322 return false;
7325 """)
7326 file.Close()
7328 def WriteServiceUnitTests(self, filename):
7329 """Writes the service decorder unit tests."""
7330 num_tests = len(self.functions)
7331 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7332 count = 0
7333 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7334 count += 1
7335 name = filename % count
7336 file = CHeaderWriter(
7337 name,
7338 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7339 file.SetFileNum(count)
7340 end = test_num + FUNCTIONS_PER_FILE
7341 if end > num_tests:
7342 end = num_tests
7343 for idx in range(test_num, end):
7344 func = self.functions[idx]
7345 if True:
7346 #gen_cmd = func.GetInfo('gen_cmd')
7347 #if gen_cmd == True or gen_cmd == None:
7348 if func.GetInfo('unit_test') == False:
7349 file.Write("// TODO(gman): %s\n" % func.name)
7350 else:
7351 func.WriteServiceUnitTest(file)
7353 file.Close()
7354 file = CHeaderWriter(
7355 filename % 0,
7356 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7357 file.Write(
7358 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7359 """)
7360 for capability in _CAPABILITY_FLAGS:
7361 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7362 (capability['name'].upper(),
7363 ('false', 'true')['default' in capability]))
7364 file.Write("""}
7366 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7367 """)
7369 # We need to sort the keys so the expectations match
7370 for state_name in sorted(_STATES.keys()):
7371 state = _STATES[state_name]
7372 if state['type'] == 'FrontBack':
7373 num_states = len(state['states'])
7374 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7375 args = []
7376 for item in group:
7377 if 'expected' in item:
7378 args.append(item['expected'])
7379 else:
7380 args.append(item['default'])
7381 file.Write(
7382 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7383 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7384 file.Write(" .Times(1)\n")
7385 file.Write(" .RetiresOnSaturation();\n")
7386 elif state['type'] == 'NamedParameter':
7387 for item in state['states']:
7388 if 'extension_flag' in item:
7389 continue
7390 file.Write(
7391 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7392 (state['func'], item['enum'], item['default']))
7393 file.Write(" .Times(1)\n")
7394 file.Write(" .RetiresOnSaturation();\n")
7395 else:
7396 args = []
7397 for item in state['states']:
7398 if 'expected' in item:
7399 args.append(item['expected'])
7400 else:
7401 args.append(item['default'])
7402 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7403 (state['func'], ", ".join(args)))
7404 file.Write(" .Times(1)\n")
7405 file.Write(" .RetiresOnSaturation();\n")
7406 file.Write("""}
7407 """)
7408 file.Close()
7410 def WriteGLES2Header(self, filename):
7411 """Writes the GLES2 header."""
7412 file = CHeaderWriter(
7413 filename,
7414 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7416 for func in self.original_functions:
7417 func.WriteGLES2Header(file)
7419 file.Write("\n")
7420 file.Close()
7422 def WriteGLES2CLibImplementation(self, filename):
7423 """Writes the GLES2 c lib implementation."""
7424 file = CHeaderWriter(
7425 filename,
7426 "// These functions emulate GLES2 over command buffers.\n")
7428 for func in self.original_functions:
7429 func.WriteGLES2CLibImplementation(file)
7431 file.Write("""
7432 namespace gles2 {
7434 extern const NameToFunc g_gles2_function_table[] = {
7435 """)
7436 for func in self.original_functions:
7437 file.Write(
7438 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7439 (func.name, func.name))
7440 file.Write(""" { NULL, NULL, },
7443 } // namespace gles2
7444 """)
7445 file.Close()
7447 def WriteGLES2InterfaceHeader(self, filename):
7448 """Writes the GLES2 interface header."""
7449 file = CHeaderWriter(
7450 filename,
7451 "// This file is included by gles2_interface.h to declare the\n"
7452 "// GL api functions.\n")
7453 for func in self.original_functions:
7454 func.WriteGLES2InterfaceHeader(file)
7455 file.Close()
7457 def WriteGLES2InterfaceStub(self, filename):
7458 """Writes the GLES2 interface stub header."""
7459 file = CHeaderWriter(
7460 filename,
7461 "// This file is included by gles2_interface_stub.h.\n")
7462 for func in self.original_functions:
7463 func.WriteGLES2InterfaceStub(file)
7464 file.Close()
7466 def WriteGLES2InterfaceStubImpl(self, filename):
7467 """Writes the GLES2 interface header."""
7468 file = CHeaderWriter(
7469 filename,
7470 "// This file is included by gles2_interface_stub.cc.\n")
7471 for func in self.original_functions:
7472 func.WriteGLES2InterfaceStubImpl(file)
7473 file.Close()
7475 def WriteGLES2ImplementationHeader(self, filename):
7476 """Writes the GLES2 Implementation header."""
7477 file = CHeaderWriter(
7478 filename,
7479 "// This file is included by gles2_implementation.h to declare the\n"
7480 "// GL api functions.\n")
7481 for func in self.original_functions:
7482 func.WriteGLES2ImplementationHeader(file)
7483 file.Close()
7485 def WriteGLES2Implementation(self, filename):
7486 """Writes the GLES2 Implementation."""
7487 file = CHeaderWriter(
7488 filename,
7489 "// This file is included by gles2_implementation.cc to define the\n"
7490 "// GL api functions.\n")
7491 for func in self.original_functions:
7492 func.WriteGLES2Implementation(file)
7493 file.Close()
7495 def WriteGLES2TraceImplementationHeader(self, filename):
7496 """Writes the GLES2 Trace Implementation header."""
7497 file = CHeaderWriter(
7498 filename,
7499 "// This file is included by gles2_trace_implementation.h\n")
7500 for func in self.original_functions:
7501 func.WriteGLES2TraceImplementationHeader(file)
7502 file.Close()
7504 def WriteGLES2TraceImplementation(self, filename):
7505 """Writes the GLES2 Trace Implementation."""
7506 file = CHeaderWriter(
7507 filename,
7508 "// This file is included by gles2_trace_implementation.cc\n")
7509 for func in self.original_functions:
7510 func.WriteGLES2TraceImplementation(file)
7511 file.Close()
7513 def WriteGLES2ImplementationUnitTests(self, filename):
7514 """Writes the GLES2 helper header."""
7515 file = CHeaderWriter(
7516 filename,
7517 "// This file is included by gles2_implementation.h to declare the\n"
7518 "// GL api functions.\n")
7519 for func in self.original_functions:
7520 func.WriteGLES2ImplementationUnitTest(file)
7521 file.Close()
7523 def WriteServiceUtilsHeader(self, filename):
7524 """Writes the gles2 auto generated utility header."""
7525 file = CHeaderWriter(filename)
7526 for enum in sorted(_ENUM_LISTS.keys()):
7527 file.Write("ValueValidator<%s> %s;\n" %
7528 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7529 file.Write("\n")
7530 file.Close()
7532 def WriteServiceUtilsImplementation(self, filename):
7533 """Writes the gles2 auto generated utility implementation."""
7534 file = CHeaderWriter(filename)
7535 enums = sorted(_ENUM_LISTS.keys())
7536 for enum in enums:
7537 if len(_ENUM_LISTS[enum]['valid']) > 0:
7538 file.Write("static const %s valid_%s_table[] = {\n" %
7539 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7540 for value in _ENUM_LISTS[enum]['valid']:
7541 file.Write(" %s,\n" % value)
7542 file.Write("};\n")
7543 file.Write("\n")
7544 file.Write("Validators::Validators()\n")
7545 pre = ': '
7546 post = ','
7547 for count, enum in enumerate(enums):
7548 if count + 1 == len(enums):
7549 post = ' {'
7550 if len(_ENUM_LISTS[enum]['valid']) > 0:
7551 code = """ %(pre)s%(name)s(
7552 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7554 else:
7555 code = """ %(pre)s%(name)s()%(post)s
7557 file.Write(code % {
7558 'name': ToUnderscore(enum),
7559 'pre': pre,
7560 'post': post,
7562 pre = ' '
7563 file.Write("}\n\n");
7564 file.Close()
7566 def WriteCommonUtilsHeader(self, filename):
7567 """Writes the gles2 common utility header."""
7568 file = CHeaderWriter(filename)
7569 enums = sorted(_ENUM_LISTS.keys())
7570 for enum in enums:
7571 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7572 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7573 file.Write("\n")
7574 file.Close()
7576 def WriteCommonUtilsImpl(self, filename):
7577 """Writes the gles2 common utility header."""
7578 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7579 dict = {}
7580 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7581 '../../third_party/khronos/GLES2/gl2ext.h',
7582 '../../gpu/GLES2/gl2chromium.h',
7583 '../../gpu/GLES2/gl2extchromium.h']:
7584 lines = open(fname).readlines()
7585 for line in lines:
7586 m = enum_re.match(line)
7587 if m:
7588 name = m.group(1)
7589 value = m.group(2)
7590 if len(value) <= 10 and not value in dict:
7591 dict[value] = name
7593 file = CHeaderWriter(filename)
7594 file.Write("static const GLES2Util::EnumToString "
7595 "enum_to_string_table[] = {\n")
7596 for value in dict:
7597 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7598 file.Write("""};
7600 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7601 enum_to_string_table;
7602 const size_t GLES2Util::enum_to_string_table_len_ =
7603 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7605 """)
7607 enums = sorted(_ENUM_LISTS.keys())
7608 for enum in enums:
7609 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7610 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7611 enum)
7612 if len(_ENUM_LISTS[enum]['valid']) > 0:
7613 file.Write(" static const EnumToString string_table[] = {\n")
7614 for value in _ENUM_LISTS[enum]['valid']:
7615 file.Write(' { %s, "%s" },\n' % (value, value))
7616 file.Write(""" };
7617 return GLES2Util::GetQualifiedEnumString(
7618 string_table, arraysize(string_table), value);
7621 """)
7622 else:
7623 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7624 NULL, 0, value);
7627 """)
7628 file.Close()
7630 def WritePepperGLES2Interface(self, filename, dev):
7631 """Writes the Pepper OpenGLES interface definition."""
7632 file = CHeaderWriter(
7633 filename,
7634 "// OpenGL ES interface.\n")
7636 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7637 if dev:
7638 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7639 else:
7640 file.Write("\n#ifndef __gl2_h_\n")
7641 for (k, v) in _GL_TYPES.iteritems():
7642 file.Write("typedef %s %s;\n" % (v, k))
7643 file.Write("#ifdef _WIN64\n")
7644 for (k, v) in _GL_TYPES_64.iteritems():
7645 file.Write("typedef %s %s;\n" % (v, k))
7646 file.Write("#else\n")
7647 for (k, v) in _GL_TYPES_32.iteritems():
7648 file.Write("typedef %s %s;\n" % (v, k))
7649 file.Write("#endif // _WIN64\n")
7650 file.Write("#endif // __gl2_h_\n\n")
7652 for interface in self.pepper_interfaces:
7653 if interface.dev != dev:
7654 continue
7655 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7656 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7657 file.Write("#define %s %s_1_0\n" %
7658 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7660 file.Write("\nstruct %s {\n" % interface.GetStructName())
7661 for func in self.original_functions:
7662 if not func.InPepperInterface(interface):
7663 continue
7665 original_arg = func.MakeTypedPepperArgString("")
7666 context_arg = "PP_Resource context"
7667 if len(original_arg):
7668 arg = context_arg + ", " + original_arg
7669 else:
7670 arg = context_arg
7671 file.Write(" %s (*%s)(%s);\n" %
7672 (func.return_type, func.GetPepperName(), arg))
7673 file.Write("};\n\n")
7676 file.Close()
7678 def WritePepperGLES2Implementation(self, filename):
7679 """Writes the Pepper OpenGLES interface implementation."""
7681 file = CWriter(filename)
7682 file.Write(_LICENSE)
7683 file.Write(_DO_NOT_EDIT_WARNING)
7685 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7686 file.Write("#include \"base/logging.h\"\n")
7687 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7688 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7689 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7691 file.Write("namespace ppapi {\n\n")
7692 file.Write("namespace {\n\n")
7694 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7695 " Enter3D;\n\n")
7697 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7698 " enter) {\n")
7699 file.Write(" DCHECK(enter);\n")
7700 file.Write(" DCHECK(enter->succeeded());\n")
7701 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7702 "gles2_impl();\n");
7703 file.Write("}\n\n");
7705 for func in self.original_functions:
7706 if not func.InAnyPepperExtension():
7707 continue
7709 original_arg = func.MakeTypedPepperArgString("")
7710 context_arg = "PP_Resource context_id"
7711 if len(original_arg):
7712 arg = context_arg + ", " + original_arg
7713 else:
7714 arg = context_arg
7715 file.Write("%s %s(%s) {\n" %
7716 (func.return_type, func.GetPepperName(), arg))
7717 file.Write(" Enter3D enter(context_id, true);\n")
7718 file.Write(" if (enter.succeeded()) {\n")
7720 return_str = "" if func.return_type == "void" else "return "
7721 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7722 (return_str, func.original_name,
7723 func.MakeOriginalArgString("")))
7724 file.Write(" }")
7725 if func.return_type == "void":
7726 file.Write("\n")
7727 else:
7728 file.Write(" else {\n")
7729 error_return = "0"
7730 if func.GetInfo("error_return"):
7731 error_return = func.GetInfo("error_return")
7732 elif func.return_type == "GLboolean":
7733 error_return = "GL_FALSE"
7734 elif "*" in func.return_type:
7735 error_return = "NULL"
7736 file.Write(" return %s;\n" % error_return)
7737 file.Write(" }\n")
7738 file.Write("}\n\n")
7740 file.Write("} // namespace\n")
7742 for interface in self.pepper_interfaces:
7743 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7744 (interface.GetStructName(), interface.GetName()))
7745 file.Write(" static const struct %s "
7746 "ppb_opengles2 = {\n" % interface.GetStructName())
7747 file.Write(" &")
7748 file.Write(",\n &".join(
7749 f.GetPepperName() for f in self.original_functions
7750 if f.InPepperInterface(interface)))
7751 file.Write("\n")
7753 file.Write(" };\n")
7754 file.Write(" return &ppb_opengles2;\n")
7755 file.Write("}\n")
7757 file.Write("} // namespace ppapi\n")
7758 file.Close()
7760 def WriteGLES2ToPPAPIBridge(self, filename):
7761 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7763 file = CWriter(filename)
7764 file.Write(_LICENSE)
7765 file.Write(_DO_NOT_EDIT_WARNING)
7767 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7768 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7769 file.Write("#endif\n")
7770 file.Write("#include <GLES2/gl2.h>\n")
7771 file.Write("#include <GLES2/gl2ext.h>\n")
7772 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7774 for func in self.original_functions:
7775 if not func.InAnyPepperExtension():
7776 continue
7778 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7780 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7781 (func.return_type, func.GetPepperName(),
7782 func.MakeTypedPepperArgString("")))
7783 return_str = "" if func.return_type == "void" else "return "
7784 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7785 original_arg = func.MakeOriginalArgString("")
7786 context_arg = "glGetCurrentContextPPAPI()"
7787 if len(original_arg):
7788 arg = context_arg + ", " + original_arg
7789 else:
7790 arg = context_arg
7791 if interface.GetName():
7792 file.Write(" const struct %s* ext = %s;\n" %
7793 (interface.GetStructName(), interface_str))
7794 file.Write(" if (ext)\n")
7795 file.Write(" %sext->%s(%s);\n" %
7796 (return_str, func.GetPepperName(), arg))
7797 if return_str:
7798 file.Write(" %s0;\n" % return_str)
7799 else:
7800 file.Write(" %s%s->%s(%s);\n" %
7801 (return_str, interface_str, func.GetPepperName(), arg))
7802 file.Write("}\n\n")
7803 file.Close()
7805 def WriteMojoGLCallVisitor(self, filename):
7806 """Provides the GL implementation for mojo"""
7807 file = CWriter(filename)
7808 file.Write(_LICENSE)
7809 file.Write(_DO_NOT_EDIT_WARNING)
7811 for func in self.original_functions:
7812 if not func.IsCoreGLFunction():
7813 continue
7814 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7815 (func.name, func.return_type,
7816 func.MakeTypedOriginalArgString(""),
7817 func.MakeOriginalArgString("")))
7819 file.Close()
7821 def main(argv):
7822 """This is the main function."""
7823 parser = OptionParser()
7824 parser.add_option(
7825 "-g", "--generate-implementation-templates", action="store_true",
7826 help="generates files that are generally hand edited..")
7827 parser.add_option(
7828 "--output-dir",
7829 help="base directory for resulting files, under chrome/src. default is "
7830 "empty. Use this if you want the result stored under gen.")
7831 parser.add_option(
7832 "-v", "--verbose", action="store_true",
7833 help="prints more output.")
7835 (options, args) = parser.parse_args(args=argv)
7837 # Add in states and capabilites to GLState
7838 for state_name in sorted(_STATES.keys()):
7839 state = _STATES[state_name]
7840 if 'enum' in state:
7841 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7842 else:
7843 for item in state['states']:
7844 if 'extension_flag' in item:
7845 continue
7846 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7847 for capability in _CAPABILITY_FLAGS:
7848 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7850 # This script lives under gpu/command_buffer, cd to base directory.
7851 os.chdir(os.path.dirname(__file__) + "/../..")
7853 gen = GLGenerator(options.verbose)
7854 gen.ParseGLH("common/GLES2/gl2.h")
7856 # Support generating files under gen/
7857 if options.output_dir != None:
7858 os.chdir(options.output_dir)
7860 gen.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7861 gen.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7862 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7863 gen.WritePepperGLES2Implementation(
7864 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7865 os.chdir("gpu/command_buffer")
7866 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7867 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7868 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7869 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7870 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7871 gen.WriteGLES2InterfaceStubImpl(
7872 "client/gles2_interface_stub_impl_autogen.h")
7873 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7874 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7875 gen.WriteGLES2ImplementationUnitTests(
7876 "client/gles2_implementation_unittest_autogen.h")
7877 gen.WriteGLES2TraceImplementationHeader(
7878 "client/gles2_trace_implementation_autogen.h")
7879 gen.WriteGLES2TraceImplementation(
7880 "client/gles2_trace_implementation_impl_autogen.h")
7881 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7882 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7883 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7884 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7885 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7886 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7887 gen.WriteClientContextStateImpl(
7888 "client/client_context_state_impl_autogen.h")
7889 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7890 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7891 gen.WriteServiceUtilsImplementation(
7892 "service/gles2_cmd_validation_implementation_autogen.h")
7893 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7894 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7895 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7896 gen.WriteMojoGLCallVisitor(
7897 "../../mojo/public/gles2/gles2_call_visitor_autogen.h")
7899 if gen.errors > 0:
7900 print "%d errors" % gen.errors
7901 return 1
7902 return 0
7905 if __name__ == '__main__':
7906 sys.exit(main(sys.argv[1:]))