1#!/usr/bin/python3
2#
3# Copyright 2017 The ANGLE Project Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6#
7# generate_entry_points.py:
8#   Generates the OpenGL bindings and entry point layers for ANGLE.
9#   NOTE: don't run this script directly. Run scripts/run_code_generation.py.
10
11import sys, os, pprint, json
12import registry_xml
13from registry_xml import apis, script_relative, strip_api_prefix
14
15# Paths
16CL_STUBS_HEADER_PATH = "../src/libGLESv2/cl_stubs_autogen.h"
17EGL_GET_LABELED_OBJECT_DATA_PATH = "../src/libGLESv2/egl_get_labeled_object_data.json"
18EGL_STUBS_HEADER_PATH = "../src/libGLESv2/egl_stubs_autogen.h"
19EGL_EXT_STUBS_HEADER_PATH = "../src/libGLESv2/egl_ext_stubs_autogen.h"
20
21# List of GLES1 extensions for which we don't need to add Context.h decls.
22GLES1_NO_CONTEXT_DECL_EXTENSIONS = [
23    "GL_OES_framebuffer_object",
24]
25
26# This is a list of exceptions for entry points which don't want to have
27# the EVENT macro. This is required for some debug marker entry points.
28NO_EVENT_MARKER_EXCEPTIONS_LIST = sorted([
29    "glPushGroupMarkerEXT",
30    "glPopGroupMarkerEXT",
31    "glInsertEventMarkerEXT",
32])
33
34# glRenderbufferStorageMultisampleEXT aliases glRenderbufferStorageMultisample on desktop GL, and is
35# marked as such in the registry.  However, that is not correct for GLES where this entry point
36# comes from GL_EXT_multisampled_render_to_texture which is never promoted to core GLES.
37ALIASING_EXCEPTIONS = [
38    'glRenderbufferStorageMultisampleEXT',
39    'renderbufferStorageMultisampleEXT',
40]
41
42# These are the entry points which potentially are used first by an application
43# and require that the back ends are initialized before the front end is called.
44INIT_DICT = {
45    "clGetPlatformIDs": "false",
46    "clGetPlatformInfo": "false",
47    "clGetDeviceIDs": "false",
48    "clCreateContext": "false",
49    "clCreateContextFromType": "false",
50    "clIcdGetPlatformIDsKHR": "true",
51}
52
53# Strip these suffixes from Context entry point names. NV is excluded (for now).
54STRIP_SUFFIXES = ["ANDROID", "ANGLE", "EXT", "KHR", "OES", "CHROMIUM", "OVR"]
55
56TEMPLATE_ENTRY_POINT_HEADER = """\
57// GENERATED FILE - DO NOT EDIT.
58// Generated by {script_name} using data from {data_source_name}.
59//
60// Copyright 2020 The ANGLE Project Authors. All rights reserved.
61// Use of this source code is governed by a BSD-style license that can be
62// found in the LICENSE file.
63//
64// entry_points_{annotation_lower}_autogen.h:
65//   Defines the {comment} entry points.
66
67#ifndef {lib}_ENTRY_POINTS_{annotation_upper}_AUTOGEN_H_
68#define {lib}_ENTRY_POINTS_{annotation_upper}_AUTOGEN_H_
69
70{includes}
71
72{entry_points}
73
74#endif  // {lib}_ENTRY_POINTS_{annotation_upper}_AUTOGEN_H_
75"""
76
77TEMPLATE_ENTRY_POINT_SOURCE = """\
78// GENERATED FILE - DO NOT EDIT.
79// Generated by {script_name} using data from {data_source_name}.
80//
81// Copyright 2020 The ANGLE Project Authors. All rights reserved.
82// Use of this source code is governed by a BSD-style license that can be
83// found in the LICENSE file.
84//
85// entry_points_{annotation_lower}_autogen.cpp:
86//   Defines the {comment} entry points.
87
88{includes}
89
90{entry_points}
91"""
92
93TEMPLATE_ENTRY_POINTS_ENUM_HEADER = """\
94// GENERATED FILE - DO NOT EDIT.
95// Generated by {script_name} using data from {data_source_name}.
96//
97// Copyright 2020 The ANGLE Project Authors. All rights reserved.
98// Use of this source code is governed by a BSD-style license that can be
99// found in the LICENSE file.
100//
101// entry_points_enum_autogen.h:
102//   Defines the {lib} entry points enumeration.
103
104#ifndef COMMON_ENTRYPOINTSENUM_AUTOGEN_H_
105#define COMMON_ENTRYPOINTSENUM_AUTOGEN_H_
106
107namespace angle
108{{
109enum class EntryPoint
110{{
111{entry_points_list}
112}};
113
114const char *GetEntryPointName(EntryPoint ep);
115}}  // namespace angle
116#endif  // COMMON_ENTRY_POINTS_ENUM_AUTOGEN_H_
117"""
118
119TEMPLATE_ENTRY_POINTS_NAME_CASE = """\
120        case EntryPoint::{enum}:
121            return "{cmd}";"""
122
123TEMPLATE_ENTRY_POINTS_ENUM_SOURCE = """\
124// GENERATED FILE - DO NOT EDIT.
125// Generated by {script_name} using data from {data_source_name}.
126//
127// Copyright 2020 The ANGLE Project Authors. All rights reserved.
128// Use of this source code is governed by a BSD-style license that can be
129// found in the LICENSE file.
130//
131// entry_points_enum_autogen.cpp:
132//   Helper methods for the {lib} entry points enumeration.
133
134#include "common/entry_points_enum_autogen.h"
135
136#include "common/debug.h"
137
138namespace angle
139{{
140const char *GetEntryPointName(EntryPoint ep)
141{{
142    switch (ep)
143    {{
144{entry_points_name_cases}
145        default:
146            UNREACHABLE();
147            return "error";
148    }}
149}}
150}}  // namespace angle
151"""
152
153TEMPLATE_LIB_ENTRY_POINT_SOURCE = """\
154// GENERATED FILE - DO NOT EDIT.
155// Generated by {script_name} using data from {data_source_name}.
156//
157// Copyright 2020 The ANGLE Project Authors. All rights reserved.
158// Use of this source code is governed by a BSD-style license that can be
159// found in the LICENSE file.
160//
161// {lib_name}_autogen.cpp: Implements the exported {lib_description} functions.
162
163{includes}
164extern "C" {{
165{entry_points}
166}} // extern "C"
167"""
168
169TEMPLATE_ENTRY_POINT_DECL = """{angle_export}{return_type} {export_def} {name}({params});"""
170
171TEMPLATE_GLES_ENTRY_POINT_NO_RETURN = """\
172void GL_APIENTRY GL_{name}({params})
173{{
174    Context *context = {context_getter};
175    {event_comment}EVENT(context, GL{name}, "context = %d{comma_if_needed}{format_params}", CID(context){comma_if_needed}{pass_params});
176
177    if ({valid_context_check})
178    {{{packed_gl_enum_conversions}
179        std::unique_lock<angle::GlobalMutex> shareContextLock = GetContextLock(context);
180        bool isCallValid = (context->skipValidation() || Validate{name}({validate_params}));
181        if (isCallValid)
182        {{
183            context->{name_lower_no_suffix}({internal_params});
184        }}
185        ANGLE_CAPTURE({name}, isCallValid, {validate_params});
186    }}
187    else
188    {{
189        {constext_lost_error_generator}
190    }}
191}}
192"""
193
194TEMPLATE_GLES_ENTRY_POINT_WITH_RETURN = """\
195{return_type} GL_APIENTRY GL_{name}({params})
196{{
197    Context *context = {context_getter};
198    {event_comment}EVENT(context, GL{name}, "context = %d{comma_if_needed}{format_params}", CID(context){comma_if_needed}{pass_params});
199
200    {return_type} returnValue;
201    if ({valid_context_check})
202    {{{packed_gl_enum_conversions}
203        std::unique_lock<angle::GlobalMutex> shareContextLock = GetContextLock(context);
204        bool isCallValid = (context->skipValidation() || Validate{name}({validate_params}));
205        if (isCallValid)
206        {{
207            returnValue = context->{name_lower_no_suffix}({internal_params});
208        }}
209        else
210        {{
211            returnValue = GetDefaultReturnValue<angle::EntryPoint::GL{name}, {return_type}>();
212    }}
213        ANGLE_CAPTURE({name}, isCallValid, {validate_params}, returnValue);
214    }}
215    else
216    {{
217        {constext_lost_error_generator}
218        returnValue = GetDefaultReturnValue<angle::EntryPoint::GL{name}, {return_type}>();
219    }}
220    return returnValue;
221}}
222"""
223
224TEMPLATE_EGL_ENTRY_POINT_NO_RETURN = """\
225void EGLAPIENTRY EGL_{name}({params})
226{{
227    ANGLE_SCOPED_GLOBAL_LOCK();
228    EGL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
229
230    Thread *thread = egl::GetCurrentThread();
231
232    {packed_gl_enum_conversions}
233
234    ANGLE_EGL_VALIDATE_VOID(thread, {name}, {labeled_object}, {internal_params});
235
236    {name}(thread{comma_if_needed}{internal_params});
237}}
238"""
239
240TEMPLATE_EGL_ENTRY_POINT_WITH_RETURN = """\
241{return_type} EGLAPIENTRY EGL_{name}({params})
242{{
243    ANGLE_SCOPED_GLOBAL_LOCK();
244    EGL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
245
246    Thread *thread = egl::GetCurrentThread();
247
248    {packed_gl_enum_conversions}
249
250    ANGLE_EGL_VALIDATE(thread, {name}, {labeled_object}, {return_type}{comma_if_needed}{internal_params});
251
252    return {name}(thread{comma_if_needed}{internal_params});
253}}
254"""
255
256TEMPLATE_CL_ENTRY_POINT_NO_RETURN = """\
257void CL_API_CALL cl{name}({params})
258{{
259    CL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
260
261    {packed_gl_enum_conversions}
262
263    ANGLE_CL_VALIDATE_VOID({name}{comma_if_needed}{internal_params});
264
265    {name}({internal_params});
266}}
267"""
268
269TEMPLATE_CL_ENTRY_POINT_WITH_RETURN_ERROR = """\
270cl_int CL_API_CALL cl{name}({params})
271{{{initialization}
272    CL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
273
274    {packed_gl_enum_conversions}
275
276    ANGLE_CL_VALIDATE_ERROR({name}{comma_if_needed}{internal_params});
277
278    return {name}({internal_params});
279}}
280"""
281
282TEMPLATE_CL_ENTRY_POINT_WITH_ERRCODE_RET = """\
283{return_type} CL_API_CALL cl{name}({params})
284{{{initialization}
285    CL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
286
287    {packed_gl_enum_conversions}
288
289    ANGLE_CL_VALIDATE_ERRCODE_RET({name}{comma_if_needed}{internal_params});
290
291    cl_int errorCode = CL_SUCCESS;
292    {return_type} object = {name}({internal_params}, errorCode);
293
294    ASSERT((errorCode == CL_SUCCESS) == (object != nullptr));
295    if (errcode_ret != nullptr)
296    {{
297        *errcode_ret = errorCode;
298    }}
299    return object;
300}}
301"""
302
303TEMPLATE_CL_ENTRY_POINT_WITH_RETURN_POINTER = """\
304{return_type} CL_API_CALL cl{name}({params})
305{{{initialization}
306    CL_EVENT({name}, "{format_params}"{comma_if_needed}{pass_params});
307
308    {packed_gl_enum_conversions}
309
310    ANGLE_CL_VALIDATE_POINTER({name}{comma_if_needed}{internal_params});
311
312    return {name}({internal_params});
313}}
314"""
315
316TEMPLATE_CL_STUBS_HEADER = """\
317// GENERATED FILE - DO NOT EDIT.
318// Generated by {script_name} using data from {data_source_name}.
319//
320// Copyright 2021 The ANGLE Project Authors. All rights reserved.
321// Use of this source code is governed by a BSD-style license that can be
322// found in the LICENSE file.
323//
324// {annotation_lower}_stubs_autogen.h: Stubs for {title} entry points.
325
326#ifndef LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
327#define LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
328
329#include "libANGLE/CLtypes.h"
330
331namespace cl
332{{
333{stubs}
334}}  // namespace cl
335#endif  // LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
336"""
337
338TEMPLATE_EGL_STUBS_HEADER = """\
339// GENERATED FILE - DO NOT EDIT.
340// Generated by {script_name} using data from {data_source_name}.
341//
342// Copyright 2020 The ANGLE Project Authors. All rights reserved.
343// Use of this source code is governed by a BSD-style license that can be
344// found in the LICENSE file.
345//
346// {annotation_lower}_stubs_autogen.h: Stubs for {title} entry points.
347
348#ifndef LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
349#define LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
350
351#include <EGL/egl.h>
352#include <EGL/eglext.h>
353
354#include "common/PackedEGLEnums_autogen.h"
355
356namespace gl
357{{
358class Context;
359}}  // namespace gl
360
361namespace egl
362{{
363class AttributeMap;
364class Device;
365class Display;
366class Image;
367class Stream;
368class Surface;
369class Sync;
370class Thread;
371struct Config;
372
373{stubs}
374}}  // namespace egl
375#endif  // LIBGLESV2_{annotation_upper}_STUBS_AUTOGEN_H_
376"""
377
378CONTEXT_HEADER = """\
379// GENERATED FILE - DO NOT EDIT.
380// Generated by {script_name} using data from {data_source_name}.
381//
382// Copyright 2020 The ANGLE Project Authors. All rights reserved.
383// Use of this source code is governed by a BSD-style license that can be
384// found in the LICENSE file.
385//
386// Context_{annotation_lower}_autogen.h: Creates a macro for interfaces in Context.
387
388#ifndef ANGLE_CONTEXT_{annotation_upper}_AUTOGEN_H_
389#define ANGLE_CONTEXT_{annotation_upper}_AUTOGEN_H_
390
391#define ANGLE_{annotation_upper}_CONTEXT_API \\
392{interface}
393
394#endif // ANGLE_CONTEXT_API_{version}_AUTOGEN_H_
395"""
396
397CONTEXT_DECL_FORMAT = """    {return_type} {name_lower_no_suffix}({internal_params}){maybe_const}; \\"""
398
399TEMPLATE_CL_ENTRY_POINT_EXPORT = """\
400{return_type} CL_API_CALL cl{name}({params})
401{{
402    return cl::GetDispatch().cl{name}({internal_params});
403}}
404"""
405
406TEMPLATE_GL_ENTRY_POINT_EXPORT = """\
407{return_type} GL_APIENTRY gl{name}({params})
408{{
409    return GL_{name}({internal_params});
410}}
411"""
412
413TEMPLATE_EGL_ENTRY_POINT_EXPORT = """\
414{return_type} EGLAPIENTRY egl{name}({params})
415{{
416    EnsureEGLLoaded();
417    return EGL_{name}({internal_params});
418}}
419"""
420
421TEMPLATE_GLEXT_FUNCTION_POINTER = """typedef {return_type}(GL_APIENTRYP PFN{name_upper}PROC)({params});"""
422TEMPLATE_GLEXT_FUNCTION_PROTOTYPE = """{apicall} {return_type}GL_APIENTRY {name}({params});"""
423
424TEMPLATE_GL_VALIDATION_HEADER = """\
425// GENERATED FILE - DO NOT EDIT.
426// Generated by {script_name} using data from {data_source_name}.
427//
428// Copyright 2020 The ANGLE Project Authors. All rights reserved.
429// Use of this source code is governed by a BSD-style license that can be
430// found in the LICENSE file.
431//
432// validation{annotation}_autogen.h:
433//   Validation functions for the OpenGL {comment} entry points.
434
435#ifndef LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
436#define LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
437
438#include "common/PackedEnums.h"
439
440namespace gl
441{{
442class Context;
443
444{prototypes}
445}}  // namespace gl
446
447#endif  // LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
448"""
449
450TEMPLATE_CL_VALIDATION_HEADER = """\
451// GENERATED FILE - DO NOT EDIT.
452// Generated by {script_name} using data from {data_source_name}.
453//
454// Copyright 2021 The ANGLE Project Authors. All rights reserved.
455// Use of this source code is governed by a BSD-style license that can be
456// found in the LICENSE file.
457//
458// validation{annotation}_autogen.h:
459//   Validation functions for the {comment} entry points.
460
461#ifndef LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
462#define LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
463
464#include "libANGLE/validationCL.h"
465
466namespace cl
467{{
468{prototypes}
469}}  // namespace cl
470
471#endif  // LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
472"""
473
474TEMPLATE_EGL_VALIDATION_HEADER = """\
475// GENERATED FILE - DO NOT EDIT.
476// Generated by {script_name} using data from {data_source_name}.
477//
478// Copyright 2020 The ANGLE Project Authors. All rights reserved.
479// Use of this source code is governed by a BSD-style license that can be
480// found in the LICENSE file.
481//
482// validation{annotation}_autogen.h:
483//   Validation functions for the {comment} entry points.
484
485#ifndef LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
486#define LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
487
488#include "libANGLE/validationEGL.h"
489
490namespace egl
491{{
492{prototypes}
493}}  // namespace egl
494
495#endif  // LIBANGLE_VALIDATION_{annotation}_AUTOGEN_H_
496"""
497
498TEMPLATE_CAPTURE_HEADER = """\
499// GENERATED FILE - DO NOT EDIT.
500// Generated by {script_name} using data from {data_source_name}.
501//
502// Copyright 2020 The ANGLE Project Authors. All rights reserved.
503// Use of this source code is governed by a BSD-style license that can be
504// found in the LICENSE file.
505//
506// capture_gles_{annotation_lower}_autogen.h:
507//   Capture functions for the OpenGL ES {comment} entry points.
508
509#ifndef LIBANGLE_CAPTURE_GLES_{annotation_upper}_AUTOGEN_H_
510#define LIBANGLE_CAPTURE_GLES_{annotation_upper}_AUTOGEN_H_
511
512#include "common/PackedEnums.h"
513#include "libANGLE/capture/FrameCapture.h"
514
515namespace gl
516{{
517{prototypes}
518}}  // namespace gl
519
520#endif  // LIBANGLE_CAPTURE_GLES_{annotation_upper}_AUTOGEN_H_
521"""
522
523TEMPLATE_CAPTURE_SOURCE = """\
524// GENERATED FILE - DO NOT EDIT.
525// Generated by {script_name} using data from {data_source_name}.
526//
527// Copyright 2020 The ANGLE Project Authors. All rights reserved.
528// Use of this source code is governed by a BSD-style license that can be
529// found in the LICENSE file.
530//
531// capture_gles_{annotation_with_dash}_autogen.cpp:
532//   Capture functions for the OpenGL ES {comment} entry points.
533
534#include "libANGLE/capture/capture_gles_{annotation_with_dash}_autogen.h"
535
536#include "libANGLE/Context.h"
537#include "libANGLE/capture/FrameCapture.h"
538#include "libANGLE/capture/gl_enum_utils.h"
539#include "libANGLE/validation{annotation_no_dash}.h"
540
541using namespace angle;
542
543namespace gl
544{{
545{capture_methods}
546}}  // namespace gl
547"""
548
549TEMPLATE_CAPTURE_METHOD_WITH_RETURN_VALUE = """
550CallCapture Capture{short_name}({params_with_type}, {return_value_type_original} returnValue)
551{{
552    ParamBuffer paramBuffer;
553
554    {parameter_captures}
555
556    ParamCapture returnValueCapture("returnValue", ParamType::T{return_value_type_custom});
557    InitParamValue(ParamType::T{return_value_type_custom}, returnValue, &returnValueCapture.value);
558    paramBuffer.addReturnValue(std::move(returnValueCapture));
559
560    return CallCapture(angle::EntryPoint::GL{short_name}, std::move(paramBuffer));
561}}
562"""
563
564TEMPLATE_CAPTURE_METHOD_NO_RETURN_VALUE = """
565CallCapture Capture{short_name}({params_with_type})
566{{
567    ParamBuffer paramBuffer;
568
569    {parameter_captures}
570
571    return CallCapture(angle::EntryPoint::GL{short_name}, std::move(paramBuffer));
572}}
573"""
574
575TEMPLATE_PARAMETER_CAPTURE_VALUE = """paramBuffer.addValueParam("{name}", ParamType::T{type}, {name});"""
576
577TEMPLATE_PARAMETER_CAPTURE_GL_ENUM = """paramBuffer.addEnumParam("{name}", GLenumGroup::{group}, ParamType::T{type}, {name});"""
578
579TEMPLATE_PARAMETER_CAPTURE_POINTER = """
580    if (isCallValid)
581    {{
582        ParamCapture {name}Param("{name}", ParamType::T{type});
583        InitParamValue(ParamType::T{type}, {name}, &{name}Param.value);
584        {capture_name}({params}, &{name}Param);
585        paramBuffer.addParam(std::move({name}Param));
586    }}
587    else
588    {{
589        ParamCapture {name}Param("{name}", ParamType::T{type});
590        InitParamValue(ParamType::T{type}, static_cast<{cast_type}>(nullptr), &{name}Param.value);
591        paramBuffer.addParam(std::move({name}Param));
592    }}
593"""
594
595TEMPLATE_PARAMETER_CAPTURE_POINTER_FUNC = """void {name}({params});"""
596
597TEMPLATE_CAPTURE_REPLAY_SOURCE = """\
598// GENERATED FILE - DO NOT EDIT.
599// Generated by {script_name} using data from {data_source_name}.
600//
601// Copyright 2020 The ANGLE Project Authors. All rights reserved.
602// Use of this source code is governed by a BSD-style license that can be
603// found in the LICENSE file.
604//
605// frame_capture_replay_autogen.cpp:
606//   Util function to dispatch captured GL calls through Context and replay them.
607
608#include "angle_gl.h"
609
610#include "common/debug.h"
611#include "common/debug.h"
612#include "libANGLE/Context.h"
613#include "libANGLE/Context.inl.h"
614#include "libANGLE/capture/FrameCapture.h"
615
616using namespace gl;
617
618namespace angle
619{{
620
621void FrameCaptureShared::ReplayCall(gl::Context *context,
622                              ReplayContext *replayContext,
623                              const CallCapture &call)
624{{
625    const ParamBuffer &params = call.params;
626    switch (call.entryPoint)
627    {{
628        {call_replay_cases}
629        default:
630            UNREACHABLE();
631    }}
632}}
633
634}}  // namespace angle
635
636"""
637
638TEMPLATE_CAPTURE_REPLAY_CALL_CASE = """case angle::EntryPoint::GL{entry_point}:
639    context->{context_call}({param_value_access});break;"""
640
641POINTER_FORMAT = "0x%016\" PRIxPTR \""
642UNSIGNED_LONG_LONG_FORMAT = "%llu"
643HEX_LONG_LONG_FORMAT = "0x%llX"
644
645FORMAT_DICT = {
646    "GLbitfield": "%s",
647    "GLboolean": "%s",
648    "GLbyte": "%d",
649    "GLclampx": "0x%X",
650    "GLDEBUGPROC": POINTER_FORMAT,
651    "GLDEBUGPROCKHR": POINTER_FORMAT,
652    "GLdouble": "%f",
653    "GLeglClientBufferEXT": POINTER_FORMAT,
654    "GLeglImageOES": POINTER_FORMAT,
655    "GLenum": "%s",
656    "GLfixed": "0x%X",
657    "GLfloat": "%f",
658    "GLint": "%d",
659    "GLintptr": UNSIGNED_LONG_LONG_FORMAT,
660    "GLshort": "%d",
661    "GLsizei": "%d",
662    "GLsizeiptr": UNSIGNED_LONG_LONG_FORMAT,
663    "GLsync": POINTER_FORMAT,
664    "GLubyte": "%d",
665    "GLuint": "%u",
666    "GLuint64": UNSIGNED_LONG_LONG_FORMAT,
667    "GLushort": "%u",
668    "int": "%d",
669    # EGL-specific types
670    "EGLConfig": POINTER_FORMAT,
671    "EGLContext": POINTER_FORMAT,
672    "EGLDisplay": POINTER_FORMAT,
673    "EGLSurface": POINTER_FORMAT,
674    "EGLSync": POINTER_FORMAT,
675    "EGLNativeDisplayType": POINTER_FORMAT,
676    "EGLNativePixmapType": POINTER_FORMAT,
677    "EGLNativeWindowType": POINTER_FORMAT,
678    "EGLClientBuffer": POINTER_FORMAT,
679    "EGLenum": "0x%X",
680    "EGLint": "%d",
681    "EGLImage": POINTER_FORMAT,
682    "EGLTime": UNSIGNED_LONG_LONG_FORMAT,
683    "EGLGetBlobFuncANDROID": POINTER_FORMAT,
684    "EGLSetBlobFuncANDROID": POINTER_FORMAT,
685    "EGLuint64KHR": UNSIGNED_LONG_LONG_FORMAT,
686    "EGLSyncKHR": POINTER_FORMAT,
687    "EGLnsecsANDROID": UNSIGNED_LONG_LONG_FORMAT,
688    "EGLDeviceEXT": POINTER_FORMAT,
689    "EGLDEBUGPROCKHR": POINTER_FORMAT,
690    "EGLObjectKHR": POINTER_FORMAT,
691    "EGLLabelKHR": POINTER_FORMAT,
692    "EGLTimeKHR": UNSIGNED_LONG_LONG_FORMAT,
693    "EGLImageKHR": POINTER_FORMAT,
694    "EGLStreamKHR": POINTER_FORMAT,
695    "EGLFrameTokenANGLE": HEX_LONG_LONG_FORMAT,
696    # WGL-specific types
697    "BOOL": "%u",
698    "DWORD": POINTER_FORMAT,
699    "FLOAT": "%f",
700    "HDC": POINTER_FORMAT,
701    "HENHMETAFILE": POINTER_FORMAT,
702    "HGLRC": POINTER_FORMAT,
703    "LPCSTR": POINTER_FORMAT,
704    "LPGLYPHMETRICSFLOAT": POINTER_FORMAT,
705    "UINT": "%u",
706    # CL-specific types
707    "size_t": "%zu",
708    "cl_char": "%hhd",
709    "cl_uchar": "%hhu",
710    "cl_short": "%hd",
711    "cl_ushort": "%hu",
712    "cl_int": "%d",
713    "cl_uint": "%u",
714    "cl_long": "%lld",
715    "cl_ulong": "%llu",
716    "cl_half": "%hu",
717    "cl_float": "%f",
718    "cl_double": "%f",
719    "cl_platform_id": POINTER_FORMAT,
720    "cl_device_id": POINTER_FORMAT,
721    "cl_context": POINTER_FORMAT,
722    "cl_command_queue": POINTER_FORMAT,
723    "cl_mem": POINTER_FORMAT,
724    "cl_program": POINTER_FORMAT,
725    "cl_kernel": POINTER_FORMAT,
726    "cl_event": POINTER_FORMAT,
727    "cl_sampler": POINTER_FORMAT,
728    "cl_bool": "%u",
729    "cl_bitfield": "%llu",
730    "cl_properties": "%llu",
731    "cl_device_type": "%llu",
732    "cl_platform_info": "%u",
733    "cl_device_info": "%u",
734    "cl_device_fp_config": "%llu",
735    "cl_device_mem_cache_type": "%u",
736    "cl_device_local_mem_type": "%u",
737    "cl_device_exec_capabilities": "%llu",
738    "cl_device_svm_capabilities": "%llu",
739    "cl_command_queue_properties": "%llu",
740    "cl_device_partition_property": "%zu",
741    "cl_device_affinity_domain": "%llu",
742    "cl_context_properties": "%zu",
743    "cl_context_info": "%u",
744    "cl_queue_properties": "%llu",
745    "cl_command_queue_info": "%u",
746    "cl_channel_order": "%u",
747    "cl_channel_type": "%u",
748    "cl_mem_flags": "%llu",
749    "cl_svm_mem_flags": "%llu",
750    "cl_mem_object_type": "%u",
751    "cl_mem_info": "%u",
752    "cl_mem_migration_flags": "%llu",
753    "cl_mem_properties": "%llu",
754    "cl_image_info": "%u",
755    "cl_buffer_create_type": "%u",
756    "cl_addressing_mode": "%u",
757    "cl_filter_mode": "%u",
758    "cl_sampler_info": "%u",
759    "cl_map_flags": "%llu",
760    "cl_pipe_properties": "%zu",
761    "cl_pipe_info": "%u",
762    "cl_program_info": "%u",
763    "cl_program_build_info": "%u",
764    "cl_program_binary_type": "%u",
765    "cl_build_status": "%d",
766    "cl_kernel_info": "%u",
767    "cl_kernel_arg_info": "%u",
768    "cl_kernel_arg_address_qualifier": "%u",
769    "cl_kernel_arg_access_qualifier": "%u",
770    "cl_kernel_arg_type_qualifier": "%llu",
771    "cl_kernel_work_group_info": "%u",
772    "cl_kernel_sub_group_info": "%u",
773    "cl_event_info": "%u",
774    "cl_command_type": "%u",
775    "cl_profiling_info": "%u",
776    "cl_sampler_properties": "%llu",
777    "cl_kernel_exec_info": "%u",
778    "cl_device_atomic_capabilities": "%llu",
779    "cl_khronos_vendor_id": "%u",
780    "cl_version": "%u",
781    "cl_device_device_enqueue_capabilities": "%llu",
782}
783
784TEMPLATE_HEADER_INCLUDES = """\
785#include <GLES{major}/gl{major}{minor}.h>
786#include <export.h>"""
787
788TEMPLATE_SOURCES_INCLUDES = """\
789#include "libGLESv2/entry_points_{header_version}_autogen.h"
790
791#include "common/entry_points_enum_autogen.h"
792#include "libANGLE/Context.h"
793#include "libANGLE/Context.inl.h"
794#include "libANGLE/capture/capture_{header_version}_autogen.h"
795#include "libANGLE/capture/gl_enum_utils.h"
796#include "libANGLE/validation{validation_header_version}.h"
797#include "libANGLE/entry_points_utils.h"
798#include "libGLESv2/global_state.h"
799
800using namespace gl;
801"""
802
803GLES_EXT_HEADER_INCLUDES = TEMPLATE_HEADER_INCLUDES.format(
804    major="", minor="") + """
805#include <GLES/glext.h>
806#include <GLES2/gl2.h>
807#include <GLES2/gl2ext.h>
808#include <GLES3/gl32.h>
809"""
810
811GLES_EXT_SOURCE_INCLUDES = TEMPLATE_SOURCES_INCLUDES.format(
812    header_version="gles_ext", validation_header_version="ESEXT") + """
813#include "libANGLE/capture/capture_gles_1_0_autogen.h"
814#include "libANGLE/capture/capture_gles_2_0_autogen.h"
815#include "libANGLE/capture/capture_gles_3_0_autogen.h"
816#include "libANGLE/capture/capture_gles_3_1_autogen.h"
817#include "libANGLE/capture/capture_gles_3_2_autogen.h"
818#include "libANGLE/validationES1.h"
819#include "libANGLE/validationES2.h"
820#include "libANGLE/validationES3.h"
821#include "libANGLE/validationES31.h"
822#include "libANGLE/validationES32.h"
823
824using namespace gl;
825"""
826
827DESKTOP_GL_HEADER_INCLUDES = """\
828#include <export.h>
829#include "angle_gl.h"
830"""
831
832TEMPLATE_DESKTOP_GL_SOURCE_INCLUDES = """\
833#include "libGL/entry_points_{}_autogen.h"
834
835#include "libANGLE/Context.h"
836#include "libANGLE/Context.inl.h"
837#include "libANGLE/capture/gl_enum_utils.h"
838#include "libANGLE/validationEGL.h"
839#include "libANGLE/validationES.h"
840#include "libANGLE/validationES1.h"
841#include "libANGLE/validationES2.h"
842#include "libANGLE/validationES3.h"
843#include "libANGLE/validationES31.h"
844#include "libANGLE/validationES32.h"
845#include "libANGLE/validationESEXT.h"
846#include "libANGLE/validationGL{}_autogen.h"
847#include "libANGLE/entry_points_utils.h"
848#include "libGLESv2/global_state.h"
849
850using namespace gl;
851"""
852
853EGL_HEADER_INCLUDES = """\
854#include <EGL/egl.h>
855#include <export.h>
856"""
857
858EGL_SOURCE_INCLUDES = """\
859#include "libGLESv2/entry_points_egl_autogen.h"
860
861#include "libANGLE/entry_points_utils.h"
862#include "libANGLE/validationEGL_autogen.h"
863#include "libGLESv2/egl_stubs_autogen.h"
864#include "libGLESv2/global_state.h"
865
866using namespace egl;
867"""
868
869EGL_EXT_HEADER_INCLUDES = """\
870#include <EGL/egl.h>
871#include <EGL/eglext.h>
872#include <export.h>
873"""
874
875EGL_EXT_SOURCE_INCLUDES = """\
876#include "libGLESv2/entry_points_egl_ext_autogen.h"
877
878#include "libANGLE/entry_points_utils.h"
879#include "libANGLE/validationEGL_autogen.h"
880#include "libGLESv2/egl_ext_stubs_autogen.h"
881#include "libGLESv2/global_state.h"
882
883using namespace egl;
884"""
885
886LIBCL_EXPORT_INCLUDES = """
887#include "libOpenCL/dispatch.h"
888"""
889
890LIBGLESV2_EXPORT_INCLUDES = """
891#include "angle_gl.h"
892
893#include "libGLESv2/entry_points_gles_1_0_autogen.h"
894#include "libGLESv2/entry_points_gles_2_0_autogen.h"
895#include "libGLESv2/entry_points_gles_3_0_autogen.h"
896#include "libGLESv2/entry_points_gles_3_1_autogen.h"
897#include "libGLESv2/entry_points_gles_3_2_autogen.h"
898#include "libGLESv2/entry_points_gles_ext_autogen.h"
899
900#include "common/event_tracer.h"
901"""
902
903LIBGL_EXPORT_INCLUDES = """
904#include "angle_gl.h"
905
906#include "libGL/entry_points_gl_1_autogen.h"
907#include "libGL/entry_points_gl_2_autogen.h"
908#include "libGL/entry_points_gl_3_autogen.h"
909#include "libGL/entry_points_gl_4_autogen.h"
910
911#include "common/event_tracer.h"
912"""
913
914LIBEGL_EXPORT_INCLUDES_AND_PREAMBLE = """
915#include "anglebase/no_destructor.h"
916#include "common/system_utils.h"
917
918#include <memory>
919
920#if defined(ANGLE_USE_EGL_LOADER)
921#    include "libEGL/egl_loader_autogen.h"
922#else
923#    include "libGLESv2/entry_points_egl_autogen.h"
924#    include "libGLESv2/entry_points_egl_ext_autogen.h"
925#endif  // defined(ANGLE_USE_EGL_LOADER)
926
927namespace
928{
929#if defined(ANGLE_USE_EGL_LOADER)
930bool gLoaded = false;
931
932std::unique_ptr<angle::Library> &EntryPointsLib()
933{
934    static angle::base::NoDestructor<std::unique_ptr<angle::Library>> sEntryPointsLib;
935    return *sEntryPointsLib;
936}
937
938angle::GenericProc KHRONOS_APIENTRY GlobalLoad(const char *symbol)
939{
940    return reinterpret_cast<angle::GenericProc>(EntryPointsLib()->getSymbol(symbol));
941}
942
943void EnsureEGLLoaded()
944{
945    if (gLoaded)
946    {
947        return;
948    }
949
950    EntryPointsLib().reset(
951        angle::OpenSharedLibrary(ANGLE_GLESV2_LIBRARY_NAME, angle::SearchType::ModuleDir));
952    angle::LoadEGL_EGL(GlobalLoad);
953    if (!EGL_GetPlatformDisplay)
954    {
955        fprintf(stderr, "Error loading EGL entry points.\\n");
956    }
957    else
958    {
959        gLoaded = true;
960    }
961}
962#else
963void EnsureEGLLoaded() {}
964#endif  // defined(ANGLE_USE_EGL_LOADER)
965}  // anonymous namespace
966"""
967
968LIBCL_HEADER_INCLUDES = """\
969#include "angle_cl.h"
970"""
971
972LIBCL_SOURCE_INCLUDES = """\
973#include "libGLESv2/entry_points_cl_autogen.h"
974
975#include "libANGLE/validationCL_autogen.h"
976#include "libGLESv2/cl_stubs_autogen.h"
977#include "libGLESv2/entry_points_cl_utils.h"
978"""
979
980TEMPLATE_EVENT_COMMENT = """\
981    // Don't run the EVENT() macro on the EXT_debug_marker entry points.
982    // It can interfere with the debug events being set by the caller.
983    // """
984
985TEMPLATE_CAPTURE_PROTO = "angle::CallCapture Capture%s(%s);"
986
987TEMPLATE_VALIDATION_PROTO = "%s Validate%s(%s);"
988
989TEMPLATE_WINDOWS_DEF_FILE = """\
990; GENERATED FILE - DO NOT EDIT.
991; Generated by {script_name} using data from {data_source_name}.
992;
993; Copyright 2020 The ANGLE Project Authors. All rights reserved.
994; Use of this source code is governed by a BSD-style license that can be
995; found in the LICENSE file.
996LIBRARY {lib}
997EXPORTS
998{exports}
999"""
1000
1001TEMPLATE_FRAME_CAPTURE_UTILS_HEADER = """\
1002// GENERATED FILE - DO NOT EDIT.
1003// Generated by {script_name} using data from {data_source_name}.
1004//
1005// Copyright 2020 The ANGLE Project Authors. All rights reserved.
1006// Use of this source code is governed by a BSD-style license that can be
1007// found in the LICENSE file.
1008//
1009// frame_capture_utils_autogen.h:
1010//   ANGLE Frame capture types and helper functions.
1011
1012#ifndef LIBANGLE_FRAME_CAPTURE_UTILS_AUTOGEN_H_
1013#define LIBANGLE_FRAME_CAPTURE_UTILS_AUTOGEN_H_
1014
1015#include "common/PackedEnums.h"
1016
1017namespace angle
1018{{
1019enum class ParamType
1020{{
1021    {param_types}
1022}};
1023
1024constexpr uint32_t kParamTypeCount = {param_type_count};
1025
1026union ParamValue
1027{{
1028    {param_union_values}
1029}};
1030
1031template <ParamType PType, typename T>
1032T GetParamVal(const ParamValue &value);
1033
1034{get_param_val_specializations}
1035
1036template <ParamType PType, typename T>
1037T GetParamVal(const ParamValue &value)
1038{{
1039    UNREACHABLE();
1040    return T();
1041}}
1042
1043template <typename T>
1044T AccessParamValue(ParamType paramType, const ParamValue &value)
1045{{
1046    switch (paramType)
1047    {{
1048{access_param_value_cases}
1049    }}
1050}}
1051
1052template <ParamType PType, typename T>
1053void SetParamVal(T valueIn, ParamValue *valueOut);
1054
1055{set_param_val_specializations}
1056
1057template <ParamType PType, typename T>
1058void SetParamVal(T valueIn, ParamValue *valueOut)
1059{{
1060    UNREACHABLE();
1061}}
1062
1063template <typename T>
1064void InitParamValue(ParamType paramType, T valueIn, ParamValue *valueOut)
1065{{
1066    switch (paramType)
1067    {{
1068{init_param_value_cases}
1069    }}
1070}}
1071
1072struct CallCapture;
1073struct ParamCapture;
1074
1075void WriteParamCaptureReplay(std::ostream &os, const CallCapture &call, const ParamCapture &param);
1076const char *ParamTypeToString(ParamType paramType);
1077
1078enum class ResourceIDType
1079{{
1080    {resource_id_types}
1081}};
1082
1083ResourceIDType GetResourceIDTypeFromParamType(ParamType paramType);
1084const char *GetResourceIDTypeName(ResourceIDType resourceIDType);
1085}}  // namespace angle
1086
1087#endif  // LIBANGLE_FRAME_CAPTURE_UTILS_AUTOGEN_H_
1088"""
1089
1090TEMPLATE_FRAME_CAPTURE_UTILS_SOURCE = """\
1091// GENERATED FILE - DO NOT EDIT.
1092// Generated by {script_name} using data from {data_source_name}.
1093//
1094// Copyright 2020 The ANGLE Project Authors. All rights reserved.
1095// Use of this source code is governed by a BSD-style license that can be
1096// found in the LICENSE file.
1097//
1098// frame_capture_utils_autogen.cpp:
1099//   ANGLE Frame capture types and helper functions.
1100
1101#include "libANGLE/capture/frame_capture_utils_autogen.h"
1102
1103#include "libANGLE/capture/FrameCapture.h"
1104
1105namespace angle
1106{{
1107void WriteParamCaptureReplay(std::ostream &os, const CallCapture &call, const ParamCapture &param)
1108{{
1109    switch (param.type)
1110    {{
1111{write_param_type_to_stream_cases}
1112        default:
1113            os << "unknown";
1114            break;
1115    }}
1116}}
1117
1118const char *ParamTypeToString(ParamType paramType)
1119{{
1120    switch (paramType)
1121    {{
1122{param_type_to_string_cases}
1123        default:
1124            UNREACHABLE();
1125            return "unknown";
1126    }}
1127}}
1128
1129ResourceIDType GetResourceIDTypeFromParamType(ParamType paramType)
1130{{
1131    switch (paramType)
1132    {{
1133{param_type_resource_id_cases}
1134        default:
1135            return ResourceIDType::InvalidEnum;
1136    }}
1137}}
1138
1139const char *GetResourceIDTypeName(ResourceIDType resourceIDType)
1140{{
1141    switch (resourceIDType)
1142    {{
1143{resource_id_type_name_cases}
1144        default:
1145            UNREACHABLE();
1146            return "GetResourceIDTypeName error";
1147    }}
1148}}
1149}}  // namespace angle
1150"""
1151
1152TEMPLATE_GET_PARAM_VAL_SPECIALIZATION = """\
1153template <>
1154inline {type} GetParamVal<ParamType::T{enum}, {type}>(const ParamValue &value)
1155{{
1156    return value.{union_name};
1157}}"""
1158
1159TEMPLATE_ACCESS_PARAM_VALUE_CASE = """\
1160        case ParamType::T{enum}:
1161            return GetParamVal<ParamType::T{enum}, T>(value);"""
1162
1163TEMPLATE_SET_PARAM_VAL_SPECIALIZATION = """\
1164template <>
1165inline void SetParamVal<ParamType::T{enum}>({type} valueIn, ParamValue *valueOut)
1166{{
1167    valueOut->{union_name} = valueIn;
1168}}"""
1169
1170TEMPLATE_INIT_PARAM_VALUE_CASE = """\
1171        case ParamType::T{enum}:
1172            SetParamVal<ParamType::T{enum}>(valueIn, valueOut);
1173            break;"""
1174
1175TEMPLATE_WRITE_PARAM_TYPE_TO_STREAM_CASE = """\
1176        case ParamType::T{enum_in}:
1177            WriteParamValueReplay<ParamType::T{enum_out}>(os, call, param.value.{union_name});
1178            break;"""
1179
1180TEMPLATE_PARAM_TYPE_TO_STRING_CASE = """\
1181        case ParamType::T{enum}:
1182            return "{type}";"""
1183
1184TEMPLATE_PARAM_TYPE_TO_RESOURCE_ID_TYPE_CASE = """\
1185        case ParamType::T{enum}:
1186            return ResourceIDType::{resource_id_type};"""
1187
1188TEMPLATE_RESOURCE_ID_TYPE_NAME_CASE = """\
1189        case ResourceIDType::{resource_id_type}:
1190            return "{resource_id_type}";"""
1191
1192CL_PACKED_TYPES = {
1193    # Enums
1194    "cl_platform_info": "PlatformInfo",
1195    "cl_device_info": "DeviceInfo",
1196    "cl_context_info": "ContextInfo",
1197    "cl_command_queue_info": "CommandQueueInfo",
1198    "cl_mem_object_type": "MemObjectType",
1199    "cl_mem_info": "MemInfo",
1200    "cl_image_info": "ImageInfo",
1201    "cl_pipe_info": "PipeInfo",
1202    "cl_addressing_mode": "AddressingMode",
1203    "cl_filter_mode": "FilterMode",
1204    "cl_sampler_info": "SamplerInfo",
1205    "cl_program_info": "ProgramInfo",
1206    "cl_program_build_info": "ProgramBuildInfo",
1207    "cl_kernel_info": "KernelInfo",
1208    "cl_kernel_arg_info": "KernelArgInfo",
1209    "cl_kernel_work_group_info": "KernelWorkGroupInfo",
1210    "cl_kernel_sub_group_info": "KernelSubGroupInfo",
1211    "cl_kernel_exec_info": "KernelExecInfo",
1212    "cl_event_info": "EventInfo",
1213    "cl_profiling_info": "ProfilingInfo",
1214    # Bit fields
1215    "cl_device_type": "DeviceType",
1216    "cl_device_fp_config": "DeviceFpConfig",
1217    "cl_device_exec_capabilities": "DeviceExecCapabilities",
1218    "cl_device_svm_capabilities": "DeviceSvmCapabilities",
1219    "cl_command_queue_properties": "CommandQueueProperties",
1220    "cl_device_affinity_domain": "DeviceAffinityDomain",
1221    "cl_mem_flags": "MemFlags",
1222    "cl_svm_mem_flags": "SVM_MemFlags",
1223    "cl_mem_migration_flags": "MemMigrationFlags",
1224    "cl_map_flags": "MapFlags",
1225    "cl_kernel_arg_type_qualifier": "KernelArgTypeQualifier",
1226    "cl_device_atomic_capabilities": "DeviceAtomicCapabilities",
1227    "cl_device_device_enqueue_capabilities": "DeviceEnqueueCapabilities",
1228}
1229
1230EGL_PACKED_TYPES = {
1231    "EGLContext": "gl::Context *",
1232    "EGLConfig": "Config *",
1233    "EGLDeviceEXT": "Device *",
1234    # Needs an explicit namespace to avoid an X11 namespace collision.
1235    "EGLDisplay": "egl::Display *",
1236    "EGLImage": "Image *",
1237    "EGLImageKHR": "Image *",
1238    "EGLStreamKHR": "Stream *",
1239    "EGLSurface": "Surface *",
1240    "EGLSync": "Sync *",
1241    "EGLSyncKHR": "Sync *",
1242}
1243
1244
1245def is_aliasing_excepted(api, cmd_name):
1246    return api == apis.GLES and cmd_name in ALIASING_EXCEPTIONS
1247
1248
1249def entry_point_export(api):
1250    if api == apis.CL:
1251        return ""
1252    return "ANGLE_EXPORT "
1253
1254
1255def entry_point_prefix(api):
1256    if api == apis.CL:
1257        return "cl"
1258    if api == apis.GLES:
1259        return "GL_"
1260    return api + "_"
1261
1262
1263def get_api_entry_def(api):
1264    if api == apis.EGL:
1265        return "EGLAPIENTRY"
1266    elif api == apis.CL:
1267        return "CL_API_CALL"
1268    else:
1269        return "GL_APIENTRY"
1270
1271
1272def get_stubs_header_template(api):
1273    if api == apis.CL:
1274        return TEMPLATE_CL_STUBS_HEADER
1275    elif api == apis.EGL:
1276        return TEMPLATE_EGL_STUBS_HEADER
1277    else:
1278        return ""
1279
1280
1281def format_entry_point_decl(api, cmd_name, proto, params):
1282    comma_if_needed = ", " if len(params) > 0 else ""
1283    stripped = strip_api_prefix(cmd_name)
1284    return TEMPLATE_ENTRY_POINT_DECL.format(
1285        angle_export=entry_point_export(api),
1286        export_def=get_api_entry_def(api),
1287        name="%s%s" % (entry_point_prefix(api), stripped),
1288        return_type=proto[:-len(cmd_name)].strip(),
1289        params=", ".join(params),
1290        comma_if_needed=comma_if_needed)
1291
1292
1293# Returns index range of identifier in function parameter
1294def find_name_range(param):
1295
1296    def is_allowed_in_identifier(char):
1297        return char.isalpha() or char.isdigit() or char == "_"
1298
1299    # If type is a function declaration, only search in first parentheses
1300    left_paren = param.find("(")
1301    if left_paren >= 0:
1302        min = left_paren + 1
1303        end = param.index(")")
1304    else:
1305        min = 0
1306        end = len(param)
1307
1308    # Find last identifier in search range
1309    while end > min and not is_allowed_in_identifier(param[end - 1]):
1310        end -= 1
1311    if end == min:
1312        raise ValueError
1313    start = end - 1
1314    while start > min and is_allowed_in_identifier(param[start - 1]):
1315        start -= 1
1316    return start, end
1317
1318
1319def just_the_type(param):
1320    start, end = find_name_range(param)
1321    return param[:start].strip() + param[end:].strip()
1322
1323
1324def just_the_name(param):
1325    start, end = find_name_range(param)
1326    return param[start:end]
1327
1328
1329def make_param(param_type, param_name):
1330
1331    def insert_name(param_type, param_name, pos):
1332        return param_type[:pos] + " " + param_name + param_type[pos:]
1333
1334    # If type is a function declaration, insert identifier before first closing parentheses
1335    left_paren = param_type.find("(")
1336    if left_paren >= 0:
1337        right_paren = param_type.index(")")
1338        return insert_name(param_type, param_name, right_paren)
1339
1340    # If type is an array declaration, insert identifier before brackets
1341    brackets = param_type.find("[")
1342    if brackets >= 0:
1343        return insert_name(param_type, param_name, brackets)
1344
1345    # Otherwise just append identifier
1346    return param_type + " " + param_name
1347
1348
1349def just_the_type_packed(param, entry):
1350    name = just_the_name(param)
1351    if name in entry:
1352        return entry[name]
1353    else:
1354        return just_the_type(param)
1355
1356
1357def just_the_name_packed(param, reserved_set):
1358    name = just_the_name(param)
1359    if name in reserved_set:
1360        return name + 'Packed'
1361    else:
1362        return name
1363
1364
1365def is_unsigned_long_format(fmt):
1366    return fmt == UNSIGNED_LONG_LONG_FORMAT or fmt == HEX_LONG_LONG_FORMAT
1367
1368
1369def param_print_argument(command_node, param):
1370    name_only = just_the_name(param)
1371    type_only = just_the_type(param)
1372
1373    if "*" not in param and type_only not in FORMAT_DICT:
1374        print(" ".join(param))
1375        raise Exception("Missing '%s %s' from '%s' entry point" %
1376                        (type_only, name_only, registry_xml.get_cmd_name(command_node)))
1377
1378    if "*" in param or FORMAT_DICT[type_only] == POINTER_FORMAT:
1379        return "(uintptr_t)%s" % name_only
1380
1381    if is_unsigned_long_format(FORMAT_DICT[type_only]):
1382        return "static_cast<unsigned long long>(%s)" % name_only
1383
1384    if type_only == "GLboolean":
1385        return "GLbooleanToString(%s)" % name_only
1386
1387    if type_only == "GLbitfield":
1388        group_name = find_gl_enum_group_in_command(command_node, name_only)
1389        return "GLbitfieldToString(GLenumGroup::%s, %s).c_str()" % (group_name, name_only)
1390
1391    if type_only == "GLenum":
1392        group_name = find_gl_enum_group_in_command(command_node, name_only)
1393        return "GLenumToString(GLenumGroup::%s, %s)" % (group_name, name_only)
1394
1395    return name_only
1396
1397
1398def param_format_string(param):
1399    if "*" in param:
1400        return just_the_name(param) + " = 0x%016\" PRIxPTR \""
1401    else:
1402        type_only = just_the_type(param)
1403        if type_only not in FORMAT_DICT:
1404            raise Exception(type_only + " is not a known type in 'FORMAT_DICT'")
1405
1406        return just_the_name(param) + " = " + FORMAT_DICT[type_only]
1407
1408
1409def is_context_lost_acceptable_cmd(cmd_name):
1410    lost_context_acceptable_cmds = [
1411        "glGetError",
1412        "glGetSync",
1413        "glGetQueryObjecti",
1414        "glGetProgramiv",
1415        "glGetGraphicsResetStatus",
1416        "glGetShaderiv",
1417    ]
1418
1419    for context_lost_entry_pont in lost_context_acceptable_cmds:
1420        if cmd_name.startswith(context_lost_entry_pont):
1421            return True
1422    return False
1423
1424
1425def get_context_getter_function(cmd_name):
1426    if is_context_lost_acceptable_cmd(cmd_name):
1427        return "GetGlobalContext()"
1428
1429    return "GetValidGlobalContext()"
1430
1431
1432def get_valid_context_check(cmd_name):
1433    return "context"
1434
1435
1436def get_constext_lost_error_generator(cmd_name):
1437    # Don't generate context lost errors on commands that accept lost contexts
1438    if is_context_lost_acceptable_cmd(cmd_name):
1439        return ""
1440
1441    return "GenerateContextLostErrorOnCurrentGlobalContext();"
1442
1443
1444def strip_suffix(api, name):
1445    # For commands where aliasing is excepted, keep the suffix
1446    if is_aliasing_excepted(api, name):
1447        return name
1448
1449    for suffix in STRIP_SUFFIXES:
1450        if name.endswith(suffix):
1451            name = name[0:-len(suffix)]
1452    return name
1453
1454
1455def find_gl_enum_group_in_command(command_node, param_name):
1456    group_name = None
1457    for param_node in command_node.findall('./param'):
1458        if param_node.find('./name').text == param_name:
1459            group_name = param_node.attrib.get('group', None)
1460            break
1461
1462    if group_name is None or group_name in registry_xml.unsupported_enum_group_names:
1463        group_name = registry_xml.default_enum_group_name
1464
1465    return group_name
1466
1467
1468def get_packed_enums(api, cmd_packed_gl_enums, cmd_name, packed_param_types, params):
1469    # Always strip the suffix when querying packed enums.
1470    result = cmd_packed_gl_enums.get(strip_suffix(api, cmd_name), {})
1471    for param in params:
1472        param_type = just_the_type(param)
1473        if param_type in packed_param_types:
1474            result[just_the_name(param)] = packed_param_types[param_type]
1475    return result
1476
1477
1478def get_def_template(api, return_type, has_errcode_ret):
1479    if return_type == "void":
1480        if api == apis.EGL:
1481            return TEMPLATE_EGL_ENTRY_POINT_NO_RETURN
1482        elif api == apis.CL:
1483            return TEMPLATE_CL_ENTRY_POINT_NO_RETURN
1484        else:
1485            return TEMPLATE_GLES_ENTRY_POINT_NO_RETURN
1486    elif return_type == "cl_int":
1487        return TEMPLATE_CL_ENTRY_POINT_WITH_RETURN_ERROR
1488    else:
1489        if api == apis.EGL:
1490            return TEMPLATE_EGL_ENTRY_POINT_WITH_RETURN
1491        elif api == apis.CL:
1492            if has_errcode_ret:
1493                return TEMPLATE_CL_ENTRY_POINT_WITH_ERRCODE_RET
1494            else:
1495                return TEMPLATE_CL_ENTRY_POINT_WITH_RETURN_POINTER
1496        else:
1497            return TEMPLATE_GLES_ENTRY_POINT_WITH_RETURN
1498
1499
1500def format_entry_point_def(api, command_node, cmd_name, proto, params, cmd_packed_enums,
1501                           packed_param_types, ep_to_object):
1502    packed_enums = get_packed_enums(api, cmd_packed_enums, cmd_name, packed_param_types, params)
1503    internal_params = [just_the_name_packed(param, packed_enums) for param in params]
1504    if internal_params and internal_params[-1] == "errcode_ret":
1505        internal_params.pop()
1506        has_errcode_ret = True
1507    else:
1508        has_errcode_ret = False
1509    packed_gl_enum_conversions = []
1510    for param in params:
1511        name = just_the_name(param)
1512        if name in packed_enums:
1513            internal_name = name + "Packed"
1514            internal_type = packed_enums[name]
1515            packed_gl_enum_conversions += [
1516                "\n        " + internal_type + " " + internal_name + " = PackParam<" +
1517                internal_type + ">(" + name + ");"
1518            ]
1519
1520    pass_params = [param_print_argument(command_node, param) for param in params]
1521    format_params = [param_format_string(param) for param in params]
1522    return_type = proto[:-len(cmd_name)].strip()
1523    initialization = "InitBackEnds(%s);\n" % INIT_DICT[cmd_name] if cmd_name in INIT_DICT else ""
1524    event_comment = TEMPLATE_EVENT_COMMENT if cmd_name in NO_EVENT_MARKER_EXCEPTIONS_LIST else ""
1525    name_lower_no_suffix = strip_suffix(api, cmd_name[2:3].lower() + cmd_name[3:])
1526
1527    format_params = {
1528        "name":
1529            strip_api_prefix(cmd_name),
1530        "name_lower_no_suffix":
1531            name_lower_no_suffix,
1532        "return_type":
1533            return_type,
1534        "params":
1535            ", ".join(params),
1536        "internal_params":
1537            ", ".join(internal_params),
1538        "initialization":
1539            initialization,
1540        "packed_gl_enum_conversions":
1541            "".join(packed_gl_enum_conversions),
1542        "pass_params":
1543            ", ".join(pass_params),
1544        "comma_if_needed":
1545            ", " if len(params) > 0 else "",
1546        "validate_params":
1547            ", ".join(["context"] + internal_params),
1548        "format_params":
1549            ", ".join(format_params),
1550        "context_getter":
1551            get_context_getter_function(cmd_name),
1552        "valid_context_check":
1553            get_valid_context_check(cmd_name),
1554        "constext_lost_error_generator":
1555            get_constext_lost_error_generator(cmd_name),
1556        "event_comment":
1557            event_comment,
1558        "labeled_object":
1559            get_egl_entry_point_labeled_object(ep_to_object, cmd_name, params, packed_enums)
1560    }
1561
1562    template = get_def_template(api, return_type, has_errcode_ret)
1563    return template.format(**format_params)
1564
1565
1566def get_capture_param_type_name(param_type):
1567
1568    pointer_count = param_type.count("*")
1569    is_const = "const" in param_type.split()
1570
1571    param_type = param_type.replace("*", "").strip()
1572    param_type = " ".join([param for param in param_type.split() if param != "const"])
1573
1574    if is_const:
1575        param_type += "Const"
1576    for x in range(pointer_count):
1577        param_type += "Pointer"
1578
1579    return param_type
1580
1581
1582def format_capture_method(api, command, cmd_name, proto, params, all_param_types,
1583                          capture_pointer_funcs, cmd_packed_gl_enums, packed_param_types):
1584
1585    packed_gl_enums = get_packed_enums(api, cmd_packed_gl_enums, cmd_name, packed_param_types,
1586                                       params)
1587
1588    params_with_type = get_internal_params(api, cmd_name,
1589                                           ["const State &glState", "bool isCallValid"] + params,
1590                                           cmd_packed_gl_enums, packed_param_types)
1591    params_just_name = ", ".join(
1592        ["glState", "isCallValid"] +
1593        [just_the_name_packed(param, packed_gl_enums) for param in params])
1594
1595    parameter_captures = []
1596    for param in params:
1597
1598        param_name = just_the_name_packed(param, packed_gl_enums)
1599        param_type = just_the_type_packed(param, packed_gl_enums).strip()
1600        pointer_count = param_type.count("*")
1601        capture_param_type = get_capture_param_type_name(param_type)
1602
1603        if pointer_count > 0:
1604            params = params_just_name
1605            capture_name = "Capture%s_%s" % (strip_api_prefix(cmd_name), param_name)
1606            capture = TEMPLATE_PARAMETER_CAPTURE_POINTER.format(
1607                name=param_name,
1608                type=capture_param_type,
1609                capture_name=capture_name,
1610                params=params,
1611                cast_type=param_type)
1612
1613            capture_pointer_func = TEMPLATE_PARAMETER_CAPTURE_POINTER_FUNC.format(
1614                name=capture_name, params=params_with_type + ", angle::ParamCapture *paramCapture")
1615            capture_pointer_funcs += [capture_pointer_func]
1616        elif capture_param_type in ('GLenum', 'GLbitfield'):
1617            gl_enum_group = find_gl_enum_group_in_command(command, param_name)
1618            capture = TEMPLATE_PARAMETER_CAPTURE_GL_ENUM.format(
1619                name=param_name, type=capture_param_type, group=gl_enum_group)
1620        else:
1621            capture = TEMPLATE_PARAMETER_CAPTURE_VALUE.format(
1622                name=param_name, type=capture_param_type)
1623
1624        all_param_types.add(capture_param_type)
1625
1626        parameter_captures += [capture]
1627
1628    return_type = proto[:-len(cmd_name)].strip()
1629
1630    format_args = {
1631        "full_name": cmd_name,
1632        "short_name": strip_api_prefix(cmd_name),
1633        "params_with_type": params_with_type,
1634        "params_just_name": params_just_name,
1635        "parameter_captures": "\n    ".join(parameter_captures),
1636        "return_value_type_original": return_type,
1637        "return_value_type_custom": get_capture_param_type_name(return_type)
1638    }
1639
1640    if return_type == "void":
1641        return TEMPLATE_CAPTURE_METHOD_NO_RETURN_VALUE.format(**format_args)
1642    else:
1643        return TEMPLATE_CAPTURE_METHOD_WITH_RETURN_VALUE.format(**format_args)
1644
1645
1646def const_pointer_type(param, packed_gl_enums):
1647    type = just_the_type_packed(param, packed_gl_enums)
1648    if just_the_name(param) == "errcode_ret" or "(" in type:
1649        return type
1650    elif "**" in type and "const" not in type:
1651        return type.replace("**", "* const *")
1652    elif "*" in type and "const" not in type:
1653        return type.replace("*", "*const ") if "[]" in type else "const " + type
1654    else:
1655        return type
1656
1657
1658def get_internal_params(api, cmd_name, params, cmd_packed_gl_enums, packed_param_types):
1659    packed_gl_enums = get_packed_enums(api, cmd_packed_gl_enums, cmd_name, packed_param_types,
1660                                       params)
1661    return ", ".join([
1662        make_param(
1663            just_the_type_packed(param, packed_gl_enums),
1664            just_the_name_packed(param, packed_gl_enums)) for param in params
1665    ])
1666
1667
1668def get_validation_params(api, cmd_name, params, cmd_packed_gl_enums, packed_param_types):
1669    packed_gl_enums = get_packed_enums(api, cmd_packed_gl_enums, cmd_name, packed_param_types,
1670                                       params)
1671    last = -1 if params and just_the_name(params[-1]) == "errcode_ret" else None
1672    return ", ".join([
1673        make_param(
1674            const_pointer_type(param, packed_gl_enums),
1675            just_the_name_packed(param, packed_gl_enums)) for param in params[:last]
1676    ])
1677
1678
1679def format_context_decl(api, cmd_name, proto, params, template, cmd_packed_gl_enums,
1680                        packed_param_types):
1681    internal_params = get_internal_params(api, cmd_name, params, cmd_packed_gl_enums,
1682                                          packed_param_types)
1683
1684    return_type = proto[:-len(cmd_name)].strip()
1685    name_lower_no_suffix = cmd_name[2:3].lower() + cmd_name[3:]
1686    name_lower_no_suffix = strip_suffix(api, name_lower_no_suffix)
1687    maybe_const = " const" if name_lower_no_suffix.startswith(
1688        "is") and name_lower_no_suffix[2].isupper() else ""
1689
1690    return template.format(
1691        return_type=return_type,
1692        name_lower_no_suffix=name_lower_no_suffix,
1693        internal_params=internal_params,
1694        maybe_const=maybe_const)
1695
1696
1697def format_entry_point_export(cmd_name, proto, params, template):
1698    internal_params = [just_the_name(param) for param in params]
1699    return_type = proto[:-len(cmd_name)].strip()
1700
1701    return template.format(
1702        name=strip_api_prefix(cmd_name),
1703        return_type=return_type,
1704        params=", ".join(params),
1705        internal_params=", ".join(internal_params))
1706
1707
1708def format_validation_proto(api, cmd_name, proto, params, cmd_packed_gl_enums, packed_param_types):
1709    if api == apis.CL:
1710        return_type = "cl_int"
1711    else:
1712        return_type = "bool"
1713    if api in [apis.GL, apis.GLES]:
1714        with_extra_params = ["Context *context"] + params
1715    elif api == apis.EGL:
1716        with_extra_params = ["ValidationContext *val"] + params
1717    else:
1718        with_extra_params = params
1719    internal_params = get_validation_params(api, cmd_name, with_extra_params, cmd_packed_gl_enums,
1720                                            packed_param_types)
1721    return TEMPLATE_VALIDATION_PROTO % (return_type, strip_api_prefix(cmd_name), internal_params)
1722
1723
1724def format_capture_proto(api, cmd_name, proto, params, cmd_packed_gl_enums, packed_param_types):
1725    internal_params = get_internal_params(api, cmd_name,
1726                                          ["const State &glState", "bool isCallValid"] + params,
1727                                          cmd_packed_gl_enums, packed_param_types)
1728    return_type = proto[:-len(cmd_name)].strip()
1729    if return_type != "void":
1730        internal_params += ", %s returnValue" % return_type
1731    return TEMPLATE_CAPTURE_PROTO % (strip_api_prefix(cmd_name), internal_params)
1732
1733
1734def path_to(folder, file):
1735    return os.path.join(script_relative(".."), "src", folder, file)
1736
1737
1738class ANGLEEntryPoints(registry_xml.EntryPoints):
1739
1740    def __init__(self,
1741                 api,
1742                 xml,
1743                 commands,
1744                 all_param_types,
1745                 cmd_packed_enums,
1746                 export_template=TEMPLATE_GL_ENTRY_POINT_EXPORT,
1747                 packed_param_types=[],
1748                 ep_to_object={}):
1749        super().__init__(api, xml, commands)
1750
1751        self.decls = []
1752        self.defs = []
1753        self.export_defs = []
1754        self.validation_protos = []
1755        self.capture_protos = []
1756        self.capture_methods = []
1757        self.capture_pointer_funcs = []
1758
1759        for (cmd_name, command_node, param_text, proto_text) in self.get_infos():
1760            self.decls.append(format_entry_point_decl(self.api, cmd_name, proto_text, param_text))
1761            self.defs.append(
1762                format_entry_point_def(self.api, command_node, cmd_name, proto_text, param_text,
1763                                       cmd_packed_enums, packed_param_types, ep_to_object))
1764
1765            self.export_defs.append(
1766                format_entry_point_export(cmd_name, proto_text, param_text, export_template))
1767
1768            self.validation_protos.append(
1769                format_validation_proto(self.api, cmd_name, proto_text, param_text,
1770                                        cmd_packed_enums, packed_param_types))
1771            self.capture_protos.append(
1772                format_capture_proto(self.api, cmd_name, proto_text, param_text, cmd_packed_enums,
1773                                     packed_param_types))
1774            self.capture_methods.append(
1775                format_capture_method(self.api, command_node, cmd_name, proto_text, param_text,
1776                                      all_param_types, self.capture_pointer_funcs,
1777                                      cmd_packed_enums, packed_param_types))
1778
1779
1780class GLEntryPoints(ANGLEEntryPoints):
1781
1782    all_param_types = set()
1783
1784    def __init__(self, api, xml, commands):
1785        super().__init__(api, xml, commands, GLEntryPoints.all_param_types,
1786                         GLEntryPoints.get_packed_enums())
1787
1788    _packed_enums = None
1789
1790    @classmethod
1791    def get_packed_enums(cls):
1792        if not cls._packed_enums:
1793            with open(script_relative('entry_point_packed_gl_enums.json')) as f:
1794                cls._packed_enums = json.loads(f.read())
1795        return cls._packed_enums
1796
1797
1798class EGLEntryPoints(ANGLEEntryPoints):
1799
1800    all_param_types = set()
1801
1802    def __init__(self, xml, commands):
1803        super().__init__(
1804            apis.EGL,
1805            xml,
1806            commands,
1807            EGLEntryPoints.all_param_types,
1808            EGLEntryPoints.get_packed_enums(),
1809            export_template=TEMPLATE_EGL_ENTRY_POINT_EXPORT,
1810            packed_param_types=EGL_PACKED_TYPES,
1811            ep_to_object=EGLEntryPoints._get_ep_to_object())
1812
1813    _ep_to_object = None
1814
1815    @classmethod
1816    def _get_ep_to_object(cls):
1817
1818        if cls._ep_to_object:
1819            return cls._ep_to_object
1820
1821        with open(EGL_GET_LABELED_OBJECT_DATA_PATH) as f:
1822            try:
1823                spec_json = json.loads(f.read())
1824            except ValueError:
1825                raise Exception("Could not decode JSON from %s" % EGL_GET_LABELED_OBJECT_DATA_PATH)
1826
1827        # Construct a mapping from EP to type. Fill in the gaps with Display/None.
1828        cls._ep_to_object = {}
1829
1830        for category, eps in spec_json.items():
1831            if category == 'description':
1832                continue
1833            for ep in eps:
1834                cls._ep_to_object[ep] = category
1835
1836        return cls._ep_to_object
1837
1838    _packed_enums = None
1839
1840    @classmethod
1841    def get_packed_enums(cls):
1842        if not cls._packed_enums:
1843            with open(script_relative('entry_point_packed_egl_enums.json')) as f:
1844                cls._packed_enums = json.loads(f.read())
1845        return cls._packed_enums
1846
1847
1848class CLEntryPoints(ANGLEEntryPoints):
1849
1850    all_param_types = set()
1851
1852    def __init__(self, xml, commands):
1853        super().__init__(
1854            apis.CL,
1855            xml,
1856            commands,
1857            CLEntryPoints.all_param_types,
1858            CLEntryPoints.get_packed_enums(),
1859            export_template=TEMPLATE_CL_ENTRY_POINT_EXPORT,
1860            packed_param_types=CL_PACKED_TYPES)
1861
1862    @classmethod
1863    def get_packed_enums(cls):
1864        return {}
1865
1866
1867def get_decls(api,
1868              formatter,
1869              all_commands,
1870              gles_commands,
1871              already_included,
1872              cmd_packed_gl_enums,
1873              packed_param_types=[]):
1874    decls = []
1875    for command in all_commands:
1876        proto = command.find('proto')
1877        cmd_name = proto.find('name').text
1878
1879        if cmd_name not in gles_commands:
1880            continue
1881
1882        name_no_suffix = strip_suffix(api, cmd_name)
1883        if name_no_suffix in already_included:
1884            continue
1885
1886        param_text = ["".join(param.itertext()) for param in command.findall('param')]
1887        proto_text = "".join(proto.itertext())
1888        decls.append(
1889            format_context_decl(api, cmd_name, proto_text, param_text, formatter,
1890                                cmd_packed_gl_enums, packed_param_types))
1891
1892    return decls
1893
1894
1895def get_glext_decls(all_commands, gles_commands, version):
1896    glext_ptrs = []
1897    glext_protos = []
1898    is_gles1 = False
1899
1900    if (version == ""):
1901        is_gles1 = True
1902
1903    for command in all_commands:
1904        proto = command.find('proto')
1905        cmd_name = proto.find('name').text
1906
1907        if cmd_name not in gles_commands:
1908            continue
1909
1910        param_text = ["".join(param.itertext()) for param in command.findall('param')]
1911        proto_text = "".join(proto.itertext())
1912
1913        return_type = proto_text[:-len(cmd_name)]
1914        params = ", ".join(param_text)
1915
1916        format_params = {
1917            "apicall": "GL_API" if is_gles1 else "GL_APICALL",
1918            "name": cmd_name,
1919            "name_upper": cmd_name.upper(),
1920            "return_type": return_type,
1921            "params": params,
1922        }
1923
1924        glext_ptrs.append(TEMPLATE_GLEXT_FUNCTION_POINTER.format(**format_params))
1925        glext_protos.append(TEMPLATE_GLEXT_FUNCTION_PROTOTYPE.format(**format_params))
1926
1927    return glext_ptrs, glext_protos
1928
1929
1930def write_file(annotation, comment, template, entry_points, suffix, includes, lib, file):
1931
1932    content = template.format(
1933        script_name=os.path.basename(sys.argv[0]),
1934        data_source_name=file,
1935        annotation_lower=annotation.lower(),
1936        annotation_upper=annotation.upper(),
1937        comment=comment,
1938        lib=lib.upper(),
1939        includes=includes,
1940        entry_points=entry_points)
1941
1942    path = path_to(lib, "entry_points_{}_autogen.{}".format(annotation.lower(), suffix))
1943
1944    with open(path, "w") as out:
1945        out.write(content)
1946        out.close()
1947
1948
1949def write_export_files(entry_points, includes, source, lib_name, lib_description):
1950    content = TEMPLATE_LIB_ENTRY_POINT_SOURCE.format(
1951        script_name=os.path.basename(sys.argv[0]),
1952        data_source_name=source,
1953        lib_name=lib_name,
1954        lib_description=lib_description,
1955        includes=includes,
1956        entry_points=entry_points)
1957
1958    path = path_to(lib_name, "{}_autogen.cpp".format(lib_name))
1959
1960    with open(path, "w") as out:
1961        out.write(content)
1962        out.close()
1963
1964
1965def write_context_api_decls(decls, api):
1966    for (major, minor), version_decls in sorted(decls['core'].items()):
1967        if minor == "X":
1968            annotation = '{}_{}'.format(api, major)
1969            version = str(major)
1970        else:
1971            annotation = '{}_{}_{}'.format(api, major, minor)
1972            version = '{}_{}'.format(major, minor)
1973        content = CONTEXT_HEADER.format(
1974            annotation_lower=annotation.lower(),
1975            annotation_upper=annotation.upper(),
1976            script_name=os.path.basename(sys.argv[0]),
1977            data_source_name="gl.xml",
1978            version=version,
1979            interface="\n".join(version_decls))
1980
1981        path = path_to("libANGLE", "Context_%s_autogen.h" % annotation.lower())
1982
1983        with open(path, "w") as out:
1984            out.write(content)
1985            out.close()
1986
1987    if 'exts' in decls.keys():
1988        interface_lines = []
1989        for annotation in decls['exts'].keys():
1990            interface_lines.append("\\\n    /* " + annotation + " */ \\\n\\")
1991
1992            for extname in sorted(decls['exts'][annotation].keys()):
1993                interface_lines.append("    /* " + extname + " */ \\")
1994                interface_lines.extend(decls['exts'][annotation][extname])
1995
1996        content = CONTEXT_HEADER.format(
1997            annotation_lower='gles_ext',
1998            annotation_upper='GLES_EXT',
1999            script_name=os.path.basename(sys.argv[0]),
2000            data_source_name="gl.xml",
2001            version='EXT',
2002            interface="\n".join(interface_lines))
2003
2004        path = path_to("libANGLE", "Context_gles_ext_autogen.h")
2005
2006        with open(path, "w") as out:
2007            out.write(content)
2008            out.close()
2009
2010
2011def write_validation_header(annotation, comment, protos, source, template):
2012    content = template.format(
2013        script_name=os.path.basename(sys.argv[0]),
2014        data_source_name=source,
2015        annotation=annotation,
2016        comment=comment,
2017        prototypes="\n".join(protos))
2018
2019    path = path_to("libANGLE", "validation%s_autogen.h" % annotation)
2020
2021    with open(path, "w") as out:
2022        out.write(content)
2023        out.close()
2024
2025
2026def write_gl_validation_header(annotation, comment, protos, source):
2027    return write_validation_header(annotation, comment, protos, source,
2028                                   TEMPLATE_GL_VALIDATION_HEADER)
2029
2030
2031def write_capture_header(annotation, comment, protos, capture_pointer_funcs):
2032    content = TEMPLATE_CAPTURE_HEADER.format(
2033        script_name=os.path.basename(sys.argv[0]),
2034        data_source_name="gl.xml and gl_angle_ext.xml",
2035        annotation_lower=annotation.lower(),
2036        annotation_upper=annotation.upper(),
2037        comment=comment,
2038        prototypes="\n".join(["\n// Method Captures\n"] + protos + ["\n// Parameter Captures\n"] +
2039                             capture_pointer_funcs))
2040
2041    path = path_to(os.path.join("libANGLE", "capture"), "capture_gles_%s_autogen.h" % annotation)
2042
2043    with open(path, "w") as out:
2044        out.write(content)
2045        out.close()
2046
2047
2048def write_capture_source(annotation_with_dash, annotation_no_dash, comment, capture_methods):
2049    content = TEMPLATE_CAPTURE_SOURCE.format(
2050        script_name=os.path.basename(sys.argv[0]),
2051        data_source_name="gl.xml and gl_angle_ext.xml",
2052        annotation_with_dash=annotation_with_dash,
2053        annotation_no_dash=annotation_no_dash,
2054        comment=comment,
2055        capture_methods="\n".join(capture_methods))
2056
2057    path = path_to(
2058        os.path.join("libANGLE", "capture"), "capture_gles_%s_autogen.cpp" % annotation_with_dash)
2059
2060    with open(path, "w") as out:
2061        out.write(content)
2062        out.close()
2063
2064
2065def is_packed_enum_param_type(param_type):
2066    return param_type[0:2] != "GL" and "void" not in param_type
2067
2068
2069def get_gl_pointer_type(param_type):
2070
2071    if "ConstPointerPointer" in param_type:
2072        return "const " + param_type.replace("ConstPointerPointer", "") + " * const *"
2073
2074    if "ConstPointer" in param_type:
2075        return "const " + param_type.replace("ConstPointer", "") + " *"
2076
2077    if "PointerPointer" in param_type:
2078        return param_type.replace("PointerPointer", "") + " **"
2079
2080    if "Pointer" in param_type:
2081        return param_type.replace("Pointer", "") + " *"
2082
2083    return param_type
2084
2085
2086def get_param_type_type(param_type):
2087
2088    if is_packed_enum_param_type(param_type):
2089        param_type = "gl::" + param_type
2090
2091    return get_gl_pointer_type(param_type)
2092
2093
2094def get_gl_param_type_type(param_type):
2095    if not is_packed_enum_param_type(param_type):
2096        return get_gl_pointer_type(param_type)
2097    else:
2098        base_type = param_type.replace("Pointer", "").replace("Const", "")
2099        if base_type[-2:] == "ID":
2100            replace_type = "GLuint"
2101        else:
2102            replace_type = "GLenum"
2103        param_type = param_type.replace(base_type, replace_type)
2104        return get_gl_pointer_type(param_type)
2105
2106
2107def get_param_type_union_name(param_type):
2108    return param_type + "Val"
2109
2110
2111def format_param_type_union_type(param_type):
2112    return "%s %s;" % (get_param_type_type(param_type), get_param_type_union_name(param_type))
2113
2114
2115def format_get_param_val_specialization(param_type):
2116    return TEMPLATE_GET_PARAM_VAL_SPECIALIZATION.format(
2117        enum=param_type,
2118        type=get_param_type_type(param_type),
2119        union_name=get_param_type_union_name(param_type))
2120
2121
2122def format_access_param_value_case(param_type):
2123    return TEMPLATE_ACCESS_PARAM_VALUE_CASE.format(enum=param_type)
2124
2125
2126def format_set_param_val_specialization(param_type):
2127    return TEMPLATE_SET_PARAM_VAL_SPECIALIZATION.format(
2128        enum=param_type,
2129        type=get_param_type_type(param_type),
2130        union_name=get_param_type_union_name(param_type))
2131
2132
2133def format_init_param_value_case(param_type):
2134    return TEMPLATE_INIT_PARAM_VALUE_CASE.format(enum=param_type)
2135
2136
2137def format_write_param_type_to_stream_case(param_type):
2138    # Force all enum printing to go through "const void *"
2139    param_out = "voidConstPointer" if "Pointer" in param_type else param_type
2140    return TEMPLATE_WRITE_PARAM_TYPE_TO_STREAM_CASE.format(
2141        enum_in=param_type, enum_out=param_out, union_name=get_param_type_union_name(param_out))
2142
2143
2144def get_resource_id_types(all_param_types):
2145    return [t[:-2] for t in filter(lambda t: t.endswith("ID"), all_param_types)]
2146
2147
2148def format_resource_id_types(all_param_types):
2149    resource_id_types = get_resource_id_types(all_param_types)
2150    resource_id_types += ["EnumCount", "InvalidEnum = EnumCount"]
2151    resource_id_types = ",\n    ".join(resource_id_types)
2152    return resource_id_types
2153
2154
2155def write_capture_helper_header(all_param_types):
2156
2157    param_types = "\n    ".join(["T%s," % t for t in all_param_types])
2158    param_union_values = "\n    ".join([format_param_type_union_type(t) for t in all_param_types])
2159    get_param_val_specializations = "\n\n".join(
2160        [format_get_param_val_specialization(t) for t in all_param_types])
2161    access_param_value_cases = "\n".join(
2162        [format_access_param_value_case(t) for t in all_param_types])
2163    set_param_val_specializations = "\n\n".join(
2164        [format_set_param_val_specialization(t) for t in all_param_types])
2165    init_param_value_cases = "\n".join([format_init_param_value_case(t) for t in all_param_types])
2166    resource_id_types = format_resource_id_types(all_param_types)
2167
2168    content = TEMPLATE_FRAME_CAPTURE_UTILS_HEADER.format(
2169        script_name=os.path.basename(sys.argv[0]),
2170        data_source_name="gl.xml and gl_angle_ext.xml",
2171        param_types=param_types,
2172        param_type_count=len(all_param_types),
2173        param_union_values=param_union_values,
2174        get_param_val_specializations=get_param_val_specializations,
2175        access_param_value_cases=access_param_value_cases,
2176        set_param_val_specializations=set_param_val_specializations,
2177        init_param_value_cases=init_param_value_cases,
2178        resource_id_types=resource_id_types)
2179
2180    path = path_to(os.path.join("libANGLE", "capture"), "frame_capture_utils_autogen.h")
2181
2182    with open(path, "w") as out:
2183        out.write(content)
2184        out.close()
2185
2186
2187def format_param_type_to_string_case(param_type):
2188    return TEMPLATE_PARAM_TYPE_TO_STRING_CASE.format(
2189        enum=param_type, type=get_gl_param_type_type(param_type))
2190
2191
2192def get_resource_id_type_from_param_type(param_type):
2193    if param_type.endswith("ConstPointer"):
2194        return param_type.replace("ConstPointer", "")[:-2]
2195    if param_type.endswith("Pointer"):
2196        return param_type.replace("Pointer", "")[:-2]
2197    return param_type[:-2]
2198
2199
2200def format_param_type_to_resource_id_type_case(param_type):
2201    return TEMPLATE_PARAM_TYPE_TO_RESOURCE_ID_TYPE_CASE.format(
2202        enum=param_type, resource_id_type=get_resource_id_type_from_param_type(param_type))
2203
2204
2205def format_param_type_resource_id_cases(all_param_types):
2206    id_types = filter(
2207        lambda t: t.endswith("ID") or t.endswith("IDConstPointer") or t.endswith("IDPointer"),
2208        all_param_types)
2209    return "\n".join([format_param_type_to_resource_id_type_case(t) for t in id_types])
2210
2211
2212def format_resource_id_type_name_case(resource_id_type):
2213    return TEMPLATE_RESOURCE_ID_TYPE_NAME_CASE.format(resource_id_type=resource_id_type)
2214
2215
2216def write_capture_helper_source(all_param_types):
2217
2218    write_param_type_to_stream_cases = "\n".join(
2219        [format_write_param_type_to_stream_case(t) for t in all_param_types])
2220    param_type_to_string_cases = "\n".join(
2221        [format_param_type_to_string_case(t) for t in all_param_types])
2222
2223    param_type_resource_id_cases = format_param_type_resource_id_cases(all_param_types)
2224
2225    resource_id_types = get_resource_id_types(all_param_types)
2226    resource_id_type_name_cases = "\n".join(
2227        [format_resource_id_type_name_case(t) for t in resource_id_types])
2228
2229    content = TEMPLATE_FRAME_CAPTURE_UTILS_SOURCE.format(
2230        script_name=os.path.basename(sys.argv[0]),
2231        data_source_name="gl.xml and gl_angle_ext.xml",
2232        write_param_type_to_stream_cases=write_param_type_to_stream_cases,
2233        param_type_to_string_cases=param_type_to_string_cases,
2234        param_type_resource_id_cases=param_type_resource_id_cases,
2235        resource_id_type_name_cases=resource_id_type_name_cases)
2236
2237    path = path_to(os.path.join("libANGLE", "capture"), "frame_capture_utils_autogen.cpp")
2238
2239    with open(path, "w") as out:
2240        out.write(content)
2241        out.close()
2242
2243
2244def get_command_params_text(command_node, cmd_name):
2245    param_text_list = list()
2246    for param_node in command_node.findall('param'):
2247        param_text_list.append("".join(param_node.itertext()))
2248    return param_text_list
2249
2250
2251def is_get_pointer_command(command_name):
2252    return command_name.endswith('Pointerv') and command_name.startswith('glGet')
2253
2254
2255def format_capture_replay_param_access(api, command_name, param_text_list, cmd_packed_gl_enums,
2256                                       packed_param_types):
2257    param_access_strs = list()
2258    cmd_packed_enums = get_packed_enums(api, cmd_packed_gl_enums, command_name, packed_param_types,
2259                                        param_text_list)
2260    for i, param_text in enumerate(param_text_list):
2261        param_type = just_the_type_packed(param_text, cmd_packed_enums)
2262        param_name = just_the_name_packed(param_text, cmd_packed_enums)
2263
2264        pointer_count = param_type.count('*')
2265        is_const = 'const' in param_type
2266        if pointer_count == 0:
2267            param_template = 'params.getParam("{name}", ParamType::T{enum_type}, {index}).value.{enum_type}Val'
2268        elif pointer_count == 1 and is_const:
2269            param_template = 'replayContext->getAsConstPointer<{type}>(params.getParam("{name}", ParamType::T{enum_type}, {index}))'
2270        elif pointer_count == 2 and is_const:
2271            param_template = 'replayContext->getAsPointerConstPointer<{type}>(params.getParam("{name}", ParamType::T{enum_type}, {index}))'
2272        elif pointer_count == 1 or (pointer_count == 2 and is_get_pointer_command(command_name)):
2273            param_template = 'replayContext->getReadBufferPointer<{type}>(params.getParam("{name}", ParamType::T{enum_type}, {index}))'
2274        else:
2275            assert False, "Not supported param type %s" % param_type
2276
2277        param_access_strs.append(
2278            param_template.format(
2279                index=i,
2280                name=param_name,
2281                type=param_type,
2282                enum_type=get_capture_param_type_name(param_type)))
2283    return ",".join(param_access_strs)
2284
2285
2286def format_capture_replay_call_case(api, command_to_param_types_mapping, cmd_packed_gl_enums,
2287                                    packed_param_types):
2288    call_str_list = list()
2289    for command_name, cmd_param_texts in sorted(command_to_param_types_mapping.items()):
2290        entry_point_name = strip_api_prefix(command_name)
2291
2292        call_str_list.append(
2293            TEMPLATE_CAPTURE_REPLAY_CALL_CASE.format(
2294                entry_point=entry_point_name,
2295                param_value_access=format_capture_replay_param_access(
2296                    api, command_name, cmd_param_texts, cmd_packed_gl_enums, packed_param_types),
2297                context_call=entry_point_name[0].lower() + entry_point_name[1:],
2298            ))
2299
2300    return '\n'.join(call_str_list)
2301
2302
2303def write_capture_replay_source(api, all_commands_nodes, gles_command_names, cmd_packed_gl_enums,
2304                                packed_param_types):
2305    all_commands_names = set(gles_command_names)
2306
2307    command_to_param_types_mapping = dict()
2308    for command_node in all_commands_nodes:
2309        command_name = command_node.find('proto').find('name').text
2310        if command_name not in all_commands_names:
2311            continue
2312
2313        command_to_param_types_mapping[command_name] = get_command_params_text(
2314            command_node, command_name)
2315
2316    call_replay_cases = format_capture_replay_call_case(api, command_to_param_types_mapping,
2317                                                        cmd_packed_gl_enums, packed_param_types)
2318
2319    source_content = TEMPLATE_CAPTURE_REPLAY_SOURCE.format(
2320        script_name=os.path.basename(sys.argv[0]),
2321        data_source_name="gl.xml and gl_angle_ext.xml",
2322        call_replay_cases=call_replay_cases,
2323    )
2324    source_file_path = registry_xml.script_relative(
2325        "../src/libANGLE/capture/frame_capture_replay_autogen.cpp")
2326    with open(source_file_path, 'w') as f:
2327        f.write(source_content)
2328
2329
2330def write_windows_def_file(data_source_name, lib, libexport, folder, exports):
2331
2332    content = TEMPLATE_WINDOWS_DEF_FILE.format(
2333        script_name=os.path.basename(sys.argv[0]),
2334        data_source_name=data_source_name,
2335        exports="\n".join(exports),
2336        lib=libexport)
2337
2338    path = path_to(folder, "%s_autogen.def" % lib)
2339
2340    with open(path, "w") as out:
2341        out.write(content)
2342        out.close()
2343
2344
2345def get_exports(commands, fmt=None):
2346    if fmt:
2347        return ["    %s" % fmt(cmd) for cmd in sorted(commands)]
2348    else:
2349        return ["    %s" % cmd for cmd in sorted(commands)]
2350
2351
2352# Get EGL exports
2353def get_egl_exports():
2354
2355    egl = registry_xml.RegistryXML('egl.xml', 'egl_angle_ext.xml')
2356    exports = []
2357
2358    capser = lambda fn: "EGL_" + fn[3:]
2359
2360    for major, minor in registry_xml.EGL_VERSIONS:
2361        annotation = "{}_{}".format(major, minor)
2362        name_prefix = "EGL_VERSION_"
2363
2364        feature_name = "{}{}".format(name_prefix, annotation)
2365
2366        egl.AddCommands(feature_name, annotation)
2367
2368        commands = egl.commands[annotation]
2369
2370        if len(commands) == 0:
2371            continue
2372
2373        exports.append("\n    ; EGL %d.%d" % (major, minor))
2374        exports += get_exports(commands, capser)
2375
2376    egl.AddExtensionCommands(registry_xml.supported_egl_extensions, ['egl'])
2377
2378    for extension_name, ext_cmd_names in sorted(egl.ext_data.items()):
2379
2380        if len(ext_cmd_names) == 0:
2381            continue
2382
2383        exports.append("\n    ; %s" % extension_name)
2384        exports += get_exports(ext_cmd_names, capser)
2385
2386    return exports
2387
2388
2389# Construct a mapping from an EGL EP to object function
2390def get_egl_entry_point_labeled_object(ep_to_object, cmd_stripped, params, packed_enums):
2391
2392    if not ep_to_object:
2393        return ""
2394
2395    # Finds a packed parameter name in a list of params
2396    def find_param(params, type_name, packed_enums):
2397        for param in params:
2398            if just_the_type_packed(param, packed_enums).split(' ')[0] == type_name:
2399                return just_the_name_packed(param, packed_enums)
2400        return None
2401
2402    display_param = find_param(params, "egl::Display", packed_enums)
2403
2404    # For entry points not listed in the JSON file, they default to an EGLDisplay or nothing.
2405    if cmd_stripped not in ep_to_object:
2406        if display_param:
2407            return "GetDisplayIfValid(%s)" % display_param
2408        return "nullptr"
2409
2410    # We first handle a few special cases for certain type categories.
2411    category = ep_to_object[cmd_stripped]
2412    if category == "Thread":
2413        return "GetThreadIfValid(thread)"
2414    found_param = find_param(params, category, packed_enums)
2415    if category == "Context" and not found_param:
2416        return "GetContextIfValid(thread->getDisplay(), thread->getContext())"
2417    assert found_param, "Did not find %s for %s: %s" % (category, cmd_stripped, str(params))
2418    if category == "Device":
2419        return "GetDeviceIfValid(%s)" % found_param
2420    if category == "LabeledObject":
2421        object_type_param = find_param(params, "ObjectType", packed_enums)
2422        return "GetLabeledObjectIfValid(thread, %s, %s, %s)" % (display_param, object_type_param,
2423                                                                found_param)
2424
2425    # We then handle the general case which handles the rest of the type categories.
2426    return "Get%sIfValid(%s, %s)" % (category, display_param, found_param)
2427
2428
2429def write_stubs_header(api, annotation, title, data_source, out_file, all_commands, commands,
2430                       cmd_packed_egl_enums, packed_param_types):
2431
2432    stubs = []
2433
2434    for command in all_commands:
2435        proto = command.find('proto')
2436        cmd_name = proto.find('name').text
2437
2438        if cmd_name not in commands:
2439            continue
2440
2441        proto_text = "".join(proto.itertext())
2442        params = [] if api == apis.CL else ["Thread *thread"]
2443        params += ["".join(param.itertext()) for param in command.findall('param')]
2444        if params and just_the_name(params[-1]) == "errcode_ret":
2445            params[-1] = "cl_int &errorCode"
2446        return_type = proto_text[:-len(cmd_name)].strip()
2447
2448        internal_params = get_internal_params(api, cmd_name, params, cmd_packed_egl_enums,
2449                                              packed_param_types)
2450
2451        stubs.append("%s %s(%s);" % (return_type, strip_api_prefix(cmd_name), internal_params))
2452
2453    args = {
2454        "annotation_lower": annotation.lower(),
2455        "annotation_upper": annotation.upper(),
2456        "data_source_name": data_source,
2457        "script_name": os.path.basename(sys.argv[0]),
2458        "stubs": "\n".join(stubs),
2459        "title": title,
2460    }
2461
2462    output = get_stubs_header_template(api).format(**args)
2463
2464    with open(out_file, "w") as f:
2465        f.write(output)
2466
2467
2468def main():
2469
2470    # auto_script parameters.
2471    if len(sys.argv) > 1:
2472        inputs = [
2473            'entry_point_packed_egl_enums.json', 'entry_point_packed_gl_enums.json',
2474            EGL_GET_LABELED_OBJECT_DATA_PATH
2475        ] + registry_xml.xml_inputs
2476        outputs = [
2477            CL_STUBS_HEADER_PATH,
2478            EGL_STUBS_HEADER_PATH,
2479            EGL_EXT_STUBS_HEADER_PATH,
2480            '../src/libOpenCL/libOpenCL_autogen.cpp',
2481            '../src/common/entry_points_enum_autogen.cpp',
2482            '../src/common/entry_points_enum_autogen.h',
2483            '../src/libANGLE/Context_gl_1_autogen.h',
2484            '../src/libANGLE/Context_gl_2_autogen.h',
2485            '../src/libANGLE/Context_gl_3_autogen.h',
2486            '../src/libANGLE/Context_gl_4_autogen.h',
2487            '../src/libANGLE/Context_gles_1_0_autogen.h',
2488            '../src/libANGLE/Context_gles_2_0_autogen.h',
2489            '../src/libANGLE/Context_gles_3_0_autogen.h',
2490            '../src/libANGLE/Context_gles_3_1_autogen.h',
2491            '../src/libANGLE/Context_gles_3_2_autogen.h',
2492            '../src/libANGLE/Context_gles_ext_autogen.h',
2493            '../src/libANGLE/capture/capture_gles_1_0_autogen.cpp',
2494            '../src/libANGLE/capture/capture_gles_1_0_autogen.h',
2495            '../src/libANGLE/capture/capture_gles_2_0_autogen.cpp',
2496            '../src/libANGLE/capture/capture_gles_2_0_autogen.h',
2497            '../src/libANGLE/capture/capture_gles_3_0_autogen.cpp',
2498            '../src/libANGLE/capture/capture_gles_3_0_autogen.h',
2499            '../src/libANGLE/capture/capture_gles_3_1_autogen.cpp',
2500            '../src/libANGLE/capture/capture_gles_3_1_autogen.h',
2501            '../src/libANGLE/capture/capture_gles_3_2_autogen.cpp',
2502            '../src/libANGLE/capture/capture_gles_3_2_autogen.h',
2503            '../src/libANGLE/capture/capture_gles_ext_autogen.cpp',
2504            '../src/libANGLE/capture/capture_gles_ext_autogen.h',
2505            '../src/libANGLE/capture/frame_capture_replay_autogen.cpp',
2506            '../src/libANGLE/capture/frame_capture_utils_autogen.cpp',
2507            '../src/libANGLE/capture/frame_capture_utils_autogen.h',
2508            '../src/libANGLE/validationCL_autogen.h',
2509            '../src/libANGLE/validationEGL_autogen.h',
2510            '../src/libANGLE/validationES1_autogen.h',
2511            '../src/libANGLE/validationES2_autogen.h',
2512            '../src/libANGLE/validationES31_autogen.h',
2513            '../src/libANGLE/validationES32_autogen.h',
2514            '../src/libANGLE/validationES3_autogen.h',
2515            '../src/libANGLE/validationESEXT_autogen.h',
2516            '../src/libANGLE/validationGL1_autogen.h',
2517            '../src/libANGLE/validationGL2_autogen.h',
2518            '../src/libANGLE/validationGL3_autogen.h',
2519            '../src/libANGLE/validationGL4_autogen.h',
2520            '../src/libEGL/libEGL_autogen.cpp',
2521            '../src/libEGL/libEGL_autogen.def',
2522            '../src/libGLESv2/entry_points_cl_autogen.cpp',
2523            '../src/libGLESv2/entry_points_cl_autogen.h',
2524            '../src/libGLESv2/entry_points_egl_autogen.cpp',
2525            '../src/libGLESv2/entry_points_egl_autogen.h',
2526            '../src/libGLESv2/entry_points_egl_ext_autogen.cpp',
2527            '../src/libGLESv2/entry_points_egl_ext_autogen.h',
2528            '../src/libGLESv2/entry_points_gles_1_0_autogen.cpp',
2529            '../src/libGLESv2/entry_points_gles_1_0_autogen.h',
2530            '../src/libGLESv2/entry_points_gles_2_0_autogen.cpp',
2531            '../src/libGLESv2/entry_points_gles_2_0_autogen.h',
2532            '../src/libGLESv2/entry_points_gles_3_0_autogen.cpp',
2533            '../src/libGLESv2/entry_points_gles_3_0_autogen.h',
2534            '../src/libGLESv2/entry_points_gles_3_1_autogen.cpp',
2535            '../src/libGLESv2/entry_points_gles_3_1_autogen.h',
2536            '../src/libGLESv2/entry_points_gles_3_2_autogen.cpp',
2537            '../src/libGLESv2/entry_points_gles_3_2_autogen.h',
2538            '../src/libGLESv2/entry_points_gles_ext_autogen.cpp',
2539            '../src/libGLESv2/entry_points_gles_ext_autogen.h',
2540            '../src/libGLESv2/libGLESv2_autogen.cpp',
2541            '../src/libGLESv2/libGLESv2_autogen.def',
2542            '../src/libGLESv2/libGLESv2_no_capture_autogen.def',
2543            '../src/libGLESv2/libGLESv2_with_capture_autogen.def',
2544            '../src/libGL/entry_points_gl_1_autogen.cpp',
2545            '../src/libGL/entry_points_gl_1_autogen.h',
2546            '../src/libGL/entry_points_gl_2_autogen.cpp',
2547            '../src/libGL/entry_points_gl_2_autogen.h',
2548            '../src/libGL/entry_points_gl_3_autogen.cpp',
2549            '../src/libGL/entry_points_gl_3_autogen.h',
2550            '../src/libGL/entry_points_gl_4_autogen.cpp',
2551            '../src/libGL/entry_points_gl_4_autogen.h',
2552            '../src/libGL/libGL_autogen.cpp',
2553            '../src/libGL/libGL_autogen.def',
2554        ]
2555
2556        if sys.argv[1] == 'inputs':
2557            print(','.join(inputs))
2558        elif sys.argv[1] == 'outputs':
2559            print(','.join(outputs))
2560        else:
2561            print('Invalid script parameters')
2562            return 1
2563        return 0
2564
2565    glesdecls = {}
2566    glesdecls['core'] = {}
2567    glesdecls['exts'] = {}
2568    for ver in registry_xml.GLES_VERSIONS:
2569        glesdecls['core'][ver] = []
2570    for ver in ['GLES1 Extensions', 'GLES2+ Extensions', 'ANGLE Extensions']:
2571        glesdecls['exts'][ver] = {}
2572
2573    libgles_ep_defs = []
2574    libgles_ep_exports = []
2575
2576    xml = registry_xml.RegistryXML('gl.xml', 'gl_angle_ext.xml')
2577
2578    # Stores core commands to keep track of duplicates
2579    all_commands_no_suffix = []
2580    all_commands_with_suffix = []
2581
2582    # First run through the main GLES entry points.  Since ES2+ is the primary use
2583    # case, we go through those first and then add ES1-only APIs at the end.
2584    for major_version, minor_version in registry_xml.GLES_VERSIONS:
2585        version = "{}_{}".format(major_version, minor_version)
2586        annotation = "GLES_{}".format(version)
2587        name_prefix = "GL_ES_VERSION_"
2588
2589        if major_version == 1:
2590            name_prefix = "GL_VERSION_ES_CM_"
2591
2592        comment = version.replace("_", ".")
2593        feature_name = "{}{}".format(name_prefix, version)
2594
2595        xml.AddCommands(feature_name, version)
2596
2597        version_commands = xml.commands[version]
2598        all_commands_no_suffix.extend(xml.commands[version])
2599        all_commands_with_suffix.extend(xml.commands[version])
2600
2601        eps = GLEntryPoints(apis.GLES, xml, version_commands)
2602        eps.decls.insert(0, "extern \"C\" {")
2603        eps.decls.append("} // extern \"C\"")
2604        eps.defs.insert(0, "extern \"C\" {")
2605        eps.defs.append("} // extern \"C\"")
2606
2607        # Write the version as a comment before the first EP.
2608        libgles_ep_exports.append("\n    ; OpenGL ES %s" % comment)
2609
2610        libgles_ep_defs += ["\n// OpenGL ES %s" % comment] + eps.export_defs
2611        libgles_ep_exports += get_exports(version_commands)
2612
2613        major_if_not_one = major_version if major_version != 1 else ""
2614        minor_if_not_zero = minor_version if minor_version != 0 else ""
2615
2616        header_includes = TEMPLATE_HEADER_INCLUDES.format(
2617            major=major_if_not_one, minor=minor_if_not_zero)
2618
2619        # We include the platform.h header since it undefines the conflicting MemoryBarrier macro.
2620        if major_version == 3 and minor_version == 1:
2621            header_includes += "\n#include \"common/platform.h\"\n"
2622
2623        version_annotation = "%s%s" % (major_version, minor_if_not_zero)
2624        source_includes = TEMPLATE_SOURCES_INCLUDES.format(
2625            header_version=annotation.lower(), validation_header_version="ES" + version_annotation)
2626
2627        write_file(annotation, "GLES " + comment, TEMPLATE_ENTRY_POINT_HEADER,
2628                   "\n".join(eps.decls), "h", header_includes, "libGLESv2", "gl.xml")
2629        write_file(annotation, "GLES " + comment, TEMPLATE_ENTRY_POINT_SOURCE, "\n".join(eps.defs),
2630                   "cpp", source_includes, "libGLESv2", "gl.xml")
2631
2632        glesdecls['core'][(major_version,
2633                           minor_version)] = get_decls(apis.GLES, CONTEXT_DECL_FORMAT,
2634                                                       xml.all_commands, version_commands, [],
2635                                                       GLEntryPoints.get_packed_enums())
2636
2637        validation_annotation = "ES%s%s" % (major_version, minor_if_not_zero)
2638        write_gl_validation_header(validation_annotation, "ES %s" % comment, eps.validation_protos,
2639                                   "gl.xml and gl_angle_ext.xml")
2640
2641        write_capture_header(version, comment, eps.capture_protos, eps.capture_pointer_funcs)
2642        write_capture_source(version, validation_annotation, comment, eps.capture_methods)
2643
2644    # After we finish with the main entry points, we process the extensions.
2645    extension_decls = ["extern \"C\" {"]
2646    extension_defs = ["extern \"C\" {"]
2647    extension_commands = []
2648
2649    # Accumulated validation prototypes.
2650    ext_validation_protos = []
2651    ext_capture_protos = []
2652    ext_capture_methods = []
2653    ext_capture_pointer_funcs = []
2654
2655    for gles1ext in registry_xml.gles1_extensions:
2656        glesdecls['exts']['GLES1 Extensions'][gles1ext] = []
2657    for glesext in registry_xml.gles_extensions:
2658        glesdecls['exts']['GLES2+ Extensions'][glesext] = []
2659    for angle_ext in registry_xml.angle_extensions:
2660        glesdecls['exts']['ANGLE Extensions'][angle_ext] = []
2661
2662    xml.AddExtensionCommands(registry_xml.supported_extensions, ['gles2', 'gles1'])
2663
2664    for extension_name, ext_cmd_names in sorted(xml.ext_data.items()):
2665        extension_commands.extend(xml.ext_data[extension_name])
2666
2667        # Detect and filter duplicate extensions.
2668        eps = GLEntryPoints(apis.GLES, xml, ext_cmd_names)
2669
2670        # Write the extension name as a comment before the first EP.
2671        comment = "\n// {}".format(extension_name)
2672        libgles_ep_exports.append("\n    ; %s" % extension_name)
2673
2674        extension_defs += [comment] + eps.defs
2675        extension_decls += [comment] + eps.decls
2676
2677        # Avoid writing out entry points defined by a prior extension.
2678        for dupe in xml.ext_dupes[extension_name]:
2679            msg = "// {} is already defined.\n".format(strip_api_prefix(dupe))
2680            extension_defs.append(msg)
2681
2682        ext_validation_protos += [comment] + eps.validation_protos
2683        ext_capture_protos += [comment] + eps.capture_protos
2684        ext_capture_methods += eps.capture_methods
2685        ext_capture_pointer_funcs += eps.capture_pointer_funcs
2686
2687        libgles_ep_defs += [comment] + eps.export_defs
2688        libgles_ep_exports += get_exports(ext_cmd_names)
2689
2690        if (extension_name in registry_xml.gles1_extensions and
2691                extension_name not in GLES1_NO_CONTEXT_DECL_EXTENSIONS):
2692            glesdecls['exts']['GLES1 Extensions'][extension_name] = get_decls(
2693                apis.GLES, CONTEXT_DECL_FORMAT, xml.all_commands, ext_cmd_names,
2694                all_commands_no_suffix, GLEntryPoints.get_packed_enums())
2695        if extension_name in registry_xml.gles_extensions:
2696            glesdecls['exts']['GLES2+ Extensions'][extension_name] = get_decls(
2697                apis.GLES, CONTEXT_DECL_FORMAT, xml.all_commands, ext_cmd_names,
2698                all_commands_no_suffix, GLEntryPoints.get_packed_enums())
2699        if extension_name in registry_xml.angle_extensions:
2700            glesdecls['exts']['ANGLE Extensions'][extension_name] = get_decls(
2701                apis.GLES, CONTEXT_DECL_FORMAT, xml.all_commands, ext_cmd_names,
2702                all_commands_no_suffix, GLEntryPoints.get_packed_enums())
2703
2704    for name in extension_commands:
2705        all_commands_with_suffix.append(name)
2706        all_commands_no_suffix.append(strip_suffix(apis.GLES, name))
2707
2708    # Now we generate entry points for the desktop implementation
2709    desktop_gl_decls = {}
2710    desktop_gl_decls['core'] = {}
2711    for major, _ in registry_xml.DESKTOP_GL_VERSIONS:
2712        desktop_gl_decls['core'][(major, "X")] = []
2713
2714    libgl_ep_defs = []
2715    libgl_ep_exports = []
2716
2717    glxml = registry_xml.RegistryXML('gl.xml')
2718
2719    for major_version in sorted(
2720            set([major for (major, minor) in registry_xml.DESKTOP_GL_VERSIONS])):
2721        is_major = lambda ver: ver[0] == major_version
2722
2723        ver_decls = ["extern \"C\" {"]
2724        ver_defs = ["extern \"C\" {"]
2725        validation_protos = []
2726
2727        for _, minor_version in filter(is_major, registry_xml.DESKTOP_GL_VERSIONS):
2728            version = "{}_{}".format(major_version, minor_version)
2729            annotation = "GL_{}".format(version)
2730            name_prefix = "GL_VERSION_"
2731
2732            comment = version.replace("_", ".")
2733            feature_name = "{}{}".format(name_prefix, version)
2734
2735            glxml.AddCommands(feature_name, version)
2736
2737            all_libgl_commands = glxml.commands[version]
2738
2739            just_libgl_commands = [
2740                cmd for cmd in all_libgl_commands if cmd not in all_commands_no_suffix
2741            ]
2742            just_libgl_commands_suffix = [
2743                cmd for cmd in all_libgl_commands if cmd not in all_commands_with_suffix
2744            ]
2745
2746            # Validation duplicates handled with suffix
2747            eps_suffix = GLEntryPoints(apis.GL, glxml, just_libgl_commands_suffix)
2748            eps = GLEntryPoints(apis.GL, glxml, all_libgl_commands)
2749
2750            desktop_gl_decls['core'][(major_version,
2751                                      "X")] += get_decls(apis.GL, CONTEXT_DECL_FORMAT,
2752                                                         glxml.all_commands, just_libgl_commands,
2753                                                         all_commands_no_suffix,
2754                                                         GLEntryPoints.get_packed_enums())
2755
2756            # Write the version as a comment before the first EP.
2757            cpp_comment = "\n// GL %s" % comment
2758            def_comment = "\n    ; GL %s" % comment
2759
2760            libgl_ep_defs += [cpp_comment] + eps.export_defs
2761            libgl_ep_exports += [def_comment] + get_exports(all_libgl_commands)
2762            validation_protos += [cpp_comment] + eps_suffix.validation_protos
2763            ver_decls += [cpp_comment] + eps.decls
2764            ver_defs += [cpp_comment] + eps.defs
2765
2766        ver_decls.append("} // extern \"C\"")
2767        ver_defs.append("} // extern \"C\"")
2768        annotation = "GL_%d" % major_version
2769        name = "Desktop GL %s.x" % major_version
2770
2771        source_includes = TEMPLATE_DESKTOP_GL_SOURCE_INCLUDES.format(annotation.lower(),
2772                                                                     major_version)
2773
2774        # Entry point files
2775        write_file(annotation, name, TEMPLATE_ENTRY_POINT_HEADER, "\n".join(ver_decls), "h",
2776                   DESKTOP_GL_HEADER_INCLUDES, "libGL", "gl.xml")
2777        write_file(annotation, name, TEMPLATE_ENTRY_POINT_SOURCE, "\n".join(ver_defs), "cpp",
2778                   source_includes, "libGL", "gl.xml")
2779
2780        # Validation files
2781        write_gl_validation_header("GL%s" % major_version, name, validation_protos, "gl.xml")
2782
2783    # OpenCL
2784    clxml = registry_xml.RegistryXML('cl.xml')
2785
2786    cl_validation_protos = []
2787    cl_decls = ["namespace cl\n{"]
2788    cl_defs = ["namespace cl\n{"]
2789    libcl_ep_defs = []
2790    libcl_windows_def_exports = []
2791    cl_commands = []
2792
2793    for major_version, minor_version in registry_xml.CL_VERSIONS:
2794        version = "%d_%d" % (major_version, minor_version)
2795        annotation = "CL_%s" % version
2796        name_prefix = "CL_VERSION_"
2797
2798        comment = version.replace("_", ".")
2799        feature_name = "%s%s" % (name_prefix, version)
2800
2801        clxml.AddCommands(feature_name, version)
2802
2803        cl_version_commands = clxml.commands[version]
2804        cl_commands += cl_version_commands
2805
2806        # Spec revs may have no new commands.
2807        if not cl_version_commands:
2808            continue
2809
2810        eps = CLEntryPoints(clxml, cl_version_commands)
2811
2812        comment = "\n// CL %d.%d" % (major_version, minor_version)
2813        win_def_comment = "\n    ; CL %d.%d" % (major_version, minor_version)
2814
2815        cl_decls += [comment] + eps.decls
2816        cl_defs += [comment] + eps.defs
2817        libcl_ep_defs += [comment] + eps.export_defs
2818        cl_validation_protos += [comment] + eps.validation_protos
2819        libcl_windows_def_exports += [win_def_comment] + get_exports(clxml.commands[version])
2820
2821    clxml.AddExtensionCommands(registry_xml.supported_cl_extensions, ['cl'])
2822    for extension_name, ext_cmd_names in sorted(clxml.ext_data.items()):
2823
2824        # Extensions may have no new commands.
2825        if not ext_cmd_names:
2826            continue
2827
2828        # Detect and filter duplicate extensions.
2829        eps = CLEntryPoints(clxml, ext_cmd_names)
2830
2831        comment = "\n// %s" % extension_name
2832        win_def_comment = "\n    ; %s" % (extension_name)
2833
2834        cl_commands += ext_cmd_names
2835
2836        cl_decls += [comment] + eps.decls
2837        cl_defs += [comment] + eps.defs
2838        libcl_ep_defs += [comment] + eps.export_defs
2839        cl_validation_protos += [comment] + eps.validation_protos
2840        libcl_windows_def_exports += [win_def_comment] + get_exports(ext_cmd_names)
2841
2842        # Avoid writing out entry points defined by a prior extension.
2843        for dupe in clxml.ext_dupes[extension_name]:
2844            msg = "// %s is already defined.\n" % strip_api_prefix(dupe)
2845            cl_defs.append(msg)
2846
2847    cl_decls.append("}  // namespace cl")
2848    cl_defs.append("}  // namespace cl")
2849
2850    write_file("cl", "CL", TEMPLATE_ENTRY_POINT_HEADER, "\n".join(cl_decls), "h",
2851               LIBCL_HEADER_INCLUDES, "libGLESv2", "cl.xml")
2852    write_file("cl", "CL", TEMPLATE_ENTRY_POINT_SOURCE, "\n".join(cl_defs), "cpp",
2853               LIBCL_SOURCE_INCLUDES, "libGLESv2", "cl.xml")
2854    write_validation_header("CL", "CL", cl_validation_protos, "cl.xml",
2855                            TEMPLATE_CL_VALIDATION_HEADER)
2856    write_stubs_header("CL", "cl", "CL", "cl.xml", CL_STUBS_HEADER_PATH, clxml.all_commands,
2857                       cl_commands, CLEntryPoints.get_packed_enums(), CL_PACKED_TYPES)
2858
2859    # EGL
2860    eglxml = registry_xml.RegistryXML('egl.xml', 'egl_angle_ext.xml')
2861
2862    egl_validation_protos = []
2863    egl_decls = ["extern \"C\" {"]
2864    egl_defs = ["extern \"C\" {"]
2865    libegl_ep_defs = []
2866    libegl_windows_def_exports = []
2867    egl_commands = []
2868
2869    for major_version, minor_version in registry_xml.EGL_VERSIONS:
2870        version = "%d_%d" % (major_version, minor_version)
2871        annotation = "EGL_%s" % version
2872        name_prefix = "EGL_VERSION_"
2873
2874        comment = version.replace("_", ".")
2875        feature_name = "%s%s" % (name_prefix, version)
2876
2877        eglxml.AddCommands(feature_name, version)
2878
2879        egl_version_commands = eglxml.commands[version]
2880        egl_commands += egl_version_commands
2881
2882        # Spec revs may have no new commands.
2883        if not egl_version_commands:
2884            continue
2885
2886        eps = EGLEntryPoints(eglxml, egl_version_commands)
2887
2888        comment = "\n// EGL %d.%d" % (major_version, minor_version)
2889        win_def_comment = "\n    ; EGL %d.%d" % (major_version, minor_version)
2890
2891        egl_decls += [comment] + eps.decls
2892        egl_defs += [comment] + eps.defs
2893        libegl_ep_defs += [comment] + eps.export_defs
2894        egl_validation_protos += [comment] + eps.validation_protos
2895        libegl_windows_def_exports += [win_def_comment] + get_exports(eglxml.commands[version])
2896
2897    egl_decls.append("} // extern \"C\"")
2898    egl_defs.append("} // extern \"C\"")
2899
2900    write_file("egl", "EGL", TEMPLATE_ENTRY_POINT_HEADER, "\n".join(egl_decls), "h",
2901               EGL_HEADER_INCLUDES, "libGLESv2", "egl.xml")
2902    write_file("egl", "EGL", TEMPLATE_ENTRY_POINT_SOURCE, "\n".join(egl_defs), "cpp",
2903               EGL_SOURCE_INCLUDES, "libGLESv2", "egl.xml")
2904    write_stubs_header("EGL", "egl", "EGL", "egl.xml", EGL_STUBS_HEADER_PATH, eglxml.all_commands,
2905                       egl_commands, EGLEntryPoints.get_packed_enums(), EGL_PACKED_TYPES)
2906
2907    eglxml.AddExtensionCommands(registry_xml.supported_egl_extensions, ['egl'])
2908    egl_ext_decls = ["extern \"C\" {"]
2909    egl_ext_defs = ["extern \"C\" {"]
2910    egl_ext_commands = []
2911
2912    for extension_name, ext_cmd_names in sorted(eglxml.ext_data.items()):
2913
2914        # Extensions may have no new commands.
2915        if not ext_cmd_names:
2916            continue
2917
2918        # Detect and filter duplicate extensions.
2919        eps = EGLEntryPoints(eglxml, ext_cmd_names)
2920
2921        comment = "\n// %s" % extension_name
2922        win_def_comment = "\n    ; %s" % (extension_name)
2923
2924        egl_ext_commands += ext_cmd_names
2925
2926        egl_ext_decls += [comment] + eps.decls
2927        egl_ext_defs += [comment] + eps.defs
2928        libegl_ep_defs += [comment] + eps.export_defs
2929        egl_validation_protos += [comment] + eps.validation_protos
2930        libegl_windows_def_exports += [win_def_comment] + get_exports(ext_cmd_names)
2931
2932        # Avoid writing out entry points defined by a prior extension.
2933        for dupe in eglxml.ext_dupes[extension_name]:
2934            msg = "// %s is already defined.\n" % strip_api_prefix(dupe)
2935            egl_ext_defs.append(msg)
2936
2937    egl_ext_decls.append("} // extern \"C\"")
2938    egl_ext_defs.append("} // extern \"C\"")
2939
2940    write_file("egl_ext", "EGL Extension", TEMPLATE_ENTRY_POINT_HEADER, "\n".join(egl_ext_decls),
2941               "h", EGL_EXT_HEADER_INCLUDES, "libGLESv2", "egl.xml and egl_angle_ext.xml")
2942    write_file("egl_ext", "EGL Extension", TEMPLATE_ENTRY_POINT_SOURCE, "\n".join(egl_ext_defs),
2943               "cpp", EGL_EXT_SOURCE_INCLUDES, "libGLESv2", "egl.xml and egl_angle_ext.xml")
2944    write_validation_header("EGL", "EGL", egl_validation_protos, "egl.xml and egl_angle_ext.xml",
2945                            TEMPLATE_EGL_VALIDATION_HEADER)
2946    write_stubs_header("EGL", "egl_ext", "EXT extension", "egl.xml and egl_angle_ext.xml",
2947                       EGL_EXT_STUBS_HEADER_PATH, eglxml.all_commands, egl_ext_commands,
2948                       EGLEntryPoints.get_packed_enums(), EGL_PACKED_TYPES)
2949
2950    # WGL
2951    wglxml = registry_xml.RegistryXML('wgl.xml')
2952
2953    name_prefix = "WGL_VERSION_"
2954    version = "1_0"
2955    comment = version.replace("_", ".")
2956    feature_name = "{}{}".format(name_prefix, version)
2957    wglxml.AddCommands(feature_name, version)
2958    wgl_commands = wglxml.commands[version]
2959
2960    wgl_commands = [cmd if cmd[:3] == 'wgl' else 'wgl' + cmd for cmd in wgl_commands]
2961
2962    # Write the version as a comment before the first EP.
2963    libgl_ep_exports.append("\n    ; WGL %s" % comment)
2964
2965    # Other versions of these functions are used
2966    wgl_commands.remove("wglUseFontBitmaps")
2967    wgl_commands.remove("wglUseFontOutlines")
2968
2969    libgl_ep_exports += get_exports(wgl_commands)
2970    extension_decls.append("} // extern \"C\"")
2971    extension_defs.append("} // extern \"C\"")
2972
2973    write_file("gles_ext", "GLES extension", TEMPLATE_ENTRY_POINT_HEADER,
2974               "\n".join([item for item in extension_decls]), "h", GLES_EXT_HEADER_INCLUDES,
2975               "libGLESv2", "gl.xml and gl_angle_ext.xml")
2976    write_file("gles_ext", "GLES extension", TEMPLATE_ENTRY_POINT_SOURCE,
2977               "\n".join([item for item in extension_defs]), "cpp", GLES_EXT_SOURCE_INCLUDES,
2978               "libGLESv2", "gl.xml and gl_angle_ext.xml")
2979
2980    write_gl_validation_header("ESEXT", "ES extension", ext_validation_protos,
2981                               "gl.xml and gl_angle_ext.xml")
2982    write_capture_header("ext", "extension", ext_capture_protos, ext_capture_pointer_funcs)
2983    write_capture_source("ext", "ESEXT", "extension", ext_capture_methods)
2984
2985    write_context_api_decls(glesdecls, "gles")
2986    write_context_api_decls(desktop_gl_decls, "gl")
2987
2988    # Entry point enum
2989    cl_cmd_names = [strip_api_prefix(cmd) for cmd in clxml.all_cmd_names.get_all_commands()]
2990    egl_cmd_names = [strip_api_prefix(cmd) for cmd in eglxml.all_cmd_names.get_all_commands()]
2991    gles_cmd_names = ["Invalid"
2992                     ] + [strip_api_prefix(cmd) for cmd in xml.all_cmd_names.get_all_commands()]
2993    gl_cmd_names = [strip_api_prefix(cmd) for cmd in glxml.all_cmd_names.get_all_commands()]
2994    wgl_cmd_names = [strip_api_prefix(cmd) for cmd in wglxml.all_cmd_names.get_all_commands()]
2995    unsorted_enums = [("CL%s" % cmd, "cl%s" % cmd) for cmd in cl_cmd_names] + [
2996        ("EGL%s" % cmd, "egl%s" % cmd) for cmd in egl_cmd_names
2997    ] + [("GL%s" % cmd, "gl%s" % cmd) for cmd in set(gles_cmd_names + gl_cmd_names)
2998        ] + [("WGL%s" % cmd, "wgl%s" % cmd) for cmd in wgl_cmd_names]
2999    all_enums = sorted(unsorted_enums)
3000
3001    entry_points_enum_header = TEMPLATE_ENTRY_POINTS_ENUM_HEADER.format(
3002        script_name=os.path.basename(sys.argv[0]),
3003        data_source_name="gl.xml and gl_angle_ext.xml",
3004        lib="GL/GLES",
3005        entry_points_list=",\n".join(["    " + enum for (enum, _) in all_enums]))
3006
3007    entry_points_enum_header_path = path_to("common", "entry_points_enum_autogen.h")
3008    with open(entry_points_enum_header_path, "w") as out:
3009        out.write(entry_points_enum_header)
3010        out.close()
3011
3012    entry_points_cases = [
3013        TEMPLATE_ENTRY_POINTS_NAME_CASE.format(enum=enum, cmd=cmd) for (enum, cmd) in all_enums
3014    ]
3015    entry_points_enum_source = TEMPLATE_ENTRY_POINTS_ENUM_SOURCE.format(
3016        script_name=os.path.basename(sys.argv[0]),
3017        data_source_name="gl.xml and gl_angle_ext.xml",
3018        lib="GL/GLES",
3019        entry_points_name_cases="\n".join(entry_points_cases))
3020
3021    entry_points_enum_source_path = path_to("common", "entry_points_enum_autogen.cpp")
3022    with open(entry_points_enum_source_path, "w") as out:
3023        out.write(entry_points_enum_source)
3024        out.close()
3025
3026    write_export_files("\n".join([item for item in libgles_ep_defs]), LIBGLESV2_EXPORT_INCLUDES,
3027                       "gl.xml and gl_angle_ext.xml", "libGLESv2", "OpenGL ES")
3028    write_export_files("\n".join([item for item in libgl_ep_defs]), LIBGL_EXPORT_INCLUDES,
3029                       "gl.xml and wgl.xml", "libGL", "Windows GL")
3030    write_export_files("\n".join([item for item in libegl_ep_defs]),
3031                       LIBEGL_EXPORT_INCLUDES_AND_PREAMBLE, "egl.xml and egl_angle_ext.xml",
3032                       "libEGL", "EGL")
3033    write_export_files("\n".join([item for item in libcl_ep_defs]), LIBCL_EXPORT_INCLUDES,
3034                       "cl.xml", "libOpenCL", "CL")
3035
3036    libgles_ep_exports += get_egl_exports()
3037
3038    everything = "Khronos and ANGLE XML files"
3039
3040    for lib in ["libGLESv2" + suffix for suffix in ["", "_no_capture", "_with_capture"]]:
3041        write_windows_def_file(everything, lib, lib, "libGLESv2", libgles_ep_exports)
3042    write_windows_def_file(everything, "libGL", "openGL32", "libGL", libgl_ep_exports)
3043    write_windows_def_file("egl.xml and egl_angle_ext.xml", "libEGL", "libEGL", "libEGL",
3044                           libegl_windows_def_exports)
3045
3046    all_gles_param_types = sorted(GLEntryPoints.all_param_types)
3047    write_capture_helper_header(all_gles_param_types)
3048    write_capture_helper_source(all_gles_param_types)
3049    write_capture_replay_source(apis.GLES, xml.all_commands, all_commands_no_suffix,
3050                                GLEntryPoints.get_packed_enums(), [])
3051
3052
3053if __name__ == '__main__':
3054    sys.exit(main())
3055