cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobf4c7e5b7367b70c10599bbc3d76cfb5096e19b6a
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',
57 'GLintptr': 'long int',
58 'GLsizeiptr': 'long int',
61 # Capabilites selected with glEnable
62 _CAPABILITY_FLAGS = [
63 {'name': 'blend'},
64 {'name': 'cull_face'},
65 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
66 {'name': 'dither', 'default': True},
67 {'name': 'polygon_offset_fill'},
68 {'name': 'sample_alpha_to_coverage'},
69 {'name': 'sample_coverage'},
70 {'name': 'scissor_test',
71 'state_flag': 'framebuffer_state_.clear_state_dirty'},
72 {'name': 'stencil_test',
73 'state_flag': 'framebuffer_state_.clear_state_dirty'},
76 _STATES = {
77 'ClearColor': {
78 'type': 'Normal',
79 'func': 'ClearColor',
80 'enum': 'GL_COLOR_CLEAR_VALUE',
81 'states': [
82 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
83 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
84 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
85 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
88 'ClearDepthf': {
89 'type': 'Normal',
90 'func': 'ClearDepth',
91 'enum': 'GL_DEPTH_CLEAR_VALUE',
92 'states': [
93 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
96 'ColorMask': {
97 'type': 'Normal',
98 'func': 'ColorMask',
99 'enum': 'GL_COLOR_WRITEMASK',
100 'states': [
101 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
102 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
103 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
104 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
106 'state_flag': 'framebuffer_state_.clear_state_dirty',
108 'ClearStencil': {
109 'type': 'Normal',
110 'func': 'ClearStencil',
111 'enum': 'GL_STENCIL_CLEAR_VALUE',
112 'states': [
113 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
116 'BlendColor': {
117 'type': 'Normal',
118 'func': 'BlendColor',
119 'enum': 'GL_BLEND_COLOR',
120 'states': [
121 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
122 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
123 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
124 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
127 'BlendEquation': {
128 'type': 'SrcDst',
129 'func': 'BlendEquationSeparate',
130 'states': [
132 'name': 'blend_equation_rgb',
133 'type': 'GLenum',
134 'enum': 'GL_BLEND_EQUATION_RGB',
135 'default': 'GL_FUNC_ADD',
138 'name': 'blend_equation_alpha',
139 'type': 'GLenum',
140 'enum': 'GL_BLEND_EQUATION_ALPHA',
141 'default': 'GL_FUNC_ADD',
145 'BlendFunc': {
146 'type': 'SrcDst',
147 'func': 'BlendFuncSeparate',
148 'states': [
150 'name': 'blend_source_rgb',
151 'type': 'GLenum',
152 'enum': 'GL_BLEND_SRC_RGB',
153 'default': 'GL_ONE',
156 'name': 'blend_dest_rgb',
157 'type': 'GLenum',
158 'enum': 'GL_BLEND_DST_RGB',
159 'default': 'GL_ZERO',
162 'name': 'blend_source_alpha',
163 'type': 'GLenum',
164 'enum': 'GL_BLEND_SRC_ALPHA',
165 'default': 'GL_ONE',
168 'name': 'blend_dest_alpha',
169 'type': 'GLenum',
170 'enum': 'GL_BLEND_DST_ALPHA',
171 'default': 'GL_ZERO',
175 'PolygonOffset': {
176 'type': 'Normal',
177 'func': 'PolygonOffset',
178 'states': [
180 'name': 'polygon_offset_factor',
181 'type': 'GLfloat',
182 'enum': 'GL_POLYGON_OFFSET_FACTOR',
183 'default': '0.0f',
186 'name': 'polygon_offset_units',
187 'type': 'GLfloat',
188 'enum': 'GL_POLYGON_OFFSET_UNITS',
189 'default': '0.0f',
193 'CullFace': {
194 'type': 'Normal',
195 'func': 'CullFace',
196 'enum': 'GL_CULL_FACE_MODE',
197 'states': [
199 'name': 'cull_mode',
200 'type': 'GLenum',
201 'default': 'GL_BACK',
205 'FrontFace': {
206 'type': 'Normal',
207 'func': 'FrontFace',
208 'enum': 'GL_FRONT_FACE',
209 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
211 'DepthFunc': {
212 'type': 'Normal',
213 'func': 'DepthFunc',
214 'enum': 'GL_DEPTH_FUNC',
215 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
217 'DepthRange': {
218 'type': 'Normal',
219 'func': 'DepthRange',
220 'enum': 'GL_DEPTH_RANGE',
221 'states': [
222 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
223 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
226 'SampleCoverage': {
227 'type': 'Normal',
228 'func': 'SampleCoverage',
229 'states': [
231 'name': 'sample_coverage_value',
232 'type': 'GLclampf',
233 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
234 'default': '1.0f',
237 'name': 'sample_coverage_invert',
238 'type': 'GLboolean',
239 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
240 'default': 'false',
244 'StencilMask': {
245 'type': 'FrontBack',
246 'func': 'StencilMaskSeparate',
247 'state_flag': 'framebuffer_state_.clear_state_dirty',
248 'states': [
250 'name': 'stencil_front_writemask',
251 'type': 'GLuint',
252 'enum': 'GL_STENCIL_WRITEMASK',
253 'default': '0xFFFFFFFFU',
256 'name': 'stencil_back_writemask',
257 'type': 'GLuint',
258 'enum': 'GL_STENCIL_BACK_WRITEMASK',
259 'default': '0xFFFFFFFFU',
263 'StencilOp': {
264 'type': 'FrontBack',
265 'func': 'StencilOpSeparate',
266 'states': [
268 'name': 'stencil_front_fail_op',
269 'type': 'GLenum',
270 'enum': 'GL_STENCIL_FAIL',
271 'default': 'GL_KEEP',
274 'name': 'stencil_front_z_fail_op',
275 'type': 'GLenum',
276 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
277 'default': 'GL_KEEP',
280 'name': 'stencil_front_z_pass_op',
281 'type': 'GLenum',
282 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
283 'default': 'GL_KEEP',
286 'name': 'stencil_back_fail_op',
287 'type': 'GLenum',
288 'enum': 'GL_STENCIL_BACK_FAIL',
289 'default': 'GL_KEEP',
292 'name': 'stencil_back_z_fail_op',
293 'type': 'GLenum',
294 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
295 'default': 'GL_KEEP',
298 'name': 'stencil_back_z_pass_op',
299 'type': 'GLenum',
300 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
301 'default': 'GL_KEEP',
305 'StencilFunc': {
306 'type': 'FrontBack',
307 'func': 'StencilFuncSeparate',
308 'states': [
310 'name': 'stencil_front_func',
311 'type': 'GLenum',
312 'enum': 'GL_STENCIL_FUNC',
313 'default': 'GL_ALWAYS',
316 'name': 'stencil_front_ref',
317 'type': 'GLint',
318 'enum': 'GL_STENCIL_REF',
319 'default': '0',
322 'name': 'stencil_front_mask',
323 'type': 'GLuint',
324 'enum': 'GL_STENCIL_VALUE_MASK',
325 'default': '0xFFFFFFFFU',
328 'name': 'stencil_back_func',
329 'type': 'GLenum',
330 'enum': 'GL_STENCIL_BACK_FUNC',
331 'default': 'GL_ALWAYS',
334 'name': 'stencil_back_ref',
335 'type': 'GLint',
336 'enum': 'GL_STENCIL_BACK_REF',
337 'default': '0',
340 'name': 'stencil_back_mask',
341 'type': 'GLuint',
342 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
343 'default': '0xFFFFFFFFU',
347 'Hint': {
348 'type': 'NamedParameter',
349 'func': 'Hint',
350 'states': [
352 'name': 'hint_generate_mipmap',
353 'type': 'GLenum',
354 'enum': 'GL_GENERATE_MIPMAP_HINT',
355 'default': 'GL_DONT_CARE'
358 'name': 'hint_fragment_shader_derivative',
359 'type': 'GLenum',
360 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
361 'default': 'GL_DONT_CARE',
362 'extension_flag': 'oes_standard_derivatives'
366 'PixelStore': {
367 'type': 'NamedParameter',
368 'func': 'PixelStorei',
369 'states': [
371 'name': 'pack_alignment',
372 'type': 'GLint',
373 'enum': 'GL_PACK_ALIGNMENT',
374 'default': '4'
377 'name': 'unpack_alignment',
378 'type': 'GLint',
379 'enum': 'GL_UNPACK_ALIGNMENT',
380 'default': '4'
384 # TODO: Consider implemenenting these states
385 # GL_ACTIVE_TEXTURE
386 'LineWidth': {
387 'type': 'Normal',
388 'func': 'LineWidth',
389 'enum': 'GL_LINE_WIDTH',
390 'states': [
392 'name': 'line_width',
393 'type': 'GLfloat',
394 'default': '1.0f',
395 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
398 'DepthMask': {
399 'type': 'Normal',
400 'func': 'DepthMask',
401 'enum': 'GL_DEPTH_WRITEMASK',
402 'states': [
403 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
405 'state_flag': 'framebuffer_state_.clear_state_dirty',
407 'Scissor': {
408 'type': 'Normal',
409 'func': 'Scissor',
410 'enum': 'GL_SCISSOR_BOX',
411 'states': [
412 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
414 'name': 'scissor_x',
415 'type': 'GLint',
416 'default': '0',
417 'expected': 'kViewportX',
420 'name': 'scissor_y',
421 'type': 'GLint',
422 'default': '0',
423 'expected': 'kViewportY',
426 'name': 'scissor_width',
427 'type': 'GLsizei',
428 'default': '1',
429 'expected': 'kViewportWidth',
432 'name': 'scissor_height',
433 'type': 'GLsizei',
434 'default': '1',
435 'expected': 'kViewportHeight',
439 'Viewport': {
440 'type': 'Normal',
441 'func': 'Viewport',
442 'enum': 'GL_VIEWPORT',
443 'states': [
444 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
446 'name': 'viewport_x',
447 'type': 'GLint',
448 'default': '0',
449 'expected': 'kViewportX',
452 'name': 'viewport_y',
453 'type': 'GLint',
454 'default': '0',
455 'expected': 'kViewportY',
458 'name': 'viewport_width',
459 'type': 'GLsizei',
460 'default': '1',
461 'expected': 'kViewportWidth',
464 'name': 'viewport_height',
465 'type': 'GLsizei',
466 'default': '1',
467 'expected': 'kViewportHeight',
473 # This is a list of enum names and their valid values. It is used to map
474 # GLenum arguments to a specific set of valid values.
475 _ENUM_LISTS = {
476 'BlitFilter': {
477 'type': 'GLenum',
478 'valid': [
479 'GL_NEAREST',
480 'GL_LINEAR',
482 'invalid': [
483 'GL_LINEAR_MIPMAP_LINEAR',
486 'FrameBufferTarget': {
487 'type': 'GLenum',
488 'valid': [
489 'GL_FRAMEBUFFER',
491 'invalid': [
492 'GL_DRAW_FRAMEBUFFER' ,
493 'GL_READ_FRAMEBUFFER' ,
496 'RenderBufferTarget': {
497 'type': 'GLenum',
498 'valid': [
499 'GL_RENDERBUFFER',
501 'invalid': [
502 'GL_FRAMEBUFFER',
505 'BufferTarget': {
506 'type': 'GLenum',
507 'valid': [
508 'GL_ARRAY_BUFFER',
509 'GL_ELEMENT_ARRAY_BUFFER',
511 'invalid': [
512 'GL_RENDERBUFFER',
515 'BufferUsage': {
516 'type': 'GLenum',
517 'valid': [
518 'GL_STREAM_DRAW',
519 'GL_STATIC_DRAW',
520 'GL_DYNAMIC_DRAW',
522 'invalid': [
523 'GL_STATIC_READ',
526 'CompressedTextureFormat': {
527 'type': 'GLenum',
528 'valid': [
531 'GLState': {
532 'type': 'GLenum',
533 'valid': [
534 # NOTE: State an Capability entries added later.
535 'GL_ACTIVE_TEXTURE',
536 'GL_ALIASED_LINE_WIDTH_RANGE',
537 'GL_ALIASED_POINT_SIZE_RANGE',
538 'GL_ALPHA_BITS',
539 'GL_ARRAY_BUFFER_BINDING',
540 'GL_BLUE_BITS',
541 'GL_COMPRESSED_TEXTURE_FORMATS',
542 'GL_CURRENT_PROGRAM',
543 'GL_DEPTH_BITS',
544 'GL_DEPTH_RANGE',
545 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
546 'GL_FRAMEBUFFER_BINDING',
547 'GL_GENERATE_MIPMAP_HINT',
548 'GL_GREEN_BITS',
549 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
550 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
551 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
552 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
553 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
554 'GL_MAX_RENDERBUFFER_SIZE',
555 'GL_MAX_TEXTURE_IMAGE_UNITS',
556 'GL_MAX_TEXTURE_SIZE',
557 'GL_MAX_VARYING_VECTORS',
558 'GL_MAX_VERTEX_ATTRIBS',
559 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_VERTEX_UNIFORM_VECTORS',
561 'GL_MAX_VIEWPORT_DIMS',
562 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
563 'GL_NUM_SHADER_BINARY_FORMATS',
564 'GL_PACK_ALIGNMENT',
565 'GL_RED_BITS',
566 'GL_RENDERBUFFER_BINDING',
567 'GL_SAMPLE_BUFFERS',
568 'GL_SAMPLE_COVERAGE_INVERT',
569 'GL_SAMPLE_COVERAGE_VALUE',
570 'GL_SAMPLES',
571 'GL_SCISSOR_BOX',
572 'GL_SHADER_BINARY_FORMATS',
573 'GL_SHADER_COMPILER',
574 'GL_SUBPIXEL_BITS',
575 'GL_STENCIL_BITS',
576 'GL_TEXTURE_BINDING_2D',
577 'GL_TEXTURE_BINDING_CUBE_MAP',
578 'GL_UNPACK_ALIGNMENT',
579 'GL_UNPACK_FLIP_Y_CHROMIUM',
580 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
581 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
582 # we can add this because we emulate it if the driver does not support it.
583 'GL_VERTEX_ARRAY_BINDING_OES',
584 'GL_VIEWPORT',
586 'invalid': [
587 'GL_FOG_HINT',
590 'GetTexParamTarget': {
591 'type': 'GLenum',
592 'valid': [
593 'GL_TEXTURE_2D',
594 'GL_TEXTURE_CUBE_MAP',
596 'invalid': [
597 'GL_PROXY_TEXTURE_CUBE_MAP',
600 'TextureTarget': {
601 'type': 'GLenum',
602 'valid': [
603 'GL_TEXTURE_2D',
604 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
605 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
606 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
607 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
608 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
609 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
611 'invalid': [
612 'GL_PROXY_TEXTURE_CUBE_MAP',
615 'TextureBindTarget': {
616 'type': 'GLenum',
617 'valid': [
618 'GL_TEXTURE_2D',
619 'GL_TEXTURE_CUBE_MAP',
621 'invalid': [
622 'GL_TEXTURE_1D',
623 'GL_TEXTURE_3D',
626 'ShaderType': {
627 'type': 'GLenum',
628 'valid': [
629 'GL_VERTEX_SHADER',
630 'GL_FRAGMENT_SHADER',
632 'invalid': [
633 'GL_GEOMETRY_SHADER',
636 'FaceType': {
637 'type': 'GLenum',
638 'valid': [
639 'GL_FRONT',
640 'GL_BACK',
641 'GL_FRONT_AND_BACK',
644 'FaceMode': {
645 'type': 'GLenum',
646 'valid': [
647 'GL_CW',
648 'GL_CCW',
651 'CmpFunction': {
652 'type': 'GLenum',
653 'valid': [
654 'GL_NEVER',
655 'GL_LESS',
656 'GL_EQUAL',
657 'GL_LEQUAL',
658 'GL_GREATER',
659 'GL_NOTEQUAL',
660 'GL_GEQUAL',
661 'GL_ALWAYS',
664 'Equation': {
665 'type': 'GLenum',
666 'valid': [
667 'GL_FUNC_ADD',
668 'GL_FUNC_SUBTRACT',
669 'GL_FUNC_REVERSE_SUBTRACT',
671 'invalid': [
672 'GL_MIN',
673 'GL_MAX',
676 'SrcBlendFactor': {
677 'type': 'GLenum',
678 'valid': [
679 'GL_ZERO',
680 'GL_ONE',
681 'GL_SRC_COLOR',
682 'GL_ONE_MINUS_SRC_COLOR',
683 'GL_DST_COLOR',
684 'GL_ONE_MINUS_DST_COLOR',
685 'GL_SRC_ALPHA',
686 'GL_ONE_MINUS_SRC_ALPHA',
687 'GL_DST_ALPHA',
688 'GL_ONE_MINUS_DST_ALPHA',
689 'GL_CONSTANT_COLOR',
690 'GL_ONE_MINUS_CONSTANT_COLOR',
691 'GL_CONSTANT_ALPHA',
692 'GL_ONE_MINUS_CONSTANT_ALPHA',
693 'GL_SRC_ALPHA_SATURATE',
696 'DstBlendFactor': {
697 'type': 'GLenum',
698 'valid': [
699 'GL_ZERO',
700 'GL_ONE',
701 'GL_SRC_COLOR',
702 'GL_ONE_MINUS_SRC_COLOR',
703 'GL_DST_COLOR',
704 'GL_ONE_MINUS_DST_COLOR',
705 'GL_SRC_ALPHA',
706 'GL_ONE_MINUS_SRC_ALPHA',
707 'GL_DST_ALPHA',
708 'GL_ONE_MINUS_DST_ALPHA',
709 'GL_CONSTANT_COLOR',
710 'GL_ONE_MINUS_CONSTANT_COLOR',
711 'GL_CONSTANT_ALPHA',
712 'GL_ONE_MINUS_CONSTANT_ALPHA',
715 'Capability': {
716 'type': 'GLenum',
717 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
718 'invalid': [
719 'GL_CLIP_PLANE0',
720 'GL_POINT_SPRITE',
723 'DrawMode': {
724 'type': 'GLenum',
725 'valid': [
726 'GL_POINTS',
727 'GL_LINE_STRIP',
728 'GL_LINE_LOOP',
729 'GL_LINES',
730 'GL_TRIANGLE_STRIP',
731 'GL_TRIANGLE_FAN',
732 'GL_TRIANGLES',
734 'invalid': [
735 'GL_QUADS',
736 'GL_POLYGON',
739 'IndexType': {
740 'type': 'GLenum',
741 'valid': [
742 'GL_UNSIGNED_BYTE',
743 'GL_UNSIGNED_SHORT',
745 'invalid': [
746 'GL_UNSIGNED_INT',
747 'GL_INT',
750 'GetMaxIndexType': {
751 'type': 'GLenum',
752 'valid': [
753 'GL_UNSIGNED_BYTE',
754 'GL_UNSIGNED_SHORT',
755 'GL_UNSIGNED_INT',
757 'invalid': [
758 'GL_INT',
761 'Attachment': {
762 'type': 'GLenum',
763 'valid': [
764 'GL_COLOR_ATTACHMENT0',
765 'GL_DEPTH_ATTACHMENT',
766 'GL_STENCIL_ATTACHMENT',
769 'BackbufferAttachment': {
770 'type': 'GLenum',
771 'valid': [
772 'GL_COLOR_EXT',
773 'GL_DEPTH_EXT',
774 'GL_STENCIL_EXT',
777 'BufferParameter': {
778 'type': 'GLenum',
779 'valid': [
780 'GL_BUFFER_SIZE',
781 'GL_BUFFER_USAGE',
783 'invalid': [
784 'GL_PIXEL_PACK_BUFFER',
787 'FrameBufferParameter': {
788 'type': 'GLenum',
789 'valid': [
790 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
791 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
792 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
793 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
796 'ProgramParameter': {
797 'type': 'GLenum',
798 'valid': [
799 'GL_DELETE_STATUS',
800 'GL_LINK_STATUS',
801 'GL_VALIDATE_STATUS',
802 'GL_INFO_LOG_LENGTH',
803 'GL_ATTACHED_SHADERS',
804 'GL_ACTIVE_ATTRIBUTES',
805 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
806 'GL_ACTIVE_UNIFORMS',
807 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
810 'QueryObjectParameter': {
811 'type': 'GLenum',
812 'valid': [
813 'GL_QUERY_RESULT_EXT',
814 'GL_QUERY_RESULT_AVAILABLE_EXT',
817 'QueryParameter': {
818 'type': 'GLenum',
819 'valid': [
820 'GL_CURRENT_QUERY_EXT',
823 'QueryTarget': {
824 'type': 'GLenum',
825 'valid': [
826 'GL_ANY_SAMPLES_PASSED_EXT',
827 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
828 'GL_COMMANDS_ISSUED_CHROMIUM',
829 'GL_LATENCY_QUERY_CHROMIUM',
830 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
831 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
834 'RenderBufferParameter': {
835 'type': 'GLenum',
836 'valid': [
837 'GL_RENDERBUFFER_RED_SIZE',
838 'GL_RENDERBUFFER_GREEN_SIZE',
839 'GL_RENDERBUFFER_BLUE_SIZE',
840 'GL_RENDERBUFFER_ALPHA_SIZE',
841 'GL_RENDERBUFFER_DEPTH_SIZE',
842 'GL_RENDERBUFFER_STENCIL_SIZE',
843 'GL_RENDERBUFFER_WIDTH',
844 'GL_RENDERBUFFER_HEIGHT',
845 'GL_RENDERBUFFER_INTERNAL_FORMAT',
848 'ShaderParameter': {
849 'type': 'GLenum',
850 'valid': [
851 'GL_SHADER_TYPE',
852 'GL_DELETE_STATUS',
853 'GL_COMPILE_STATUS',
854 'GL_INFO_LOG_LENGTH',
855 'GL_SHADER_SOURCE_LENGTH',
856 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
859 'ShaderPrecision': {
860 'type': 'GLenum',
861 'valid': [
862 'GL_LOW_FLOAT',
863 'GL_MEDIUM_FLOAT',
864 'GL_HIGH_FLOAT',
865 'GL_LOW_INT',
866 'GL_MEDIUM_INT',
867 'GL_HIGH_INT',
870 'StringType': {
871 'type': 'GLenum',
872 'valid': [
873 'GL_VENDOR',
874 'GL_RENDERER',
875 'GL_VERSION',
876 'GL_SHADING_LANGUAGE_VERSION',
877 'GL_EXTENSIONS',
880 'TextureParameter': {
881 'type': 'GLenum',
882 'valid': [
883 'GL_TEXTURE_MAG_FILTER',
884 'GL_TEXTURE_MIN_FILTER',
885 'GL_TEXTURE_POOL_CHROMIUM',
886 'GL_TEXTURE_WRAP_S',
887 'GL_TEXTURE_WRAP_T',
889 'invalid': [
890 'GL_GENERATE_MIPMAP',
893 'TexturePool': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
897 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
900 'TextureWrapMode': {
901 'type': 'GLenum',
902 'valid': [
903 'GL_CLAMP_TO_EDGE',
904 'GL_MIRRORED_REPEAT',
905 'GL_REPEAT',
908 'TextureMinFilterMode': {
909 'type': 'GLenum',
910 'valid': [
911 'GL_NEAREST',
912 'GL_LINEAR',
913 'GL_NEAREST_MIPMAP_NEAREST',
914 'GL_LINEAR_MIPMAP_NEAREST',
915 'GL_NEAREST_MIPMAP_LINEAR',
916 'GL_LINEAR_MIPMAP_LINEAR',
919 'TextureMagFilterMode': {
920 'type': 'GLenum',
921 'valid': [
922 'GL_NEAREST',
923 'GL_LINEAR',
926 'TextureUsage': {
927 'type': 'GLenum',
928 'valid': [
929 'GL_NONE',
930 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
933 'VertexAttribute': {
934 'type': 'GLenum',
935 'valid': [
936 # some enum that the decoder actually passes through to GL needs
937 # to be the first listed here since it's used in unit tests.
938 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
939 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
940 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
941 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
942 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
943 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
944 'GL_CURRENT_VERTEX_ATTRIB',
947 'VertexPointer': {
948 'type': 'GLenum',
949 'valid': [
950 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
953 'HintTarget': {
954 'type': 'GLenum',
955 'valid': [
956 'GL_GENERATE_MIPMAP_HINT',
958 'invalid': [
959 'GL_PERSPECTIVE_CORRECTION_HINT',
962 'HintMode': {
963 'type': 'GLenum',
964 'valid': [
965 'GL_FASTEST',
966 'GL_NICEST',
967 'GL_DONT_CARE',
970 'PixelStore': {
971 'type': 'GLenum',
972 'valid': [
973 'GL_PACK_ALIGNMENT',
974 'GL_UNPACK_ALIGNMENT',
975 'GL_UNPACK_FLIP_Y_CHROMIUM',
976 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
977 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
979 'invalid': [
980 'GL_PACK_SWAP_BYTES',
981 'GL_UNPACK_SWAP_BYTES',
984 'PixelStoreAlignment': {
985 'type': 'GLint',
986 'valid': [
987 '1',
988 '2',
989 '4',
990 '8',
992 'invalid': [
993 '3',
994 '9',
997 'ReadPixelFormat': {
998 'type': 'GLenum',
999 'valid': [
1000 'GL_ALPHA',
1001 'GL_RGB',
1002 'GL_RGBA',
1005 'PixelType': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_UNSIGNED_BYTE',
1009 'GL_UNSIGNED_SHORT_5_6_5',
1010 'GL_UNSIGNED_SHORT_4_4_4_4',
1011 'GL_UNSIGNED_SHORT_5_5_5_1',
1013 'invalid': [
1014 'GL_SHORT',
1015 'GL_INT',
1018 'ReadPixelType': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_UNSIGNED_BYTE',
1022 'GL_UNSIGNED_SHORT_5_6_5',
1023 'GL_UNSIGNED_SHORT_4_4_4_4',
1024 'GL_UNSIGNED_SHORT_5_5_5_1',
1026 'invalid': [
1027 'GL_SHORT',
1028 'GL_INT',
1031 'RenderBufferFormat': {
1032 'type': 'GLenum',
1033 'valid': [
1034 'GL_RGBA4',
1035 'GL_RGB565',
1036 'GL_RGB5_A1',
1037 'GL_DEPTH_COMPONENT16',
1038 'GL_STENCIL_INDEX8',
1041 'ShaderBinaryFormat': {
1042 'type': 'GLenum',
1043 'valid': [
1046 'StencilOp': {
1047 'type': 'GLenum',
1048 'valid': [
1049 'GL_KEEP',
1050 'GL_ZERO',
1051 'GL_REPLACE',
1052 'GL_INCR',
1053 'GL_INCR_WRAP',
1054 'GL_DECR',
1055 'GL_DECR_WRAP',
1056 'GL_INVERT',
1059 'TextureFormat': {
1060 'type': 'GLenum',
1061 'valid': [
1062 'GL_ALPHA',
1063 'GL_LUMINANCE',
1064 'GL_LUMINANCE_ALPHA',
1065 'GL_RGB',
1066 'GL_RGBA',
1068 'invalid': [
1069 'GL_BGRA',
1070 'GL_BGR',
1073 'TextureInternalFormat': {
1074 'type': 'GLenum',
1075 'valid': [
1076 'GL_ALPHA',
1077 'GL_LUMINANCE',
1078 'GL_LUMINANCE_ALPHA',
1079 'GL_RGB',
1080 'GL_RGBA',
1082 'invalid': [
1083 'GL_BGRA',
1084 'GL_BGR',
1087 'TextureInternalFormatStorage': {
1088 'type': 'GLenum',
1089 'valid': [
1090 'GL_RGB565',
1091 'GL_RGBA4',
1092 'GL_RGB5_A1',
1093 'GL_ALPHA8_EXT',
1094 'GL_LUMINANCE8_EXT',
1095 'GL_LUMINANCE8_ALPHA8_EXT',
1096 'GL_RGB8_OES',
1097 'GL_RGBA8_OES',
1100 'VertexAttribType': {
1101 'type': 'GLenum',
1102 'valid': [
1103 'GL_BYTE',
1104 'GL_UNSIGNED_BYTE',
1105 'GL_SHORT',
1106 'GL_UNSIGNED_SHORT',
1107 # 'GL_FIXED', // This is not available on Desktop GL.
1108 'GL_FLOAT',
1110 'invalid': [
1111 'GL_DOUBLE',
1114 'TextureBorder': {
1115 'type': 'GLint',
1116 'valid': [
1117 '0',
1119 'invalid': [
1120 '1',
1123 'VertexAttribSize': {
1124 'type': 'GLint',
1125 'valid': [
1126 '1',
1127 '2',
1128 '3',
1129 '4',
1131 'invalid': [
1132 '0',
1133 '5',
1136 'ZeroOnly': {
1137 'type': 'GLint',
1138 'valid': [
1139 '0',
1141 'invalid': [
1142 '1',
1145 'FalseOnly': {
1146 'type': 'GLboolean',
1147 'valid': [
1148 'false',
1150 'invalid': [
1151 'true',
1154 'ResetStatus': {
1155 'type': 'GLenum',
1156 'valid': [
1157 'GL_GUILTY_CONTEXT_RESET_ARB',
1158 'GL_INNOCENT_CONTEXT_RESET_ARB',
1159 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1164 # This table specifies the different pepper interfaces that are supported for
1165 # GL commands. 'dev' is true if it's a dev interface.
1166 _PEPPER_INTERFACES = [
1167 {'name': '', 'dev': False},
1168 {'name': 'InstancedArrays', 'dev': False},
1169 {'name': 'FramebufferBlit', 'dev': False},
1170 {'name': 'FramebufferMultisample', 'dev': False},
1171 {'name': 'ChromiumEnableFeature', 'dev': False},
1172 {'name': 'ChromiumMapSub', 'dev': False},
1173 {'name': 'Query', 'dev': False},
1176 # This table specifies types and other special data for the commands that
1177 # will be generated.
1179 # Must match function names specified in "cmd_buffer_functions.txt".
1181 # cmd_comment: A comment added to the cmd format.
1182 # type: defines which handler will be used to generate code.
1183 # decoder_func: defines which function to call in the decoder to execute the
1184 # corresponding GL command. If not specified the GL command will
1185 # be called directly.
1186 # gl_test_func: GL function that is expected to be called when testing.
1187 # cmd_args: The arguments to use for the command. This overrides generating
1188 # them based on the GL function arguments.
1189 # a NonImmediate type is a type that stays a pointer even in
1190 # and immediate version of acommand.
1191 # gen_cmd: Whether or not this function geneates a command. Default = True.
1192 # immediate: Whether or not to generate an immediate command for the GL
1193 # function. The default is if there is exactly 1 pointer argument
1194 # in the GL function an immediate command is generated.
1195 # bucket: True to generate a bucket version of the command.
1196 # impl_func: Whether or not to generate the GLES2Implementation part of this
1197 # command.
1198 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1199 # for this command.
1200 # needs_size: If true a data_size field is added to the command.
1201 # data_type: The type of data the command uses. For PUTn or PUT types.
1202 # count: The number of units per element. For PUTn or PUT types.
1203 # unit_test: If False no service side unit test will be generated.
1204 # client_test: If False no client side unit test will be generated.
1205 # expectation: If False the unit test will have no expected calls.
1206 # gen_func: Name of function that generates GL resource for corresponding
1207 # bind function.
1208 # states: array of states that get set by this function corresponding to
1209 # the given arguments
1210 # state_flag: name of flag that is set to true when function is called.
1211 # no_gl: no GL function is called.
1212 # valid_args: A dictionary of argument indices to args to use in unit tests
1213 # when they can not be automatically determined.
1214 # pepper_interface: The pepper interface that is used for this extension
1215 # invalid_test: False if no invalid test needed.
1216 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1217 # first_element_only: For PUT types, True if only the first element of an
1218 # array is used and we end up calling the single value
1219 # corresponding function. eg. TexParameteriv -> TexParameteri
1221 _FUNCTION_INFO = {
1222 'ActiveTexture': {
1223 'decoder_func': 'DoActiveTexture',
1224 'unit_test': False,
1225 'impl_func': False,
1226 'client_test': False,
1228 'AttachShader': {'decoder_func': 'DoAttachShader'},
1229 'BindAttribLocation': {'type': 'GLchar', 'bucket': True, 'needs_size': True},
1230 'BindBuffer': {
1231 'type': 'Bind',
1232 'decoder_func': 'DoBindBuffer',
1233 'gen_func': 'GenBuffersARB',
1235 'BindFramebuffer': {
1236 'type': 'Bind',
1237 'decoder_func': 'DoBindFramebuffer',
1238 'gl_test_func': 'glBindFramebufferEXT',
1239 'gen_func': 'GenFramebuffersEXT',
1241 'BindRenderbuffer': {
1242 'type': 'Bind',
1243 'decoder_func': 'DoBindRenderbuffer',
1244 'gl_test_func': 'glBindRenderbufferEXT',
1245 'gen_func': 'GenRenderbuffersEXT',
1247 'BindTexture': {
1248 'type': 'Bind',
1249 'decoder_func': 'DoBindTexture',
1250 'gen_func': 'GenTextures',
1251 # TODO(gman): remove this once client side caching works.
1252 'client_test': False,
1254 'BlitFramebufferEXT': {
1255 'decoder_func': 'DoBlitFramebufferEXT',
1256 'unit_test': False,
1257 'extension': True,
1258 'pepper_interface': 'FramebufferBlit',
1259 'defer_reads': True,
1260 'defer_draws': True,
1262 'BufferData': {
1263 'type': 'Manual',
1264 'immediate': True,
1265 'client_test': False,
1267 'BufferSubData': {
1268 'type': 'Data',
1269 'client_test': False,
1270 'decoder_func': 'DoBufferSubData',
1272 'CheckFramebufferStatus': {
1273 'type': 'Is',
1274 'decoder_func': 'DoCheckFramebufferStatus',
1275 'gl_test_func': 'glCheckFramebufferStatusEXT',
1276 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1277 'result': ['GLenum'],
1279 'Clear': {
1280 'decoder_func': 'DoClear',
1281 'defer_draws': True,
1283 'ClearColor': {
1284 'type': 'StateSet',
1285 'state': 'ClearColor',
1287 'ClearDepthf': {
1288 'type': 'StateSet',
1289 'state': 'ClearDepthf',
1290 'decoder_func': 'glClearDepth',
1291 'gl_test_func': 'glClearDepth',
1292 'valid_args': {
1293 '0': '0.5f'
1296 'ColorMask': {
1297 'type': 'StateSet',
1298 'state': 'ColorMask',
1299 'no_gl': True,
1300 'expectation': False,
1302 'ConsumeTextureCHROMIUM': {
1303 'decoder_func': 'DoConsumeTextureCHROMIUM',
1304 'type': 'PUT',
1305 'data_type': 'GLbyte',
1306 'count': 64,
1307 'unit_test': False,
1308 'extension': True,
1309 'chromium': True,
1311 'ClearStencil': {
1312 'type': 'StateSet',
1313 'state': 'ClearStencil',
1315 'EnableFeatureCHROMIUM': {
1316 'type': 'Custom',
1317 'immediate': False,
1318 'decoder_func': 'DoEnableFeatureCHROMIUM',
1319 'expectation': False,
1320 'cmd_args': 'GLuint bucket_id, GLint* result',
1321 'result': ['GLint'],
1322 'extension': True,
1323 'chromium': True,
1324 'pepper_interface': 'ChromiumEnableFeature',
1326 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1327 'CompressedTexImage2D': {
1328 'type': 'Manual',
1329 'immediate': True,
1330 'bucket': True,
1332 'CompressedTexSubImage2D': {
1333 'type': 'Data',
1334 'bucket': True,
1335 'decoder_func': 'DoCompressedTexSubImage2D',
1337 'CopyTexImage2D': {
1338 'decoder_func': 'DoCopyTexImage2D',
1339 'unit_test': False,
1340 'defer_reads': True,
1342 'CopyTexSubImage2D': {
1343 'decoder_func': 'DoCopyTexSubImage2D',
1344 'defer_reads': True,
1346 'CreateImageCHROMIUM': {
1347 'type': 'Manual',
1348 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1349 'result': ['GLuint'],
1350 'client_test': False,
1351 'gen_cmd': False,
1352 'expectation': False,
1353 'extension': True,
1354 'chromium': True,
1356 'DestroyImageCHROMIUM': {
1357 'type': 'Manual',
1358 'immediate': True,
1359 'client_test': False,
1360 'gen_cmd': False,
1361 'extension': True,
1362 'chromium': True,
1364 'GetImageParameterivCHROMIUM': {
1365 'type': 'Manual',
1366 'client_test': False,
1367 'gen_cmd': False,
1368 'expectation': False,
1369 'extension': True,
1370 'chromium': True,
1372 'CreateProgram': {
1373 'type': 'Create',
1374 'client_test': False,
1376 'CreateShader': {
1377 'type': 'Create',
1378 'client_test': False,
1380 'BlendColor': {
1381 'type': 'StateSet',
1382 'state': 'BlendColor',
1384 'BlendEquation': {
1385 'type': 'StateSetRGBAlpha',
1386 'state': 'BlendEquation',
1387 'valid_args': {
1388 '0': 'GL_FUNC_SUBTRACT'
1391 'BlendEquationSeparate': {
1392 'type': 'StateSet',
1393 'state': 'BlendEquation',
1394 'valid_args': {
1395 '0': 'GL_FUNC_SUBTRACT'
1398 'BlendFunc': {
1399 'type': 'StateSetRGBAlpha',
1400 'state': 'BlendFunc',
1402 'BlendFuncSeparate': {
1403 'type': 'StateSet',
1404 'state': 'BlendFunc',
1406 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1407 'StencilFunc': {
1408 'type': 'StateSetFrontBack',
1409 'state': 'StencilFunc',
1411 'StencilFuncSeparate': {
1412 'type': 'StateSetFrontBackSeparate',
1413 'state': 'StencilFunc',
1415 'StencilOp': {
1416 'type': 'StateSetFrontBack',
1417 'state': 'StencilOp',
1418 'valid_args': {
1419 '1': 'GL_INCR'
1422 'StencilOpSeparate': {
1423 'type': 'StateSetFrontBackSeparate',
1424 'state': 'StencilOp',
1425 'valid_args': {
1426 '1': 'GL_INCR'
1429 'Hint': {
1430 'type': 'StateSetNamedParameter',
1431 'state': 'Hint',
1433 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1434 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1435 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1436 'LineWidth': {
1437 'type': 'StateSet',
1438 'state': 'LineWidth',
1439 'valid_args': {
1440 '0': '0.5f'
1443 'PolygonOffset': {
1444 'type': 'StateSet',
1445 'state': 'PolygonOffset',
1447 'DeleteBuffers': {
1448 'type': 'DELn',
1449 'gl_test_func': 'glDeleteBuffersARB',
1450 'resource_type': 'Buffer',
1451 'resource_types': 'Buffers',
1453 'DeleteFramebuffers': {
1454 'type': 'DELn',
1455 'gl_test_func': 'glDeleteFramebuffersEXT',
1456 'resource_type': 'Framebuffer',
1457 'resource_types': 'Framebuffers',
1459 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1460 'DeleteRenderbuffers': {
1461 'type': 'DELn',
1462 'gl_test_func': 'glDeleteRenderbuffersEXT',
1463 'resource_type': 'Renderbuffer',
1464 'resource_types': 'Renderbuffers',
1466 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1467 'DeleteSharedIdsCHROMIUM': {
1468 'type': 'Custom',
1469 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1470 'impl_func': False,
1471 'expectation': False,
1472 'immediate': False,
1473 'extension': True,
1474 'chromium': True,
1476 'DeleteTextures': {
1477 'type': 'DELn',
1478 'resource_type': 'Texture',
1479 'resource_types': 'Textures',
1481 'DepthRangef': {
1482 'decoder_func': 'DoDepthRangef',
1483 'gl_test_func': 'glDepthRange',
1485 'DepthMask': {
1486 'type': 'StateSet',
1487 'state': 'DepthMask',
1488 'no_gl': True,
1489 'expectation': False,
1491 'DetachShader': {'decoder_func': 'DoDetachShader'},
1492 'Disable': {
1493 'decoder_func': 'DoDisable',
1494 'impl_func': False,
1495 'client_test': False,
1497 'DisableVertexAttribArray': {
1498 'decoder_func': 'DoDisableVertexAttribArray',
1499 'impl_decl': False,
1501 'DrawArrays': {
1502 'type': 'Manual',
1503 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1504 'defer_draws': True,
1506 'DrawElements': {
1507 'type': 'Manual',
1508 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1509 'GLenumIndexType type, GLuint index_offset',
1510 'client_test': False,
1511 'defer_draws': True,
1513 'Enable': {
1514 'decoder_func': 'DoEnable',
1515 'impl_func': False,
1516 'client_test': False,
1518 'EnableVertexAttribArray': {
1519 'decoder_func': 'DoEnableVertexAttribArray',
1520 'impl_decl': False,
1522 'Finish': {
1523 'impl_func': False,
1524 'client_test': False,
1525 'decoder_func': 'DoFinish',
1526 'defer_reads': True,
1528 'Flush': {
1529 'impl_func': False,
1530 'decoder_func': 'DoFlush',
1532 'FramebufferRenderbuffer': {
1533 'decoder_func': 'DoFramebufferRenderbuffer',
1534 'gl_test_func': 'glFramebufferRenderbufferEXT',
1536 'FramebufferTexture2D': {
1537 'decoder_func': 'DoFramebufferTexture2D',
1538 'gl_test_func': 'glFramebufferTexture2DEXT',
1540 'FramebufferTexture2DMultisampleEXT': {
1541 'decoder_func': 'DoFramebufferTexture2DMultisample',
1542 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1543 'expectation': False,
1544 'unit_test': False,
1545 'extension': True,
1547 'GenerateMipmap': {
1548 'decoder_func': 'DoGenerateMipmap',
1549 'gl_test_func': 'glGenerateMipmapEXT',
1551 'GenBuffers': {
1552 'type': 'GENn',
1553 'gl_test_func': 'glGenBuffersARB',
1554 'resource_type': 'Buffer',
1555 'resource_types': 'Buffers',
1557 'GenMailboxCHROMIUM': {
1558 'type': 'Manual',
1559 'cmd_args': 'GLuint bucket_id',
1560 'result': ['SizedResult<GLint>'],
1561 'client_test': False,
1562 'unit_test': False,
1563 'extension': True,
1564 'chromium': True,
1566 'GenFramebuffers': {
1567 'type': 'GENn',
1568 'gl_test_func': 'glGenFramebuffersEXT',
1569 'resource_type': 'Framebuffer',
1570 'resource_types': 'Framebuffers',
1572 'GenRenderbuffers': {
1573 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1574 'resource_type': 'Renderbuffer',
1575 'resource_types': 'Renderbuffers',
1577 'GenTextures': {
1578 'type': 'GENn',
1579 'gl_test_func': 'glGenTextures',
1580 'resource_type': 'Texture',
1581 'resource_types': 'Textures',
1583 'GenSharedIdsCHROMIUM': {
1584 'type': 'Custom',
1585 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1586 'impl_func': False,
1587 'expectation': False,
1588 'immediate': False,
1589 'extension': True,
1590 'chromium': True,
1592 'GetActiveAttrib': {
1593 'type': 'Custom',
1594 'immediate': False,
1595 'cmd_args':
1596 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1597 'void* result',
1598 'result': [
1599 'int32 success',
1600 'int32 size',
1601 'uint32 type',
1604 'GetActiveUniform': {
1605 'type': 'Custom',
1606 'immediate': False,
1607 'cmd_args':
1608 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1609 'void* result',
1610 'result': [
1611 'int32 success',
1612 'int32 size',
1613 'uint32 type',
1616 'GetAttachedShaders': {
1617 'type': 'Custom',
1618 'immediate': False,
1619 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1620 'result': ['SizedResult<GLuint>'],
1622 'GetAttribLocation': {
1623 'type': 'HandWritten',
1624 'immediate': True,
1625 'bucket': True,
1626 'needs_size': True,
1627 'cmd_args':
1628 'GLidProgram program, const char* name, NonImmediate GLint* location',
1629 'result': ['GLint'],
1631 'GetBooleanv': {
1632 'type': 'GETn',
1633 'result': ['SizedResult<GLboolean>'],
1634 'decoder_func': 'DoGetBooleanv',
1635 'gl_test_func': 'glGetBooleanv',
1637 'GetBufferParameteriv': {
1638 'type': 'GETn',
1639 'result': ['SizedResult<GLint>'],
1640 'decoder_func': 'DoGetBufferParameteriv',
1641 'expectation': False,
1642 'shadowed': True,
1644 'GetError': {
1645 'type': 'Is',
1646 'decoder_func': 'GetErrorState()->GetGLError',
1647 'impl_func': False,
1648 'result': ['GLenum'],
1649 'client_test': False,
1651 'GetFloatv': {
1652 'type': 'GETn',
1653 'result': ['SizedResult<GLfloat>'],
1654 'decoder_func': 'DoGetFloatv',
1655 'gl_test_func': 'glGetFloatv',
1657 'GetFramebufferAttachmentParameteriv': {
1658 'type': 'GETn',
1659 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1660 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1661 'result': ['SizedResult<GLint>'],
1663 'GetIntegerv': {
1664 'type': 'GETn',
1665 'result': ['SizedResult<GLint>'],
1666 'decoder_func': 'DoGetIntegerv',
1667 'client_test': False,
1669 'GetMaxValueInBufferCHROMIUM': {
1670 'type': 'Is',
1671 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1672 'result': ['GLuint'],
1673 'unit_test': False,
1674 'client_test': False,
1675 'extension': True,
1676 'chromium': True,
1677 'impl_func': False,
1679 'GetMultipleIntegervCHROMIUM': {
1680 'type': 'Custom',
1681 'immediate': False,
1682 'expectation': False,
1683 'extension': True,
1684 'chromium': True,
1685 'client_test': False,
1687 'GetProgramiv': {
1688 'type': 'GETn',
1689 'decoder_func': 'DoGetProgramiv',
1690 'result': ['SizedResult<GLint>'],
1691 'expectation': False,
1693 'GetProgramInfoCHROMIUM': {
1694 'type': 'Custom',
1695 'immediate': False,
1696 'expectation': False,
1697 'impl_func': False,
1698 'extension': True,
1699 'chromium': True,
1700 'client_test': False,
1701 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1702 'result': [
1703 'uint32 link_status',
1704 'uint32 num_attribs',
1705 'uint32 num_uniforms',
1708 'GetProgramInfoLog': {
1709 'type': 'STRn',
1710 'expectation': False,
1712 'GetRenderbufferParameteriv': {
1713 'type': 'GETn',
1714 'decoder_func': 'DoGetRenderbufferParameteriv',
1715 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1716 'result': ['SizedResult<GLint>'],
1718 'GetShaderiv': {
1719 'type': 'GETn',
1720 'decoder_func': 'DoGetShaderiv',
1721 'result': ['SizedResult<GLint>'],
1723 'GetShaderInfoLog': {
1724 'type': 'STRn',
1725 'get_len_func': 'glGetShaderiv',
1726 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1727 'unit_test': False,
1729 'GetShaderPrecisionFormat': {
1730 'type': 'Custom',
1731 'immediate': False,
1732 'cmd_args':
1733 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1734 'void* result',
1735 'result': [
1736 'int32 success',
1737 'int32 min_range',
1738 'int32 max_range',
1739 'int32 precision',
1742 'GetShaderSource': {
1743 'type': 'STRn',
1744 'get_len_func': 'DoGetShaderiv',
1745 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1746 'unit_test': False,
1747 'client_test': False,
1749 'GetString': {
1750 'type': 'Custom',
1751 'client_test': False,
1752 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1754 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1755 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1756 'GetTranslatedShaderSourceANGLE': {
1757 'type': 'STRn',
1758 'get_len_func': 'DoGetShaderiv',
1759 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1760 'unit_test': False,
1761 'extension': True,
1763 'GetUniformfv': {
1764 'type': 'Custom',
1765 'immediate': False,
1766 'result': ['SizedResult<GLfloat>'],
1768 'GetUniformiv': {
1769 'type': 'Custom',
1770 'immediate': False,
1771 'result': ['SizedResult<GLint>'],
1773 'GetUniformLocation': {
1774 'type': 'HandWritten',
1775 'immediate': True,
1776 'bucket': True,
1777 'needs_size': True,
1778 'cmd_args':
1779 'GLidProgram program, const char* name, NonImmediate GLint* location',
1780 'result': ['GLint'],
1782 'GetVertexAttribfv': {
1783 'type': 'GETn',
1784 'result': ['SizedResult<GLfloat>'],
1785 'impl_decl': False,
1786 'decoder_func': 'DoGetVertexAttribfv',
1787 'expectation': False,
1788 'client_test': False,
1790 'GetVertexAttribiv': {
1791 'type': 'GETn',
1792 'result': ['SizedResult<GLint>'],
1793 'impl_decl': False,
1794 'decoder_func': 'DoGetVertexAttribiv',
1795 'expectation': False,
1796 'client_test': False,
1798 'GetVertexAttribPointerv': {
1799 'type': 'Custom',
1800 'immediate': False,
1801 'result': ['SizedResult<GLuint>'],
1802 'client_test': False,
1804 'IsBuffer': {
1805 'type': 'Is',
1806 'decoder_func': 'DoIsBuffer',
1807 'expectation': False,
1809 'IsEnabled': {
1810 'type': 'Is',
1811 'decoder_func': 'DoIsEnabled',
1812 'impl_func': False,
1813 'expectation': False,
1815 'IsFramebuffer': {
1816 'type': 'Is',
1817 'decoder_func': 'DoIsFramebuffer',
1818 'expectation': False,
1820 'IsProgram': {
1821 'type': 'Is',
1822 'decoder_func': 'DoIsProgram',
1823 'expectation': False,
1825 'IsRenderbuffer': {
1826 'type': 'Is',
1827 'decoder_func': 'DoIsRenderbuffer',
1828 'expectation': False,
1830 'IsShader': {
1831 'type': 'Is',
1832 'decoder_func': 'DoIsShader',
1833 'expectation': False,
1835 'IsTexture': {
1836 'type': 'Is',
1837 'decoder_func': 'DoIsTexture',
1838 'expectation': False,
1840 'LinkProgram': {
1841 'decoder_func': 'DoLinkProgram',
1842 'impl_func': False,
1844 'MapBufferCHROMIUM': {
1845 'gen_cmd': False,
1846 'extension': True,
1847 'chromium': True,
1848 'client_test': False,
1850 'MapBufferSubDataCHROMIUM': {
1851 'gen_cmd': False,
1852 'extension': True,
1853 'chromium': True,
1854 'client_test': False,
1855 'pepper_interface': 'ChromiumMapSub',
1857 'MapImageCHROMIUM': {
1858 'gen_cmd': False,
1859 'extension': True,
1860 'chromium': True,
1861 'client_test': False,
1863 'MapTexSubImage2DCHROMIUM': {
1864 'gen_cmd': False,
1865 'extension': True,
1866 'chromium': True,
1867 'client_test': False,
1868 'pepper_interface': 'ChromiumMapSub',
1870 'PixelStorei': {'type': 'Manual'},
1871 'PostSubBufferCHROMIUM': {
1872 'type': 'Custom',
1873 'impl_func': False,
1874 'unit_test': False,
1875 'client_test': False,
1876 'extension': True,
1877 'chromium': True,
1879 'ProduceTextureCHROMIUM': {
1880 'decoder_func': 'DoProduceTextureCHROMIUM',
1881 'type': 'PUT',
1882 'data_type': 'GLbyte',
1883 'count': 64,
1884 'unit_test': False,
1885 'extension': True,
1886 'chromium': True,
1888 'RenderbufferStorage': {
1889 'decoder_func': 'DoRenderbufferStorage',
1890 'gl_test_func': 'glRenderbufferStorageEXT',
1891 'expectation': False,
1893 'RenderbufferStorageMultisampleEXT': {
1894 'decoder_func': 'DoRenderbufferStorageMultisample',
1895 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1896 'expectation': False,
1897 'unit_test': False,
1898 'extension': True,
1899 'pepper_interface': 'FramebufferMultisample',
1901 'ReadPixels': {
1902 'cmd_comment':
1903 '// ReadPixels has the result separated from the pixel buffer so that\n'
1904 '// it is easier to specify the result going to some specific place\n'
1905 '// that exactly fits the rectangle of pixels.\n',
1906 'type': 'Custom',
1907 'immediate': False,
1908 'impl_func': False,
1909 'client_test': False,
1910 'cmd_args':
1911 'GLint x, GLint y, GLsizei width, GLsizei height, '
1912 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1913 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1914 'uint32 result_shm_id, uint32 result_shm_offset, '
1915 'GLboolean async',
1916 'result': ['uint32'],
1917 'defer_reads': True,
1919 'RegisterSharedIdsCHROMIUM': {
1920 'type': 'Custom',
1921 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1922 'impl_func': False,
1923 'expectation': False,
1924 'immediate': False,
1925 'extension': True,
1926 'chromium': True,
1928 'ReleaseShaderCompiler': {
1929 'decoder_func': 'DoReleaseShaderCompiler',
1930 'unit_test': False,
1932 'ShaderBinary': {
1933 'type': 'Custom',
1934 'client_test': False,
1936 'ShaderSource': {
1937 'type': 'Manual',
1938 'immediate': True,
1939 'bucket': True,
1940 'needs_size': True,
1941 'client_test': False,
1942 'cmd_args':
1943 'GLuint shader, const char* data',
1945 'StencilMask': {
1946 'type': 'StateSetFrontBack',
1947 'state': 'StencilMask',
1948 'no_gl': True,
1949 'expectation': False,
1951 'StencilMaskSeparate': {
1952 'type': 'StateSetFrontBackSeparate',
1953 'state': 'StencilMask',
1954 'no_gl': True,
1955 'expectation': False,
1957 'SwapBuffers': {
1958 'impl_func': False,
1959 'decoder_func': 'DoSwapBuffers',
1960 'unit_test': False,
1961 'client_test': False,
1962 'extension': True,
1964 'TexImage2D': {
1965 'type': 'Manual',
1966 'immediate': True,
1967 'client_test': False,
1969 'TexParameterf': {
1970 'decoder_func': 'DoTexParameterf',
1971 'gl_test_func': 'glTexParameteri',
1972 'valid_args': {
1973 '2': 'GL_NEAREST'
1976 'TexParameteri': {
1977 'decoder_func': 'DoTexParameteri',
1978 'valid_args': {
1979 '2': 'GL_NEAREST'
1982 'TexParameterfv': {
1983 'type': 'PUT',
1984 'data_type': 'GLfloat',
1985 'data_value': 'GL_NEAREST',
1986 'count': 1,
1987 'decoder_func': 'DoTexParameterfv',
1988 'gl_test_func': 'glTexParameteri',
1989 'first_element_only': True,
1991 'TexParameteriv': {
1992 'type': 'PUT',
1993 'data_type': 'GLint',
1994 'data_value': 'GL_NEAREST',
1995 'count': 1,
1996 'decoder_func': 'DoTexParameteriv',
1997 'gl_test_func': 'glTexParameteri',
1998 'first_element_only': True,
2000 'TexSubImage2D': {
2001 'type': 'Manual',
2002 'immediate': True,
2003 'client_test': False,
2004 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2005 'GLint xoffset, GLint yoffset, '
2006 'GLsizei width, GLsizei height, '
2007 'GLenumTextureFormat format, GLenumPixelType type, '
2008 'const void* pixels, GLboolean internal'
2010 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2011 'Uniform1fv': {
2012 'type': 'PUTn',
2013 'data_type': 'GLfloat',
2014 'count': 1,
2015 'decoder_func': 'DoUniform1fv',
2017 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2018 'Uniform1iv': {
2019 'type': 'PUTn',
2020 'data_type': 'GLint',
2021 'count': 1,
2022 'decoder_func': 'DoUniform1iv',
2023 'unit_test': False,
2025 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2026 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2027 'Uniform2fv': {
2028 'type': 'PUTn',
2029 'data_type': 'GLfloat',
2030 'count': 2,
2031 'decoder_func': 'DoUniform2fv',
2033 'Uniform2iv': {
2034 'type': 'PUTn',
2035 'data_type': 'GLint',
2036 'count': 2,
2037 'decoder_func': 'DoUniform2iv',
2039 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2040 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2041 'Uniform3fv': {
2042 'type': 'PUTn',
2043 'data_type': 'GLfloat',
2044 'count': 3,
2045 'decoder_func': 'DoUniform3fv',
2047 'Uniform3iv': {
2048 'type': 'PUTn',
2049 'data_type': 'GLint',
2050 'count': 3,
2051 'decoder_func': 'DoUniform3iv',
2053 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2054 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2055 'Uniform4fv': {
2056 'type': 'PUTn',
2057 'data_type': 'GLfloat',
2058 'count': 4,
2059 'decoder_func': 'DoUniform4fv',
2061 'Uniform4iv': {
2062 'type': 'PUTn',
2063 'data_type': 'GLint',
2064 'count': 4,
2065 'decoder_func': 'DoUniform4iv',
2067 'UniformMatrix2fv': {
2068 'type': 'PUTn',
2069 'data_type': 'GLfloat',
2070 'count': 4,
2071 'decoder_func': 'DoUniformMatrix2fv',
2073 'UniformMatrix3fv': {
2074 'type': 'PUTn',
2075 'data_type': 'GLfloat',
2076 'count': 9,
2077 'decoder_func': 'DoUniformMatrix3fv',
2079 'UniformMatrix4fv': {
2080 'type': 'PUTn',
2081 'data_type': 'GLfloat',
2082 'count': 16,
2083 'decoder_func': 'DoUniformMatrix4fv',
2085 'UnmapBufferCHROMIUM': {
2086 'gen_cmd': False,
2087 'extension': True,
2088 'chromium': True,
2089 'client_test': False,
2091 'UnmapBufferSubDataCHROMIUM': {
2092 'gen_cmd': False,
2093 'extension': True,
2094 'chromium': True,
2095 'client_test': False,
2096 'pepper_interface': 'ChromiumMapSub',
2098 'UnmapImageCHROMIUM': {
2099 'gen_cmd': False,
2100 'extension': True,
2101 'chromium': True,
2102 'client_test': False,
2104 'UnmapTexSubImage2DCHROMIUM': {
2105 'gen_cmd': False,
2106 'extension': True,
2107 'chromium': True,
2108 'client_test': False,
2109 'pepper_interface': 'ChromiumMapSub',
2111 'UseProgram': {
2112 'decoder_func': 'DoUseProgram',
2113 'impl_func': False,
2114 'unit_test': False,
2116 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2117 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2118 'VertexAttrib1fv': {
2119 'type': 'PUT',
2120 'data_type': 'GLfloat',
2121 'count': 1,
2122 'decoder_func': 'DoVertexAttrib1fv',
2124 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2125 'VertexAttrib2fv': {
2126 'type': 'PUT',
2127 'data_type': 'GLfloat',
2128 'count': 2,
2129 'decoder_func': 'DoVertexAttrib2fv',
2131 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2132 'VertexAttrib3fv': {
2133 'type': 'PUT',
2134 'data_type': 'GLfloat',
2135 'count': 3,
2136 'decoder_func': 'DoVertexAttrib3fv',
2138 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2139 'VertexAttrib4fv': {
2140 'type': 'PUT',
2141 'data_type': 'GLfloat',
2142 'count': 4,
2143 'decoder_func': 'DoVertexAttrib4fv',
2145 'VertexAttribPointer': {
2146 'type': 'Manual',
2147 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2148 'GLenumVertexAttribType type, GLboolean normalized, '
2149 'GLsizei stride, GLuint offset',
2150 'client_test': False,
2152 'Scissor': {
2153 'type': 'StateSet',
2154 'state': 'Scissor',
2156 'Viewport': {
2157 'decoder_func': 'DoViewport',
2159 'ResizeCHROMIUM': {
2160 'type': 'Custom',
2161 'impl_func': False,
2162 'unit_test': False,
2163 'extension': True,
2164 'chromium': True,
2166 'GetRequestableExtensionsCHROMIUM': {
2167 'type': 'Custom',
2168 'impl_func': False,
2169 'immediate': False,
2170 'cmd_args': 'uint32 bucket_id',
2171 'extension': True,
2172 'chromium': True,
2174 'RequestExtensionCHROMIUM': {
2175 'type': 'Custom',
2176 'impl_func': False,
2177 'immediate': False,
2178 'client_test': False,
2179 'cmd_args': 'uint32 bucket_id',
2180 'extension': True,
2181 'chromium': True,
2183 'RateLimitOffscreenContextCHROMIUM': {
2184 'gen_cmd': False,
2185 'extension': True,
2186 'chromium': True,
2187 'client_test': False,
2189 'CreateStreamTextureCHROMIUM': {
2190 'type': 'Custom',
2191 'cmd_args': 'GLuint client_id, void* result',
2192 'result': ['GLuint'],
2193 'immediate': False,
2194 'impl_func': False,
2195 'expectation': False,
2196 'extension': True,
2197 'chromium': True,
2198 'client_test': False,
2200 'DestroyStreamTextureCHROMIUM': {
2201 'type': 'Custom',
2202 'impl_func': False,
2203 'expectation': False,
2204 'extension': True,
2205 'chromium': True,
2207 'TexImageIOSurface2DCHROMIUM': {
2208 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2209 'unit_test': False,
2210 'extension': True,
2211 'chromium': True,
2213 'CopyTextureCHROMIUM': {
2214 'decoder_func': 'DoCopyTextureCHROMIUM',
2215 'unit_test': False,
2216 'extension': True,
2217 'chromium': True,
2219 'TexStorage2DEXT': {
2220 'unit_test': False,
2221 'extension': True,
2222 'decoder_func': 'DoTexStorage2DEXT',
2224 'DrawArraysInstancedANGLE': {
2225 'type': 'Manual',
2226 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2227 'GLsizei primcount',
2228 'extension': True,
2229 'unit_test': False,
2230 'pepper_interface': 'InstancedArrays',
2231 'defer_draws': True,
2233 'DrawBuffersEXT': {
2234 'type': 'PUTn',
2235 'decoder_func': 'DoDrawBuffersEXT',
2236 'data_type': 'GLenum',
2237 'count': 1,
2238 'client_test': False,
2239 'unit_test': False,
2240 'extension': True,
2242 'DrawElementsInstancedANGLE': {
2243 'type': 'Manual',
2244 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2245 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2246 'extension': True,
2247 'unit_test': False,
2248 'client_test': False,
2249 'pepper_interface': 'InstancedArrays',
2250 'defer_draws': True,
2252 'VertexAttribDivisorANGLE': {
2253 'type': 'Manual',
2254 'cmd_args': 'GLuint index, GLuint divisor',
2255 'extension': True,
2256 'unit_test': False,
2257 'pepper_interface': 'InstancedArrays',
2259 'GenQueriesEXT': {
2260 'type': 'GENn',
2261 'gl_test_func': 'glGenQueriesARB',
2262 'resource_type': 'Query',
2263 'resource_types': 'Queries',
2264 'unit_test': False,
2265 'pepper_interface': 'Query',
2267 'DeleteQueriesEXT': {
2268 'type': 'DELn',
2269 'gl_test_func': 'glDeleteQueriesARB',
2270 'resource_type': 'Query',
2271 'resource_types': 'Queries',
2272 'unit_test': False,
2273 'pepper_interface': 'Query',
2275 'IsQueryEXT': {
2276 'gen_cmd': False,
2277 'client_test': False,
2278 'pepper_interface': 'Query',
2280 'BeginQueryEXT': {
2281 'type': 'Manual',
2282 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2283 'immediate': False,
2284 'gl_test_func': 'glBeginQuery',
2285 'pepper_interface': 'Query',
2287 'EndQueryEXT': {
2288 'type': 'Manual',
2289 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2290 'gl_test_func': 'glEndnQuery',
2291 'client_test': False,
2292 'pepper_interface': 'Query',
2294 'GetQueryivEXT': {
2295 'gen_cmd': False,
2296 'client_test': False,
2297 'gl_test_func': 'glGetQueryiv',
2298 'pepper_interface': 'Query',
2300 'GetQueryObjectuivEXT': {
2301 'gen_cmd': False,
2302 'client_test': False,
2303 'gl_test_func': 'glGetQueryObjectuiv',
2304 'pepper_interface': 'Query',
2306 'BindUniformLocationCHROMIUM': {
2307 'type': 'GLchar',
2308 'bucket': True,
2309 'needs_size': True,
2310 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2312 'InsertEventMarkerEXT': {
2313 'type': 'GLcharN',
2314 'decoder_func': 'DoInsertEventMarkerEXT',
2315 'expectation': False,
2317 'PushGroupMarkerEXT': {
2318 'type': 'GLcharN',
2319 'decoder_func': 'DoPushGroupMarkerEXT',
2320 'expectation': False,
2322 'PopGroupMarkerEXT': {
2323 'decoder_func': 'DoPopGroupMarkerEXT',
2324 'expectation': False,
2325 'impl_func': False,
2328 'GenVertexArraysOES': {
2329 'type': 'GENn',
2330 'gl_test_func': 'glGenVertexArraysOES',
2331 'resource_type': 'VertexArray',
2332 'resource_types': 'VertexArrays',
2333 'unit_test': False,
2335 'BindVertexArrayOES': {
2336 'type': 'Bind',
2337 'gl_test_func': 'glBindVertexArrayOES',
2338 'decoder_func': 'DoBindVertexArrayOES',
2339 'gen_func': 'GenVertexArraysOES',
2340 'unit_test': False,
2341 'client_test': False,
2343 'DeleteVertexArraysOES': {
2344 'type': 'DELn',
2345 'gl_test_func': 'glDeleteVertexArraysOES',
2346 'resource_type': 'VertexArray',
2347 'resource_types': 'VertexArrays',
2348 'unit_test': False,
2350 'IsVertexArrayOES': {
2351 'type': 'Is',
2352 'gl_test_func': 'glIsVertexArrayOES',
2353 'decoder_func': 'DoIsVertexArrayOES',
2354 'expectation': False,
2355 'unit_test': False,
2357 'BindTexImage2DCHROMIUM': {
2358 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2359 'unit_test': False,
2360 'extension': True,
2361 'chromium': True,
2363 'ReleaseTexImage2DCHROMIUM': {
2364 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2365 'unit_test': False,
2366 'extension': True,
2367 'chromium': True,
2369 'ShallowFinishCHROMIUM': {
2370 'impl_func': False,
2371 'gen_cmd': False,
2372 'extension': True,
2373 'chromium': True,
2374 'client_test': False,
2376 'ShallowFlushCHROMIUM': {
2377 'impl_func': False,
2378 'gen_cmd': False,
2379 'extension': True,
2380 'chromium': True,
2381 'client_test': False,
2383 'TraceBeginCHROMIUM': {
2384 'type': 'Custom',
2385 'impl_func': False,
2386 'immediate': False,
2387 'client_test': False,
2388 'cmd_args': 'GLuint bucket_id',
2389 'extension': True,
2390 'chromium': True,
2392 'TraceEndCHROMIUM': {
2393 'impl_func': False,
2394 'immediate': False,
2395 'client_test': False,
2396 'decoder_func': 'DoTraceEndCHROMIUM',
2397 'unit_test': False,
2398 'extension': True,
2399 'chromium': True,
2401 'AsyncTexImage2DCHROMIUM': {
2402 'type': 'Manual',
2403 'immediate': False,
2404 'client_test': False,
2405 'extension': True,
2406 'chromium': True,
2408 'AsyncTexSubImage2DCHROMIUM': {
2409 'type': 'Manual',
2410 'immediate': False,
2411 'client_test': False,
2412 'extension': True,
2413 'chromium': True,
2415 'WaitAsyncTexImage2DCHROMIUM': {
2416 'type': 'Manual',
2417 'immediate': False,
2418 'client_test': False,
2419 'extension': True,
2420 'chromium': True,
2422 'DiscardFramebufferEXT': {
2423 'type': 'PUTn',
2424 'count': 1,
2425 'data_type': 'GLenum',
2426 'cmd_args': 'GLenum target, GLsizei count, '
2427 'const GLenum* attachments',
2428 'decoder_func': 'DoDiscardFramebufferEXT',
2429 'unit_test': False,
2430 'client_test': False,
2431 'extension': True,
2433 'LoseContextCHROMIUM': {
2434 'type': 'Manual',
2435 'impl_func': True,
2436 'extension': True,
2437 'chromium': True,
2439 'InsertSyncPointCHROMIUM': {
2440 'type': 'HandWritten',
2441 'impl_func': False,
2442 'extension': True,
2443 'chromium': True,
2445 'WaitSyncPointCHROMIUM': {
2446 'type': 'Custom',
2447 'impl_func': True,
2448 'extension': True,
2449 'chromium': True,
2454 def Grouper(n, iterable, fillvalue=None):
2455 """Collect data into fixed-length chunks or blocks"""
2456 args = [iter(iterable)] * n
2457 return itertools.izip_longest(fillvalue=fillvalue, *args)
2460 def SplitWords(input_string):
2461 """Transforms a input_string into a list of lower-case components.
2463 Args:
2464 input_string: the input string.
2466 Returns:
2467 a list of lower-case words.
2469 if input_string.find('_') > -1:
2470 # 'some_TEXT_' -> 'some text'
2471 return input_string.replace('_', ' ').strip().lower().split()
2472 else:
2473 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2474 # mixed case.
2475 # look for capitalization to cut input_strings
2476 # 'SomeText' -> 'Some Text'
2477 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2478 # 'Vector3' -> 'Vector 3'
2479 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2480 return input_string.lower().split()
2483 def Lower(words):
2484 """Makes a lower-case identifier from words.
2486 Args:
2487 words: a list of lower-case words.
2489 Returns:
2490 the lower-case identifier.
2492 return '_'.join(words)
2495 def ToUnderscore(input_string):
2496 """converts CamelCase to camel_case."""
2497 words = SplitWords(input_string)
2498 return Lower(words)
2501 class CWriter(object):
2502 """Writes to a file formatting it for Google's style guidelines."""
2504 def __init__(self, filename):
2505 self.filename = filename
2506 self.file_num = 0
2507 self.content = []
2509 def SetFileNum(self, num):
2510 """Used to help write number files and tests."""
2511 self.file_num = num
2513 def Write(self, string):
2514 """Writes a string to a file spliting if it's > 80 characters."""
2515 lines = string.splitlines()
2516 num_lines = len(lines)
2517 for ii in range(0, num_lines):
2518 self.__WriteLine(lines[ii], ii < (num_lines - 1) or string[-1] == '\n')
2520 def __FindSplit(self, string):
2521 """Finds a place to split a string."""
2522 splitter = string.find('=')
2523 if splitter >= 1 and not string[splitter + 1] == '=' and splitter < 80:
2524 return splitter
2525 # parts = string.split('(')
2526 parts = re.split("(?<=[^\"])\((?!\")", string)
2527 fptr = re.compile('\*\w*\)')
2528 if len(parts) > 1:
2529 splitter = len(parts[0])
2530 for ii in range(1, len(parts)):
2531 # Don't split on the dot in "if (.condition)".
2532 if (not parts[ii - 1][-3:] == "if " and
2533 # Don't split "(.)" or "(.*fptr)".
2534 (len(parts[ii]) > 0 and
2535 not parts[ii][0] == ")" and not fptr.match(parts[ii]))
2536 and splitter < 80):
2537 return splitter
2538 splitter += len(parts[ii]) + 1
2539 done = False
2540 end = len(string)
2541 last_splitter = -1
2542 while not done:
2543 splitter = string[0:end].rfind(',')
2544 if splitter < 0 or (splitter > 0 and string[splitter - 1] == '"'):
2545 return last_splitter
2546 elif splitter >= 80:
2547 end = splitter
2548 else:
2549 return splitter
2551 def __WriteLine(self, line, ends_with_eol):
2552 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2553 if len(line) >= 80:
2554 i = self.__FindSplit(line)
2555 if i > 0:
2556 line1 = line[0:i + 1]
2557 if line1[-1] == ' ':
2558 line1 = line1[:-1]
2559 lineend = ''
2560 if line1[0] == '#':
2561 lineend = ' \\'
2562 nolint = ''
2563 if len(line1) > 80:
2564 nolint = ' // NOLINT'
2565 self.__AddLine(line1 + nolint + lineend + '\n')
2566 match = re.match("( +)", line1)
2567 indent = ""
2568 if match:
2569 indent = match.group(1)
2570 splitter = line[i]
2571 if not splitter == ',':
2572 indent = " " + indent
2573 self.__WriteLine(indent + line[i + 1:].lstrip(), True)
2574 return
2575 nolint = ''
2576 if len(line) > 80:
2577 nolint = ' // NOLINT'
2578 self.__AddLine(line + nolint)
2579 if ends_with_eol:
2580 self.__AddLine('\n')
2582 def __AddLine(self, line):
2583 self.content.append(line)
2585 def Close(self):
2586 """Close the file."""
2587 content = "".join(self.content)
2588 write_file = True
2589 if os.path.exists(self.filename):
2590 old_file = open(self.filename, "rb");
2591 old_content = old_file.read()
2592 old_file.close();
2593 if content == old_content:
2594 write_file = False
2595 if write_file:
2596 file = open(self.filename, "wb")
2597 file.write(content)
2598 file.close()
2601 class CHeaderWriter(CWriter):
2602 """Writes a C Header file."""
2604 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2606 def __init__(self, filename, file_comment = None):
2607 CWriter.__init__(self, filename)
2609 base = os.path.abspath(filename)
2610 while os.path.basename(base) != 'src':
2611 new_base = os.path.dirname(base)
2612 assert new_base != base # Prevent infinite loop.
2613 base = new_base
2615 hpath = os.path.relpath(filename, base)
2616 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2618 self.Write(_LICENSE)
2619 self.Write(_DO_NOT_EDIT_WARNING)
2620 if not file_comment == None:
2621 self.Write(file_comment)
2622 self.Write("#ifndef %s\n" % self.guard)
2623 self.Write("#define %s\n\n" % self.guard)
2625 def Close(self):
2626 self.Write("#endif // %s\n\n" % self.guard)
2627 CWriter.Close(self)
2629 class TypeHandler(object):
2630 """This class emits code for a particular type of function."""
2632 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2634 def __init__(self):
2635 pass
2637 def InitFunction(self, func):
2638 """Add or adjust anything type specific for this function."""
2639 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2640 func.AddCmdArg(DataSizeArgument('data_size'))
2642 def AddImmediateFunction(self, generator, func):
2643 """Adds an immediate version of a function."""
2644 # Generate an immediate command if there is only 1 pointer arg.
2645 immediate = func.GetInfo('immediate') # can be True, False or None
2646 if immediate == True or immediate == None:
2647 if func.num_pointer_args == 1 or immediate:
2648 generator.AddFunction(ImmediateFunction(func))
2650 def AddBucketFunction(self, generator, func):
2651 """Adds a bucket version of a function."""
2652 # Generate an immediate command if there is only 1 pointer arg.
2653 bucket = func.GetInfo('bucket') # can be True, False or None
2654 if bucket:
2655 generator.AddFunction(BucketFunction(func))
2657 def WriteStruct(self, func, file):
2658 """Writes a structure that matches the arguments to a function."""
2659 comment = func.GetInfo('cmd_comment')
2660 if not comment == None:
2661 file.Write(comment)
2662 file.Write("struct %s {\n" % func.name)
2663 file.Write(" typedef %s ValueType;\n" % func.name)
2664 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2665 func.WriteCmdArgFlag(file)
2666 file.Write("\n")
2667 result = func.GetInfo('result')
2668 if not result == None:
2669 if len(result) == 1:
2670 file.Write(" typedef %s Result;\n\n" % result[0])
2671 else:
2672 file.Write(" struct Result {\n")
2673 for line in result:
2674 file.Write(" %s;\n" % line)
2675 file.Write(" };\n\n")
2677 func.WriteCmdComputeSize(file)
2678 func.WriteCmdSetHeader(file)
2679 func.WriteCmdInit(file)
2680 func.WriteCmdSet(file)
2682 file.Write(" gpu::CommandHeader header;\n")
2683 args = func.GetCmdArgs()
2684 for arg in args:
2685 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2686 file.Write("};\n")
2687 file.Write("\n")
2689 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2690 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2691 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2692 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2693 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2694 offset = _SIZE_OF_COMMAND_HEADER
2695 for arg in args:
2696 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2697 (func.name, arg.name, offset))
2698 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2699 (func.name, arg.name, offset))
2700 offset += _SIZE_OF_UINT32
2701 if not result == None and len(result) > 1:
2702 offset = 0;
2703 for line in result:
2704 parts = line.split()
2705 name = parts[-1]
2706 check = """
2707 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2708 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2710 file.Write((check.strip() + "\n") % {
2711 'cmd_name': func.name,
2712 'field_name': name,
2713 'offset': offset,
2715 offset += _SIZE_OF_UINT32
2716 file.Write("\n")
2718 def WriteHandlerImplementation(self, func, file):
2719 """Writes the handler implementation for this command."""
2720 file.Write(" %s(%s);\n" %
2721 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2723 def WriteCmdSizeTest(self, func, file):
2724 """Writes the size test for a command."""
2725 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2727 def WriteFormatTest(self, func, file):
2728 """Writes a format test for a command."""
2729 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2730 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2731 (func.name, func.name))
2732 file.Write(" void* next_cmd = cmd.Set(\n")
2733 file.Write(" &cmd")
2734 args = func.GetCmdArgs()
2735 for value, arg in enumerate(args):
2736 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2737 file.Write(");\n")
2738 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2739 func.name)
2740 file.Write(" cmd.header.command);\n")
2741 func.type_handler.WriteCmdSizeTest(func, file)
2742 for value, arg in enumerate(args):
2743 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2744 (arg.type, value + 11, arg.name))
2745 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2746 file.Write(" next_cmd, sizeof(cmd));\n")
2747 file.Write("}\n")
2748 file.Write("\n")
2750 def WriteImmediateFormatTest(self, func, file):
2751 """Writes a format test for an immediate version of a command."""
2752 pass
2754 def WriteBucketFormatTest(self, func, file):
2755 """Writes a format test for a bucket version of a command."""
2756 pass
2758 def WriteGetDataSizeCode(self, func, file):
2759 """Writes the code to set data_size used in validation"""
2760 pass
2762 def WriteImmediateCmdSizeTest(self, func, file):
2763 """Writes a size test for an immediate version of a command."""
2764 file.Write(" // TODO(gman): Compute correct size.\n")
2765 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2767 def WriteImmediateHandlerImplementation (self, func, file):
2768 """Writes the handler impl for the immediate version of a command."""
2769 file.Write(" %s(%s);\n" %
2770 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2772 def WriteBucketHandlerImplementation (self, func, file):
2773 """Writes the handler impl for the bucket version of a command."""
2774 file.Write(" %s(%s);\n" %
2775 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2777 def WriteServiceImplementation(self, func, file):
2778 """Writes the service implementation for a command."""
2779 file.Write(
2780 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2781 file.Write(
2782 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2783 func.name)
2784 self.WriteHandlerDeferReadWrite(func, file);
2785 if len(func.GetOriginalArgs()) > 0:
2786 last_arg = func.GetLastOriginalArg()
2787 all_but_last_arg = func.GetOriginalArgs()[:-1]
2788 for arg in all_but_last_arg:
2789 arg.WriteGetCode(file)
2790 self.WriteGetDataSizeCode(func, file)
2791 last_arg.WriteGetCode(file)
2792 func.WriteHandlerValidation(file)
2793 func.WriteHandlerImplementation(file)
2794 file.Write(" return error::kNoError;\n")
2795 file.Write("}\n")
2796 file.Write("\n")
2798 def WriteImmediateServiceImplementation(self, func, file):
2799 """Writes the service implementation for an immediate version of command."""
2800 file.Write(
2801 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2802 file.Write(
2803 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2804 func.name)
2805 self.WriteHandlerDeferReadWrite(func, file);
2806 last_arg = func.GetLastOriginalArg()
2807 all_but_last_arg = func.GetOriginalArgs()[:-1]
2808 for arg in all_but_last_arg:
2809 arg.WriteGetCode(file)
2810 self.WriteGetDataSizeCode(func, file)
2811 last_arg.WriteGetCode(file)
2812 func.WriteHandlerValidation(file)
2813 func.WriteHandlerImplementation(file)
2814 file.Write(" return error::kNoError;\n")
2815 file.Write("}\n")
2816 file.Write("\n")
2818 def WriteBucketServiceImplementation(self, func, file):
2819 """Writes the service implementation for a bucket version of command."""
2820 file.Write(
2821 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2822 file.Write(
2823 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2824 func.name)
2825 self.WriteHandlerDeferReadWrite(func, file);
2826 last_arg = func.GetLastOriginalArg()
2827 all_but_last_arg = func.GetOriginalArgs()[:-1]
2828 for arg in all_but_last_arg:
2829 arg.WriteGetCode(file)
2830 self.WriteGetDataSizeCode(func, file)
2831 last_arg.WriteGetCode(file)
2832 func.WriteHandlerValidation(file)
2833 func.WriteHandlerImplementation(file)
2834 file.Write(" return error::kNoError;\n")
2835 file.Write("}\n")
2836 file.Write("\n")
2838 def WriteHandlerDeferReadWrite(self, func, file):
2839 """Writes the code to handle deferring reads or writes."""
2840 defer_reads = func.GetInfo('defer_reads')
2841 defer_draws = func.GetInfo('defer_draws')
2842 conditions = []
2843 if defer_draws:
2844 conditions.append('ShouldDeferDraws()');
2845 if defer_reads:
2846 conditions.append('ShouldDeferReads()');
2847 if not conditions:
2848 return
2849 file.Write(" if (%s)\n" % ' || '.join(conditions))
2850 file.Write(" return error::kDeferCommandUntilLater;\n")
2852 def WriteValidUnitTest(self, func, file, test, extra = {}):
2853 """Writes a valid unit test."""
2854 if func.GetInfo('expectation') == False:
2855 test = self._remove_expected_call_re.sub('', test)
2856 name = func.name
2857 arg_strings = []
2858 for count, arg in enumerate(func.GetOriginalArgs()):
2859 arg_strings.append(arg.GetValidArg(func, count, 0))
2860 gl_arg_strings = []
2861 for count, arg in enumerate(func.GetOriginalArgs()):
2862 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
2863 gl_func_name = func.GetGLTestFunctionName()
2864 vars = {
2865 'test_name': 'GLES2DecoderTest%d' % file.file_num,
2866 'name':name,
2867 'gl_func_name': gl_func_name,
2868 'args': ", ".join(arg_strings),
2869 'gl_args': ", ".join(gl_arg_strings),
2871 vars.update(extra)
2872 old_test = ""
2873 while (old_test != test):
2874 old_test = test
2875 test = test % vars
2876 file.Write(test % vars)
2878 def WriteInvalidUnitTest(self, func, file, test, extra = {}):
2879 """Writes a invalid unit test."""
2880 for arg_index, arg in enumerate(func.GetOriginalArgs()):
2881 num_invalid_values = arg.GetNumInvalidValues(func)
2882 for value_index in range(0, num_invalid_values):
2883 arg_strings = []
2884 parse_result = "kNoError"
2885 gl_error = None
2886 for count, arg in enumerate(func.GetOriginalArgs()):
2887 if count == arg_index:
2888 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
2889 count, value_index)
2890 else:
2891 arg_string = arg.GetValidArg(func, count, 0)
2892 arg_strings.append(arg_string)
2893 gl_arg_strings = []
2894 for arg in func.GetOriginalArgs():
2895 gl_arg_strings.append("_")
2896 gl_func_name = func.GetGLTestFunctionName()
2897 gl_error_test = ''
2898 if not gl_error == None:
2899 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2901 vars = {
2902 'test_name': 'GLES2DecoderTest%d' % file.file_num ,
2903 'name': func.name,
2904 'arg_index': arg_index,
2905 'value_index': value_index,
2906 'gl_func_name': gl_func_name,
2907 'args': ", ".join(arg_strings),
2908 'all_but_last_args': ", ".join(arg_strings[:-1]),
2909 'gl_args': ", ".join(gl_arg_strings),
2910 'parse_result': parse_result,
2911 'gl_error_test': gl_error_test,
2913 vars.update(extra)
2914 file.Write(test % vars)
2916 def WriteServiceUnitTest(self, func, file):
2917 """Writes the service unit test for a command."""
2918 valid_test = """
2919 TEST_F(%(test_name)s, %(name)sValidArgs) {
2920 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2921 SpecializedSetup<cmds::%(name)s, 0>(true);
2922 cmds::%(name)s cmd;
2923 cmd.Init(%(args)s);
2924 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2925 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2928 self.WriteValidUnitTest(func, file, valid_test)
2930 invalid_test = """
2931 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2932 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2933 SpecializedSetup<cmds::%(name)s, 0>(false);
2934 cmds::%(name)s cmd;
2935 cmd.Init(%(args)s);
2936 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2939 self.WriteInvalidUnitTest(func, file, invalid_test)
2941 def WriteImmediateServiceUnitTest(self, func, file):
2942 """Writes the service unit test for an immediate command."""
2943 file.Write("// TODO(gman): %s\n" % func.name)
2945 def WriteImmediateValidationCode(self, func, file):
2946 """Writes the validation code for an immediate version of a command."""
2947 pass
2949 def WriteBucketServiceUnitTest(self, func, file):
2950 """Writes the service unit test for a bucket command."""
2951 file.Write("// TODO(gman): %s\n" % func.name)
2953 def WriteBucketValidationCode(self, func, file):
2954 """Writes the validation code for a bucket version of a command."""
2955 file.Write("// TODO(gman): %s\n" % func.name)
2957 def WriteGLES2ImplementationDeclaration(self, func, file):
2958 """Writes the GLES2 Implemention declaration."""
2959 impl_decl = func.GetInfo('impl_decl')
2960 if impl_decl == None or impl_decl == True:
2961 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
2962 (func.return_type, func.original_name,
2963 func.MakeTypedOriginalArgString("")))
2964 file.Write("\n")
2966 def WriteGLES2CLibImplementation(self, func, file):
2967 file.Write("%s GLES2%s(%s) {\n" %
2968 (func.return_type, func.name,
2969 func.MakeTypedOriginalArgString("")))
2970 result_string = "return "
2971 if func.return_type == "void":
2972 result_string = ""
2973 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
2974 (result_string, func.original_name,
2975 func.MakeOriginalArgString("")))
2976 file.Write("}\n")
2978 def WriteGLES2Header(self, func, file):
2979 """Writes a re-write macro for GLES"""
2980 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
2982 def WriteClientGLCallLog(self, func, file):
2983 """Writes a logging macro for the client side code."""
2984 comma = ""
2985 if len(func.GetOriginalArgs()):
2986 comma = " << "
2987 file.Write(
2988 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
2989 (func.original_name, comma, func.MakeLogArgString()))
2991 def WriteClientGLReturnLog(self, func, file):
2992 """Writes the return value logging code."""
2993 if func.return_type != "void":
2994 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
2996 def WriteGLES2ImplementationHeader(self, func, file):
2997 """Writes the GLES2 Implemention."""
2998 self.WriteGLES2ImplementationDeclaration(func, file)
3000 def WriteGLES2TraceImplementationHeader(self, func, file):
3001 """Writes the GLES2 Trace Implemention header."""
3002 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3003 (func.return_type, func.original_name,
3004 func.MakeTypedOriginalArgString("")))
3006 def WriteGLES2TraceImplementation(self, func, file):
3007 """Writes the GLES2 Trace Implemention."""
3008 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3009 (func.return_type, func.original_name,
3010 func.MakeTypedOriginalArgString("")))
3011 result_string = "return "
3012 if func.return_type == "void":
3013 result_string = ""
3014 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3015 func.name)
3016 file.Write(" %sgl_->%s(%s);\n" %
3017 (result_string, func.name, func.MakeOriginalArgString("")))
3018 file.Write("}\n")
3019 file.Write("\n")
3021 def WriteGLES2Implementation(self, func, file):
3022 """Writes the GLES2 Implemention."""
3023 impl_func = func.GetInfo('impl_func')
3024 impl_decl = func.GetInfo('impl_decl')
3025 gen_cmd = func.GetInfo('gen_cmd')
3026 if (func.can_auto_generate and
3027 (impl_func == None or impl_func == True) and
3028 (impl_decl == None or impl_decl == True) and
3029 (gen_cmd == None or gen_cmd == True)):
3030 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3031 (func.return_type, func.original_name,
3032 func.MakeTypedOriginalArgString("")))
3033 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3034 self.WriteClientGLCallLog(func, file)
3035 func.WriteDestinationInitalizationValidation(file)
3036 for arg in func.GetOriginalArgs():
3037 arg.WriteClientSideValidationCode(file, func)
3038 file.Write(" helper_->%s(%s);\n" %
3039 (func.name, func.MakeOriginalArgString("")))
3040 file.Write(" CheckGLError();\n")
3041 self.WriteClientGLReturnLog(func, file)
3042 file.Write("}\n")
3043 file.Write("\n")
3045 def WriteGLES2InterfaceHeader(self, func, file):
3046 """Writes the GLES2 Interface."""
3047 file.Write("virtual %s %s(%s) = 0;\n" %
3048 (func.return_type, func.original_name,
3049 func.MakeTypedOriginalArgString("")))
3051 def WriteGLES2InterfaceStub(self, func, file):
3052 """Writes the GLES2 Interface stub declaration."""
3053 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3054 (func.return_type, func.original_name,
3055 func.MakeTypedOriginalArgString("")))
3057 def WriteGLES2InterfaceStubImpl(self, func, file):
3058 """Writes the GLES2 Interface stub declaration."""
3059 args = func.GetOriginalArgs()
3060 arg_string = ", ".join(
3061 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3062 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3063 (func.return_type, func.original_name, arg_string))
3064 if func.return_type != "void":
3065 file.Write(" return 0;\n")
3066 file.Write("}\n")
3068 def WriteGLES2ImplementationUnitTest(self, func, file):
3069 """Writes the GLES2 Implemention unit test."""
3070 client_test = func.GetInfo('client_test')
3071 if (func.can_auto_generate and
3072 (client_test == None or client_test == True)):
3073 code = """
3074 TEST_F(GLES2ImplementationTest, %(name)s) {
3075 struct Cmds {
3076 cmds::%(name)s cmd;
3078 Cmds expected;
3079 expected.cmd.Init(%(cmd_args)s);
3081 gl_->%(name)s(%(args)s);
3082 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3085 cmd_arg_strings = []
3086 for count, arg in enumerate(func.GetCmdArgs()):
3087 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3088 count += 1
3089 gl_arg_strings = []
3090 for count, arg in enumerate(func.GetOriginalArgs()):
3091 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3092 file.Write(code % {
3093 'name': func.name,
3094 'args': ", ".join(gl_arg_strings),
3095 'cmd_args': ", ".join(cmd_arg_strings),
3097 else:
3098 if client_test != False:
3099 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3101 def WriteDestinationInitalizationValidation(self, func, file):
3102 """Writes the client side destintion initialization validation."""
3103 for arg in func.GetOriginalArgs():
3104 arg.WriteDestinationInitalizationValidation(file, func)
3106 def WriteTraceEvent(self, func, file):
3107 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3108 func.original_name)
3110 def WriteImmediateCmdComputeSize(self, func, file):
3111 """Writes the size computation code for the immediate version of a cmd."""
3112 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3113 file.Write(" return static_cast<uint32>(\n")
3114 file.Write(" sizeof(ValueType) + // NOLINT\n")
3115 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3116 file.Write(" }\n")
3117 file.Write("\n")
3119 def WriteImmediateCmdSetHeader(self, func, file):
3120 """Writes the SetHeader function for the immediate version of a cmd."""
3121 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3122 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3123 file.Write(" }\n")
3124 file.Write("\n")
3126 def WriteImmediateCmdInit(self, func, file):
3127 """Writes the Init function for the immediate version of a command."""
3128 raise NotImplementedError(func.name)
3130 def WriteImmediateCmdSet(self, func, file):
3131 """Writes the Set function for the immediate version of a command."""
3132 raise NotImplementedError(func.name)
3134 def WriteCmdHelper(self, func, file):
3135 """Writes the cmd helper definition for a cmd."""
3136 code = """ void %(name)s(%(typed_args)s) {
3137 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3138 if (c) {
3139 c->Init(%(args)s);
3144 file.Write(code % {
3145 "name": func.name,
3146 "typed_args": func.MakeTypedCmdArgString(""),
3147 "args": func.MakeCmdArgString(""),
3150 def WriteImmediateCmdHelper(self, func, file):
3151 """Writes the cmd helper definition for the immediate version of a cmd."""
3152 code = """ void %(name)s(%(typed_args)s) {
3153 const uint32 s = 0; // TODO(gman): compute correct size
3154 gles2::cmds::%(name)s* c =
3155 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3156 if (c) {
3157 c->Init(%(args)s);
3162 file.Write(code % {
3163 "name": func.name,
3164 "typed_args": func.MakeTypedCmdArgString(""),
3165 "args": func.MakeCmdArgString(""),
3169 class StateSetHandler(TypeHandler):
3170 """Handler for commands that simply set state."""
3172 def __init__(self):
3173 TypeHandler.__init__(self)
3175 def WriteHandlerImplementation(self, func, file):
3176 """Overrriden from TypeHandler."""
3177 state_name = func.GetInfo('state')
3178 state = _STATES[state_name]
3179 states = state['states']
3180 args = func.GetOriginalArgs()
3181 code = []
3182 for ndx,item in enumerate(states):
3183 if 'range_checks' in item:
3184 for range_check in item['range_checks']:
3185 code.append("%s %s" % (args[ndx].name, range_check['check']))
3186 if len(code):
3187 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3188 file.Write(
3189 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3190 ' "%s", "%s out of range");\n' %
3191 (func.name, args[ndx].name))
3192 file.Write(" return error::kNoError;\n")
3193 file.Write(" }\n")
3194 code = []
3195 for ndx,item in enumerate(states):
3196 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3197 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3198 for ndx,item in enumerate(states):
3199 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3200 if 'state_flag' in state:
3201 file.Write(" %s = true;\n" % state['state_flag'])
3202 if not func.GetInfo("no_gl"):
3203 file.Write(" %s(%s);\n" %
3204 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3205 file.Write(" }\n")
3207 def WriteServiceUnitTest(self, func, file):
3208 """Overrriden from TypeHandler."""
3209 TypeHandler.WriteServiceUnitTest(self, func, file)
3210 state_name = func.GetInfo('state')
3211 state = _STATES[state_name]
3212 states = state['states']
3213 for ndx,item in enumerate(states):
3214 if 'range_checks' in item:
3215 for check_ndx, range_check in enumerate(item['range_checks']):
3216 valid_test = """
3217 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3218 SpecializedSetup<cmds::%(name)s, 0>(false);
3219 cmds::%(name)s cmd;
3220 cmd.Init(%(args)s);
3221 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3222 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3225 name = func.name
3226 arg_strings = []
3227 for count, arg in enumerate(func.GetOriginalArgs()):
3228 arg_strings.append(arg.GetValidArg(func, count, 0))
3229 arg_strings[ndx] = range_check['test_value']
3230 vars = {
3231 'test_name': 'GLES2DecoderTest%d' % file.file_num,
3232 'name': name,
3233 'ndx': ndx,
3234 'check_ndx': check_ndx,
3235 'args': ", ".join(arg_strings),
3237 file.Write(valid_test % vars)
3240 class StateSetRGBAlphaHandler(TypeHandler):
3241 """Handler for commands that simply set state that have rgb/alpha."""
3243 def __init__(self):
3244 TypeHandler.__init__(self)
3246 def WriteHandlerImplementation(self, func, file):
3247 """Overrriden from TypeHandler."""
3248 state_name = func.GetInfo('state')
3249 state = _STATES[state_name]
3250 states = state['states']
3251 args = func.GetOriginalArgs()
3252 num_args = len(args)
3253 code = []
3254 for ndx,item in enumerate(states):
3255 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3256 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3257 for ndx, item in enumerate(states):
3258 file.Write(" state_.%s = %s;\n" %
3259 (item['name'], args[ndx % num_args].name))
3260 if 'state_flag' in state:
3261 file.Write(" %s = true;\n" % state['state_flag'])
3262 if not func.GetInfo("no_gl"):
3263 file.Write(" %s(%s);\n" %
3264 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3265 file.Write(" }\n")
3268 class StateSetFrontBackSeparateHandler(TypeHandler):
3269 """Handler for commands that simply set state that have front/back."""
3271 def __init__(self):
3272 TypeHandler.__init__(self)
3274 def WriteHandlerImplementation(self, func, file):
3275 """Overrriden from TypeHandler."""
3276 state_name = func.GetInfo('state')
3277 state = _STATES[state_name]
3278 states = state['states']
3279 args = func.GetOriginalArgs()
3280 face = args[0].name
3281 num_args = len(args)
3282 file.Write(" bool changed = false;\n")
3283 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3284 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3285 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3286 code = []
3287 for ndx, item in enumerate(group):
3288 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3289 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3290 file.Write(" }\n")
3291 file.Write(" if (changed) {\n")
3292 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3293 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3294 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3295 for ndx, item in enumerate(group):
3296 file.Write(" state_.%s = %s;\n" %
3297 (item['name'], args[ndx + 1].name))
3298 file.Write(" }\n")
3299 if 'state_flag' in state:
3300 file.Write(" %s = true;\n" % state['state_flag'])
3301 if not func.GetInfo("no_gl"):
3302 file.Write(" %s(%s);\n" %
3303 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3304 file.Write(" }\n")
3307 class StateSetFrontBackHandler(TypeHandler):
3308 """Handler for commands that simply set state that set both front/back."""
3310 def __init__(self):
3311 TypeHandler.__init__(self)
3313 def WriteHandlerImplementation(self, func, file):
3314 """Overrriden from TypeHandler."""
3315 state_name = func.GetInfo('state')
3316 state = _STATES[state_name]
3317 states = state['states']
3318 args = func.GetOriginalArgs()
3319 num_args = len(args)
3320 code = []
3321 for group_ndx, group in enumerate(Grouper(num_args, states)):
3322 for ndx, item in enumerate(group):
3323 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3324 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3325 for group_ndx, group in enumerate(Grouper(num_args, states)):
3326 for ndx, item in enumerate(group):
3327 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3328 if 'state_flag' in state:
3329 file.Write(" %s = true;\n" % state['state_flag'])
3330 if not func.GetInfo("no_gl"):
3331 file.Write(" %s(%s);\n" %
3332 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3333 file.Write(" }\n")
3336 class StateSetNamedParameter(TypeHandler):
3337 """Handler for commands that set a state chosen with an enum parameter."""
3339 def __init__(self):
3340 TypeHandler.__init__(self)
3342 def WriteHandlerImplementation(self, func, file):
3343 """Overridden from TypeHandler."""
3344 state_name = func.GetInfo('state')
3345 state = _STATES[state_name]
3346 states = state['states']
3347 args = func.GetOriginalArgs()
3348 num_args = len(args)
3349 assert num_args == 2
3350 file.Write(" switch (%s) {\n" % args[0].name)
3351 for state in states:
3352 file.Write(" case %s:\n" % state['enum'])
3353 file.Write(" if (state_.%s != %s) {\n" %
3354 (state['name'], args[1].name))
3355 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3356 if not func.GetInfo("no_gl"):
3357 file.Write(" %s(%s);\n" %
3358 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3359 file.Write(" }\n")
3360 file.Write(" break;\n")
3361 file.Write(" default:\n")
3362 file.Write(" NOTREACHED();\n")
3363 file.Write(" }\n")
3366 class CustomHandler(TypeHandler):
3367 """Handler for commands that are auto-generated but require minor tweaks."""
3369 def __init__(self):
3370 TypeHandler.__init__(self)
3372 def WriteServiceImplementation(self, func, file):
3373 """Overrriden from TypeHandler."""
3374 pass
3376 def WriteImmediateServiceImplementation(self, func, file):
3377 """Overrriden from TypeHandler."""
3378 pass
3380 def WriteBucketServiceImplementation(self, func, file):
3381 """Overrriden from TypeHandler."""
3382 pass
3384 def WriteServiceUnitTest(self, func, file):
3385 """Overrriden from TypeHandler."""
3386 file.Write("// TODO(gman): %s\n\n" % func.name)
3388 def WriteImmediateServiceUnitTest(self, func, file):
3389 """Overrriden from TypeHandler."""
3390 file.Write("// TODO(gman): %s\n\n" % func.name)
3392 def WriteImmediateCmdGetTotalSize(self, func, file):
3393 """Overrriden from TypeHandler."""
3394 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3396 def WriteImmediateCmdInit(self, func, file):
3397 """Overrriden from TypeHandler."""
3398 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3399 self.WriteImmediateCmdGetTotalSize(func, file)
3400 file.Write(" SetHeader(total_size);\n")
3401 args = func.GetCmdArgs()
3402 for arg in args:
3403 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3404 file.Write(" }\n")
3405 file.Write("\n")
3407 def WriteImmediateCmdSet(self, func, file):
3408 """Overrriden from TypeHandler."""
3409 copy_args = func.MakeCmdArgString("_", False)
3410 file.Write(" void* Set(void* cmd%s) {\n" %
3411 func.MakeTypedCmdArgString("_", True))
3412 self.WriteImmediateCmdGetTotalSize(func, file)
3413 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3414 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3415 "cmd, total_size);\n")
3416 file.Write(" }\n")
3417 file.Write("\n")
3420 class TodoHandler(CustomHandler):
3421 """Handle for commands that are not yet implemented."""
3423 def AddImmediateFunction(self, generator, func):
3424 """Overrriden from TypeHandler."""
3425 pass
3427 def WriteImmediateFormatTest(self, func, file):
3428 """Overrriden from TypeHandler."""
3429 pass
3431 def WriteGLES2ImplementationUnitTest(self, func, file):
3432 """Overrriden from TypeHandler."""
3433 pass
3435 def WriteGLES2Implementation(self, func, file):
3436 """Overrriden from TypeHandler."""
3437 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3438 (func.return_type, func.original_name,
3439 func.MakeTypedOriginalArgString("")))
3440 file.Write(" // TODO: for now this is a no-op\n")
3441 file.Write(
3442 " SetGLError("
3443 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3444 func.name)
3445 if func.return_type != "void":
3446 file.Write(" return 0;\n")
3447 file.Write("}\n")
3448 file.Write("\n")
3450 def WriteServiceImplementation(self, func, file):
3451 """Overrriden from TypeHandler."""
3452 file.Write(
3453 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3454 file.Write(
3455 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3456 func.name)
3457 file.Write(" // TODO: for now this is a no-op\n")
3458 file.Write(
3459 " LOCAL_SET_GL_ERROR("
3460 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3461 func.name)
3462 file.Write(" return error::kNoError;\n")
3463 file.Write("}\n")
3464 file.Write("\n")
3467 class HandWrittenHandler(CustomHandler):
3468 """Handler for comands where everything must be written by hand."""
3470 def InitFunction(self, func):
3471 """Add or adjust anything type specific for this function."""
3472 CustomHandler.InitFunction(self, func)
3473 func.can_auto_generate = False
3475 def WriteStruct(self, func, file):
3476 """Overrriden from TypeHandler."""
3477 pass
3479 def WriteDocs(self, func, file):
3480 """Overrriden from TypeHandler."""
3481 pass
3483 def WriteServiceUnitTest(self, func, file):
3484 """Overrriden from TypeHandler."""
3485 file.Write("// TODO(gman): %s\n\n" % func.name)
3487 def WriteImmediateServiceUnitTest(self, func, file):
3488 """Overrriden from TypeHandler."""
3489 file.Write("// TODO(gman): %s\n\n" % func.name)
3491 def WriteBucketServiceUnitTest(self, func, file):
3492 """Overrriden from TypeHandler."""
3493 file.Write("// TODO(gman): %s\n\n" % func.name)
3495 def WriteServiceImplementation(self, func, file):
3496 """Overrriden from TypeHandler."""
3497 pass
3499 def WriteImmediateServiceImplementation(self, func, file):
3500 """Overrriden from TypeHandler."""
3501 pass
3503 def WriteBucketServiceImplementation(self, func, file):
3504 """Overrriden from TypeHandler."""
3505 pass
3507 def WriteImmediateCmdHelper(self, func, file):
3508 """Overrriden from TypeHandler."""
3509 pass
3511 def WriteBucketCmdHelper(self, func, file):
3512 """Overrriden from TypeHandler."""
3513 pass
3515 def WriteCmdHelper(self, func, file):
3516 """Overrriden from TypeHandler."""
3517 pass
3519 def WriteFormatTest(self, func, file):
3520 """Overrriden from TypeHandler."""
3521 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3523 def WriteImmediateFormatTest(self, func, file):
3524 """Overrriden from TypeHandler."""
3525 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3527 def WriteBucketFormatTest(self, func, file):
3528 """Overrriden from TypeHandler."""
3529 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3533 class ManualHandler(CustomHandler):
3534 """Handler for commands who's handlers must be written by hand."""
3536 def __init__(self):
3537 CustomHandler.__init__(self)
3539 def InitFunction(self, func):
3540 """Overrriden from TypeHandler."""
3541 if (func.name == 'CompressedTexImage2DBucket'):
3542 func.cmd_args = func.cmd_args[:-1]
3543 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3544 else:
3545 CustomHandler.InitFunction(self, func)
3547 def WriteServiceImplementation(self, func, file):
3548 """Overrriden from TypeHandler."""
3549 pass
3551 def WriteBucketServiceImplementation(self, func, file):
3552 """Overrriden from TypeHandler."""
3553 pass
3555 def WriteServiceUnitTest(self, func, file):
3556 """Overrriden from TypeHandler."""
3557 file.Write("// TODO(gman): %s\n\n" % func.name)
3559 def WriteImmediateServiceUnitTest(self, func, file):
3560 """Overrriden from TypeHandler."""
3561 file.Write("// TODO(gman): %s\n\n" % func.name)
3563 def WriteImmediateServiceImplementation(self, func, file):
3564 """Overrriden from TypeHandler."""
3565 pass
3567 def WriteImmediateFormatTest(self, func, file):
3568 """Overrriden from TypeHandler."""
3569 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3571 def WriteGLES2Implementation(self, func, file):
3572 """Overrriden from TypeHandler."""
3573 if func.GetInfo('impl_func'):
3574 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3576 def WriteGLES2ImplementationHeader(self, func, file):
3577 """Overrriden from TypeHandler."""
3578 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3579 (func.return_type, func.original_name,
3580 func.MakeTypedOriginalArgString("")))
3581 file.Write("\n")
3583 def WriteImmediateCmdGetTotalSize(self, func, file):
3584 """Overrriden from TypeHandler."""
3585 # TODO(gman): Move this data to _FUNCTION_INFO?
3586 if func.name == 'ShaderSourceImmediate':
3587 file.Write(" uint32 total_size = ComputeSize(_data_size);\n")
3588 else:
3589 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3592 class DataHandler(TypeHandler):
3593 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3594 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3595 def __init__(self):
3596 TypeHandler.__init__(self)
3598 def InitFunction(self, func):
3599 """Overrriden from TypeHandler."""
3600 if func.name == 'CompressedTexSubImage2DBucket':
3601 func.cmd_args = func.cmd_args[:-1]
3602 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3604 def WriteGetDataSizeCode(self, func, file):
3605 """Overrriden from TypeHandler."""
3606 # TODO(gman): Move this data to _FUNCTION_INFO?
3607 name = func.name
3608 if name.endswith("Immediate"):
3609 name = name[0:-9]
3610 if name == 'BufferData' or name == 'BufferSubData':
3611 file.Write(" uint32 data_size = size;\n")
3612 elif (name == 'CompressedTexImage2D' or
3613 name == 'CompressedTexSubImage2D'):
3614 file.Write(" uint32 data_size = imageSize;\n")
3615 elif (name == 'CompressedTexSubImage2DBucket'):
3616 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3617 file.Write(" uint32 data_size = bucket->size();\n")
3618 file.Write(" GLsizei imageSize = data_size;\n")
3619 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3620 code = """ uint32 data_size;
3621 if (!GLES2Util::ComputeImageDataSize(
3622 width, height, format, type, unpack_alignment_, &data_size)) {
3623 return error::kOutOfBounds;
3626 file.Write(code)
3627 else:
3628 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3630 def WriteImmediateCmdGetTotalSize(self, func, file):
3631 """Overrriden from TypeHandler."""
3632 # TODO(gman): Move this data to _FUNCTION_INFO?
3633 if func.name == 'BufferDataImmediate':
3634 file.Write(" uint32 total_size = ComputeSize(_size);\n")
3635 elif func.name == 'BufferSubDataImmediate':
3636 file.Write(" uint32 total_size = ComputeSize(_size);\n")
3637 elif func.name == 'CompressedTexImage2DImmediate':
3638 file.Write(" uint32 total_size = ComputeSize(_imageSize);\n")
3639 elif func.name == 'CompressedTexSubImage2DImmediate':
3640 file.Write(" uint32 total_size = ComputeSize(_imageSize);\n")
3641 elif func.name == 'TexImage2DImmediate':
3642 file.Write(
3643 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3644 elif func.name == 'TexSubImage2DImmediate':
3645 file.Write(
3646 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3648 def WriteImmediateCmdSizeTest(self, func, file):
3649 """Overrriden from TypeHandler."""
3650 # TODO(gman): Move this data to _FUNCTION_INFO?
3651 if func.name == 'BufferDataImmediate':
3652 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.size);\n")
3653 elif func.name == 'BufferSubDataImmediate':
3654 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.size);\n")
3655 elif func.name == 'CompressedTexImage2DImmediate':
3656 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.imageSize);\n")
3657 elif func.name == 'CompressedTexSubImage2DImmediate':
3658 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.imageSize);\n")
3659 elif func.name == 'TexImage2DImmediate':
3660 file.Write(
3661 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3662 elif func.name == 'TexSubImage2DImmediate':
3663 file.Write(
3664 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3665 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3667 def WriteImmediateCmdInit(self, func, file):
3668 """Overrriden from TypeHandler."""
3669 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3670 self.WriteImmediateCmdGetTotalSize(func, file)
3671 file.Write(" SetHeader(total_size);\n")
3672 args = func.GetCmdArgs()
3673 for arg in args:
3674 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3675 file.Write(" }\n")
3676 file.Write("\n")
3678 def WriteImmediateCmdSet(self, func, file):
3679 """Overrriden from TypeHandler."""
3680 copy_args = func.MakeCmdArgString("_", False)
3681 file.Write(" void* Set(void* cmd%s) {\n" %
3682 func.MakeTypedCmdArgString("_", True))
3683 self.WriteImmediateCmdGetTotalSize(func, file)
3684 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3685 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3686 "cmd, total_size);\n")
3687 file.Write(" }\n")
3688 file.Write("\n")
3690 def WriteImmediateFormatTest(self, func, file):
3691 """Overrriden from TypeHandler."""
3692 # TODO(gman): Remove this exception.
3693 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3694 return
3696 def WriteServiceUnitTest(self, func, file):
3697 """Overrriden from TypeHandler."""
3698 file.Write("// TODO(gman): %s\n\n" % func.name)
3700 def WriteImmediateServiceUnitTest(self, func, file):
3701 """Overrriden from TypeHandler."""
3702 file.Write("// TODO(gman): %s\n\n" % func.name)
3704 def WriteBucketServiceImplementation(self, func, file):
3705 """Overrriden from TypeHandler."""
3706 if not func.name == 'CompressedTexSubImage2DBucket':
3707 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3710 class BindHandler(TypeHandler):
3711 """Handler for glBind___ type functions."""
3713 def __init__(self):
3714 TypeHandler.__init__(self)
3716 def WriteServiceUnitTest(self, func, file):
3717 """Overrriden from TypeHandler."""
3719 if len(func.GetOriginalArgs()) == 1:
3720 valid_test = """
3721 TEST_F(%(test_name)s, %(name)sValidArgs) {
3722 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3723 SpecializedSetup<cmds::%(name)s, 0>(true);
3724 cmds::%(name)s cmd;
3725 cmd.Init(%(args)s);
3726 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3727 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3730 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3731 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3732 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3733 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3734 SpecializedSetup<cmds::%(name)s, 0>(true);
3735 cmds::%(name)s cmd;
3736 cmd.Init(kNewClientId);
3737 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3738 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3739 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3742 gen_func_names = {
3744 self.WriteValidUnitTest(func, file, valid_test, {
3745 'resource_type': func.GetOriginalArgs()[0].resource_type,
3746 'gl_gen_func_name': func.GetInfo("gen_func"),
3748 else:
3749 valid_test = """
3750 TEST_F(%(test_name)s, %(name)sValidArgs) {
3751 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3752 SpecializedSetup<cmds::%(name)s, 0>(true);
3753 cmds::%(name)s cmd;
3754 cmd.Init(%(args)s);
3755 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3756 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3759 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3760 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3761 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3762 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3763 SpecializedSetup<cmds::%(name)s, 0>(true);
3764 cmds::%(name)s cmd;
3765 cmd.Init(%(first_arg)s, kNewClientId);
3766 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3767 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3768 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3771 gen_func_names = {
3773 self.WriteValidUnitTest(func, file, valid_test, {
3774 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func, 0, 0),
3775 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func, 0, 0),
3776 'resource_type': func.GetOriginalArgs()[1].resource_type,
3777 'gl_gen_func_name': func.GetInfo("gen_func"),
3780 invalid_test = """
3781 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3782 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3783 SpecializedSetup<cmds::%(name)s, 0>(false);
3784 cmds::%(name)s cmd;
3785 cmd.Init(%(args)s);
3786 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3789 self.WriteInvalidUnitTest(func, file, invalid_test)
3791 def WriteGLES2Implementation(self, func, file):
3792 """Writes the GLES2 Implemention."""
3794 impl_func = func.GetInfo('impl_func')
3795 impl_decl = func.GetInfo('impl_decl')
3797 if (func.can_auto_generate and
3798 (impl_func == None or impl_func == True) and
3799 (impl_decl == None or impl_decl == True)):
3801 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3802 (func.return_type, func.original_name,
3803 func.MakeTypedOriginalArgString("")))
3804 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3805 func.WriteDestinationInitalizationValidation(file)
3806 self.WriteClientGLCallLog(func, file)
3807 for arg in func.GetOriginalArgs():
3808 arg.WriteClientSideValidationCode(file, func)
3810 code = """ if (Is%(type)sReservedId(%(id)s)) {
3811 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3812 return;
3814 if (Bind%(type)sHelper(%(arg_string)s)) {
3815 helper_->%(name)s(%(arg_string)s);
3817 CheckGLError();
3821 name_arg = None
3822 if len(func.GetOriginalArgs()) == 1:
3823 # Bind functions that have no target (like BindVertexArrayOES)
3824 name_arg = func.GetOriginalArgs()[0]
3825 else:
3826 # Bind functions that have both a target and a name (like BindTexture)
3827 name_arg = func.GetOriginalArgs()[1]
3829 file.Write(code % {
3830 'name': func.name,
3831 'arg_string': func.MakeOriginalArgString(""),
3832 'id': name_arg.name,
3833 'type': name_arg.resource_type,
3834 'lc_type': name_arg.resource_type.lower(),
3837 def WriteGLES2ImplementationUnitTest(self, func, file):
3838 """Overrriden from TypeHandler."""
3839 client_test = func.GetInfo('client_test')
3840 if client_test == False:
3841 return
3842 code = """
3843 TEST_F(GLES2ImplementationTest, %(name)s) {
3844 struct Cmds {
3845 cmds::%(name)s cmd;
3847 Cmds expected;
3848 expected.cmd.Init(%(cmd_args)s);
3850 gl_->%(name)s(%(args)s);
3851 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3852 ClearCommands();
3853 gl_->%(name)s(%(args)s);
3854 EXPECT_TRUE(NoCommandsWritten());
3857 cmd_arg_strings = []
3858 for count, arg in enumerate(func.GetCmdArgs()):
3859 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
3860 count += 1
3861 gl_arg_strings = []
3862 for count, arg in enumerate(func.GetOriginalArgs()):
3863 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
3864 file.Write(code % {
3865 'name': func.name,
3866 'args': ", ".join(gl_arg_strings),
3867 'cmd_args': ", ".join(cmd_arg_strings),
3871 class GENnHandler(TypeHandler):
3872 """Handler for glGen___ type functions."""
3874 def __init__(self):
3875 TypeHandler.__init__(self)
3877 def InitFunction(self, func):
3878 """Overrriden from TypeHandler."""
3879 pass
3881 def WriteGetDataSizeCode(self, func, file):
3882 """Overrriden from TypeHandler."""
3883 code = """ uint32 data_size;
3884 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3885 return error::kOutOfBounds;
3888 file.Write(code)
3890 def WriteHandlerImplementation (self, func, file):
3891 """Overrriden from TypeHandler."""
3892 file.Write(" if (!%sHelper(n, %s)) {\n"
3893 " return error::kInvalidArguments;\n"
3894 " }\n" %
3895 (func.name, func.GetLastOriginalArg().name))
3897 def WriteImmediateHandlerImplementation(self, func, file):
3898 """Overrriden from TypeHandler."""
3899 file.Write(" if (!%sHelper(n, %s)) {\n"
3900 " return error::kInvalidArguments;\n"
3901 " }\n" %
3902 (func.original_name, func.GetLastOriginalArg().name))
3904 def WriteGLES2Implementation(self, func, file):
3905 """Overrriden from TypeHandler."""
3906 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
3907 for (GLsizei i = 0; i < n; ++i) {
3908 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3910 });""" % func.GetOriginalArgs()[1].name)
3911 args = {
3912 'log_code': log_code,
3913 'return_type': func.return_type,
3914 'name': func.original_name,
3915 'typed_args': func.MakeTypedOriginalArgString(""),
3916 'args': func.MakeOriginalArgString(""),
3917 'resource_types': func.GetInfo('resource_types'),
3918 'count_name': func.GetOriginalArgs()[0].name,
3920 file.Write(
3921 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3922 args)
3923 func.WriteDestinationInitalizationValidation(file)
3924 self.WriteClientGLCallLog(func, file)
3925 for arg in func.GetOriginalArgs():
3926 arg.WriteClientSideValidationCode(file, func)
3927 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3928 GetIdHandler(id_namespaces::k%(resource_types)s)->
3929 MakeIds(this, 0, %(args)s);
3930 %(name)sHelper(%(args)s);
3931 helper_->%(name)sImmediate(%(args)s);
3932 helper_->CommandBufferHelper::Flush();
3933 %(log_code)s
3934 CheckGLError();
3938 file.Write(code % args)
3940 def WriteGLES2ImplementationUnitTest(self, func, file):
3941 """Overrriden from TypeHandler."""
3942 code = """
3943 TEST_F(GLES2ImplementationTest, %(name)s) {
3944 GLuint ids[2] = { 0, };
3945 struct Cmds {
3946 cmds::%(name)sImmediate gen;
3947 GLuint data[2];
3949 Cmds expected;
3950 expected.gen.Init(arraysize(ids), &ids[0]);
3951 expected.data[0] = k%(types)sStartId;
3952 expected.data[1] = k%(types)sStartId + 1;
3953 gl_->%(name)s(arraysize(ids), &ids[0]);
3954 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3955 EXPECT_EQ(k%(types)sStartId, ids[0]);
3956 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3959 file.Write(code % {
3960 'name': func.name,
3961 'types': func.GetInfo('resource_types'),
3964 def WriteServiceUnitTest(self, func, file):
3965 """Overrriden from TypeHandler."""
3966 valid_test = """
3967 TEST_F(%(test_name)s, %(name)sValidArgs) {
3968 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3969 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3970 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3971 SpecializedSetup<cmds::%(name)s, 0>(true);
3972 cmds::%(name)s cmd;
3973 cmd.Init(%(args)s);
3974 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3975 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3976 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3979 self.WriteValidUnitTest(func, file, valid_test, {
3980 'resource_name': func.GetInfo('resource_type'),
3982 invalid_test = """
3983 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
3985 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
3986 SpecializedSetup<cmds::%(name)s, 0>(false);
3987 cmds::%(name)s cmd;
3988 cmd.Init(%(args)s);
3989 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
3992 self.WriteValidUnitTest(func, file, invalid_test, {
3993 'resource_name': func.GetInfo('resource_type').lower(),
3996 def WriteImmediateServiceUnitTest(self, func, file):
3997 """Overrriden from TypeHandler."""
3998 valid_test = """
3999 TEST_F(%(test_name)s, %(name)sValidArgs) {
4000 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4001 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4002 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4003 GLuint temp = kNewClientId;
4004 SpecializedSetup<cmds::%(name)s, 0>(true);
4005 cmd->Init(1, &temp);
4006 EXPECT_EQ(error::kNoError,
4007 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4008 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4009 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4012 self.WriteValidUnitTest(func, file, valid_test, {
4013 'resource_name': func.GetInfo('resource_type'),
4015 invalid_test = """
4016 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4017 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4018 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4019 SpecializedSetup<cmds::%(name)s, 0>(false);
4020 cmd->Init(1, &client_%(resource_name)s_id_);
4021 EXPECT_EQ(error::kInvalidArguments,
4022 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4025 self.WriteValidUnitTest(func, file, invalid_test, {
4026 'resource_name': func.GetInfo('resource_type').lower(),
4029 def WriteImmediateCmdComputeSize(self, func, file):
4030 """Overrriden from TypeHandler."""
4031 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4032 file.Write(
4033 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4034 file.Write(" }\n")
4035 file.Write("\n")
4036 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4037 file.Write(" return static_cast<uint32>(\n")
4038 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4039 file.Write(" }\n")
4040 file.Write("\n")
4042 def WriteImmediateCmdSetHeader(self, func, file):
4043 """Overrriden from TypeHandler."""
4044 file.Write(" void SetHeader(GLsizei n) {\n")
4045 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4046 file.Write(" }\n")
4047 file.Write("\n")
4049 def WriteImmediateCmdInit(self, func, file):
4050 """Overrriden from TypeHandler."""
4051 last_arg = func.GetLastOriginalArg()
4052 file.Write(" void Init(%s, %s _%s) {\n" %
4053 (func.MakeTypedCmdArgString("_"),
4054 last_arg.type, last_arg.name))
4055 file.Write(" SetHeader(_n);\n")
4056 args = func.GetCmdArgs()
4057 for arg in args:
4058 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4059 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4060 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4061 file.Write(" }\n")
4062 file.Write("\n")
4064 def WriteImmediateCmdSet(self, func, file):
4065 """Overrriden from TypeHandler."""
4066 last_arg = func.GetLastOriginalArg()
4067 copy_args = func.MakeCmdArgString("_", False)
4068 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4069 (func.MakeTypedCmdArgString("_", True),
4070 last_arg.type, last_arg.name))
4071 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4072 (copy_args, last_arg.name))
4073 file.Write(" const uint32 size = ComputeSize(_n);\n")
4074 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4075 "cmd, size);\n")
4076 file.Write(" }\n")
4077 file.Write("\n")
4079 def WriteImmediateCmdHelper(self, func, file):
4080 """Overrriden from TypeHandler."""
4081 code = """ void %(name)s(%(typed_args)s) {
4082 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4083 gles2::cmds::%(name)s* c =
4084 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4085 if (c) {
4086 c->Init(%(args)s);
4091 file.Write(code % {
4092 "name": func.name,
4093 "typed_args": func.MakeTypedOriginalArgString(""),
4094 "args": func.MakeOriginalArgString(""),
4097 def WriteImmediateFormatTest(self, func, file):
4098 """Overrriden from TypeHandler."""
4099 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4100 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4101 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4102 (func.name, func.name))
4103 file.Write(" void* next_cmd = cmd.Set(\n")
4104 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4105 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4106 func.name)
4107 file.Write(" cmd.header.command);\n")
4108 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4109 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4110 file.Write(" cmd.header.size * 4u);\n")
4111 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4112 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4113 file.Write(" next_cmd, sizeof(cmd) +\n")
4114 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4115 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4116 file.Write("}\n")
4117 file.Write("\n")
4120 class CreateHandler(TypeHandler):
4121 """Handler for glCreate___ type functions."""
4123 def __init__(self):
4124 TypeHandler.__init__(self)
4126 def InitFunction(self, func):
4127 """Overrriden from TypeHandler."""
4128 func.AddCmdArg(Argument("client_id", 'uint32'))
4130 def WriteServiceUnitTest(self, func, file):
4131 """Overrriden from TypeHandler."""
4132 valid_test = """
4133 TEST_F(%(test_name)s, %(name)sValidArgs) {
4134 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4135 .WillOnce(Return(kNewServiceId));
4136 SpecializedSetup<cmds::%(name)s, 0>(true);
4137 cmds::%(name)s cmd;
4138 cmd.Init(%(args)s%(comma)skNewClientId);
4139 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4140 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4141 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4144 comma = ""
4145 if len(func.GetOriginalArgs()):
4146 comma =", "
4147 self.WriteValidUnitTest(func, file, valid_test, {
4148 'comma': comma,
4149 'resource_type': func.name[6:],
4151 invalid_test = """
4152 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4153 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4154 SpecializedSetup<cmds::%(name)s, 0>(false);
4155 cmds::%(name)s cmd;
4156 cmd.Init(%(args)s%(comma)skNewClientId);
4157 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4160 self.WriteInvalidUnitTest(func, file, invalid_test, {
4161 'comma': comma,
4164 def WriteHandlerImplementation (self, func, file):
4165 """Overrriden from TypeHandler."""
4166 file.Write(" uint32 client_id = c.client_id;\n")
4167 file.Write(" if (!%sHelper(%s)) {\n" %
4168 (func.name, func.MakeCmdArgString("")))
4169 file.Write(" return error::kInvalidArguments;\n")
4170 file.Write(" }\n")
4172 def WriteGLES2Implementation(self, func, file):
4173 """Overrriden from TypeHandler."""
4174 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4175 (func.return_type, func.original_name,
4176 func.MakeTypedOriginalArgString("")))
4177 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4178 func.WriteDestinationInitalizationValidation(file)
4179 self.WriteClientGLCallLog(func, file)
4180 for arg in func.GetOriginalArgs():
4181 arg.WriteClientSideValidationCode(file, func)
4182 file.Write(" GLuint client_id;\n")
4183 file.Write(
4184 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4185 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4186 file.Write(" helper_->%s(%s);\n" %
4187 (func.name, func.MakeCmdArgString("")))
4188 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4189 file.Write(" CheckGLError();\n")
4190 file.Write(" return client_id;\n")
4191 file.Write("}\n")
4192 file.Write("\n")
4195 class DeleteHandler(TypeHandler):
4196 """Handler for glDelete___ single resource type functions."""
4198 def __init__(self):
4199 TypeHandler.__init__(self)
4201 def WriteServiceImplementation(self, func, file):
4202 """Overrriden from TypeHandler."""
4203 pass
4205 def WriteGLES2Implementation(self, func, file):
4206 """Overrriden from TypeHandler."""
4207 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4208 (func.return_type, func.original_name,
4209 func.MakeTypedOriginalArgString("")))
4210 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4211 func.WriteDestinationInitalizationValidation(file)
4212 self.WriteClientGLCallLog(func, file)
4213 for arg in func.GetOriginalArgs():
4214 arg.WriteClientSideValidationCode(file, func)
4215 file.Write(
4216 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4217 file.Write(" %sHelper(%s);\n" %
4218 (func.original_name, func.GetOriginalArgs()[-1].name))
4219 file.Write(" CheckGLError();\n")
4220 file.Write("}\n")
4221 file.Write("\n")
4224 class DELnHandler(TypeHandler):
4225 """Handler for glDelete___ type functions."""
4227 def __init__(self):
4228 TypeHandler.__init__(self)
4230 def WriteGetDataSizeCode(self, func, file):
4231 """Overrriden from TypeHandler."""
4232 code = """ uint32 data_size;
4233 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4234 return error::kOutOfBounds;
4237 file.Write(code)
4239 def WriteGLES2ImplementationUnitTest(self, func, file):
4240 """Overrriden from TypeHandler."""
4241 code = """
4242 TEST_F(GLES2ImplementationTest, %(name)s) {
4243 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4244 struct Cmds {
4245 cmds::%(name)sImmediate del;
4246 GLuint data[2];
4248 Cmds expected;
4249 expected.del.Init(arraysize(ids), &ids[0]);
4250 expected.data[0] = k%(types)sStartId;
4251 expected.data[1] = k%(types)sStartId + 1;
4252 gl_->%(name)s(arraysize(ids), &ids[0]);
4253 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4256 file.Write(code % {
4257 'name': func.name,
4258 'types': func.GetInfo('resource_types'),
4261 def WriteServiceUnitTest(self, func, file):
4262 """Overrriden from TypeHandler."""
4263 valid_test = """
4264 TEST_F(%(test_name)s, %(name)sValidArgs) {
4265 EXPECT_CALL(
4266 *gl_,
4267 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4268 .Times(1);
4269 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4270 SpecializedSetup<cmds::%(name)s, 0>(true);
4271 cmds::%(name)s cmd;
4272 cmd.Init(%(args)s);
4273 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4274 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4275 EXPECT_TRUE(
4276 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4279 self.WriteValidUnitTest(func, file, valid_test, {
4280 'resource_name': func.GetInfo('resource_type').lower(),
4281 'upper_resource_name': func.GetInfo('resource_type'),
4283 invalid_test = """
4284 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4285 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4286 SpecializedSetup<cmds::%(name)s, 0>(false);
4287 cmds::%(name)s cmd;
4288 cmd.Init(%(args)s);
4289 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4292 self.WriteValidUnitTest(func, file, invalid_test)
4294 def WriteImmediateServiceUnitTest(self, func, file):
4295 """Overrriden from TypeHandler."""
4296 valid_test = """
4297 TEST_F(%(test_name)s, %(name)sValidArgs) {
4298 EXPECT_CALL(
4299 *gl_,
4300 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4301 .Times(1);
4302 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4303 SpecializedSetup<cmds::%(name)s, 0>(true);
4304 cmd.Init(1, &client_%(resource_name)s_id_);
4305 EXPECT_EQ(error::kNoError,
4306 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4307 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4308 EXPECT_TRUE(
4309 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4312 self.WriteValidUnitTest(func, file, valid_test, {
4313 'resource_name': func.GetInfo('resource_type').lower(),
4314 'upper_resource_name': func.GetInfo('resource_type'),
4316 invalid_test = """
4317 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4318 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4319 SpecializedSetup<cmds::%(name)s, 0>(false);
4320 GLuint temp = kInvalidClientId;
4321 cmd.Init(1, &temp);
4322 EXPECT_EQ(error::kNoError,
4323 ExecuteImmediateCmd(cmd, sizeof(temp)));
4326 self.WriteValidUnitTest(func, file, invalid_test)
4328 def WriteHandlerImplementation (self, func, file):
4329 """Overrriden from TypeHandler."""
4330 file.Write(" %sHelper(n, %s);\n" %
4331 (func.name, func.GetLastOriginalArg().name))
4333 def WriteImmediateHandlerImplementation (self, func, file):
4334 """Overrriden from TypeHandler."""
4335 file.Write(" %sHelper(n, %s);\n" %
4336 (func.original_name, func.GetLastOriginalArg().name))
4338 def WriteGLES2Implementation(self, func, file):
4339 """Overrriden from TypeHandler."""
4340 impl_decl = func.GetInfo('impl_decl')
4341 if impl_decl == None or impl_decl == True:
4342 args = {
4343 'return_type': func.return_type,
4344 'name': func.original_name,
4345 'typed_args': func.MakeTypedOriginalArgString(""),
4346 'args': func.MakeOriginalArgString(""),
4347 'resource_type': func.GetInfo('resource_type').lower(),
4348 'count_name': func.GetOriginalArgs()[0].name,
4350 file.Write(
4351 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4352 args)
4353 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4354 func.WriteDestinationInitalizationValidation(file)
4355 self.WriteClientGLCallLog(func, file)
4356 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4357 for (GLsizei i = 0; i < n; ++i) {
4358 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4361 """ % func.GetOriginalArgs()[1].name)
4362 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4363 for (GLsizei i = 0; i < n; ++i) {
4364 GPU_DCHECK(%s[i] != 0);
4367 """ % func.GetOriginalArgs()[1].name)
4368 for arg in func.GetOriginalArgs():
4369 arg.WriteClientSideValidationCode(file, func)
4370 code = """ %(name)sHelper(%(args)s);
4371 CheckGLError();
4375 file.Write(code % args)
4377 def WriteImmediateCmdComputeSize(self, func, file):
4378 """Overrriden from TypeHandler."""
4379 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4380 file.Write(
4381 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4382 file.Write(" }\n")
4383 file.Write("\n")
4384 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4385 file.Write(" return static_cast<uint32>(\n")
4386 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4387 file.Write(" }\n")
4388 file.Write("\n")
4390 def WriteImmediateCmdSetHeader(self, func, file):
4391 """Overrriden from TypeHandler."""
4392 file.Write(" void SetHeader(GLsizei n) {\n")
4393 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4394 file.Write(" }\n")
4395 file.Write("\n")
4397 def WriteImmediateCmdInit(self, func, file):
4398 """Overrriden from TypeHandler."""
4399 last_arg = func.GetLastOriginalArg()
4400 file.Write(" void Init(%s, %s _%s) {\n" %
4401 (func.MakeTypedCmdArgString("_"),
4402 last_arg.type, last_arg.name))
4403 file.Write(" SetHeader(_n);\n")
4404 args = func.GetCmdArgs()
4405 for arg in args:
4406 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4407 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4408 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4409 file.Write(" }\n")
4410 file.Write("\n")
4412 def WriteImmediateCmdSet(self, func, file):
4413 """Overrriden from TypeHandler."""
4414 last_arg = func.GetLastOriginalArg()
4415 copy_args = func.MakeCmdArgString("_", False)
4416 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4417 (func.MakeTypedCmdArgString("_", True),
4418 last_arg.type, last_arg.name))
4419 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4420 (copy_args, last_arg.name))
4421 file.Write(" const uint32 size = ComputeSize(_n);\n")
4422 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4423 "cmd, size);\n")
4424 file.Write(" }\n")
4425 file.Write("\n")
4427 def WriteImmediateCmdHelper(self, func, file):
4428 """Overrriden from TypeHandler."""
4429 code = """ void %(name)s(%(typed_args)s) {
4430 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4431 gles2::cmds::%(name)s* c =
4432 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4433 if (c) {
4434 c->Init(%(args)s);
4439 file.Write(code % {
4440 "name": func.name,
4441 "typed_args": func.MakeTypedOriginalArgString(""),
4442 "args": func.MakeOriginalArgString(""),
4445 def WriteImmediateFormatTest(self, func, file):
4446 """Overrriden from TypeHandler."""
4447 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4448 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4449 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4450 (func.name, func.name))
4451 file.Write(" void* next_cmd = cmd.Set(\n")
4452 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4453 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4454 func.name)
4455 file.Write(" cmd.header.command);\n")
4456 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4457 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4458 file.Write(" cmd.header.size * 4u);\n")
4459 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4460 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4461 file.Write(" next_cmd, sizeof(cmd) +\n")
4462 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4463 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4464 file.Write("}\n")
4465 file.Write("\n")
4468 class GETnHandler(TypeHandler):
4469 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4471 def __init__(self):
4472 TypeHandler.__init__(self)
4474 def AddImmediateFunction(self, generator, func):
4475 """Overrriden from TypeHandler."""
4476 pass
4478 def WriteServiceImplementation(self, func, file):
4479 """Overrriden from TypeHandler."""
4480 file.Write(
4481 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4482 file.Write(
4483 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4484 func.name)
4485 last_arg = func.GetLastOriginalArg()
4487 all_but_last_args = func.GetOriginalArgs()[:-1]
4488 for arg in all_but_last_args:
4489 arg.WriteGetCode(file)
4491 code = """ typedef cmds::%(func_name)s::Result Result;
4492 GLsizei num_values = 0;
4493 GetNumValuesReturnedForGLGet(pname, &num_values);
4494 Result* result = GetSharedMemoryAs<Result*>(
4495 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4496 %(last_arg_type)s params = result ? result->GetData() : NULL;
4498 file.Write(code % {
4499 'last_arg_type': last_arg.type,
4500 'func_name': func.name,
4502 func.WriteHandlerValidation(file)
4503 code = """ // Check that the client initialized the result.
4504 if (result->size != 0) {
4505 return error::kInvalidArguments;
4508 shadowed = func.GetInfo('shadowed')
4509 if not shadowed:
4510 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4511 file.Write(code)
4512 func.WriteHandlerImplementation(file)
4513 if shadowed:
4514 code = """ result->SetNumResults(num_values);
4515 return error::kNoError;
4518 else:
4519 code = """ GLenum error = glGetError();
4520 if (error == GL_NO_ERROR) {
4521 result->SetNumResults(num_values);
4522 } else {
4523 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4525 return error::kNoError;
4529 file.Write(code % {'func_name': func.name})
4531 def WriteGLES2Implementation(self, func, file):
4532 """Overrriden from TypeHandler."""
4533 impl_decl = func.GetInfo('impl_decl')
4534 if impl_decl == None or impl_decl == True:
4535 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4536 (func.return_type, func.original_name,
4537 func.MakeTypedOriginalArgString("")))
4538 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4539 func.WriteDestinationInitalizationValidation(file)
4540 self.WriteClientGLCallLog(func, file)
4541 for arg in func.GetOriginalArgs():
4542 arg.WriteClientSideValidationCode(file, func)
4543 all_but_last_args = func.GetOriginalArgs()[:-1]
4544 arg_string = (
4545 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4546 all_arg_string = (
4547 ", ".join(["%s" % arg.name for arg in func.GetOriginalArgs()]))
4548 self.WriteTraceEvent(func, file)
4549 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4550 return;
4552 typedef cmds::%(func_name)s::Result Result;
4553 Result* result = GetResultAs<Result*>();
4554 if (!result) {
4555 return;
4557 result->SetNumResults(0);
4558 helper_->%(func_name)s(%(arg_string)s,
4559 GetResultShmId(), GetResultShmOffset());
4560 WaitForCmd();
4561 result->CopyResult(params);
4562 GPU_CLIENT_LOG_CODE_BLOCK({
4563 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4564 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4567 CheckGLError();
4570 file.Write(code % {
4571 'func_name': func.name,
4572 'arg_string': arg_string,
4573 'all_arg_string': all_arg_string,
4576 def WriteGLES2ImplementationUnitTest(self, func, file):
4577 """Writes the GLES2 Implemention unit test."""
4578 code = """
4579 TEST_F(GLES2ImplementationTest, %(name)s) {
4580 struct Cmds {
4581 cmds::%(name)s cmd;
4583 typedef cmds::%(name)s::Result Result;
4584 Result::Type result = 0;
4585 Cmds expected;
4586 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4587 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4588 EXPECT_CALL(*command_buffer(), OnFlush())
4589 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4590 .RetiresOnSaturation();
4591 gl_->%(name)s(%(args)s, &result);
4592 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4593 EXPECT_EQ(static_cast<Result::Type>(1), result);
4596 cmd_arg_strings = []
4597 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4598 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4599 cmd_arg_strings[0] = '123'
4600 gl_arg_strings = []
4601 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4602 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4603 gl_arg_strings[0] = '123'
4604 file.Write(code % {
4605 'name': func.name,
4606 'args': ", ".join(gl_arg_strings),
4607 'cmd_args': ", ".join(cmd_arg_strings),
4610 def WriteServiceUnitTest(self, func, file):
4611 """Overrriden from TypeHandler."""
4612 valid_test = """
4613 TEST_F(%(test_name)s, %(name)sValidArgs) {
4614 EXPECT_CALL(*gl_, GetError())
4615 .WillOnce(Return(GL_NO_ERROR))
4616 .WillOnce(Return(GL_NO_ERROR))
4617 .RetiresOnSaturation();
4618 SpecializedSetup<cmds::%(name)s, 0>(true);
4619 typedef cmds::%(name)s::Result Result;
4620 Result* result = static_cast<Result*>(shared_memory_address_);
4621 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4622 result->size = 0;
4623 cmds::%(name)s cmd;
4624 cmd.Init(%(args)s);
4625 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4626 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4627 %(valid_pname)s),
4628 result->GetNumResults());
4629 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4632 gl_arg_strings = []
4633 valid_pname = ''
4634 for count, arg in enumerate(func.GetOriginalArgs()[:-1]):
4635 arg_value = arg.GetValidGLArg(func, count, 0)
4636 gl_arg_strings.append(arg_value)
4637 if arg.name == 'pname':
4638 valid_pname = arg_value
4639 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4640 gl_arg_strings.append("_")
4641 else:
4642 gl_arg_strings.append("result->GetData()")
4644 self.WriteValidUnitTest(func, file, valid_test, {
4645 'local_gl_args': ", ".join(gl_arg_strings),
4646 'valid_pname': valid_pname,
4649 invalid_test = """
4650 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4651 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4652 SpecializedSetup<cmds::%(name)s, 0>(false);
4653 cmds::%(name)s::Result* result =
4654 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4655 result->size = 0;
4656 cmds::%(name)s cmd;
4657 cmd.Init(%(args)s);
4658 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4659 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4662 self.WriteInvalidUnitTest(func, file, invalid_test)
4665 class PUTHandler(TypeHandler):
4666 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4668 def __init__(self):
4669 TypeHandler.__init__(self)
4671 def WriteServiceUnitTest(self, func, file):
4672 """Writes the service unit test for a command."""
4673 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4674 if func.GetInfo("first_element_only"):
4675 gl_arg_strings = []
4676 for count, arg in enumerate(func.GetOriginalArgs()):
4677 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4678 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4679 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4680 ", ".join(gl_arg_strings))
4681 valid_test = """
4682 TEST_F(%(test_name)s, %(name)sValidArgs) {
4683 SpecializedSetup<cmds::%(name)s, 0>(true);
4684 cmds::%(name)s cmd;
4685 cmd.Init(%(args)s);
4686 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4687 %(expected_call)s
4688 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4689 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4692 extra = {
4693 'data_type': func.GetInfo('data_type'),
4694 'data_value': func.GetInfo('data_value') or '0',
4695 'expected_call': expected_call,
4697 self.WriteValidUnitTest(func, file, valid_test, extra)
4699 invalid_test = """
4700 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4701 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4702 SpecializedSetup<cmds::%(name)s, 0>(false);
4703 cmds::%(name)s cmd;
4704 cmd.Init(%(args)s);
4705 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4706 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4709 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4711 def WriteImmediateServiceUnitTest(self, func, file):
4712 """Writes the service unit test for a command."""
4713 valid_test = """
4714 TEST_F(%(test_name)s, %(name)sValidArgs) {
4715 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4716 SpecializedSetup<cmds::%(name)s, 0>(true);
4717 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4718 cmd.Init(%(gl_args)s, &temp[0]);
4719 EXPECT_CALL(
4720 *gl_,
4721 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4722 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4723 EXPECT_EQ(error::kNoError,
4724 ExecuteImmediateCmd(cmd, sizeof(temp)));
4725 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4728 gl_arg_strings = []
4729 gl_any_strings = []
4730 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4731 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4732 gl_any_strings.append("_")
4733 extra = {
4734 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
4735 'data_type': func.GetInfo('data_type'),
4736 'data_count': func.GetInfo('count'),
4737 'data_value': func.GetInfo('data_value') or '0',
4738 'gl_args': ", ".join(gl_arg_strings),
4739 'gl_any_args': ", ".join(gl_any_strings),
4741 self.WriteValidUnitTest(func, file, valid_test, extra)
4743 invalid_test = """
4744 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4745 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4746 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4747 SpecializedSetup<cmds::%(name)s, 0>(false);
4748 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4749 cmd.Init(%(all_but_last_args)s, &temp[0]);
4750 EXPECT_EQ(error::%(parse_result)s,
4751 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4754 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
4756 def WriteGetDataSizeCode(self, func, file):
4757 """Overrriden from TypeHandler."""
4758 code = """ uint32 data_size;
4759 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4760 return error::kOutOfBounds;
4763 file.Write(code % (func.info.data_type, func.info.count))
4764 if func.is_immediate:
4765 file.Write(" if (data_size > immediate_data_size) {\n")
4766 file.Write(" return error::kOutOfBounds;\n")
4767 file.Write(" }\n")
4769 def WriteGLES2Implementation(self, func, file):
4770 """Overrriden from TypeHandler."""
4771 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4772 (func.return_type, func.original_name,
4773 func.MakeTypedOriginalArgString("")))
4774 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4775 func.WriteDestinationInitalizationValidation(file)
4776 self.WriteClientGLCallLog(func, file)
4777 last_arg_name = func.GetLastOriginalArg().name
4778 values_str = ' << ", " << '.join(
4779 ["%s[%d]" % (last_arg_name, ndx) for ndx in range(0, func.info.count)])
4780 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
4781 for arg in func.GetOriginalArgs():
4782 arg.WriteClientSideValidationCode(file, func)
4783 file.Write(" helper_->%sImmediate(%s);\n" %
4784 (func.name, func.MakeOriginalArgString("")))
4785 file.Write(" CheckGLError();\n")
4786 file.Write("}\n")
4787 file.Write("\n")
4789 def WriteGLES2ImplementationUnitTest(self, func, file):
4790 """Writes the GLES2 Implemention unit test."""
4791 code = """
4792 TEST_F(GLES2ImplementationTest, %(name)s) {
4793 %(type)s data[%(count)d] = {0};
4794 struct Cmds {
4795 cmds::%(name)sImmediate cmd;
4796 %(type)s data[%(count)d];
4799 for (int jj = 0; jj < %(count)d; ++jj) {
4800 data[jj] = static_cast<%(type)s>(jj);
4802 Cmds expected;
4803 expected.cmd.Init(%(cmd_args)s, &data[0]);
4804 gl_->%(name)s(%(args)s, &data[0]);
4805 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4808 cmd_arg_strings = []
4809 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
4810 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
4811 gl_arg_strings = []
4812 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4813 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
4814 file.Write(code % {
4815 'name': func.name,
4816 'type': func.GetInfo('data_type'),
4817 'count': func.GetInfo('count'),
4818 'args': ", ".join(gl_arg_strings),
4819 'cmd_args': ", ".join(cmd_arg_strings),
4822 def WriteImmediateCmdComputeSize(self, func, file):
4823 """Overrriden from TypeHandler."""
4824 file.Write(" static uint32 ComputeDataSize() {\n")
4825 file.Write(" return static_cast<uint32>(\n")
4826 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4827 (func.info.data_type, func.info.count))
4828 file.Write(" }\n")
4829 file.Write("\n")
4830 file.Write(" static uint32 ComputeSize() {\n")
4831 file.Write(" return static_cast<uint32>(\n")
4832 file.Write(
4833 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4834 file.Write(" }\n")
4835 file.Write("\n")
4837 def WriteImmediateCmdSetHeader(self, func, file):
4838 """Overrriden from TypeHandler."""
4839 file.Write(" void SetHeader() {\n")
4840 file.Write(
4841 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4842 file.Write(" }\n")
4843 file.Write("\n")
4845 def WriteImmediateCmdInit(self, func, file):
4846 """Overrriden from TypeHandler."""
4847 last_arg = func.GetLastOriginalArg()
4848 file.Write(" void Init(%s, %s _%s) {\n" %
4849 (func.MakeTypedCmdArgString("_"),
4850 last_arg.type, last_arg.name))
4851 file.Write(" SetHeader();\n")
4852 args = func.GetCmdArgs()
4853 for arg in args:
4854 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4855 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4856 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
4857 file.Write(" }\n")
4858 file.Write("\n")
4860 def WriteImmediateCmdSet(self, func, file):
4861 """Overrriden from TypeHandler."""
4862 last_arg = func.GetLastOriginalArg()
4863 copy_args = func.MakeCmdArgString("_", False)
4864 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4865 (func.MakeTypedCmdArgString("_", True),
4866 last_arg.type, last_arg.name))
4867 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4868 (copy_args, last_arg.name))
4869 file.Write(" const uint32 size = ComputeSize();\n")
4870 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4871 "cmd, size);\n")
4872 file.Write(" }\n")
4873 file.Write("\n")
4875 def WriteImmediateCmdHelper(self, func, file):
4876 """Overrriden from TypeHandler."""
4877 code = """ void %(name)s(%(typed_args)s) {
4878 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4879 gles2::cmds::%(name)s* c =
4880 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4881 if (c) {
4882 c->Init(%(args)s);
4887 file.Write(code % {
4888 "name": func.name,
4889 "typed_args": func.MakeTypedOriginalArgString(""),
4890 "args": func.MakeOriginalArgString(""),
4893 def WriteImmediateFormatTest(self, func, file):
4894 """Overrriden from TypeHandler."""
4895 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4896 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4897 file.Write(" static %s data[] = {\n" % func.info.data_type)
4898 for v in range(0, func.info.count):
4899 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4900 (func.info.data_type, v))
4901 file.Write(" };\n")
4902 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4903 (func.name, func.name))
4904 file.Write(" void* next_cmd = cmd.Set(\n")
4905 file.Write(" &cmd")
4906 args = func.GetCmdArgs()
4907 for value, arg in enumerate(args):
4908 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4909 file.Write(",\n data);\n")
4910 args = func.GetCmdArgs()
4911 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4912 % func.name)
4913 file.Write(" cmd.header.command);\n")
4914 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4915 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4916 file.Write(" cmd.header.size * 4u);\n")
4917 for value, arg in enumerate(args):
4918 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4919 (arg.type, value + 11, arg.name))
4920 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4921 file.Write(" next_cmd, sizeof(cmd) +\n")
4922 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4923 file.Write(" // TODO(gman): Check that data was inserted;\n")
4924 file.Write("}\n")
4925 file.Write("\n")
4928 class PUTnHandler(TypeHandler):
4929 """Handler for PUTn 'glUniform__v' type functions."""
4931 def __init__(self):
4932 TypeHandler.__init__(self)
4934 def WriteServiceUnitTest(self, func, file):
4935 """Overridden from TypeHandler."""
4936 TypeHandler.WriteServiceUnitTest(self, func, file)
4938 valid_test = """
4939 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4940 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4941 SpecializedSetup<cmds::%(name)s, 0>(true);
4942 cmds::%(name)s cmd;
4943 cmd.Init(%(args)s);
4944 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4945 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4948 gl_arg_strings = []
4949 arg_strings = []
4950 for count, arg in enumerate(func.GetOriginalArgs()):
4951 # hardcoded to match unit tests.
4952 if count == 0:
4953 # the location of the second element of the 2nd uniform.
4954 # defined in GLES2DecoderBase::SetupShaderForUniform
4955 gl_arg_strings.append("3")
4956 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
4957 elif count == 1:
4958 # the number of elements that gl will be called with.
4959 gl_arg_strings.append("3")
4960 # the number of elements requested in the command.
4961 arg_strings.append("5")
4962 else:
4963 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4964 arg_strings.append(arg.GetValidArg(func, count, 0))
4965 extra = {
4966 'gl_args': ", ".join(gl_arg_strings),
4967 'args': ", ".join(arg_strings),
4969 self.WriteValidUnitTest(func, file, valid_test, extra)
4971 def WriteImmediateServiceUnitTest(self, func, file):
4972 """Overridden from TypeHandler."""
4973 valid_test = """
4974 TEST_F(%(test_name)s, %(name)sValidArgs) {
4975 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4976 EXPECT_CALL(
4977 *gl_,
4978 %(gl_func_name)s(%(gl_args)s,
4979 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4980 SpecializedSetup<cmds::%(name)s, 0>(true);
4981 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4982 cmd.Init(%(args)s, &temp[0]);
4983 EXPECT_EQ(error::kNoError,
4984 ExecuteImmediateCmd(cmd, sizeof(temp)));
4985 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4988 gl_arg_strings = []
4989 gl_any_strings = []
4990 arg_strings = []
4991 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
4992 gl_arg_strings.append(arg.GetValidGLArg(func, count, 0))
4993 gl_any_strings.append("_")
4994 arg_strings.append(arg.GetValidArg(func, count, 0))
4995 extra = {
4996 'data_type': func.GetInfo('data_type'),
4997 'data_count': func.GetInfo('count'),
4998 'args': ", ".join(arg_strings),
4999 'gl_args': ", ".join(gl_arg_strings),
5000 'gl_any_args': ", ".join(gl_any_strings),
5002 self.WriteValidUnitTest(func, file, valid_test, extra)
5004 invalid_test = """
5005 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5006 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5007 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5008 SpecializedSetup<cmds::%(name)s, 0>(false);
5009 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5010 cmd.Init(%(all_but_last_args)s, &temp[0]);
5011 EXPECT_EQ(error::%(parse_result)s,
5012 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5015 self.WriteInvalidUnitTest(func, file, invalid_test, extra)
5017 def WriteGetDataSizeCode(self, func, file):
5018 """Overrriden from TypeHandler."""
5019 code = """ uint32 data_size;
5020 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5021 return error::kOutOfBounds;
5024 file.Write(code % (func.info.data_type, func.info.count))
5025 if func.is_immediate:
5026 file.Write(" if (data_size > immediate_data_size) {\n")
5027 file.Write(" return error::kOutOfBounds;\n")
5028 file.Write(" }\n")
5030 def WriteGLES2Implementation(self, func, file):
5031 """Overrriden from TypeHandler."""
5032 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5033 (func.return_type, func.original_name,
5034 func.MakeTypedOriginalArgString("")))
5035 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5036 func.WriteDestinationInitalizationValidation(file)
5037 self.WriteClientGLCallLog(func, file)
5038 last_arg_name = func.GetLastOriginalArg().name
5039 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5040 for (GLsizei i = 0; i < count; ++i) {
5041 """)
5042 values_str = ' << ", " << '.join(
5043 ["%s[%d + i * %d]" % (
5044 last_arg_name, ndx, func.info.count) for ndx in range(
5045 0, func.info.count)])
5046 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5047 file.Write(" }\n });\n")
5048 for arg in func.GetOriginalArgs():
5049 arg.WriteClientSideValidationCode(file, func)
5050 file.Write(" helper_->%sImmediate(%s);\n" %
5051 (func.name, func.MakeOriginalArgString("")))
5052 file.Write(" CheckGLError();\n")
5053 file.Write("}\n")
5054 file.Write("\n")
5056 def WriteGLES2ImplementationUnitTest(self, func, file):
5057 """Writes the GLES2 Implemention unit test."""
5058 code = """
5059 TEST_F(GLES2ImplementationTest, %(name)s) {
5060 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5061 struct Cmds {
5062 cmds::%(name)sImmediate cmd;
5063 %(type)s data[%(count_param)d][%(count)d];
5066 Cmds expected;
5067 for (int ii = 0; ii < %(count_param)d; ++ii) {
5068 for (int jj = 0; jj < %(count)d; ++jj) {
5069 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5072 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5073 gl_->%(name)s(%(args)s, &data[0][0]);
5074 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5077 cmd_arg_strings = []
5078 for count, arg in enumerate(func.GetCmdArgs()[0:-2]):
5079 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func, count, 0))
5080 gl_arg_strings = []
5081 count_param = 0
5082 for count, arg in enumerate(func.GetOriginalArgs()[0:-1]):
5083 gl_arg_strings.append(arg.GetValidClientSideArg(func, count, 0))
5084 if arg.name == "count":
5085 count_param = int(arg.GetValidClientSideArg(func, count, 0))
5086 file.Write(code % {
5087 'name': func.name,
5088 'type': func.GetInfo('data_type'),
5089 'count': func.GetInfo('count'),
5090 'args': ", ".join(gl_arg_strings),
5091 'cmd_args': ", ".join(cmd_arg_strings),
5092 'count_param': count_param,
5095 def WriteImmediateCmdComputeSize(self, func, file):
5096 """Overrriden from TypeHandler."""
5097 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5098 file.Write(" return static_cast<uint32>(\n")
5099 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5100 (func.info.data_type, func.info.count))
5101 file.Write(" }\n")
5102 file.Write("\n")
5103 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5104 file.Write(" return static_cast<uint32>(\n")
5105 file.Write(
5106 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5107 file.Write(" }\n")
5108 file.Write("\n")
5110 def WriteImmediateCmdSetHeader(self, func, file):
5111 """Overrriden from TypeHandler."""
5112 file.Write(" void SetHeader(GLsizei count) {\n")
5113 file.Write(
5114 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5115 file.Write(" }\n")
5116 file.Write("\n")
5118 def WriteImmediateCmdInit(self, func, file):
5119 """Overrriden from TypeHandler."""
5120 last_arg = func.GetLastOriginalArg()
5121 file.Write(" void Init(%s, %s _%s) {\n" %
5122 (func.MakeTypedCmdArgString("_"),
5123 last_arg.type, last_arg.name))
5124 file.Write(" SetHeader(_count);\n")
5125 args = func.GetCmdArgs()
5126 for arg in args:
5127 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5128 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5129 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5130 file.Write(" }\n")
5131 file.Write("\n")
5133 def WriteImmediateCmdSet(self, func, file):
5134 """Overrriden from TypeHandler."""
5135 last_arg = func.GetLastOriginalArg()
5136 copy_args = func.MakeCmdArgString("_", False)
5137 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5138 (func.MakeTypedCmdArgString("_", True),
5139 last_arg.type, last_arg.name))
5140 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5141 (copy_args, last_arg.name))
5142 file.Write(" const uint32 size = ComputeSize(_count);\n")
5143 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5144 "cmd, size);\n")
5145 file.Write(" }\n")
5146 file.Write("\n")
5148 def WriteImmediateCmdHelper(self, func, file):
5149 """Overrriden from TypeHandler."""
5150 code = """ void %(name)s(%(typed_args)s) {
5151 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5152 gles2::cmds::%(name)s* c =
5153 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5154 if (c) {
5155 c->Init(%(args)s);
5160 file.Write(code % {
5161 "name": func.name,
5162 "typed_args": func.MakeTypedOriginalArgString(""),
5163 "args": func.MakeOriginalArgString(""),
5166 def WriteImmediateFormatTest(self, func, file):
5167 """Overrriden from TypeHandler."""
5168 args = func.GetCmdArgs()
5169 count_param = 0
5170 for value, arg in enumerate(args):
5171 if arg.name == "count":
5172 count_param = int(arg.GetValidClientSideArg(func, value, 0))
5173 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5174 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5175 file.Write(" static %s data[] = {\n" % func.info.data_type)
5176 for v in range(0, func.info.count * count_param):
5177 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5178 (func.info.data_type, v))
5179 file.Write(" };\n")
5180 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5181 (func.name, func.name))
5182 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5183 file.Write(" const size_t kExpectedCmdSize =\n")
5184 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5185 (func.info.data_type, func.info.count))
5186 file.Write(" void* next_cmd = cmd.Set(\n")
5187 file.Write(" &cmd")
5188 for value, arg in enumerate(args):
5189 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5190 file.Write(",\n data);\n")
5191 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5192 func.name)
5193 file.Write(" cmd.header.command);\n")
5194 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5195 for value, arg in enumerate(args):
5196 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5197 (arg.type, value + 1, arg.name))
5198 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5199 file.Write(" next_cmd, sizeof(cmd) +\n")
5200 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5201 file.Write(" // TODO(gman): Check that data was inserted;\n")
5202 file.Write("}\n")
5203 file.Write("\n")
5206 class PUTXnHandler(TypeHandler):
5207 """Handler for glUniform?f functions."""
5208 def __init__(self):
5209 TypeHandler.__init__(self)
5211 def WriteHandlerImplementation(self, func, file):
5212 """Overrriden from TypeHandler."""
5213 code = """ %(type)s temp[%(count)s] = { %(values)s};
5214 Do%(name)sv(%(location)s, 1, &temp[0]);
5216 values = ""
5217 args = func.GetOriginalArgs()
5218 count = int(func.GetInfo('count'))
5219 num_args = len(args)
5220 for ii in range(count):
5221 values += "%s, " % args[len(args) - count + ii].name
5223 file.Write(code % {
5224 'name': func.name,
5225 'count': func.GetInfo('count'),
5226 'type': func.GetInfo('data_type'),
5227 'location': args[0].name,
5228 'args': func.MakeOriginalArgString(""),
5229 'values': values,
5232 def WriteServiceUnitTest(self, func, file):
5233 """Overrriden from TypeHandler."""
5234 valid_test = """
5235 TEST_F(%(test_name)s, %(name)sValidArgs) {
5236 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5237 SpecializedSetup<cmds::%(name)s, 0>(true);
5238 cmds::%(name)s cmd;
5239 cmd.Init(%(args)s);
5240 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5241 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5244 args = func.GetOriginalArgs()
5245 local_args = "%s, 1, _" % args[0].GetValidGLArg(func, 0, 0)
5246 self.WriteValidUnitTest(func, file, valid_test, {
5247 'name': func.name,
5248 'count': func.GetInfo('count'),
5249 'local_args': local_args,
5252 invalid_test = """
5253 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5254 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5255 SpecializedSetup<cmds::%(name)s, 0>(false);
5256 cmds::%(name)s cmd;
5257 cmd.Init(%(args)s);
5258 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5261 self.WriteInvalidUnitTest(func, file, invalid_test, {
5262 'name': func.GetInfo('name'),
5263 'count': func.GetInfo('count'),
5267 class GLcharHandler(CustomHandler):
5268 """Handler for functions that pass a single string ."""
5270 def __init__(self):
5271 CustomHandler.__init__(self)
5273 def WriteImmediateCmdComputeSize(self, func, file):
5274 """Overrriden from TypeHandler."""
5275 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5276 file.Write(" return static_cast<uint32>(\n")
5277 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5278 file.Write(" }\n")
5280 def WriteImmediateCmdSetHeader(self, func, file):
5281 """Overrriden from TypeHandler."""
5282 code = """
5283 void SetHeader(uint32 data_size) {
5284 header.SetCmdBySize<ValueType>(data_size);
5287 file.Write(code)
5289 def WriteImmediateCmdInit(self, func, file):
5290 """Overrriden from TypeHandler."""
5291 last_arg = func.GetLastOriginalArg()
5292 args = func.GetCmdArgs()
5293 set_code = []
5294 for arg in args:
5295 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5296 code = """
5297 void Init(%(typed_args)s, uint32 _data_size) {
5298 SetHeader(_data_size);
5299 %(set_code)s
5300 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5304 file.Write(code % {
5305 "typed_args": func.MakeTypedOriginalArgString("_"),
5306 "set_code": "\n".join(set_code),
5307 "last_arg": last_arg.name
5310 def WriteImmediateCmdSet(self, func, file):
5311 """Overrriden from TypeHandler."""
5312 last_arg = func.GetLastOriginalArg()
5313 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5314 func.MakeTypedOriginalArgString("_", True))
5315 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5316 func.MakeOriginalArgString("_"))
5317 file.Write(" return NextImmediateCmdAddress<ValueType>("
5318 "cmd, _data_size);\n")
5319 file.Write(" }\n")
5320 file.Write("\n")
5322 def WriteImmediateCmdHelper(self, func, file):
5323 """Overrriden from TypeHandler."""
5324 code = """ void %(name)s(%(typed_args)s) {
5325 const uint32 data_size = strlen(name);
5326 gles2::cmds::%(name)s* c =
5327 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5328 if (c) {
5329 c->Init(%(args)s, data_size);
5334 file.Write(code % {
5335 "name": func.name,
5336 "typed_args": func.MakeTypedOriginalArgString(""),
5337 "args": func.MakeOriginalArgString(""),
5341 def WriteImmediateFormatTest(self, func, file):
5342 """Overrriden from TypeHandler."""
5343 init_code = []
5344 check_code = []
5345 all_but_last_arg = func.GetCmdArgs()[:-1]
5346 for value, arg in enumerate(all_but_last_arg):
5347 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5348 for value, arg in enumerate(all_but_last_arg):
5349 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5350 (arg.type, value + 11, arg.name))
5351 code = """
5352 TEST_F(GLES2FormatTest, %(func_name)s) {
5353 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5354 static const char* const test_str = \"test string\";
5355 void* next_cmd = cmd.Set(
5356 &cmd,
5357 %(init_code)s
5358 test_str,
5359 strlen(test_str));
5360 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5361 cmd.header.command);
5362 EXPECT_EQ(sizeof(cmd) +
5363 RoundSizeToMultipleOfEntries(strlen(test_str)),
5364 cmd.header.size * 4u);
5365 EXPECT_EQ(static_cast<char*>(next_cmd),
5366 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5367 RoundSizeToMultipleOfEntries(strlen(test_str)));
5368 %(check_code)s
5369 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5370 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5371 CheckBytesWritten(
5372 next_cmd,
5373 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5374 sizeof(cmd) + strlen(test_str));
5378 file.Write(code % {
5379 'func_name': func.name,
5380 'init_code': "\n".join(init_code),
5381 'check_code': "\n".join(check_code),
5385 class GLcharNHandler(CustomHandler):
5386 """Handler for functions that pass a single string with an optional len."""
5388 def __init__(self):
5389 CustomHandler.__init__(self)
5391 def InitFunction(self, func):
5392 """Overrriden from TypeHandler."""
5393 func.cmd_args = []
5394 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5396 def AddImmediateFunction(self, generator, func):
5397 """Overrriden from TypeHandler."""
5398 pass
5400 def AddBucketFunction(self, generator, func):
5401 """Overrriden from TypeHandler."""
5402 pass
5404 def WriteServiceImplementation(self, func, file):
5405 """Overrriden from TypeHandler."""
5406 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5407 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5408 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5409 Bucket* bucket = GetBucket(bucket_id);
5410 if (!bucket || bucket->size() == 0) {
5411 return error::kInvalidArguments;
5413 std::string str;
5414 if (!bucket->GetAsString(&str)) {
5415 return error::kInvalidArguments;
5417 %(gl_func_name)s(0, str.c_str());
5418 return error::kNoError;
5421 """ % {
5422 'name': func.name,
5423 'gl_func_name': func.GetGLFunctionName(),
5424 'bucket_id': func.cmd_args[0].name,
5428 class IsHandler(TypeHandler):
5429 """Handler for glIs____ type and glGetError functions."""
5431 def __init__(self):
5432 TypeHandler.__init__(self)
5434 def InitFunction(self, func):
5435 """Overrriden from TypeHandler."""
5436 func.AddCmdArg(Argument("result_shm_id", 'uint32'))
5437 func.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5438 if func.GetInfo('result') == None:
5439 func.AddInfo('result', ['uint32'])
5441 def WriteServiceUnitTest(self, func, file):
5442 """Overrriden from TypeHandler."""
5443 valid_test = """
5444 TEST_F(%(test_name)s, %(name)sValidArgs) {
5445 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5446 SpecializedSetup<cmds::%(name)s, 0>(true);
5447 cmds::%(name)s cmd;
5448 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5449 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5450 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5453 comma = ""
5454 if len(func.GetOriginalArgs()):
5455 comma =", "
5456 self.WriteValidUnitTest(func, file, valid_test, {
5457 'comma': comma,
5460 invalid_test = """
5461 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5462 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5463 SpecializedSetup<cmds::%(name)s, 0>(false);
5464 cmds::%(name)s cmd;
5465 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5466 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5469 self.WriteInvalidUnitTest(func, file, invalid_test, {
5470 'comma': comma,
5473 invalid_test = """
5474 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5476 SpecializedSetup<cmds::%(name)s, 0>(false);
5477 cmds::%(name)s cmd;
5478 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5479 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5480 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5481 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5484 self.WriteValidUnitTest(func, file, invalid_test, {
5485 'comma': comma,
5488 def WriteServiceImplementation(self, func, file):
5489 """Overrriden from TypeHandler."""
5490 file.Write(
5491 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5492 file.Write(
5493 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5494 func.name)
5495 args = func.GetOriginalArgs()
5496 for arg in args:
5497 arg.WriteGetCode(file)
5499 code = """ typedef cmds::%(func_name)s::Result Result;
5500 Result* result_dst = GetSharedMemoryAs<Result*>(
5501 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5502 if (!result_dst) {
5503 return error::kOutOfBounds;
5506 file.Write(code % {'func_name': func.name})
5507 func.WriteHandlerValidation(file)
5508 file.Write(" *result_dst = %s(%s);\n" %
5509 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5510 file.Write(" return error::kNoError;\n")
5511 file.Write("}\n")
5512 file.Write("\n")
5514 def WriteGLES2Implementation(self, func, file):
5515 """Overrriden from TypeHandler."""
5516 impl_func = func.GetInfo('impl_func')
5517 if impl_func == None or impl_func == True:
5518 error_value = func.GetInfo("error_value") or "GL_FALSE"
5519 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5520 (func.return_type, func.original_name,
5521 func.MakeTypedOriginalArgString("")))
5522 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5523 self.WriteTraceEvent(func, file)
5524 func.WriteDestinationInitalizationValidation(file)
5525 self.WriteClientGLCallLog(func, file)
5526 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5527 file.Write(" Result* result = GetResultAs<Result*>();\n")
5528 file.Write(" if (!result) {\n")
5529 file.Write(" return %s;\n" % error_value)
5530 file.Write(" }\n")
5531 file.Write(" *result = 0;\n")
5532 arg_string = func.MakeOriginalArgString("")
5533 comma = ""
5534 if len(arg_string) > 0:
5535 comma = ", "
5536 file.Write(
5537 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5538 (func.name, arg_string, comma))
5539 file.Write(" WaitForCmd();\n")
5540 file.Write(" %s result_value = *result;\n" % func.return_type)
5541 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5542 file.Write(" CheckGLError();\n")
5543 file.Write(" return result_value;\n")
5544 file.Write("}\n")
5545 file.Write("\n")
5547 def WriteGLES2ImplementationUnitTest(self, func, file):
5548 """Overrriden from TypeHandler."""
5549 client_test = func.GetInfo('client_test')
5550 if client_test == None or client_test == True:
5551 code = """
5552 TEST_F(GLES2ImplementationTest, %(name)s) {
5553 struct Cmds {
5554 cmds::%(name)s cmd;
5557 typedef cmds::%(name)s::Result Result;
5558 Cmds expected;
5559 ExpectedMemoryInfo result1 =
5560 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5561 expected.cmd.Init(1, result1.id, result1.offset);
5563 EXPECT_CALL(*command_buffer(), OnFlush())
5564 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5565 .RetiresOnSaturation();
5567 GLboolean result = gl_->%(name)s(1);
5568 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5569 EXPECT_TRUE(result);
5572 file.Write(code % {
5573 'name': func.name,
5577 class STRnHandler(TypeHandler):
5578 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5579 GetTranslatedShaderSourceANGLE."""
5581 def __init__(self):
5582 TypeHandler.__init__(self)
5584 def InitFunction(self, func):
5585 """Overrriden from TypeHandler."""
5586 # remove all but the first cmd args.
5587 cmd_args = func.GetCmdArgs()
5588 func.ClearCmdArgs()
5589 func.AddCmdArg(cmd_args[0])
5590 # add on a bucket id.
5591 func.AddCmdArg(Argument('bucket_id', 'uint32'))
5593 def WriteGLES2Implementation(self, func, file):
5594 """Overrriden from TypeHandler."""
5595 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5596 GPU_CLIENT_SINGLE_THREAD_CHECK();
5598 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5599 << "] gl%(func_name)s" << "("
5600 << %(arg0)s << ", "
5601 << %(arg1)s << ", "
5602 << static_cast<void*>(%(arg2)s) << ", "
5603 << static_cast<void*>(%(arg3)s) << ")");
5604 helper_->SetBucketSize(kResultBucketId, 0);
5605 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5606 std::string str;
5607 GLsizei max_size = 0;
5608 if (GetBucketAsString(kResultBucketId, &str)) {
5609 if (bufsize > 0) {
5610 max_size =
5611 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5612 memcpy(%(dest_name)s, str.c_str(), max_size);
5613 %(dest_name)s[max_size] = '\\0';
5614 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5617 if (%(length_name)s != NULL) {
5618 *%(length_name)s = max_size;
5620 CheckGLError();
5623 args = func.GetOriginalArgs()
5624 str_args = {
5625 'return_type': func.return_type,
5626 'func_name': func.original_name,
5627 'args': func.MakeTypedOriginalArgString(""),
5628 'id_name': args[0].name,
5629 'bufsize_name': args[1].name,
5630 'length_name': args[2].name,
5631 'dest_name': args[3].name,
5632 'arg0': args[0].name,
5633 'arg1': args[1].name,
5634 'arg2': args[2].name,
5635 'arg3': args[3].name,
5637 file.Write(code_1 % str_args)
5638 func.WriteDestinationInitalizationValidation(file)
5639 file.Write(code_2 % str_args)
5641 def WriteServiceUnitTest(self, func, file):
5642 """Overrriden from TypeHandler."""
5643 valid_test = """
5644 TEST_F(%(test_name)s, %(name)sValidArgs) {
5645 const char* kInfo = "hello";
5646 const uint32 kBucketId = 123;
5647 SpecializedSetup<cmds::%(name)s, 0>(true);
5648 %(expect_len_code)s
5649 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5650 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5651 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5652 cmds::%(name)s cmd;
5653 cmd.Init(%(args)s);
5654 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5655 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5656 ASSERT_TRUE(bucket != NULL);
5657 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5658 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5659 bucket->size()));
5660 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5663 args = func.GetOriginalArgs()
5664 id_name = args[0].GetValidGLArg(func, 0, 0)
5665 get_len_func = func.GetInfo('get_len_func')
5666 get_len_enum = func.GetInfo('get_len_enum')
5667 sub = {
5668 'id_name': id_name,
5669 'get_len_func': get_len_func,
5670 'get_len_enum': get_len_enum,
5671 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5672 args[0].GetValidGLArg(func, 0, 0),
5673 'args': '%s, kBucketId' % args[0].GetValidArg(func, 0, 0),
5674 'expect_len_code': '',
5676 if get_len_func and get_len_func[0:2] == 'gl':
5677 sub['expect_len_code'] = (
5678 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5679 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5680 get_len_func[2:], id_name, get_len_enum)
5681 self.WriteValidUnitTest(func, file, valid_test, sub)
5683 invalid_test = """
5684 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5685 const uint32 kBucketId = 123;
5686 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5687 .Times(0);
5688 cmds::%(name)s cmd;
5689 cmd.Init(kInvalidClientId, kBucketId);
5690 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5691 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5694 self.WriteValidUnitTest(func, file, invalid_test)
5696 def WriteServiceImplementation(self, func, file):
5697 """Overrriden from TypeHandler."""
5698 pass
5701 class FunctionInfo(object):
5702 """Holds info about a function."""
5704 def __init__(self, info, type_handler):
5705 for key in info:
5706 setattr(self, key, info[key])
5707 self.type_handler = type_handler
5708 if not 'type' in info:
5709 self.type = ''
5712 class Argument(object):
5713 """A class that represents a function argument."""
5715 cmd_type_map_ = {
5716 'GLenum': 'uint32',
5717 'GLint': 'int32',
5718 'GLintptr': 'int32',
5719 'GLsizei': 'int32',
5720 'GLsizeiptr': 'int32',
5721 'GLfloat': 'float',
5722 'GLclampf': 'float',
5724 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5726 def __init__(self, name, type):
5727 self.name = name
5728 self.optional = type.endswith("Optional*")
5729 if self.optional:
5730 type = type[:-9] + "*"
5731 self.type = type
5733 if type in self.cmd_type_map_:
5734 self.cmd_type = self.cmd_type_map_[type]
5735 else:
5736 self.cmd_type = 'uint32'
5738 def IsPointer(self):
5739 """Returns true if argument is a pointer."""
5740 return False
5742 def AddCmdArgs(self, args):
5743 """Adds command arguments for this argument to the given list."""
5744 return args.append(self)
5746 def AddInitArgs(self, args):
5747 """Adds init arguments for this argument to the given list."""
5748 return args.append(self)
5750 def GetValidArg(self, func, offset, index):
5751 """Gets a valid value for this argument."""
5752 valid_arg = func.GetValidArg(offset)
5753 if valid_arg != None:
5754 return valid_arg
5755 return str(offset + 1)
5757 def GetValidClientSideArg(self, func, offset, index):
5758 """Gets a valid value for this argument."""
5759 return str(offset + 1)
5761 def GetValidClientSideCmdArg(self, func, offset, index):
5762 """Gets a valid value for this argument."""
5763 return str(offset + 1)
5765 def GetValidGLArg(self, func, offset, index):
5766 """Gets a valid GL value for this argument."""
5767 valid_arg = func.GetValidArg(offset)
5768 if valid_arg != None:
5769 return valid_arg
5770 return str(offset + 1)
5772 def GetNumInvalidValues(self, func):
5773 """returns the number of invalid values to be tested."""
5774 return 0
5776 def GetInvalidArg(self, offset, index):
5777 """returns an invalid value and expected parse result by index."""
5778 return ("---ERROR0---", "---ERROR2---", None)
5780 def GetLogArg(self):
5781 """Get argument appropriate for LOG macro."""
5782 if self.type == 'GLboolean':
5783 return 'GLES2Util::GetStringBool(%s)' % self.name
5784 if self.type == 'GLenum':
5785 return 'GLES2Util::GetStringEnum(%s)' % self.name
5786 return self.name
5788 def WriteGetCode(self, file):
5789 """Writes the code to get an argument from a command structure."""
5790 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5791 (self.type, self.name, self.type, self.name))
5793 def WriteValidationCode(self, file, func):
5794 """Writes the validation code for an argument."""
5795 pass
5797 def WriteClientSideValidationCode(self, file, func):
5798 """Writes the validation code for an argument."""
5799 pass
5801 def WriteDestinationInitalizationValidation(self, file, func):
5802 """Writes the client side destintion initialization validation."""
5803 pass
5805 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
5806 """Writes the client side destintion initialization validation if needed."""
5807 parts = self.type.split(" ")
5808 if len(parts) > 1:
5809 return
5810 if parts[0] in self.need_validation_:
5811 file.Write(
5812 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5813 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
5816 def WriteGetAddress(self, file):
5817 """Writes the code to get the address this argument refers to."""
5818 pass
5820 def GetImmediateVersion(self):
5821 """Gets the immediate version of this argument."""
5822 return self
5824 def GetBucketVersion(self):
5825 """Gets the bucket version of this argument."""
5826 return self
5829 class BoolArgument(Argument):
5830 """class for GLboolean"""
5832 def __init__(self, name, type):
5833 Argument.__init__(self, name, 'GLboolean')
5835 def GetValidArg(self, func, offset, index):
5836 """Gets a valid value for this argument."""
5837 return 'true'
5839 def GetValidClientSideArg(self, func, offset, index):
5840 """Gets a valid value for this argument."""
5841 return 'true'
5843 def GetValidClientSideCmdArg(self, func, offset, index):
5844 """Gets a valid value for this argument."""
5845 return 'true'
5847 def GetValidGLArg(self, func, offset, index):
5848 """Gets a valid GL value for this argument."""
5849 return 'true'
5852 class UniformLocationArgument(Argument):
5853 """class for uniform locations."""
5855 def __init__(self, name):
5856 Argument.__init__(self, name, "GLint")
5858 def WriteGetCode(self, file):
5859 """Writes the code to get an argument from a command structure."""
5860 code = """ %s %s = static_cast<%s>(c.%s);
5862 file.Write(code % (self.type, self.name, self.type, self.name))
5864 def GetValidArg(self, func, offset, index):
5865 """Gets a valid value for this argument."""
5866 return "%d" % (offset + 1)
5869 class DataSizeArgument(Argument):
5870 """class for data_size which Bucket commands do not need."""
5872 def __init__(self, name):
5873 Argument.__init__(self, name, "uint32")
5875 def GetBucketVersion(self):
5876 return None
5879 class SizeArgument(Argument):
5880 """class for GLsizei and GLsizeiptr."""
5882 def __init__(self, name, type):
5883 Argument.__init__(self, name, type)
5885 def GetNumInvalidValues(self, func):
5886 """overridden from Argument."""
5887 if func.is_immediate:
5888 return 0
5889 return 1
5891 def GetInvalidArg(self, offset, index):
5892 """overridden from Argument."""
5893 return ("-1", "kNoError", "GL_INVALID_VALUE")
5895 def WriteValidationCode(self, file, func):
5896 """overridden from Argument."""
5897 file.Write(" if (%s < 0) {\n" % self.name)
5898 file.Write(
5899 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5900 (func.original_name, self.name))
5901 file.Write(" return error::kNoError;\n")
5902 file.Write(" }\n")
5904 def WriteClientSideValidationCode(self, file, func):
5905 """overridden from Argument."""
5906 file.Write(" if (%s < 0) {\n" % self.name)
5907 file.Write(
5908 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5909 (func.original_name, self.name))
5910 file.Write(" return;\n")
5911 file.Write(" }\n")
5914 class SizeNotNegativeArgument(SizeArgument):
5915 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5917 def __init__(self, name, type, gl_type):
5918 SizeArgument.__init__(self, name, gl_type)
5920 def GetInvalidArg(self, offset, index):
5921 """overridden from SizeArgument."""
5922 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5924 def WriteValidationCode(self, file, func):
5925 """overridden from SizeArgument."""
5926 pass
5929 class EnumBaseArgument(Argument):
5930 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5932 def __init__(self, name, gl_type, type, gl_error):
5933 Argument.__init__(self, name, gl_type)
5935 self.local_type = type
5936 self.gl_error = gl_error
5937 name = type[len(gl_type):]
5938 self.type_name = name
5939 self.enum_info = _ENUM_LISTS[name]
5941 def WriteValidationCode(self, file, func):
5942 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5943 (ToUnderscore(self.type_name), self.name))
5944 if self.gl_error == "GL_INVALID_ENUM":
5945 file.Write(
5946 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5947 (func.original_name, self.name, self.name))
5948 else:
5949 file.Write(
5950 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5951 (self.gl_error, func.original_name, self.name, self.gl_error))
5952 file.Write(" return error::kNoError;\n")
5953 file.Write(" }\n")
5955 def GetValidArg(self, func, offset, index):
5956 valid_arg = func.GetValidArg(offset)
5957 if valid_arg != None:
5958 return valid_arg
5959 if 'valid' in self.enum_info:
5960 valid = self.enum_info['valid']
5961 num_valid = len(valid)
5962 if index >= num_valid:
5963 index = num_valid - 1
5964 return valid[index]
5965 return str(offset + 1)
5967 def GetValidClientSideArg(self, func, offset, index):
5968 """Gets a valid value for this argument."""
5969 return self.GetValidArg(func, offset, index)
5971 def GetValidClientSideCmdArg(self, func, offset, index):
5972 """Gets a valid value for this argument."""
5973 return self.GetValidArg(func, offset, index)
5975 def GetValidGLArg(self, func, offset, index):
5976 """Gets a valid value for this argument."""
5977 return self.GetValidArg(func, offset, index)
5979 def GetNumInvalidValues(self, func):
5980 """returns the number of invalid values to be tested."""
5981 if 'invalid' in self.enum_info:
5982 invalid = self.enum_info['invalid']
5983 return len(invalid)
5984 return 0
5986 def GetInvalidArg(self, offset, index):
5987 """returns an invalid value by index."""
5988 if 'invalid' in self.enum_info:
5989 invalid = self.enum_info['invalid']
5990 num_invalid = len(invalid)
5991 if index >= num_invalid:
5992 index = num_invalid - 1
5993 return (invalid[index], "kNoError", self.gl_error)
5994 return ("---ERROR1---", "kNoError", self.gl_error)
5997 class EnumArgument(EnumBaseArgument):
5998 """A class that represents a GLenum argument"""
6000 def __init__(self, name, type):
6001 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6003 def GetLogArg(self):
6004 """Overridden from Argument."""
6005 return ("GLES2Util::GetString%s(%s)" %
6006 (self.type_name, self.name))
6009 class IntArgument(EnumBaseArgument):
6010 """A class for a GLint argument that can only except specific values.
6012 For example glTexImage2D takes a GLint for its internalformat
6013 argument instead of a GLenum.
6016 def __init__(self, name, type):
6017 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6020 class ValidatedBoolArgument(EnumBaseArgument):
6021 """A class for a GLboolean argument that can only except specific values.
6023 For example glUniformMatrix takes a GLboolean for it's transpose but it
6024 must be false.
6027 def __init__(self, name, type):
6028 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6030 def GetLogArg(self):
6031 """Overridden from Argument."""
6032 return 'GLES2Util::GetStringBool(%s)' % self.name
6035 class ImmediatePointerArgument(Argument):
6036 """A class that represents an immediate argument to a function.
6038 An immediate argument is one where the data follows the command.
6041 def __init__(self, name, type):
6042 Argument.__init__(self, name, type)
6044 def AddCmdArgs(self, args):
6045 """Overridden from Argument."""
6046 pass
6048 def WriteGetCode(self, file):
6049 """Overridden from Argument."""
6050 file.Write(
6051 " %s %s = GetImmediateDataAs<%s>(\n" %
6052 (self.type, self.name, self.type))
6053 file.Write(" c, data_size, immediate_data_size);\n")
6055 def WriteValidationCode(self, file, func):
6056 """Overridden from Argument."""
6057 file.Write(" if (%s == NULL) {\n" % self.name)
6058 file.Write(" return error::kOutOfBounds;\n")
6059 file.Write(" }\n")
6061 def GetImmediateVersion(self):
6062 """Overridden from Argument."""
6063 return None
6065 def WriteDestinationInitalizationValidation(self, file, func):
6066 """Overridden from Argument."""
6067 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6069 def GetLogArg(self):
6070 """Overridden from Argument."""
6071 return "static_cast<const void*>(%s)" % self.name
6074 class BucketPointerArgument(Argument):
6075 """A class that represents an bucket argument to a function."""
6077 def __init__(self, name, type):
6078 Argument.__init__(self, name, type)
6080 def AddCmdArgs(self, args):
6081 """Overridden from Argument."""
6082 pass
6084 def WriteGetCode(self, file):
6085 """Overridden from Argument."""
6086 file.Write(
6087 " %s %s = bucket->GetData(0, data_size);\n" %
6088 (self.type, self.name))
6090 def WriteValidationCode(self, file, func):
6091 """Overridden from Argument."""
6092 pass
6094 def GetImmediateVersion(self):
6095 """Overridden from Argument."""
6096 return None
6098 def WriteDestinationInitalizationValidation(self, file, func):
6099 """Overridden from Argument."""
6100 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6102 def GetLogArg(self):
6103 """Overridden from Argument."""
6104 return "static_cast<const void*>(%s)" % self.name
6107 class PointerArgument(Argument):
6108 """A class that represents a pointer argument to a function."""
6110 def __init__(self, name, type):
6111 Argument.__init__(self, name, type)
6113 def IsPointer(self):
6114 """Returns true if argument is a pointer."""
6115 return True
6117 def GetValidArg(self, func, offset, index):
6118 """Overridden from Argument."""
6119 return "shared_memory_id_, shared_memory_offset_"
6121 def GetValidGLArg(self, func, offset, index):
6122 """Overridden from Argument."""
6123 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6125 def GetNumInvalidValues(self, func):
6126 """Overridden from Argument."""
6127 return 2
6129 def GetInvalidArg(self, offset, index):
6130 """Overridden from Argument."""
6131 if index == 0:
6132 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6133 else:
6134 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6135 "kOutOfBounds", None)
6137 def GetLogArg(self):
6138 """Overridden from Argument."""
6139 return "static_cast<const void*>(%s)" % self.name
6141 def AddCmdArgs(self, args):
6142 """Overridden from Argument."""
6143 args.append(Argument("%s_shm_id" % self.name, 'uint32'))
6144 args.append(Argument("%s_shm_offset" % self.name, 'uint32'))
6146 def WriteGetCode(self, file):
6147 """Overridden from Argument."""
6148 file.Write(
6149 " %s %s = GetSharedMemoryAs<%s>(\n" %
6150 (self.type, self.name, self.type))
6151 file.Write(
6152 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6153 (self.name, self.name))
6155 def WriteGetAddress(self, file):
6156 """Overridden from Argument."""
6157 file.Write(
6158 " %s %s = GetSharedMemoryAs<%s>(\n" %
6159 (self.type, self.name, self.type))
6160 file.Write(
6161 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6162 (self.name, self.name, self.name))
6164 def WriteValidationCode(self, file, func):
6165 """Overridden from Argument."""
6166 file.Write(" if (%s == NULL) {\n" % self.name)
6167 file.Write(" return error::kOutOfBounds;\n")
6168 file.Write(" }\n")
6170 def GetImmediateVersion(self):
6171 """Overridden from Argument."""
6172 return ImmediatePointerArgument(self.name, self.type)
6174 def GetBucketVersion(self):
6175 """Overridden from Argument."""
6176 if self.type == "const char*":
6177 return InputStringBucketArgument(self.name, self.type)
6178 return BucketPointerArgument(self.name, self.type)
6180 def WriteDestinationInitalizationValidation(self, file, func):
6181 """Overridden from Argument."""
6182 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6185 class InputStringBucketArgument(Argument):
6186 """An string input argument where the string is passed in a bucket."""
6188 def __init__(self, name, type):
6189 Argument.__init__(self, name + "_bucket_id", "uint32")
6191 def WriteGetCode(self, file):
6192 """Overridden from Argument."""
6193 code = """
6194 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6195 if (!%(name)s_bucket) {
6196 return error::kInvalidArguments;
6198 std::string %(name)s_str;
6199 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6200 return error::kInvalidArguments;
6202 const char* %(name)s = %(name)s_str.c_str();
6204 file.Write(code % {
6205 'name': self.name,
6208 def GetValidArg(self, func, offset, index):
6209 return "kNameBucketId"
6211 def GetValidGLArg(self, func, offset, index):
6212 return "_"
6215 class NonImmediatePointerArgument(PointerArgument):
6216 """A pointer argument that stays a pointer even in an immediate cmd."""
6218 def __init__(self, name, type):
6219 PointerArgument.__init__(self, name, type)
6221 def IsPointer(self):
6222 """Returns true if argument is a pointer."""
6223 return False
6225 def GetImmediateVersion(self):
6226 """Overridden from Argument."""
6227 return self
6230 class ResourceIdArgument(Argument):
6231 """A class that represents a resource id argument to a function."""
6233 def __init__(self, name, type):
6234 match = re.match("(GLid\w+)", type)
6235 self.resource_type = match.group(1)[4:]
6236 type = type.replace(match.group(1), "GLuint")
6237 Argument.__init__(self, name, type)
6239 def WriteGetCode(self, file):
6240 """Overridden from Argument."""
6241 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6243 def GetValidArg(self, func, offset, index):
6244 return "client_%s_id_" % self.resource_type.lower()
6246 def GetValidGLArg(self, func, offset, index):
6247 return "kService%sId" % self.resource_type
6250 class ResourceIdBindArgument(Argument):
6251 """Represents a resource id argument to a bind function."""
6253 def __init__(self, name, type):
6254 match = re.match("(GLidBind\w+)", type)
6255 self.resource_type = match.group(1)[8:]
6256 type = type.replace(match.group(1), "GLuint")
6257 Argument.__init__(self, name, type)
6259 def WriteGetCode(self, file):
6260 """Overridden from Argument."""
6261 code = """ %(type)s %(name)s = c.%(name)s;
6263 file.Write(code % {'type': self.type, 'name': self.name})
6265 def GetValidArg(self, func, offset, index):
6266 return "client_%s_id_" % self.resource_type.lower()
6268 def GetValidGLArg(self, func, offset, index):
6269 return "kService%sId" % self.resource_type
6272 class ResourceIdZeroArgument(Argument):
6273 """Represents a resource id argument to a function that can be zero."""
6275 def __init__(self, name, type):
6276 match = re.match("(GLidZero\w+)", type)
6277 self.resource_type = match.group(1)[8:]
6278 type = type.replace(match.group(1), "GLuint")
6279 Argument.__init__(self, name, type)
6281 def WriteGetCode(self, file):
6282 """Overridden from Argument."""
6283 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6285 def GetValidArg(self, func, offset, index):
6286 return "client_%s_id_" % self.resource_type.lower()
6288 def GetValidGLArg(self, func, offset, index):
6289 return "kService%sId" % self.resource_type
6291 def GetNumInvalidValues(self, func):
6292 """returns the number of invalid values to be tested."""
6293 return 1
6295 def GetInvalidArg(self, offset, index):
6296 """returns an invalid value by index."""
6297 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6300 class Function(object):
6301 """A class that represents a function."""
6303 def __init__(self, original_name, name, info, return_type, original_args,
6304 args_for_cmds, cmd_args, init_args, num_pointer_args):
6305 self.name = name
6306 self.original_name = original_name
6307 self.info = info
6308 self.type_handler = info.type_handler
6309 self.return_type = return_type
6310 self.original_args = original_args
6311 self.num_pointer_args = num_pointer_args
6312 self.can_auto_generate = num_pointer_args == 0 and return_type == "void"
6313 self.cmd_args = cmd_args
6314 self.init_args = init_args
6315 self.InitFunction()
6316 self.args_for_cmds = args_for_cmds
6317 self.is_immediate = False
6319 def IsType(self, type_name):
6320 """Returns true if function is a certain type."""
6321 return self.info.type == type_name
6323 def InitFunction(self):
6324 """Calls the init function for the type handler."""
6325 self.type_handler.InitFunction(self)
6327 def GetInfo(self, name):
6328 """Returns a value from the function info for this function."""
6329 if hasattr(self.info, name):
6330 return getattr(self.info, name)
6331 return None
6333 def GetValidArg(self, index):
6334 """Gets a valid arg from the function info if one exists."""
6335 valid_args = self.GetInfo('valid_args')
6336 if valid_args and str(index) in valid_args:
6337 return valid_args[str(index)]
6338 return None
6340 def AddInfo(self, name, value):
6341 """Adds an info."""
6342 setattr(self.info, name, value)
6344 def IsCoreGLFunction(self):
6345 return (not self.GetInfo('extension') and
6346 not self.GetInfo('pepper_interface'))
6348 def InPepperInterface(self, interface):
6349 ext = self.GetInfo('pepper_interface')
6350 if not interface.GetName():
6351 return self.IsCoreGLFunction()
6352 return ext == interface.GetName()
6354 def InAnyPepperExtension(self):
6355 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6357 def GetGLFunctionName(self):
6358 """Gets the function to call to execute GL for this command."""
6359 if self.GetInfo('decoder_func'):
6360 return self.GetInfo('decoder_func')
6361 return "gl%s" % self.original_name
6363 def GetGLTestFunctionName(self):
6364 gl_func_name = self.GetInfo('gl_test_func')
6365 if gl_func_name == None:
6366 gl_func_name = self.GetGLFunctionName()
6367 if gl_func_name.startswith("gl"):
6368 gl_func_name = gl_func_name[2:]
6369 else:
6370 gl_func_name = self.original_name
6371 return gl_func_name
6373 def AddCmdArg(self, arg):
6374 """Adds a cmd argument to this function."""
6375 self.cmd_args.append(arg)
6377 def GetCmdArgs(self):
6378 """Gets the command args for this function."""
6379 return self.cmd_args
6381 def ClearCmdArgs(self):
6382 """Clears the command args for this function."""
6383 self.cmd_args = []
6385 def GetInitArgs(self):
6386 """Gets the init args for this function."""
6387 return self.init_args
6389 def GetOriginalArgs(self):
6390 """Gets the original arguments to this function."""
6391 return self.original_args
6393 def GetLastOriginalArg(self):
6394 """Gets the last original argument to this function."""
6395 return self.original_args[len(self.original_args) - 1]
6397 def __GetArgList(self, arg_string, add_comma):
6398 """Adds a comma if arg_string is not empty and add_comma is true."""
6399 comma = ""
6400 if add_comma and len(arg_string):
6401 comma = ", "
6402 return "%s%s" % (comma, arg_string)
6404 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6405 """Gets a list of arguments as they arg in GL."""
6406 args = self.GetOriginalArgs()
6407 arg_string = ", ".join(
6408 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6409 return self.__GetArgList(arg_string, add_comma)
6411 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6412 """Gets the list of arguments as they are in GL."""
6413 args = self.GetOriginalArgs()
6414 arg_string = separator.join(
6415 ["%s%s" % (prefix, arg.name) for arg in args])
6416 return self.__GetArgList(arg_string, add_comma)
6418 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6419 """Gets a typed list of arguments as they need to be for command buffers."""
6420 args = self.GetCmdArgs()
6421 arg_string = ", ".join(
6422 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6423 return self.__GetArgList(arg_string, add_comma)
6425 def MakeCmdArgString(self, prefix, add_comma = False):
6426 """Gets the list of arguments as they need to be for command buffers."""
6427 args = self.GetCmdArgs()
6428 arg_string = ", ".join(
6429 ["%s%s" % (prefix, arg.name) for arg in args])
6430 return self.__GetArgList(arg_string, add_comma)
6432 def MakeTypedInitString(self, prefix, add_comma = False):
6433 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6434 args = self.GetInitArgs()
6435 arg_string = ", ".join(
6436 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6437 return self.__GetArgList(arg_string, add_comma)
6439 def MakeInitString(self, prefix, add_comma = False):
6440 """Gets the list of arguments as they need to be for cmd Init/Set."""
6441 args = self.GetInitArgs()
6442 arg_string = ", ".join(
6443 ["%s%s" % (prefix, arg.name) for arg in args])
6444 return self.__GetArgList(arg_string, add_comma)
6446 def MakeLogArgString(self):
6447 """Makes a string of the arguments for the LOG macros"""
6448 args = self.GetOriginalArgs()
6449 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
6451 def WriteCommandDescription(self, file):
6452 """Writes a description of the command."""
6453 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
6455 def WriteHandlerValidation(self, file):
6456 """Writes validation code for the function."""
6457 for arg in self.GetOriginalArgs():
6458 arg.WriteValidationCode(file, self)
6459 self.WriteValidationCode(file)
6461 def WriteHandlerImplementation(self, file):
6462 """Writes the handler implementation for this command."""
6463 self.type_handler.WriteHandlerImplementation(self, file)
6465 def WriteValidationCode(self, file):
6466 """Writes the validation code for a command."""
6467 pass
6469 def WriteCmdArgFlag(self, file):
6470 """Writes the cmd kArgFlags constant."""
6471 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6473 def WriteCmdComputeSize(self, file):
6474 """Writes the ComputeSize function for the command."""
6475 file.Write(" static uint32 ComputeSize() {\n")
6476 file.Write(
6477 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6478 file.Write(" }\n")
6479 file.Write("\n")
6481 def WriteCmdSetHeader(self, file):
6482 """Writes the cmd's SetHeader function."""
6483 file.Write(" void SetHeader() {\n")
6484 file.Write(" header.SetCmd<ValueType>();\n")
6485 file.Write(" }\n")
6486 file.Write("\n")
6488 def WriteCmdInit(self, file):
6489 """Writes the cmd's Init function."""
6490 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
6491 file.Write(" SetHeader();\n")
6492 args = self.GetCmdArgs()
6493 for arg in args:
6494 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6495 file.Write(" }\n")
6496 file.Write("\n")
6498 def WriteCmdSet(self, file):
6499 """Writes the cmd's Set function."""
6500 copy_args = self.MakeCmdArgString("_", False)
6501 file.Write(" void* Set(void* cmd%s) {\n" %
6502 self.MakeTypedCmdArgString("_", True))
6503 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
6504 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6505 file.Write(" }\n")
6506 file.Write("\n")
6508 def WriteStruct(self, file):
6509 self.type_handler.WriteStruct(self, file)
6511 def WriteDocs(self, file):
6512 self.type_handler.WriteDocs(self, file)
6514 def WriteCmdHelper(self, file):
6515 """Writes the cmd's helper."""
6516 self.type_handler.WriteCmdHelper(self, file)
6518 def WriteServiceImplementation(self, file):
6519 """Writes the service implementation for a command."""
6520 self.type_handler.WriteServiceImplementation(self, file)
6522 def WriteServiceUnitTest(self, file):
6523 """Writes the service implementation for a command."""
6524 self.type_handler.WriteServiceUnitTest(self, file)
6526 def WriteGLES2CLibImplementation(self, file):
6527 """Writes the GLES2 C Lib Implemention."""
6528 self.type_handler.WriteGLES2CLibImplementation(self, file)
6530 def WriteGLES2InterfaceHeader(self, file):
6531 """Writes the GLES2 Interface declaration."""
6532 self.type_handler.WriteGLES2InterfaceHeader(self, file)
6534 def WriteGLES2InterfaceStub(self, file):
6535 """Writes the GLES2 Interface Stub declaration."""
6536 self.type_handler.WriteGLES2InterfaceStub(self, file)
6538 def WriteGLES2InterfaceStubImpl(self, file):
6539 """Writes the GLES2 Interface Stub declaration."""
6540 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
6542 def WriteGLES2ImplementationHeader(self, file):
6543 """Writes the GLES2 Implemention declaration."""
6544 self.type_handler.WriteGLES2ImplementationHeader(self, file)
6546 def WriteGLES2Implementation(self, file):
6547 """Writes the GLES2 Implemention definition."""
6548 self.type_handler.WriteGLES2Implementation(self, file)
6550 def WriteGLES2TraceImplementationHeader(self, file):
6551 """Writes the GLES2 Trace Implemention declaration."""
6552 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
6554 def WriteGLES2TraceImplementation(self, file):
6555 """Writes the GLES2 Trace Implemention definition."""
6556 self.type_handler.WriteGLES2TraceImplementation(self, file)
6558 def WriteGLES2Header(self, file):
6559 """Writes the GLES2 Implemention unit test."""
6560 self.type_handler.WriteGLES2Header(self, file)
6562 def WriteGLES2ImplementationUnitTest(self, file):
6563 """Writes the GLES2 Implemention unit test."""
6564 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
6566 def WriteDestinationInitalizationValidation(self, file):
6567 """Writes the client side destintion initialization validation."""
6568 self.type_handler.WriteDestinationInitalizationValidation(self, file)
6570 def WriteFormatTest(self, file):
6571 """Writes the cmd's format test."""
6572 self.type_handler.WriteFormatTest(self, file)
6575 class PepperInterface(object):
6576 """A class that represents a function."""
6578 def __init__(self, info):
6579 self.name = info["name"]
6580 self.dev = info["dev"]
6582 def GetName(self):
6583 return self.name
6585 def GetInterfaceName(self):
6586 upperint = ""
6587 dev = ""
6588 if self.name:
6589 upperint = "_" + self.name.upper()
6590 if self.dev:
6591 dev = "_DEV"
6592 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
6594 def GetInterfaceString(self):
6595 dev = ""
6596 if self.dev:
6597 dev = "(Dev)"
6598 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6600 def GetStructName(self):
6601 dev = ""
6602 if self.dev:
6603 dev = "_Dev"
6604 return "PPB_OpenGLES2%s%s" % (self.name, dev)
6607 class ImmediateFunction(Function):
6608 """A class that represnets an immediate function command."""
6610 def __init__(self, func):
6611 new_args = []
6612 for arg in func.GetOriginalArgs():
6613 new_arg = arg.GetImmediateVersion()
6614 if new_arg:
6615 new_args.append(new_arg)
6617 cmd_args = []
6618 new_args_for_cmds = []
6619 for arg in func.args_for_cmds:
6620 new_arg = arg.GetImmediateVersion()
6621 if new_arg:
6622 new_args_for_cmds.append(new_arg)
6623 new_arg.AddCmdArgs(cmd_args)
6625 new_init_args = []
6626 for arg in new_args_for_cmds:
6627 arg.AddInitArgs(new_init_args)
6629 Function.__init__(
6630 self,
6631 func.original_name,
6632 "%sImmediate" % func.name,
6633 func.info,
6634 func.return_type,
6635 new_args,
6636 new_args_for_cmds,
6637 cmd_args,
6638 new_init_args,
6640 self.is_immediate = True
6642 def WriteCommandDescription(self, file):
6643 """Overridden from Function"""
6644 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6645 self.original_name)
6647 def WriteServiceImplementation(self, file):
6648 """Overridden from Function"""
6649 self.type_handler.WriteImmediateServiceImplementation(self, file)
6651 def WriteHandlerImplementation(self, file):
6652 """Overridden from Function"""
6653 self.type_handler.WriteImmediateHandlerImplementation(self, file)
6655 def WriteServiceUnitTest(self, file):
6656 """Writes the service implementation for a command."""
6657 self.type_handler.WriteImmediateServiceUnitTest(self, file)
6659 def WriteValidationCode(self, file):
6660 """Overridden from Function"""
6661 self.type_handler.WriteImmediateValidationCode(self, file)
6663 def WriteCmdArgFlag(self, file):
6664 """Overridden from Function"""
6665 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6667 def WriteCmdComputeSize(self, file):
6668 """Overridden from Function"""
6669 self.type_handler.WriteImmediateCmdComputeSize(self, file)
6671 def WriteCmdSetHeader(self, file):
6672 """Overridden from Function"""
6673 self.type_handler.WriteImmediateCmdSetHeader(self, file)
6675 def WriteCmdInit(self, file):
6676 """Overridden from Function"""
6677 self.type_handler.WriteImmediateCmdInit(self, file)
6679 def WriteCmdSet(self, file):
6680 """Overridden from Function"""
6681 self.type_handler.WriteImmediateCmdSet(self, file)
6683 def WriteCmdHelper(self, file):
6684 """Overridden from Function"""
6685 self.type_handler.WriteImmediateCmdHelper(self, file)
6687 def WriteFormatTest(self, file):
6688 """Overridden from Function"""
6689 self.type_handler.WriteImmediateFormatTest(self, file)
6692 class BucketFunction(Function):
6693 """A class that represnets a bucket version of a function command."""
6695 def __init__(self, func):
6696 new_args = []
6697 for arg in func.GetOriginalArgs():
6698 new_arg = arg.GetBucketVersion()
6699 if new_arg:
6700 new_args.append(new_arg)
6702 cmd_args = []
6703 new_args_for_cmds = []
6704 for arg in func.args_for_cmds:
6705 new_arg = arg.GetBucketVersion()
6706 if new_arg:
6707 new_args_for_cmds.append(new_arg)
6708 new_arg.AddCmdArgs(cmd_args)
6710 new_init_args = []
6711 for arg in new_args_for_cmds:
6712 arg.AddInitArgs(new_init_args)
6714 Function.__init__(
6715 self,
6716 func.original_name,
6717 "%sBucket" % func.name,
6718 func.info,
6719 func.return_type,
6720 new_args,
6721 new_args_for_cmds,
6722 cmd_args,
6723 new_init_args,
6726 # def InitFunction(self):
6727 # """Overridden from Function"""
6728 # pass
6730 def WriteCommandDescription(self, file):
6731 """Overridden from Function"""
6732 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6733 self.original_name)
6735 def WriteServiceImplementation(self, file):
6736 """Overridden from Function"""
6737 self.type_handler.WriteBucketServiceImplementation(self, file)
6739 def WriteHandlerImplementation(self, file):
6740 """Overridden from Function"""
6741 self.type_handler.WriteBucketHandlerImplementation(self, file)
6743 def WriteServiceUnitTest(self, file):
6744 """Writes the service implementation for a command."""
6745 self.type_handler.WriteBucketServiceUnitTest(self, file)
6748 def CreateArg(arg_string):
6749 """Creates an Argument."""
6750 arg_parts = arg_string.split()
6751 if len(arg_parts) == 1 and arg_parts[0] == 'void':
6752 return None
6753 # Is this a pointer argument?
6754 elif arg_string.find('*') >= 0:
6755 if arg_parts[0] == 'NonImmediate':
6756 return NonImmediatePointerArgument(
6757 arg_parts[-1],
6758 " ".join(arg_parts[1:-1]))
6759 else:
6760 return PointerArgument(
6761 arg_parts[-1],
6762 " ".join(arg_parts[0:-1]))
6763 # Is this a resource argument? Must come after pointer check.
6764 elif arg_parts[0].startswith('GLidBind'):
6765 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6766 elif arg_parts[0].startswith('GLidZero'):
6767 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6768 elif arg_parts[0].startswith('GLid'):
6769 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6770 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
6771 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6772 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
6773 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6774 elif arg_parts[0].startswith('GLboolean'):
6775 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6776 elif arg_parts[0].startswith('GLintUniformLocation'):
6777 return UniformLocationArgument(arg_parts[-1])
6778 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
6779 not arg_parts[0].startswith('GLintptr')):
6780 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6781 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
6782 arg_parts[0].startswith('GLintptrNotNegative')):
6783 return SizeNotNegativeArgument(arg_parts[-1],
6784 " ".join(arg_parts[0:-1]),
6785 arg_parts[0][0:-11])
6786 elif arg_parts[0].startswith('GLsize'):
6787 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6788 else:
6789 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
6792 class GLGenerator(object):
6793 """A class to generate GL command buffers."""
6795 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6797 def __init__(self, verbose):
6798 self.original_functions = []
6799 self.functions = []
6800 self.verbose = verbose
6801 self.errors = 0
6802 self._function_info = {}
6803 self._empty_type_handler = TypeHandler()
6804 self._empty_function_info = FunctionInfo({}, self._empty_type_handler)
6805 self.pepper_interfaces = []
6806 self.interface_info = {}
6808 self._type_handlers = {
6809 'Bind': BindHandler(),
6810 'Create': CreateHandler(),
6811 'Custom': CustomHandler(),
6812 'Data': DataHandler(),
6813 'Delete': DeleteHandler(),
6814 'DELn': DELnHandler(),
6815 'GENn': GENnHandler(),
6816 'GETn': GETnHandler(),
6817 'GLchar': GLcharHandler(),
6818 'GLcharN': GLcharNHandler(),
6819 'HandWritten': HandWrittenHandler(),
6820 'Is': IsHandler(),
6821 'Manual': ManualHandler(),
6822 'PUT': PUTHandler(),
6823 'PUTn': PUTnHandler(),
6824 'PUTXn': PUTXnHandler(),
6825 'StateSet': StateSetHandler(),
6826 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6827 'StateSetFrontBack': StateSetFrontBackHandler(),
6828 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6829 'StateSetNamedParameter': StateSetNamedParameter(),
6830 'STRn': STRnHandler(),
6831 'Todo': TodoHandler(),
6834 for func_name in _FUNCTION_INFO:
6835 info = _FUNCTION_INFO[func_name]
6836 type = ''
6837 if 'type' in info:
6838 type = info['type']
6839 self._function_info[func_name] = FunctionInfo(info,
6840 self.GetTypeHandler(type))
6841 for interface in _PEPPER_INTERFACES:
6842 interface = PepperInterface(interface)
6843 self.pepper_interfaces.append(interface)
6844 self.interface_info[interface.GetName()] = interface
6846 def AddFunction(self, func):
6847 """Adds a function."""
6848 self.functions.append(func)
6850 def GetTypeHandler(self, name):
6851 """Gets a type info for the given type."""
6852 if len(name):
6853 if name in self._type_handlers:
6854 return self._type_handlers[name]
6855 else:
6856 raise KeyError("no such type handler: %s" % name)
6857 return self._empty_type_handler
6859 def GetFunctionInfo(self, name):
6860 """Gets a type info for the given function name."""
6861 if name in self._function_info:
6862 return self._function_info[name]
6863 return self._empty_function_info
6865 def Log(self, msg):
6866 """Prints something if verbose is true."""
6867 if self.verbose:
6868 print msg
6870 def Error(self, msg):
6871 """Prints an error."""
6872 print "Error: %s" % msg
6873 self.errors += 1
6875 def WriteLicense(self, file):
6876 """Writes the license."""
6877 file.Write(_LICENSE)
6879 def WriteNamespaceOpen(self, file):
6880 """Writes the code for the namespace."""
6881 file.Write("namespace gpu {\n")
6882 file.Write("namespace gles2 {\n")
6883 file.Write("\n")
6885 def WriteNamespaceClose(self, file):
6886 """Writes the code to close the namespace."""
6887 file.Write("} // namespace gles2\n")
6888 file.Write("} // namespace gpu\n")
6889 file.Write("\n")
6891 def ParseArgs(self, arg_string):
6892 """Parses a function arg string."""
6893 args = []
6894 num_pointer_args = 0
6895 parts = arg_string.split(',')
6896 is_gl_enum = False
6897 for arg_string in parts:
6898 if arg_string.startswith('GLenum '):
6899 is_gl_enum = True
6900 arg = CreateArg(arg_string)
6901 if arg:
6902 args.append(arg)
6903 if arg.IsPointer():
6904 num_pointer_args += 1
6905 return (args, num_pointer_args, is_gl_enum)
6907 def ParseGLH(self, filename):
6908 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6909 f = open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6910 functions = f.read()
6911 f.close()
6912 for line in functions.splitlines():
6913 match = self._function_re.match(line)
6914 if match:
6915 func_name = match.group(2)[2:]
6916 func_info = self.GetFunctionInfo(func_name)
6917 if func_info.type != 'Noop':
6918 return_type = match.group(1).strip()
6919 arg_string = match.group(3)
6920 (args, num_pointer_args, is_gl_enum) = self.ParseArgs(arg_string)
6921 # comment in to find out which functions use bare enums.
6922 # if is_gl_enum:
6923 # self.Log("%s uses bare GLenum" % func_name)
6924 args_for_cmds = args
6925 if hasattr(func_info, 'cmd_args'):
6926 (args_for_cmds, num_pointer_args, is_gl_enum) = (
6927 self.ParseArgs(getattr(func_info, 'cmd_args')))
6928 cmd_args = []
6929 for arg in args_for_cmds:
6930 arg.AddCmdArgs(cmd_args)
6931 init_args = []
6932 for arg in args_for_cmds:
6933 arg.AddInitArgs(init_args)
6934 return_arg = CreateArg(return_type + " result")
6935 if return_arg:
6936 init_args.append(return_arg)
6937 f = Function(func_name, func_name, func_info, return_type, args,
6938 args_for_cmds, cmd_args, init_args, num_pointer_args)
6939 self.original_functions.append(f)
6940 gen_cmd = f.GetInfo('gen_cmd')
6941 if gen_cmd == True or gen_cmd == None:
6942 self.AddFunction(f)
6943 f.type_handler.AddImmediateFunction(self, f)
6944 f.type_handler.AddBucketFunction(self, f)
6946 self.Log("Auto Generated Functions : %d" %
6947 len([f for f in self.functions if f.can_auto_generate or
6948 (not f.IsType('') and not f.IsType('Custom') and
6949 not f.IsType('Todo'))]))
6951 funcs = [f for f in self.functions if not f.can_auto_generate and
6952 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
6953 self.Log("Non Auto Generated Functions: %d" % len(funcs))
6955 for f in funcs:
6956 self.Log(" %-10s %-20s gl%s" % (f.info.type, f.return_type, f.name))
6958 def WriteCommandIds(self, filename):
6959 """Writes the command buffer format"""
6960 file = CHeaderWriter(filename)
6961 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
6962 id = 256
6963 for func in self.functions:
6964 file.Write(" %-60s /* %d */ \\\n" %
6965 ("OP(%s)" % func.name, id))
6966 id += 1
6967 file.Write("\n")
6969 file.Write("enum CommandId {\n")
6970 file.Write(" kStartPoint = cmd::kLastCommonId, "
6971 "// All GLES2 commands start after this.\n")
6972 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
6973 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
6974 file.Write("#undef GLES2_CMD_OP\n")
6975 file.Write(" kNumCommands\n")
6976 file.Write("};\n")
6977 file.Write("\n")
6978 file.Close()
6980 def WriteFormat(self, filename):
6981 """Writes the command buffer format"""
6982 file = CHeaderWriter(filename)
6983 for func in self.functions:
6984 if True:
6985 #gen_cmd = func.GetInfo('gen_cmd')
6986 #if gen_cmd == True or gen_cmd == None:
6987 func.WriteStruct(file)
6988 file.Write("\n")
6989 file.Close()
6991 def WriteDocs(self, filename):
6992 """Writes the command buffer doc version of the commands"""
6993 file = CWriter(filename)
6994 for func in self.functions:
6995 if True:
6996 #gen_cmd = func.GetInfo('gen_cmd')
6997 #if gen_cmd == True or gen_cmd == None:
6998 func.WriteDocs(file)
6999 file.Write("\n")
7000 file.Close()
7002 def WriteFormatTest(self, filename):
7003 """Writes the command buffer format test."""
7004 file = CHeaderWriter(
7005 filename,
7006 "// This file contains unit tests for gles2 commmands\n"
7007 "// It is included by gles2_cmd_format_test.cc\n"
7008 "\n")
7010 for func in self.functions:
7011 if True:
7012 #gen_cmd = func.GetInfo('gen_cmd')
7013 #if gen_cmd == True or gen_cmd == None:
7014 func.WriteFormatTest(file)
7016 file.Close()
7018 def WriteCmdHelperHeader(self, filename):
7019 """Writes the gles2 command helper."""
7020 file = CHeaderWriter(filename)
7022 for func in self.functions:
7023 if True:
7024 #gen_cmd = func.GetInfo('gen_cmd')
7025 #if gen_cmd == True or gen_cmd == None:
7026 func.WriteCmdHelper(file)
7028 file.Close()
7030 def WriteServiceContextStateHeader(self, filename):
7031 """Writes the service context state header."""
7032 file = CHeaderWriter(
7033 filename,
7034 "// It is included by context_state.h\n")
7035 file.Write("struct EnableFlags {\n")
7036 file.Write(" EnableFlags();\n")
7037 for capability in _CAPABILITY_FLAGS:
7038 file.Write(" bool %s;\n" % capability['name'])
7039 file.Write("};\n\n")
7041 for state_name in sorted(_STATES.keys()):
7042 state = _STATES[state_name]
7043 for item in state['states']:
7044 file.Write("%s %s;\n" % (item['type'], item['name']))
7045 file.Write("\n")
7047 file.Close()
7049 def WriteClientContextStateHeader(self, filename):
7050 """Writes the client context state header."""
7051 file = CHeaderWriter(
7052 filename,
7053 "// It is included by client_context_state.h\n")
7054 file.Write("struct EnableFlags {\n")
7055 file.Write(" EnableFlags();\n")
7056 for capability in _CAPABILITY_FLAGS:
7057 file.Write(" bool %s;\n" % capability['name'])
7058 file.Write("};\n\n")
7060 file.Close()
7062 def WriteContextStateGetters(self, file, class_name):
7063 """Writes the state getters."""
7064 for gl_type in ["GLint", "GLfloat"]:
7065 file.Write("""
7066 bool %s::GetStateAs%s(
7067 GLenum pname, %s* params, GLsizei* num_written) const {
7068 switch (pname) {
7069 """ % (class_name, gl_type, gl_type))
7070 for state_name in sorted(_STATES.keys()):
7071 state = _STATES[state_name]
7072 if 'enum' in state:
7073 file.Write(" case %s:\n" % state['enum'])
7074 file.Write(" *num_written = %d;\n" % len(state['states']))
7075 file.Write(" if (params) {\n")
7076 for ndx,item in enumerate(state['states']):
7077 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7078 (ndx, gl_type, item['name']))
7079 file.Write(" }\n")
7080 file.Write(" return true;\n")
7081 else:
7082 for item in state['states']:
7083 file.Write(" case %s:\n" % item['enum'])
7084 file.Write(" *num_written = 1;\n")
7085 file.Write(" if (params) {\n")
7086 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7087 (gl_type, item['name']))
7088 file.Write(" }\n")
7089 file.Write(" return true;\n")
7090 for capability in _CAPABILITY_FLAGS:
7091 file.Write(" case GL_%s:\n" % capability['name'].upper())
7092 file.Write(" *num_written = 1;\n")
7093 file.Write(" if (params) {\n")
7094 file.Write(
7095 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7096 (gl_type, capability['name']))
7097 file.Write(" }\n")
7098 file.Write(" return true;\n")
7099 file.Write(""" default:
7100 return false;
7103 """)
7105 def WriteServiceContextStateImpl(self, filename):
7106 """Writes the context state service implementation."""
7107 file = CHeaderWriter(
7108 filename,
7109 "// It is included by context_state.cc\n")
7110 code = []
7111 for capability in _CAPABILITY_FLAGS:
7112 code.append("%s(%s)" %
7113 (capability['name'],
7114 ('false', 'true')['default' in capability]))
7115 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7116 ",\n ".join(code))
7117 file.Write("\n")
7119 file.Write("void ContextState::Initialize() {\n")
7120 for state_name in sorted(_STATES.keys()):
7121 state = _STATES[state_name]
7122 for item in state['states']:
7123 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7124 file.Write("}\n")
7126 file.Write("""
7127 void ContextState::InitCapabilities() const {
7128 """)
7129 for capability in _CAPABILITY_FLAGS:
7130 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7131 (capability['name'].upper(), capability['name']))
7132 file.Write("""}
7134 void ContextState::InitState() const {
7135 """)
7137 # We need to sort the keys so the expectations match
7138 for state_name in sorted(_STATES.keys()):
7139 state = _STATES[state_name]
7140 if state['type'] == 'FrontBack':
7141 num_states = len(state['states'])
7142 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7143 args = []
7144 for item in group:
7145 args.append('%s' % item['name'])
7146 file.Write(
7147 " gl%s(%s, %s);\n" %
7148 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7149 elif state['type'] == 'NamedParameter':
7150 for item in state['states']:
7151 if 'extension_flag' in item:
7152 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7153 item['extension_flag'])
7154 file.Write(" gl%s(%s, %s);\n" %
7155 (state['func'], item['enum'], item['name']))
7156 else:
7157 args = []
7158 for item in state['states']:
7159 args.append('%s' % item['name'])
7160 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7161 file.Write("}\n")
7163 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7164 switch (cap) {
7165 """)
7166 for capability in _CAPABILITY_FLAGS:
7167 file.Write(" case GL_%s:\n" % capability['name'].upper())
7168 file.Write(" return enable_flags.%s;\n" % capability['name'])
7169 file.Write(""" default:
7170 GPU_NOTREACHED();
7171 return false;
7174 """)
7176 self.WriteContextStateGetters(file, "ContextState")
7177 file.Close()
7179 def WriteClientContextStateImpl(self, filename):
7180 """Writes the context state client side implementation."""
7181 file = CHeaderWriter(
7182 filename,
7183 "// It is included by client_context_state.cc\n")
7184 code = []
7185 for capability in _CAPABILITY_FLAGS:
7186 code.append("%s(%s)" %
7187 (capability['name'],
7188 ('false', 'true')['default' in capability]))
7189 file.Write(
7190 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7191 ",\n ".join(code))
7192 file.Write("\n")
7194 file.Write("""
7195 bool ClientContextState::SetCapabilityState(
7196 GLenum cap, bool enabled, bool* changed) {
7197 *changed = false;
7198 switch (cap) {
7199 """)
7200 for capability in _CAPABILITY_FLAGS:
7201 file.Write(" case GL_%s:\n" % capability['name'].upper())
7202 file.Write(""" if (enable_flags.%(name)s != enabled) {
7203 *changed = true;
7204 enable_flags.%(name)s = enabled;
7206 return true;
7207 """ % capability)
7208 file.Write(""" default:
7209 return false;
7212 """)
7213 file.Write("""bool ClientContextState::GetEnabled(
7214 GLenum cap, bool* enabled) const {
7215 switch (cap) {
7216 """)
7217 for capability in _CAPABILITY_FLAGS:
7218 file.Write(" case GL_%s:\n" % capability['name'].upper())
7219 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7220 file.Write(" return true;\n")
7221 file.Write(""" default:
7222 return false;
7225 """)
7226 file.Close()
7228 def WriteServiceImplementation(self, filename):
7229 """Writes the service decorder implementation."""
7230 file = CHeaderWriter(
7231 filename,
7232 "// It is included by gles2_cmd_decoder.cc\n")
7234 for func in self.functions:
7235 if True:
7236 #gen_cmd = func.GetInfo('gen_cmd')
7237 #if gen_cmd == True or gen_cmd == None:
7238 func.WriteServiceImplementation(file)
7240 file.Write("""
7241 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7242 switch (cap) {
7243 """)
7244 for capability in _CAPABILITY_FLAGS:
7245 file.Write(" case GL_%s:\n" % capability['name'].upper())
7246 if 'state_flag' in capability:
7247 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7248 state_.enable_flags.%(name)s = enabled;
7249 %(state_flag)s = true;
7251 return false;
7252 """ % capability)
7253 else:
7254 file.Write(""" state_.enable_flags.%(name)s = enabled;
7255 return true;
7256 """ % capability)
7257 file.Write(""" default:
7258 NOTREACHED();
7259 return false;
7262 """)
7263 file.Close()
7265 def WriteServiceUnitTests(self, filename):
7266 """Writes the service decorder unit tests."""
7267 num_tests = len(self.functions)
7268 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7269 count = 0
7270 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7271 count += 1
7272 name = filename % count
7273 file = CHeaderWriter(
7274 name,
7275 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7276 file.SetFileNum(count)
7277 end = test_num + FUNCTIONS_PER_FILE
7278 if end > num_tests:
7279 end = num_tests
7280 for idx in range(test_num, end):
7281 func = self.functions[idx]
7282 if True:
7283 #gen_cmd = func.GetInfo('gen_cmd')
7284 #if gen_cmd == True or gen_cmd == None:
7285 if func.GetInfo('unit_test') == False:
7286 file.Write("// TODO(gman): %s\n" % func.name)
7287 else:
7288 func.WriteServiceUnitTest(file)
7290 file.Close()
7291 file = CHeaderWriter(
7292 filename % 0,
7293 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7294 file.Write(
7295 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7296 """)
7297 for capability in _CAPABILITY_FLAGS:
7298 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7299 (capability['name'].upper(),
7300 ('false', 'true')['default' in capability]))
7301 file.Write("""}
7303 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7304 """)
7306 # We need to sort the keys so the expectations match
7307 for state_name in sorted(_STATES.keys()):
7308 state = _STATES[state_name]
7309 if state['type'] == 'FrontBack':
7310 num_states = len(state['states'])
7311 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7312 args = []
7313 for item in group:
7314 if 'expected' in item:
7315 args.append(item['expected'])
7316 else:
7317 args.append(item['default'])
7318 file.Write(
7319 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7320 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7321 file.Write(" .Times(1)\n")
7322 file.Write(" .RetiresOnSaturation();\n")
7323 elif state['type'] == 'NamedParameter':
7324 for item in state['states']:
7325 if 'extension_flag' in item:
7326 continue
7327 file.Write(
7328 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7329 (state['func'], item['enum'], item['default']))
7330 file.Write(" .Times(1)\n")
7331 file.Write(" .RetiresOnSaturation();\n")
7332 else:
7333 args = []
7334 for item in state['states']:
7335 if 'expected' in item:
7336 args.append(item['expected'])
7337 else:
7338 args.append(item['default'])
7339 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7340 (state['func'], ", ".join(args)))
7341 file.Write(" .Times(1)\n")
7342 file.Write(" .RetiresOnSaturation();\n")
7343 file.Write("""}
7344 """)
7345 file.Close()
7347 def WriteGLES2Header(self, filename):
7348 """Writes the GLES2 header."""
7349 file = CHeaderWriter(
7350 filename,
7351 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7353 for func in self.original_functions:
7354 func.WriteGLES2Header(file)
7356 file.Write("\n")
7357 file.Close()
7359 def WriteGLES2CLibImplementation(self, filename):
7360 """Writes the GLES2 c lib implementation."""
7361 file = CHeaderWriter(
7362 filename,
7363 "// These functions emulate GLES2 over command buffers.\n")
7365 for func in self.original_functions:
7366 func.WriteGLES2CLibImplementation(file)
7368 file.Write("""
7369 namespace gles2 {
7371 extern const NameToFunc g_gles2_function_table[] = {
7372 """)
7373 for func in self.original_functions:
7374 file.Write(
7375 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7376 (func.name, func.name))
7377 file.Write(""" { NULL, NULL, },
7380 } // namespace gles2
7381 """)
7382 file.Close()
7384 def WriteGLES2InterfaceHeader(self, filename):
7385 """Writes the GLES2 interface header."""
7386 file = CHeaderWriter(
7387 filename,
7388 "// This file is included by gles2_interface.h to declare the\n"
7389 "// GL api functions.\n")
7390 for func in self.original_functions:
7391 func.WriteGLES2InterfaceHeader(file)
7392 file.Close()
7394 def WriteGLES2InterfaceStub(self, filename):
7395 """Writes the GLES2 interface stub header."""
7396 file = CHeaderWriter(
7397 filename,
7398 "// This file is included by gles2_interface_stub.h.\n")
7399 for func in self.original_functions:
7400 func.WriteGLES2InterfaceStub(file)
7401 file.Close()
7403 def WriteGLES2InterfaceStubImpl(self, filename):
7404 """Writes the GLES2 interface header."""
7405 file = CHeaderWriter(
7406 filename,
7407 "// This file is included by gles2_interface_stub.cc.\n")
7408 for func in self.original_functions:
7409 func.WriteGLES2InterfaceStubImpl(file)
7410 file.Close()
7412 def WriteGLES2ImplementationHeader(self, filename):
7413 """Writes the GLES2 Implementation header."""
7414 file = CHeaderWriter(
7415 filename,
7416 "// This file is included by gles2_implementation.h to declare the\n"
7417 "// GL api functions.\n")
7418 for func in self.original_functions:
7419 func.WriteGLES2ImplementationHeader(file)
7420 file.Close()
7422 def WriteGLES2Implementation(self, filename):
7423 """Writes the GLES2 Implementation."""
7424 file = CHeaderWriter(
7425 filename,
7426 "// This file is included by gles2_implementation.cc to define the\n"
7427 "// GL api functions.\n")
7428 for func in self.original_functions:
7429 func.WriteGLES2Implementation(file)
7430 file.Close()
7432 def WriteGLES2TraceImplementationHeader(self, filename):
7433 """Writes the GLES2 Trace Implementation header."""
7434 file = CHeaderWriter(
7435 filename,
7436 "// This file is included by gles2_trace_implementation.h\n")
7437 for func in self.original_functions:
7438 func.WriteGLES2TraceImplementationHeader(file)
7439 file.Close()
7441 def WriteGLES2TraceImplementation(self, filename):
7442 """Writes the GLES2 Trace Implementation."""
7443 file = CHeaderWriter(
7444 filename,
7445 "// This file is included by gles2_trace_implementation.cc\n")
7446 for func in self.original_functions:
7447 func.WriteGLES2TraceImplementation(file)
7448 file.Close()
7450 def WriteGLES2ImplementationUnitTests(self, filename):
7451 """Writes the GLES2 helper header."""
7452 file = CHeaderWriter(
7453 filename,
7454 "// This file is included by gles2_implementation.h to declare the\n"
7455 "// GL api functions.\n")
7456 for func in self.original_functions:
7457 func.WriteGLES2ImplementationUnitTest(file)
7458 file.Close()
7460 def WriteServiceUtilsHeader(self, filename):
7461 """Writes the gles2 auto generated utility header."""
7462 file = CHeaderWriter(filename)
7463 for enum in sorted(_ENUM_LISTS.keys()):
7464 file.Write("ValueValidator<%s> %s;\n" %
7465 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7466 file.Write("\n")
7467 file.Close()
7469 def WriteServiceUtilsImplementation(self, filename):
7470 """Writes the gles2 auto generated utility implementation."""
7471 file = CHeaderWriter(filename)
7472 enums = sorted(_ENUM_LISTS.keys())
7473 for enum in enums:
7474 if len(_ENUM_LISTS[enum]['valid']) > 0:
7475 file.Write("static const %s valid_%s_table[] = {\n" %
7476 (_ENUM_LISTS[enum]['type'], ToUnderscore(enum)))
7477 for value in _ENUM_LISTS[enum]['valid']:
7478 file.Write(" %s,\n" % value)
7479 file.Write("};\n")
7480 file.Write("\n")
7481 file.Write("Validators::Validators()\n")
7482 pre = ': '
7483 post = ','
7484 for count, enum in enumerate(enums):
7485 if count + 1 == len(enums):
7486 post = ' {'
7487 if len(_ENUM_LISTS[enum]['valid']) > 0:
7488 code = """ %(pre)s%(name)s(
7489 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7491 else:
7492 code = """ %(pre)s%(name)s()%(post)s
7494 file.Write(code % {
7495 'name': ToUnderscore(enum),
7496 'pre': pre,
7497 'post': post,
7499 pre = ' '
7500 file.Write("}\n\n");
7501 file.Close()
7503 def WriteCommonUtilsHeader(self, filename):
7504 """Writes the gles2 common utility header."""
7505 file = CHeaderWriter(filename)
7506 enums = sorted(_ENUM_LISTS.keys())
7507 for enum in enums:
7508 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7509 file.Write("static std::string GetString%s(uint32 value);\n" % enum)
7510 file.Write("\n")
7511 file.Close()
7513 def WriteCommonUtilsImpl(self, filename):
7514 """Writes the gles2 common utility header."""
7515 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7516 dict = {}
7517 for fname in ['../../third_party/khronos/GLES2/gl2.h',
7518 '../../third_party/khronos/GLES2/gl2ext.h',
7519 '../../gpu/GLES2/gl2chromium.h',
7520 '../../gpu/GLES2/gl2extchromium.h']:
7521 lines = open(fname).readlines()
7522 for line in lines:
7523 m = enum_re.match(line)
7524 if m:
7525 name = m.group(1)
7526 value = m.group(2)
7527 if len(value) <= 10 and not value in dict:
7528 dict[value] = name
7530 file = CHeaderWriter(filename)
7531 file.Write("static const GLES2Util::EnumToString "
7532 "enum_to_string_table[] = {\n")
7533 for value in dict:
7534 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
7535 file.Write("""};
7537 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7538 enum_to_string_table;
7539 const size_t GLES2Util::enum_to_string_table_len_ =
7540 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7542 """)
7544 enums = sorted(_ENUM_LISTS.keys())
7545 for enum in enums:
7546 if _ENUM_LISTS[enum]['type'] == 'GLenum':
7547 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7548 enum)
7549 if len(_ENUM_LISTS[enum]['valid']) > 0:
7550 file.Write(" static const EnumToString string_table[] = {\n")
7551 for value in _ENUM_LISTS[enum]['valid']:
7552 file.Write(' { %s, "%s" },\n' % (value, value))
7553 file.Write(""" };
7554 return GLES2Util::GetQualifiedEnumString(
7555 string_table, arraysize(string_table), value);
7558 """)
7559 else:
7560 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7561 NULL, 0, value);
7564 """)
7565 file.Close()
7567 def WritePepperGLES2Interface(self, filename, dev):
7568 """Writes the Pepper OpenGLES interface definition."""
7569 file = CHeaderWriter(
7570 filename,
7571 "// OpenGL ES interface.\n",
7574 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7575 if dev:
7576 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7577 else:
7578 file.Write("\n#ifndef __gl2_h_\n")
7579 for (k, v) in _GL_TYPES.iteritems():
7580 file.Write("typedef %s %s;\n" % (v, k))
7581 file.Write("#endif // __gl2_h_\n\n")
7583 for interface in self.pepper_interfaces:
7584 if interface.dev != dev:
7585 continue
7586 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7587 (interface.GetInterfaceName(), interface.GetInterfaceString()))
7588 file.Write("#define %s %s_1_0\n" %
7589 (interface.GetInterfaceName(), interface.GetInterfaceName()))
7591 file.Write("\nstruct %s {\n" % interface.GetStructName())
7592 for func in self.original_functions:
7593 if not func.InPepperInterface(interface):
7594 continue
7596 original_arg = func.MakeTypedOriginalArgString("")
7597 context_arg = "PP_Resource context"
7598 if len(original_arg):
7599 arg = context_arg + ", " + original_arg
7600 else:
7601 arg = context_arg
7602 file.Write(" %s (*%s)(%s);\n" % (func.return_type, func.name, arg))
7603 file.Write("};\n\n")
7606 file.Close()
7608 def WritePepperGLES2Implementation(self, filename):
7609 """Writes the Pepper OpenGLES interface implementation."""
7611 file = CWriter(filename)
7612 file.Write(_LICENSE)
7613 file.Write(_DO_NOT_EDIT_WARNING)
7615 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7616 file.Write("#include \"base/logging.h\"\n")
7617 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7618 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7619 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7621 file.Write("namespace ppapi {\n\n")
7622 file.Write("namespace {\n\n")
7624 file.Write("gpu::gles2::GLES2Implementation*"
7625 " GetGLES(PP_Resource context) {\n")
7626 file.Write(" thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7627 " enter_g3d(context, false);\n")
7628 file.Write(" DCHECK(enter_g3d.succeeded());\n")
7629 file.Write(" return static_cast<PPB_Graphics3D_Shared*>"
7630 "(enter_g3d.object())->gles2_impl();\n")
7631 file.Write("}\n\n")
7633 for func in self.original_functions:
7634 if not func.InAnyPepperExtension():
7635 continue
7637 original_arg = func.MakeTypedOriginalArgString("")
7638 context_arg = "PP_Resource context_id"
7639 if len(original_arg):
7640 arg = context_arg + ", " + original_arg
7641 else:
7642 arg = context_arg
7643 file.Write("%s %s(%s) {\n" % (func.return_type, func.name, arg))
7645 return_str = "" if func.return_type == "void" else "return "
7646 file.Write(" %sGetGLES(context_id)->%s(%s);\n" %
7647 (return_str, func.original_name,
7648 func.MakeOriginalArgString("")))
7649 file.Write("}\n\n")
7651 file.Write("} // namespace\n")
7653 for interface in self.pepper_interfaces:
7654 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7655 (interface.GetStructName(), interface.GetName()))
7656 file.Write(" static const struct %s "
7657 "ppb_opengles2 = {\n" % interface.GetStructName())
7658 file.Write(" &")
7659 file.Write(",\n &".join(
7660 f.name for f in self.original_functions
7661 if f.InPepperInterface(interface)))
7662 file.Write("\n")
7664 file.Write(" };\n")
7665 file.Write(" return &ppb_opengles2;\n")
7666 file.Write("}\n")
7668 file.Write("} // namespace ppapi\n")
7669 file.Close()
7671 def WriteGLES2ToPPAPIBridge(self, filename):
7672 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7674 file = CWriter(filename)
7675 file.Write(_LICENSE)
7676 file.Write(_DO_NOT_EDIT_WARNING)
7678 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7679 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7680 file.Write("#endif\n")
7681 file.Write("#include <GLES2/gl2.h>\n")
7682 file.Write("#include <GLES2/gl2ext.h>\n")
7683 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7685 for func in self.original_functions:
7686 if not func.InAnyPepperExtension():
7687 continue
7689 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
7691 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7692 (func.return_type, func.name,
7693 func.MakeTypedOriginalArgString("")))
7694 return_str = "" if func.return_type == "void" else "return "
7695 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
7696 original_arg = func.MakeOriginalArgString("")
7697 context_arg = "glGetCurrentContextPPAPI()"
7698 if len(original_arg):
7699 arg = context_arg + ", " + original_arg
7700 else:
7701 arg = context_arg
7702 if interface.GetName():
7703 file.Write(" const struct %s* ext = %s;\n" %
7704 (interface.GetStructName(), interface_str))
7705 file.Write(" if (ext)\n")
7706 file.Write(" %sext->%s(%s);\n" %
7707 (return_str, func.name, arg))
7708 if return_str:
7709 file.Write(" %s0;\n" % return_str)
7710 else:
7711 file.Write(" %s%s->%s(%s);\n" %
7712 (return_str, interface_str, func.name, arg))
7713 file.Write("}\n\n")
7714 file.Close()
7716 def main(argv):
7717 """This is the main function."""
7718 parser = OptionParser()
7719 parser.add_option(
7720 "-g", "--generate-implementation-templates", action="store_true",
7721 help="generates files that are generally hand edited..")
7722 parser.add_option(
7723 "--alternate-mode", type="choice",
7724 choices=("ppapi", "chrome_ppapi", "chrome_ppapi_proxy", "nacl_ppapi"),
7725 help="generate files for other projects. \"ppapi\" will generate ppapi "
7726 "bindings. \"chrome_ppapi\" generate chrome implementation for ppapi. "
7727 "\"chrome_ppapi_proxy\" will generate the glue for the chrome IPC ppapi"
7728 "proxy. \"nacl_ppapi\" will generate NaCl implementation for ppapi")
7729 parser.add_option(
7730 "--output-dir",
7731 help="base directory for resulting files, under chrome/src. default is "
7732 "empty. Use this if you want the result stored under gen.")
7733 parser.add_option(
7734 "-v", "--verbose", action="store_true",
7735 help="prints more output.")
7737 (options, args) = parser.parse_args(args=argv)
7739 # Add in states and capabilites to GLState
7740 for state_name in sorted(_STATES.keys()):
7741 state = _STATES[state_name]
7742 if 'enum' in state:
7743 _ENUM_LISTS['GLState']['valid'].append(state['enum'])
7744 else:
7745 for item in state['states']:
7746 if 'extension_flag' in item:
7747 continue
7748 _ENUM_LISTS['GLState']['valid'].append(item['enum'])
7749 for capability in _CAPABILITY_FLAGS:
7750 _ENUM_LISTS['GLState']['valid'].append("GL_%s" % capability['name'].upper())
7752 # This script lives under gpu/command_buffer, cd to base directory.
7753 os.chdir(os.path.dirname(__file__) + "/../..")
7755 gen = GLGenerator(options.verbose)
7756 gen.ParseGLH("common/GLES2/gl2.h")
7758 # Support generating files under gen/
7759 if options.output_dir != None:
7760 os.chdir(options.output_dir)
7762 if options.alternate_mode == "ppapi":
7763 # To trigger this action, do "make ppapi_gles_bindings"
7764 os.chdir("ppapi");
7765 gen.WritePepperGLES2Interface("c/ppb_opengles2.h", False)
7766 gen.WritePepperGLES2Interface("c/dev/ppb_opengles2ext_dev.h", True)
7767 gen.WriteGLES2ToPPAPIBridge("lib/gl/gles2/gles2.c")
7769 elif options.alternate_mode == "chrome_ppapi":
7770 # To trigger this action, do "make ppapi_gles_implementation"
7771 gen.WritePepperGLES2Implementation(
7772 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7774 else:
7775 os.chdir("gpu/command_buffer")
7776 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7777 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
7778 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7779 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7780 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7781 gen.WriteGLES2InterfaceStubImpl(
7782 "client/gles2_interface_stub_impl_autogen.h")
7783 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7784 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7785 gen.WriteGLES2ImplementationUnitTests(
7786 "client/gles2_implementation_unittest_autogen.h")
7787 gen.WriteGLES2TraceImplementationHeader(
7788 "client/gles2_trace_implementation_autogen.h")
7789 gen.WriteGLES2TraceImplementation(
7790 "client/gles2_trace_implementation_impl_autogen.h")
7791 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7792 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7793 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7794 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
7795 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7796 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7797 gen.WriteClientContextStateImpl(
7798 "client/client_context_state_impl_autogen.h")
7799 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7800 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7801 gen.WriteServiceUtilsImplementation(
7802 "service/gles2_cmd_validation_implementation_autogen.h")
7803 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7804 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7805 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7807 if gen.errors > 0:
7808 print "%d errors" % gen.errors
7809 return 1
7810 return 0
7813 if __name__ == '__main__':
7814 sys.exit(main(sys.argv[1:]))