#!/usr/bin/python2
# Copyright 2018 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.
#
# gen_vk_mandatory_format_support_table.py:
#  Code generation for mandatory formats supported by Vulkan.
#  NOTE: don't run this script directly. Run scripts/run_code_generation.py.

import sys

sys.path.append('..')
import angle_format
import xml.etree.ElementTree as etree
import sys, os

TEMPLATE_TABLE_AUTOGEN_CPP = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {input_file_name} and
// the vk.xml file situated at
// /third_party/vulkan-validation-layers/src/scripts/vk.xml
//
// Copyright 2020 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.
//
// {out_file_name}:
//   Queries for full Vulkan mandatory format support information based on VK format.

#include "libANGLE/renderer/vulkan/vk_format_utils.h"

using namespace angle;

namespace rx
{{
namespace vk
{{
namespace
{{
constexpr VkFormatFeatureFlagBits BLIT_DST = VK_FORMAT_FEATURE_BLIT_DST_BIT;
constexpr VkFormatFeatureFlagBits BLIT_SRC = VK_FORMAT_FEATURE_BLIT_SRC_BIT;
constexpr VkFormatFeatureFlagBits COLOR_ATTACHMENT = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT;
constexpr VkFormatFeatureFlagBits COLOR_ATTACHMENT_BLEND = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT;
constexpr VkFormatFeatureFlagBits DEPTH_STENCIL_ATTACHMENT = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT;
constexpr VkFormatFeatureFlagBits SAMPLED_IMAGE = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
constexpr VkFormatFeatureFlagBits SAMPLED_IMAGE_FILTER_LINEAR = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
constexpr VkFormatFeatureFlagBits STORAGE_IMAGE = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT;
constexpr VkFormatFeatureFlagBits STORAGE_IMAGE_ATOMIC = VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT;
constexpr VkFormatFeatureFlagBits STORAGE_TEXEL_BUFFER = VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT;
constexpr VkFormatFeatureFlagBits STORAGE_TEXEL_BUFFER_ATOMIC = VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT;
constexpr VkFormatFeatureFlagBits UNIFORM_TEXEL_BUFFER = VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT;
constexpr VkFormatFeatureFlagBits VERTEX_BUFFER = VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT;

using namespace angle;

constexpr FormatMap<VkFormatProperties> kFormatProperties = {{
    {format_case_data}
}};
}}  // anonymous namespace

const VkFormatProperties& GetMandatoryFormatSupport(FormatID formatID)
{{
    return kFormatProperties[formatID];
}}
}}  // namespace vk
}}  // namespace rx
"""

TEMPLATE_FORMAT_PROPERTY = """{{FormatID::{format_id}, {{0, {optimal_features}, {buffer_features}}}}}"""


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


def gen_format_case(format_id, vk_format, vk_map):

    def de(str):
        return str.replace("VK_FORMAT_FEATURE_", "").replace("_BIT", "")

    if vk_format in vk_map and len(vk_map[vk_format]) > 0:
        # Check which feature is a buffer feature or not.
        buffer_features = [de(x) for x in vk_map[vk_format] if x.find("_BUFFER_") != -1]
        optimal_features = [de(x) for x in vk_map[vk_format] if x.find("_BUFFER_") == -1]
        optimal_features_str = "|".join(sorted(optimal_features)) if len(optimal_features) else "0"
        buffer_features_str = "|".join(sorted(buffer_features)) if len(buffer_features) else "0"
    else:
        optimal_features_str = "0"
        buffer_features_str = "0"

    return TEMPLATE_FORMAT_PROPERTY.format(
        format_id=format_id,
        vk_format=vk_format,
        optimal_features=optimal_features_str,
        buffer_features=buffer_features_str)


def main():

    input_file_name = 'vk_mandatory_format_support_data.json'
    vk_format_map_path = 'vk_format_map.json'
    out_file_name = 'vk_mandatory_format_support_table_autogen.cpp'
    vk_xml_file = '../../../../third_party/vulkan-deps/vulkan-headers/src/registry/vk.xml'

    # auto_script parameters.
    if len(sys.argv) > 1:
        inputs = [
            '../angle_format.py',
            input_file_name,
            vk_format_map_path,
            vk_xml_file,
        ]
        outputs = [out_file_name]

        if sys.argv[1] == 'inputs':
            print ','.join(inputs)
        elif sys.argv[1] == 'outputs':
            print ','.join(outputs)
        else:
            print('Invalid script parameters')
            return 1
        return 0

    tree = etree.parse(script_relative(vk_xml_file))
    root = tree.getroot()
    vk_format_enums = root.findall(".//enums[@name='VkFormat']/enum")
    vk_map = angle_format.load_json(input_file_name)
    vk_format_map = angle_format.load_json(vk_format_map_path)
    vk_cases = [
        gen_format_case(format_id, vk_format, vk_map)
        for format_id, vk_format in vk_format_map["map"].iteritems()
    ]

    output_cpp = TEMPLATE_TABLE_AUTOGEN_CPP.format(
        format_case_data=",\n".join(vk_cases),
        script_name=__file__,
        out_file_name=out_file_name,
        input_file_name=input_file_name)

    with open(out_file_name, 'wt') as out_file:
        out_file.write(output_cpp)
        out_file.close()
    return 0


if __name__ == '__main__':
    sys.exit(main())
