#!/usr/bin/python
#
# Copyright 2017 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# generate_entry_points.py:
#   Generates the OpenGL bindings and entry point layers for ANGLE.

import sys, os, pprint
import xml.etree.ElementTree as etree
from datetime import date

def script_relative(path):
    return os.path.join(os.path.dirname(sys.argv[0]), path)

tree = etree.parse(script_relative('gl.xml'))
root = tree.getroot()

gles2_xpath = ".//feature[@name='GL_ES_VERSION_2_0']//command"
gles2_commands = [cmd.attrib['name'] for cmd in root.findall(gles2_xpath)]

template_entry_point_header = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright {year} The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// entry_points_gles_{major_version}_{minor_version}_autogen.h:
//   Defines the GLES {major_version}.{minor_version} entry points.

#ifndef LIBGLESV2_ENTRYPOINTSGLES{major_version}{minor_version}_AUTOGEN_H_
#define LIBGLESV2_ENTRYPOINTSGLES{major_version}{minor_version}_AUTOGEN_H_

#include <GLES2/gl{major_version}.h>
#include <export.h>

namespace gl
{{
{entry_points}
}}  // namespace gl

#endif  // LIBGLESV2_ENTRYPOINTSGLES{major_version}{minor_version}_AUTOGEN_H_
"""

template_entry_point_decl = """ANGLE_EXPORT {return_type}GL_APIENTRY {name}({params});"""

commands = root.find(".//commands[@namespace='GL']")
entry_point_decls_gles_2_0 = []

def format_entry_point_decl(cmd_name, proto, params):
    return template_entry_point_decl.format(
        name = cmd_name[2:],
        return_type = proto[:-len(cmd_name)],
        params = ", ".join(params))

for cmd_name in gles2_commands:
    command_xpath = "command/proto[name='" + cmd_name + "']/.."
    command = commands.find(command_xpath)
    params = ["".join(param.itertext()) for param in command.findall("./param")]
    proto = "".join(command.find("./proto").itertext())
    entry_point_decls_gles_2_0 += [format_entry_point_decl(cmd_name, proto, params)]

gles_2_0_header = template_entry_point_header.format(
    script_name = os.path.basename(sys.argv[0]),
    data_source_name = "gl.xml",
    year = date.today().year,
    major_version = 2,
    minor_version = 0,
    entry_points = "\n".join(entry_point_decls_gles_2_0))

def path_to(folder, file):
    return os.path.join(script_relative(".."), "src", folder, file)

gles_2_0_header_path = path_to("libGLESv2", "entry_points_gles_2_0_autogen.h")

with open(gles_2_0_header_path, "w") as out:
    out.write(gles_2_0_header)
    out.close()
