Updated Khronos GLES2 headers.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
bloba10a6126c802a6661c27736b06fd7b6c534ca4ac
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) 2012 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_args: A string representing the argument list (what would appear in
1224 # C/C++ between the parentheses for the function declaration)
1225 # that the Pepper API expects for this function. Use this only if
1226 # the stable Pepper API differs from the GLES2 argument list.
1227 # invalid_test: False if no invalid test needed.
1228 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1229 # first_element_only: For PUT types, True if only the first element of an
1230 # array is used and we end up calling the single value
1231 # corresponding function. eg. TexParameteriv -> TexParameteri
1233 _FUNCTION_INFO = {
1234 'ActiveTexture': {
1235 'decoder_func': 'DoActiveTexture',
1236 'unit_test': False,
1237 'impl_func': False,
1238 'client_test': False,
1240 'AttachShader': {'decoder_func': 'DoAttachShader'},
1241 'BindAttribLocation': {
1242 'type': 'GLchar',
1243 'bucket': True,
1244 'needs_size': True,
1245 'immediate': False,
1247 'BindBuffer': {
1248 'type': 'Bind',
1249 'decoder_func': 'DoBindBuffer',
1250 'gen_func': 'GenBuffersARB',
1252 'BindFramebuffer': {
1253 'type': 'Bind',
1254 'decoder_func': 'DoBindFramebuffer',
1255 'gl_test_func': 'glBindFramebufferEXT',
1256 'gen_func': 'GenFramebuffersEXT',
1258 'BindRenderbuffer': {
1259 'type': 'Bind',
1260 'decoder_func': 'DoBindRenderbuffer',
1261 'gl_test_func': 'glBindRenderbufferEXT',
1262 'gen_func': 'GenRenderbuffersEXT',
1264 'BindTexture': {
1265 'type': 'Bind',
1266 'decoder_func': 'DoBindTexture',
1267 'gen_func': 'GenTextures',
1268 # TODO(gman): remove this once client side caching works.
1269 'client_test': False,
1271 'BlitFramebufferCHROMIUM': {
1272 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1273 'unit_test': False,
1274 'extension': True,
1275 'pepper_interface': 'FramebufferBlit',
1276 'defer_reads': True,
1277 'defer_draws': True,
1279 'BufferData': {
1280 'type': 'Manual',
1281 'immediate': False,
1282 'client_test': False,
1284 'BufferSubData': {
1285 'type': 'Data',
1286 'client_test': False,
1287 'decoder_func': 'DoBufferSubData',
1288 'immediate': False,
1290 'CheckFramebufferStatus': {
1291 'type': 'Is',
1292 'decoder_func': 'DoCheckFramebufferStatus',
1293 'gl_test_func': 'glCheckFramebufferStatusEXT',
1294 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1295 'result': ['GLenum'],
1297 'Clear': {
1298 'decoder_func': 'DoClear',
1299 'defer_draws': True,
1301 'ClearColor': {
1302 'type': 'StateSet',
1303 'state': 'ClearColor',
1305 'ClearDepthf': {
1306 'type': 'StateSet',
1307 'state': 'ClearDepthf',
1308 'decoder_func': 'glClearDepth',
1309 'gl_test_func': 'glClearDepth',
1310 'valid_args': {
1311 '0': '0.5f'
1314 'ColorMask': {
1315 'type': 'StateSet',
1316 'state': 'ColorMask',
1317 'no_gl': True,
1318 'expectation': False,
1320 'ConsumeTextureCHROMIUM': {
1321 'decoder_func': 'DoConsumeTextureCHROMIUM',
1322 'type': 'PUT',
1323 'data_type': 'GLbyte',
1324 'count': 64,
1325 'unit_test': False,
1326 'extension': True,
1327 'chromium': True,
1329 'ClearStencil': {
1330 'type': 'StateSet',
1331 'state': 'ClearStencil',
1333 'EnableFeatureCHROMIUM': {
1334 'type': 'Custom',
1335 'immediate': False,
1336 'decoder_func': 'DoEnableFeatureCHROMIUM',
1337 'expectation': False,
1338 'cmd_args': 'GLuint bucket_id, GLint* result',
1339 'result': ['GLint'],
1340 'extension': True,
1341 'chromium': True,
1342 'pepper_interface': 'ChromiumEnableFeature',
1344 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1345 'CompressedTexImage2D': {
1346 'type': 'Manual',
1347 'immediate': False,
1348 'bucket': True,
1350 'CompressedTexSubImage2D': {
1351 'type': 'Data',
1352 'bucket': True,
1353 'decoder_func': 'DoCompressedTexSubImage2D',
1354 'immediate': False,
1356 'CopyTexImage2D': {
1357 'decoder_func': 'DoCopyTexImage2D',
1358 'unit_test': False,
1359 'defer_reads': True,
1361 'CopyTexSubImage2D': {
1362 'decoder_func': 'DoCopyTexSubImage2D',
1363 'defer_reads': True,
1365 'CreateImageCHROMIUM': {
1366 'type': 'Manual',
1367 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1368 'result': ['GLuint'],
1369 'client_test': False,
1370 'gen_cmd': False,
1371 'expectation': False,
1372 'extension': True,
1373 'chromium': True,
1375 'DestroyImageCHROMIUM': {
1376 'type': 'Manual',
1377 'immediate': False,
1378 'client_test': False,
1379 'gen_cmd': False,
1380 'extension': True,
1381 'chromium': True,
1383 'GetImageParameterivCHROMIUM': {
1384 'type': 'Manual',
1385 'client_test': False,
1386 'gen_cmd': False,
1387 'expectation': False,
1388 'extension': True,
1389 'chromium': True,
1391 'CreateProgram': {
1392 'type': 'Create',
1393 'client_test': False,
1395 'CreateShader': {
1396 'type': 'Create',
1397 'client_test': False,
1399 'BlendColor': {
1400 'type': 'StateSet',
1401 'state': 'BlendColor',
1403 'BlendEquation': {
1404 'type': 'StateSetRGBAlpha',
1405 'state': 'BlendEquation',
1406 'valid_args': {
1407 '0': 'GL_FUNC_SUBTRACT'
1410 'BlendEquationSeparate': {
1411 'type': 'StateSet',
1412 'state': 'BlendEquation',
1413 'valid_args': {
1414 '0': 'GL_FUNC_SUBTRACT'
1417 'BlendFunc': {
1418 'type': 'StateSetRGBAlpha',
1419 'state': 'BlendFunc',
1421 'BlendFuncSeparate': {
1422 'type': 'StateSet',
1423 'state': 'BlendFunc',
1425 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1426 'StencilFunc': {
1427 'type': 'StateSetFrontBack',
1428 'state': 'StencilFunc',
1430 'StencilFuncSeparate': {
1431 'type': 'StateSetFrontBackSeparate',
1432 'state': 'StencilFunc',
1434 'StencilOp': {
1435 'type': 'StateSetFrontBack',
1436 'state': 'StencilOp',
1437 'valid_args': {
1438 '1': 'GL_INCR'
1441 'StencilOpSeparate': {
1442 'type': 'StateSetFrontBackSeparate',
1443 'state': 'StencilOp',
1444 'valid_args': {
1445 '1': 'GL_INCR'
1448 'Hint': {
1449 'type': 'StateSetNamedParameter',
1450 'state': 'Hint',
1452 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1453 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1454 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1455 'LineWidth': {
1456 'type': 'StateSet',
1457 'state': 'LineWidth',
1458 'valid_args': {
1459 '0': '0.5f'
1462 'PolygonOffset': {
1463 'type': 'StateSet',
1464 'state': 'PolygonOffset',
1466 'DeleteBuffers': {
1467 'type': 'DELn',
1468 'gl_test_func': 'glDeleteBuffersARB',
1469 'resource_type': 'Buffer',
1470 'resource_types': 'Buffers',
1472 'DeleteFramebuffers': {
1473 'type': 'DELn',
1474 'gl_test_func': 'glDeleteFramebuffersEXT',
1475 'resource_type': 'Framebuffer',
1476 'resource_types': 'Framebuffers',
1478 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1479 'DeleteRenderbuffers': {
1480 'type': 'DELn',
1481 'gl_test_func': 'glDeleteRenderbuffersEXT',
1482 'resource_type': 'Renderbuffer',
1483 'resource_types': 'Renderbuffers',
1485 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1486 'DeleteSharedIdsCHROMIUM': {
1487 'type': 'Custom',
1488 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1489 'impl_func': False,
1490 'expectation': False,
1491 'immediate': False,
1492 'extension': True,
1493 'chromium': True,
1495 'DeleteTextures': {
1496 'type': 'DELn',
1497 'resource_type': 'Texture',
1498 'resource_types': 'Textures',
1500 'DepthRangef': {
1501 'decoder_func': 'DoDepthRangef',
1502 'gl_test_func': 'glDepthRange',
1504 'DepthMask': {
1505 'type': 'StateSet',
1506 'state': 'DepthMask',
1507 'no_gl': True,
1508 'expectation': False,
1510 'DetachShader': {'decoder_func': 'DoDetachShader'},
1511 'Disable': {
1512 'decoder_func': 'DoDisable',
1513 'impl_func': False,
1514 'client_test': False,
1516 'DisableVertexAttribArray': {
1517 'decoder_func': 'DoDisableVertexAttribArray',
1518 'impl_decl': False,
1520 'DrawArrays': {
1521 'type': 'Manual',
1522 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1523 'defer_draws': True,
1525 'DrawElements': {
1526 'type': 'Manual',
1527 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1528 'GLenumIndexType type, GLuint index_offset',
1529 'client_test': False,
1530 'defer_draws': True,
1532 'Enable': {
1533 'decoder_func': 'DoEnable',
1534 'impl_func': False,
1535 'client_test': False,
1537 'EnableVertexAttribArray': {
1538 'decoder_func': 'DoEnableVertexAttribArray',
1539 'impl_decl': False,
1541 'Finish': {
1542 'impl_func': False,
1543 'client_test': False,
1544 'decoder_func': 'DoFinish',
1545 'defer_reads': True,
1547 'Flush': {
1548 'impl_func': False,
1549 'decoder_func': 'DoFlush',
1551 'FramebufferRenderbuffer': {
1552 'decoder_func': 'DoFramebufferRenderbuffer',
1553 'gl_test_func': 'glFramebufferRenderbufferEXT',
1555 'FramebufferTexture2D': {
1556 'decoder_func': 'DoFramebufferTexture2D',
1557 'gl_test_func': 'glFramebufferTexture2DEXT',
1559 'FramebufferTexture2DMultisampleEXT': {
1560 'decoder_func': 'DoFramebufferTexture2DMultisample',
1561 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1562 'expectation': False,
1563 'unit_test': False,
1564 'extension': True,
1566 'GenerateMipmap': {
1567 'decoder_func': 'DoGenerateMipmap',
1568 'gl_test_func': 'glGenerateMipmapEXT',
1570 'GenBuffers': {
1571 'type': 'GENn',
1572 'gl_test_func': 'glGenBuffersARB',
1573 'resource_type': 'Buffer',
1574 'resource_types': 'Buffers',
1576 'GenMailboxCHROMIUM': {
1577 'type': 'HandWritten',
1578 'immediate': False,
1579 'impl_func': False,
1580 'extension': True,
1581 'chromium': True,
1583 'GenFramebuffers': {
1584 'type': 'GENn',
1585 'gl_test_func': 'glGenFramebuffersEXT',
1586 'resource_type': 'Framebuffer',
1587 'resource_types': 'Framebuffers',
1589 'GenRenderbuffers': {
1590 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1591 'resource_type': 'Renderbuffer',
1592 'resource_types': 'Renderbuffers',
1594 'GenTextures': {
1595 'type': 'GENn',
1596 'gl_test_func': 'glGenTextures',
1597 'resource_type': 'Texture',
1598 'resource_types': 'Textures',
1600 'GenSharedIdsCHROMIUM': {
1601 'type': 'Custom',
1602 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1603 'impl_func': False,
1604 'expectation': False,
1605 'immediate': False,
1606 'extension': True,
1607 'chromium': True,
1609 'GetActiveAttrib': {
1610 'type': 'Custom',
1611 'immediate': False,
1612 'cmd_args':
1613 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1614 'void* result',
1615 'result': [
1616 'int32 success',
1617 'int32 size',
1618 'uint32 type',
1621 'GetActiveUniform': {
1622 'type': 'Custom',
1623 'immediate': False,
1624 'cmd_args':
1625 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1626 'void* result',
1627 'result': [
1628 'int32 success',
1629 'int32 size',
1630 'uint32 type',
1633 'GetAttachedShaders': {
1634 'type': 'Custom',
1635 'immediate': False,
1636 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1637 'result': ['SizedResult<GLuint>'],
1639 'GetAttribLocation': {
1640 'type': 'HandWritten',
1641 'immediate': False,
1642 'bucket': True,
1643 'needs_size': True,
1644 'cmd_args':
1645 'GLidProgram program, const char* name, NonImmediate GLint* location',
1646 'result': ['GLint'],
1647 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1649 'GetBooleanv': {
1650 'type': 'GETn',
1651 'result': ['SizedResult<GLboolean>'],
1652 'decoder_func': 'DoGetBooleanv',
1653 'gl_test_func': 'glGetBooleanv',
1655 'GetBufferParameteriv': {
1656 'type': 'GETn',
1657 'result': ['SizedResult<GLint>'],
1658 'decoder_func': 'DoGetBufferParameteriv',
1659 'expectation': False,
1660 'shadowed': True,
1662 'GetError': {
1663 'type': 'Is',
1664 'decoder_func': 'GetErrorState()->GetGLError',
1665 'impl_func': False,
1666 'result': ['GLenum'],
1667 'client_test': False,
1669 'GetFloatv': {
1670 'type': 'GETn',
1671 'result': ['SizedResult<GLfloat>'],
1672 'decoder_func': 'DoGetFloatv',
1673 'gl_test_func': 'glGetFloatv',
1675 'GetFramebufferAttachmentParameteriv': {
1676 'type': 'GETn',
1677 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1678 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1679 'result': ['SizedResult<GLint>'],
1681 'GetIntegerv': {
1682 'type': 'GETn',
1683 'result': ['SizedResult<GLint>'],
1684 'decoder_func': 'DoGetIntegerv',
1685 'client_test': False,
1687 'GetMaxValueInBufferCHROMIUM': {
1688 'type': 'Is',
1689 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1690 'result': ['GLuint'],
1691 'unit_test': False,
1692 'client_test': False,
1693 'extension': True,
1694 'chromium': True,
1695 'impl_func': False,
1697 'GetMultipleIntegervCHROMIUM': {
1698 'type': 'Custom',
1699 'immediate': False,
1700 'expectation': False,
1701 'extension': True,
1702 'chromium': True,
1703 'client_test': False,
1705 'GetProgramiv': {
1706 'type': 'GETn',
1707 'decoder_func': 'DoGetProgramiv',
1708 'result': ['SizedResult<GLint>'],
1709 'expectation': False,
1711 'GetProgramInfoCHROMIUM': {
1712 'type': 'Custom',
1713 'immediate': False,
1714 'expectation': False,
1715 'impl_func': False,
1716 'extension': True,
1717 'chromium': True,
1718 'client_test': False,
1719 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1720 'result': [
1721 'uint32 link_status',
1722 'uint32 num_attribs',
1723 'uint32 num_uniforms',
1726 'GetProgramInfoLog': {
1727 'type': 'STRn',
1728 'expectation': False,
1730 'GetRenderbufferParameteriv': {
1731 'type': 'GETn',
1732 'decoder_func': 'DoGetRenderbufferParameteriv',
1733 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1734 'result': ['SizedResult<GLint>'],
1736 'GetShaderiv': {
1737 'type': 'GETn',
1738 'decoder_func': 'DoGetShaderiv',
1739 'result': ['SizedResult<GLint>'],
1741 'GetShaderInfoLog': {
1742 'type': 'STRn',
1743 'get_len_func': 'glGetShaderiv',
1744 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1745 'unit_test': False,
1747 'GetShaderPrecisionFormat': {
1748 'type': 'Custom',
1749 'immediate': False,
1750 'cmd_args':
1751 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1752 'void* result',
1753 'result': [
1754 'int32 success',
1755 'int32 min_range',
1756 'int32 max_range',
1757 'int32 precision',
1760 'GetShaderSource': {
1761 'type': 'STRn',
1762 'get_len_func': 'DoGetShaderiv',
1763 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1764 'unit_test': False,
1765 'client_test': False,
1767 'GetString': {
1768 'type': 'Custom',
1769 'client_test': False,
1770 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1772 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1773 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1774 'GetTranslatedShaderSourceANGLE': {
1775 'type': 'STRn',
1776 'get_len_func': 'DoGetShaderiv',
1777 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1778 'unit_test': False,
1779 'extension': True,
1781 'GetUniformfv': {
1782 'type': 'Custom',
1783 'immediate': False,
1784 'result': ['SizedResult<GLfloat>'],
1786 'GetUniformiv': {
1787 'type': 'Custom',
1788 'immediate': False,
1789 'result': ['SizedResult<GLint>'],
1791 'GetUniformLocation': {
1792 'type': 'HandWritten',
1793 'immediate': False,
1794 'bucket': True,
1795 'needs_size': True,
1796 'cmd_args':
1797 'GLidProgram program, const char* name, NonImmediate GLint* location',
1798 'result': ['GLint'],
1799 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1801 'GetVertexAttribfv': {
1802 'type': 'GETn',
1803 'result': ['SizedResult<GLfloat>'],
1804 'impl_decl': False,
1805 'decoder_func': 'DoGetVertexAttribfv',
1806 'expectation': False,
1807 'client_test': False,
1809 'GetVertexAttribiv': {
1810 'type': 'GETn',
1811 'result': ['SizedResult<GLint>'],
1812 'impl_decl': False,
1813 'decoder_func': 'DoGetVertexAttribiv',
1814 'expectation': False,
1815 'client_test': False,
1817 'GetVertexAttribPointerv': {
1818 'type': 'Custom',
1819 'immediate': False,
1820 'result': ['SizedResult<GLuint>'],
1821 'client_test': False,
1823 'IsBuffer': {
1824 'type': 'Is',
1825 'decoder_func': 'DoIsBuffer',
1826 'expectation': False,
1828 'IsEnabled': {
1829 'type': 'Is',
1830 'decoder_func': 'DoIsEnabled',
1831 'impl_func': False,
1832 'expectation': False,
1834 'IsFramebuffer': {
1835 'type': 'Is',
1836 'decoder_func': 'DoIsFramebuffer',
1837 'expectation': False,
1839 'IsProgram': {
1840 'type': 'Is',
1841 'decoder_func': 'DoIsProgram',
1842 'expectation': False,
1844 'IsRenderbuffer': {
1845 'type': 'Is',
1846 'decoder_func': 'DoIsRenderbuffer',
1847 'expectation': False,
1849 'IsShader': {
1850 'type': 'Is',
1851 'decoder_func': 'DoIsShader',
1852 'expectation': False,
1854 'IsTexture': {
1855 'type': 'Is',
1856 'decoder_func': 'DoIsTexture',
1857 'expectation': False,
1859 'LinkProgram': {
1860 'decoder_func': 'DoLinkProgram',
1861 'impl_func': False,
1863 'MapBufferCHROMIUM': {
1864 'gen_cmd': False,
1865 'extension': True,
1866 'chromium': True,
1867 'client_test': False,
1869 'MapBufferSubDataCHROMIUM': {
1870 'gen_cmd': False,
1871 'extension': True,
1872 'chromium': True,
1873 'client_test': False,
1874 'pepper_interface': 'ChromiumMapSub',
1876 'MapImageCHROMIUM': {
1877 'gen_cmd': False,
1878 'extension': True,
1879 'chromium': True,
1880 'client_test': False,
1882 'MapTexSubImage2DCHROMIUM': {
1883 'gen_cmd': False,
1884 'extension': True,
1885 'chromium': True,
1886 'client_test': False,
1887 'pepper_interface': 'ChromiumMapSub',
1889 'PixelStorei': {'type': 'Manual'},
1890 'PostSubBufferCHROMIUM': {
1891 'type': 'Custom',
1892 'impl_func': False,
1893 'unit_test': False,
1894 'client_test': False,
1895 'extension': True,
1896 'chromium': True,
1898 'ProduceTextureCHROMIUM': {
1899 'decoder_func': 'DoProduceTextureCHROMIUM',
1900 'type': 'PUT',
1901 'data_type': 'GLbyte',
1902 'count': 64,
1903 'unit_test': False,
1904 'extension': True,
1905 'chromium': True,
1907 'RenderbufferStorage': {
1908 'decoder_func': 'DoRenderbufferStorage',
1909 'gl_test_func': 'glRenderbufferStorageEXT',
1910 'expectation': False,
1912 'RenderbufferStorageMultisampleCHROMIUM': {
1913 'cmd_comment':
1914 '// GL_CHROMIUM_framebuffer_multisample\n',
1915 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1916 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1917 'expectation': False,
1918 'unit_test': False,
1919 'extension': True,
1920 'pepper_interface': 'FramebufferMultisample',
1922 'RenderbufferStorageMultisampleEXT': {
1923 'cmd_comment':
1924 '// GL_EXT_multisampled_render_to_texture\n',
1925 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1926 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1927 'expectation': False,
1928 'unit_test': False,
1929 'extension': True,
1931 'ReadPixels': {
1932 'cmd_comment':
1933 '// ReadPixels has the result separated from the pixel buffer so that\n'
1934 '// it is easier to specify the result going to some specific place\n'
1935 '// that exactly fits the rectangle of pixels.\n',
1936 'type': 'Custom',
1937 'immediate': False,
1938 'impl_func': False,
1939 'client_test': False,
1940 'cmd_args':
1941 'GLint x, GLint y, GLsizei width, GLsizei height, '
1942 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1943 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1944 'uint32 result_shm_id, uint32 result_shm_offset, '
1945 'GLboolean async',
1946 'result': ['uint32'],
1947 'defer_reads': True,
1949 'RegisterSharedIdsCHROMIUM': {
1950 'type': 'Custom',
1951 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1952 'impl_func': False,
1953 'expectation': False,
1954 'immediate': False,
1955 'extension': True,
1956 'chromium': True,
1958 'ReleaseShaderCompiler': {
1959 'decoder_func': 'DoReleaseShaderCompiler',
1960 'unit_test': False,
1962 'ShaderBinary': {
1963 'type': 'Custom',
1964 'client_test': False,
1966 'ShaderSource': {
1967 'type': 'Manual',
1968 'immediate': False,
1969 'bucket': True,
1970 'needs_size': True,
1971 'client_test': False,
1972 'cmd_args':
1973 'GLuint shader, const char* data',
1974 'pepper_args':
1975 'GLuint shader, GLsizei count, const char** str, const GLint* length',
1977 'StencilMask': {
1978 'type': 'StateSetFrontBack',
1979 'state': 'StencilMask',
1980 'no_gl': True,
1981 'expectation': False,
1983 'StencilMaskSeparate': {
1984 'type': 'StateSetFrontBackSeparate',
1985 'state': 'StencilMask',
1986 'no_gl': True,
1987 'expectation': False,
1989 'SwapBuffers': {
1990 'impl_func': False,
1991 'decoder_func': 'DoSwapBuffers',
1992 'unit_test': False,
1993 'client_test': False,
1994 'extension': True,
1996 'TexImage2D': {
1997 'type': 'Manual',
1998 'immediate': False,
1999 'client_test': False,
2001 'TexParameterf': {
2002 'decoder_func': 'DoTexParameterf',
2003 'gl_test_func': 'glTexParameteri',
2004 'valid_args': {
2005 '2': 'GL_NEAREST'
2008 'TexParameteri': {
2009 'decoder_func': 'DoTexParameteri',
2010 'valid_args': {
2011 '2': 'GL_NEAREST'
2014 'TexParameterfv': {
2015 'type': 'PUT',
2016 'data_type': 'GLfloat',
2017 'data_value': 'GL_NEAREST',
2018 'count': 1,
2019 'decoder_func': 'DoTexParameterfv',
2020 'gl_test_func': 'glTexParameteri',
2021 'first_element_only': True,
2023 'TexParameteriv': {
2024 'type': 'PUT',
2025 'data_type': 'GLint',
2026 'data_value': 'GL_NEAREST',
2027 'count': 1,
2028 'decoder_func': 'DoTexParameteriv',
2029 'gl_test_func': 'glTexParameteri',
2030 'first_element_only': True,
2032 'TexSubImage2D': {
2033 'type': 'Manual',
2034 'immediate': False,
2035 'client_test': False,
2036 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2037 'GLint xoffset, GLint yoffset, '
2038 'GLsizei width, GLsizei height, '
2039 'GLenumTextureFormat format, GLenumPixelType type, '
2040 'const void* pixels, GLboolean internal'
2042 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2043 'Uniform1fv': {
2044 'type': 'PUTn',
2045 'data_type': 'GLfloat',
2046 'count': 1,
2047 'decoder_func': 'DoUniform1fv',
2049 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2050 'Uniform1iv': {
2051 'type': 'PUTn',
2052 'data_type': 'GLint',
2053 'count': 1,
2054 'decoder_func': 'DoUniform1iv',
2055 'unit_test': False,
2057 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2058 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2059 'Uniform2fv': {
2060 'type': 'PUTn',
2061 'data_type': 'GLfloat',
2062 'count': 2,
2063 'decoder_func': 'DoUniform2fv',
2065 'Uniform2iv': {
2066 'type': 'PUTn',
2067 'data_type': 'GLint',
2068 'count': 2,
2069 'decoder_func': 'DoUniform2iv',
2071 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2072 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2073 'Uniform3fv': {
2074 'type': 'PUTn',
2075 'data_type': 'GLfloat',
2076 'count': 3,
2077 'decoder_func': 'DoUniform3fv',
2079 'Uniform3iv': {
2080 'type': 'PUTn',
2081 'data_type': 'GLint',
2082 'count': 3,
2083 'decoder_func': 'DoUniform3iv',
2085 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2086 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2087 'Uniform4fv': {
2088 'type': 'PUTn',
2089 'data_type': 'GLfloat',
2090 'count': 4,
2091 'decoder_func': 'DoUniform4fv',
2093 'Uniform4iv': {
2094 'type': 'PUTn',
2095 'data_type': 'GLint',
2096 'count': 4,
2097 'decoder_func': 'DoUniform4iv',
2099 'UniformMatrix2fv': {
2100 'type': 'PUTn',
2101 'data_type': 'GLfloat',
2102 'count': 4,
2103 'decoder_func': 'DoUniformMatrix2fv',
2105 'UniformMatrix3fv': {
2106 'type': 'PUTn',
2107 'data_type': 'GLfloat',
2108 'count': 9,
2109 'decoder_func': 'DoUniformMatrix3fv',
2111 'UniformMatrix4fv': {
2112 'type': 'PUTn',
2113 'data_type': 'GLfloat',
2114 'count': 16,
2115 'decoder_func': 'DoUniformMatrix4fv',
2117 'UnmapBufferCHROMIUM': {
2118 'gen_cmd': False,
2119 'extension': True,
2120 'chromium': True,
2121 'client_test': False,
2123 'UnmapBufferSubDataCHROMIUM': {
2124 'gen_cmd': False,
2125 'extension': True,
2126 'chromium': True,
2127 'client_test': False,
2128 'pepper_interface': 'ChromiumMapSub',
2130 'UnmapImageCHROMIUM': {
2131 'gen_cmd': False,
2132 'extension': True,
2133 'chromium': True,
2134 'client_test': False,
2136 'UnmapTexSubImage2DCHROMIUM': {
2137 'gen_cmd': False,
2138 'extension': True,
2139 'chromium': True,
2140 'client_test': False,
2141 'pepper_interface': 'ChromiumMapSub',
2143 'UseProgram': {
2144 'decoder_func': 'DoUseProgram',
2145 'impl_func': False,
2146 'unit_test': False,
2148 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2149 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2150 'VertexAttrib1fv': {
2151 'type': 'PUT',
2152 'data_type': 'GLfloat',
2153 'count': 1,
2154 'decoder_func': 'DoVertexAttrib1fv',
2156 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2157 'VertexAttrib2fv': {
2158 'type': 'PUT',
2159 'data_type': 'GLfloat',
2160 'count': 2,
2161 'decoder_func': 'DoVertexAttrib2fv',
2163 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2164 'VertexAttrib3fv': {
2165 'type': 'PUT',
2166 'data_type': 'GLfloat',
2167 'count': 3,
2168 'decoder_func': 'DoVertexAttrib3fv',
2170 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2171 'VertexAttrib4fv': {
2172 'type': 'PUT',
2173 'data_type': 'GLfloat',
2174 'count': 4,
2175 'decoder_func': 'DoVertexAttrib4fv',
2177 'VertexAttribPointer': {
2178 'type': 'Manual',
2179 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2180 'GLenumVertexAttribType type, GLboolean normalized, '
2181 'GLsizei stride, GLuint offset',
2182 'client_test': False,
2184 'Scissor': {
2185 'type': 'StateSet',
2186 'state': 'Scissor',
2188 'Viewport': {
2189 'decoder_func': 'DoViewport',
2191 'ResizeCHROMIUM': {
2192 'type': 'Custom',
2193 'impl_func': False,
2194 'unit_test': False,
2195 'extension': True,
2196 'chromium': True,
2198 'GetRequestableExtensionsCHROMIUM': {
2199 'type': 'Custom',
2200 'impl_func': False,
2201 'immediate': False,
2202 'cmd_args': 'uint32 bucket_id',
2203 'extension': True,
2204 'chromium': True,
2206 'RequestExtensionCHROMIUM': {
2207 'type': 'Custom',
2208 'impl_func': False,
2209 'immediate': False,
2210 'client_test': False,
2211 'cmd_args': 'uint32 bucket_id',
2212 'extension': True,
2213 'chromium': True,
2215 'RateLimitOffscreenContextCHROMIUM': {
2216 'gen_cmd': False,
2217 'extension': True,
2218 'chromium': True,
2219 'client_test': False,
2221 'CreateStreamTextureCHROMIUM': {
2222 'type': 'Custom',
2223 'cmd_args': 'GLuint client_id, void* result',
2224 'result': ['GLuint'],
2225 'immediate': False,
2226 'impl_func': False,
2227 'expectation': False,
2228 'extension': True,
2229 'chromium': True,
2230 'client_test': False,
2232 'DestroyStreamTextureCHROMIUM': {
2233 'type': 'Custom',
2234 'impl_func': False,
2235 'expectation': False,
2236 'extension': True,
2237 'chromium': True,
2239 'TexImageIOSurface2DCHROMIUM': {
2240 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2241 'unit_test': False,
2242 'extension': True,
2243 'chromium': True,
2245 'CopyTextureCHROMIUM': {
2246 'decoder_func': 'DoCopyTextureCHROMIUM',
2247 'unit_test': False,
2248 'extension': True,
2249 'chromium': True,
2251 'TexStorage2DEXT': {
2252 'unit_test': False,
2253 'extension': True,
2254 'decoder_func': 'DoTexStorage2DEXT',
2256 'DrawArraysInstancedANGLE': {
2257 'type': 'Manual',
2258 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2259 'GLsizei primcount',
2260 'extension': True,
2261 'unit_test': False,
2262 'pepper_interface': 'InstancedArrays',
2263 'defer_draws': True,
2265 'DrawBuffersEXT': {
2266 'type': 'PUTn',
2267 'decoder_func': 'DoDrawBuffersEXT',
2268 'data_type': 'GLenum',
2269 'count': 1,
2270 'client_test': False,
2271 'unit_test': False,
2272 'extension': True,
2274 'DrawElementsInstancedANGLE': {
2275 'type': 'Manual',
2276 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2277 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2278 'extension': True,
2279 'unit_test': False,
2280 'client_test': False,
2281 'pepper_interface': 'InstancedArrays',
2282 'defer_draws': True,
2284 'VertexAttribDivisorANGLE': {
2285 'type': 'Manual',
2286 'cmd_args': 'GLuint index, GLuint divisor',
2287 'extension': True,
2288 'unit_test': False,
2289 'pepper_interface': 'InstancedArrays',
2291 'GenQueriesEXT': {
2292 'type': 'GENn',
2293 'gl_test_func': 'glGenQueriesARB',
2294 'resource_type': 'Query',
2295 'resource_types': 'Queries',
2296 'unit_test': False,
2297 'pepper_interface': 'Query',
2299 'DeleteQueriesEXT': {
2300 'type': 'DELn',
2301 'gl_test_func': 'glDeleteQueriesARB',
2302 'resource_type': 'Query',
2303 'resource_types': 'Queries',
2304 'unit_test': False,
2305 'pepper_interface': 'Query',
2307 'IsQueryEXT': {
2308 'gen_cmd': False,
2309 'client_test': False,
2310 'pepper_interface': 'Query',
2312 'BeginQueryEXT': {
2313 'type': 'Manual',
2314 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2315 'immediate': False,
2316 'gl_test_func': 'glBeginQuery',
2317 'pepper_interface': 'Query',
2319 'EndQueryEXT': {
2320 'type': 'Manual',
2321 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2322 'gl_test_func': 'glEndnQuery',
2323 'client_test': False,
2324 'pepper_interface': 'Query',
2326 'GetQueryivEXT': {
2327 'gen_cmd': False,
2328 'client_test': False,
2329 'gl_test_func': 'glGetQueryiv',
2330 'pepper_interface': 'Query',
2332 'GetQueryObjectuivEXT': {
2333 'gen_cmd': False,
2334 'client_test': False,
2335 'gl_test_func': 'glGetQueryObjectuiv',
2336 'pepper_interface': 'Query',
2338 'BindUniformLocationCHROMIUM': {
2339 'type': 'GLchar',
2340 'extension': True,
2341 'bucket': True,
2342 'needs_size': True,
2343 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2344 'immediate': False,
2346 'InsertEventMarkerEXT': {
2347 'type': 'GLcharN',
2348 'decoder_func': 'DoInsertEventMarkerEXT',
2349 'expectation': False,
2350 'extension': True,
2352 'PushGroupMarkerEXT': {
2353 'type': 'GLcharN',
2354 'decoder_func': 'DoPushGroupMarkerEXT',
2355 'expectation': False,
2356 'extension': True,
2358 'PopGroupMarkerEXT': {
2359 'decoder_func': 'DoPopGroupMarkerEXT',
2360 'expectation': False,
2361 'extension': True,
2362 'impl_func': False,
2365 'GenVertexArraysOES': {
2366 'type': 'GENn',
2367 'extension': True,
2368 'gl_test_func': 'glGenVertexArraysOES',
2369 'resource_type': 'VertexArray',
2370 'resource_types': 'VertexArrays',
2371 'unit_test': False,
2373 'BindVertexArrayOES': {
2374 'type': 'Bind',
2375 'extension': True,
2376 'gl_test_func': 'glBindVertexArrayOES',
2377 'decoder_func': 'DoBindVertexArrayOES',
2378 'gen_func': 'GenVertexArraysOES',
2379 'unit_test': False,
2380 'client_test': False,
2382 'DeleteVertexArraysOES': {
2383 'type': 'DELn',
2384 'extension': True,
2385 'gl_test_func': 'glDeleteVertexArraysOES',
2386 'resource_type': 'VertexArray',
2387 'resource_types': 'VertexArrays',
2388 'unit_test': False,
2390 'IsVertexArrayOES': {
2391 'type': 'Is',
2392 'extension': True,
2393 'gl_test_func': 'glIsVertexArrayOES',
2394 'decoder_func': 'DoIsVertexArrayOES',
2395 'expectation': False,
2396 'unit_test': False,
2398 'BindTexImage2DCHROMIUM': {
2399 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2400 'unit_test': False,
2401 'extension': True,
2402 'chromium': True,
2404 'ReleaseTexImage2DCHROMIUM': {
2405 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2406 'unit_test': False,
2407 'extension': True,
2408 'chromium': True,
2410 'ShallowFinishCHROMIUM': {
2411 'impl_func': False,
2412 'gen_cmd': False,
2413 'extension': True,
2414 'chromium': True,
2415 'client_test': False,
2417 'ShallowFlushCHROMIUM': {
2418 'impl_func': False,
2419 'gen_cmd': False,
2420 'extension': True,
2421 'chromium': True,
2422 'client_test': False,
2424 'TraceBeginCHROMIUM': {
2425 'type': 'Custom',
2426 'impl_func': False,
2427 'immediate': False,
2428 'client_test': False,
2429 'cmd_args': 'GLuint bucket_id',
2430 'extension': True,
2431 'chromium': True,
2433 'TraceEndCHROMIUM': {
2434 'impl_func': False,
2435 'immediate': False,
2436 'client_test': False,
2437 'decoder_func': 'DoTraceEndCHROMIUM',
2438 'unit_test': False,
2439 'extension': True,
2440 'chromium': True,
2442 'AsyncTexImage2DCHROMIUM': {
2443 'type': 'Manual',
2444 'immediate': False,
2445 'client_test': False,
2446 'extension': True,
2447 'chromium': True,
2449 'AsyncTexSubImage2DCHROMIUM': {
2450 'type': 'Manual',
2451 'immediate': False,
2452 'client_test': False,
2453 'extension': True,
2454 'chromium': True,
2456 'WaitAsyncTexImage2DCHROMIUM': {
2457 'type': 'Manual',
2458 'immediate': False,
2459 'client_test': False,
2460 'extension': True,
2461 'chromium': True,
2463 'DiscardFramebufferEXT': {
2464 'type': 'PUTn',
2465 'count': 1,
2466 'data_type': 'GLenum',
2467 'cmd_args': 'GLenum target, GLsizei count, '
2468 'const GLenum* attachments',
2469 'decoder_func': 'DoDiscardFramebufferEXT',
2470 'unit_test': False,
2471 'client_test': False,
2472 'extension': True,
2474 'LoseContextCHROMIUM': {
2475 'type': 'Manual',
2476 'impl_func': True,
2477 'extension': True,
2478 'chromium': True,
2480 'InsertSyncPointCHROMIUM': {
2481 'type': 'HandWritten',
2482 'impl_func': False,
2483 'extension': True,
2484 'chromium': True,
2486 'WaitSyncPointCHROMIUM': {
2487 'type': 'Custom',
2488 'impl_func': True,
2489 'extension': True,
2490 'chromium': True,
2492 'DiscardBackbufferCHROMIUM': {
2493 'type': 'Custom',
2494 'impl_func': True,
2495 'extension': True,
2496 'chromium': True,
2501 def Grouper(n, iterable, fillvalue=None):
2502 """Collect data into fixed-length chunks or blocks"""
2503 args = [iter(iterable)] * n
2504 return itertools.izip_longest(fillvalue=fillvalue, *args)
2507 def SplitWords(input_string):
2508 """Transforms a input_string into a list of lower-case components.
2510 Args:
2511 input_string: the input string.
2513 Returns:
2514 a list of lower-case words.
2516 if input_string.find('_') > -1:
2517 # 'some_TEXT_' -> 'some text'
2518 return input_string.replace('_', ' ').strip().lower().split()
2519 else:
2520 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2521 # mixed case.
2522 # look for capitalization to cut input_strings
2523 # 'SomeText' -> 'Some Text'
2524 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2525 # 'Vector3' -> 'Vector 3'
2526 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2527 return input_string.lower().split()
2530 def Lower(words):
2531 """Makes a lower-case identifier from words.
2533 Args:
2534 words: a list of lower-case words.
2536 Returns:
2537 the lower-case identifier.
2539 return '_'.join(words)
2542 def ToUnderscore(input_string):
2543 """converts CamelCase to camel_case."""
2544 words = SplitWords(input_string)
2545 return Lower(words)
2548 class CWriter(object):
2549 """Writes to a file formatting it for Google's style guidelines."""
2551 def __init__(self, filename):
2552 self.filename = filename
2553 self.file_num = 0
2554 self.content = []
2556 def SetFileNum(self, num):
2557 """Used to help write number files and tests."""
2558 self.file_num = num
2560 def Write(self, string):
2561 """Writes a string to a file spliting if it's > 80 characters."""
2562 lines = string.splitlines()
2563 num_lines = len(lines)
2564 for ii in range(0, num_lines):
2565 self.__WriteLine(lines[ii], ii < (num_lines - 1) or string[-1] == '\n')
2567 def __FindSplit(self, string):
2568 """Finds a place to split a string."""
2569 splitter = string.find('=')
2570 if splitter >= 1 and not string[splitter + 1] == '=' and splitter < 80:
2571 return splitter
2572 # parts = string.split('(')
2573 parts = re.split("(?<=[^\"])\((?!\")", string)
2574 fptr = re.compile('\*\w*\)')
2575 if len(parts) > 1:
2576 splitter = len(parts[0])
2577 for ii in range(1, len(parts)):
2578 # Don't split on the dot in "if (.condition)".
2579 if (not parts[ii - 1][-3:] == "if " and
2580 # Don't split "(.)" or "(.*fptr)".
2581 (len(parts[ii]) > 0 and
2582 not parts[ii][0] == ")" and not fptr.match(parts[ii]))
2583 and splitter < 80):
2584 return splitter
2585 splitter += len(parts[ii]) + 1
2586 done = False
2587 end = len(string)
2588 last_splitter = -1
2589 while not done:
2590 splitter = string[0:end].rfind(',')
2591 if splitter < 0 or (splitter > 0 and string[splitter - 1] == '"'):
2592 return last_splitter
2593 elif splitter >= 80:
2594 end = splitter
2595 else:
2596 return splitter
2598 def __WriteLine(self, line, ends_with_eol):
2599 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2600 if len(line) >= 80:
2601 i = self.__FindSplit(line)
2602 if i > 0:
2603 line1 = line[0:i + 1]
2604 if line1[-1] == ' ':
2605 line1 = line1[:-1]
2606 lineend = ''
2607 if line1[0] == '#':
2608 lineend = ' \\'
2609 nolint = ''
2610 if len(line1) > 80:
2611 nolint = ' // NOLINT'
2612 self.__AddLine(line1 + nolint + lineend + '\n')
2613 match = re.match("( +)", line1)
2614 indent = ""
2615 if match:
2616 indent = match.group(1)
2617 splitter = line[i]
2618 if not splitter == ',':
2619 indent = " " + indent
2620 self.__WriteLine(indent + line[i + 1:].lstrip(), True)
2621 return
2622 nolint = ''
2623 if len(line) > 80:
2624 nolint = ' // NOLINT'
2625 self.__AddLine(line + nolint)
2626 if ends_with_eol:
2627 self.__AddLine('\n')
2629 def __AddLine(self, line):
2630 self.content.append(line)
2632 def Close(self):
2633 """Close the file."""
2634 content = "".join(self.content)
2635 write_file = True
2636 if os.path.exists(self.filename):
2637 old_file = open(self.filename, "rb");
2638 old_content = old_file.read()
2639 old_file.close();
2640 if content == old_content:
2641 write_file = False
2642 if write_file:
2643 file = open(self.filename, "wb")
2644 file.write(content)
2645 file.close()
2648 class CHeaderWriter(CWriter):
2649 """Writes a C Header file."""
2651 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2653 def __init__(self, filename, file_comment = None):
2654 CWriter.__init__(self, filename)
2656 base = os.path.abspath(filename)
2657 while os.path.basename(base) != 'src':
2658 new_base = os.path.dirname(base)
2659 assert new_base != base # Prevent infinite loop.
2660 base = new_base
2662 hpath = os.path.relpath(filename, base)
2663 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2665 self.Write(_LICENSE)
2666 self.Write(_DO_NOT_EDIT_WARNING)
2667 if not file_comment == None:
2668 self.Write(file_comment)
2669 self.Write("#ifndef %s\n" % self.guard)
2670 self.Write("#define %s\n\n" % self.guard)
2672 def Close(self):
2673 self.Write("#endif // %s\n\n" % self.guard)
2674 CWriter.Close(self)
2676 class TypeHandler(object):
2677 """This class emits code for a particular type of function."""
2679 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2681 def __init__(self):
2682 pass
2684 def InitFunction(self, func):
2685 """Add or adjust anything type specific for this function."""
2686 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2687 func.AddCmdArg(DataSizeArgument('data_size'))
2689 def AddImmediateFunction(self, generator, func):
2690 """Adds an immediate version of a function."""
2691 # Generate an immediate command if there is only 1 pointer arg.
2692 immediate = func.GetInfo('immediate') # can be True, False or None
2693 if immediate == True or immediate == None:
2694 if func.num_pointer_args == 1 or immediate:
2695 generator.AddFunction(ImmediateFunction(func))
2697 def AddBucketFunction(self, generator, func):
2698 """Adds a bucket version of a function."""
2699 # Generate an immediate command if there is only 1 pointer arg.
2700 bucket = func.GetInfo('bucket') # can be True, False or None
2701 if bucket:
2702 generator.AddFunction(BucketFunction(func))
2704 def WriteStruct(self, func, file):
2705 """Writes a structure that matches the arguments to a function."""
2706 comment = func.GetInfo('cmd_comment')
2707 if not comment == None:
2708 file.Write(comment)
2709 file.Write("struct %s {\n" % func.name)
2710 file.Write(" typedef %s ValueType;\n" % func.name)
2711 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2712 func.WriteCmdArgFlag(file)
2713 file.Write("\n")
2714 result = func.GetInfo('result')
2715 if not result == None:
2716 if len(result) == 1:
2717 file.Write(" typedef %s Result;\n\n" % result[0])
2718 else:
2719 file.Write(" struct Result {\n")
2720 for line in result:
2721 file.Write(" %s;\n" % line)
2722 file.Write(" };\n\n")
2724 func.WriteCmdComputeSize(file)
2725 func.WriteCmdSetHeader(file)
2726 func.WriteCmdInit(file)
2727 func.WriteCmdSet(file)
2729 file.Write(" gpu::CommandHeader header;\n")
2730 args = func.GetCmdArgs()
2731 for arg in args:
2732 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2733 file.Write("};\n")
2734 file.Write("\n")
2736 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2737 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2738 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2739 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2740 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2741 offset = _SIZE_OF_COMMAND_HEADER
2742 for arg in args:
2743 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2744 (func.name, arg.name, offset))
2745 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2746 (func.name, arg.name, offset))
2747 offset += _SIZE_OF_UINT32
2748 if not result == None and len(result) > 1:
2749 offset = 0;
2750 for line in result:
2751 parts = line.split()
2752 name = parts[-1]
2753 check = """
2754 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2755 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2757 file.Write((check.strip() + "\n") % {
2758 'cmd_name': func.name,
2759 'field_name': name,
2760 'offset': offset,
2762 offset += _SIZE_OF_UINT32
2763 file.Write("\n")
2765 def WriteHandlerImplementation(self, func, file):
2766 """Writes the handler implementation for this command."""
2767 file.Write(" %s(%s);\n" %
2768 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2770 def WriteCmdSizeTest(self, func, file):
2771 """Writes the size test for a command."""
2772 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2774 def WriteFormatTest(self, func, file):
2775 """Writes a format test for a command."""
2776 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2777 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2778 (func.name, func.name))
2779 file.Write(" void* next_cmd = cmd.Set(\n")
2780 file.Write(" &cmd")
2781 args = func.GetCmdArgs()
2782 for value, arg in enumerate(args):
2783 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2784 file.Write(");\n")
2785 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2786 func.name)
2787 file.Write(" cmd.header.command);\n")
2788 func.type_handler.WriteCmdSizeTest(func, file)
2789 for value, arg in enumerate(args):
2790 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2791 (arg.type, value + 11, arg.name))
2792 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2793 file.Write(" next_cmd, sizeof(cmd));\n")
2794 file.Write("}\n")
2795 file.Write("\n")
2797 def WriteImmediateFormatTest(self, func, file):
2798 """Writes a format test for an immediate version of a command."""
2799 pass
2801 def WriteBucketFormatTest(self, func, file):
2802 """Writes a format test for a bucket version of a command."""
2803 pass
2805 def WriteGetDataSizeCode(self, func, file):
2806 """Writes the code to set data_size used in validation"""
2807 pass
2809 def WriteImmediateCmdSizeTest(self, func, file):
2810 """Writes a size test for an immediate version of a command."""
2811 file.Write(" // TODO(gman): Compute correct size.\n")
2812 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2814 def WriteImmediateHandlerImplementation (self, func, file):
2815 """Writes the handler impl for the immediate version of a command."""
2816 file.Write(" %s(%s);\n" %
2817 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2819 def WriteBucketHandlerImplementation (self, func, file):
2820 """Writes the handler impl for the bucket version of a command."""
2821 file.Write(" %s(%s);\n" %
2822 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2824 def WriteServiceImplementation(self, func, file):
2825 """Writes the service implementation for a command."""
2826 file.Write(
2827 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2828 file.Write(
2829 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2830 func.name)
2831 self.WriteHandlerDeferReadWrite(func, file);
2832 if len(func.GetOriginalArgs()) > 0:
2833 last_arg = func.GetLastOriginalArg()
2834 all_but_last_arg = func.GetOriginalArgs()[:-1]
2835 for arg in all_but_last_arg:
2836 arg.WriteGetCode(file)
2837 self.WriteGetDataSizeCode(func, file)
2838 last_arg.WriteGetCode(file)
2839 func.WriteHandlerValidation(file)
2840 func.WriteHandlerImplementation(file)
2841 file.Write(" return error::kNoError;\n")
2842 file.Write("}\n")
2843 file.Write("\n")
2845 def WriteImmediateServiceImplementation(self, func, file):
2846 """Writes the service implementation for an immediate version of command."""
2847 file.Write(
2848 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2849 file.Write(
2850 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2851 func.name)
2852 self.WriteHandlerDeferReadWrite(func, file);
2853 last_arg = func.GetLastOriginalArg()
2854 all_but_last_arg = func.GetOriginalArgs()[:-1]
2855 for arg in all_but_last_arg:
2856 arg.WriteGetCode(file)
2857 self.WriteGetDataSizeCode(func, file)
2858 last_arg.WriteGetCode(file)
2859 func.WriteHandlerValidation(file)
2860 func.WriteHandlerImplementation(file)
2861 file.Write(" return error::kNoError;\n")
2862 file.Write("}\n")
2863 file.Write("\n")
2865 def WriteBucketServiceImplementation(self, func, file):
2866 """Writes the service implementation for a bucket version of command."""
2867 file.Write(
2868 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2869 file.Write(
2870 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2871 func.name)
2872 self.WriteHandlerDeferReadWrite(func, file);
2873 last_arg = func.GetLastOriginalArg()
2874 all_but_last_arg = func.GetOriginalArgs()[:-1]
2875 for arg in all_but_last_arg:
2876 arg.WriteGetCode(file)
2877 self.WriteGetDataSizeCode(func, file)
2878 last_arg.WriteGetCode(file)
2879 func.WriteHandlerValidation(file)
2880 func.WriteHandlerImplementation(file)
2881 file.Write(" return error::kNoError;\n")
2882 file.Write("}\n")
2883 file.Write("\n")
2885 def WriteHandlerDeferReadWrite(self, func, file):
2886 """Writes the code to handle deferring reads or writes."""
2887 defer_draws = func.GetInfo('defer_draws')
2888 defer_reads = func.GetInfo('defer_reads')
2889 if defer_draws or defer_reads:
2890 file.Write(" error::Error error;\n")
2891 if defer_draws:
2892 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2893 file.Write(" if (error != error::kNoError)\n")
2894 file.Write(" return error;\n")
2895 if defer_reads:
2896 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2897 file.Write(" if (error != error::kNoError)\n")
2898 file.Write(" return error;\n")
2900 def WriteValidUnitTest(self, func, file, test, extra = {}):
2901 """Writes a valid unit test."""
2902 if func.GetInfo('expectation') == False:
2903 test = self._remove_expected_call_re.sub('', test)
2904 name = func.name
2905 arg_strings = []
2906 for count, arg in enumerate(func.GetOriginalArgs()):
2907 arg_strings.append(arg.GetValidArg(func, count, 0))
2908 gl_arg_strings = []
2909 for count, arg in enumerate(func.GetOriginalArgs()):
2910 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2911 gl_func_name = func.GetGLTestFunctionName()
2912 vars = {
2913 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2914 'name':name,
2915 'gl_func_name': gl_func_name,
2916 'args': ", ".join(arg_strings),
2917 'gl_args': ", ".join(gl_arg_strings),
2919 vars.update(extra)
2920 old_test = ""
2921 while (old_test != test):
2922 old_test = test
2923 test = test % vars
2924 file.Write(test % vars)
2926 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2927 """Writes a invalid unit test."""
2928 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2929 num_invalid_values = arg.GetNumInvalidValues(func)
2930 for value_index in range(0, num_invalid_values):
2931 arg_strings = []
2932 parse_result = "kNoError"
2933 gl_error = None
2934 for count, arg in enumerate(func.GetOriginalArgs()):
2935 if count == arg_index:
2936 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2937 count, value_index)
2938 else:
2939 arg_string = arg.GetValidArg(func, count, 0)
2940 arg_strings.append(arg_string)
2941 gl_arg_strings = []
2942 for arg in func.GetOriginalArgs():
2943 gl_arg_strings.append("_")
2944 gl_func_name = func.GetGLTestFunctionName()
2945 gl_error_test = ''
2946 if not gl_error == None:
2947 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2949 vars = {
2950 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2951 'name': func.name,
2952 'arg_index': arg_index,
2953 'value_index': value_index,
2954 'gl_func_name': gl_func_name,
2955 'args': ", ".join(arg_strings),
2956 'all_but_last_args': ", ".join(arg_strings[:-1]),
2957 'gl_args': ", ".join(gl_arg_strings),
2958 'parse_result': parse_result,
2959 'gl_error_test': gl_error_test,
2961 vars.update(extra)
2962 file.Write(test % vars)
2964 def WriteServiceUnitTest(self, func, file):
2965 """Writes the service unit test for a command."""
2966 valid_test = """
2967 TEST_F(%(test_name)s, %(name)sValidArgs) {
2968 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2969 SpecializedSetup<cmds::%(name)s, 0>(true);
2970 cmds::%(name)s cmd;
2971 cmd.Init(%(args)s);
2972 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2973 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2976 self.WriteValidUnitTest(func, file, valid_test)
2978 invalid_test = """
2979 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2980 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2981 SpecializedSetup<cmds::%(name)s, 0>(false);
2982 cmds::%(name)s cmd;
2983 cmd.Init(%(args)s);
2984 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2987 self.WriteInvalidUnitTest(func, file, invalid_test)
2989 def WriteImmediateServiceUnitTest(self, func, file):
2990 """Writes the service unit test for an immediate command."""
2991 file.Write("// TODO(gman): %s\n" % func.name)
2993 def WriteImmediateValidationCode(self, func, file):
2994 """Writes the validation code for an immediate version of a command."""
2995 pass
2997 def WriteBucketServiceUnitTest(self, func, file):
2998 """Writes the service unit test for a bucket command."""
2999 file.Write("// TODO(gman): %s\n" % func.name)
3001 def WriteBucketValidationCode(self, func, file):
3002 """Writes the validation code for a bucket version of a command."""
3003 file.Write("// TODO(gman): %s\n" % func.name)
3005 def WriteGLES2ImplementationDeclaration(self, func, file):
3006 """Writes the GLES2 Implemention declaration."""
3007 impl_decl = func.GetInfo('impl_decl')
3008 if impl_decl == None or impl_decl == True:
3009 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3010 (func.return_type, func.original_name,
3011 func.MakeTypedOriginalArgString("")))
3012 file.Write("\n")
3014 def WriteGLES2CLibImplementation(self, func, file):
3015 file.Write("%s GLES2%s(%s) {\n" %
3016 (func.return_type, func.name,
3017 func.MakeTypedOriginalArgString("")))
3018 result_string = "return "
3019 if func.return_type == "void":
3020 result_string = ""
3021 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3022 (result_string, func.original_name,
3023 func.MakeOriginalArgString("")))
3024 file.Write("}\n")
3026 def WriteGLES2Header(self, func, file):
3027 """Writes a re-write macro for GLES"""
3028 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3030 def WriteClientGLCallLog(self, func, file):
3031 """Writes a logging macro for the client side code."""
3032 comma = ""
3033 if len(func.GetOriginalArgs()):
3034 comma = " << "
3035 file.Write(
3036 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3037 (func.original_name, comma, func.MakeLogArgString()))
3039 def WriteClientGLReturnLog(self, func, file):
3040 """Writes the return value logging code."""
3041 if func.return_type != "void":
3042 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3044 def WriteGLES2ImplementationHeader(self, func, file):
3045 """Writes the GLES2 Implemention."""
3046 self.WriteGLES2ImplementationDeclaration(func, file)
3048 def WriteGLES2TraceImplementationHeader(self, func, file):
3049 """Writes the GLES2 Trace Implemention header."""
3050 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3051 (func.return_type, func.original_name,
3052 func.MakeTypedOriginalArgString("")))
3054 def WriteGLES2TraceImplementation(self, func, file):
3055 """Writes the GLES2 Trace Implemention."""
3056 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3057 (func.return_type, func.original_name,
3058 func.MakeTypedOriginalArgString("")))
3059 result_string = "return "
3060 if func.return_type == "void":
3061 result_string = ""
3062 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3063 func.name)
3064 file.Write(" %sgl_->%s(%s);\n" %
3065 (result_string, func.name, func.MakeOriginalArgString("")))
3066 file.Write("}\n")
3067 file.Write("\n")
3069 def WriteGLES2Implementation(self, func, file):
3070 """Writes the GLES2 Implemention."""
3071 impl_func = func.GetInfo('impl_func')
3072 impl_decl = func.GetInfo('impl_decl')
3073 gen_cmd = func.GetInfo('gen_cmd')
3074 if (func.can_auto_generate and
3075 (impl_func == None or impl_func == True) and
3076 (impl_decl == None or impl_decl == True) and
3077 (gen_cmd == None or gen_cmd == True)):
3078 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3079 (func.return_type, func.original_name,
3080 func.MakeTypedOriginalArgString("")))
3081 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3082 self.WriteClientGLCallLog(func, file)
3083 func.WriteDestinationInitalizationValidation(file)
3084 for arg in func.GetOriginalArgs():
3085 arg.WriteClientSideValidationCode(file, func)
3086 file.Write(" helper_->%s(%s);\n" %
3087 (func.name, func.MakeOriginalArgString("")))
3088 file.Write(" CheckGLError();\n")
3089 self.WriteClientGLReturnLog(func, file)
3090 file.Write("}\n")
3091 file.Write("\n")
3093 def WriteGLES2InterfaceHeader(self, func, file):
3094 """Writes the GLES2 Interface."""
3095 file.Write("virtual %s %s(%s) = 0;\n" %
3096 (func.return_type, func.original_name,
3097 func.MakeTypedOriginalArgString("")))
3099 def WriteGLES2InterfaceStub(self, func, file):
3100 """Writes the GLES2 Interface stub declaration."""
3101 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3102 (func.return_type, func.original_name,
3103 func.MakeTypedOriginalArgString("")))
3105 def WriteGLES2InterfaceStubImpl(self, func, file):
3106 """Writes the GLES2 Interface stub declaration."""
3107 args = func.GetOriginalArgs()
3108 arg_string = ", ".join(
3109 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3110 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3111 (func.return_type, func.original_name, arg_string))
3112 if func.return_type != "void":
3113 file.Write(" return 0;\n")
3114 file.Write("}\n")
3116 def WriteGLES2ImplementationUnitTest(self, func, file):
3117 """Writes the GLES2 Implemention unit test."""
3118 client_test = func.GetInfo('client_test')
3119 if (func.can_auto_generate and
3120 (client_test == None or client_test == True)):
3121 code = """
3122 TEST_F(GLES2ImplementationTest, %(name)s) {
3123 struct Cmds {
3124 cmds::%(name)s cmd;
3126 Cmds expected;
3127 expected.cmd.Init(%(cmd_args)s);
3129 gl_->%(name)s(%(args)s);
3130 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3133 cmd_arg_strings = []
3134 for count, arg in enumerate(func.GetCmdArgs()):
3135 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3136 count += 1
3137 gl_arg_strings = []
3138 for count, arg in enumerate(func.GetOriginalArgs()):
3139 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3140 file.Write(code % {
3141 'name': func.name,
3142 'args': ", ".join(gl_arg_strings),
3143 'cmd_args': ", ".join(cmd_arg_strings),
3145 else:
3146 if client_test != False:
3147 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3149 def WriteDestinationInitalizationValidation(self, func, file):
3150 """Writes the client side destintion initialization validation."""
3151 for arg in func.GetOriginalArgs():
3152 arg.WriteDestinationInitalizationValidation(file, func)
3154 def WriteTraceEvent(self, func, file):
3155 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3156 func.original_name)
3158 def WriteImmediateCmdComputeSize(self, func, file):
3159 """Writes the size computation code for the immediate version of a cmd."""
3160 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3161 file.Write(" return static_cast<uint32>(\n")
3162 file.Write(" sizeof(ValueType) + // NOLINT\n")
3163 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3164 file.Write(" }\n")
3165 file.Write("\n")
3167 def WriteImmediateCmdSetHeader(self, func, file):
3168 """Writes the SetHeader function for the immediate version of a cmd."""
3169 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3170 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3171 file.Write(" }\n")
3172 file.Write("\n")
3174 def WriteImmediateCmdInit(self, func, file):
3175 """Writes the Init function for the immediate version of a command."""
3176 raise NotImplementedError(func.name)
3178 def WriteImmediateCmdSet(self, func, file):
3179 """Writes the Set function for the immediate version of a command."""
3180 raise NotImplementedError(func.name)
3182 def WriteCmdHelper(self, func, file):
3183 """Writes the cmd helper definition for a cmd."""
3184 code = """ void %(name)s(%(typed_args)s) {
3185 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3186 if (c) {
3187 c->Init(%(args)s);
3192 file.Write(code % {
3193 "name": func.name,
3194 "typed_args": func.MakeTypedCmdArgString(""),
3195 "args": func.MakeCmdArgString(""),
3198 def WriteImmediateCmdHelper(self, func, file):
3199 """Writes the cmd helper definition for the immediate version of a cmd."""
3200 code = """ void %(name)s(%(typed_args)s) {
3201 const uint32 s = 0; // TODO(gman): compute correct size
3202 gles2::cmds::%(name)s* c =
3203 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3204 if (c) {
3205 c->Init(%(args)s);
3210 file.Write(code % {
3211 "name": func.name,
3212 "typed_args": func.MakeTypedCmdArgString(""),
3213 "args": func.MakeCmdArgString(""),
3217 class StateSetHandler(TypeHandler):
3218 """Handler for commands that simply set state."""
3220 def __init__(self):
3221 TypeHandler.__init__(self)
3223 def WriteHandlerImplementation(self, func, file):
3224 """Overrriden from TypeHandler."""
3225 state_name = func.GetInfo('state')
3226 state = _STATES[state_name]
3227 states = state['states']
3228 args = func.GetOriginalArgs()
3229 code = []
3230 for ndx,item in enumerate(states):
3231 if 'range_checks' in item:
3232 for range_check in item['range_checks']:
3233 code.append("%s %s" % (args[ndx].name, range_check['check']))
3234 if len(code):
3235 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3236 file.Write(
3237 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3238 ' "%s", "%s out of range");\n' %
3239 (func.name, args[ndx].name))
3240 file.Write(" return error::kNoError;\n")
3241 file.Write(" }\n")
3242 code = []
3243 for ndx,item in enumerate(states):
3244 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3245 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3246 for ndx,item in enumerate(states):
3247 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3248 if 'state_flag' in state:
3249 file.Write(" %s = true;\n" % state['state_flag'])
3250 if not func.GetInfo("no_gl"):
3251 file.Write(" %s(%s);\n" %
3252 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3253 file.Write(" }\n")
3255 def WriteServiceUnitTest(self, func, file):
3256 """Overrriden from TypeHandler."""
3257 TypeHandler.WriteServiceUnitTest(self, func, file)
3258 state_name = func.GetInfo('state')
3259 state = _STATES[state_name]
3260 states = state['states']
3261 for ndx,item in enumerate(states):
3262 if 'range_checks' in item:
3263 for check_ndx, range_check in enumerate(item['range_checks']):
3264 valid_test = """
3265 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3266 SpecializedSetup<cmds::%(name)s, 0>(false);
3267 cmds::%(name)s cmd;
3268 cmd.Init(%(args)s);
3269 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3270 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3273 name = func.name
3274 arg_strings = []
3275 for count, arg in enumerate(func.GetOriginalArgs()):
3276 arg_strings.append(arg.GetValidArg(func, count, 0))
3277 arg_strings[ndx] = range_check['test_value']
3278 vars = {
3279 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3280 'name': name,
3281 'ndx': ndx,
3282 'check_ndx': check_ndx,
3283 'args': ", ".join(arg_strings),
3285 file.Write(valid_test % vars)
3288 class StateSetRGBAlphaHandler(TypeHandler):
3289 """Handler for commands that simply set state that have rgb/alpha."""
3291 def __init__(self):
3292 TypeHandler.__init__(self)
3294 def WriteHandlerImplementation(self, func, file):
3295 """Overrriden from TypeHandler."""
3296 state_name = func.GetInfo('state')
3297 state = _STATES[state_name]
3298 states = state['states']
3299 args = func.GetOriginalArgs()
3300 num_args = len(args)
3301 code = []
3302 for ndx,item in enumerate(states):
3303 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3304 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3305 for ndx, item in enumerate(states):
3306 file.Write(" state_.%s = %s;\n" %
3307 (item['name'], args[ndx % num_args].name))
3308 if 'state_flag' in state:
3309 file.Write(" %s = true;\n" % state['state_flag'])
3310 if not func.GetInfo("no_gl"):
3311 file.Write(" %s(%s);\n" %
3312 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3313 file.Write(" }\n")
3316 class StateSetFrontBackSeparateHandler(TypeHandler):
3317 """Handler for commands that simply set state that have front/back."""
3319 def __init__(self):
3320 TypeHandler.__init__(self)
3322 def WriteHandlerImplementation(self, func, file):
3323 """Overrriden from TypeHandler."""
3324 state_name = func.GetInfo('state')
3325 state = _STATES[state_name]
3326 states = state['states']
3327 args = func.GetOriginalArgs()
3328 face = args[0].name
3329 num_args = len(args)
3330 file.Write(" bool changed = false;\n")
3331 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3332 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3333 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3334 code = []
3335 for ndx, item in enumerate(group):
3336 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3337 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3338 file.Write(" }\n")
3339 file.Write(" if (changed) {\n")
3340 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3341 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3342 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3343 for ndx, item in enumerate(group):
3344 file.Write(" state_.%s = %s;\n" %
3345 (item['name'], args[ndx + 1].name))
3346 file.Write(" }\n")
3347 if 'state_flag' in state:
3348 file.Write(" %s = true;\n" % state['state_flag'])
3349 if not func.GetInfo("no_gl"):
3350 file.Write(" %s(%s);\n" %
3351 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3352 file.Write(" }\n")
3355 class StateSetFrontBackHandler(TypeHandler):
3356 """Handler for commands that simply set state that set both front/back."""
3358 def __init__(self):
3359 TypeHandler.__init__(self)
3361 def WriteHandlerImplementation(self, func, file):
3362 """Overrriden from TypeHandler."""
3363 state_name = func.GetInfo('state')
3364 state = _STATES[state_name]
3365 states = state['states']
3366 args = func.GetOriginalArgs()
3367 num_args = len(args)
3368 code = []
3369 for group_ndx, group in enumerate(Grouper(num_args, states)):
3370 for ndx, item in enumerate(group):
3371 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3372 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3373 for group_ndx, group in enumerate(Grouper(num_args, states)):
3374 for ndx, item in enumerate(group):
3375 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3376 if 'state_flag' in state:
3377 file.Write(" %s = true;\n" % state['state_flag'])
3378 if not func.GetInfo("no_gl"):
3379 file.Write(" %s(%s);\n" %
3380 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3381 file.Write(" }\n")
3384 class StateSetNamedParameter(TypeHandler):
3385 """Handler for commands that set a state chosen with an enum parameter."""
3387 def __init__(self):
3388 TypeHandler.__init__(self)
3390 def WriteHandlerImplementation(self, func, file):
3391 """Overridden from TypeHandler."""
3392 state_name = func.GetInfo('state')
3393 state = _STATES[state_name]
3394 states = state['states']
3395 args = func.GetOriginalArgs()
3396 num_args = len(args)
3397 assert num_args == 2
3398 file.Write(" switch (%s) {\n" % args[0].name)
3399 for state in states:
3400 file.Write(" case %s:\n" % state['enum'])
3401 file.Write(" if (state_.%s != %s) {\n" %
3402 (state['name'], args[1].name))
3403 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3404 if not func.GetInfo("no_gl"):
3405 file.Write(" %s(%s);\n" %
3406 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3407 file.Write(" }\n")
3408 file.Write(" break;\n")
3409 file.Write(" default:\n")
3410 file.Write(" NOTREACHED();\n")
3411 file.Write(" }\n")
3414 class CustomHandler(TypeHandler):
3415 """Handler for commands that are auto-generated but require minor tweaks."""
3417 def __init__(self):
3418 TypeHandler.__init__(self)
3420 def WriteServiceImplementation(self, func, file):
3421 """Overrriden from TypeHandler."""
3422 pass
3424 def WriteImmediateServiceImplementation(self, func, file):
3425 """Overrriden from TypeHandler."""
3426 pass
3428 def WriteBucketServiceImplementation(self, func, file):
3429 """Overrriden from TypeHandler."""
3430 pass
3432 def WriteServiceUnitTest(self, func, file):
3433 """Overrriden from TypeHandler."""
3434 file.Write("// TODO(gman): %s\n\n" % func.name)
3436 def WriteImmediateServiceUnitTest(self, func, file):
3437 """Overrriden from TypeHandler."""
3438 file.Write("// TODO(gman): %s\n\n" % func.name)
3440 def WriteImmediateCmdGetTotalSize(self, func, file):
3441 """Overrriden from TypeHandler."""
3442 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3444 def WriteImmediateCmdInit(self, func, file):
3445 """Overrriden from TypeHandler."""
3446 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3447 self.WriteImmediateCmdGetTotalSize(func, file)
3448 file.Write(" SetHeader(total_size);\n")
3449 args = func.GetCmdArgs()
3450 for arg in args:
3451 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3452 file.Write(" }\n")
3453 file.Write("\n")
3455 def WriteImmediateCmdSet(self, func, file):
3456 """Overrriden from TypeHandler."""
3457 copy_args = func.MakeCmdArgString("_", False)
3458 file.Write(" void* Set(void* cmd%s) {\n" %
3459 func.MakeTypedCmdArgString("_", True))
3460 self.WriteImmediateCmdGetTotalSize(func, file)
3461 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3462 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3463 "cmd, total_size);\n")
3464 file.Write(" }\n")
3465 file.Write("\n")
3468 class TodoHandler(CustomHandler):
3469 """Handle for commands that are not yet implemented."""
3471 def AddImmediateFunction(self, generator, func):
3472 """Overrriden from TypeHandler."""
3473 pass
3475 def WriteImmediateFormatTest(self, func, file):
3476 """Overrriden from TypeHandler."""
3477 pass
3479 def WriteGLES2ImplementationUnitTest(self, func, file):
3480 """Overrriden from TypeHandler."""
3481 pass
3483 def WriteGLES2Implementation(self, func, file):
3484 """Overrriden from TypeHandler."""
3485 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3486 (func.return_type, func.original_name,
3487 func.MakeTypedOriginalArgString("")))
3488 file.Write(" // TODO: for now this is a no-op\n")
3489 file.Write(
3490 " SetGLError("
3491 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3492 func.name)
3493 if func.return_type != "void":
3494 file.Write(" return 0;\n")
3495 file.Write("}\n")
3496 file.Write("\n")
3498 def WriteServiceImplementation(self, func, file):
3499 """Overrriden from TypeHandler."""
3500 file.Write(
3501 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3502 file.Write(
3503 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3504 func.name)
3505 file.Write(" // TODO: for now this is a no-op\n")
3506 file.Write(
3507 " LOCAL_SET_GL_ERROR("
3508 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3509 func.name)
3510 file.Write(" return error::kNoError;\n")
3511 file.Write("}\n")
3512 file.Write("\n")
3515 class HandWrittenHandler(CustomHandler):
3516 """Handler for comands where everything must be written by hand."""
3518 def InitFunction(self, func):
3519 """Add or adjust anything type specific for this function."""
3520 CustomHandler.InitFunction(self, func)
3521 func.can_auto_generate = False
3523 def WriteStruct(self, func, file):
3524 """Overrriden from TypeHandler."""
3525 pass
3527 def WriteDocs(self, func, file):
3528 """Overrriden from TypeHandler."""
3529 pass
3531 def WriteServiceUnitTest(self, func, file):
3532 """Overrriden from TypeHandler."""
3533 file.Write("// TODO(gman): %s\n\n" % func.name)
3535 def WriteImmediateServiceUnitTest(self, func, file):
3536 """Overrriden from TypeHandler."""
3537 file.Write("// TODO(gman): %s\n\n" % func.name)
3539 def WriteBucketServiceUnitTest(self, func, file):
3540 """Overrriden from TypeHandler."""
3541 file.Write("// TODO(gman): %s\n\n" % func.name)
3543 def WriteServiceImplementation(self, func, file):
3544 """Overrriden from TypeHandler."""
3545 pass
3547 def WriteImmediateServiceImplementation(self, func, file):
3548 """Overrriden from TypeHandler."""
3549 pass
3551 def WriteBucketServiceImplementation(self, func, file):
3552 """Overrriden from TypeHandler."""
3553 pass
3555 def WriteImmediateCmdHelper(self, func, file):
3556 """Overrriden from TypeHandler."""
3557 pass
3559 def WriteBucketCmdHelper(self, func, file):
3560 """Overrriden from TypeHandler."""
3561 pass
3563 def WriteCmdHelper(self, func, file):
3564 """Overrriden from TypeHandler."""
3565 pass
3567 def WriteFormatTest(self, func, file):
3568 """Overrriden from TypeHandler."""
3569 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3571 def WriteImmediateFormatTest(self, func, file):
3572 """Overrriden from TypeHandler."""
3573 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3575 def WriteBucketFormatTest(self, func, file):
3576 """Overrriden from TypeHandler."""
3577 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3581 class ManualHandler(CustomHandler):
3582 """Handler for commands who's handlers must be written by hand."""
3584 def __init__(self):
3585 CustomHandler.__init__(self)
3587 def InitFunction(self, func):
3588 """Overrriden from TypeHandler."""
3589 if (func.name == 'CompressedTexImage2DBucket'):
3590 func.cmd_args = func.cmd_args[:-1]
3591 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3592 else:
3593 CustomHandler.InitFunction(self, func)
3595 def WriteServiceImplementation(self, func, file):
3596 """Overrriden from TypeHandler."""
3597 pass
3599 def WriteBucketServiceImplementation(self, func, file):
3600 """Overrriden from TypeHandler."""
3601 pass
3603 def WriteServiceUnitTest(self, func, file):
3604 """Overrriden from TypeHandler."""
3605 file.Write("// TODO(gman): %s\n\n" % func.name)
3607 def WriteImmediateServiceUnitTest(self, func, file):
3608 """Overrriden from TypeHandler."""
3609 file.Write("// TODO(gman): %s\n\n" % func.name)
3611 def WriteImmediateServiceImplementation(self, func, file):
3612 """Overrriden from TypeHandler."""
3613 pass
3615 def WriteImmediateFormatTest(self, func, file):
3616 """Overrriden from TypeHandler."""
3617 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3619 def WriteGLES2Implementation(self, func, file):
3620 """Overrriden from TypeHandler."""
3621 if func.GetInfo('impl_func'):
3622 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3624 def WriteGLES2ImplementationHeader(self, func, file):
3625 """Overrriden from TypeHandler."""
3626 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3627 (func.return_type, func.original_name,
3628 func.MakeTypedOriginalArgString("")))
3629 file.Write("\n")
3631 def WriteImmediateCmdGetTotalSize(self, func, file):
3632 """Overrriden from TypeHandler."""
3633 # TODO(gman): Move this data to _FUNCTION_INFO?
3634 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3637 class DataHandler(TypeHandler):
3638 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3639 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3640 def __init__(self):
3641 TypeHandler.__init__(self)
3643 def InitFunction(self, func):
3644 """Overrriden from TypeHandler."""
3645 if func.name == 'CompressedTexSubImage2DBucket':
3646 func.cmd_args = func.cmd_args[:-1]
3647 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3649 def WriteGetDataSizeCode(self, func, file):
3650 """Overrriden from TypeHandler."""
3651 # TODO(gman): Move this data to _FUNCTION_INFO?
3652 name = func.name
3653 if name.endswith("Immediate"):
3654 name = name[0:-9]
3655 if name == 'BufferData' or name == 'BufferSubData':
3656 file.Write(" uint32 data_size = size;\n")
3657 elif (name == 'CompressedTexImage2D' or
3658 name == 'CompressedTexSubImage2D'):
3659 file.Write(" uint32 data_size = imageSize;\n")
3660 elif (name == 'CompressedTexSubImage2DBucket'):
3661 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3662 file.Write(" uint32 data_size = bucket->size();\n")
3663 file.Write(" GLsizei imageSize = data_size;\n")
3664 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3665 code = """ uint32 data_size;
3666 if (!GLES2Util::ComputeImageDataSize(
3667 width, height, format, type, unpack_alignment_, &data_size)) {
3668 return error::kOutOfBounds;
3671 file.Write(code)
3672 else:
3673 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3675 def WriteImmediateCmdGetTotalSize(self, func, file):
3676 """Overrriden from TypeHandler."""
3677 pass
3679 def WriteImmediateCmdSizeTest(self, func, file):
3680 """Overrriden from TypeHandler."""
3681 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3683 def WriteImmediateCmdInit(self, func, file):
3684 """Overrriden from TypeHandler."""
3685 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3686 self.WriteImmediateCmdGetTotalSize(func, file)
3687 file.Write(" SetHeader(total_size);\n")
3688 args = func.GetCmdArgs()
3689 for arg in args:
3690 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3691 file.Write(" }\n")
3692 file.Write("\n")
3694 def WriteImmediateCmdSet(self, func, file):
3695 """Overrriden from TypeHandler."""
3696 copy_args = func.MakeCmdArgString("_", False)
3697 file.Write(" void* Set(void* cmd%s) {\n" %
3698 func.MakeTypedCmdArgString("_", True))
3699 self.WriteImmediateCmdGetTotalSize(func, file)
3700 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3701 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3702 "cmd, total_size);\n")
3703 file.Write(" }\n")
3704 file.Write("\n")
3706 def WriteImmediateFormatTest(self, func, file):
3707 """Overrriden from TypeHandler."""
3708 # TODO(gman): Remove this exception.
3709 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3710 return
3712 def WriteServiceUnitTest(self, func, file):
3713 """Overrriden from TypeHandler."""
3714 file.Write("// TODO(gman): %s\n\n" % func.name)
3716 def WriteImmediateServiceUnitTest(self, func, file):
3717 """Overrriden from TypeHandler."""
3718 file.Write("// TODO(gman): %s\n\n" % func.name)
3720 def WriteBucketServiceImplementation(self, func, file):
3721 """Overrriden from TypeHandler."""
3722 if not func.name == 'CompressedTexSubImage2DBucket':
3723 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3726 class BindHandler(TypeHandler):
3727 """Handler for glBind___ type functions."""
3729 def __init__(self):
3730 TypeHandler.__init__(self)
3732 def WriteServiceUnitTest(self, func, file):
3733 """Overrriden from TypeHandler."""
3735 if len(func.GetOriginalArgs()) == 1:
3736 valid_test = """
3737 TEST_F(%(test_name)s, %(name)sValidArgs) {
3738 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3739 SpecializedSetup<cmds::%(name)s, 0>(true);
3740 cmds::%(name)s cmd;
3741 cmd.Init(%(args)s);
3742 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3743 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3746 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3747 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3748 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3749 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3750 SpecializedSetup<cmds::%(name)s, 0>(true);
3751 cmds::%(name)s cmd;
3752 cmd.Init(kNewClientId);
3753 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3754 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3755 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3758 gen_func_names = {
3760 self.WriteValidUnitTest(func, file, valid_test, {
3761 'resource_type': func.GetOriginalArgs()[0].resource_type,
3762 'gl_gen_func_name': func.GetInfo("gen_func"),
3764 else:
3765 valid_test = """
3766 TEST_F(%(test_name)s, %(name)sValidArgs) {
3767 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3768 SpecializedSetup<cmds::%(name)s, 0>(true);
3769 cmds::%(name)s cmd;
3770 cmd.Init(%(args)s);
3771 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3772 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3775 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3776 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3777 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3778 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3779 SpecializedSetup<cmds::%(name)s, 0>(true);
3780 cmds::%(name)s cmd;
3781 cmd.Init(%(first_arg)s, kNewClientId);
3782 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3783 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3784 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3787 gen_func_names = {
3789 self.WriteValidUnitTest(func, file, valid_test, {
3790 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3791 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3792 'resource_type': func.GetOriginalArgs()[1].resource_type,
3793 'gl_gen_func_name': func.GetInfo("gen_func"),
3796 invalid_test = """
3797 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3798 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3799 SpecializedSetup<cmds::%(name)s, 0>(false);
3800 cmds::%(name)s cmd;
3801 cmd.Init(%(args)s);
3802 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3805 self.WriteInvalidUnitTest(func, file, invalid_test)
3807 def WriteGLES2Implementation(self, func, file):
3808 """Writes the GLES2 Implemention."""
3810 impl_func = func.GetInfo('impl_func')
3811 impl_decl = func.GetInfo('impl_decl')
3813 if (func.can_auto_generate and
3814 (impl_func == None or impl_func == True) and
3815 (impl_decl == None or impl_decl == True)):
3817 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3818 (func.return_type, func.original_name,
3819 func.MakeTypedOriginalArgString("")))
3820 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3821 func.WriteDestinationInitalizationValidation(file)
3822 self.WriteClientGLCallLog(func, file)
3823 for arg in func.GetOriginalArgs():
3824 arg.WriteClientSideValidationCode(file, func)
3826 code = """ if (Is%(type)sReservedId(%(id)s)) {
3827 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3828 return;
3830 if (Bind%(type)sHelper(%(arg_string)s)) {
3831 helper_->%(name)s(%(arg_string)s);
3833 CheckGLError();
3837 name_arg = None
3838 if len(func.GetOriginalArgs()) == 1:
3839 # Bind functions that have no target (like BindVertexArrayOES)
3840 name_arg = func.GetOriginalArgs()[0]
3841 else:
3842 # Bind functions that have both a target and a name (like BindTexture)
3843 name_arg = func.GetOriginalArgs()[1]
3845 file.Write(code % {
3846 'name': func.name,
3847 'arg_string': func.MakeOriginalArgString(""),
3848 'id': name_arg.name,
3849 'type': name_arg.resource_type,
3850 'lc_type': name_arg.resource_type.lower(),
3853 def WriteGLES2ImplementationUnitTest(self, func, file):
3854 """Overrriden from TypeHandler."""
3855 client_test = func.GetInfo('client_test')
3856 if client_test == False:
3857 return
3858 code = """
3859 TEST_F(GLES2ImplementationTest, %(name)s) {
3860 struct Cmds {
3861 cmds::%(name)s cmd;
3863 Cmds expected;
3864 expected.cmd.Init(%(cmd_args)s);
3866 gl_->%(name)s(%(args)s);
3867 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3868 ClearCommands();
3869 gl_->%(name)s(%(args)s);
3870 EXPECT_TRUE(NoCommandsWritten());
3873 cmd_arg_strings = []
3874 for count, arg in enumerate(func.GetCmdArgs()):
3875 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3876 count += 1
3877 gl_arg_strings = []
3878 for count, arg in enumerate(func.GetOriginalArgs()):
3879 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3880 file.Write(code % {
3881 'name': func.name,
3882 'args': ", ".join(gl_arg_strings),
3883 'cmd_args': ", ".join(cmd_arg_strings),
3887 class GENnHandler(TypeHandler):
3888 """Handler for glGen___ type functions."""
3890 def __init__(self):
3891 TypeHandler.__init__(self)
3893 def InitFunction(self, func):
3894 """Overrriden from TypeHandler."""
3895 pass
3897 def WriteGetDataSizeCode(self, func, file):
3898 """Overrriden from TypeHandler."""
3899 code = """ uint32 data_size;
3900 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3901 return error::kOutOfBounds;
3904 file.Write(code)
3906 def WriteHandlerImplementation (self, func, file):
3907 """Overrriden from TypeHandler."""
3908 file.Write(" if (!%sHelper(n, %s)) {\n"
3909 " return error::kInvalidArguments;\n"
3910 " }\n" %
3911 (func.name, func.GetLastOriginalArg().name))
3913 def WriteImmediateHandlerImplementation(self, func, file):
3914 """Overrriden from TypeHandler."""
3915 file.Write(" if (!%sHelper(n, %s)) {\n"
3916 " return error::kInvalidArguments;\n"
3917 " }\n" %
3918 (func.original_name, func.GetLastOriginalArg().name))
3920 def WriteGLES2Implementation(self, func, file):
3921 """Overrriden from TypeHandler."""
3922 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3923 for (GLsizei i = 0; i < n; ++i) {
3924 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3926 });""" % func.GetOriginalArgs()[1].name)
3927 args = {
3928 'log_code': log_code,
3929 'return_type': func.return_type,
3930 'name': func.original_name,
3931 'typed_args': func.MakeTypedOriginalArgString(""),
3932 'args': func.MakeOriginalArgString(""),
3933 'resource_types': func.GetInfo('resource_types'),
3934 'count_name': func.GetOriginalArgs()[0].name,
3936 file.Write(
3937 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3938 args)
3939 func.WriteDestinationInitalizationValidation(file)
3940 self.WriteClientGLCallLog(func, file)
3941 for arg in func.GetOriginalArgs():
3942 arg.WriteClientSideValidationCode(file, func)
3943 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3944 GetIdHandler(id_namespaces::k%(resource_types)s)->
3945 MakeIds(this, 0, %(args)s);
3946 %(name)sHelper(%(args)s);
3947 helper_->%(name)sImmediate(%(args)s);
3948 helper_->CommandBufferHelper::Flush();
3949 %(log_code)s
3950 CheckGLError();
3954 file.Write(code % args)
3956 def WriteGLES2ImplementationUnitTest(self, func, file):
3957 """Overrriden from TypeHandler."""
3958 code = """
3959 TEST_F(GLES2ImplementationTest, %(name)s) {
3960 GLuint ids[2] = { 0, };
3961 struct Cmds {
3962 cmds::%(name)sImmediate gen;
3963 GLuint data[2];
3965 Cmds expected;
3966 expected.gen.Init(arraysize(ids), &ids[0]);
3967 expected.data[0] = k%(types)sStartId;
3968 expected.data[1] = k%(types)sStartId + 1;
3969 gl_->%(name)s(arraysize(ids), &ids[0]);
3970 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3971 EXPECT_EQ(k%(types)sStartId, ids[0]);
3972 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3975 file.Write(code % {
3976 'name': func.name,
3977 'types': func.GetInfo('resource_types'),
3980 def WriteServiceUnitTest(self, func, file):
3981 """Overrriden from TypeHandler."""
3982 valid_test = """
3983 TEST_F(%(test_name)s, %(name)sValidArgs) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3985 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3986 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3987 SpecializedSetup<cmds::%(name)s, 0>(true);
3988 cmds::%(name)s cmd;
3989 cmd.Init(%(args)s);
3990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3992 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3995 self.WriteValidUnitTest(func, file, valid_test, {
3996 'resource_name': func.GetInfo('resource_type'),
3998 invalid_test = """
3999 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4000 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4001 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4002 SpecializedSetup<cmds::%(name)s, 0>(false);
4003 cmds::%(name)s cmd;
4004 cmd.Init(%(args)s);
4005 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4008 self.WriteValidUnitTest(func, file, invalid_test, {
4009 'resource_name': func.GetInfo('resource_type').lower(),
4012 def WriteImmediateServiceUnitTest(self, func, file):
4013 """Overrriden from TypeHandler."""
4014 valid_test = """
4015 TEST_F(%(test_name)s, %(name)sValidArgs) {
4016 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4017 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4018 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4019 GLuint temp = kNewClientId;
4020 SpecializedSetup<cmds::%(name)s, 0>(true);
4021 cmd->Init(1, &temp);
4022 EXPECT_EQ(error::kNoError,
4023 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4024 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4025 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4028 self.WriteValidUnitTest(func, file, valid_test, {
4029 'resource_name': func.GetInfo('resource_type'),
4031 invalid_test = """
4032 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4033 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4034 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4035 SpecializedSetup<cmds::%(name)s, 0>(false);
4036 cmd->Init(1, &client_%(resource_name)s_id_);
4037 EXPECT_EQ(error::kInvalidArguments,
4038 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4041 self.WriteValidUnitTest(func, file, invalid_test, {
4042 'resource_name': func.GetInfo('resource_type').lower(),
4045 def WriteImmediateCmdComputeSize(self, func, file):
4046 """Overrriden from TypeHandler."""
4047 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4048 file.Write(
4049 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4050 file.Write(" }\n")
4051 file.Write("\n")
4052 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4053 file.Write(" return static_cast<uint32>(\n")
4054 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4055 file.Write(" }\n")
4056 file.Write("\n")
4058 def WriteImmediateCmdSetHeader(self, func, file):
4059 """Overrriden from TypeHandler."""
4060 file.Write(" void SetHeader(GLsizei n) {\n")
4061 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4062 file.Write(" }\n")
4063 file.Write("\n")
4065 def WriteImmediateCmdInit(self, func, file):
4066 """Overrriden from TypeHandler."""
4067 last_arg = func.GetLastOriginalArg()
4068 file.Write(" void Init(%s, %s _%s) {\n" %
4069 (func.MakeTypedCmdArgString("_"),
4070 last_arg.type, last_arg.name))
4071 file.Write(" SetHeader(_n);\n")
4072 args = func.GetCmdArgs()
4073 for arg in args:
4074 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4075 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4076 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4077 file.Write(" }\n")
4078 file.Write("\n")
4080 def WriteImmediateCmdSet(self, func, file):
4081 """Overrriden from TypeHandler."""
4082 last_arg = func.GetLastOriginalArg()
4083 copy_args = func.MakeCmdArgString("_", False)
4084 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4085 (func.MakeTypedCmdArgString("_", True),
4086 last_arg.type, last_arg.name))
4087 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4088 (copy_args, last_arg.name))
4089 file.Write(" const uint32 size = ComputeSize(_n);\n")
4090 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4091 "cmd, size);\n")
4092 file.Write(" }\n")
4093 file.Write("\n")
4095 def WriteImmediateCmdHelper(self, func, file):
4096 """Overrriden from TypeHandler."""
4097 code = """ void %(name)s(%(typed_args)s) {
4098 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4099 gles2::cmds::%(name)s* c =
4100 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4101 if (c) {
4102 c->Init(%(args)s);
4107 file.Write(code % {
4108 "name": func.name,
4109 "typed_args": func.MakeTypedOriginalArgString(""),
4110 "args": func.MakeOriginalArgString(""),
4113 def WriteImmediateFormatTest(self, func, file):
4114 """Overrriden from TypeHandler."""
4115 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4116 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4117 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4118 (func.name, func.name))
4119 file.Write(" void* next_cmd = cmd.Set(\n")
4120 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4121 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4122 func.name)
4123 file.Write(" cmd.header.command);\n")
4124 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4125 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4126 file.Write(" cmd.header.size * 4u);\n")
4127 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4128 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4129 file.Write(" next_cmd, sizeof(cmd) +\n")
4130 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4131 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4132 file.Write("}\n")
4133 file.Write("\n")
4136 class CreateHandler(TypeHandler):
4137 """Handler for glCreate___ type functions."""
4139 def __init__(self):
4140 TypeHandler.__init__(self)
4142 def InitFunction(self, func):
4143 """Overrriden from TypeHandler."""
4144 func.AddCmdArg(Argument("client_id", 'uint32'))
4146 def WriteServiceUnitTest(self, func, file):
4147 """Overrriden from TypeHandler."""
4148 valid_test = """
4149 TEST_F(%(test_name)s, %(name)sValidArgs) {
4150 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4151 .WillOnce(Return(kNewServiceId));
4152 SpecializedSetup<cmds::%(name)s, 0>(true);
4153 cmds::%(name)s cmd;
4154 cmd.Init(%(args)s%(comma)skNewClientId);
4155 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4156 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4157 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4160 comma = ""
4161 if len(func.GetOriginalArgs()):
4162 comma =", "
4163 self.WriteValidUnitTest(func, file, valid_test, {
4164 'comma': comma,
4165 'resource_type': func.name[6:],
4167 invalid_test = """
4168 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4169 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4170 SpecializedSetup<cmds::%(name)s, 0>(false);
4171 cmds::%(name)s cmd;
4172 cmd.Init(%(args)s%(comma)skNewClientId);
4173 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4176 self.WriteInvalidUnitTest(func, file, invalid_test, {
4177 'comma': comma,
4180 def WriteHandlerImplementation (self, func, file):
4181 """Overrriden from TypeHandler."""
4182 file.Write(" uint32 client_id = c.client_id;\n")
4183 file.Write(" if (!%sHelper(%s)) {\n" %
4184 (func.name, func.MakeCmdArgString("")))
4185 file.Write(" return error::kInvalidArguments;\n")
4186 file.Write(" }\n")
4188 def WriteGLES2Implementation(self, func, file):
4189 """Overrriden from TypeHandler."""
4190 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4191 (func.return_type, func.original_name,
4192 func.MakeTypedOriginalArgString("")))
4193 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4194 func.WriteDestinationInitalizationValidation(file)
4195 self.WriteClientGLCallLog(func, file)
4196 for arg in func.GetOriginalArgs():
4197 arg.WriteClientSideValidationCode(file, func)
4198 file.Write(" GLuint client_id;\n")
4199 file.Write(
4200 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4201 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4202 file.Write(" helper_->%s(%s);\n" %
4203 (func.name, func.MakeCmdArgString("")))
4204 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4205 file.Write(" CheckGLError();\n")
4206 file.Write(" return client_id;\n")
4207 file.Write("}\n")
4208 file.Write("\n")
4211 class DeleteHandler(TypeHandler):
4212 """Handler for glDelete___ single resource type functions."""
4214 def __init__(self):
4215 TypeHandler.__init__(self)
4217 def WriteServiceImplementation(self, func, file):
4218 """Overrriden from TypeHandler."""
4219 pass
4221 def WriteGLES2Implementation(self, func, file):
4222 """Overrriden from TypeHandler."""
4223 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4224 (func.return_type, func.original_name,
4225 func.MakeTypedOriginalArgString("")))
4226 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4227 func.WriteDestinationInitalizationValidation(file)
4228 self.WriteClientGLCallLog(func, file)
4229 for arg in func.GetOriginalArgs():
4230 arg.WriteClientSideValidationCode(file, func)
4231 file.Write(
4232 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4233 file.Write(" %sHelper(%s);\n" %
4234 (func.original_name, func.GetOriginalArgs()[-1].name))
4235 file.Write(" CheckGLError();\n")
4236 file.Write("}\n")
4237 file.Write("\n")
4240 class DELnHandler(TypeHandler):
4241 """Handler for glDelete___ type functions."""
4243 def __init__(self):
4244 TypeHandler.__init__(self)
4246 def WriteGetDataSizeCode(self, func, file):
4247 """Overrriden from TypeHandler."""
4248 code = """ uint32 data_size;
4249 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4250 return error::kOutOfBounds;
4253 file.Write(code)
4255 def WriteGLES2ImplementationUnitTest(self, func, file):
4256 """Overrriden from TypeHandler."""
4257 code = """
4258 TEST_F(GLES2ImplementationTest, %(name)s) {
4259 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4260 struct Cmds {
4261 cmds::%(name)sImmediate del;
4262 GLuint data[2];
4264 Cmds expected;
4265 expected.del.Init(arraysize(ids), &ids[0]);
4266 expected.data[0] = k%(types)sStartId;
4267 expected.data[1] = k%(types)sStartId + 1;
4268 gl_->%(name)s(arraysize(ids), &ids[0]);
4269 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4272 file.Write(code % {
4273 'name': func.name,
4274 'types': func.GetInfo('resource_types'),
4277 def WriteServiceUnitTest(self, func, file):
4278 """Overrriden from TypeHandler."""
4279 valid_test = """
4280 TEST_F(%(test_name)s, %(name)sValidArgs) {
4281 EXPECT_CALL(
4282 *gl_,
4283 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4284 .Times(1);
4285 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4286 SpecializedSetup<cmds::%(name)s, 0>(true);
4287 cmds::%(name)s cmd;
4288 cmd.Init(%(args)s);
4289 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4290 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4291 EXPECT_TRUE(
4292 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4295 self.WriteValidUnitTest(func, file, valid_test, {
4296 'resource_name': func.GetInfo('resource_type').lower(),
4297 'upper_resource_name': func.GetInfo('resource_type'),
4299 invalid_test = """
4300 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4301 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4302 SpecializedSetup<cmds::%(name)s, 0>(false);
4303 cmds::%(name)s cmd;
4304 cmd.Init(%(args)s);
4305 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4308 self.WriteValidUnitTest(func, file, invalid_test)
4310 def WriteImmediateServiceUnitTest(self, func, file):
4311 """Overrriden from TypeHandler."""
4312 valid_test = """
4313 TEST_F(%(test_name)s, %(name)sValidArgs) {
4314 EXPECT_CALL(
4315 *gl_,
4316 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4317 .Times(1);
4318 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4319 SpecializedSetup<cmds::%(name)s, 0>(true);
4320 cmd.Init(1, &client_%(resource_name)s_id_);
4321 EXPECT_EQ(error::kNoError,
4322 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4323 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4324 EXPECT_TRUE(
4325 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4328 self.WriteValidUnitTest(func, file, valid_test, {
4329 'resource_name': func.GetInfo('resource_type').lower(),
4330 'upper_resource_name': func.GetInfo('resource_type'),
4332 invalid_test = """
4333 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4334 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4335 SpecializedSetup<cmds::%(name)s, 0>(false);
4336 GLuint temp = kInvalidClientId;
4337 cmd.Init(1, &temp);
4338 EXPECT_EQ(error::kNoError,
4339 ExecuteImmediateCmd(cmd, sizeof(temp)));
4342 self.WriteValidUnitTest(func, file, invalid_test)
4344 def WriteHandlerImplementation (self, func, file):
4345 """Overrriden from TypeHandler."""
4346 file.Write(" %sHelper(n, %s);\n" %
4347 (func.name, func.GetLastOriginalArg().name))
4349 def WriteImmediateHandlerImplementation (self, func, file):
4350 """Overrriden from TypeHandler."""
4351 file.Write(" %sHelper(n, %s);\n" %
4352 (func.original_name, func.GetLastOriginalArg().name))
4354 def WriteGLES2Implementation(self, func, file):
4355 """Overrriden from TypeHandler."""
4356 impl_decl = func.GetInfo('impl_decl')
4357 if impl_decl == None or impl_decl == True:
4358 args = {
4359 'return_type': func.return_type,
4360 'name': func.original_name,
4361 'typed_args': func.MakeTypedOriginalArgString(""),
4362 'args': func.MakeOriginalArgString(""),
4363 'resource_type': func.GetInfo('resource_type').lower(),
4364 'count_name': func.GetOriginalArgs()[0].name,
4366 file.Write(
4367 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4368 args)
4369 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4370 func.WriteDestinationInitalizationValidation(file)
4371 self.WriteClientGLCallLog(func, file)
4372 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4373 for (GLsizei i = 0; i < n; ++i) {
4374 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4377 """ % func.GetOriginalArgs()[1].name)
4378 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4379 for (GLsizei i = 0; i < n; ++i) {
4380 DCHECK(%s[i] != 0);
4383 """ % func.GetOriginalArgs()[1].name)
4384 for arg in func.GetOriginalArgs():
4385 arg.WriteClientSideValidationCode(file, func)
4386 code = """ %(name)sHelper(%(args)s);
4387 CheckGLError();
4391 file.Write(code % args)
4393 def WriteImmediateCmdComputeSize(self, func, file):
4394 """Overrriden from TypeHandler."""
4395 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4396 file.Write(
4397 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4398 file.Write(" }\n")
4399 file.Write("\n")
4400 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4401 file.Write(" return static_cast<uint32>(\n")
4402 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4403 file.Write(" }\n")
4404 file.Write("\n")
4406 def WriteImmediateCmdSetHeader(self, func, file):
4407 """Overrriden from TypeHandler."""
4408 file.Write(" void SetHeader(GLsizei n) {\n")
4409 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4410 file.Write(" }\n")
4411 file.Write("\n")
4413 def WriteImmediateCmdInit(self, func, file):
4414 """Overrriden from TypeHandler."""
4415 last_arg = func.GetLastOriginalArg()
4416 file.Write(" void Init(%s, %s _%s) {\n" %
4417 (func.MakeTypedCmdArgString("_"),
4418 last_arg.type, last_arg.name))
4419 file.Write(" SetHeader(_n);\n")
4420 args = func.GetCmdArgs()
4421 for arg in args:
4422 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4423 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4424 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4425 file.Write(" }\n")
4426 file.Write("\n")
4428 def WriteImmediateCmdSet(self, func, file):
4429 """Overrriden from TypeHandler."""
4430 last_arg = func.GetLastOriginalArg()
4431 copy_args = func.MakeCmdArgString("_", False)
4432 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4433 (func.MakeTypedCmdArgString("_", True),
4434 last_arg.type, last_arg.name))
4435 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4436 (copy_args, last_arg.name))
4437 file.Write(" const uint32 size = ComputeSize(_n);\n")
4438 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4439 "cmd, size);\n")
4440 file.Write(" }\n")
4441 file.Write("\n")
4443 def WriteImmediateCmdHelper(self, func, file):
4444 """Overrriden from TypeHandler."""
4445 code = """ void %(name)s(%(typed_args)s) {
4446 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4447 gles2::cmds::%(name)s* c =
4448 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4449 if (c) {
4450 c->Init(%(args)s);
4455 file.Write(code % {
4456 "name": func.name,
4457 "typed_args": func.MakeTypedOriginalArgString(""),
4458 "args": func.MakeOriginalArgString(""),
4461 def WriteImmediateFormatTest(self, func, file):
4462 """Overrriden from TypeHandler."""
4463 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4464 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4465 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4466 (func.name, func.name))
4467 file.Write(" void* next_cmd = cmd.Set(\n")
4468 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4469 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4470 func.name)
4471 file.Write(" cmd.header.command);\n")
4472 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4473 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4474 file.Write(" cmd.header.size * 4u);\n")
4475 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4476 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4477 file.Write(" next_cmd, sizeof(cmd) +\n")
4478 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4479 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4480 file.Write("}\n")
4481 file.Write("\n")
4484 class GETnHandler(TypeHandler):
4485 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4487 def __init__(self):
4488 TypeHandler.__init__(self)
4490 def AddImmediateFunction(self, generator, func):
4491 """Overrriden from TypeHandler."""
4492 pass
4494 def WriteServiceImplementation(self, func, file):
4495 """Overrriden from TypeHandler."""
4496 file.Write(
4497 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4498 file.Write(
4499 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4500 func.name)
4501 last_arg = func.GetLastOriginalArg()
4503 all_but_last_args = func.GetOriginalArgs()[:-1]
4504 for arg in all_but_last_args:
4505 arg.WriteGetCode(file)
4507 code = """ typedef cmds::%(func_name)s::Result Result;
4508 GLsizei num_values = 0;
4509 GetNumValuesReturnedForGLGet(pname, &num_values);
4510 Result* result = GetSharedMemoryAs<Result*>(
4511 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4512 %(last_arg_type)s params = result ? result->GetData() : NULL;
4514 file.Write(code % {
4515 'last_arg_type': last_arg.type,
4516 'func_name': func.name,
4518 func.WriteHandlerValidation(file)
4519 code = """ // Check that the client initialized the result.
4520 if (result->size != 0) {
4521 return error::kInvalidArguments;
4524 shadowed = func.GetInfo('shadowed')
4525 if not shadowed:
4526 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4527 file.Write(code)
4528 func.WriteHandlerImplementation(file)
4529 if shadowed:
4530 code = """ result->SetNumResults(num_values);
4531 return error::kNoError;
4534 else:
4535 code = """ GLenum error = glGetError();
4536 if (error == GL_NO_ERROR) {
4537 result->SetNumResults(num_values);
4538 } else {
4539 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4541 return error::kNoError;
4545 file.Write(code % {'func_name': func.name})
4547 def WriteGLES2Implementation(self, func, file):
4548 """Overrriden from TypeHandler."""
4549 impl_decl = func.GetInfo('impl_decl')
4550 if impl_decl == None or impl_decl == True:
4551 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4552 (func.return_type, func.original_name,
4553 func.MakeTypedOriginalArgString("")))
4554 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4555 func.WriteDestinationInitalizationValidation(file)
4556 self.WriteClientGLCallLog(func, file)
4557 for arg in func.GetOriginalArgs():
4558 arg.WriteClientSideValidationCode(file, func)
4559 all_but_last_args = func.GetOriginalArgs()[:-1]
4560 arg_string = (
4561 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4562 all_arg_string = (
4563 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4564 self.WriteTraceEvent(func, file)
4565 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4566 return;
4568 typedef cmds::%(func_name)s::Result Result;
4569 Result* result = GetResultAs<Result*>();
4570 if (!result) {
4571 return;
4573 result->SetNumResults(0);
4574 helper_->%(func_name)s(%(arg_string)s,
4575 GetResultShmId(), GetResultShmOffset());
4576 WaitForCmd();
4577 result->CopyResult(params);
4578 GPU_CLIENT_LOG_CODE_BLOCK({
4579 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4580 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4583 CheckGLError();
4586 file.Write(code % {
4587 'func_name': func.name,
4588 'arg_string': arg_string,
4589 'all_arg_string': all_arg_string,
4592 def WriteGLES2ImplementationUnitTest(self, func, file):
4593 """Writes the GLES2 Implemention unit test."""
4594 code = """
4595 TEST_F(GLES2ImplementationTest, %(name)s) {
4596 struct Cmds {
4597 cmds::%(name)s cmd;
4599 typedef cmds::%(name)s::Result Result;
4600 Result::Type result = 0;
4601 Cmds expected;
4602 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4603 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4604 EXPECT_CALL(*command_buffer(), OnFlush())
4605 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4606 .RetiresOnSaturation();
4607 gl_->%(name)s(%(args)s, &result);
4608 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4609 EXPECT_EQ(static_cast<Result::Type>(1), result);
4612 cmd_arg_strings = []
4613 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4614 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4615 cmd_arg_strings[0] = '123'
4616 gl_arg_strings = []
4617 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4618 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4619 gl_arg_strings[0] = '123'
4620 file.Write(code % {
4621 'name': func.name,
4622 'args': ", ".join(gl_arg_strings),
4623 'cmd_args': ", ".join(cmd_arg_strings),
4626 def WriteServiceUnitTest(self, func, file):
4627 """Overrriden from TypeHandler."""
4628 valid_test = """
4629 TEST_F(%(test_name)s, %(name)sValidArgs) {
4630 EXPECT_CALL(*gl_, GetError())
4631 .WillOnce(Return(GL_NO_ERROR))
4632 .WillOnce(Return(GL_NO_ERROR))
4633 .RetiresOnSaturation();
4634 SpecializedSetup<cmds::%(name)s, 0>(true);
4635 typedef cmds::%(name)s::Result Result;
4636 Result* result = static_cast<Result*>(shared_memory_address_);
4637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4638 result->size = 0;
4639 cmds::%(name)s cmd;
4640 cmd.Init(%(args)s);
4641 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4642 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4643 %(valid_pname)s),
4644 result->GetNumResults());
4645 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4648 gl_arg_strings = []
4649 valid_pname = ''
4650 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4651 arg_value = arg.GetValidGLArg(func, count, 0)
4652 gl_arg_strings.append(arg_value)
4653 if arg.name == 'pname':
4654 valid_pname = arg_value
4655 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4656 gl_arg_strings.append("_")
4657 else:
4658 gl_arg_strings.append("result->GetData()")
4660 self.WriteValidUnitTest(func, file, valid_test, {
4661 'local_gl_args': ", ".join(gl_arg_strings),
4662 'valid_pname': valid_pname,
4665 invalid_test = """
4666 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4667 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4668 SpecializedSetup<cmds::%(name)s, 0>(false);
4669 cmds::%(name)s::Result* result =
4670 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4671 result->size = 0;
4672 cmds::%(name)s cmd;
4673 cmd.Init(%(args)s);
4674 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4675 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4678 self.WriteInvalidUnitTest(func, file, invalid_test)
4681 class PUTHandler(TypeHandler):
4682 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4684 def __init__(self):
4685 TypeHandler.__init__(self)
4687 def WriteServiceUnitTest(self, func, file):
4688 """Writes the service unit test for a command."""
4689 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4690 if func.GetInfo("first_element_only"):
4691 gl_arg_strings = []
4692 for count, arg in enumerate(func.GetOriginalArgs()):
4693 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4694 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4695 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4696 ", ".join(gl_arg_strings))
4697 valid_test = """
4698 TEST_F(%(test_name)s, %(name)sValidArgs) {
4699 SpecializedSetup<cmds::%(name)s, 0>(true);
4700 cmds::%(name)s cmd;
4701 cmd.Init(%(args)s);
4702 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4703 %(expected_call)s
4704 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4705 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4708 extra = {
4709 'data_type': func.GetInfo('data_type'),
4710 'data_value': func.GetInfo('data_value') or '0',
4711 'expected_call': expected_call,
4713 self.WriteValidUnitTest(func, file, valid_test, extra)
4715 invalid_test = """
4716 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4717 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4718 SpecializedSetup<cmds::%(name)s, 0>(false);
4719 cmds::%(name)s cmd;
4720 cmd.Init(%(args)s);
4721 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4722 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4725 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4727 def WriteImmediateServiceUnitTest(self, func, file):
4728 """Writes the service unit test for a command."""
4729 valid_test = """
4730 TEST_F(%(test_name)s, %(name)sValidArgs) {
4731 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4732 SpecializedSetup<cmds::%(name)s, 0>(true);
4733 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4734 cmd.Init(%(gl_args)s, &temp[0]);
4735 EXPECT_CALL(
4736 *gl_,
4737 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4738 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4739 EXPECT_EQ(error::kNoError,
4740 ExecuteImmediateCmd(cmd, sizeof(temp)));
4741 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4744 gl_arg_strings = []
4745 gl_any_strings = []
4746 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4747 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4748 gl_any_strings.append("_")
4749 extra = {
4750 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4751 'data_type': func.GetInfo('data_type'),
4752 'data_count': func.GetInfo('count'),
4753 'data_value': func.GetInfo('data_value') or '0',
4754 'gl_args': ", ".join(gl_arg_strings),
4755 'gl_any_args': ", ".join(gl_any_strings),
4757 self.WriteValidUnitTest(func, file, valid_test, extra)
4759 invalid_test = """
4760 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4761 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4762 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4763 SpecializedSetup<cmds::%(name)s, 0>(false);
4764 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4765 cmd.Init(%(all_but_last_args)s, &temp[0]);
4766 EXPECT_EQ(error::%(parse_result)s,
4767 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4770 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4772 def WriteGetDataSizeCode(self, func, file):
4773 """Overrriden from TypeHandler."""
4774 code = """ uint32 data_size;
4775 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4776 return error::kOutOfBounds;
4779 file.Write(code % (func.info.data_type, func.info.count))
4780 if func.is_immediate:
4781 file.Write(" if (data_size > immediate_data_size) {\n")
4782 file.Write(" return error::kOutOfBounds;\n")
4783 file.Write(" }\n")
4785 def WriteGLES2Implementation(self, func, file):
4786 """Overrriden from TypeHandler."""
4787 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4788 (func.return_type, func.original_name,
4789 func.MakeTypedOriginalArgString("")))
4790 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4791 func.WriteDestinationInitalizationValidation(file)
4792 self.WriteClientGLCallLog(func, file)
4793 last_arg_name = func.GetLastOriginalArg().name
4794 values_str = ' << ", " << '.join(
4795 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4796 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4797 for arg in func.GetOriginalArgs():
4798 arg.WriteClientSideValidationCode(file, func)
4799 file.Write(" helper_->%sImmediate(%s);\n" %
4800 (func.name, func.MakeOriginalArgString("")))
4801 file.Write(" CheckGLError();\n")
4802 file.Write("}\n")
4803 file.Write("\n")
4805 def WriteGLES2ImplementationUnitTest(self, func, file):
4806 """Writes the GLES2 Implemention unit test."""
4807 code = """
4808 TEST_F(GLES2ImplementationTest, %(name)s) {
4809 %(type)s data[%(count)d] = {0};
4810 struct Cmds {
4811 cmds::%(name)sImmediate cmd;
4812 %(type)s data[%(count)d];
4815 for (int jj = 0; jj < %(count)d; ++jj) {
4816 data[jj] = static_cast<%(type)s>(jj);
4818 Cmds expected;
4819 expected.cmd.Init(%(cmd_args)s, &data[0]);
4820 gl_->%(name)s(%(args)s, &data[0]);
4821 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4824 cmd_arg_strings = []
4825 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4826 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4827 gl_arg_strings = []
4828 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4829 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4830 file.Write(code % {
4831 'name': func.name,
4832 'type': func.GetInfo('data_type'),
4833 'count': func.GetInfo('count'),
4834 'args': ", ".join(gl_arg_strings),
4835 'cmd_args': ", ".join(cmd_arg_strings),
4838 def WriteImmediateCmdComputeSize(self, func, file):
4839 """Overrriden from TypeHandler."""
4840 file.Write(" static uint32 ComputeDataSize() {\n")
4841 file.Write(" return static_cast<uint32>(\n")
4842 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4843 (func.info.data_type, func.info.count))
4844 file.Write(" }\n")
4845 file.Write("\n")
4846 file.Write(" static uint32 ComputeSize() {\n")
4847 file.Write(" return static_cast<uint32>(\n")
4848 file.Write(
4849 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4850 file.Write(" }\n")
4851 file.Write("\n")
4853 def WriteImmediateCmdSetHeader(self, func, file):
4854 """Overrriden from TypeHandler."""
4855 file.Write(" void SetHeader() {\n")
4856 file.Write(
4857 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4858 file.Write(" }\n")
4859 file.Write("\n")
4861 def WriteImmediateCmdInit(self, func, file):
4862 """Overrriden from TypeHandler."""
4863 last_arg = func.GetLastOriginalArg()
4864 file.Write(" void Init(%s, %s _%s) {\n" %
4865 (func.MakeTypedCmdArgString("_"),
4866 last_arg.type, last_arg.name))
4867 file.Write(" SetHeader();\n")
4868 args = func.GetCmdArgs()
4869 for arg in args:
4870 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4871 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4872 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4873 file.Write(" }\n")
4874 file.Write("\n")
4876 def WriteImmediateCmdSet(self, func, file):
4877 """Overrriden from TypeHandler."""
4878 last_arg = func.GetLastOriginalArg()
4879 copy_args = func.MakeCmdArgString("_", False)
4880 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4881 (func.MakeTypedCmdArgString("_", True),
4882 last_arg.type, last_arg.name))
4883 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4884 (copy_args, last_arg.name))
4885 file.Write(" const uint32 size = ComputeSize();\n")
4886 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4887 "cmd, size);\n")
4888 file.Write(" }\n")
4889 file.Write("\n")
4891 def WriteImmediateCmdHelper(self, func, file):
4892 """Overrriden from TypeHandler."""
4893 code = """ void %(name)s(%(typed_args)s) {
4894 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4895 gles2::cmds::%(name)s* c =
4896 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4897 if (c) {
4898 c->Init(%(args)s);
4903 file.Write(code % {
4904 "name": func.name,
4905 "typed_args": func.MakeTypedOriginalArgString(""),
4906 "args": func.MakeOriginalArgString(""),
4909 def WriteImmediateFormatTest(self, func, file):
4910 """Overrriden from TypeHandler."""
4911 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4912 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4913 file.Write(" static %s data[] = {\n" % func.info.data_type)
4914 for v in range(0, func.info.count):
4915 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4916 (func.info.data_type, v))
4917 file.Write(" };\n")
4918 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4919 (func.name, func.name))
4920 file.Write(" void* next_cmd = cmd.Set(\n")
4921 file.Write(" &cmd")
4922 args = func.GetCmdArgs()
4923 for value, arg in enumerate(args):
4924 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4925 file.Write(",\n data);\n")
4926 args = func.GetCmdArgs()
4927 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4928 % func.name)
4929 file.Write(" cmd.header.command);\n")
4930 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4931 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4932 file.Write(" cmd.header.size * 4u);\n")
4933 for value, arg in enumerate(args):
4934 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4935 (arg.type, value + 11, arg.name))
4936 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4937 file.Write(" next_cmd, sizeof(cmd) +\n")
4938 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4939 file.Write(" // TODO(gman): Check that data was inserted;\n")
4940 file.Write("}\n")
4941 file.Write("\n")
4944 class PUTnHandler(TypeHandler):
4945 """Handler for PUTn 'glUniform__v' type functions."""
4947 def __init__(self):
4948 TypeHandler.__init__(self)
4950 def WriteServiceUnitTest(self, func, file):
4951 """Overridden from TypeHandler."""
4952 TypeHandler.WriteServiceUnitTest(self, func, file)
4954 valid_test = """
4955 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4956 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4957 SpecializedSetup<cmds::%(name)s, 0>(true);
4958 cmds::%(name)s cmd;
4959 cmd.Init(%(args)s);
4960 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4961 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4964 gl_arg_strings = []
4965 arg_strings = []
4966 for count, arg in enumerate(func.GetOriginalArgs()):
4967 # hardcoded to match unit tests.
4968 if count == 0:
4969 # the location of the second element of the 2nd uniform.
4970 # defined in GLES2DecoderBase::SetupShaderForUniform
4971 gl_arg_strings.append("3")
4972 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
4973 elif count == 1:
4974 # the number of elements that gl will be called with.
4975 gl_arg_strings.append("3")
4976 # the number of elements requested in the command.
4977 arg_strings.append("5")
4978 else:
4979 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4980 arg_strings.append(arg.GetValidArg(func, count, 0))
4981 extra = {
4982 'gl_args': ", ".join(gl_arg_strings),
4983 'args': ", ".join(arg_strings),
4985 self.WriteValidUnitTest(func, file, valid_test, extra)
4987 def WriteImmediateServiceUnitTest(self, func, file):
4988 """Overridden from TypeHandler."""
4989 valid_test = """
4990 TEST_F(%(test_name)s, %(name)sValidArgs) {
4991 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4992 EXPECT_CALL(
4993 *gl_,
4994 %(gl_func_name)s(%(gl_args)s,
4995 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4996 SpecializedSetup<cmds::%(name)s, 0>(true);
4997 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4998 cmd.Init(%(args)s, &temp[0]);
4999 EXPECT_EQ(error::kNoError,
5000 ExecuteImmediateCmd(cmd, sizeof(temp)));
5001 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5004 gl_arg_strings = []
5005 gl_any_strings = []
5006 arg_strings = []
5007 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5008 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
5009 gl_any_strings.append("_")
5010 arg_strings.append(arg.GetValidArg(func, count, 0))
5011 extra = {
5012 'data_type': func.GetInfo('data_type'),
5013 'data_count': func.GetInfo('count'),
5014 'args': ", ".join(arg_strings),
5015 'gl_args': ", ".join(gl_arg_strings),
5016 'gl_any_args': ", ".join(gl_any_strings),
5018 self.WriteValidUnitTest(func, file, valid_test, extra)
5020 invalid_test = """
5021 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5022 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5023 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5024 SpecializedSetup<cmds::%(name)s, 0>(false);
5025 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5026 cmd.Init(%(all_but_last_args)s, &temp[0]);
5027 EXPECT_EQ(error::%(parse_result)s,
5028 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5031 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5033 def WriteGetDataSizeCode(self, func, file):
5034 """Overrriden from TypeHandler."""
5035 code = """ uint32 data_size;
5036 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5037 return error::kOutOfBounds;
5040 file.Write(code % (func.info.data_type, func.info.count))
5041 if func.is_immediate:
5042 file.Write(" if (data_size > immediate_data_size) {\n")
5043 file.Write(" return error::kOutOfBounds;\n")
5044 file.Write(" }\n")
5046 def WriteGLES2Implementation(self, func, file):
5047 """Overrriden from TypeHandler."""
5048 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5049 (func.return_type, func.original_name,
5050 func.MakeTypedOriginalArgString("")))
5051 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5052 func.WriteDestinationInitalizationValidation(file)
5053 self.WriteClientGLCallLog(func, file)
5054 last_arg_name = func.GetLastOriginalArg().name
5055 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5056 for (GLsizei i = 0; i < count; ++i) {
5057 """)
5058 values_str = ' << ", " << '.join(
5059 ["%s[%d + i * %d]" % (
5060 last_arg_name, ndx, func.info.count) for ndx in range(
5061 0, func.info.count)])
5062 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5063 file.Write(" }\n });\n")
5064 for arg in func.GetOriginalArgs():
5065 arg.WriteClientSideValidationCode(file, func)
5066 file.Write(" helper_->%sImmediate(%s);\n" %
5067 (func.name, func.MakeOriginalArgString("")))
5068 file.Write(" CheckGLError();\n")
5069 file.Write("}\n")
5070 file.Write("\n")
5072 def WriteGLES2ImplementationUnitTest(self, func, file):
5073 """Writes the GLES2 Implemention unit test."""
5074 code = """
5075 TEST_F(GLES2ImplementationTest, %(name)s) {
5076 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5077 struct Cmds {
5078 cmds::%(name)sImmediate cmd;
5079 %(type)s data[%(count_param)d][%(count)d];
5082 Cmds expected;
5083 for (int ii = 0; ii < %(count_param)d; ++ii) {
5084 for (int jj = 0; jj < %(count)d; ++jj) {
5085 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5088 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5089 gl_->%(name)s(%(args)s, &data[0][0]);
5090 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5093 cmd_arg_strings = []
5094 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5095 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5096 gl_arg_strings = []
5097 count_param = 0
5098 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5099 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5100 if arg.name == "count":
5101 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5102 file.Write(code % {
5103 'name': func.name,
5104 'type': func.GetInfo('data_type'),
5105 'count': func.GetInfo('count'),
5106 'args': ", ".join(gl_arg_strings),
5107 'cmd_args': ", ".join(cmd_arg_strings),
5108 'count_param': count_param,
5111 def WriteImmediateCmdComputeSize(self, func, file):
5112 """Overrriden from TypeHandler."""
5113 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5114 file.Write(" return static_cast<uint32>(\n")
5115 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5116 (func.info.data_type, func.info.count))
5117 file.Write(" }\n")
5118 file.Write("\n")
5119 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5120 file.Write(" return static_cast<uint32>(\n")
5121 file.Write(
5122 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5123 file.Write(" }\n")
5124 file.Write("\n")
5126 def WriteImmediateCmdSetHeader(self, func, file):
5127 """Overrriden from TypeHandler."""
5128 file.Write(" void SetHeader(GLsizei count) {\n")
5129 file.Write(
5130 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5131 file.Write(" }\n")
5132 file.Write("\n")
5134 def WriteImmediateCmdInit(self, func, file):
5135 """Overrriden from TypeHandler."""
5136 last_arg = func.GetLastOriginalArg()
5137 file.Write(" void Init(%s, %s _%s) {\n" %
5138 (func.MakeTypedCmdArgString("_"),
5139 last_arg.type, last_arg.name))
5140 file.Write(" SetHeader(_count);\n")
5141 args = func.GetCmdArgs()
5142 for arg in args:
5143 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5144 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5145 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5146 file.Write(" }\n")
5147 file.Write("\n")
5149 def WriteImmediateCmdSet(self, func, file):
5150 """Overrriden from TypeHandler."""
5151 last_arg = func.GetLastOriginalArg()
5152 copy_args = func.MakeCmdArgString("_", False)
5153 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5154 (func.MakeTypedCmdArgString("_", True),
5155 last_arg.type, last_arg.name))
5156 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5157 (copy_args, last_arg.name))
5158 file.Write(" const uint32 size = ComputeSize(_count);\n")
5159 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5160 "cmd, size);\n")
5161 file.Write(" }\n")
5162 file.Write("\n")
5164 def WriteImmediateCmdHelper(self, func, file):
5165 """Overrriden from TypeHandler."""
5166 code = """ void %(name)s(%(typed_args)s) {
5167 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5168 gles2::cmds::%(name)s* c =
5169 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5170 if (c) {
5171 c->Init(%(args)s);
5176 file.Write(code % {
5177 "name": func.name,
5178 "typed_args": func.MakeTypedOriginalArgString(""),
5179 "args": func.MakeOriginalArgString(""),
5182 def WriteImmediateFormatTest(self, func, file):
5183 """Overrriden from TypeHandler."""
5184 args = func.GetCmdArgs()
5185 count_param = 0
5186 for value, arg in enumerate(args):
5187 if arg.name == "count":
5188 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5189 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5190 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5191 file.Write(" static %s data[] = {\n" % func.info.data_type)
5192 for v in range(0, func.info.count * count_param):
5193 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5194 (func.info.data_type, v))
5195 file.Write(" };\n")
5196 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5197 (func.name, func.name))
5198 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5199 file.Write(" const size_t kExpectedCmdSize =\n")
5200 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5201 (func.info.data_type, func.info.count))
5202 file.Write(" void* next_cmd = cmd.Set(\n")
5203 file.Write(" &cmd")
5204 for value, arg in enumerate(args):
5205 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5206 file.Write(",\n data);\n")
5207 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5208 func.name)
5209 file.Write(" cmd.header.command);\n")
5210 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5211 for value, arg in enumerate(args):
5212 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5213 (arg.type, value + 1, arg.name))
5214 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5215 file.Write(" next_cmd, sizeof(cmd) +\n")
5216 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5217 file.Write(" // TODO(gman): Check that data was inserted;\n")
5218 file.Write("}\n")
5219 file.Write("\n")
5222 class PUTXnHandler(TypeHandler):
5223 """Handler for glUniform?f functions."""
5224 def __init__(self):
5225 TypeHandler.__init__(self)
5227 def WriteHandlerImplementation(self, func, file):
5228 """Overrriden from TypeHandler."""
5229 code = """ %(type)s temp[%(count)s] = { %(values)s};
5230 Do%(name)sv(%(location)s, 1, &temp[0]);
5232 values = ""
5233 args = func.GetOriginalArgs()
5234 count = int(func.GetInfo('count'))
5235 num_args = len(args)
5236 for ii in range(count):
5237 values += "%s, " % args[len(args) - count + ii].name
5239 file.Write(code % {
5240 'name': func.name,
5241 'count': func.GetInfo('count'),
5242 'type': func.GetInfo('data_type'),
5243 'location': args[0].name,
5244 'args': func.MakeOriginalArgString(""),
5245 'values': values,
5248 def WriteServiceUnitTest(self, func, file):
5249 """Overrriden from TypeHandler."""
5250 valid_test = """
5251 TEST_F(%(test_name)s, %(name)sValidArgs) {
5252 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5253 SpecializedSetup<cmds::%(name)s, 0>(true);
5254 cmds::%(name)s cmd;
5255 cmd.Init(%(args)s);
5256 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5257 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5260 args = func.GetOriginalArgs()
5261 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5262 self.WriteValidUnitTest(func, file, valid_test, {
5263 'name': func.name,
5264 'count': func.GetInfo('count'),
5265 'local_args': local_args,
5268 invalid_test = """
5269 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5270 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5271 SpecializedSetup<cmds::%(name)s, 0>(false);
5272 cmds::%(name)s cmd;
5273 cmd.Init(%(args)s);
5274 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5277 self.WriteInvalidUnitTest(func, file, invalid_test, {
5278 'name': func.GetInfo('name'),
5279 'count': func.GetInfo('count'),
5283 class GLcharHandler(CustomHandler):
5284 """Handler for functions that pass a single string ."""
5286 def __init__(self):
5287 CustomHandler.__init__(self)
5289 def WriteImmediateCmdComputeSize(self, func, file):
5290 """Overrriden from TypeHandler."""
5291 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5292 file.Write(" return static_cast<uint32>(\n")
5293 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5294 file.Write(" }\n")
5296 def WriteImmediateCmdSetHeader(self, func, file):
5297 """Overrriden from TypeHandler."""
5298 code = """
5299 void SetHeader(uint32 data_size) {
5300 header.SetCmdBySize<ValueType>(data_size);
5303 file.Write(code)
5305 def WriteImmediateCmdInit(self, func, file):
5306 """Overrriden from TypeHandler."""
5307 last_arg = func.GetLastOriginalArg()
5308 args = func.GetCmdArgs()
5309 set_code = []
5310 for arg in args:
5311 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5312 code = """
5313 void Init(%(typed_args)s, uint32 _data_size) {
5314 SetHeader(_data_size);
5315 %(set_code)s
5316 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5320 file.Write(code % {
5321 "typed_args": func.MakeTypedOriginalArgString("_"),
5322 "set_code": "\n".join(set_code),
5323 "last_arg": last_arg.name
5326 def WriteImmediateCmdSet(self, func, file):
5327 """Overrriden from TypeHandler."""
5328 last_arg = func.GetLastOriginalArg()
5329 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5330 func.MakeTypedOriginalArgString("_", True))
5331 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5332 func.MakeOriginalArgString("_"))
5333 file.Write(" return NextImmediateCmdAddress<ValueType>("
5334 "cmd, _data_size);\n")
5335 file.Write(" }\n")
5336 file.Write("\n")
5338 def WriteImmediateCmdHelper(self, func, file):
5339 """Overrriden from TypeHandler."""
5340 code = """ void %(name)s(%(typed_args)s) {
5341 const uint32 data_size = strlen(name);
5342 gles2::cmds::%(name)s* c =
5343 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5344 if (c) {
5345 c->Init(%(args)s, data_size);
5350 file.Write(code % {
5351 "name": func.name,
5352 "typed_args": func.MakeTypedOriginalArgString(""),
5353 "args": func.MakeOriginalArgString(""),
5357 def WriteImmediateFormatTest(self, func, file):
5358 """Overrriden from TypeHandler."""
5359 init_code = []
5360 check_code = []
5361 all_but_last_arg = func.GetCmdArgs()[:-1]
5362 for value, arg in enumerate(all_but_last_arg):
5363 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5364 for value, arg in enumerate(all_but_last_arg):
5365 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5366 (arg.type, value + 11, arg.name))
5367 code = """
5368 TEST_F(GLES2FormatTest, %(func_name)s) {
5369 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5370 static const char* const test_str = \"test string\";
5371 void* next_cmd = cmd.Set(
5372 &cmd,
5373 %(init_code)s
5374 test_str,
5375 strlen(test_str));
5376 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5377 cmd.header.command);
5378 EXPECT_EQ(sizeof(cmd) +
5379 RoundSizeToMultipleOfEntries(strlen(test_str)),
5380 cmd.header.size * 4u);
5381 EXPECT_EQ(static_cast<char*>(next_cmd),
5382 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5383 RoundSizeToMultipleOfEntries(strlen(test_str)));
5384 %(check_code)s
5385 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5386 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5387 CheckBytesWritten(
5388 next_cmd,
5389 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5390 sizeof(cmd) + strlen(test_str));
5394 file.Write(code % {
5395 'func_name': func.name,
5396 'init_code': "\n".join(init_code),
5397 'check_code': "\n".join(check_code),
5401 class GLcharNHandler(CustomHandler):
5402 """Handler for functions that pass a single string with an optional len."""
5404 def __init__(self):
5405 CustomHandler.__init__(self)
5407 def InitFunction(self, func):
5408 """Overrriden from TypeHandler."""
5409 func.cmd_args = []
5410 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5412 def AddImmediateFunction(self, generator, func):
5413 """Overrriden from TypeHandler."""
5414 pass
5416 def AddBucketFunction(self, generator, func):
5417 """Overrriden from TypeHandler."""
5418 pass
5420 def WriteServiceImplementation(self, func, file):
5421 """Overrriden from TypeHandler."""
5422 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5423 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5424 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5425 Bucket* bucket = GetBucket(bucket_id);
5426 if (!bucket || bucket->size() == 0) {
5427 return error::kInvalidArguments;
5429 std::string str;
5430 if (!bucket->GetAsString(&str)) {
5431 return error::kInvalidArguments;
5433 %(gl_func_name)s(0, str.c_str());
5434 return error::kNoError;
5437 """ % {
5438 'name': func.name,
5439 'gl_func_name': func.GetGLFunctionName(),
5440 'bucket_id': func.cmd_args[0].name,
5444 class IsHandler(TypeHandler):
5445 """Handler for glIs____ type and glGetError functions."""
5447 def __init__(self):
5448 TypeHandler.__init__(self)
5450 def InitFunction(self, func):
5451 """Overrriden from TypeHandler."""
5452 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5453 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5454 if func.GetInfo('result') == None:
5455 func.AddInfo('result', ['uint32'])
5457 def WriteServiceUnitTest(self, func, file):
5458 """Overrriden from TypeHandler."""
5459 valid_test = """
5460 TEST_F(%(test_name)s, %(name)sValidArgs) {
5461 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5462 SpecializedSetup<cmds::%(name)s, 0>(true);
5463 cmds::%(name)s cmd;
5464 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5465 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5466 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5469 comma = ""
5470 if len(func.GetOriginalArgs()):
5471 comma =", "
5472 self.WriteValidUnitTest(func, file, valid_test, {
5473 'comma': comma,
5476 invalid_test = """
5477 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5478 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5479 SpecializedSetup<cmds::%(name)s, 0>(false);
5480 cmds::%(name)s cmd;
5481 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5482 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5485 self.WriteInvalidUnitTest(func, file, invalid_test, {
5486 'comma': comma,
5489 invalid_test = """
5490 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5491 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5492 SpecializedSetup<cmds::%(name)s, 0>(false);
5493 cmds::%(name)s cmd;
5494 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5495 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5496 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5497 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5500 self.WriteValidUnitTest(func, file, invalid_test, {
5501 'comma': comma,
5504 def WriteServiceImplementation(self, func, file):
5505 """Overrriden from TypeHandler."""
5506 file.Write(
5507 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5508 file.Write(
5509 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5510 func.name)
5511 args = func.GetOriginalArgs()
5512 for arg in args:
5513 arg.WriteGetCode(file)
5515 code = """ typedef cmds::%(func_name)s::Result Result;
5516 Result* result_dst = GetSharedMemoryAs<Result*>(
5517 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5518 if (!result_dst) {
5519 return error::kOutOfBounds;
5522 file.Write(code % {'func_name': func.name})
5523 func.WriteHandlerValidation(file)
5524 file.Write(" *result_dst = %s(%s);\n" %
5525 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5526 file.Write(" return error::kNoError;\n")
5527 file.Write("}\n")
5528 file.Write("\n")
5530 def WriteGLES2Implementation(self, func, file):
5531 """Overrriden from TypeHandler."""
5532 impl_func = func.GetInfo('impl_func')
5533 if impl_func == None or impl_func == True:
5534 error_value = func.GetInfo("error_value") or "GL_FALSE"
5535 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5536 (func.return_type, func.original_name,
5537 func.MakeTypedOriginalArgString("")))
5538 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5539 self.WriteTraceEvent(func, file)
5540 func.WriteDestinationInitalizationValidation(file)
5541 self.WriteClientGLCallLog(func, file)
5542 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5543 file.Write(" Result* result = GetResultAs<Result*>();\n")
5544 file.Write(" if (!result) {\n")
5545 file.Write(" return %s;\n" % error_value)
5546 file.Write(" }\n")
5547 file.Write(" *result = 0;\n")
5548 arg_string = func.MakeOriginalArgString("")
5549 comma = ""
5550 if len(arg_string) > 0:
5551 comma = ", "
5552 file.Write(
5553 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5554 (func.name, arg_string, comma))
5555 file.Write(" WaitForCmd();\n")
5556 file.Write(" %s result_value = *result;\n" % func.return_type)
5557 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5558 file.Write(" CheckGLError();\n")
5559 file.Write(" return result_value;\n")
5560 file.Write("}\n")
5561 file.Write("\n")
5563 def WriteGLES2ImplementationUnitTest(self, func, file):
5564 """Overrriden from TypeHandler."""
5565 client_test = func.GetInfo('client_test')
5566 if client_test == None or client_test == True:
5567 code = """
5568 TEST_F(GLES2ImplementationTest, %(name)s) {
5569 struct Cmds {
5570 cmds::%(name)s cmd;
5573 typedef cmds::%(name)s::Result Result;
5574 Cmds expected;
5575 ExpectedMemoryInfo result1 =
5576 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5577 expected.cmd.Init(1, result1.id, result1.offset);
5579 EXPECT_CALL(*command_buffer(), OnFlush())
5580 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5581 .RetiresOnSaturation();
5583 GLboolean result = gl_->%(name)s(1);
5584 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5585 EXPECT_TRUE(result);
5588 file.Write(code % {
5589 'name': func.name,
5593 class STRnHandler(TypeHandler):
5594 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5595 GetTranslatedShaderSourceANGLE."""
5597 def __init__(self):
5598 TypeHandler.__init__(self)
5600 def InitFunction(self, func):
5601 """Overrriden from TypeHandler."""
5602 # remove all but the first cmd args.
5603 cmd_args = func.GetCmdArgs()
5604 func.ClearCmdArgs()
5605 func.AddCmdArg(cmd_args[0])
5606 # add on a bucket id.
5607 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5609 def WriteGLES2Implementation(self, func, file):
5610 """Overrriden from TypeHandler."""
5611 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5612 GPU_CLIENT_SINGLE_THREAD_CHECK();
5614 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5615 << "] gl%(func_name)s" << "("
5616 << %(arg0)s << ", "
5617 << %(arg1)s << ", "
5618 << static_cast<void*>(%(arg2)s) << ", "
5619 << static_cast<void*>(%(arg3)s) << ")");
5620 helper_->SetBucketSize(kResultBucketId, 0);
5621 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5622 std::string str;
5623 GLsizei max_size = 0;
5624 if (GetBucketAsString(kResultBucketId, &str)) {
5625 if (bufsize > 0) {
5626 max_size =
5627 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5628 memcpy(%(dest_name)s, str.c_str(), max_size);
5629 %(dest_name)s[max_size] = '\\0';
5630 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5633 if (%(length_name)s != NULL) {
5634 *%(length_name)s = max_size;
5636 CheckGLError();
5639 args = func.GetOriginalArgs()
5640 str_args = {
5641 'return_type': func.return_type,
5642 'func_name': func.original_name,
5643 'args': func.MakeTypedOriginalArgString(""),
5644 'id_name': args[0].name,
5645 'bufsize_name': args[1].name,
5646 'length_name': args[2].name,
5647 'dest_name': args[3].name,
5648 'arg0': args[0].name,
5649 'arg1': args[1].name,
5650 'arg2': args[2].name,
5651 'arg3': args[3].name,
5653 file.Write(code_1 % str_args)
5654 func.WriteDestinationInitalizationValidation(file)
5655 file.Write(code_2 % str_args)
5657 def WriteServiceUnitTest(self, func, file):
5658 """Overrriden from TypeHandler."""
5659 valid_test = """
5660 TEST_F(%(test_name)s, %(name)sValidArgs) {
5661 const char* kInfo = "hello";
5662 const uint32 kBucketId = 123;
5663 SpecializedSetup<cmds::%(name)s, 0>(true);
5664 %(expect_len_code)s
5665 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5666 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5667 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5668 cmds::%(name)s cmd;
5669 cmd.Init(%(args)s);
5670 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5671 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5672 ASSERT_TRUE(bucket != NULL);
5673 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5674 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5675 bucket->size()));
5676 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5679 args = func.GetOriginalArgs()
5680 id_name = args[0].GetValidGLArg(func, 0, 0)
5681 get_len_func = func.GetInfo('get_len_func')
5682 get_len_enum = func.GetInfo('get_len_enum')
5683 sub = {
5684 'id_name': id_name,
5685 'get_len_func': get_len_func,
5686 'get_len_enum': get_len_enum,
5687 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5688 args[0].GetValidGLArg(func, 0, 0),
5689 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5690 'expect_len_code': '',
5692 if get_len_func and get_len_func[0:2] == 'gl':
5693 sub['expect_len_code'] = (
5694 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5695 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5696 get_len_func[2:], id_name, get_len_enum)
5697 self.WriteValidUnitTest(func, file, valid_test, sub)
5699 invalid_test = """
5700 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5701 const uint32 kBucketId = 123;
5702 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5703 .Times(0);
5704 cmds::%(name)s cmd;
5705 cmd.Init(kInvalidClientId, kBucketId);
5706 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5707 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5710 self.WriteValidUnitTest(func, file, invalid_test)
5712 def WriteServiceImplementation(self, func, file):
5713 """Overrriden from TypeHandler."""
5714 pass
5717 class FunctionInfo(object):
5718 """Holds info about a function."""
5720 def __init__(self, info, type_handler):
5721 for key in info:
5722 setattr(self, key, info[key])
5723 self.type_handler = type_handler
5724 if not 'type' in info:
5725 self.type = ''
5728 class Argument(object):
5729 """A class that represents a function argument."""
5731 cmd_type_map_ = {
5732 'GLenum': 'uint32',
5733 'GLint': 'int32',
5734 'GLintptr': 'int32',
5735 'GLsizei': 'int32',
5736 'GLsizeiptr': 'int32',
5737 'GLfloat': 'float',
5738 'GLclampf': 'float',
5740 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5742 def __init__(self, name, type):
5743 self.name = name
5744 self.optional = type.endswith("Optional*")
5745 if self.optional:
5746 type = type[:-9] + "*"
5747 self.type = type
5749 if type in self.cmd_type_map_:
5750 self.cmd_type = self.cmd_type_map_[type]
5751 else:
5752 self.cmd_type = 'uint32'
5754 def IsPointer(self):
5755 """Returns true if argument is a pointer."""
5756 return False
5758 def AddCmdArgs(self, args):
5759 """Adds command arguments for this argument to the given list."""
5760 return args.append(self)
5762 def AddInitArgs(self, args):
5763 """Adds init arguments for this argument to the given list."""
5764 return args.append(self)
5766 def GetValidArg(self, func, offset, index):
5767 """Gets a valid value for this argument."""
5768 valid_arg = func.GetValidArg(offset)
5769 if valid_arg != None:
5770 return valid_arg
5771 return str(offset + 1)
5773 def GetValidClientSideArg(self, func, offset, index):
5774 """Gets a valid value for this argument."""
5775 return str(offset + 1)
5777 def GetValidClientSideCmdArg(self, func, offset, index):
5778 """Gets a valid value for this argument."""
5779 return str(offset + 1)
5781 def GetValidGLArg(self, func, offset, index):
5782 """Gets a valid GL value for this argument."""
5783 valid_arg = func.GetValidArg(offset)
5784 if valid_arg != None:
5785 return valid_arg
5786 return str(offset + 1)
5788 def GetNumInvalidValues(self, func):
5789 """returns the number of invalid values to be tested."""
5790 return 0
5792 def GetInvalidArg(self, offset, index):
5793 """returns an invalid value and expected parse result by index."""
5794 return ("---ERROR0---", "---ERROR2---", None)
5796 def GetLogArg(self):
5797 """Get argument appropriate for LOG macro."""
5798 if self.type == 'GLboolean':
5799 return 'GLES2Util::GetStringBool(%s)' % self.name
5800 if self.type == 'GLenum':
5801 return 'GLES2Util::GetStringEnum(%s)' % self.name
5802 return self.name
5804 def WriteGetCode(self, file):
5805 """Writes the code to get an argument from a command structure."""
5806 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5807 (self.type, self.name, self.type, self.name))
5809 def WriteValidationCode(self, file, func):
5810 """Writes the validation code for an argument."""
5811 pass
5813 def WriteClientSideValidationCode(self, file, func):
5814 """Writes the validation code for an argument."""
5815 pass
5817 def WriteDestinationInitalizationValidation(self, file, func):
5818 """Writes the client side destintion initialization validation."""
5819 pass
5821 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5822 """Writes the client side destintion initialization validation if needed."""
5823 parts = self.type.split(" ")
5824 if len(parts) > 1:
5825 return
5826 if parts[0] in self.need_validation_:
5827 file.Write(
5828 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5829 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5832 def WriteGetAddress(self, file):
5833 """Writes the code to get the address this argument refers to."""
5834 pass
5836 def GetImmediateVersion(self):
5837 """Gets the immediate version of this argument."""
5838 return self
5840 def GetBucketVersion(self):
5841 """Gets the bucket version of this argument."""
5842 return self
5845 class BoolArgument(Argument):
5846 """class for GLboolean"""
5848 def __init__(self, name, type):
5849 Argument.__init__(self, name, 'GLboolean')
5851 def GetValidArg(self, func, offset, index):
5852 """Gets a valid value for this argument."""
5853 return 'true'
5855 def GetValidClientSideArg(self, func, offset, index):
5856 """Gets a valid value for this argument."""
5857 return 'true'
5859 def GetValidClientSideCmdArg(self, func, offset, index):
5860 """Gets a valid value for this argument."""
5861 return 'true'
5863 def GetValidGLArg(self, func, offset, index):
5864 """Gets a valid GL value for this argument."""
5865 return 'true'
5868 class UniformLocationArgument(Argument):
5869 """class for uniform locations."""
5871 def __init__(self, name):
5872 Argument.__init__(self, name, "GLint")
5874 def WriteGetCode(self, file):
5875 """Writes the code to get an argument from a command structure."""
5876 code = """ %s %s = static_cast<%s>(c.%s);
5878 file.Write(code % (self.type, self.name, self.type, self.name))
5880 def GetValidArg(self, func, offset, index):
5881 """Gets a valid value for this argument."""
5882 return "%d" % (offset + 1)
5885 class DataSizeArgument(Argument):
5886 """class for data_size which Bucket commands do not need."""
5888 def __init__(self, name):
5889 Argument.__init__(self, name, "uint32")
5891 def GetBucketVersion(self):
5892 return None
5895 class SizeArgument(Argument):
5896 """class for GLsizei and GLsizeiptr."""
5898 def __init__(self, name, type):
5899 Argument.__init__(self, name, type)
5901 def GetNumInvalidValues(self, func):
5902 """overridden from Argument."""
5903 if func.is_immediate:
5904 return 0
5905 return 1
5907 def GetInvalidArg(self, offset, index):
5908 """overridden from Argument."""
5909 return ("-1", "kNoError", "GL_INVALID_VALUE")
5911 def WriteValidationCode(self, file, func):
5912 """overridden from Argument."""
5913 file.Write(" if (%s < 0) {\n" % self.name)
5914 file.Write(
5915 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5916 (func.original_name, self.name))
5917 file.Write(" return error::kNoError;\n")
5918 file.Write(" }\n")
5920 def WriteClientSideValidationCode(self, file, func):
5921 """overridden from Argument."""
5922 file.Write(" if (%s < 0) {\n" % self.name)
5923 file.Write(
5924 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5925 (func.original_name, self.name))
5926 file.Write(" return;\n")
5927 file.Write(" }\n")
5930 class SizeNotNegativeArgument(SizeArgument):
5931 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5933 def __init__(self, name, type, gl_type):
5934 SizeArgument.__init__(self, name, gl_type)
5936 def GetInvalidArg(self, offset, index):
5937 """overridden from SizeArgument."""
5938 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5940 def WriteValidationCode(self, file, func):
5941 """overridden from SizeArgument."""
5942 pass
5945 class EnumBaseArgument(Argument):
5946 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5948 def __init__(self, name, gl_type, type, gl_error):
5949 Argument.__init__(self, name, gl_type)
5951 self.local_type = type
5952 self.gl_error = gl_error
5953 name = type[len(gl_type):]
5954 self.type_name = name
5955 self.enum_info = _ENUM_LISTS[name]
5957 def WriteValidationCode(self, file, func):
5958 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5959 (ToUnderscore(self.type_name), self.name))
5960 if self.gl_error == "GL_INVALID_ENUM":
5961 file.Write(
5962 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5963 (func.original_name, self.name, self.name))
5964 else:
5965 file.Write(
5966 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5967 (self.gl_error, func.original_name, self.name, self.gl_error))
5968 file.Write(" return error::kNoError;\n")
5969 file.Write(" }\n")
5971 def GetValidArg(self, func, offset, index):
5972 valid_arg = func.GetValidArg(offset)
5973 if valid_arg != None:
5974 return valid_arg
5975 if 'valid' in self.enum_info:
5976 valid = self.enum_info['valid']
5977 num_valid = len(valid)
5978 if index >= num_valid:
5979 index = num_valid - 1
5980 return valid[index]
5981 return str(offset + 1)
5983 def GetValidClientSideArg(self, func, offset, index):
5984 """Gets a valid value for this argument."""
5985 return self.GetValidArg(func, offset, index)
5987 def GetValidClientSideCmdArg(self, func, offset, index):
5988 """Gets a valid value for this argument."""
5989 return self.GetValidArg(func, offset, index)
5991 def GetValidGLArg(self, func, offset, index):
5992 """Gets a valid value for this argument."""
5993 return self.GetValidArg(func, offset, index)
5995 def GetNumInvalidValues(self, func):
5996 """returns the number of invalid values to be tested."""
5997 if 'invalid' in self.enum_info:
5998 invalid = self.enum_info['invalid']
5999 return len(invalid)
6000 return 0
6002 def GetInvalidArg(self, offset, index):
6003 """returns an invalid value by index."""
6004 if 'invalid' in self.enum_info:
6005 invalid = self.enum_info['invalid']
6006 num_invalid = len(invalid)
6007 if index >= num_invalid:
6008 index = num_invalid - 1
6009 return (invalid[index], "kNoError", self.gl_error)
6010 return ("---ERROR1---", "kNoError", self.gl_error)
6013 class EnumArgument(EnumBaseArgument):
6014 """A class that represents a GLenum argument"""
6016 def __init__(self, name, type):
6017 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6019 def GetLogArg(self):
6020 """Overridden from Argument."""
6021 return ("GLES2Util::GetString%s(%s)" %
6022 (self.type_name, self.name))
6025 class IntArgument(EnumBaseArgument):
6026 """A class for a GLint argument that can only except specific values.
6028 For example glTexImage2D takes a GLint for its internalformat
6029 argument instead of a GLenum.
6032 def __init__(self, name, type):
6033 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6036 class ValidatedBoolArgument(EnumBaseArgument):
6037 """A class for a GLboolean argument that can only except specific values.
6039 For example glUniformMatrix takes a GLboolean for it's transpose but it
6040 must be false.
6043 def __init__(self, name, type):
6044 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6046 def GetLogArg(self):
6047 """Overridden from Argument."""
6048 return 'GLES2Util::GetStringBool(%s)' % self.name
6051 class ImmediatePointerArgument(Argument):
6052 """A class that represents an immediate argument to a function.
6054 An immediate argument is one where the data follows the command.
6057 def __init__(self, name, type):
6058 Argument.__init__(self, name, type)
6060 def AddCmdArgs(self, args):
6061 """Overridden from Argument."""
6062 pass
6064 def WriteGetCode(self, file):
6065 """Overridden from Argument."""
6066 file.Write(
6067 " %s %s = GetImmediateDataAs<%s>(\n" %
6068 (self.type, self.name, self.type))
6069 file.Write(" c, data_size, immediate_data_size);\n")
6071 def WriteValidationCode(self, file, func):
6072 """Overridden from Argument."""
6073 file.Write(" if (%s == NULL) {\n" % self.name)
6074 file.Write(" return error::kOutOfBounds;\n")
6075 file.Write(" }\n")
6077 def GetImmediateVersion(self):
6078 """Overridden from Argument."""
6079 return None
6081 def WriteDestinationInitalizationValidation(self, file, func):
6082 """Overridden from Argument."""
6083 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6085 def GetLogArg(self):
6086 """Overridden from Argument."""
6087 return "static_cast<const void*>(%s)" % self.name
6090 class BucketPointerArgument(Argument):
6091 """A class that represents an bucket argument to a function."""
6093 def __init__(self, name, type):
6094 Argument.__init__(self, name, type)
6096 def AddCmdArgs(self, args):
6097 """Overridden from Argument."""
6098 pass
6100 def WriteGetCode(self, file):
6101 """Overridden from Argument."""
6102 file.Write(
6103 " %s %s = bucket->GetData(0, data_size);\n" %
6104 (self.type, self.name))
6106 def WriteValidationCode(self, file, func):
6107 """Overridden from Argument."""
6108 pass
6110 def GetImmediateVersion(self):
6111 """Overridden from Argument."""
6112 return None
6114 def WriteDestinationInitalizationValidation(self, file, func):
6115 """Overridden from Argument."""
6116 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6118 def GetLogArg(self):
6119 """Overridden from Argument."""
6120 return "static_cast<const void*>(%s)" % self.name
6123 class PointerArgument(Argument):
6124 """A class that represents a pointer argument to a function."""
6126 def __init__(self, name, type):
6127 Argument.__init__(self, name, type)
6129 def IsPointer(self):
6130 """Returns true if argument is a pointer."""
6131 return True
6133 def GetValidArg(self, func, offset, index):
6134 """Overridden from Argument."""
6135 return "shared_memory_id_, shared_memory_offset_"
6137 def GetValidGLArg(self, func, offset, index):
6138 """Overridden from Argument."""
6139 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6141 def GetNumInvalidValues(self, func):
6142 """Overridden from Argument."""
6143 return 2
6145 def GetInvalidArg(self, offset, index):
6146 """Overridden from Argument."""
6147 if index == 0:
6148 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6149 else:
6150 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6151 "kOutOfBounds", None)
6153 def GetLogArg(self):
6154 """Overridden from Argument."""
6155 return "static_cast<const void*>(%s)" % self.name
6157 def AddCmdArgs(self, args):
6158 """Overridden from Argument."""
6159 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6160 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6162 def WriteGetCode(self, file):
6163 """Overridden from Argument."""
6164 file.Write(
6165 " %s %s = GetSharedMemoryAs<%s>(\n" %
6166 (self.type, self.name, self.type))
6167 file.Write(
6168 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6169 (self.name, self.name))
6171 def WriteGetAddress(self, file):
6172 """Overridden from Argument."""
6173 file.Write(
6174 " %s %s = GetSharedMemoryAs<%s>(\n" %
6175 (self.type, self.name, self.type))
6176 file.Write(
6177 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6178 (self.name, self.name, self.name))
6180 def WriteValidationCode(self, file, func):
6181 """Overridden from Argument."""
6182 file.Write(" if (%s == NULL) {\n" % self.name)
6183 file.Write(" return error::kOutOfBounds;\n")
6184 file.Write(" }\n")
6186 def GetImmediateVersion(self):
6187 """Overridden from Argument."""
6188 return ImmediatePointerArgument(self.name, self.type)
6190 def GetBucketVersion(self):
6191 """Overridden from Argument."""
6192 if self.type == "const char*":
6193 return InputStringBucketArgument(self.name, self.type)
6194 return BucketPointerArgument(self.name, self.type)
6196 def WriteDestinationInitalizationValidation(self, file, func):
6197 """Overridden from Argument."""
6198 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6201 class InputStringBucketArgument(Argument):
6202 """An string input argument where the string is passed in a bucket."""
6204 def __init__(self, name, type):
6205 Argument.__init__(self, name + "_bucket_id", "uint32")
6207 def WriteGetCode(self, file):
6208 """Overridden from Argument."""
6209 code = """
6210 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6211 if (!%(name)s_bucket) {
6212 return error::kInvalidArguments;
6214 std::string %(name)s_str;
6215 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6216 return error::kInvalidArguments;
6218 const char* %(name)s = %(name)s_str.c_str();
6220 file.Write(code % {
6221 'name': self.name,
6224 def GetValidArg(self, func, offset, index):
6225 return "kNameBucketId"
6227 def GetValidGLArg(self, func, offset, index):
6228 return "_"
6231 class NonImmediatePointerArgument(PointerArgument):
6232 """A pointer argument that stays a pointer even in an immediate cmd."""
6234 def __init__(self, name, type):
6235 PointerArgument.__init__(self, name, type)
6237 def IsPointer(self):
6238 """Returns true if argument is a pointer."""
6239 return False
6241 def GetImmediateVersion(self):
6242 """Overridden from Argument."""
6243 return self
6246 class ResourceIdArgument(Argument):
6247 """A class that represents a resource id argument to a function."""
6249 def __init__(self, name, type):
6250 match = re.match("(GLid\w+)", type)
6251 self.resource_type = match.group(1)[4:]
6252 type = type.replace(match.group(1), "GLuint")
6253 Argument.__init__(self, name, type)
6255 def WriteGetCode(self, file):
6256 """Overridden from Argument."""
6257 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6259 def GetValidArg(self, func, offset, index):
6260 return "client_%s_id_" % self.resource_type.lower()
6262 def GetValidGLArg(self, func, offset, index):
6263 return "kService%sId" % self.resource_type
6266 class ResourceIdBindArgument(Argument):
6267 """Represents a resource id argument to a bind function."""
6269 def __init__(self, name, type):
6270 match = re.match("(GLidBind\w+)", type)
6271 self.resource_type = match.group(1)[8:]
6272 type = type.replace(match.group(1), "GLuint")
6273 Argument.__init__(self, name, type)
6275 def WriteGetCode(self, file):
6276 """Overridden from Argument."""
6277 code = """ %(type)s %(name)s = c.%(name)s;
6279 file.Write(code % {'type': self.type, 'name': self.name})
6281 def GetValidArg(self, func, offset, index):
6282 return "client_%s_id_" % self.resource_type.lower()
6284 def GetValidGLArg(self, func, offset, index):
6285 return "kService%sId" % self.resource_type
6288 class ResourceIdZeroArgument(Argument):
6289 """Represents a resource id argument to a function that can be zero."""
6291 def __init__(self, name, type):
6292 match = re.match("(GLidZero\w+)", type)
6293 self.resource_type = match.group(1)[8:]
6294 type = type.replace(match.group(1), "GLuint")
6295 Argument.__init__(self, name, type)
6297 def WriteGetCode(self, file):
6298 """Overridden from Argument."""
6299 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6301 def GetValidArg(self, func, offset, index):
6302 return "client_%s_id_" % self.resource_type.lower()
6304 def GetValidGLArg(self, func, offset, index):
6305 return "kService%sId" % self.resource_type
6307 def GetNumInvalidValues(self, func):
6308 """returns the number of invalid values to be tested."""
6309 return 1
6311 def GetInvalidArg(self, offset, index):
6312 """returns an invalid value by index."""
6313 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6316 class Function(object):
6317 """A class that represents a function."""
6319 def __init__(self, original_name, name, info, return_type, original_args,
6320 args_for_cmds, cmd_args, init_args, num_pointer_args):
6321 self.name = name
6322 self.original_name = original_name
6323 self.info = info
6324 self.type_handler = info.type_handler
6325 self.return_type = return_type
6326 self.original_args = original_args
6327 self.num_pointer_args = num_pointer_args
6328 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6329 self.cmd_args = cmd_args
6330 self.init_args = init_args
6331 self.InitFunction()
6332 self.args_for_cmds = args_for_cmds
6333 self.is_immediate = False
6335 def IsType(self, type_name):
6336 """Returns true if function is a certain type."""
6337 return self.info.type == type_name
6339 def InitFunction(self):
6340 """Calls the init function for the type handler."""
6341 self.type_handler.InitFunction(self)
6343 def GetInfo(self, name):
6344 """Returns a value from the function info for this function."""
6345 if hasattr(self.info, name):
6346 return getattr(self.info, name)
6347 return None
6349 def GetValidArg(self, index):
6350 """Gets a valid arg from the function info if one exists."""
6351 valid_args = self.GetInfo('valid_args')
6352 if valid_args and str(index) in valid_args:
6353 return valid_args[str(index)]
6354 return None
6356 def AddInfo(self, name, value):
6357 """Adds an info."""
6358 setattr(self.info, name, value)
6360 def IsCoreGLFunction(self):
6361 return (not self.GetInfo('extension') and
6362 not self.GetInfo('pepper_interface'))
6364 def InPepperInterface(self, interface):
6365 ext = self.GetInfo('pepper_interface')
6366 if not interface.GetName():
6367 return self.IsCoreGLFunction()
6368 return ext == interface.GetName()
6370 def InAnyPepperExtension(self):
6371 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6373 def GetGLFunctionName(self):
6374 """Gets the function to call to execute GL for this command."""
6375 if self.GetInfo('decoder_func'):
6376 return self.GetInfo('decoder_func')
6377 return "gl%s" % self.original_name
6379 def GetGLTestFunctionName(self):
6380 gl_func_name = self.GetInfo('gl_test_func')
6381 if gl_func_name == None:
6382 gl_func_name = self.GetGLFunctionName()
6383 if gl_func_name.startswith("gl"):
6384 gl_func_name = gl_func_name[2:]
6385 else:
6386 gl_func_name = self.original_name
6387 return gl_func_name
6389 def AddCmdArg(self, arg):
6390 """Adds a cmd argument to this function."""
6391 self.cmd_args.append(arg)
6393 def GetCmdArgs(self):
6394 """Gets the command args for this function."""
6395 return self.cmd_args
6397 def ClearCmdArgs(self):
6398 """Clears the command args for this function."""
6399 self.cmd_args = []
6401 def GetInitArgs(self):
6402 """Gets the init args for this function."""
6403 return self.init_args
6405 def GetOriginalArgs(self):
6406 """Gets the original arguments to this function."""
6407 return self.original_args
6409 def GetLastOriginalArg(self):
6410 """Gets the last original argument to this function."""
6411 return self.original_args[len(self.original_args) - 1]
6413 def __MaybePrependComma(self, arg_string, add_comma):
6414 """Adds a comma if arg_string is not empty and add_comma is true."""
6415 comma = ""
6416 if add_comma and len(arg_string):
6417 comma = ", "
6418 return "%s%s" % (comma, arg_string)
6420 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6421 """Gets a list of arguments as they are in GL."""
6422 args = self.GetOriginalArgs()
6423 arg_string = ", ".join(
6424 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6425 return self.__MaybePrependComma(arg_string, add_comma)
6427 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6428 """Gets the list of arguments as they are in GL."""
6429 args = self.GetOriginalArgs()
6430 arg_string = separator.join(
6431 ["%s%s" % (prefix, arg.name) for arg in args])
6432 return self.__MaybePrependComma(arg_string, add_comma)
6434 def MakeTypedPepperArgString(self, prefix):
6435 """Gets a list of arguments as they need to be for Pepper."""
6436 if self.GetInfo("pepper_args"):
6437 return self.GetInfo("pepper_args")
6438 else:
6439 return self.MakeTypedOriginalArgString(prefix, False)
6441 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6442 """Gets a typed list of arguments as they need to be for command buffers."""
6443 args = self.GetCmdArgs()
6444 arg_string = ", ".join(
6445 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6446 return self.__MaybePrependComma(arg_string, add_comma)
6448 def MakeCmdArgString(self, prefix, add_comma = False):
6449 """Gets the list of arguments as they need to be for command buffers."""
6450 args = self.GetCmdArgs()
6451 arg_string = ", ".join(
6452 ["%s%s" % (prefix, arg.name) for arg in args])
6453 return self.__MaybePrependComma(arg_string, add_comma)
6455 def MakeTypedInitString(self, prefix, add_comma = False):
6456 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6457 args = self.GetInitArgs()
6458 arg_string = ", ".join(
6459 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6460 return self.__MaybePrependComma(arg_string, add_comma)
6462 def MakeInitString(self, prefix, add_comma = False):
6463 """Gets the list of arguments as they need to be for cmd Init/Set."""
6464 args = self.GetInitArgs()
6465 arg_string = ", ".join(
6466 ["%s%s" % (prefix, arg.name) for arg in args])
6467 return self.__MaybePrependComma(arg_string, add_comma)
6469 def MakeLogArgString(self):
6470 """Makes a string of the arguments for the LOG macros"""
6471 args = self.GetOriginalArgs()
6472 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6474 def WriteCommandDescription(self, file):
6475 """Writes a description of the command."""
6476 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6478 def WriteHandlerValidation(self, file):
6479 """Writes validation code for the function."""
6480 for arg in self.GetOriginalArgs():
6481 arg.WriteValidationCode(file, self)
6482 self.WriteValidationCode(file)
6484 def WriteHandlerImplementation(self, file):
6485 """Writes the handler implementation for this command."""
6486 self.type_handler.WriteHandlerImplementation(self, file)
6488 def WriteValidationCode(self, file):
6489 """Writes the validation code for a command."""
6490 pass
6492 def WriteCmdArgFlag(self, file):
6493 """Writes the cmd kArgFlags constant."""
6494 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6496 def WriteCmdComputeSize(self, file):
6497 """Writes the ComputeSize function for the command."""
6498 file.Write(" static uint32 ComputeSize() {\n")
6499 file.Write(
6500 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6501 file.Write(" }\n")
6502 file.Write("\n")
6504 def WriteCmdSetHeader(self, file):
6505 """Writes the cmd's SetHeader function."""
6506 file.Write(" void SetHeader() {\n")
6507 file.Write(" header.SetCmd<ValueType>();\n")
6508 file.Write(" }\n")
6509 file.Write("\n")
6511 def WriteCmdInit(self, file):
6512 """Writes the cmd's Init function."""
6513 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6514 file.Write(" SetHeader();\n")
6515 args = self.GetCmdArgs()
6516 for arg in args:
6517 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6518 file.Write(" }\n")
6519 file.Write("\n")
6521 def WriteCmdSet(self, file):
6522 """Writes the cmd's Set function."""
6523 copy_args = self.MakeCmdArgString("_", False)
6524 file.Write(" void* Set(void* cmd%s) {\n" %
6525 self.MakeTypedCmdArgString("_", True))
6526 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6527 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6528 file.Write(" }\n")
6529 file.Write("\n")
6531 def WriteStruct(self, file):
6532 self.type_handler.WriteStruct(self, file)
6534 def WriteDocs(self, file):
6535 self.type_handler.WriteDocs(self, file)
6537 def WriteCmdHelper(self, file):
6538 """Writes the cmd's helper."""
6539 self.type_handler.WriteCmdHelper(self, file)
6541 def WriteServiceImplementation(self, file):
6542 """Writes the service implementation for a command."""
6543 self.type_handler.WriteServiceImplementation(self, file)
6545 def WriteServiceUnitTest(self, file):
6546 """Writes the service implementation for a command."""
6547 self.type_handler.WriteServiceUnitTest(self, file)
6549 def WriteGLES2CLibImplementation(self, file):
6550 """Writes the GLES2 C Lib Implemention."""
6551 self.type_handler.WriteGLES2CLibImplementation(self, file)
6553 def WriteGLES2InterfaceHeader(self, file):
6554 """Writes the GLES2 Interface declaration."""
6555 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6557 def WriteGLES2InterfaceStub(self, file):
6558 """Writes the GLES2 Interface Stub declaration."""
6559 self.type_handler.WriteGLES2InterfaceStub(self, file)
6561 def WriteGLES2InterfaceStubImpl(self, file):
6562 """Writes the GLES2 Interface Stub declaration."""
6563 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6565 def WriteGLES2ImplementationHeader(self, file):
6566 """Writes the GLES2 Implemention declaration."""
6567 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6569 def WriteGLES2Implementation(self, file):
6570 """Writes the GLES2 Implemention definition."""
6571 self.type_handler.WriteGLES2Implementation(self, file)
6573 def WriteGLES2TraceImplementationHeader(self, file):
6574 """Writes the GLES2 Trace Implemention declaration."""
6575 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6577 def WriteGLES2TraceImplementation(self, file):
6578 """Writes the GLES2 Trace Implemention definition."""
6579 self.type_handler.WriteGLES2TraceImplementation(self, file)
6581 def WriteGLES2Header(self, file):
6582 """Writes the GLES2 Implemention unit test."""
6583 self.type_handler.WriteGLES2Header(self, file)
6585 def WriteGLES2ImplementationUnitTest(self, file):
6586 """Writes the GLES2 Implemention unit test."""
6587 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6589 def WriteDestinationInitalizationValidation(self, file):
6590 """Writes the client side destintion initialization validation."""
6591 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6593 def WriteFormatTest(self, file):
6594 """Writes the cmd's format test."""
6595 self.type_handler.WriteFormatTest(self, file)
6598 class PepperInterface(object):
6599 """A class that represents a function."""
6601 def __init__(self, info):
6602 self.name = info["name"]
6603 self.dev = info["dev"]
6605 def GetName(self):
6606 return self.name
6608 def GetInterfaceName(self):
6609 upperint = ""
6610 dev = ""
6611 if self.name:
6612 upperint = "_" + self.name.upper()
6613 if self.dev:
6614 dev = "_DEV"
6615 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6617 def GetInterfaceString(self):
6618 dev = ""
6619 if self.dev:
6620 dev = "(Dev)"
6621 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6623 def GetStructName(self):
6624 dev = ""
6625 if self.dev:
6626 dev = "_Dev"
6627 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6630 class ImmediateFunction(Function):
6631 """A class that represnets an immediate function command."""
6633 def __init__(self, func):
6634 new_args = []
6635 for arg in func.GetOriginalArgs():
6636 new_arg = arg.GetImmediateVersion()
6637 if new_arg:
6638 new_args.append(new_arg)
6640 cmd_args = []
6641 new_args_for_cmds = []
6642 for arg in func.args_for_cmds:
6643 new_arg = arg.GetImmediateVersion()
6644 if new_arg:
6645 new_args_for_cmds.append(new_arg)
6646 new_arg.AddCmdArgs(cmd_args)
6648 new_init_args = []
6649 for arg in new_args_for_cmds:
6650 arg.AddInitArgs(new_init_args)
6652 Function.__init__(
6653 self,
6654 func.original_name,
6655 "%sImmediate" % func.name,
6656 func.info,
6657 func.return_type,
6658 new_args,
6659 new_args_for_cmds,
6660 cmd_args,
6661 new_init_args,
6663 self.is_immediate = True
6665 def WriteCommandDescription(self, file):
6666 """Overridden from Function"""
6667 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6668 self.original_name)
6670 def WriteServiceImplementation(self, file):
6671 """Overridden from Function"""
6672 self.type_handler.WriteImmediateServiceImplementation(self, file)
6674 def WriteHandlerImplementation(self, file):
6675 """Overridden from Function"""
6676 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6678 def WriteServiceUnitTest(self, file):
6679 """Writes the service implementation for a command."""
6680 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6682 def WriteValidationCode(self, file):
6683 """Overridden from Function"""
6684 self.type_handler.WriteImmediateValidationCode(self, file)
6686 def WriteCmdArgFlag(self, file):
6687 """Overridden from Function"""
6688 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6690 def WriteCmdComputeSize(self, file):
6691 """Overridden from Function"""
6692 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6694 def WriteCmdSetHeader(self, file):
6695 """Overridden from Function"""
6696 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6698 def WriteCmdInit(self, file):
6699 """Overridden from Function"""
6700 self.type_handler.WriteImmediateCmdInit(self, file)
6702 def WriteCmdSet(self, file):
6703 """Overridden from Function"""
6704 self.type_handler.WriteImmediateCmdSet(self, file)
6706 def WriteCmdHelper(self, file):
6707 """Overridden from Function"""
6708 self.type_handler.WriteImmediateCmdHelper(self, file)
6710 def WriteFormatTest(self, file):
6711 """Overridden from Function"""
6712 self.type_handler.WriteImmediateFormatTest(self, file)
6715 class BucketFunction(Function):
6716 """A class that represnets a bucket version of a function command."""
6718 def __init__(self, func):
6719 new_args = []
6720 for arg in func.GetOriginalArgs():
6721 new_arg = arg.GetBucketVersion()
6722 if new_arg:
6723 new_args.append(new_arg)
6725 cmd_args = []
6726 new_args_for_cmds = []
6727 for arg in func.args_for_cmds:
6728 new_arg = arg.GetBucketVersion()
6729 if new_arg:
6730 new_args_for_cmds.append(new_arg)
6731 new_arg.AddCmdArgs(cmd_args)
6733 new_init_args = []
6734 for arg in new_args_for_cmds:
6735 arg.AddInitArgs(new_init_args)
6737 Function.__init__(
6738 self,
6739 func.original_name,
6740 "%sBucket" % func.name,
6741 func.info,
6742 func.return_type,
6743 new_args,
6744 new_args_for_cmds,
6745 cmd_args,
6746 new_init_args,
6749 # def InitFunction(self):
6750 # """Overridden from Function"""
6751 # pass
6753 def WriteCommandDescription(self, file):
6754 """Overridden from Function"""
6755 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6756 self.original_name)
6758 def WriteServiceImplementation(self, file):
6759 """Overridden from Function"""
6760 self.type_handler.WriteBucketServiceImplementation(self, file)
6762 def WriteHandlerImplementation(self, file):
6763 """Overridden from Function"""
6764 self.type_handler.WriteBucketHandlerImplementation(self, file)
6766 def WriteServiceUnitTest(self, file):
6767 """Writes the service implementation for a command."""
6768 self.type_handler.WriteBucketServiceUnitTest(self, file)
6771 def CreateArg(arg_string):
6772 """Creates an Argument."""
6773 arg_parts = arg_string.split()
6774 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6775 return None
6776 # Is this a pointer argument?
6777 elif arg_string.find('*') >= 0:
6778 if arg_parts[0] == 'NonImmediate':
6779 return NonImmediatePointerArgument(
6780 arg_parts[-1],
6781 " ".join(arg_parts[1:-1]))
6782 else:
6783 return PointerArgument(
6784 arg_parts[-1],
6785 " ".join(arg_parts[0:-1]))
6786 # Is this a resource argument? Must come after pointer check.
6787 elif arg_parts[0].startswith('GLidBind'):
6788 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6789 elif arg_parts[0].startswith('GLidZero'):
6790 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6791 elif arg_parts[0].startswith('GLid'):
6792 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6793 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6794 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6795 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6796 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6797 elif arg_parts[0].startswith('GLboolean'):
6798 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6799 elif arg_parts[0].startswith('GLintUniformLocation'):
6800 return UniformLocationArgument(arg_parts[-1])
6801 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6802 not arg_parts[0].startswith('GLintptr')):
6803 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6804 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6805 arg_parts[0].startswith('GLintptrNotNegative')):
6806 return SizeNotNegativeArgument(arg_parts[-1],
6807 " ".join(arg_parts[0:-1]),
6808 arg_parts[0][0:-11])
6809 elif arg_parts[0].startswith('GLsize'):
6810 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6811 else:
6812 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6815 class GLGenerator(object):
6816 """A class to generate GL command buffers."""
6818 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6820 def __init__(self, verbose):
6821 self.original_functions = []
6822 self.functions = []
6823 self.verbose = verbose
6824 self.errors = 0
6825 self._function_info = {}
6826 self._empty_type_handler = TypeHandler()
6827 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6828 self.pepper_interfaces = []
6829 self.interface_info = {}
6831 self._type_handlers = {
6832 'Bind': BindHandler(),
6833 'Create': CreateHandler(),
6834 'Custom': CustomHandler(),
6835 'Data': DataHandler(),
6836 'Delete': DeleteHandler(),
6837 'DELn': DELnHandler(),
6838 'GENn': GENnHandler(),
6839 'GETn': GETnHandler(),
6840 'GLchar': GLcharHandler(),
6841 'GLcharN': GLcharNHandler(),
6842 'HandWritten': HandWrittenHandler(),
6843 'Is': IsHandler(),
6844 'Manual': ManualHandler(),
6845 'PUT': PUTHandler(),
6846 'PUTn': PUTnHandler(),
6847 'PUTXn': PUTXnHandler(),
6848 'StateSet': StateSetHandler(),
6849 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6850 'StateSetFrontBack': StateSetFrontBackHandler(),
6851 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6852 'StateSetNamedParameter': StateSetNamedParameter(),
6853 'STRn': STRnHandler(),
6854 'Todo': TodoHandler(),
6857 for func_name in _FUNCTION_INFO:
6858 info = _FUNCTION_INFO[func_name]
6859 type = ''
6860 if 'type' in info:
6861 type = info['type']
6862 self._function_info[func_name] = FunctionInfo(info,
6863 self.GetTypeHandler(type))
6864 for interface in _PEPPER_INTERFACES:
6865 interface = PepperInterface(interface)
6866 self.pepper_interfaces.append(interface)
6867 self.interface_info[interface.GetName()] = interface
6869 def AddFunction(self, func):
6870 """Adds a function."""
6871 self.functions.append(func)
6873 def GetTypeHandler(self, name):
6874 """Gets a type info for the given type."""
6875 if len(name):
6876 if name in self._type_handlers:
6877 return self._type_handlers[name]
6878 else:
6879 raise KeyError("no such type handler: %s" % name)
6880 return self._empty_type_handler
6882 def GetFunctionInfo(self, name):
6883 """Gets a type info for the given function name."""
6884 if name in self._function_info:
6885 return self._function_info[name]
6886 return self._empty_function_info
6888 def Log(self, msg):
6889 """Prints something if verbose is true."""
6890 if self.verbose:
6891 print msg
6893 def Error(self, msg):
6894 """Prints an error."""
6895 print "Error: %s" % msg
6896 self.errors += 1
6898 def WriteLicense(self, file):
6899 """Writes the license."""
6900 file.Write(_LICENSE)
6902 def WriteNamespaceOpen(self, file):
6903 """Writes the code for the namespace."""
6904 file.Write("namespace gpu {\n")
6905 file.Write("namespace gles2 {\n")
6906 file.Write("\n")
6908 def WriteNamespaceClose(self, file):
6909 """Writes the code to close the namespace."""
6910 file.Write("} // namespace gles2\n")
6911 file.Write("} // namespace gpu\n")
6912 file.Write("\n")
6914 def ParseArgs(self, arg_string):
6915 """Parses a function arg string."""
6916 args = []
6917 num_pointer_args = 0
6918 parts = arg_string.split(',')
6919 is_gl_enum = False
6920 for arg_string in parts:
6921 if arg_string.startswith('GLenum '):
6922 is_gl_enum = True
6923 arg = CreateArg(arg_string)
6924 if arg:
6925 args.append(arg)
6926 if arg.IsPointer():
6927 num_pointer_args += 1
6928 return (args, num_pointer_args, is_gl_enum)
6930 def ParseGLH(self, filename):
6931 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6932 f = open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6933 functions = f.read()
6934 f.close()
6935 for line in functions.splitlines():
6936 match = self._function_re.match(line)
6937 if match:
6938 func_name = match.group(2)[2:]
6939 func_info = self.GetFunctionInfo(func_name)
6940 if func_info.type != 'Noop':
6941 return_type = match.group(1).strip()
6942 arg_string = match.group(3)
6943 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6944 # comment in to find out which functions use bare enums.
6945 # if is_gl_enum:
6946 # self.Log("%s uses bare GLenum" % func_name)
6947 args_for_cmds = args
6948 if hasattr(func_info, 'cmd_args'):
6949 (args_for_cmds, num_pointer_args, is_gl_enum) = (
6950 self.ParseArgs(getattr(func_info, 'cmd_args')))
6951 cmd_args = []
6952 for arg in args_for_cmds:
6953 arg.AddCmdArgs(cmd_args)
6954 init_args = []
6955 for arg in args_for_cmds:
6956 arg.AddInitArgs(init_args)
6957 return_arg = CreateArg(return_type + " result")
6958 if return_arg:
6959 init_args.append(return_arg)
6960 f = Function(func_name, func_name, func_info, return_type, args,
6961 args_for_cmds, cmd_args, init_args, num_pointer_args)
6962 self.original_functions.append(f)
6963 gen_cmd = f.GetInfo('gen_cmd')
6964 if gen_cmd == True or gen_cmd == None:
6965 self.AddFunction(f)
6966 f.type_handler.AddImmediateFunction(self, f)
6967 f.type_handler.AddBucketFunction(self, f)
6969 self.Log("Auto Generated Functions : %d" %
6970 len([f for f in self.functions if f.can_auto_generate or
6971 (not f.IsType('') and not f.IsType('Custom') and
6972 not f.IsType('Todo'))]))
6974 funcs = [f for f in self.functions if not f.can_auto_generate and
6975 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
6976 self.Log("Non Auto Generated Functions: %d" % len(funcs))
6978 for f in funcs:
6979 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
6981 def WriteCommandIds(self, filename):
6982 """Writes the command buffer format"""
6983 file = CHeaderWriter(filename)
6984 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
6985 id = 256
6986 for func in self.functions:
6987 file.Write(" %-60s /* %d */ \\\n" %
6988 ("OP(%s)" % func.name, id))
6989 id += 1
6990 file.Write("\n")
6992 file.Write("enum CommandId {\n")
6993 file.Write(" kStartPoint = cmd::kLastCommonId, "
6994 "// All GLES2 commands start after this.\n")
6995 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
6996 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
6997 file.Write("#undef GLES2_CMD_OP\n")
6998 file.Write(" kNumCommands\n")
6999 file.Write("};\n")
7000 file.Write("\n")
7001 file.Close()
7003 def WriteFormat(self, filename):
7004 """Writes the command buffer format"""
7005 file = CHeaderWriter(filename)
7006 for func in self.functions:
7007 if True:
7008 #gen_cmd = func.GetInfo('gen_cmd')
7009 #if gen_cmd == True or gen_cmd == None:
7010 func.WriteStruct(file)
7011 file.Write("\n")
7012 file.Close()
7014 def WriteDocs(self, filename):
7015 """Writes the command buffer doc version of the commands"""
7016 file = CWriter(filename)
7017 for func in self.functions:
7018 if True:
7019 #gen_cmd = func.GetInfo('gen_cmd')
7020 #if gen_cmd == True or gen_cmd == None:
7021 func.WriteDocs(file)
7022 file.Write("\n")
7023 file.Close()
7025 def WriteFormatTest(self, filename):
7026 """Writes the command buffer format test."""
7027 file = CHeaderWriter(
7028 filename,
7029 "// This file contains unit tests for gles2 commmands\n"
7030 "// It is included by gles2_cmd_format_test.cc\n"
7031 "\n")
7033 for func in self.functions:
7034 if True:
7035 #gen_cmd = func.GetInfo('gen_cmd')
7036 #if gen_cmd == True or gen_cmd == None:
7037 func.WriteFormatTest(file)
7039 file.Close()
7041 def WriteCmdHelperHeader(self, filename):
7042 """Writes the gles2 command helper."""
7043 file = CHeaderWriter(filename)
7045 for func in self.functions:
7046 if True:
7047 #gen_cmd = func.GetInfo('gen_cmd')
7048 #if gen_cmd == True or gen_cmd == None:
7049 func.WriteCmdHelper(file)
7051 file.Close()
7053 def WriteServiceContextStateHeader(self, filename):
7054 """Writes the service context state header."""
7055 file = CHeaderWriter(
7056 filename,
7057 "// It is included by context_state.h\n")
7058 file.Write("struct EnableFlags {\n")
7059 file.Write(" EnableFlags();\n")
7060 for capability in _CAPABILITY_FLAGS:
7061 file.Write(" bool %s;\n" % capability['name'])
7062 file.Write("};\n\n")
7064 for state_name in sorted(_STATES.keys()):
7065 state = _STATES[state_name]
7066 for item in state['states']:
7067 file.Write("%s %s;\n" % (item['type'], item['name']))
7068 file.Write("\n")
7070 file.Close()
7072 def WriteClientContextStateHeader(self, filename):
7073 """Writes the client context state header."""
7074 file = CHeaderWriter(
7075 filename,
7076 "// It is included by client_context_state.h\n")
7077 file.Write("struct EnableFlags {\n")
7078 file.Write(" EnableFlags();\n")
7079 for capability in _CAPABILITY_FLAGS:
7080 file.Write(" bool %s;\n" % capability['name'])
7081 file.Write("};\n\n")
7083 file.Close()
7085 def WriteContextStateGetters(self, file, class_name):
7086 """Writes the state getters."""
7087 for gl_type in ["GLint", "GLfloat"]:
7088 file.Write("""
7089 bool %s::GetStateAs%s(
7090 GLenum pname, %s* params, GLsizei* num_written) const {
7091 switch (pname) {
7092 """ % (class_name, gl_type, gl_type))
7093 for state_name in sorted(_STATES.keys()):
7094 state = _STATES[state_name]
7095 if 'enum' in state:
7096 file.Write(" case %s:\n" % state['enum'])
7097 file.Write(" *num_written = %d;\n" % len(state['states']))
7098 file.Write(" if (params) {\n")
7099 for ndx,item in enumerate(state['states']):
7100 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7101 (ndx, gl_type, item['name']))
7102 file.Write(" }\n")
7103 file.Write(" return true;\n")
7104 else:
7105 for item in state['states']:
7106 file.Write(" case %s:\n" % item['enum'])
7107 file.Write(" *num_written = 1;\n")
7108 file.Write(" if (params) {\n")
7109 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7110 (gl_type, item['name']))
7111 file.Write(" }\n")
7112 file.Write(" return true;\n")
7113 for capability in _CAPABILITY_FLAGS:
7114 file.Write(" case GL_%s:\n" % capability['name'].upper())
7115 file.Write(" *num_written = 1;\n")
7116 file.Write(" if (params) {\n")
7117 file.Write(
7118 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7119 (gl_type, capability['name']))
7120 file.Write(" }\n")
7121 file.Write(" return true;\n")
7122 file.Write(""" default:
7123 return false;
7126 """)
7128 def WriteServiceContextStateImpl(self, filename):
7129 """Writes the context state service implementation."""
7130 file = CHeaderWriter(
7131 filename,
7132 "// It is included by context_state.cc\n")
7133 code = []
7134 for capability in _CAPABILITY_FLAGS:
7135 code.append("%s(%s)" %
7136 (capability['name'],
7137 ('false', 'true')['default' in capability]))
7138 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7139 ",\n ".join(code))
7140 file.Write("\n")
7142 file.Write("void ContextState::Initialize() {\n")
7143 for state_name in sorted(_STATES.keys()):
7144 state = _STATES[state_name]
7145 for item in state['states']:
7146 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7147 file.Write("}\n")
7149 file.Write("""
7150 void ContextState::InitCapabilities() const {
7151 """)
7152 for capability in _CAPABILITY_FLAGS:
7153 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7154 (capability['name'].upper(), capability['name']))
7155 file.Write("""}
7157 void ContextState::InitState() const {
7158 """)
7160 # We need to sort the keys so the expectations match
7161 for state_name in sorted(_STATES.keys()):
7162 state = _STATES[state_name]
7163 if state['type'] == 'FrontBack':
7164 num_states = len(state['states'])
7165 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7166 args = []
7167 for item in group:
7168 args.append('%s' % item['name'])
7169 file.Write(
7170 " gl%s(%s, %s);\n" %
7171 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7172 elif state['type'] == 'NamedParameter':
7173 for item in state['states']:
7174 if 'extension_flag' in item:
7175 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7176 item['extension_flag'])
7177 file.Write(" gl%s(%s, %s);\n" %
7178 (state['func'], item['enum'], item['name']))
7179 else:
7180 args = []
7181 for item in state['states']:
7182 args.append('%s' % item['name'])
7183 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7184 file.Write("}\n")
7186 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7187 switch (cap) {
7188 """)
7189 for capability in _CAPABILITY_FLAGS:
7190 file.Write(" case GL_%s:\n" % capability['name'].upper())
7191 file.Write(" return enable_flags.%s;\n" % capability['name'])
7192 file.Write(""" default:
7193 NOTREACHED();
7194 return false;
7197 """)
7199 self.WriteContextStateGetters(file, "ContextState")
7200 file.Close()
7202 def WriteClientContextStateImpl(self, filename):
7203 """Writes the context state client side implementation."""
7204 file = CHeaderWriter(
7205 filename,
7206 "// It is included by client_context_state.cc\n")
7207 code = []
7208 for capability in _CAPABILITY_FLAGS:
7209 code.append("%s(%s)" %
7210 (capability['name'],
7211 ('false', 'true')['default' in capability]))
7212 file.Write(
7213 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7214 ",\n ".join(code))
7215 file.Write("\n")
7217 file.Write("""
7218 bool ClientContextState::SetCapabilityState(
7219 GLenum cap, bool enabled, bool* changed) {
7220 *changed = false;
7221 switch (cap) {
7222 """)
7223 for capability in _CAPABILITY_FLAGS:
7224 file.Write(" case GL_%s:\n" % capability['name'].upper())
7225 file.Write(""" if (enable_flags.%(name)s != enabled) {
7226 *changed = true;
7227 enable_flags.%(name)s = enabled;
7229 return true;
7230 """ % capability)
7231 file.Write(""" default:
7232 return false;
7235 """)
7236 file.Write("""bool ClientContextState::GetEnabled(
7237 GLenum cap, bool* enabled) const {
7238 switch (cap) {
7239 """)
7240 for capability in _CAPABILITY_FLAGS:
7241 file.Write(" case GL_%s:\n" % capability['name'].upper())
7242 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7243 file.Write(" return true;\n")
7244 file.Write(""" default:
7245 return false;
7248 """)
7249 file.Close()
7251 def WriteServiceImplementation(self, filename):
7252 """Writes the service decorder implementation."""
7253 file = CHeaderWriter(
7254 filename,
7255 "// It is included by gles2_cmd_decoder.cc\n")
7257 for func in self.functions:
7258 if True:
7259 #gen_cmd = func.GetInfo('gen_cmd')
7260 #if gen_cmd == True or gen_cmd == None:
7261 func.WriteServiceImplementation(file)
7263 file.Write("""
7264 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7265 switch (cap) {
7266 """)
7267 for capability in _CAPABILITY_FLAGS:
7268 file.Write(" case GL_%s:\n" % capability['name'].upper())
7269 if 'state_flag' in capability:
7270 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7271 state_.enable_flags.%(name)s = enabled;
7272 %(state_flag)s = true;
7274 return false;
7275 """ % capability)
7276 else:
7277 file.Write(""" state_.enable_flags.%(name)s = enabled;
7278 return true;
7279 """ % capability)
7280 file.Write(""" default:
7281 NOTREACHED();
7282 return false;
7285 """)
7286 file.Close()
7288 def WriteServiceUnitTests(self, filename):
7289 """Writes the service decorder unit tests."""
7290 num_tests = len(self.functions)
7291 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7292 count = 0
7293 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7294 count += 1
7295 name = filename % count
7296 file = CHeaderWriter(
7297 name,
7298 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7299 file.SetFileNum(count)
7300 end = test_num + FUNCTIONS_PER_FILE
7301 if end > num_tests:
7302 end = num_tests
7303 for idx in range(test_num, end):
7304 func = self.functions[idx]
7305 if True:
7306 #gen_cmd = func.GetInfo('gen_cmd')
7307 #if gen_cmd == True or gen_cmd == None:
7308 if func.GetInfo('unit_test') == False:
7309 file.Write("// TODO(gman): %s\n" % func.name)
7310 else:
7311 func.WriteServiceUnitTest(file)
7313 file.Close()
7314 file = CHeaderWriter(
7315 filename % 0,
7316 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7317 file.Write(
7318 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7319 """)
7320 for capability in _CAPABILITY_FLAGS:
7321 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7322 (capability['name'].upper(),
7323 ('false', 'true')['default' in capability]))
7324 file.Write("""}
7326 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7327 """)
7329 # We need to sort the keys so the expectations match
7330 for state_name in sorted(_STATES.keys()):
7331 state = _STATES[state_name]
7332 if state['type'] == 'FrontBack':
7333 num_states = len(state['states'])
7334 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7335 args = []
7336 for item in group:
7337 if 'expected' in item:
7338 args.append(item['expected'])
7339 else:
7340 args.append(item['default'])
7341 file.Write(
7342 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7343 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7344 file.Write(" .Times(1)\n")
7345 file.Write(" .RetiresOnSaturation();\n")
7346 elif state['type'] == 'NamedParameter':
7347 for item in state['states']:
7348 if 'extension_flag' in item:
7349 continue
7350 file.Write(
7351 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7352 (state['func'], item['enum'], item['default']))
7353 file.Write(" .Times(1)\n")
7354 file.Write(" .RetiresOnSaturation();\n")
7355 else:
7356 args = []
7357 for item in state['states']:
7358 if 'expected' in item:
7359 args.append(item['expected'])
7360 else:
7361 args.append(item['default'])
7362 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7363 (state['func'], ", ".join(args)))
7364 file.Write(" .Times(1)\n")
7365 file.Write(" .RetiresOnSaturation();\n")
7366 file.Write("""}
7367 """)
7368 file.Close()
7370 def WriteGLES2Header(self, filename):
7371 """Writes the GLES2 header."""
7372 file = CHeaderWriter(
7373 filename,
7374 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7376 for func in self.original_functions:
7377 func.WriteGLES2Header(file)
7379 file.Write("\n")
7380 file.Close()
7382 def WriteGLES2CLibImplementation(self, filename):
7383 """Writes the GLES2 c lib implementation."""
7384 file = CHeaderWriter(
7385 filename,
7386 "// These functions emulate GLES2 over command buffers.\n")
7388 for func in self.original_functions:
7389 func.WriteGLES2CLibImplementation(file)
7391 file.Write("""
7392 namespace gles2 {
7394 extern const NameToFunc g_gles2_function_table[] = {
7395 """)
7396 for func in self.original_functions:
7397 file.Write(
7398 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7399 (func.name, func.name))
7400 file.Write(""" { NULL, NULL, },
7403 } // namespace gles2
7404 """)
7405 file.Close()
7407 def WriteGLES2InterfaceHeader(self, filename):
7408 """Writes the GLES2 interface header."""
7409 file = CHeaderWriter(
7410 filename,
7411 "// This file is included by gles2_interface.h to declare the\n"
7412 "// GL api functions.\n")
7413 for func in self.original_functions:
7414 func.WriteGLES2InterfaceHeader(file)
7415 file.Close()
7417 def WriteGLES2InterfaceStub(self, filename):
7418 """Writes the GLES2 interface stub header."""
7419 file = CHeaderWriter(
7420 filename,
7421 "// This file is included by gles2_interface_stub.h.\n")
7422 for func in self.original_functions:
7423 func.WriteGLES2InterfaceStub(file)
7424 file.Close()
7426 def WriteGLES2InterfaceStubImpl(self, filename):
7427 """Writes the GLES2 interface header."""
7428 file = CHeaderWriter(
7429 filename,
7430 "// This file is included by gles2_interface_stub.cc.\n")
7431 for func in self.original_functions:
7432 func.WriteGLES2InterfaceStubImpl(file)
7433 file.Close()
7435 def WriteGLES2ImplementationHeader(self, filename):
7436 """Writes the GLES2 Implementation header."""
7437 file = CHeaderWriter(
7438 filename,
7439 "// This file is included by gles2_implementation.h to declare the\n"
7440 "// GL api functions.\n")
7441 for func in self.original_functions:
7442 func.WriteGLES2ImplementationHeader(file)
7443 file.Close()
7445 def WriteGLES2Implementation(self, filename):
7446 """Writes the GLES2 Implementation."""
7447 file = CHeaderWriter(
7448 filename,
7449 "// This file is included by gles2_implementation.cc to define the\n"
7450 "// GL api functions.\n")
7451 for func in self.original_functions:
7452 func.WriteGLES2Implementation(file)
7453 file.Close()
7455 def WriteGLES2TraceImplementationHeader(self, filename):
7456 """Writes the GLES2 Trace Implementation header."""
7457 file = CHeaderWriter(
7458 filename,
7459 "// This file is included by gles2_trace_implementation.h\n")
7460 for func in self.original_functions:
7461 func.WriteGLES2TraceImplementationHeader(file)
7462 file.Close()
7464 def WriteGLES2TraceImplementation(self, filename):
7465 """Writes the GLES2 Trace Implementation."""
7466 file = CHeaderWriter(
7467 filename,
7468 "// This file is included by gles2_trace_implementation.cc\n")
7469 for func in self.original_functions:
7470 func.WriteGLES2TraceImplementation(file)
7471 file.Close()
7473 def WriteGLES2ImplementationUnitTests(self, filename):
7474 """Writes the GLES2 helper header."""
7475 file = CHeaderWriter(
7476 filename,
7477 "// This file is included by gles2_implementation.h to declare the\n"
7478 "// GL api functions.\n")
7479 for func in self.original_functions:
7480 func.WriteGLES2ImplementationUnitTest(file)
7481 file.Close()
7483 def WriteServiceUtilsHeader(self, filename):
7484 """Writes the gles2 auto generated utility header."""
7485 file = CHeaderWriter(filename)
7486 for enum in sorted(_ENUM_LISTS.keys()):
7487 file.Write("ValueValidator<%s> %s;\n" %
7488 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7489 file.Write("\n")
7490 file.Close()
7492 def WriteServiceUtilsImplementation(self, filename):
7493 """Writes the gles2 auto generated utility implementation."""
7494 file = CHeaderWriter(filename)
7495 enums = sorted(_ENUM_LISTS.keys())
7496 for enum in enums:
7497 if len(_ENUM_LISTS[enum]['valid']) > 0:
7498 file.Write("static const %s valid_%s_table[] = {\n" %
7499 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7500 for value in _ENUM_LISTS[enum]['valid']:
7501 file.Write(" %s,\n" % value)
7502 file.Write("};\n")
7503 file.Write("\n")
7504 file.Write("Validators::Validators()\n")
7505 pre = ': '
7506 post = ','
7507 for count, enum in enumerate(enums):
7508 if count + 1 == len(enums):
7509 post = ' {'
7510 if len(_ENUM_LISTS[enum]['valid']) > 0:
7511 code = """ %(pre)s%(name)s(
7512 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7514 else:
7515 code = """ %(pre)s%(name)s()%(post)s
7517 file.Write(code % {
7518 'name': ToUnderscore(enum),
7519 'pre': pre,
7520 'post': post,
7522 pre = ' '
7523 file.Write("}\n\n");
7524 file.Close()
7526 def WriteCommonUtilsHeader(self, filename):
7527 """Writes the gles2 common utility header."""
7528 file = CHeaderWriter(filename)
7529 enums = sorted(_ENUM_LISTS.keys())
7530 for enum in enums:
7531 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7532 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7533 file.Write("\n")
7534 file.Close()
7536 def WriteCommonUtilsImpl(self, filename):
7537 """Writes the gles2 common utility header."""
7538 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7539 dict = {}
7540 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7541 '../../third_party/khronos/GLES2/gl2ext.h',
7542 '../../gpu/GLES2/gl2chromium.h',
7543 '../../gpu/GLES2/gl2extchromium.h']:
7544 lines = open(fname).readlines()
7545 for line in lines:
7546 m = enum_re.match(line)
7547 if m:
7548 name = m.group(1)
7549 value = m.group(2)
7550 if len(value) <= 10 and not value in dict:
7551 dict[value] = name
7553 file = CHeaderWriter(filename)
7554 file.Write("static const GLES2Util::EnumToString "
7555 "enum_to_string_table[] = {\n")
7556 for value in dict:
7557 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7558 file.Write("""};
7560 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7561 enum_to_string_table;
7562 const size_t GLES2Util::enum_to_string_table_len_ =
7563 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7565 """)
7567 enums = sorted(_ENUM_LISTS.keys())
7568 for enum in enums:
7569 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7570 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7571 enum)
7572 if len(_ENUM_LISTS[enum]['valid']) > 0:
7573 file.Write(" static const EnumToString string_table[] = {\n")
7574 for value in _ENUM_LISTS[enum]['valid']:
7575 file.Write(' { %s, "%s" },\n' % (value, value))
7576 file.Write(""" };
7577 return GLES2Util::GetQualifiedEnumString(
7578 string_table, arraysize(string_table), value);
7581 """)
7582 else:
7583 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7584 NULL, 0, value);
7587 """)
7588 file.Close()
7590 def WritePepperGLES2Interface(self, filename, dev):
7591 """Writes the Pepper OpenGLES interface definition."""
7592 file = CHeaderWriter(
7593 filename,
7594 "// OpenGL ES interface.\n",
7597 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7598 if dev:
7599 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7600 else:
7601 file.Write("\n#ifndef __gl2_h_\n")
7602 for (k, v) in _GL_TYPES.iteritems():
7603 file.Write("typedef %s %s;\n" % (v, k))
7604 file.Write("#ifdef _WIN64\n")
7605 for (k, v) in _GL_TYPES_64.iteritems():
7606 file.Write("typedef %s %s;\n" % (v, k))
7607 file.Write("#else\n")
7608 for (k, v) in _GL_TYPES_32.iteritems():
7609 file.Write("typedef %s %s;\n" % (v, k))
7610 file.Write("#endif // _WIN64\n")
7611 file.Write("#endif // __gl2_h_\n\n")
7613 for interface in self.pepper_interfaces:
7614 if interface.dev != dev:
7615 continue
7616 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7617 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7618 file.Write("#define %s %s_1_0\n" %
7619 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7621 file.Write("\nstruct %s {\n" % interface.GetStructName())
7622 for func in self.original_functions:
7623 if not func.InPepperInterface(interface):
7624 continue
7626 original_arg = func.MakeTypedPepperArgString("")
7627 context_arg = "PP_Resource context"
7628 if len(original_arg):
7629 arg = context_arg + ", " + original_arg
7630 else:
7631 arg = context_arg
7632 file.Write(" %s (*%s)(%s);\n" % (func.return_type, func.name, arg))
7633 file.Write("};\n\n")
7636 file.Close()
7638 def WritePepperGLES2Implementation(self, filename):
7639 """Writes the Pepper OpenGLES interface implementation."""
7641 file = CWriter(filename)
7642 file.Write(_LICENSE)
7643 file.Write(_DO_NOT_EDIT_WARNING)
7645 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7646 file.Write("#include \"base/logging.h\"\n")
7647 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7648 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7649 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7651 file.Write("namespace ppapi {\n\n")
7652 file.Write("namespace {\n\n")
7654 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7655 " Enter3D;\n\n")
7657 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7658 " enter) {\n")
7659 file.Write(" DCHECK(enter);\n")
7660 file.Write(" DCHECK(enter->succeeded());\n")
7661 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7662 "gles2_impl();\n");
7663 file.Write("}\n\n");
7665 for func in self.original_functions:
7666 if not func.InAnyPepperExtension():
7667 continue
7669 original_arg = func.MakeTypedPepperArgString("")
7670 context_arg = "PP_Resource context_id"
7671 if len(original_arg):
7672 arg = context_arg + ", " + original_arg
7673 else:
7674 arg = context_arg
7675 file.Write("%s %s(%s) {\n" % (func.return_type, func.name, arg))
7676 file.Write(" Enter3D enter(context_id, true);\n")
7677 file.Write(" if (enter.succeeded()) {\n")
7679 return_str = "" if func.return_type == "void" else "return "
7680 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7681 (return_str, func.original_name,
7682 func.MakeOriginalArgString("")))
7683 file.Write(" }")
7684 if func.return_type == "void":
7685 file.Write("\n")
7686 else:
7687 file.Write(" else {\n")
7688 error_return = "0"
7689 if func.GetInfo("error_return"):
7690 error_return = func.GetInfo("error_return")
7691 elif func.return_type == "GLboolean":
7692 error_return = "GL_FALSE"
7693 elif "*" in func.return_type:
7694 error_return = "NULL"
7695 file.Write(" return %s;\n" % error_return)
7696 file.Write(" }\n")
7697 file.Write("}\n\n")
7699 file.Write("} // namespace\n")
7701 for interface in self.pepper_interfaces:
7702 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7703 (interface.GetStructName(), interface.GetName()))
7704 file.Write(" static const struct %s "
7705 "ppb_opengles2 = {\n" % interface.GetStructName())
7706 file.Write(" &")
7707 file.Write(",\n &".join(
7708 f.name for f in self.original_functions
7709 if f.InPepperInterface(interface)))
7710 file.Write("\n")
7712 file.Write(" };\n")
7713 file.Write(" return &ppb_opengles2;\n")
7714 file.Write("}\n")
7716 file.Write("} // namespace ppapi\n")
7717 file.Close()
7719 def WriteGLES2ToPPAPIBridge(self, filename):
7720 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7722 file = CWriter(filename)
7723 file.Write(_LICENSE)
7724 file.Write(_DO_NOT_EDIT_WARNING)
7726 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7727 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7728 file.Write("#endif\n")
7729 file.Write("#include <GLES2/gl2.h>\n")
7730 file.Write("#include <GLES2/gl2ext.h>\n")
7731 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7733 for func in self.original_functions:
7734 if not func.InAnyPepperExtension():
7735 continue
7737 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7739 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7740 (func.return_type, func.name,
7741 func.MakeTypedOriginalArgString("")))
7742 return_str = "" if func.return_type == "void" else "return "
7743 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7744 original_arg = func.MakeOriginalArgString("")
7745 context_arg = "glGetCurrentContextPPAPI()"
7746 if len(original_arg):
7747 arg = context_arg + ", " + original_arg
7748 else:
7749 arg = context_arg
7750 if interface.GetName():
7751 file.Write(" const struct %s* ext = %s;\n" %
7752 (interface.GetStructName(), interface_str))
7753 file.Write(" if (ext)\n")
7754 file.Write(" %sext->%s(%s);\n" %
7755 (return_str, func.name, arg))
7756 if return_str:
7757 file.Write(" %s0;\n" % return_str)
7758 else:
7759 file.Write(" %s%s->%s(%s);\n" %
7760 (return_str, interface_str, func.name, arg))
7761 file.Write("}\n\n")
7762 file.Close()
7764 def main(argv):
7765 """This is the main function."""
7766 parser = OptionParser()
7767 parser.add_option(
7768 "-g", "--generate-implementation-templates", action="store_true",
7769 help="generates files that are generally hand edited..")
7770 parser.add_option(
7771 "--alternate-mode", type="choice",
7772 choices=("ppapi", "chrome_ppapi", "chrome_ppapi_proxy", "nacl_ppapi"),
7773 help="generate files for other projects. \"ppapi\" will generate ppapi "
7774 "bindings. \"chrome_ppapi\" generate chrome implementation for ppapi. "
7775 "\"chrome_ppapi_proxy\" will generate the glue for the chrome IPC ppapi"
7776 "proxy. \"nacl_ppapi\" will generate NaCl implementation for ppapi")
7777 parser.add_option(
7778 "--output-dir",
7779 help="base directory for resulting files, under chrome/src. default is "
7780 "empty. Use this if you want the result stored under gen.")
7781 parser.add_option(
7782 "-v", "--verbose", action="store_true",
7783 help="prints more output.")
7785 (options, args) = parser.parse_args(args=argv)
7787 # Add in states and capabilites to GLState
7788 for state_name in sorted(_STATES.keys()):
7789 state = _STATES[state_name]
7790 if 'enum' in state:
7791 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7792 else:
7793 for item in state['states']:
7794 if 'extension_flag' in item:
7795 continue
7796 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7797 for capability in _CAPABILITY_FLAGS:
7798 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7800 # This script lives under gpu/command_buffer, cd to base directory.
7801 os.chdir(os.path.dirname(__file__) + "/../..")
7803 gen = GLGenerator(options.verbose)
7804 gen.ParseGLH("common/GLES2/gl2.h")
7806 # Support generating files under gen/
7807 if options.output_dir != None:
7808 os.chdir(options.output_dir)
7810 if options.alternate_mode == "ppapi":
7811 # To trigger this action, do "make ppapi_gles_bindings"
7812 os.chdir("ppapi");
7813 gen.WritePepperGLES2Interface("c/ppb_opengles2.h", False)
7814 gen.WritePepperGLES2Interface("c/dev/ppb_opengles2ext_dev.h", True)
7815 gen.WriteGLES2ToPPAPIBridge("lib/gl/gles2/gles2.c")
7817 elif options.alternate_mode == "chrome_ppapi":
7818 # To trigger this action, do "make ppapi_gles_implementation"
7819 gen.WritePepperGLES2Implementation(
7820 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7822 else:
7823 os.chdir("gpu/command_buffer")
7824 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7825 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7826 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7827 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7828 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7829 gen.WriteGLES2InterfaceStubImpl(
7830 "client/gles2_interface_stub_impl_autogen.h")
7831 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7832 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7833 gen.WriteGLES2ImplementationUnitTests(
7834 "client/gles2_implementation_unittest_autogen.h")
7835 gen.WriteGLES2TraceImplementationHeader(
7836 "client/gles2_trace_implementation_autogen.h")
7837 gen.WriteGLES2TraceImplementation(
7838 "client/gles2_trace_implementation_impl_autogen.h")
7839 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7840 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7841 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7842 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7843 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7844 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7845 gen.WriteClientContextStateImpl(
7846 "client/client_context_state_impl_autogen.h")
7847 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7848 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7849 gen.WriteServiceUtilsImplementation(
7850 "service/gles2_cmd_validation_implementation_autogen.h")
7851 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7852 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7853 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7855 if gen.errors > 0:
7856 print "%d errors" % gen.errors
7857 return 1
7858 return 0
7861 if __name__ == '__main__':
7862 sys.exit(main(sys.argv[1:]))