diff --git a/SConstruct b/SConstruct index 94bc53eaa5c..72012ada999 100644 --- a/SConstruct +++ b/SConstruct @@ -15,6 +15,8 @@ from collections import OrderedDict # Local import methods import glsl_builders +import gles_builders +from platform_methods import run_in_subprocess # Scan possible build platforms @@ -706,6 +708,26 @@ if selected_platform in platform_list: } env.Append(BUILDERS=GLSL_BUILDERS) + if not env["platform"] == "server": # FIXME: detect GLES3 + env.Append( + BUILDERS={ + "GLES3_GLSL": env.Builder( + action=run_in_subprocess(gles_builders.build_gles3_headers), + suffix="glsl.gen.h", + src_suffix=".glsl", + ) + } + ) + env.Append( + BUILDERS={ + "GLES2_GLSL": env.Builder( + action=run_in_subprocess(gles_builders.build_gles2_headers), + suffix="glsl.gen.h", + src_suffix=".glsl", + ) + } + ) + scons_cache_path = os.environ.get("SCONS_CACHE") if scons_cache_path != None: CacheDir(scons_cache_path) diff --git a/core/os/os.h b/core/os/os.h index 2700759fefa..f02f600c588 100644 --- a/core/os/os.h +++ b/core/os/os.h @@ -68,6 +68,11 @@ class OS { bool restart_on_exit = false; List restart_commandline; + // for the user interface we keep a record of the current display driver + // so we can retrieve the rendering drivers available + int _display_driver_id = -1; + String _current_rendering_driver_name = ""; + protected: void _set_logger(CompositeLogger *p_logger); @@ -81,6 +86,11 @@ public: RENDER_SEPARATE_THREAD }; + enum RenderMainThreadMode { + RENDER_MAIN_THREAD_ONLY, + RENDER_ANY_THREAD, + }; + protected: friend class Main; // Needed by tests to setup command-line args. @@ -88,6 +98,7 @@ protected: HasServerFeatureCallback has_server_feature_callback = nullptr; RenderThreadMode _render_thread_mode = RENDER_THREAD_SAFE; + RenderMainThreadMode _render_main_thread_mode = RENDER_ANY_THREAD; // Functions used by Main to initialize/deinitialize the OS. void add_logger(Logger *p_logger); @@ -95,6 +106,9 @@ protected: virtual void initialize() = 0; virtual void initialize_joypads() = 0; + void set_current_rendering_driver_name(String p_driver_name) { _current_rendering_driver_name = p_driver_name; } + void set_display_driver_id(int p_display_driver_id) { _display_driver_id = p_display_driver_id; } + virtual void set_main_loop(MainLoop *p_main_loop) = 0; virtual void delete_main_loop() = 0; @@ -110,6 +124,9 @@ public: static OS *get_singleton(); + String get_current_rendering_driver_name() const { return _current_rendering_driver_name; } + int get_display_driver_id() const { return _display_driver_id; } + void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, Logger::ErrorType p_type = Logger::ERR_ERROR); void print(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3; void printerr(const char *p_format, ...) _PRINTF_FORMAT_ATTRIBUTE_2_3; @@ -241,6 +258,8 @@ public: virtual uint64_t get_free_static_memory() const; RenderThreadMode get_render_thread_mode() const { return _render_thread_mode; } + RenderMainThreadMode get_render_main_thread_mode() const { return _render_main_thread_mode; } + void set_render_main_thread_mode(RenderMainThreadMode p_thread_mode) { _render_main_thread_mode = p_thread_mode; } virtual String get_locale() const; String get_locale_language() const; diff --git a/drivers/SCsub b/drivers/SCsub index a7b21b855fe..c486a15856c 100644 --- a/drivers/SCsub +++ b/drivers/SCsub @@ -25,6 +25,11 @@ SConscript("winmidi/SCsub") # Graphics drivers if env["vulkan"]: SConscript("vulkan/SCsub") + SConscript("gles2/SCsub") + SConscript("gles_common/SCsub") + SConscript("gl_context/SCsub") +else: + SConscript("dummy/SCsub") # Core dependencies SConscript("png/SCsub") diff --git a/drivers/gl_context/SCsub b/drivers/gl_context/SCsub new file mode 100644 index 00000000000..ddeec6f4c6f --- /dev/null +++ b/drivers/gl_context/SCsub @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +Import("env") + +if env["platform"] in ["haiku", "osx", "windows", "linuxbsd"]: + # Thirdparty source files + thirdparty_dir = "#thirdparty/glad/" + thirdparty_sources = [ + "glad.c", + ] + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + env.Prepend(CPPPATH=[thirdparty_dir]) + + env.Append(CPPDEFINES=["GLAD_ENABLED"]) + env.Append(CPPDEFINES=["GLES_OVER_GL"]) + + env_thirdparty = env.Clone() + env_thirdparty.disable_warnings() + env_thirdparty.add_source_files(env.drivers_sources, thirdparty_sources) + +# Godot source files +env.add_source_files(env.drivers_sources, "*.cpp") diff --git a/drivers/gles2/SCsub b/drivers/gles2/SCsub new file mode 100644 index 00000000000..987ddcd16ed --- /dev/null +++ b/drivers/gles2/SCsub @@ -0,0 +1,7 @@ +#!/usr/bin/env python + +Import("env") + +env.add_source_files(env.drivers_sources, "*.cpp") + +SConscript("shaders/SCsub") diff --git a/drivers/gles2/rasterizer_canvas_base_gles2.cpp b/drivers/gles2/rasterizer_canvas_base_gles2.cpp new file mode 100644 index 00000000000..44eeede7575 --- /dev/null +++ b/drivers/gles2/rasterizer_canvas_base_gles2.cpp @@ -0,0 +1,1218 @@ +/*************************************************************************/ +/* rasterizer_canvas_base_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "rasterizer_canvas_base_gles2.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/os/os.h" +#include "drivers/gles_common/rasterizer_asserts.h" +#include "rasterizer_scene_gles2.h" + +#ifdef GODOT_3 +#include "core/project_settings.h" +#include "servers/visual/visual_server_raster.h" +#else +#include "core/config/project_settings.h" +#include "servers/rendering/rendering_server_default.h" +#endif + +#ifndef GLES_OVER_GL +#define glClearDepth glClearDepthf +#endif + +RID RasterizerCanvasBaseGLES2::light_internal_create() { + return RID(); +} + +void RasterizerCanvasBaseGLES2::light_internal_update(RID p_rid, Light *p_light) { +} + +void RasterizerCanvasBaseGLES2::light_internal_free(RID p_rid) { +} + +void RasterizerCanvasBaseGLES2::canvas_begin() { + state.using_transparent_rt = false; + + // always start with light_angle unset + state.using_light_angle = false; + state.using_large_vertex = false; + state.using_modulate = false; + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_LIGHT_ANGLE, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_MODULATE, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_LARGE_VERTEX, false); + state.canvas_shader.bind(); + + int viewport_x, viewport_y, viewport_width, viewport_height; + + if (storage->frame.current_rt) { + storage->bind_framebuffer(storage->frame.current_rt->fbo); + state.using_transparent_rt = storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]; + + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + // set Viewport and Scissor when rendering directly to screen + viewport_width = storage->_dims.rt_width; + viewport_height = storage->_dims.rt_height; + viewport_x = storage->frame.current_rt->x; + // FTODO + // viewport_y = OS::get_singleton()->get_window_size().height - viewport_height - storage->frame.current_rt->y; + viewport_y = storage->frame.current_rt->y; + + // viewport_x = 0; + // viewport_y = 0; + + glScissor(viewport_x, viewport_y, viewport_width, viewport_height); + glViewport(viewport_x, viewport_y, viewport_width, viewport_height); + glEnable(GL_SCISSOR_TEST); + } + } + + // FTODO .. this was commented out to try and get the clear color correct + //#ifdef GODOT3 + // OLD METHOD .. now done by render target rather than frame +#if 0 + if (storage->frame.clear_request) { + glClearColor(storage->frame.clear_request_color.r, + storage->frame.clear_request_color.g, + storage->frame.clear_request_color.b, + state.using_transparent_rt ? storage->frame.clear_request_color.a : 1.0); + glClear(GL_COLOR_BUFFER_BIT); + storage->frame.clear_request = false; + } +#endif + + // NEW METHOD + if (storage->frame.current_rt && storage->frame.current_rt->clear_requested) { + const Color &col = storage->frame.current_rt->clear_color; + glClearColor(col.r, col.g, col.b, col.a); + + // clear EVERYTHING. + // not clearing everything can be devastating on tiled renderers especially, + // because if anything is preserved, often the whole frame buffer needs to be preserved. + // Not sure if GL_ACCUM_BUFFER_BIT is needed or supported in GLES. + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + storage->frame.current_rt->clear_requested = false; + } + + //#endif + + /* + if (storage->frame.current_rt) { + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); + glColorMask(1, 1, 1, 1); + } + */ + + reset_canvas(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + + // set up default uniforms + + Transform3D canvas_transform; + + if (storage->frame.current_rt) { + float csy = 1.0; + // FTODO + // if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) { + // csy = -1.0; + // } + canvas_transform.translate(-(storage->frame.current_rt->width / 2.0f), -(storage->frame.current_rt->height / 2.0f), 0.0f); + canvas_transform.scale(Vector3(2.0f / storage->frame.current_rt->width, csy * -2.0f / storage->frame.current_rt->height, 1.0f)); + } else { + // FTODO + // Vector2 ssize = OS::get_singleton()->get_window_size(); + Vector2 ssize; + ssize.x = storage->_dims.win_width; + ssize.y = storage->_dims.win_height; + + canvas_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f); + canvas_transform.scale(Vector3(2.0f / ssize.width, -2.0f / ssize.height, 1.0f)); + } + + state.uniforms.projection_matrix = canvas_transform; + + state.uniforms.final_modulate = Color(1, 1, 1, 1); + + state.uniforms.modelview_matrix = Transform2D(); + state.uniforms.extra_matrix = Transform2D(); + + _set_uniforms(); + _bind_quad_buffer(); +} + +void RasterizerCanvasBaseGLES2::canvas_end() { + glBindBuffer(GL_ARRAY_BUFFER, 0); + + for (int i = 0; i < GD_VS::ARRAY_MAX; i++) { + glDisableVertexAttribArray(i); + } + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + //reset viewport to full window size + // int viewport_width = OS::get_singleton()->get_window_size().width; + // int viewport_height = OS::get_singleton()->get_window_size().height; + int viewport_width = storage->_dims.win_width; + int viewport_height = storage->_dims.win_height; + glViewport(0, 0, viewport_width, viewport_height); + glScissor(0, 0, viewport_width, viewport_height); + } + + state.using_texture_rect = false; + state.using_skeleton = false; + state.using_ninepatch = false; + state.using_transparent_rt = false; +} + +void RasterizerCanvasBaseGLES2::draw_generic_textured_rect(const Rect2 &p_rect, const Rect2 &p_src) { + state.canvas_shader.set_uniform(CanvasShaderGLES2::DST_RECT, Color(p_rect.position.x, p_rect.position.y, p_rect.size.x, p_rect.size.y)); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SRC_RECT, Color(p_src.position.x, p_src.position.y, p_src.size.x, p_src.size.y)); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); +} + +void RasterizerCanvasBaseGLES2::_set_texture_rect_mode(bool p_texture_rect, bool p_light_angle, bool p_modulate, bool p_large_vertex) { + // always set this directly (this could be state checked) + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_TEXTURE_RECT, p_texture_rect); + + if (state.using_light_angle != p_light_angle) { + state.using_light_angle = p_light_angle; + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_LIGHT_ANGLE, p_light_angle); + } + + if (state.using_modulate != p_modulate) { + state.using_modulate = p_modulate; + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_MODULATE, p_modulate); + } + + if (state.using_large_vertex != p_large_vertex) { + state.using_large_vertex = p_large_vertex; + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_ATTRIB_LARGE_VERTEX, p_large_vertex); + } +} + +RasterizerStorageGLES2::Texture *RasterizerCanvasBaseGLES2::_bind_canvas_texture(const RID &p_texture, const RID &p_normal_map) { + RasterizerStorageGLES2::Texture *tex_return = NULL; + + if (p_texture.is_valid()) { + RasterizerStorageGLES2::Texture *texture = storage->texture_owner.getornull(p_texture); + + if (!texture) { + state.current_tex = RID(); + state.current_tex_ptr = NULL; + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1); + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + + } else { + if (texture->redraw_if_visible) { + RenderingServerDefault::redraw_request(); + } + + texture = texture->get_ptr(); + + if (texture->render_target) { + texture->render_target->used_in_frame = true; + } + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1); + glBindTexture(GL_TEXTURE_2D, texture->tex_id); + + state.current_tex = p_texture; + state.current_tex_ptr = texture; + + // new for Godot 4. Set the texture min mag filter and repeat per item + // we use a wrapper to avoid noop GL state changes + texture->GLSetFilter(GL_TEXTURE_2D, state.current_filter); + + tex_return = texture; + } + } else { + state.current_tex = RID(); + state.current_tex_ptr = NULL; + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1); + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } + + if (p_normal_map == state.current_normal) { + //do none + state.canvas_shader.set_uniform(CanvasShaderGLES2::USE_DEFAULT_NORMAL, state.current_normal.is_valid()); + + } else if (p_normal_map.is_valid()) { + RasterizerStorageGLES2::Texture *normal_map = storage->texture_owner.getornull(p_normal_map); + + if (!normal_map) { + state.current_normal = RID(); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2); + glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); + state.canvas_shader.set_uniform(CanvasShaderGLES2::USE_DEFAULT_NORMAL, false); + + } else { + if (normal_map->redraw_if_visible) { //check before proxy, because this is usually used with proxies + RenderingServerDefault::redraw_request(); + } + + normal_map = normal_map->get_ptr(); + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2); + glBindTexture(GL_TEXTURE_2D, normal_map->tex_id); + state.current_normal = p_normal_map; + state.canvas_shader.set_uniform(CanvasShaderGLES2::USE_DEFAULT_NORMAL, true); + } + + } else { + state.current_normal = RID(); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2); + glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); + state.canvas_shader.set_uniform(CanvasShaderGLES2::USE_DEFAULT_NORMAL, false); + } + + return tex_return; +} + +/* +void RasterizerCanvasBaseGLES2::draw_window_margins(int *black_margin, RID *black_image) { + return; + + // FTODO + int window_w = storage->_dims.rt_width; + int window_h = storage->_dims.rt_height; + //Vector2 window_size = Vector2(window_w, window_h); + + // int window_h = window_size.height; + // int window_w = window_size.width; + + // glBindFramebuffer(GL_FRAMEBUFFER, storage->system_fbo); + // glViewport(0, 0, window_size.width, window_size.height); + + canvas_begin(); + + if (black_image[SIDE_LEFT].is_valid()) { + _bind_canvas_texture(black_image[SIDE_LEFT], RID()); + Size2 sz(storage->texture_get_width(black_image[SIDE_LEFT]), storage->texture_get_height(black_image[SIDE_LEFT])); + draw_generic_textured_rect(Rect2(0, 0, black_margin[SIDE_LEFT], window_h), + Rect2(0, 0, (float)black_margin[SIDE_LEFT] / sz.x, (float)(window_h) / sz.y)); + } else if (black_margin[SIDE_LEFT]) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + + draw_generic_textured_rect(Rect2(0, 0, black_margin[SIDE_LEFT], window_h), Rect2(0, 0, 1, 1)); + } + + if (black_image[SIDE_RIGHT].is_valid()) { + _bind_canvas_texture(black_image[SIDE_RIGHT], RID()); + Size2 sz(storage->texture_get_width(black_image[SIDE_RIGHT]), storage->texture_get_height(black_image[SIDE_RIGHT])); + draw_generic_textured_rect(Rect2(window_w - black_margin[SIDE_RIGHT], 0, black_margin[SIDE_RIGHT], window_h), + Rect2(0, 0, (float)black_margin[SIDE_RIGHT] / sz.x, (float)window_h / sz.y)); + } else if (black_margin[SIDE_RIGHT]) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + + draw_generic_textured_rect(Rect2(window_w - black_margin[SIDE_RIGHT], 0, black_margin[SIDE_RIGHT], window_h), Rect2(0, 0, 1, 1)); + } + + if (black_image[SIDE_TOP].is_valid()) { + _bind_canvas_texture(black_image[SIDE_TOP], RID()); + + Size2 sz(storage->texture_get_width(black_image[SIDE_TOP]), storage->texture_get_height(black_image[SIDE_TOP])); + draw_generic_textured_rect(Rect2(0, 0, window_w, black_margin[SIDE_TOP]), + Rect2(0, 0, (float)window_w / sz.x, (float)black_margin[SIDE_TOP] / sz.y)); + + } else if (black_margin[SIDE_TOP]) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + + draw_generic_textured_rect(Rect2(0, 0, window_w, black_margin[SIDE_TOP]), Rect2(0, 0, 1, 1)); + } + + if (black_image[SIDE_BOTTOM].is_valid()) { + _bind_canvas_texture(black_image[SIDE_BOTTOM], RID()); + + Size2 sz(storage->texture_get_width(black_image[SIDE_BOTTOM]), storage->texture_get_height(black_image[SIDE_BOTTOM])); + draw_generic_textured_rect(Rect2(0, window_h - black_margin[SIDE_BOTTOM], window_w, black_margin[SIDE_BOTTOM]), + Rect2(0, 0, (float)window_w / sz.x, (float)black_margin[SIDE_BOTTOM] / sz.y)); + + } else if (black_margin[SIDE_BOTTOM]) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + + draw_generic_textured_rect(Rect2(0, window_h - black_margin[SIDE_BOTTOM], window_w, black_margin[SIDE_BOTTOM]), Rect2(0, 0, 1, 1)); + } + + canvas_end(); +} +*/ + +void RasterizerCanvasBaseGLES2::_bind_quad_buffer() { + glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices); + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, NULL); +} + +void RasterizerCanvasBaseGLES2::_set_uniforms() { + state.canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX, state.uniforms.projection_matrix); + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.uniforms.modelview_matrix); + state.canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, state.uniforms.extra_matrix); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::FINAL_MODULATE, state.uniforms.final_modulate); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::TIME, storage->frame.time[0]); + + if (storage->frame.current_rt) { + Vector2 screen_pixel_size; + screen_pixel_size.x = 1.0 / storage->frame.current_rt->width; + screen_pixel_size.y = 1.0 / storage->frame.current_rt->height; + + state.canvas_shader.set_uniform(CanvasShaderGLES2::SCREEN_PIXEL_SIZE, screen_pixel_size); + } + + if (state.using_skeleton) { + state.canvas_shader.set_uniform(CanvasShaderGLES2::SKELETON_TRANSFORM, state.skeleton_transform); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SKELETON_TRANSFORM_INVERSE, state.skeleton_transform_inverse); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SKELETON_TEXTURE_SIZE, state.skeleton_texture_size); + } + + if (state.using_light) { + Light *light = state.using_light; + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_MATRIX, light->light_shader_xform); + Transform2D basis_inverse = light->light_shader_xform.affine_inverse().orthonormalized(); + basis_inverse.elements[2] = Vector2(); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_MATRIX_INVERSE, basis_inverse); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_LOCAL_MATRIX, light->xform_cache.affine_inverse()); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_COLOR, light->color * light->energy); + // state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_POS, light->light_shader_pos); + // FTODO + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_POS, light->light_shader_xform.elements[2]); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_HEIGHT, light->height); + + // FTODO + //state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_OUTSIDE_ALPHA, light->mode == GD_VS::CANVAS_LIGHT_MODE_MASK ? 1.0 : 0.0); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_OUTSIDE_ALPHA, 0.0f); + + if (state.using_shadow) { + // FTODO +#if 0 + RasterizerStorageGLES2::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(light->shadow_buffer); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 5); + glBindTexture(GL_TEXTURE_2D, cls->distance); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_MATRIX, light->shadow_matrix_cache); + state.canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_SHADOW_COLOR, light->shadow_color); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::SHADOWPIXEL_SIZE, (1.0 / light->shadow_buffer_size) * (1.0 + light->shadow_smooth)); + if (light->radius_cache == 0) { + state.canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_GRADIENT, 0.0); + } else { + state.canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_GRADIENT, light->shadow_gradient_length / (light->radius_cache * 1.1)); + } + state.canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_DISTANCE_MULT, light->radius_cache * 1.1); +#endif + } + } +} + +void RasterizerCanvasBaseGLES2::reset_canvas() { + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_DITHER); + glEnable(GL_BLEND); + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + // bind the back buffer to a texture so shaders can use it. + // It should probably use texture unit -3 (as GLES2 does as well) but currently that's buggy. + // keeping this for now as there's nothing else that uses texture unit 2 + // TODO ^ + if (storage->frame.current_rt) { + // glActiveTexture(GL_TEXTURE0 + 2); + // glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->copy_screen_effect.color); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasBaseGLES2::canvas_debug_viewport_shadows(Light *p_lights_with_shadow) { +} + +void RasterizerCanvasBaseGLES2::_copy_texscreen(const Rect2 &p_rect) { + state.canvas_texscreen_used = true; + + _copy_screen(p_rect); + + // back to canvas, force rebind + state.using_texture_rect = false; + state.canvas_shader.bind(); + _bind_canvas_texture(state.current_tex, state.current_normal); + _set_uniforms(); +} + +void RasterizerCanvasBaseGLES2::_draw_polygon(const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor, const float *p_weights, const int *p_bones) { + glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); + + uint32_t buffer_ofs = 0; + uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); +#endif + + storage->buffer_orphan_and_upload(data.polygon_buffer_size, 0, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), NULL); + buffer_ofs = buffer_ofs_after; + + if (p_singlecolor) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + Color m = *p_colors; + glVertexAttrib4f(GD_VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); + } else if (!p_colors) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + } else { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } + + if (p_uvs) { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + } + + if (p_weights && p_bones) { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(float) * 4 * p_vertex_count, p_weights, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_WEIGHTS); + glVertexAttribPointer(GD_VS::ARRAY_WEIGHTS, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(int) * 4 * p_vertex_count, p_bones, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_BONES); + glVertexAttribPointer(GD_VS::ARRAY_BONES, 4, GL_UNSIGNED_INT, GL_FALSE, sizeof(int) * 4, CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_WEIGHTS); + glDisableVertexAttribArray(GD_VS::ARRAY_BONES); + } + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); + + if (storage->config.support_32_bits_indices) { //should check for +#ifdef DEBUG_ENABLED + ERR_FAIL_COND((sizeof(int) * p_index_count) > data.polygon_index_buffer_size); +#endif + storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(int) * p_index_count, p_indices, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + + glDrawElements(GL_TRIANGLES, p_index_count, GL_UNSIGNED_INT, 0); + storage->info.render._2d_draw_call_count++; + } else { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND((sizeof(uint16_t) * p_index_count) > data.polygon_index_buffer_size); +#endif + uint16_t *index16 = (uint16_t *)alloca(sizeof(uint16_t) * p_index_count); + for (int i = 0; i < p_index_count; i++) { + index16[i] = uint16_t(p_indices[i]); + } + storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(uint16_t) * p_index_count, index16, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + glDrawElements(GL_TRIANGLES, p_index_count, GL_UNSIGNED_SHORT, 0); + storage->info.render._2d_draw_call_count++; + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasBaseGLES2::_draw_generic(GLuint p_primitive, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor) { + glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); + + uint32_t buffer_ofs = 0; + uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); +#endif + storage->buffer_orphan_and_upload(data.polygon_buffer_size, 0, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), NULL); + buffer_ofs = buffer_ofs_after; + + if (p_singlecolor) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + Color m = *p_colors; + glVertexAttrib4f(GD_VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); + } else if (!p_colors) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + } else { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } + + if (p_uvs) { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + } + + glDrawArrays(p_primitive, 0, p_vertex_count); + storage->info.render._2d_draw_call_count++; + + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasBaseGLES2::_draw_generic_indices(GLuint p_primitive, const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor) { + glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); + + uint32_t buffer_ofs = 0; + uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); +#endif + storage->buffer_orphan_and_upload(data.polygon_buffer_size, 0, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), NULL); + buffer_ofs = buffer_ofs_after; + + if (p_singlecolor) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + Color m = *p_colors; + glVertexAttrib4f(GD_VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); + } else if (!p_colors) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + } else { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } + + if (p_uvs) { + RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); + buffer_ofs = buffer_ofs_after; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + } + +#ifdef RASTERIZER_EXTRA_CHECKS + // very slow, do not enable in normal use + for (int n = 0; n < p_index_count; n++) { + RAST_DEV_DEBUG_ASSERT(p_indices[n] < p_vertex_count); + } +#endif + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); + + if (storage->config.support_32_bits_indices) { //should check for +#ifdef DEBUG_ENABLED + ERR_FAIL_COND((sizeof(int) * p_index_count) > data.polygon_index_buffer_size); +#endif + storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(int) * p_index_count, p_indices, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + glDrawElements(p_primitive, p_index_count, GL_UNSIGNED_INT, 0); + storage->info.render._2d_draw_call_count++; + } else { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND((sizeof(uint16_t) * p_index_count) > data.polygon_index_buffer_size); +#endif + uint16_t *index16 = (uint16_t *)alloca(sizeof(uint16_t) * p_index_count); + for (int i = 0; i < p_index_count; i++) { + index16[i] = uint16_t(p_indices[i]); + } + storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(uint16_t) * p_index_count, index16, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + glDrawElements(p_primitive, p_index_count, GL_UNSIGNED_SHORT, 0); + storage->info.render._2d_draw_call_count++; + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasBaseGLES2::_legacy_draw_poly_triangles(Item::CommandPolygon *p_poly, RasterizerStorageGLES2::Material *p_material) { + // return; + + const PolyData &pd = _polydata[p_poly->polygon.polygon_id]; + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + // FTODO + //RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(polygon->texture, polygon->normal_map); + RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(p_poly->texture, RID()); + + if (texture) { + Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + } + + _draw_polygon(pd.indices.ptr(), pd.indices.size(), pd.points.size(), pd.points.ptr(), pd.uvs.ptr(), pd.colors.ptr(), pd.colors.size() == 1, nullptr, nullptr); + +// _draw_polygon(polygon->indices.ptr(), polygon->count, polygon->points.size(), polygon->points.ptr(), polygon->uvs.ptr(), polygon->colors.ptr(), polygon->colors.size() == 1, polygon->weights.ptr(), polygon->bones.ptr()); +#ifdef GLES_OVER_GL +#if 0 + if (polygon->antialiased) { + glEnable(GL_LINE_SMOOTH); + if (polygon->antialiasing_use_indices) { + _draw_generic_indices(GL_LINE_STRIP, polygon->indices.ptr(), polygon->count, polygon->points.size(), polygon->points.ptr(), polygon->uvs.ptr(), polygon->colors.ptr(), polygon->colors.size() == 1); + } else { + _draw_generic(GL_LINE_LOOP, polygon->points.size(), polygon->points.ptr(), polygon->uvs.ptr(), polygon->colors.ptr(), polygon->colors.size() == 1); + } + glDisable(GL_LINE_SMOOTH); + } +#endif +#endif +} + +void RasterizerCanvasBaseGLES2::_legacy_draw_primitive(Item::CommandPrimitive *p_pr, RasterizerStorageGLES2::Material *p_material) { + // return; + + if (p_pr->point_count != 4) + return; // not sure if supported + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(RID(), RID()); + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, p_pr->colors[0].components); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.uniforms.modelview_matrix); + + _draw_gui_primitive(p_pr->point_count, p_pr->points, NULL, NULL); +} + +void RasterizerCanvasBaseGLES2::_legacy_draw_line(Item::CommandPrimitive *p_pr, RasterizerStorageGLES2::Material *p_material) { + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(RID(), RID()); + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, p_pr->colors[0].components); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.uniforms.modelview_matrix); + +#ifdef GLES_OVER_GL +// if (line->antialiased) +// glEnable(GL_LINE_SMOOTH); +#endif + _draw_gui_primitive(2, p_pr->points, NULL, NULL); + +#ifdef GLES_OVER_GL +// if (line->antialiased) +// glDisable(GL_LINE_SMOOTH); +#endif +} + +void RasterizerCanvasBaseGLES2::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs, const float *p_light_angles) { + static const GLenum prim[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN }; + + int color_offset = 0; + int uv_offset = 0; + int light_angle_offset = 0; + int stride = 2; + + if (p_colors) { + color_offset = stride; + stride += 4; + } + + if (p_uvs) { + uv_offset = stride; + stride += 2; + } + + if (p_light_angles) { //light_angles + light_angle_offset = stride; + stride += 1; + } + + RAST_DEV_DEBUG_ASSERT(p_points <= 4); + float buffer_data[(2 + 2 + 4 + 1) * 4]; + + for (int i = 0; i < p_points; i++) { + buffer_data[stride * i + 0] = p_vertices[i].x; + buffer_data[stride * i + 1] = p_vertices[i].y; + } + + if (p_colors) { + for (int i = 0; i < p_points; i++) { + buffer_data[stride * i + color_offset + 0] = p_colors[i].r; + buffer_data[stride * i + color_offset + 1] = p_colors[i].g; + buffer_data[stride * i + color_offset + 2] = p_colors[i].b; + buffer_data[stride * i + color_offset + 3] = p_colors[i].a; + } + } + + if (p_uvs) { + for (int i = 0; i < p_points; i++) { + buffer_data[stride * i + uv_offset + 0] = p_uvs[i].x; + buffer_data[stride * i + uv_offset + 1] = p_uvs[i].y; + } + } + + if (p_light_angles) { + for (int i = 0; i < p_points; i++) { + buffer_data[stride * i + light_angle_offset + 0] = p_light_angles[i]; + } + } + + glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); + storage->buffer_orphan_and_upload(data.polygon_buffer_size, 0, p_points * stride * 4 * sizeof(float), buffer_data, GL_ARRAY_BUFFER, _buffer_upload_usage_flag, true); + + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), NULL); + + if (p_colors) { + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(color_offset * sizeof(float))); + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + } + + if (p_uvs) { + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(uv_offset * sizeof(float))); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + } + + if (p_light_angles) { + glVertexAttribPointer(GD_VS::ARRAY_TANGENT, 1, GL_FLOAT, GL_FALSE, stride * sizeof(float), CAST_INT_TO_UCHAR_PTR(light_angle_offset * sizeof(float))); + glEnableVertexAttribArray(GD_VS::ARRAY_TANGENT); + } + + glDrawArrays(prim[p_points], 0, p_points); + storage->info.render._2d_draw_call_count++; + + if (p_light_angles) { + // may not be needed + glDisableVertexAttribArray(GD_VS::ARRAY_TANGENT); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasBaseGLES2::_copy_screen(const Rect2 &p_rect) { + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + ERR_PRINT_ONCE("Cannot use screen texture copying in render target set to render direct to screen."); + return; + } + + ERR_FAIL_COND_MSG(storage->frame.current_rt->copy_screen_effect.color == 0, "Can't use screen texture copying in a render target configured without copy buffers."); + + glDisable(GL_BLEND); + + Vector2 wh(storage->frame.current_rt->width, storage->frame.current_rt->height); + + Color copy_section(p_rect.position.x / wh.x, p_rect.position.y / wh.y, p_rect.size.x / wh.x, p_rect.size.y / wh.y); + + if (p_rect != Rect2()) { + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, true); + } + + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, !state.using_transparent_rt); + + storage->bind_framebuffer(storage->frame.current_rt->copy_screen_effect.fbo); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); + + storage->shaders.copy.bind(); + storage->shaders.copy.set_uniform(CopyShaderGLES2::COPY_SECTION, copy_section); + + const Vector2 vertpos[4] = { + Vector2(-1, -1), + Vector2(-1, 1), + Vector2(1, 1), + Vector2(1, -1), + }; + + const Vector2 uvpos[4] = { + Vector2(0, 0), + Vector2(0, 1), + Vector2(1, 1), + Vector2(1, 0) + }; + + const int indexpos[6] = { + 0, 1, 2, + 2, 3, 0 + }; + + _draw_polygon(indexpos, 6, 4, vertpos, uvpos, NULL, false); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, false); + + storage->bind_framebuffer(storage->frame.current_rt->fbo); + glEnable(GL_BLEND); +} + +void RasterizerCanvasBaseGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) { +#if 0 + RasterizerStorageGLES2::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(p_buffer); + ERR_FAIL_COND(!cls); + + glDisable(GL_BLEND); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_DITHER); + glDisable(GL_CULL_FACE); + glDepthFunc(GL_LEQUAL); + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + + glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo); + + state.canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES2::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows); + state.canvas_shadow_shader.bind(); + + glViewport(0, 0, cls->size, cls->height); + glClearDepth(1.0f); + glClearColor(1, 1, 1, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + GD_VS::CanvasOccluderPolygonCullMode cull = GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; + + for (int i = 0; i < 4; i++) { + //make sure it remains orthogonal, makes easy to read angle later + + Transform3D light; + light.origin[0] = p_light_xform[2][0]; + light.origin[1] = p_light_xform[2][1]; + light.basis[0][0] = p_light_xform[0][0]; + light.basis[0][1] = p_light_xform[1][0]; + light.basis[1][0] = p_light_xform[0][1]; + light.basis[1][1] = p_light_xform[1][1]; + + //light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1)); + + //p_near=1; + CameraMatrix projection; + { + real_t fov = 90; + real_t nearp = p_near; + real_t farp = p_far; + real_t aspect = 1.0; + + real_t ymax = nearp * Math::tan(Math::deg2rad(fov * 0.5)); + real_t ymin = -ymax; + real_t xmin = ymin * aspect; + real_t xmax = ymax * aspect; + + projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp); + } + + Vector3 cam_target = Basis(Vector3(0, 0, Math_PI * 2 * (i / 4.0))).xform(Vector3(0, 1, 0)); + projection = projection * CameraMatrix(Transform3D().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse()); + + state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::PROJECTION_MATRIX, projection); + state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::LIGHT_MATRIX, light); + state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::DISTANCE_NORM, 1.0 / p_far); + + if (i == 0) + *p_xform_cache = projection; + + glViewport(0, (cls->height / 4) * i, cls->size, cls->height / 4); + + LightOccluderInstance *instance = p_occluders; + + while (instance) { + RasterizerStorageGLES2::CanvasOccluder *cc = storage->canvas_occluder_owner.getornull(instance->polygon_buffer); + if (!cc || cc->len == 0 || !(p_light_mask & instance->light_mask)) { + instance = instance->next; + continue; + } + + state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::WORLD_MATRIX, instance->xform_cache); + + GD_VS::CanvasOccluderPolygonCullMode transformed_cull_cache = instance->cull_cache; + + if (transformed_cull_cache != GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED && + (p_light_xform.basis_determinant() * instance->xform_cache.basis_determinant()) < 0) { + transformed_cull_cache = + transformed_cull_cache == GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? + GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE : + GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE; + } + + if (cull != transformed_cull_cache) { + cull = transformed_cull_cache; + switch (cull) { + case GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED: { + glDisable(GL_CULL_FACE); + + } break; + case GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE: { + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); + } break; + case GD_VS::CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE: { + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + } break; + } + } + + glBindBuffer(GL_ARRAY_BUFFER, cc->vertex_id); + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cc->index_id); + + glDrawElements(GL_TRIANGLES, cc->len * 3, GL_UNSIGNED_SHORT, 0); + + instance = instance->next; + } + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +#endif +} + +void RasterizerCanvasBaseGLES2::draw_lens_distortion_rect(const Rect2 &p_rect, float p_k1, float p_k2, const Vector2 &p_eye_center, float p_oversample) { + Vector2 half_size; + if (storage->frame.current_rt) { + half_size = Vector2(storage->frame.current_rt->width, storage->frame.current_rt->height); + } else { + // half_size = OS::get_singleton()->get_window_size(); + half_size = Vector2(storage->_dims.win_width, storage->_dims.win_height); + } + half_size *= 0.5; + Vector2 offset((p_rect.position.x - half_size.x) / half_size.x, (p_rect.position.y - half_size.y) / half_size.y); + Vector2 scale(p_rect.size.x / half_size.x, p_rect.size.y / half_size.y); + + float aspect_ratio = p_rect.size.x / p_rect.size.y; + + // setup our lens shader + state.lens_shader.bind(); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::OFFSET, offset); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::SCALE, scale); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::K1, p_k1); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::K2, p_k2); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::EYE_CENTER, p_eye_center); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::UPSCALE, p_oversample); + state.lens_shader.set_uniform(LensDistortedShaderGLES2::ASPECT_RATIO, aspect_ratio); + + // bind our quad buffer + _bind_quad_buffer(); + + // and draw + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + // and cleanup + glBindBuffer(GL_ARRAY_BUFFER, 0); + + for (int i = 0; i < GD_VS::ARRAY_MAX; i++) { + glDisableVertexAttribArray(i); + } +} + +void RasterizerCanvasBaseGLES2::initialize() { + bool flag_stream = false; + //flag_stream = GLOBAL_GET("rendering/options/api_usage_legacy/flag_stream"); + if (flag_stream) + _buffer_upload_usage_flag = GL_STREAM_DRAW; + else + _buffer_upload_usage_flag = GL_DYNAMIC_DRAW; + + // quad buffer + { + glGenBuffers(1, &data.canvas_quad_vertices); + glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices); + + const float qv[8] = { + 0, 0, + 0, 1, + 1, 1, + 1, 0 + }; + + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 8, qv, GL_STATIC_DRAW); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + + // polygon buffer + { + uint32_t poly_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); + poly_size = MAX(poly_size, 128); // minimum 2k, may still see anomalies in editor + poly_size *= 1024; + glGenBuffers(1, &data.polygon_buffer); + glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); + glBufferData(GL_ARRAY_BUFFER, poly_size, NULL, GL_DYNAMIC_DRAW); + + data.polygon_buffer_size = poly_size; + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + uint32_t index_size = GLOBAL_DEF("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", 128); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); + index_size = MAX(index_size, 128); + index_size *= 1024; // kb + glGenBuffers(1, &data.polygon_index_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_size, NULL, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + data.polygon_index_buffer_size = index_size; + } + + // ninepatch buffers + { + // array buffer + glGenBuffers(1, &data.ninepatch_vertices); + glBindBuffer(GL_ARRAY_BUFFER, data.ninepatch_vertices); + + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * (16 + 16) * 2, NULL, GL_DYNAMIC_DRAW); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + // element buffer + glGenBuffers(1, &data.ninepatch_elements); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ninepatch_elements); + +#define _EIDX(y, x) (y * 4 + x) + uint8_t elems[3 * 2 * 9] = { + // first row + + _EIDX(0, 0), _EIDX(0, 1), _EIDX(1, 1), + _EIDX(1, 1), _EIDX(1, 0), _EIDX(0, 0), + + _EIDX(0, 1), _EIDX(0, 2), _EIDX(1, 2), + _EIDX(1, 2), _EIDX(1, 1), _EIDX(0, 1), + + _EIDX(0, 2), _EIDX(0, 3), _EIDX(1, 3), + _EIDX(1, 3), _EIDX(1, 2), _EIDX(0, 2), + + // second row + + _EIDX(1, 0), _EIDX(1, 1), _EIDX(2, 1), + _EIDX(2, 1), _EIDX(2, 0), _EIDX(1, 0), + + // the center one would be here, but we'll put it at the end + // so it's easier to disable the center and be able to use + // one draw call for both + + _EIDX(1, 2), _EIDX(1, 3), _EIDX(2, 3), + _EIDX(2, 3), _EIDX(2, 2), _EIDX(1, 2), + + // third row + + _EIDX(2, 0), _EIDX(2, 1), _EIDX(3, 1), + _EIDX(3, 1), _EIDX(3, 0), _EIDX(2, 0), + + _EIDX(2, 1), _EIDX(2, 2), _EIDX(3, 2), + _EIDX(3, 2), _EIDX(3, 1), _EIDX(2, 1), + + _EIDX(2, 2), _EIDX(2, 3), _EIDX(3, 3), + _EIDX(3, 3), _EIDX(3, 2), _EIDX(2, 2), + + // center field + + _EIDX(1, 1), _EIDX(1, 2), _EIDX(2, 2), + _EIDX(2, 2), _EIDX(2, 1), _EIDX(1, 1) + }; +#undef _EIDX + + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elems), elems, GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + state.canvas_shadow_shader.init(); + + state.canvas_shader.init(); + + _set_texture_rect_mode(true); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows); + + state.canvas_shader.bind(); + + state.lens_shader.init(); + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_PIXEL_SNAP, GLOBAL_DEF("rendering/quality/2d/use_pixel_snap", false)); + + state.using_light = NULL; + state.using_transparent_rt = false; + state.using_skeleton = false; +} + +RendererCanvasRender::PolygonID RasterizerCanvasBaseGLES2::request_polygon(const Vector &p_indices, const Vector &p_points, const Vector &p_colors, const Vector &p_uvs, const Vector &p_bones, const Vector &p_weights) { + uint32_t id = _polydata.alloc(); + PolyData &pd = _polydata[id]; + pd.indices = p_indices; + pd.points = p_points; + pd.colors = p_colors; + pd.uvs = p_uvs; + return id; +} +void RasterizerCanvasBaseGLES2::free_polygon(PolygonID p_polygon) { + _polydata.free(p_polygon); +} + +void RasterizerCanvasBaseGLES2::finalize() { +} + +RasterizerCanvasBaseGLES2::RasterizerCanvasBaseGLES2() { +} + +#endif diff --git a/drivers/gles2/rasterizer_canvas_base_gles2.h b/drivers/gles2/rasterizer_canvas_base_gles2.h new file mode 100644 index 00000000000..e2b396dca80 --- /dev/null +++ b/drivers/gles2/rasterizer_canvas_base_gles2.h @@ -0,0 +1,176 @@ +/*************************************************************************/ +/* rasterizer_canvas_base_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "drivers/gles_common/rasterizer_array.h" +#include "drivers/gles_common/rasterizer_common_stubs.h" +#include "drivers/gles_common/rasterizer_storage_common.h" +#include "drivers/gles_common/rasterizer_version.h" +#include "rasterizer_scene_gles2.h" +#include "rasterizer_storage_gles2.h" +#include "servers/rendering/renderer_compositor.h" + +#include "shaders/canvas.glsl.gen.h" +#include "shaders/canvas_shadow.glsl.gen.h" +#include "shaders/lens_distorted.glsl.gen.h" + +class RasterizerCanvasBaseGLES2 : public StubsCanvas { +public: + enum { + INSTANCE_ATTRIB_BASE = 8, + }; + + struct Uniforms { + Transform3D projection_matrix; + + Transform2D modelview_matrix; + Transform2D extra_matrix; + + Color final_modulate; + + float time; + }; + + struct Data { + GLuint canvas_quad_vertices; + GLuint polygon_buffer; + GLuint polygon_index_buffer; + + uint32_t polygon_buffer_size; + uint32_t polygon_index_buffer_size; + + GLuint ninepatch_vertices; + GLuint ninepatch_elements; + } data; + + struct State { + Uniforms uniforms; + bool canvas_texscreen_used; + CanvasShaderGLES2 canvas_shader; + CanvasShadowShaderGLES2 canvas_shadow_shader; + LensDistortedShaderGLES2 lens_shader; + + bool using_texture_rect; + + bool using_light_angle; + bool using_modulate; + bool using_large_vertex; + + bool using_ninepatch; + bool using_skeleton; + + Transform2D skeleton_transform; + Transform2D skeleton_transform_inverse; + Size2i skeleton_texture_size; + + RID current_tex; + RID current_normal; + RasterizerStorageGLES2::Texture *current_tex_ptr; + + Transform3D vp; + Light *using_light; + bool using_shadow; + bool using_transparent_rt; + + // new for Godot 4.0 + // min mag filter is per item, and repeat + RS::CanvasItemTextureFilter current_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR; + RS::CanvasItemTextureRepeat current_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED; + } state; + + typedef void Texture; + + RasterizerSceneGLES2 *scene_render; + + RasterizerStorageGLES2 *storage; + + // allow user to choose api usage + GLenum _buffer_upload_usage_flag; + + void _set_uniforms(); + + virtual RID light_internal_create(); + virtual void light_internal_update(RID p_rid, Light *p_light); + virtual void light_internal_free(RID p_rid); + + virtual void canvas_begin(); + virtual void canvas_end(); + +protected: + void _legacy_draw_primitive(Item::CommandPrimitive *p_pr, RasterizerStorageGLES2::Material *p_material); + void _legacy_draw_line(Item::CommandPrimitive *p_pr, RasterizerStorageGLES2::Material *p_material); + void _legacy_draw_poly_triangles(Item::CommandPolygon *p_poly, RasterizerStorageGLES2::Material *p_material); + +public: + void _draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs, const float *p_light_angles = nullptr); + void _draw_polygon(const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor, const float *p_weights = NULL, const int *p_bones = NULL); + void _draw_generic(GLuint p_primitive, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor); + void _draw_generic_indices(GLuint p_primitive, const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor); + + void _bind_quad_buffer(); + void _copy_texscreen(const Rect2 &p_rect); + void _copy_screen(const Rect2 &p_rect); + + //virtual void draw_window_margins(int *black_margin, RID *black_image) override; + void draw_generic_textured_rect(const Rect2 &p_rect, const Rect2 &p_src); + void draw_lens_distortion_rect(const Rect2 &p_rect, float p_k1, float p_k2, const Vector2 &p_eye_center, float p_oversample); + + virtual void reset_canvas(); + virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache); + virtual void canvas_debug_viewport_shadows(Light *p_lights_with_shadow) override; + + RasterizerStorageGLES2::Texture *_bind_canvas_texture(const RID &p_texture, const RID &p_normal_map); + void _set_texture_rect_mode(bool p_texture_rect, bool p_light_angle = false, bool p_modulate = false, bool p_large_vertex = false); + + // NEW API + struct PolyData { + LocalVector indices; + LocalVector points; + LocalVector colors; + LocalVector uvs; + }; + + RendererCanvasRender::PolygonID request_polygon(const Vector &p_indices, const Vector &p_points, const Vector &p_colors, const Vector &p_uvs = Vector(), const Vector &p_bones = Vector(), const Vector &p_weights = Vector()) override; + void free_polygon(PolygonID p_polygon) override; + + RasterizerPooledIndirectList _polydata; + + ////////////////////// + void initialize(); + void finalize(); + + RasterizerCanvasBaseGLES2(); +}; + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_canvas_gles2.cpp b/drivers/gles2/rasterizer_canvas_gles2.cpp new file mode 100644 index 00000000000..ef4159563f7 --- /dev/null +++ b/drivers/gles2/rasterizer_canvas_gles2.cpp @@ -0,0 +1,2393 @@ +/*************************************************************************/ +/* rasterizer_canvas_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "rasterizer_canvas_gles2.h" +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/os/os.h" +#include "drivers/gles_common/rasterizer_asserts.h" +#include "rasterizer_scene_gles2.h" +#include "rasterizer_storage_gles2.h" + +#ifdef GODOT_4 +#include "core/config/project_settings.h" +#include "servers/rendering/rendering_server_default.h" +#else +#include "core/project_settings.h" +#include "servers/visual/visual_server_raster.h" +#endif + +//static const GLenum gl_primitive[] = { +// GL_POINTS, +// GL_LINES, +// GL_LINE_STRIP, +// GL_LINE_LOOP, +// GL_TRIANGLES, +// GL_TRIANGLE_STRIP, +// GL_TRIANGLE_FAN +//}; + +#if 0 +void RasterizerCanvasGLES2::_batch_upload_buffers() { + // noop? + if (!bdata.vertices.size()) + return; + + glBindBuffer(GL_ARRAY_BUFFER, bdata.gl_vertex_buffer); + + // usage flag is a project setting + GLenum buffer_usage_flag = GL_DYNAMIC_DRAW; + if (bdata.buffer_mode_batch_upload_flag_stream) { + buffer_usage_flag = GL_STREAM_DRAW; + } + + // orphan the old (for now) + if (bdata.buffer_mode_batch_upload_send_null) { + glBufferData(GL_ARRAY_BUFFER, 0, 0, buffer_usage_flag); // GL_DYNAMIC_DRAW); + } + + switch (bdata.fvf) { + case RasterizerStorageCommon::FVF_UNBATCHED: // should not happen + break; + case RasterizerStorageCommon::FVF_REGULAR: // no change + glBufferData(GL_ARRAY_BUFFER, sizeof(BatchVertex) * bdata.vertices.size(), bdata.vertices.get_data(), buffer_usage_flag); + break; + case RasterizerStorageCommon::FVF_COLOR: + glBufferData(GL_ARRAY_BUFFER, sizeof(BatchVertexColored) * bdata.unit_vertices.size(), bdata.unit_vertices.get_unit(0), buffer_usage_flag); + break; + case RasterizerStorageCommon::FVF_LIGHT_ANGLE: + glBufferData(GL_ARRAY_BUFFER, sizeof(BatchVertexLightAngled) * bdata.unit_vertices.size(), bdata.unit_vertices.get_unit(0), buffer_usage_flag); + break; + case RasterizerStorageCommon::FVF_MODULATED: + glBufferData(GL_ARRAY_BUFFER, sizeof(BatchVertexModulated) * bdata.unit_vertices.size(), bdata.unit_vertices.get_unit(0), buffer_usage_flag); + break; + case RasterizerStorageCommon::FVF_LARGE: + glBufferData(GL_ARRAY_BUFFER, sizeof(BatchVertexLarge) * bdata.unit_vertices.size(), bdata.unit_vertices.get_unit(0), buffer_usage_flag); + break; + } + + // might not be necessary + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +void RasterizerCanvasGLES2::_batch_render_lines(const Batch &p_batch, RasterizerStorageGLES2::Material *p_material, bool p_anti_alias) { + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(RID(), RID()); + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, (float *)&p_batch.color); + +#ifdef GLES_OVER_GL + if (p_anti_alias) + glEnable(GL_LINE_SMOOTH); +#endif + + int sizeof_vert = sizeof(BatchVertex); + + // bind the index and vertex buffer + glBindBuffer(GL_ARRAY_BUFFER, bdata.gl_vertex_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bdata.gl_index_buffer); + + uint64_t pointer = 0; + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof_vert, (const void *)pointer); + + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + + int64_t offset = p_batch.first_vert; // 6 inds per quad at 2 bytes each + + int num_elements = p_batch.num_commands * 2; + glDrawArrays(GL_LINES, offset, num_elements); + + storage->info.render._2d_draw_call_count++; + + // may not be necessary .. state change optimization still TODO + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + +#ifdef GLES_OVER_GL + if (p_anti_alias) + glDisable(GL_LINE_SMOOTH); +#endif +} + +void RasterizerCanvasGLES2::_batch_render_generic(const Batch &p_batch, RasterizerStorageGLES2::Material *p_material) { + ERR_FAIL_COND(p_batch.num_commands <= 0); + + const bool &use_light_angles = bdata.use_light_angles; + const bool &use_modulate = bdata.use_modulate; + const bool &use_large_verts = bdata.use_large_verts; + const bool &colored_verts = bdata.use_colored_vertices | use_light_angles | use_modulate | use_large_verts; + + int sizeof_vert; + + switch (bdata.fvf) { + default: + sizeof_vert = 0; // prevent compiler warning - this should never happen + break; + case RasterizerStorageCommon::FVF_UNBATCHED: { + sizeof_vert = 0; // prevent compiler warning - this should never happen + return; + } break; + case RasterizerStorageCommon::FVF_REGULAR: // no change + sizeof_vert = sizeof(BatchVertex); + break; + case RasterizerStorageCommon::FVF_COLOR: + sizeof_vert = sizeof(BatchVertexColored); + break; + case RasterizerStorageCommon::FVF_LIGHT_ANGLE: + sizeof_vert = sizeof(BatchVertexLightAngled); + break; + case RasterizerStorageCommon::FVF_MODULATED: + sizeof_vert = sizeof(BatchVertexModulated); + break; + case RasterizerStorageCommon::FVF_LARGE: + sizeof_vert = sizeof(BatchVertexLarge); + break; + } + + // make sure to set all conditionals BEFORE binding the shader + _set_texture_rect_mode(false, use_light_angles, use_modulate, use_large_verts); + + // batch tex + const BatchTex &tex = bdata.batch_textures[p_batch.batch_texture_id]; + //VSG::rasterizer->gl_check_for_error(); + + // force repeat is set if non power of 2 texture, and repeat is needed if hardware doesn't support npot + if (tex.tile_mode == BatchTex::TILE_FORCE_REPEAT) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_FORCE_REPEAT, true); + } + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(tex.RID_texture, tex.RID_normal); + + // bind the index and vertex buffer + glBindBuffer(GL_ARRAY_BUFFER, bdata.gl_vertex_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bdata.gl_index_buffer); + + uint64_t pointer = 0; + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof_vert, (const void *)pointer); + + // always send UVs, even within a texture specified because a shader can still use UVs + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (2 * 4))); + + // color + if (!colored_verts) { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, p_batch.color.get_data()); + } else { + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (4 * 4))); + } + + if (use_light_angles) { + glEnableVertexAttribArray(GD_VS::ARRAY_TANGENT); + glVertexAttribPointer(GD_VS::ARRAY_TANGENT, 1, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (8 * 4))); + } + + if (use_modulate) { + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV2); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV2, 4, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (9 * 4))); + } + + if (use_large_verts) { + glEnableVertexAttribArray(GD_VS::ARRAY_BONES); + glVertexAttribPointer(GD_VS::ARRAY_BONES, 2, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (13 * 4))); + glEnableVertexAttribArray(GD_VS::ARRAY_WEIGHTS); + glVertexAttribPointer(GD_VS::ARRAY_WEIGHTS, 4, GL_FLOAT, GL_FALSE, sizeof_vert, CAST_INT_TO_UCHAR_PTR(pointer + (15 * 4))); + } + + // We only want to set the GL wrapping mode if the texture is not already tiled (i.e. set in Import). + // This is an optimization left over from the legacy renderer. + // If we DID set tiling in the API, and reverted to clamped, then the next draw using this texture + // may use clamped mode incorrectly. + bool tex_is_already_tiled = tex.flags & RasterizerStorageGLES2::TEXTURE_FLAG_REPEAT; + + if (tex.tile_mode == BatchTex::TILE_NORMAL) { + // if the texture is imported as tiled, no need to set GL state, as it will already be bound with repeat + if (!tex_is_already_tiled) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + } + + // we need to convert explicitly from pod Vec2 to Vector2 ... + // could use a cast but this might be unsafe in future + Vector2 tps; + tex.tex_pixel_size.to(tps); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, tps); + + switch (p_batch.type) { + default: { + // prevent compiler warning + } break; + case RasterizerStorageCommon::BT_RECT: { + int64_t offset = p_batch.first_vert * 3; + + int num_elements = p_batch.num_commands * 6; + glDrawElements(GL_TRIANGLES, num_elements, GL_UNSIGNED_SHORT, (void *)offset); + } break; + case RasterizerStorageCommon::BT_POLY: { + int64_t offset = p_batch.first_vert; + + int num_elements = p_batch.num_commands; + glDrawArrays(GL_TRIANGLES, offset, num_elements); + } break; + } + + storage->info.render._2d_draw_call_count++; + + switch (tex.tile_mode) { + case BatchTex::TILE_FORCE_REPEAT: { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_FORCE_REPEAT, false); + } break; + case BatchTex::TILE_NORMAL: { + // if the texture is imported as tiled, no need to revert GL state + if (!tex_is_already_tiled) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + } break; + default: { + } break; + } + + // could these have ifs? + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glDisableVertexAttribArray(GD_VS::ARRAY_TANGENT); + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV2); + glDisableVertexAttribArray(GD_VS::ARRAY_BONES); + glDisableVertexAttribArray(GD_VS::ARRAY_WEIGHTS); + + // may not be necessary .. state change optimization still TODO + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +} +#endif +void RasterizerCanvasGLES2::render_batches(Item::Command *const *p_commands, Item *p_current_clip, bool &r_reclip, RasterizerStorageGLES2::Material *p_material) { + int num_batches = bdata.batches.size(); + + for (int batch_num = 0; batch_num < num_batches; batch_num++) { + const Batch &batch = bdata.batches[batch_num]; + + switch (batch.type) { + case RasterizerStorageCommon::BT_RECT: { + //_batch_render_generic(batch, p_material); + } break; + case RasterizerStorageCommon::BT_POLY: { + //_batch_render_generic(batch, p_material); + } break; + case RasterizerStorageCommon::BT_LINE: { + //_batch_render_lines(batch, p_material, false); + } break; + case RasterizerStorageCommon::BT_LINE_AA: { + //_batch_render_lines(batch, p_material, true); + } break; + default: { + int end_command = batch.first_command + batch.num_commands; + + for (int i = batch.first_command; i < end_command; i++) { + Item::Command *command = p_commands[i]; + + switch (command->type) { +#if 0 + case Item::Command::TYPE_LINE: { + Item::CommandLine *line = static_cast(command); + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(RID(), RID()); + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, line->color.components); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.uniforms.modelview_matrix); + + if (line->width <= 1) { + Vector2 verts[2] = { + Vector2(line->from.x, line->from.y), + Vector2(line->to.x, line->to.y) + }; + +#ifdef GLES_OVER_GL + if (line->antialiased) + glEnable(GL_LINE_SMOOTH); +#endif + _draw_gui_primitive(2, verts, NULL, NULL); + +#ifdef GLES_OVER_GL + if (line->antialiased) + glDisable(GL_LINE_SMOOTH); +#endif + } else { + Vector2 t = (line->from - line->to).normalized().tangent() * line->width * 0.5; + + Vector2 verts[4] = { + line->from - t, + line->from + t, + line->to + t, + line->to - t + }; + + _draw_gui_primitive(4, verts, NULL, NULL); +#ifdef GLES_OVER_GL + if (line->antialiased) { + glEnable(GL_LINE_SMOOTH); + for (int j = 0; j < 4; j++) { + Vector2 vertsl[2] = { + verts[j], + verts[(j + 1) % 4], + }; + _draw_gui_primitive(2, vertsl, NULL, NULL); + } + glDisable(GL_LINE_SMOOTH); + } +#endif + } + } break; +#endif + case Item::Command::TYPE_PRIMITIVE: { + Item::CommandPrimitive *pr = static_cast(command); + + switch (pr->point_count) { + case 2: { + _legacy_draw_line(pr, p_material); + } break; + default: { + _legacy_draw_primitive(pr, p_material); + } break; + } + + } break; + + case Item::Command::TYPE_RECT: { + Item::CommandRect *r = static_cast(command); + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, r->modulate.components); + + bool can_tile = true; + + // we will take account of render target textures which need to be drawn upside down + // quirk of opengl + bool upside_down = r->flags & CANVAS_RECT_FLIP_V; + + // very inefficient, improve this + if (r->texture.is_valid()) { + RasterizerStorageGLES2::Texture *texture = storage->texture_owner.getornull(r->texture); + + if (texture) { + if (texture->is_upside_down()) + upside_down = true; + } + } + + if (r->texture.is_valid() && r->flags & CANVAS_RECT_TILE && !storage->config.support_npot_repeat_mipmap) { + // workaround for when setting tiling does not work due to hardware limitation + + RasterizerStorageGLES2::Texture *texture = storage->texture_owner.getornull(r->texture); + + if (texture) { + texture = texture->get_ptr(); + + if (next_power_of_2(texture->alloc_width) != (unsigned int)texture->alloc_width && next_power_of_2(texture->alloc_height) != (unsigned int)texture->alloc_height) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_FORCE_REPEAT, true); + can_tile = false; + } + } + } + + // On some widespread Nvidia cards, the normal draw method can produce some + // flickering in draw_rect and especially TileMap rendering (tiles randomly flicker). + // See GH-9913. + // To work it around, we use a simpler draw method which does not flicker, but gives + // a non negligible performance hit, so it's opt-in (GH-24466). + if (use_nvidia_rect_workaround) { + // are we using normal maps, if so we want to use light angle + bool send_light_angles = false; + + // only need to use light angles when normal mapping + // otherwise we can use the default shader + if (state.current_normal != RID()) { + send_light_angles = true; + } + + _set_texture_rect_mode(false, send_light_angles); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + Vector2 points[4] = { + r->rect.position, + r->rect.position + Vector2(r->rect.size.x, 0.0), + r->rect.position + r->rect.size, + r->rect.position + Vector2(0.0, r->rect.size.y), + }; + + if (r->rect.size.x < 0) { + SWAP(points[0], points[1]); + SWAP(points[2], points[3]); + } + if (r->rect.size.y < 0) { + SWAP(points[0], points[3]); + SWAP(points[1], points[2]); + } + + // FTODO + //RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(r->texture, r->normal_map); + RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(r->texture, RID()); + + if (texture) { + Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height); + + Rect2 src_rect = (r->flags & CANVAS_RECT_REGION) ? Rect2(r->source.position * texpixel_size, r->source.size * texpixel_size) : Rect2(0, 0, 1, 1); + + Vector2 uvs[4] = { + src_rect.position, + src_rect.position + Vector2(src_rect.size.x, 0.0), + src_rect.position + src_rect.size, + src_rect.position + Vector2(0.0, src_rect.size.y), + }; + + // for encoding in light angle + bool flip_h = false; + bool flip_v = false; + + if (r->flags & CANVAS_RECT_TRANSPOSE) { + SWAP(uvs[1], uvs[3]); + } + + if (r->flags & CANVAS_RECT_FLIP_H) { + SWAP(uvs[0], uvs[1]); + SWAP(uvs[2], uvs[3]); + flip_h = true; + flip_v = !flip_v; + } + if (upside_down) { + SWAP(uvs[0], uvs[3]); + SWAP(uvs[1], uvs[2]); + flip_v = !flip_v; + } + + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + + bool untile = false; + + if (can_tile && r->flags & CANVAS_RECT_TILE && !(texture->flags & RasterizerStorageGLES2::TEXTURE_FLAG_REPEAT)) { + texture->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED); + untile = true; + } + + if (send_light_angles) { + // for single rects, there is no need to fully utilize the light angle, + // we only need it to encode flips (horz and vert). But the shader can be reused with + // batching in which case the angle encodes the transform as well as + // the flips. + // Note transpose is NYI. I don't think it worked either with the non-nvidia method. + + // if horizontal flip, angle is 180 + float angle = 0.0f; + if (flip_h) + angle = Math_PI; + + // add 1 (to take care of zero floating point error with sign) + angle += 1.0f; + + // flip if necessary + if (flip_v) + angle *= -1.0f; + + // light angle must be sent for each vert, instead as a single uniform in the uniform draw method + // this has the benefit of enabling batching with light angles. + float light_angles[4] = { angle, angle, angle, angle }; + + _draw_gui_primitive(4, points, NULL, uvs, light_angles); + } else { + _draw_gui_primitive(4, points, NULL, uvs); + } + + if (untile) { + texture->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } + } else { + static const Vector2 uvs[4] = { + Vector2(0.0, 0.0), + Vector2(0.0, 1.0), + Vector2(1.0, 1.0), + Vector2(1.0, 0.0), + }; + + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, Vector2()); + _draw_gui_primitive(4, points, NULL, uvs); + } + + } else { + // This branch is better for performance, but can produce flicker on Nvidia, see above comment. + _bind_quad_buffer(); + + _set_texture_rect_mode(true); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + // FTODO + //RasterizerStorageGLES2::Texture *tex = _bind_canvas_texture(r->texture, r->normal_map); + RasterizerStorageGLES2::Texture *tex = _bind_canvas_texture(r->texture, RID()); + + if (!tex) { + Rect2 dst_rect = Rect2(r->rect.position, r->rect.size); + + if (dst_rect.size.width < 0) { + dst_rect.position.x += dst_rect.size.width; + dst_rect.size.width *= -1; + } + if (dst_rect.size.height < 0) { + dst_rect.position.y += dst_rect.size.height; + dst_rect.size.height *= -1; + } + + state.canvas_shader.set_uniform(CanvasShaderGLES2::DST_RECT, Color(dst_rect.position.x, dst_rect.position.y, dst_rect.size.x, dst_rect.size.y)); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SRC_RECT, Color(0, 0, 1, 1)); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + storage->info.render._2d_draw_call_count++; + } else { + bool untile = false; + + if (can_tile && r->flags & CANVAS_RECT_TILE && !(tex->flags & RasterizerStorageGLES2::TEXTURE_FLAG_REPEAT)) { + tex->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED); + untile = true; + } + + Size2 texpixel_size(1.0 / tex->width, 1.0 / tex->height); + Rect2 src_rect = (r->flags & CANVAS_RECT_REGION) ? Rect2(r->source.position * texpixel_size, r->source.size * texpixel_size) : Rect2(0, 0, 1, 1); + + Rect2 dst_rect = Rect2(r->rect.position, r->rect.size); + + if (dst_rect.size.width < 0) { + dst_rect.position.x += dst_rect.size.width; + dst_rect.size.width *= -1; + } + if (dst_rect.size.height < 0) { + dst_rect.position.y += dst_rect.size.height; + dst_rect.size.height *= -1; + } + + if (r->flags & CANVAS_RECT_FLIP_H) { + src_rect.size.x *= -1; + } + + if (upside_down) { + src_rect.size.y *= -1; + } + + if (r->flags & CANVAS_RECT_TRANSPOSE) { + dst_rect.size.x *= -1; // Encoding in the dst_rect.z uniform + } + + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::DST_RECT, Color(dst_rect.position.x, dst_rect.position.y, dst_rect.size.x, dst_rect.size.y)); + state.canvas_shader.set_uniform(CanvasShaderGLES2::SRC_RECT, Color(src_rect.position.x, src_rect.position.y, src_rect.size.x, src_rect.size.y)); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + storage->info.render._2d_draw_call_count++; + + if (untile) { + tex->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_FORCE_REPEAT, false); + + } break; + case Item::Command::TYPE_NINEPATCH: { + Item::CommandNinePatch *np = static_cast(command); + + _set_texture_rect_mode(false); + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + glVertexAttrib4fv(GD_VS::ARRAY_COLOR, np->color.components); + + // FTODO + //RasterizerStorageGLES2::Texture *tex = _bind_canvas_texture(np->texture, np->normal_map); + RasterizerStorageGLES2::Texture *tex = _bind_canvas_texture(np->texture, RID()); + + if (!tex) { + // FIXME: Handle textureless ninepatch gracefully + WARN_PRINT("NinePatch without texture not supported yet in GLES2 backend, skipping."); + continue; + } + if (tex->width == 0 || tex->height == 0) { + WARN_PRINT("Cannot set empty texture to NinePatch."); + continue; + } + + Size2 texpixel_size(1.0 / tex->width, 1.0 / tex->height); + + // state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.uniforms.modelview_matrix); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + + Rect2 source = np->source; + if (source.size.x == 0 && source.size.y == 0) { + source.size.x = tex->width; + source.size.y = tex->height; + } + + float screen_scale = 1.0; + + if ((bdata.settings_ninepatch_mode == 1) && (source.size.x != 0) && (source.size.y != 0)) { + screen_scale = MIN(np->rect.size.x / source.size.x, np->rect.size.y / source.size.y); + screen_scale = MIN(1.0, screen_scale); + } + + // prepare vertex buffer + + // this buffer contains [ POS POS UV UV ] * + + float buffer[16 * 2 + 16 * 2]; + + { + // first row + + buffer[(0 * 4 * 4) + 0] = np->rect.position.x; + buffer[(0 * 4 * 4) + 1] = np->rect.position.y; + + buffer[(0 * 4 * 4) + 2] = source.position.x * texpixel_size.x; + buffer[(0 * 4 * 4) + 3] = source.position.y * texpixel_size.y; + + buffer[(0 * 4 * 4) + 4] = np->rect.position.x + np->margin[SIDE_LEFT] * screen_scale; + buffer[(0 * 4 * 4) + 5] = np->rect.position.y; + + buffer[(0 * 4 * 4) + 6] = (source.position.x + np->margin[SIDE_LEFT]) * texpixel_size.x; + buffer[(0 * 4 * 4) + 7] = source.position.y * texpixel_size.y; + + buffer[(0 * 4 * 4) + 8] = np->rect.position.x + np->rect.size.x - np->margin[SIDE_RIGHT] * screen_scale; + buffer[(0 * 4 * 4) + 9] = np->rect.position.y; + + buffer[(0 * 4 * 4) + 10] = (source.position.x + source.size.x - np->margin[SIDE_RIGHT]) * texpixel_size.x; + buffer[(0 * 4 * 4) + 11] = source.position.y * texpixel_size.y; + + buffer[(0 * 4 * 4) + 12] = np->rect.position.x + np->rect.size.x; + buffer[(0 * 4 * 4) + 13] = np->rect.position.y; + + buffer[(0 * 4 * 4) + 14] = (source.position.x + source.size.x) * texpixel_size.x; + buffer[(0 * 4 * 4) + 15] = source.position.y * texpixel_size.y; + + // second row + + buffer[(1 * 4 * 4) + 0] = np->rect.position.x; + buffer[(1 * 4 * 4) + 1] = np->rect.position.y + np->margin[SIDE_TOP] * screen_scale; + + buffer[(1 * 4 * 4) + 2] = source.position.x * texpixel_size.x; + buffer[(1 * 4 * 4) + 3] = (source.position.y + np->margin[SIDE_TOP]) * texpixel_size.y; + + buffer[(1 * 4 * 4) + 4] = np->rect.position.x + np->margin[SIDE_LEFT] * screen_scale; + buffer[(1 * 4 * 4) + 5] = np->rect.position.y + np->margin[SIDE_TOP] * screen_scale; + + buffer[(1 * 4 * 4) + 6] = (source.position.x + np->margin[SIDE_LEFT]) * texpixel_size.x; + buffer[(1 * 4 * 4) + 7] = (source.position.y + np->margin[SIDE_TOP]) * texpixel_size.y; + + buffer[(1 * 4 * 4) + 8] = np->rect.position.x + np->rect.size.x - np->margin[SIDE_RIGHT] * screen_scale; + buffer[(1 * 4 * 4) + 9] = np->rect.position.y + np->margin[SIDE_TOP] * screen_scale; + + buffer[(1 * 4 * 4) + 10] = (source.position.x + source.size.x - np->margin[SIDE_RIGHT]) * texpixel_size.x; + buffer[(1 * 4 * 4) + 11] = (source.position.y + np->margin[SIDE_TOP]) * texpixel_size.y; + + buffer[(1 * 4 * 4) + 12] = np->rect.position.x + np->rect.size.x; + buffer[(1 * 4 * 4) + 13] = np->rect.position.y + np->margin[SIDE_TOP] * screen_scale; + + buffer[(1 * 4 * 4) + 14] = (source.position.x + source.size.x) * texpixel_size.x; + buffer[(1 * 4 * 4) + 15] = (source.position.y + np->margin[SIDE_TOP]) * texpixel_size.y; + + // third row + + buffer[(2 * 4 * 4) + 0] = np->rect.position.x; + buffer[(2 * 4 * 4) + 1] = np->rect.position.y + np->rect.size.y - np->margin[SIDE_BOTTOM] * screen_scale; + + buffer[(2 * 4 * 4) + 2] = source.position.x * texpixel_size.x; + buffer[(2 * 4 * 4) + 3] = (source.position.y + source.size.y - np->margin[SIDE_BOTTOM]) * texpixel_size.y; + + buffer[(2 * 4 * 4) + 4] = np->rect.position.x + np->margin[SIDE_LEFT] * screen_scale; + buffer[(2 * 4 * 4) + 5] = np->rect.position.y + np->rect.size.y - np->margin[SIDE_BOTTOM] * screen_scale; + + buffer[(2 * 4 * 4) + 6] = (source.position.x + np->margin[SIDE_LEFT]) * texpixel_size.x; + buffer[(2 * 4 * 4) + 7] = (source.position.y + source.size.y - np->margin[SIDE_BOTTOM]) * texpixel_size.y; + + buffer[(2 * 4 * 4) + 8] = np->rect.position.x + np->rect.size.x - np->margin[SIDE_RIGHT] * screen_scale; + buffer[(2 * 4 * 4) + 9] = np->rect.position.y + np->rect.size.y - np->margin[SIDE_BOTTOM] * screen_scale; + + buffer[(2 * 4 * 4) + 10] = (source.position.x + source.size.x - np->margin[SIDE_RIGHT]) * texpixel_size.x; + buffer[(2 * 4 * 4) + 11] = (source.position.y + source.size.y - np->margin[SIDE_BOTTOM]) * texpixel_size.y; + + buffer[(2 * 4 * 4) + 12] = np->rect.position.x + np->rect.size.x; + buffer[(2 * 4 * 4) + 13] = np->rect.position.y + np->rect.size.y - np->margin[SIDE_BOTTOM] * screen_scale; + + buffer[(2 * 4 * 4) + 14] = (source.position.x + source.size.x) * texpixel_size.x; + buffer[(2 * 4 * 4) + 15] = (source.position.y + source.size.y - np->margin[SIDE_BOTTOM]) * texpixel_size.y; + + // fourth row + + buffer[(3 * 4 * 4) + 0] = np->rect.position.x; + buffer[(3 * 4 * 4) + 1] = np->rect.position.y + np->rect.size.y; + + buffer[(3 * 4 * 4) + 2] = source.position.x * texpixel_size.x; + buffer[(3 * 4 * 4) + 3] = (source.position.y + source.size.y) * texpixel_size.y; + + buffer[(3 * 4 * 4) + 4] = np->rect.position.x + np->margin[SIDE_LEFT] * screen_scale; + buffer[(3 * 4 * 4) + 5] = np->rect.position.y + np->rect.size.y; + + buffer[(3 * 4 * 4) + 6] = (source.position.x + np->margin[SIDE_LEFT]) * texpixel_size.x; + buffer[(3 * 4 * 4) + 7] = (source.position.y + source.size.y) * texpixel_size.y; + + buffer[(3 * 4 * 4) + 8] = np->rect.position.x + np->rect.size.x - np->margin[SIDE_RIGHT] * screen_scale; + buffer[(3 * 4 * 4) + 9] = np->rect.position.y + np->rect.size.y; + + buffer[(3 * 4 * 4) + 10] = (source.position.x + source.size.x - np->margin[SIDE_RIGHT]) * texpixel_size.x; + buffer[(3 * 4 * 4) + 11] = (source.position.y + source.size.y) * texpixel_size.y; + + buffer[(3 * 4 * 4) + 12] = np->rect.position.x + np->rect.size.x; + buffer[(3 * 4 * 4) + 13] = np->rect.position.y + np->rect.size.y; + + buffer[(3 * 4 * 4) + 14] = (source.position.x + source.size.x) * texpixel_size.x; + buffer[(3 * 4 * 4) + 15] = (source.position.y + source.size.y) * texpixel_size.y; + } + + glBindBuffer(GL_ARRAY_BUFFER, data.ninepatch_vertices); + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * (16 + 16) * 2, buffer, _buffer_upload_usage_flag); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ninepatch_elements); + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), NULL); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), CAST_INT_TO_UCHAR_PTR((sizeof(float) * 2))); + + glDrawElements(GL_TRIANGLES, 18 * 3 - (np->draw_center ? 0 : 6), GL_UNSIGNED_BYTE, NULL); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + storage->info.render._2d_draw_call_count++; + + } break; +#if 0 + case Item::Command::TYPE_CIRCLE: { + Item::CommandCircle *circle = static_cast(command); + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + static const int num_points = 32; + + Vector2 points[num_points + 1]; + points[num_points] = circle->pos; + + int indices[num_points * 3]; + + for (int j = 0; j < num_points; j++) { + points[j] = circle->pos + Vector2(Math::sin(j * Math_PI * 2.0 / num_points), Math::cos(j * Math_PI * 2.0 / num_points)) * circle->radius; + indices[j * 3 + 0] = j; + indices[j * 3 + 1] = (j + 1) % num_points; + indices[j * 3 + 2] = num_points; + } + + _bind_canvas_texture(RID(), RID()); + + _draw_polygon(indices, num_points * 3, num_points + 1, points, NULL, &circle->color, true); + } break; +#endif + case Item::Command::TYPE_POLYGON: { + Item::CommandPolygon *polygon = static_cast(command); + //const PolyData &pd = _polydata[polygon->polygon.polygon_id]; + + switch (polygon->primitive) { + case RS::PRIMITIVE_TRIANGLES: { + _legacy_draw_poly_triangles(polygon, p_material); + } break; + default: + break; + } + + } break; +#if 0 + case Item::Command::TYPE_MESH: { + Item::CommandMesh *mesh = static_cast(command); + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(mesh->texture, mesh->normal_map); + + if (texture) { + Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + } + + RasterizerStorageGLES2::Mesh *mesh_data = storage->mesh_owner.getornull(mesh->mesh); + if (mesh_data) { + for (int j = 0; j < mesh_data->surfaces.size(); j++) { + RasterizerStorageGLES2::Surface *s = mesh_data->surfaces[j]; + // materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing + + glBindBuffer(GL_ARRAY_BUFFER, s->vertex_id); + + if (s->index_array_len > 0) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id); + } + + for (int k = 0; k < GD_VS::ARRAY_MAX - 1; k++) { + if (s->attribs[k].enabled) { + glEnableVertexAttribArray(k); + glVertexAttribPointer(s->attribs[k].index, s->attribs[k].size, s->attribs[k].type, s->attribs[k].normalized, s->attribs[k].stride, CAST_INT_TO_UCHAR_PTR(s->attribs[k].offset)); + } else { + glDisableVertexAttribArray(k); + switch (k) { + case GD_VS::ARRAY_NORMAL: { + glVertexAttrib4f(GD_VS::ARRAY_NORMAL, 0.0, 0.0, 1, 1); + } break; + case GD_VS::ARRAY_COLOR: { + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + + } break; + default: { + } + } + } + } + + if (s->index_array_len > 0) { + glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0); + } else { + glDrawArrays(gl_primitive[s->primitive], 0, s->array_len); + } + } + + for (int j = 1; j < GD_VS::ARRAY_MAX - 1; j++) { + glDisableVertexAttribArray(j); + } + } + + storage->info.render._2d_draw_call_count++; + } break; + case Item::Command::TYPE_MULTIMESH: { + Item::CommandMultiMesh *mmesh = static_cast(command); + + RasterizerStorageGLES2::MultiMesh *multi_mesh = storage->multimesh_owner.getornull(mmesh->multimesh); + + if (!multi_mesh) + break; + + RasterizerStorageGLES2::Mesh *mesh_data = storage->mesh_owner.getornull(multi_mesh->mesh); + + if (!mesh_data) + break; + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_INSTANCE_CUSTOM, multi_mesh->custom_data_format != GD_VS::MULTIMESH_CUSTOM_DATA_NONE); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_INSTANCING, true); + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(mmesh->texture, mmesh->normal_map); + + if (texture) { + Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + } + + //reset shader and force rebind + + int amount = MIN(multi_mesh->size, multi_mesh->visible_instances); + + if (amount == -1) { + amount = multi_mesh->size; + } + + int stride = multi_mesh->color_floats + multi_mesh->custom_data_floats + multi_mesh->xform_floats; + + int color_ofs = multi_mesh->xform_floats; + int custom_data_ofs = color_ofs + multi_mesh->color_floats; + + // drawing + + const float *base_buffer = multi_mesh->data.ptr(); + + for (int j = 0; j < mesh_data->surfaces.size(); j++) { + RasterizerStorageGLES2::Surface *s = mesh_data->surfaces[j]; + // materials are ignored in 2D meshes, could be added but many things (ie, lighting mode, reading from screen, etc) would break as they are not meant be set up at this point of drawing + + //bind buffers for mesh surface + glBindBuffer(GL_ARRAY_BUFFER, s->vertex_id); + + if (s->index_array_len > 0) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id); + } + + for (int k = 0; k < GD_VS::ARRAY_MAX - 1; k++) { + if (s->attribs[k].enabled) { + glEnableVertexAttribArray(k); + glVertexAttribPointer(s->attribs[k].index, s->attribs[k].size, s->attribs[k].type, s->attribs[k].normalized, s->attribs[k].stride, CAST_INT_TO_UCHAR_PTR(s->attribs[k].offset)); + } else { + glDisableVertexAttribArray(k); + switch (k) { + case GD_VS::ARRAY_NORMAL: { + glVertexAttrib4f(GD_VS::ARRAY_NORMAL, 0.0, 0.0, 1, 1); + } break; + case GD_VS::ARRAY_COLOR: { + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + + } break; + default: { + } + } + } + } + + for (int k = 0; k < amount; k++) { + const float *buffer = base_buffer + k * stride; + + { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 0, &buffer[0]); + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 1, &buffer[4]); + if (multi_mesh->transform_format == GD_VS::MULTIMESH_TRANSFORM_3D) { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 2, &buffer[8]); + } else { + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 2, 0.0, 0.0, 1.0, 0.0); + } + } + + if (multi_mesh->color_floats) { + if (multi_mesh->color_format == GD_VS::MULTIMESH_COLOR_8BIT) { + uint8_t *color_data = (uint8_t *)(buffer + color_ofs); + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 3, color_data[0] / 255.0, color_data[1] / 255.0, color_data[2] / 255.0, color_data[3] / 255.0); + } else { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 3, buffer + color_ofs); + } + } else { + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 3, 1.0, 1.0, 1.0, 1.0); + } + + if (multi_mesh->custom_data_floats) { + if (multi_mesh->custom_data_format == GD_VS::MULTIMESH_CUSTOM_DATA_8BIT) { + uint8_t *custom_data = (uint8_t *)(buffer + custom_data_ofs); + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 4, custom_data[0] / 255.0, custom_data[1] / 255.0, custom_data[2] / 255.0, custom_data[3] / 255.0); + } else { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 4, buffer + custom_data_ofs); + } + } + + if (s->index_array_len > 0) { + glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0); + } else { + glDrawArrays(gl_primitive[s->primitive], 0, s->array_len); + } + } + } + + // LIGHT ANGLE PR replaced USE_INSTANCE_CUSTOM line with below .. think it was a typo, + // but just in case, made this note. + //_set_texture_rect_mode(false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_INSTANCE_CUSTOM, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_INSTANCING, false); + + storage->info.render._2d_draw_call_count++; + } break; + case Item::Command::TYPE_POLYLINE: { + Item::CommandPolyLine *pline = static_cast(command); + + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + _bind_canvas_texture(RID(), RID()); + + if (pline->triangles.size()) { + _draw_generic(GL_TRIANGLE_STRIP, pline->triangles.size(), pline->triangles.ptr(), NULL, pline->triangle_colors.ptr(), pline->triangle_colors.size() == 1); +#ifdef GLES_OVER_GL + glEnable(GL_LINE_SMOOTH); + if (pline->multiline) { + //needs to be different + } else { + _draw_generic(GL_LINE_LOOP, pline->lines.size(), pline->lines.ptr(), NULL, pline->line_colors.ptr(), pline->line_colors.size() == 1); + } + glDisable(GL_LINE_SMOOTH); +#endif + } else { +#ifdef GLES_OVER_GL + if (pline->antialiased) + glEnable(GL_LINE_SMOOTH); +#endif + + if (pline->multiline) { + int todo = pline->lines.size() / 2; + int max_per_call = data.polygon_buffer_size / (sizeof(real_t) * 4); + int offset = 0; + + while (todo) { + int to_draw = MIN(max_per_call, todo); + _draw_generic(GL_LINES, to_draw * 2, &pline->lines.ptr()[offset], NULL, pline->line_colors.size() == 1 ? pline->line_colors.ptr() : &pline->line_colors.ptr()[offset], pline->line_colors.size() == 1); + todo -= to_draw; + offset += to_draw * 2; + } + } else { + _draw_generic(GL_LINE_STRIP, pline->lines.size(), pline->lines.ptr(), NULL, pline->line_colors.ptr(), pline->line_colors.size() == 1); + } + +#ifdef GLES_OVER_GL + if (pline->antialiased) + glDisable(GL_LINE_SMOOTH); +#endif + } + } break; + + case Item::Command::TYPE_PRIMITIVE: { + Item::CommandPrimitive *primitive = static_cast(command); + _set_texture_rect_mode(false); + + if (state.canvas_shader.bind()) { + _set_uniforms(); + state.canvas_shader.use_material((void *)p_material); + } + + ERR_CONTINUE(primitive->points.size() < 1); + + RasterizerStorageGLES2::Texture *texture = _bind_canvas_texture(primitive->texture, primitive->normal_map); + + if (texture) { + Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height); + state.canvas_shader.set_uniform(CanvasShaderGLES2::COLOR_TEXPIXEL_SIZE, texpixel_size); + } + + // we need a temporary because this must be nulled out + // if only a single color specified + const Color *colors = primitive->colors.ptr(); + if (primitive->colors.size() == 1 && primitive->points.size() > 1) { + Color c = primitive->colors[0]; + glVertexAttrib4f(GD_VS::ARRAY_COLOR, c.r, c.g, c.b, c.a); + colors = nullptr; + } else if (primitive->colors.empty()) { + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + } +#ifdef RASTERIZER_EXTRA_CHECKS + else { + RAST_DEV_DEBUG_ASSERT(primitive->colors.size() == primitive->points.size()); + } + + if (primitive->uvs.ptr()) { + RAST_DEV_DEBUG_ASSERT(primitive->uvs.size() == primitive->points.size()); + } +#endif + + _draw_gui_primitive(primitive->points.size(), primitive->points.ptr(), colors, primitive->uvs.ptr()); + } break; +#endif + case Item::Command::TYPE_TRANSFORM: { + Item::CommandTransform *transform = static_cast(command); + state.uniforms.extra_matrix = transform->xform; + state.canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, state.uniforms.extra_matrix); + } break; + + case Item::Command::TYPE_PARTICLES: { + } break; + case Item::Command::TYPE_CLIP_IGNORE: { + Item::CommandClipIgnore *ci = static_cast(command); + if (p_current_clip) { + if (ci->ignore != r_reclip) { + if (ci->ignore) { + glDisable(GL_SCISSOR_TEST); + r_reclip = true; + } else { + glEnable(GL_SCISSOR_TEST); + + int x = p_current_clip->final_clip_rect.position.x; + int y = storage->frame.current_rt->height - (p_current_clip->final_clip_rect.position.y + p_current_clip->final_clip_rect.size.y); + int w = p_current_clip->final_clip_rect.size.x; + int h = p_current_clip->final_clip_rect.size.y; + + // FTODO + // if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + // y = p_current_clip->final_clip_rect.position.y; + + glScissor(x, y, w, h); + + r_reclip = false; + } + } + } + + } break; + default: { + // FIXME: Proper error handling if relevant + //print_line("other"); + } break; + } + } + + } // default + break; + } + } +} + +void RasterizerCanvasGLES2::canvas_end() { + batch_canvas_end(); + RasterizerCanvasBaseGLES2::canvas_end(); +} + +void RasterizerCanvasGLES2::canvas_begin() { + batch_canvas_begin(); + RasterizerCanvasBaseGLES2::canvas_begin(); +} + +void RasterizerCanvasGLES2::canvas_render_items_begin(const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform) { + batch_canvas_render_items_begin(p_modulate, p_light, p_base_transform); +} + +void RasterizerCanvasGLES2::canvas_render_items_end() { + batch_canvas_render_items_end(); +} + +void RasterizerCanvasGLES2::canvas_render_items_internal(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform) { + batch_canvas_render_items(p_item_list, p_z, p_modulate, p_light, p_base_transform); + + //glClearColor(Math::randf(), 0, 1, 1); +} + +void RasterizerCanvasGLES2::canvas_render_items_implementation(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform) { + // parameters are easier to pass around in a structure + RenderItemState ris; + ris.item_group_z = p_z; + ris.item_group_modulate = p_modulate; + ris.item_group_light = p_light; + ris.item_group_base_transform = p_base_transform; + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SKELETON, false); + + state.current_tex = RID(); + state.current_tex_ptr = NULL; + state.current_normal = RID(); + state.canvas_texscreen_used = false; + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + + if (bdata.settings_use_batching) { +#ifdef GODOT_3 + for (int j = 0; j < bdata.items_joined.size(); j++) { + render_joined_item(bdata.items_joined[j], ris); + } +#endif + } else { + while (p_item_list) { + Item *ci = p_item_list; + _legacy_canvas_render_item(ci, ris); + p_item_list = p_item_list->next; + } + } + + if (ris.current_clip) { + glDisable(GL_SCISSOR_TEST); + } + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SKELETON, false); +} + +#ifdef GODOT_3 +// This function is a dry run of the state changes when drawing the item. +// It should duplicate the logic in _canvas_render_item, +// to decide whether items are similar enough to join +// i.e. no state differences between the 2 items. +bool RasterizerCanvasGLES2::try_join_item(Item *p_ci, RenderItemState &r_ris, bool &r_batch_break) { + // if we set max join items to zero we can effectively prevent any joining, so + // none of the other logic needs to run. Good for testing regression bugs, and + // could conceivably be faster in some games. + if (!bdata.settings_max_join_item_commands) { + return false; + } + + // if there are any state changes we change join to false + // we also set r_batch_break to true if we don't want this item joined to the next + // (e.g. an item that must not be joined at all) + r_batch_break = false; + bool join = true; + + // light_masked may possibly need state checking here. Check for regressions! + + // we will now allow joining even if final modulate is different + // we will instead bake the final modulate into the vertex colors + // if (p_ci->final_modulate != r_ris.final_modulate) { + // join = false; + // r_ris.final_modulate = p_ci->final_modulate; + // } + + if (r_ris.current_clip != p_ci->final_clip_owner) { + r_ris.current_clip = p_ci->final_clip_owner; + join = false; + } + + // TODO: copy back buffer + + if (p_ci->copy_back_buffer) { + join = false; + } + + RasterizerStorageGLES2::Skeleton *skeleton = NULL; + + { + //skeleton handling + if (p_ci->skeleton.is_valid() && storage->skeleton_owner.owns(p_ci->skeleton)) { + skeleton = storage->skeleton_owner.get(p_ci->skeleton); + if (!skeleton->use_2d) { + skeleton = NULL; + } + } + + bool skeleton_prevent_join = false; + + bool use_skeleton = skeleton != NULL; + if (r_ris.prev_use_skeleton != use_skeleton) { + if (!bdata.settings_use_software_skinning) + r_ris.rebind_shader = true; + + r_ris.prev_use_skeleton = use_skeleton; + // join = false; + skeleton_prevent_join = true; + } + + if (skeleton) { + // join = false; + skeleton_prevent_join = true; + state.using_skeleton = true; + } else { + state.using_skeleton = false; + } + + if (skeleton_prevent_join) { + if (!bdata.settings_use_software_skinning) + join = false; + } + } + + Item *material_owner = p_ci->material_owner ? p_ci->material_owner : p_ci; + + RID material = material_owner->material; + RasterizerStorageGLES2::Material *material_ptr = storage->material_owner.getornull(material); + + if (material != r_ris.canvas_last_material || r_ris.rebind_shader) { + join = false; + RasterizerStorageGLES2::Shader *shader_ptr = NULL; + + if (material_ptr) { + shader_ptr = material_ptr->shader; + + if (shader_ptr && shader_ptr->mode != GD_VS::SHADER_CANVAS_ITEM) { + shader_ptr = NULL; // not a canvas item shader, don't use. + } + } + + if (shader_ptr) { + if (shader_ptr->canvas_item.uses_screen_texture) { + if (!state.canvas_texscreen_used) { + join = false; + } + } + } + + r_ris.shader_cache = shader_ptr; + + r_ris.canvas_last_material = material; + + r_ris.rebind_shader = false; + } + + int blend_mode = r_ris.shader_cache ? r_ris.shader_cache->canvas_item.blend_mode : RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX; + bool unshaded = r_ris.shader_cache && (r_ris.shader_cache->canvas_item.light_mode == RasterizerStorageGLES2::Shader::CanvasItem::LIGHT_MODE_UNSHADED || (blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX && blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA)); + bool reclip = false; + + // we are precalculating the final_modulate ahead of time because we need this for baking of final modulate into vertex colors + // (only in software transform mode) + // This maybe inefficient storing it... + r_ris.final_modulate = unshaded ? p_ci->final_modulate : (p_ci->final_modulate * r_ris.item_group_modulate); + + if (r_ris.last_blend_mode != blend_mode) { + join = false; + r_ris.last_blend_mode = blend_mode; + } + + // does the shader contain BUILTINs which should break the batching? + bdata.joined_item_batch_flags = 0; + if (r_ris.shader_cache) { + unsigned int and_flags = r_ris.shader_cache->canvas_item.batch_flags & (RasterizerStorageCommon::PREVENT_COLOR_BAKING | RasterizerStorageCommon::PREVENT_VERTEX_BAKING | RasterizerStorageCommon::PREVENT_ITEM_JOINING); + if (and_flags) { + // special case for preventing item joining altogether + if (and_flags & RasterizerStorageCommon::PREVENT_ITEM_JOINING) { + join = false; + //r_batch_break = true; // don't think we need a batch break + + // save the flags so that they don't need to be recalculated in the 2nd pass + bdata.joined_item_batch_flags |= r_ris.shader_cache->canvas_item.batch_flags; + } else { + bool use_larger_fvfs = true; + + if (and_flags == RasterizerStorageCommon::PREVENT_COLOR_BAKING) { + // in some circumstances, if the modulate is identity, we still allow baking because reading modulate / color + // will still be okay to do in the shader with no ill effects + if (r_ris.final_modulate == Color(1, 1, 1, 1)) { + use_larger_fvfs = false; + } + } + + // new .. always use large FVF + if (use_larger_fvfs) { + if (and_flags == RasterizerStorageCommon::PREVENT_COLOR_BAKING) { + bdata.joined_item_batch_flags |= RasterizerStorageCommon::USE_MODULATE_FVF; + } else { + // we need to save on the joined item that it should use large fvf. + // This info will then be used in filling and rendering + bdata.joined_item_batch_flags |= RasterizerStorageCommon::USE_LARGE_FVF; + } + + bdata.joined_item_batch_flags |= r_ris.shader_cache->canvas_item.batch_flags; + } + +#if 0 + if (and_flags == RasterizerStorageCommon::PREVENT_COLOR_BAKING) { + // in some circumstances, if the modulate is identity, we still allow baking because reading modulate / color + // will still be okay to do in the shader with no ill effects + if (r_ris.final_modulate == Color(1, 1, 1, 1)) { + break_batching = false; + } + else + { + // new .. large FVF + break_batching = false; + + // we need to save on the joined item that it should use large fvf. + // This info will then be used in filling and rendering + bdata.joined_item_batch_flags |= RasterizerStorageCommon::USE_LARGE_FVF; + } + } + + if (break_batching) { + join = false; + r_batch_break = true; + + // save the flags so that they don't need to be recalculated in the 2nd pass + bdata.joined_item_batch_flags |= r_ris.shader_cache->canvas_item.batch_flags; + } +#endif + } // if not prevent item joining + } + } + + if ((blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX || blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA) && r_ris.item_group_light && !unshaded) { + // we cannot join lit items easily. + // it is possible, but not if they overlap, because + // a + light_blend + b + light_blend IS NOT THE SAME AS + // a + b + light_blend + + bool light_allow_join = true; + + // this is a quick getout if we have turned off light joining + if ((bdata.settings_light_max_join_items == 0) || r_ris.light_region.too_many_lights) { + light_allow_join = false; + } else { + // do light joining... + + // first calculate the light bitfield + uint64_t light_bitfield = 0; + uint64_t shadow_bitfield = 0; + Light *light = r_ris.item_group_light; + + int light_count = -1; + while (light) { + light_count++; + uint64_t light_bit = 1ULL << light_count; + + // note that as a cost of batching, the light culling will be less effective + if (p_ci->light_mask & light->item_mask && r_ris.item_group_z >= light->z_min && r_ris.item_group_z <= light->z_max) { + // Note that with the above test, it is possible to also include a bound check. + // Tests so far have indicated better performance without it, but there may be reason to change this at a later stage, + // so I leave the line here for reference: + // && p_ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) { + light_bitfield |= light_bit; + + bool has_shadow = light->shadow_buffer.is_valid() && p_ci->light_mask & light->item_shadow_mask; + + if (has_shadow) { + shadow_bitfield |= light_bit; + } + } + + light = light->next_ptr; + } + + // now compare to previous + if ((r_ris.light_region.light_bitfield != light_bitfield) || (r_ris.light_region.shadow_bitfield != shadow_bitfield)) { + light_allow_join = false; + + r_ris.light_region.light_bitfield = light_bitfield; + r_ris.light_region.shadow_bitfield = shadow_bitfield; + } else { + // only do these checks if necessary + if (join && (!r_batch_break)) { + // we still can't join, even if the lights are exactly the same, if there is overlap between the previous and this item + if (r_ris.joined_item && light_bitfield) { + if ((int)r_ris.joined_item->num_item_refs <= bdata.settings_light_max_join_items) { + for (uint32_t r = 0; r < r_ris.joined_item->num_item_refs; r++) { + Item *pRefItem = bdata.item_refs[r_ris.joined_item->first_item_ref + r].item; + if (p_ci->global_rect_cache.intersects(pRefItem->global_rect_cache)) { + light_allow_join = false; + break; + } + } + +#ifdef DEBUG_ENABLED + if (light_allow_join) { + bdata.stats_light_items_joined++; + } +#endif + + } // if below max join items + else { + // just don't allow joining if above overlap check max items + light_allow_join = false; + } + } + + } // if not batch broken already (no point in doing expensive overlap tests if not needed) + } // if bitfields don't match + } // if do light joining + + if (!light_allow_join) { + // can't join + join = false; + // we also dont want to allow joining this item with the next item, because the next item could have no lights! + r_batch_break = true; + } + + } else { + // if the last item had lights, we should not join it to this one (which has no lights) + if (r_ris.light_region.light_bitfield || r_ris.light_region.shadow_bitfield) { + join = false; + + // setting these to zero ensures that any following item with lights will, by definition, + // be affected by a different set of lights, and thus prevent a join + r_ris.light_region.light_bitfield = 0; + r_ris.light_region.shadow_bitfield = 0; + } + } + + if (reclip) { + join = false; + } + + // non rects will break the batching anyway, we don't want to record item changes, detect this + if (!r_batch_break && _detect_item_batch_break(r_ris, p_ci, r_batch_break)) { + join = false; + + r_batch_break = true; + } + + return join; +} +#endif // godot 3 + +// Legacy non-batched implementation for regression testing. +// Should be removed after testing phase to avoid duplicate codepaths. +void RasterizerCanvasGLES2::_legacy_canvas_render_item(Item *p_ci, RenderItemState &r_ris) { + storage->info.render._2d_item_count++; + + // defaults + state.current_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR; + state.current_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED; + + if (p_ci->texture_filter != RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT) { + state.current_filter = p_ci->texture_filter; + } + + if (p_ci->texture_repeat != RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT) { + state.current_repeat = p_ci->texture_repeat; + } + + if (r_ris.current_clip != p_ci->final_clip_owner) { + r_ris.current_clip = p_ci->final_clip_owner; + + if (r_ris.current_clip) { + glEnable(GL_SCISSOR_TEST); + int y = storage->_dims.rt_height - (r_ris.current_clip->final_clip_rect.position.y + r_ris.current_clip->final_clip_rect.size.y); + // int y = storage->frame.current_rt->height - (r_ris.current_clip->final_clip_rect.position.y + r_ris.current_clip->final_clip_rect.size.y); + // FTODO + // if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + // y = r_ris.current_clip->final_clip_rect.position.y; + glScissor(r_ris.current_clip->final_clip_rect.position.x, y, r_ris.current_clip->final_clip_rect.size.width, r_ris.current_clip->final_clip_rect.size.height); + + // debug VFLIP + // if ((r_ris.current_clip->final_clip_rect.position.x == 223) + // && (y == 54) + // && (r_ris.current_clip->final_clip_rect.size.width == 1383)) + // { + // glScissor(r_ris.current_clip->final_clip_rect.position.x, y, r_ris.current_clip->final_clip_rect.size.width, r_ris.current_clip->final_clip_rect.size.height); + // } + + } else { + glDisable(GL_SCISSOR_TEST); + } + } + + // TODO: copy back buffer + + if (p_ci->copy_back_buffer) { + if (p_ci->copy_back_buffer->full) { + _copy_texscreen(Rect2()); + } else { + _copy_texscreen(p_ci->copy_back_buffer->rect); + } + } + +#if 0 + RasterizerStorageGLES2::Skeleton *skeleton = NULL; + + { + //skeleton handling + if (p_ci->skeleton.is_valid() && storage->skeleton_owner.owns(p_ci->skeleton)) { + skeleton = storage->skeleton_owner.get(p_ci->skeleton); + if (!skeleton->use_2d) { + skeleton = NULL; + } else { + state.skeleton_transform = r_ris.item_group_base_transform * skeleton->base_transform_2d; + state.skeleton_transform_inverse = state.skeleton_transform.affine_inverse(); + state.skeleton_texture_size = Vector2(skeleton->size * 2, 0); + } + } + + bool use_skeleton = skeleton != NULL; + if (r_ris.prev_use_skeleton != use_skeleton) { + r_ris.rebind_shader = true; + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SKELETON, use_skeleton); + r_ris.prev_use_skeleton = use_skeleton; + } + + if (skeleton) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); + glBindTexture(GL_TEXTURE_2D, skeleton->tex_id); + state.using_skeleton = true; + } else { + state.using_skeleton = false; + } + } +#endif + + Item *material_owner = p_ci->material_owner ? p_ci->material_owner : p_ci; + + RID material = material_owner->material; + RasterizerStorageGLES2::Material *material_ptr = storage->material_owner.getornull(material); + + if (material != r_ris.canvas_last_material || r_ris.rebind_shader) { + RasterizerStorageGLES2::Shader *shader_ptr = NULL; + + if (material_ptr) { + shader_ptr = material_ptr->shader; + + if (shader_ptr && shader_ptr->mode != GD_VS::SHADER_CANVAS_ITEM) { + shader_ptr = NULL; // not a canvas item shader, don't use. + } + } + + if (shader_ptr) { + if (shader_ptr->canvas_item.uses_screen_texture) { + if (!state.canvas_texscreen_used) { + //copy if not copied before + _copy_texscreen(Rect2()); + + // blend mode will have been enabled so make sure we disable it again later on + //last_blend_mode = last_blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_DISABLED ? last_blend_mode : -1; + } + + if (storage->frame.current_rt->copy_screen_effect.color) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->copy_screen_effect.color); + } + } + + if (shader_ptr != r_ris.shader_cache) { + if (shader_ptr->canvas_item.uses_time) { + RenderingServerDefault::redraw_request(); + } + + state.canvas_shader.set_custom_shader(shader_ptr->custom_code_id); + state.canvas_shader.bind(); + } + + int tc = material_ptr->textures.size(); + Pair *textures = material_ptr->textures.ptrw(); + + ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = shader_ptr->texture_hints.ptrw(); + + for (int i = 0; i < tc; i++) { + glActiveTexture(GL_TEXTURE0 + i); + + RasterizerStorageGLES2::Texture *t = storage->texture_owner.getornull(textures[i].second); + + if (!t) { + switch (texture_hints[i]) { + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { + glBindTexture(GL_TEXTURE_2D, storage->resources.aniso_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { + glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); + } break; + default: { + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } break; + } + + continue; + } + + if (t->redraw_if_visible) { + RenderingServerDefault::redraw_request(); + } + + t = t->get_ptr(); + +#ifdef TOOLS_ENABLED + if (t->detect_normal && texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) { + t->detect_normal(t->detect_normal_ud); + } +#endif + if (t->render_target) + t->render_target->used_in_frame = true; + + glBindTexture(t->target, t->tex_id); + } + + } else { + state.canvas_shader.set_custom_shader(0); + state.canvas_shader.bind(); + } + state.canvas_shader.use_material((void *)material_ptr); + + r_ris.shader_cache = shader_ptr; + + r_ris.canvas_last_material = material; + + r_ris.rebind_shader = false; + } + + int blend_mode = r_ris.shader_cache ? r_ris.shader_cache->canvas_item.blend_mode : RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX; + bool unshaded = r_ris.shader_cache && (r_ris.shader_cache->canvas_item.light_mode == RasterizerStorageGLES2::Shader::CanvasItem::LIGHT_MODE_UNSHADED || (blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX && blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA)); + bool reclip = false; + + if (r_ris.last_blend_mode != blend_mode) { + switch (blend_mode) { + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + } + + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE); + } + + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE); + } + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MUL: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); + } else { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); + } + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + } + } break; + } + } + + state.uniforms.final_modulate = unshaded ? p_ci->final_modulate : Color(p_ci->final_modulate.r * r_ris.item_group_modulate.r, p_ci->final_modulate.g * r_ris.item_group_modulate.g, p_ci->final_modulate.b * r_ris.item_group_modulate.b, p_ci->final_modulate.a * r_ris.item_group_modulate.a); + + state.uniforms.modelview_matrix = p_ci->final_transform; + state.uniforms.extra_matrix = Transform2D(); + + _set_uniforms(); + + if (unshaded || (state.uniforms.final_modulate.a > 0.001 && (!r_ris.shader_cache || r_ris.shader_cache->canvas_item.light_mode != RasterizerStorageGLES2::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY) && !p_ci->light_masked)) + _legacy_canvas_item_render_commands(p_ci, NULL, reclip, material_ptr); + + r_ris.rebind_shader = true; // hacked in for now. + + if ((blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX || blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA) && r_ris.item_group_light && !unshaded) { + Light *light = r_ris.item_group_light; + bool light_used = false; + GD_VS::CanvasLightBlendMode bmode = GD_VS::CANVAS_LIGHT_BLEND_MODE_ADD; + state.uniforms.final_modulate = p_ci->final_modulate; // remove the canvas modulate + + while (light) { + if (p_ci->light_mask & light->item_mask && r_ris.item_group_z >= light->z_min && r_ris.item_group_z <= light->z_max && p_ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) { + //intersects this light + + if (!light_used || bmode != light->blend_mode) { + bmode = light->blend_mode; + + switch (bmode) { + case GD_VS::CANVAS_LIGHT_BLEND_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + } break; + case GD_VS::CANVAS_LIGHT_BLEND_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + } break; + case GD_VS::CANVAS_LIGHT_BLEND_MODE_MIX: { + // case GD_VS::CANVAS_LIGHT_MODE_MASK: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + } break; + } + } + + if (!light_used) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, true); + light_used = true; + } + + // FTODO + //bool has_shadow = light->shadow_buffer.is_valid() && p_ci->light_mask & light->item_shadow_mask; + bool has_shadow = light->use_shadow && p_ci->light_mask & light->item_shadow_mask; + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, has_shadow); + if (has_shadow) { + // FTODO + //state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_USE_GRADIENT, light->shadow_gradient_length > 0); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_USE_GRADIENT, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_NEAREST, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_NONE); + //state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF3, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF3); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF3, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF5, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF5); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF7, false); + //state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF7, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF7); + //state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF9, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF9); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF9, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF13, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF13); + } + + state.canvas_shader.bind(); + state.using_light = light; + state.using_shadow = has_shadow; + + //always re-set uniforms, since light parameters changed + _set_uniforms(); + state.canvas_shader.use_material((void *)material_ptr); + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 6); + RasterizerStorageGLES2::Texture *t = storage->texture_owner.getornull(light->texture); + if (!t) { + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } else { + t = t->get_ptr(); + + glBindTexture(t->target, t->tex_id); + } + + glActiveTexture(GL_TEXTURE0); + _legacy_canvas_item_render_commands(p_ci, NULL, reclip, material_ptr); //redraw using light + + state.using_light = NULL; + } + + light = light->next_ptr; + } + + if (light_used) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_NEAREST, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF3, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF5, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF7, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF9, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF13, false); + + state.canvas_shader.bind(); + + r_ris.last_blend_mode = -1; + +#if 0 + //this is set again, so it should not be needed anyway? + state.canvas_item_modulate = unshaded ? ci->final_modulate : Color(ci->final_modulate.r * p_modulate.r, ci->final_modulate.g * p_modulate.g, ci->final_modulate.b * p_modulate.b, ci->final_modulate.a * p_modulate.a); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, state.final_transform); + state.canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D()); + state.canvas_shader.set_uniform(CanvasShaderGLES2::FINAL_MODULATE, state.canvas_item_modulate); + + glBlendEquation(GL_FUNC_ADD); + + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + //@TODO RESET canvas_blend_mode +#endif + } + } + + if (reclip) { + glEnable(GL_SCISSOR_TEST); + int y = storage->frame.current_rt->height - (r_ris.current_clip->final_clip_rect.position.y + r_ris.current_clip->final_clip_rect.size.y); + // FTODO + // if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + // y = r_ris.current_clip->final_clip_rect.position.y; + glScissor(r_ris.current_clip->final_clip_rect.position.x, y, r_ris.current_clip->final_clip_rect.size.width, r_ris.current_clip->final_clip_rect.size.height); + } +} + +#ifdef GODOT_3 +void RasterizerCanvasGLES2::render_joined_item(const BItemJoined &p_bij, RenderItemState &r_ris) { + storage->info.render._2d_item_count++; + +#ifdef DEBUG_ENABLED + if (bdata.diagnose_frame) { + bdata.frame_string += "\tjoined_item " + itos(p_bij.num_item_refs) + " refs\n"; + if (p_bij.z_index != 0) { + bdata.frame_string += "\t\t(z " + itos(p_bij.z_index) + ")\n"; + } + } +#endif + + // all the joined items will share the same state with the first item + Item *ci = bdata.item_refs[p_bij.first_item_ref].item; + + if (r_ris.current_clip != ci->final_clip_owner) { + r_ris.current_clip = ci->final_clip_owner; + + if (r_ris.current_clip) { + glEnable(GL_SCISSOR_TEST); + int y = storage->frame.current_rt->height - (r_ris.current_clip->final_clip_rect.position.y + r_ris.current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + y = r_ris.current_clip->final_clip_rect.position.y; + glScissor(r_ris.current_clip->final_clip_rect.position.x, y, r_ris.current_clip->final_clip_rect.size.width, r_ris.current_clip->final_clip_rect.size.height); + } else { + glDisable(GL_SCISSOR_TEST); + } + } + + // TODO: copy back buffer + + if (ci->copy_back_buffer) { + if (ci->copy_back_buffer->full) { + _copy_texscreen(Rect2()); + } else { + _copy_texscreen(ci->copy_back_buffer->rect); + } + } + + if (!bdata.settings_use_batching || !bdata.settings_use_software_skinning) { + RasterizerStorageGLES2::Skeleton *skeleton = NULL; + + //skeleton handling + if (ci->skeleton.is_valid() && storage->skeleton_owner.owns(ci->skeleton)) { + skeleton = storage->skeleton_owner.get(ci->skeleton); + if (!skeleton->use_2d) { + skeleton = NULL; + } else { + state.skeleton_transform = r_ris.item_group_base_transform * skeleton->base_transform_2d; + state.skeleton_transform_inverse = state.skeleton_transform.affine_inverse(); + state.skeleton_texture_size = Vector2(skeleton->size * 2, 0); + } + } + + bool use_skeleton = skeleton != NULL; + if (r_ris.prev_use_skeleton != use_skeleton) { + r_ris.rebind_shader = true; + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SKELETON, use_skeleton); + r_ris.prev_use_skeleton = use_skeleton; + } + + if (skeleton) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); + glBindTexture(GL_TEXTURE_2D, skeleton->tex_id); + state.using_skeleton = true; + } else { + state.using_skeleton = false; + } + + } // if not using batching + + Item *material_owner = ci->material_owner ? ci->material_owner : ci; + + RID material = material_owner->material; + RasterizerStorageGLES2::Material *material_ptr = storage->material_owner.getornull(material); + + if (material != r_ris.canvas_last_material || r_ris.rebind_shader) { + RasterizerStorageGLES2::Shader *shader_ptr = NULL; + + if (material_ptr) { + shader_ptr = material_ptr->shader; + + if (shader_ptr && shader_ptr->mode != GD_VS::SHADER_CANVAS_ITEM) { + shader_ptr = NULL; // not a canvas item shader, don't use. + } + } + + if (shader_ptr) { + if (shader_ptr->canvas_item.uses_screen_texture) { + if (!state.canvas_texscreen_used) { + //copy if not copied before + _copy_texscreen(Rect2()); + + // blend mode will have been enabled so make sure we disable it again later on + //last_blend_mode = last_blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_DISABLED ? last_blend_mode : -1; + } + + if (storage->frame.current_rt->copy_screen_effect.color) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->copy_screen_effect.color); + } + } + + if (shader_ptr != r_ris.shader_cache) { + if (shader_ptr->canvas_item.uses_time) { + VisualServerRaster::redraw_request(); + } + + state.canvas_shader.set_custom_shader(shader_ptr->custom_code_id); + state.canvas_shader.bind(); + } + + int tc = material_ptr->textures.size(); + Pair *textures = material_ptr->textures.ptrw(); + + ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = shader_ptr->texture_hints.ptrw(); + + for (int i = 0; i < tc; i++) { + glActiveTexture(GL_TEXTURE0 + i); + + RasterizerStorageGLES2::Texture *t = storage->texture_owner.getornull(textures[i].second); + + if (!t) { + switch (texture_hints[i]) { + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { + glBindTexture(GL_TEXTURE_2D, storage->resources.aniso_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { + glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); + } break; + default: { + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } break; + } + + continue; + } + + if (t->redraw_if_visible) { + VisualServerRaster::redraw_request(); + } + + t = t->get_ptr(); + +#ifdef TOOLS_ENABLED + if (t->detect_normal && texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) { + t->detect_normal(t->detect_normal_ud); + } +#endif + if (t->render_target) + t->render_target->used_in_frame = true; + + glBindTexture(t->target, t->tex_id); + } + + } else { + state.canvas_shader.set_custom_shader(0); + state.canvas_shader.bind(); + } + state.canvas_shader.use_material((void *)material_ptr); + + r_ris.shader_cache = shader_ptr; + + r_ris.canvas_last_material = material; + + r_ris.rebind_shader = false; + } + + int blend_mode = r_ris.shader_cache ? r_ris.shader_cache->canvas_item.blend_mode : RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX; + bool unshaded = r_ris.shader_cache && (r_ris.shader_cache->canvas_item.light_mode == RasterizerStorageGLES2::Shader::CanvasItem::LIGHT_MODE_UNSHADED || (blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX && blend_mode != RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA)); + bool reclip = false; + + if (r_ris.last_blend_mode != blend_mode) { + switch (blend_mode) { + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + } + + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE); + } + + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); + } else { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE); + } + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MUL: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); + } else { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); + } + } break; + case RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + } + } break; + } + } + + // using software transform? + // (i.e. don't send the transform matrix, send identity, and either use baked verts, + // or large fvf where the transform is done in the shader from transform stored in the fvf.) + if (!p_bij.use_hardware_transform()) { + state.uniforms.modelview_matrix = Transform2D(); + // final_modulate will be baked per item ref so the final_modulate can be an identity color + state.uniforms.final_modulate = Color(1, 1, 1, 1); + } else { + state.uniforms.modelview_matrix = ci->final_transform; + // could use the stored version of final_modulate in item ref? Test which is faster NYI + state.uniforms.final_modulate = unshaded ? ci->final_modulate : (ci->final_modulate * r_ris.item_group_modulate); + } + state.uniforms.extra_matrix = Transform2D(); + + _set_uniforms(); + + if (unshaded || (state.uniforms.final_modulate.a > 0.001 && (!r_ris.shader_cache || r_ris.shader_cache->canvas_item.light_mode != RasterizerStorageGLES2::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY) && !ci->light_masked)) + render_joined_item_commands(p_bij, NULL, reclip, material_ptr, false); + + r_ris.rebind_shader = true; // hacked in for now. + + if ((blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_MIX || blend_mode == RasterizerStorageGLES2::Shader::CanvasItem::BLEND_MODE_PMALPHA) && r_ris.item_group_light && !unshaded) { + Light *light = r_ris.item_group_light; + bool light_used = false; + VS::CanvasLightMode mode = GD_VS::CANVAS_LIGHT_MODE_ADD; + + // we leave this set to 1, 1, 1, 1 if using software because the colors are baked into the vertices + if (p_bij.use_hardware_transform()) { + state.uniforms.final_modulate = ci->final_modulate; // remove the canvas modulate + } + + while (light) { + // use the bounding rect of the joined items, NOT only the bounding rect of the first item. + // note this is a cost of batching, the light culling will be less effective + + // note that the r_ris.item_group_z will be out of date because we are using deferred rendering till canvas_render_items_end() + // so we have to test z against the stored value in the joined item + if (ci->light_mask & light->item_mask && p_bij.z_index >= light->z_min && p_bij.z_index <= light->z_max && p_bij.bounding_rect.intersects_transformed(light->xform_cache, light->rect_cache)) { + //intersects this light + + if (!light_used || mode != light->mode) { + mode = light->mode; + + switch (mode) { + case GD_VS::CANVAS_LIGHT_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + + } break; + case GD_VS::CANVAS_LIGHT_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + } break; + case GD_VS::CANVAS_LIGHT_MODE_MIX: + case GD_VS::CANVAS_LIGHT_MODE_MASK: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + } break; + } + } + + if (!light_used) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, true); + light_used = true; + } + + bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask & light->item_shadow_mask; + + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, has_shadow); + if (has_shadow) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_USE_GRADIENT, light->shadow_gradient_length > 0); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_NEAREST, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_NONE); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF3, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF3); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF5, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF5); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF7, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF7); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF9, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF9); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF13, light->shadow_filter == GD_VS::CANVAS_LIGHT_FILTER_PCF13); + } + + state.canvas_shader.bind(); + state.using_light = light; + state.using_shadow = has_shadow; + + //always re-set uniforms, since light parameters changed + _set_uniforms(); + state.canvas_shader.use_material((void *)material_ptr); + + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 6); + RasterizerStorageGLES2::Texture *t = storage->texture_owner.getornull(light->texture); + if (!t) { + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } else { + t = t->get_ptr(); + + glBindTexture(t->target, t->tex_id); + } + + glActiveTexture(GL_TEXTURE0); + + // redraw using light. + // if there is no clip item, we can consider scissoring to the intersection area between the light and the item + // this can greatly reduce fill rate .. + // at the cost of glScissor commands, so is optional + if (!bdata.settings_scissor_lights || r_ris.current_clip) { + render_joined_item_commands(p_bij, NULL, reclip, material_ptr, true); + } else { + bool scissor = _light_scissor_begin(p_bij.bounding_rect, light->xform_cache, light->rect_cache); + render_joined_item_commands(p_bij, NULL, reclip, material_ptr, true); + if (scissor) { + glDisable(GL_SCISSOR_TEST); + } + } + + state.using_light = NULL; + } + + light = light->next_ptr; + } + + if (light_used) { + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_NEAREST, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF3, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF5, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF7, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF9, false); + state.canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_FILTER_PCF13, false); + + state.canvas_shader.bind(); + + r_ris.last_blend_mode = -1; + +#if 0 + //this is set again, so it should not be needed anyway? + state.canvas_item_modulate = unshaded ? ci->final_modulate : Color( + ci->final_modulate.r * p_modulate.r, + ci->final_modulate.g * p_modulate.g, + ci->final_modulate.b * p_modulate.b, + ci->final_modulate.a * p_modulate.a ); + + state.canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,state.final_transform); + state.canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D()); + state.canvas_shader.set_uniform(CanvasShaderGLES2::FINAL_MODULATE,state.canvas_item_modulate); + + glBlendEquation(GL_FUNC_ADD); + + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + //@TODO RESET canvas_blend_mode +#endif + } + } + + if (reclip) { + glEnable(GL_SCISSOR_TEST); + int y = storage->frame.current_rt->height - (r_ris.current_clip->final_clip_rect.position.y + r_ris.current_clip->final_clip_rect.size.y); + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + y = r_ris.current_clip->final_clip_rect.position.y; + glScissor(r_ris.current_clip->final_clip_rect.position.x, y, r_ris.current_clip->final_clip_rect.size.width, r_ris.current_clip->final_clip_rect.size.height); + } +} +#endif // def GODOT 3 + +void RasterizerCanvasGLES2::gl_enable_scissor(int p_x, int p_y, int p_width, int p_height) const { + glEnable(GL_SCISSOR_TEST); + glScissor(p_x, p_y, p_width, p_height); +} + +void RasterizerCanvasGLES2::gl_disable_scissor() const { + glDisable(GL_SCISSOR_TEST); +} + +void RasterizerCanvasGLES2::initialize() { + RasterizerCanvasBaseGLES2::initialize(); + + batch_initialize(); + + // just reserve some space (may not be needed as we are orphaning, but hey ho) + glGenBuffers(1, &bdata.gl_vertex_buffer); + + if (bdata.vertex_buffer_size_bytes) { + glBindBuffer(GL_ARRAY_BUFFER, bdata.gl_vertex_buffer); + glBufferData(GL_ARRAY_BUFFER, bdata.vertex_buffer_size_bytes, NULL, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + // pre fill index buffer, the indices never need to change so can be static + glGenBuffers(1, &bdata.gl_index_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bdata.gl_index_buffer); + + Vector indices; + indices.resize(bdata.index_buffer_size_units); + + for (unsigned int q = 0; q < bdata.max_quads; q++) { + int i_pos = q * 6; // 6 inds per quad + int q_pos = q * 4; // 4 verts per quad + indices.set(i_pos, q_pos); + indices.set(i_pos + 1, q_pos + 1); + indices.set(i_pos + 2, q_pos + 2); + indices.set(i_pos + 3, q_pos); + indices.set(i_pos + 4, q_pos + 2); + indices.set(i_pos + 5, q_pos + 3); + + // we can only use 16 bit indices in GLES2! +#ifdef DEBUG_ENABLED + CRASH_COND((q_pos + 3) > 65535); +#endif + } + + glBufferData(GL_ELEMENT_ARRAY_BUFFER, bdata.index_buffer_size_bytes, &indices[0], GL_STATIC_DRAW); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + } // only if there is a vertex buffer (batching is on) +} + +RasterizerCanvasGLES2::RasterizerCanvasGLES2() { + batch_constructor(); +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_canvas_gles2.h b/drivers/gles2/rasterizer_canvas_gles2.h new file mode 100644 index 00000000000..fd4da5434e6 --- /dev/null +++ b/drivers/gles2/rasterizer_canvas_gles2.h @@ -0,0 +1,104 @@ +/*************************************************************************/ +/* rasterizer_canvas_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZERCANVASGLES2_H +#define RASTERIZERCANVASGLES2_H + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "drivers/gles_common/rasterizer_canvas_batcher.h" +#include "drivers/gles_common/rasterizer_version.h" +#include "rasterizer_canvas_base_gles2.h" + +class RasterizerSceneGLES2; + +class RasterizerCanvasGLES2 : public RasterizerCanvasBaseGLES2, public RasterizerCanvasBatcher { + friend class RasterizerCanvasBatcher; + +public: + virtual void canvas_render_items_begin(const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform); + virtual void canvas_render_items_end(); + void canvas_render_items_internal(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform); + virtual void canvas_begin() override; + virtual void canvas_end() override; + + void canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_list, const Transform2D &p_canvas_transform, RS::CanvasItemTextureFilter p_default_filter, RS::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used) override { + storage->frame.current_rt = nullptr; + + //if (p_to_render_target.is_valid()) + // print_line("canvas_render_items " + itos(p_to_render_target.get_id()) ); + // print_line("canvas_render_items "); + + // first set the current render target + storage->_set_current_render_target(p_to_render_target); + + // binds the render target (framebuffer) + canvas_begin(); + + canvas_render_items_begin(p_modulate, p_light_list, p_canvas_transform); + canvas_render_items_internal(p_item_list, 0, p_modulate, p_light_list, p_canvas_transform); + canvas_render_items_end(); + + canvas_end(); + + // not sure why these are needed to get frame to render? + storage->_set_current_render_target(RID()); + // storage->frame.current_rt = nullptr; + // canvas_begin(); + // canvas_end(); + } + +private: + // legacy codepath .. to remove after testing + void _legacy_canvas_render_item(Item *p_ci, RenderItemState &r_ris); + + // high level batch funcs + void canvas_render_items_implementation(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light, const Transform2D &p_base_transform); + //void render_joined_item(const BItemJoined &p_bij, RenderItemState &r_ris); + //bool try_join_item(Item *p_ci, RenderItemState &r_ris, bool &r_batch_break); + void render_batches(Item::Command *const *p_commands, Item *p_current_clip, bool &r_reclip, RasterizerStorageGLES2::Material *p_material); + + // low level batch funcs + // void _batch_upload_buffers(); + // void _batch_render_generic(const Batch &p_batch, RasterizerStorageGLES2::Material *p_material); + // void _batch_render_lines(const Batch &p_batch, RasterizerStorageGLES2::Material *p_material, bool p_anti_alias); + + // funcs used from rasterizer_canvas_batcher template + void gl_enable_scissor(int p_x, int p_y, int p_width, int p_height) const; + void gl_disable_scissor() const; + +public: + void initialize(); + RasterizerCanvasGLES2(); +}; + +#endif // GLES2_BACKEND_ENABLED +#endif // RASTERIZERCANVASGLES2_H diff --git a/drivers/gles2/rasterizer_gles2.cpp b/drivers/gles2/rasterizer_gles2.cpp new file mode 100644 index 00000000000..222c9b8494c --- /dev/null +++ b/drivers/gles2/rasterizer_gles2.cpp @@ -0,0 +1,377 @@ +/*************************************************************************/ +/* rasterizer_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "rasterizer_gles2.h" + +#ifdef GLES2_BACKEND_ENABLED +#include "shader_gles2.h" + +#include "core/config/project_settings.h" +#include "core/os/os.h" + +#define _EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 +#define _EXT_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 +#define _EXT_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 +#define _EXT_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 +#define _EXT_DEBUG_SOURCE_API_ARB 0x8246 +#define _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 +#define _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 +#define _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 +#define _EXT_DEBUG_SOURCE_APPLICATION_ARB 0x824A +#define _EXT_DEBUG_SOURCE_OTHER_ARB 0x824B +#define _EXT_DEBUG_TYPE_ERROR_ARB 0x824C +#define _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D +#define _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E +#define _EXT_DEBUG_TYPE_PORTABILITY_ARB 0x824F +#define _EXT_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 +#define _EXT_DEBUG_TYPE_OTHER_ARB 0x8251 +#define _EXT_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 +#define _EXT_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 +#define _EXT_DEBUG_LOGGED_MESSAGES_ARB 0x9145 +#define _EXT_DEBUG_SEVERITY_HIGH_ARB 0x9146 +#define _EXT_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 +#define _EXT_DEBUG_SEVERITY_LOW_ARB 0x9148 +#define _EXT_DEBUG_OUTPUT 0x92E0 + +#ifndef GLAPIENTRY +#if defined(WINDOWS_ENABLED) && !defined(UWP_ENABLED) +#define GLAPIENTRY APIENTRY +#else +#define GLAPIENTRY +#endif +#endif + +#ifndef IPHONE_ENABLED +// We include EGL below to get debug callback on GLES2 platforms, +// but EGL is not available on iOS. +#define CAN_DEBUG +#endif + +#if !defined(GLES_OVER_GL) && defined(CAN_DEBUG) +#include +#include +#include + +#include +#include +#endif + +#if defined(MINGW_ENABLED) || defined(_MSC_VER) +#define strcpy strcpy_s +#endif + +void RasterizerGLES2::begin_frame(double frame_step) { + frame++; + delta = frame_step; + + // from 3.2 + time_total += frame_step * time_scale; + + if (frame_step == 0) { + //to avoid hiccups + frame_step = 0.001; + } + + double time_roll_over = GLOBAL_GET("rendering/limits/time/time_rollover_secs"); + time_total = Math::fmod(time_total, time_roll_over); + + storage.frame.time[0] = time_total; + storage.frame.time[1] = Math::fmod(time_total, 3600); + storage.frame.time[2] = Math::fmod(time_total, 900); + storage.frame.time[3] = Math::fmod(time_total, 60); + storage.frame.count++; + storage.frame.delta = frame_step; + + storage.update_dirty_resources(); + + storage.info.render_final = storage.info.render; + storage.info.render.reset(); + + //scene->iteration(); +} + +void RasterizerGLES2::end_frame(bool p_swap_buffers) { + // if (OS::get_singleton()->is_layered_allowed()) { + // if (!OS::get_singleton()->get_window_per_pixel_transparency_enabled()) { + //clear alpha + // glColorMask(false, false, false, true); + // glClearColor(0.5, 0, 0, 1); + // glClear(GL_COLOR_BUFFER_BIT); + // glColorMask(true, true, true, true); + // } + // } + + // glClearColor(1, 0, 0, 1); + // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ACCUM_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + if (p_swap_buffers) + DisplayServer::get_singleton()->swap_buffers(); + else + glFinish(); +} + +#ifdef CAN_DEBUG +static void GLAPIENTRY _gl_debug_print(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *userParam) { + if (type == _EXT_DEBUG_TYPE_OTHER_ARB) + return; + + if (type == _EXT_DEBUG_TYPE_PERFORMANCE_ARB) + return; //these are ultimately annoying, so removing for now + + char debSource[256], debType[256], debSev[256]; + + if (source == _EXT_DEBUG_SOURCE_API_ARB) + strcpy(debSource, "OpenGL"); + else if (source == _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB) + strcpy(debSource, "Windows"); + else if (source == _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB) + strcpy(debSource, "Shader Compiler"); + else if (source == _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB) + strcpy(debSource, "Third Party"); + else if (source == _EXT_DEBUG_SOURCE_APPLICATION_ARB) + strcpy(debSource, "Application"); + else if (source == _EXT_DEBUG_SOURCE_OTHER_ARB) + strcpy(debSource, "Other"); + + if (type == _EXT_DEBUG_TYPE_ERROR_ARB) + strcpy(debType, "Error"); + else if (type == _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB) + strcpy(debType, "Deprecated behavior"); + else if (type == _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB) + strcpy(debType, "Undefined behavior"); + else if (type == _EXT_DEBUG_TYPE_PORTABILITY_ARB) + strcpy(debType, "Portability"); + else if (type == _EXT_DEBUG_TYPE_PERFORMANCE_ARB) + strcpy(debType, "Performance"); + else if (type == _EXT_DEBUG_TYPE_OTHER_ARB) + strcpy(debType, "Other"); + + if (severity == _EXT_DEBUG_SEVERITY_HIGH_ARB) + strcpy(debSev, "High"); + else if (severity == _EXT_DEBUG_SEVERITY_MEDIUM_ARB) + strcpy(debSev, "Medium"); + else if (severity == _EXT_DEBUG_SEVERITY_LOW_ARB) + strcpy(debSev, "Low"); + + String output = String() + "GL ERROR: Source: " + debSource + "\tType: " + debType + "\tID: " + itos(id) + "\tSeverity: " + debSev + "\tMessage: " + message; + + ERR_PRINT(output); +} +#endif // CAN_DEBUG + +typedef void (*DEBUGPROCARB)(GLenum source, + GLenum type, + GLuint id, + GLenum severity, + GLsizei length, + const char *message, + const void *userParam); + +typedef void (*DebugMessageCallbackARB)(DEBUGPROCARB callback, const void *userParam); + +void RasterizerGLES2::initialize() { + print_verbose("Using GLES2 video driver"); + + storage._main_thread_id = Thread::get_caller_id(); + +#ifdef GLAD_ENABLED + if (!gladLoadGL()) { + ERR_PRINT("Error initializing GLAD"); + return; + } +#endif + +#ifdef GLAD_ENABLED + if (OS::get_singleton()->is_stdout_verbose()) { + if (GLAD_GL_ARB_debug_output) { + glEnable(_EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB); + glDebugMessageCallbackARB(_gl_debug_print, NULL); + glEnable(_EXT_DEBUG_OUTPUT); + } else { + print_line("OpenGL debugging not supported!"); + } + } +#endif // GLAD_ENABLED + + // For debugging +#ifdef CAN_DEBUG +#ifdef GLES_OVER_GL + if (OS::get_singleton()->is_stdout_verbose() && GLAD_GL_ARB_debug_output) { + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_ERROR_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_PORTABILITY_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_PERFORMANCE_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + glDebugMessageControlARB(_EXT_DEBUG_SOURCE_API_ARB, _EXT_DEBUG_TYPE_OTHER_ARB, _EXT_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE); + // glDebugMessageInsertARB( + // GL_DEBUG_SOURCE_API_ARB, + // GL_DEBUG_TYPE_OTHER_ARB, 1, + // GL_DEBUG_SEVERITY_HIGH_ARB, 5, "hello"); + } +#else + if (OS::get_singleton()->is_stdout_verbose()) { + DebugMessageCallbackARB callback = (DebugMessageCallbackARB)eglGetProcAddress("glDebugMessageCallback"); + if (!callback) { + callback = (DebugMessageCallbackARB)eglGetProcAddress("glDebugMessageCallbackKHR"); + } + + if (callback) { + print_line("godot: ENABLING GL DEBUG"); + glEnable(_EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB); + callback(_gl_debug_print, NULL); + glEnable(_EXT_DEBUG_OUTPUT); + } + } +#endif // GLES_OVER_GL +#endif // CAN_DEBUG + + print_line("OpenGL ES 2.0 Renderer: " + GD_VS::get_singleton()->get_video_adapter_name()); + storage.initialize(); + canvas.initialize(); + // scene.initialize(); + + // make sure the OS knows to only access the renderer from the main thread + OS::get_singleton()->set_render_main_thread_mode(OS::RENDER_MAIN_THREAD_ONLY); +} + +RasterizerGLES2::RasterizerGLES2() { + canvas.storage = &storage; + canvas.scene_render = &scene; + storage.canvas = &canvas; + //scene.storage = &storage; + storage.scene = &scene; +} + +void RasterizerGLES2::prepare_for_blitting_render_targets() { +} + +void RasterizerGLES2::_blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect) { + ERR_FAIL_COND(storage.frame.current_rt); + + // print_line("_blit_render_target_to_screen " + itos (p_screen) + ", rect " + String(Variant(p_screen_rect))); + + RasterizerStorageGLES2::RenderTarget *rt = storage.render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + canvas._set_texture_rect_mode(true); + canvas.state.canvas_shader.set_custom_shader(0); + canvas.state.canvas_shader.bind(); + + canvas.canvas_begin(); + + glDisable(GL_BLEND); + glActiveTexture(GL_TEXTURE0 + storage.config.max_texture_image_units - 1); + if (rt->external.fbo != 0) { + glBindTexture(GL_TEXTURE_2D, rt->external.color); + } else { + glBindTexture(GL_TEXTURE_2D, rt->color); + } + canvas.draw_generic_textured_rect(p_screen_rect, Rect2(0, 0, 1, -1)); + glBindTexture(GL_TEXTURE_2D, 0); + + canvas.canvas_end(); +} + +// is this p_screen useless in a multi window environment? +void RasterizerGLES2::blit_render_targets_to_screen(DisplayServer::WindowID p_screen, const BlitToScreen *p_render_targets, int p_amount) { + // do this once off for all blits + storage.bind_framebuffer_system(); + + storage.frame.current_rt = nullptr; + + for (int i = 0; i < p_amount; i++) { + const BlitToScreen &blit = p_render_targets[i]; + + RID rid_rt = blit.render_target; + + Rect2 dst_rect = blit.dst_rect; + _blit_render_target_to_screen(rid_rt, dst_rect); + } +} + +void RasterizerGLES2::set_boot_image(const Ref &p_image, const Color &p_color, bool p_scale, bool p_use_filter) { + if (p_image.is_null() || p_image->is_empty()) + return; + + int window_w = 640; //OS::get_singleton()->get_video_mode(0).width; + int window_h = 480; //OS::get_singleton()->get_video_mode(0).height; + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, window_w, window_h); + glDisable(GL_BLEND); + glDepthMask(GL_FALSE); + if (false) { + // if (OS::get_singleton()->get_window_per_pixel_transparency_enabled()) { + glClearColor(0.0, 0.0, 0.0, 0.0); + } else { + glClearColor(p_color.r, p_color.g, p_color.b, 1.0); + } + glClear(GL_COLOR_BUFFER_BIT); + + canvas.canvas_begin(); + + RID texture = storage.texture_create(); + //storage.texture_allocate(texture, p_image->get_width(), p_image->get_height(), 0, p_image->get_format(), VS::TEXTURE_TYPE_2D, p_use_filter ? VS::TEXTURE_FLAG_FILTER : 0); + storage._texture_allocate_internal(texture, p_image->get_width(), p_image->get_height(), 0, p_image->get_format(), GD_RD::TEXTURE_TYPE_2D); + storage.texture_set_data(texture, p_image); + + Rect2 imgrect(0, 0, p_image->get_width(), p_image->get_height()); + Rect2 screenrect; + if (p_scale) { + if (window_w > window_h) { + //scale horizontally + screenrect.size.y = window_h; + screenrect.size.x = imgrect.size.x * window_h / imgrect.size.y; + screenrect.position.x = (window_w - screenrect.size.x) / 2; + + } else { + //scale vertically + screenrect.size.x = window_w; + screenrect.size.y = imgrect.size.y * window_w / imgrect.size.x; + screenrect.position.y = (window_h - screenrect.size.y) / 2; + } + } else { + screenrect = imgrect; + screenrect.position += ((Size2(window_w, window_h) - screenrect.size) / 2.0).floor(); + } + + RasterizerStorageGLES2::Texture *t = storage.texture_owner.getornull(texture); + glActiveTexture(GL_TEXTURE0 + storage.config.max_texture_image_units - 1); + glBindTexture(GL_TEXTURE_2D, t->tex_id); + canvas.draw_generic_textured_rect(screenrect, Rect2(0, 0, 1, 1)); + glBindTexture(GL_TEXTURE_2D, 0); + canvas.canvas_end(); + + storage.free(texture); + + end_frame(true); +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_gles2.h b/drivers/gles2/rasterizer_gles2.h new file mode 100644 index 00000000000..3066dc421b3 --- /dev/null +++ b/drivers/gles2/rasterizer_gles2.h @@ -0,0 +1,90 @@ +/*************************************************************************/ +/* rasterizer_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "drivers/gles_common/rasterizer_version.h" +#include "rasterizer_canvas_gles2.h" +#include "rasterizer_scene_gles2.h" +#include "rasterizer_storage_gles2.h" +#include "servers/rendering/renderer_compositor.h" + +class RasterizerGLES2 : public RendererCompositor { +private: + uint64_t frame = 1; + float delta = 0; + + double time_total = 0.0; + double time_scale = 1.0; + +protected: + RasterizerCanvasGLES2 canvas; + RasterizerStorageGLES2 storage; + RasterizerSceneGLES2 scene; + + void _blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect); + +public: + RendererStorage *get_storage() { return &storage; } + RendererCanvasRender *get_canvas() { return &canvas; } + RendererSceneRender *get_scene() { return &scene; } + + void set_boot_image(const Ref &p_image, const Color &p_color, bool p_scale, bool p_use_filter = true); + + void initialize(); + void begin_frame(double frame_step); + + void prepare_for_blitting_render_targets(); + void blit_render_targets_to_screen(DisplayServer::WindowID p_screen, const BlitToScreen *p_render_targets, int p_amount); + + void end_frame(bool p_swap_buffers); + + void finalize() {} + + static RendererCompositor *_create_current() { + return memnew(RasterizerGLES2); + } + + static void make_current() { + _create_func = _create_current; + } + + virtual bool is_low_end() const { return true; } + uint64_t get_frame_number() const { return frame; } + double get_frame_delta_time() const { return delta; } + + RasterizerGLES2(); + ~RasterizerGLES2() {} +}; + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_scene_gles2.cpp b/drivers/gles2/rasterizer_scene_gles2.cpp new file mode 100644 index 00000000000..6ef0816934d --- /dev/null +++ b/drivers/gles2/rasterizer_scene_gles2.cpp @@ -0,0 +1,3955 @@ +/*************************************************************************/ +/* rasterizer_scene_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "rasterizer_scene_gles2.h" +#ifdef GLES2_BACKEND_ENABLED + +#ifdef GODOT_3 + +#include "core/math/math_funcs.h" +#include "core/math/transform.h" +#include "core/os/os.h" +#include "core/project_settings.h" +#include "core/vmap.h" +#include "rasterizer_canvas_gles2.h" +#include "servers/camera/camera_feed.h" +#include "servers/visual/visual_server_raster.h" + +#ifndef GLES_OVER_GL +#define glClearDepth glClearDepthf +#endif + +#ifndef GLES_OVER_GL +#ifdef IPHONE_ENABLED +#include +//void *glResolveMultisampleFramebufferAPPLE; + +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif +#endif + +static const GLenum _cube_side_enum[6] = { + GL_TEXTURE_CUBE_MAP_NEGATIVE_X, + GL_TEXTURE_CUBE_MAP_POSITIVE_X, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, + GL_TEXTURE_CUBE_MAP_POSITIVE_Y, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, + GL_TEXTURE_CUBE_MAP_POSITIVE_Z, +}; + +/* SHADOW ATLAS API */ + +RID RasterizerSceneGLES2::shadow_atlas_create() { + ShadowAtlas *shadow_atlas = memnew(ShadowAtlas); + shadow_atlas->fbo = 0; + shadow_atlas->depth = 0; + shadow_atlas->color = 0; + shadow_atlas->size = 0; + shadow_atlas->smallest_subdiv = 0; + + for (int i = 0; i < 4; i++) { + shadow_atlas->size_order[i] = i; + } + + return shadow_atlas_owner.make_rid(shadow_atlas); +} + +void RasterizerSceneGLES2::shadow_atlas_set_size(RID p_atlas, int p_size) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); + ERR_FAIL_COND(!shadow_atlas); + ERR_FAIL_COND(p_size < 0); + + p_size = next_power_of_2(p_size); + + if (p_size == shadow_atlas->size) + return; + + // erase the old atlast + if (shadow_atlas->fbo) { + if (storage->config.use_rgba_3d_shadows) { + glDeleteRenderbuffers(1, &shadow_atlas->depth); + } else { + glDeleteTextures(1, &shadow_atlas->depth); + } + glDeleteFramebuffers(1, &shadow_atlas->fbo); + if (shadow_atlas->color) { + glDeleteTextures(1, &shadow_atlas->color); + } + + shadow_atlas->fbo = 0; + shadow_atlas->depth = 0; + shadow_atlas->color = 0; + } + + // erase shadow atlast references from lights + for (Map::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) { + LightInstance *li = light_instance_owner.getornull(E->key()); + ERR_CONTINUE(!li); + li->shadow_atlases.erase(p_atlas); + } + + shadow_atlas->shadow_owners.clear(); + + shadow_atlas->size = p_size; + + if (shadow_atlas->size) { + glGenFramebuffers(1, &shadow_atlas->fbo); + glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo); + + // create a depth texture + glActiveTexture(GL_TEXTURE0); + + if (storage->config.use_rgba_3d_shadows) { + //maximum compatibility, renderbuffer and RGBA shadow + glGenRenderbuffers(1, &shadow_atlas->depth); + glBindRenderbuffer(GL_RENDERBUFFER, shadow_atlas->depth); + glRenderbufferStorage(GL_RENDERBUFFER, storage->config.depth_internalformat, shadow_atlas->size, shadow_atlas->size); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, shadow_atlas->depth); + + glGenTextures(1, &shadow_atlas->color); + glBindTexture(GL_TEXTURE_2D, shadow_atlas->color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, shadow_atlas->size, shadow_atlas->size, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, shadow_atlas->color, 0); + } else { + //just depth texture + glGenTextures(1, &shadow_atlas->depth); + glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); + glTexImage2D(GL_TEXTURE_2D, 0, storage->config.depth_internalformat, shadow_atlas->size, shadow_atlas->size, 0, GL_DEPTH_COMPONENT, storage->config.depth_type, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadow_atlas->depth, 0); + } + glViewport(0, 0, shadow_atlas->size, shadow_atlas->size); + + glDepthMask(GL_TRUE); + + glClearDepth(0.0f); + glClear(GL_DEPTH_BUFFER_BIT); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } +} + +void RasterizerSceneGLES2::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); + ERR_FAIL_COND(!shadow_atlas); + ERR_FAIL_INDEX(p_quadrant, 4); + ERR_FAIL_INDEX(p_subdivision, 16384); + + uint32_t subdiv = next_power_of_2(p_subdivision); + if (subdiv & 0xaaaaaaaa) { // sqrt(subdiv) must be integer + subdiv <<= 1; + } + + subdiv = int(Math::sqrt((float)subdiv)); + + if (shadow_atlas->quadrants[p_quadrant].shadows.size() == (int)subdiv) + return; + + // erase all data from the quadrant + for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) { + if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) { + shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); + + LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); + ERR_CONTINUE(!li); + li->shadow_atlases.erase(p_atlas); + } + } + + shadow_atlas->quadrants[p_quadrant].shadows.resize(0); + shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv); + shadow_atlas->quadrants[p_quadrant].subdivision = subdiv; + + // cache the smallest subdivision for faster allocations + + shadow_atlas->smallest_subdiv = 1 << 30; + + for (int i = 0; i < 4; i++) { + if (shadow_atlas->quadrants[i].subdivision) { + shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision); + } + } + + if (shadow_atlas->smallest_subdiv == 1 << 30) { + shadow_atlas->smallest_subdiv = 0; + } + + // re-sort the quadrants + + int swaps = 0; + do { + swaps = 0; + + for (int i = 0; i < 3; i++) { + if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) { + SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]); + swaps++; + } + } + + } while (swaps > 0); +} + +bool RasterizerSceneGLES2::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) { + for (int i = p_quadrant_count - 1; i >= 0; i--) { + int qidx = p_in_quadrants[i]; + + if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) { + return false; + } + + // look for an empty space + + int sc = shadow_atlas->quadrants[qidx].shadows.size(); + + ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw(); + + int found_free_idx = -1; // found a free one + int found_used_idx = -1; // found an existing one, must steal it + uint64_t min_pass = 0; // pass of the existing one, try to use the least recently + + for (int j = 0; j < sc; j++) { + if (!sarr[j].owner.is_valid()) { + found_free_idx = j; + break; + } + + LightInstance *sli = light_instance_owner.getornull(sarr[j].owner); + ERR_CONTINUE(!sli); + + if (sli->last_scene_pass != scene_pass) { + // was just allocated, don't kill it so soon, wait a bit... + + if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) { + continue; + } + + if (found_used_idx == -1 || sli->last_scene_pass < min_pass) { + found_used_idx = j; + min_pass = sli->last_scene_pass; + } + } + } + + if (found_free_idx == -1 && found_used_idx == -1) { + continue; // nothing found + } + + if (found_free_idx == -1 && found_used_idx != -1) { + found_free_idx = found_used_idx; + } + + r_quadrant = qidx; + r_shadow = found_free_idx; + + return true; + } + + return false; +} + +bool RasterizerSceneGLES2::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); + ERR_FAIL_COND_V(!shadow_atlas, false); + + LightInstance *li = light_instance_owner.getornull(p_light_intance); + ERR_FAIL_COND_V(!li, false); + + if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) { + return false; + } + + uint32_t quad_size = shadow_atlas->size >> 1; + int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage)); + + int valid_quadrants[4]; + int valid_quadrant_count = 0; + int best_size = -1; + int best_subdiv = -1; + + for (int i = 0; i < 4; i++) { + int q = shadow_atlas->size_order[i]; + int sd = shadow_atlas->quadrants[q].subdivision; + + if (sd == 0) { + continue; + } + + int max_fit = quad_size / sd; + + if (best_size != -1 && max_fit > best_size) { + break; // what we asked for is bigger than this. + } + + valid_quadrants[valid_quadrant_count] = q; + valid_quadrant_count++; + + best_subdiv = sd; + + if (max_fit >= desired_fit) { + best_size = max_fit; + } + } + + ERR_FAIL_COND_V(valid_quadrant_count == 0, false); // no suitable block available + + uint64_t tick = OS::get_singleton()->get_ticks_msec(); + + if (shadow_atlas->shadow_owners.has(p_light_intance)) { + // light was already known! + + uint32_t key = shadow_atlas->shadow_owners[p_light_intance]; + uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; + uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK; + + bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec); + + bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version; + + if (!should_realloc) { + shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version; + return should_redraw; + } + + int new_quadrant; + int new_shadow; + + // find a better place + + if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) { + // found a better place + + ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow]; + if (sh->owner.is_valid()) { + // it is take but invalid, so we can take it + + shadow_atlas->shadow_owners.erase(sh->owner); + LightInstance *sli = light_instance_owner.get(sh->owner); + sli->shadow_atlases.erase(p_atlas); + } + + // erase previous + shadow_atlas->quadrants[q].shadows.write[s].version = 0; + shadow_atlas->quadrants[q].shadows.write[s].owner = RID(); + + sh->owner = p_light_intance; + sh->alloc_tick = tick; + sh->version = p_light_version; + li->shadow_atlases.insert(p_atlas); + + // make a new key + key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT; + key |= new_shadow; + + // update it in the map + shadow_atlas->shadow_owners[p_light_intance] = key; + + // make it dirty, so we redraw + return true; + } + + // no better place found, so we keep the current place + + shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version; + + return should_redraw; + } + + int new_quadrant; + int new_shadow; + + if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) { + // found a better place + + ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow]; + if (sh->owner.is_valid()) { + // it is take but invalid, so we can take it + + shadow_atlas->shadow_owners.erase(sh->owner); + LightInstance *sli = light_instance_owner.get(sh->owner); + sli->shadow_atlases.erase(p_atlas); + } + + sh->owner = p_light_intance; + sh->alloc_tick = tick; + sh->version = p_light_version; + li->shadow_atlases.insert(p_atlas); + + // make a new key + uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT; + key |= new_shadow; + + // update it in the map + shadow_atlas->shadow_owners[p_light_intance] = key; + + // make it dirty, so we redraw + return true; + } + + return false; +} + +void RasterizerSceneGLES2::set_directional_shadow_count(int p_count) { + directional_shadow.light_count = p_count; + directional_shadow.current_light = 0; +} + +int RasterizerSceneGLES2::get_directional_light_shadow_size(RID p_light_intance) { + ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0); + + int shadow_size; + + if (directional_shadow.light_count == 1) { + shadow_size = directional_shadow.size; + } else { + shadow_size = directional_shadow.size / 2; //more than 4 not supported anyway + } + + LightInstance *light_instance = light_instance_owner.getornull(p_light_intance); + ERR_FAIL_COND_V(!light_instance, 0); + + switch (light_instance->light_ptr->directional_shadow_mode) { + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: + break; //none + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: + shadow_size /= 2; + break; + } + + return shadow_size; +} +////////////////////////////////////////////////////// + +RID RasterizerSceneGLES2::reflection_atlas_create() { + return RID(); +} + +void RasterizerSceneGLES2::reflection_atlas_set_size(RID p_ref_atlas, int p_size) { +} + +void RasterizerSceneGLES2::reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) { +} + +//////////////////////////////////////////////////// + +RID RasterizerSceneGLES2::reflection_probe_instance_create(RID p_probe) { + RasterizerStorageGLES2::ReflectionProbe *probe = storage->reflection_probe_owner.getornull(p_probe); + ERR_FAIL_COND_V(!probe, RID()); + + ReflectionProbeInstance *rpi = memnew(ReflectionProbeInstance); + + rpi->probe_ptr = probe; + rpi->self = reflection_probe_instance_owner.make_rid(rpi); + rpi->probe = p_probe; + rpi->reflection_atlas_index = -1; + rpi->render_step = -1; + rpi->last_pass = 0; + rpi->current_resolution = 0; + rpi->dirty = true; + + rpi->index = 0; + + for (int i = 0; i < 6; i++) { + glGenFramebuffers(1, &rpi->fbo[i]); + glGenTextures(1, &rpi->color[i]); + } + + glGenRenderbuffers(1, &rpi->depth); + + rpi->cubemap = 0; + //glGenTextures(1, &rpi->cubemap); + + return rpi->self; +} + +void RasterizerSceneGLES2::reflection_probe_instance_set_transform(RID p_instance, const Transform3D &p_transform) { + ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); + ERR_FAIL_COND(!rpi); + rpi->transform = p_transform; +} + +void RasterizerSceneGLES2::reflection_probe_release_atlas_index(RID p_instance) { +} + +bool RasterizerSceneGLES2::reflection_probe_instance_needs_redraw(RID p_instance) { + const ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); + ERR_FAIL_COND_V(!rpi, false); + + bool need_redraw = rpi->probe_ptr->resolution != rpi->current_resolution || rpi->dirty || rpi->probe_ptr->update_mode == GD_VS::REFLECTION_PROBE_UPDATE_ALWAYS; + rpi->dirty = false; + return need_redraw; +} + +bool RasterizerSceneGLES2::reflection_probe_instance_has_reflection(RID p_instance) { + return true; +} + +bool RasterizerSceneGLES2::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) { + ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); + ERR_FAIL_COND_V(!rpi, false); + + rpi->render_step = 0; + + if (rpi->probe_ptr->resolution != rpi->current_resolution) { + //update cubemap if resolution changed + int size = rpi->probe_ptr->resolution; + rpi->current_resolution = size; + + GLenum internal_format = GL_RGB; + GLenum format = GL_RGB; + GLenum type = GL_UNSIGNED_BYTE; + + glActiveTexture(GL_TEXTURE0); + + glBindRenderbuffer(GL_RENDERBUFFER, rpi->depth); + glRenderbufferStorage(GL_RENDERBUFFER, storage->config.depth_internalformat, size, size); + + if (rpi->cubemap != 0) { + glDeleteTextures(1, &rpi->cubemap); + } + + glGenTextures(1, &rpi->cubemap); + glBindTexture(GL_TEXTURE_CUBE_MAP, rpi->cubemap); + + // Mobile hardware (PowerVR specially) prefers this approach, + // the previous approach with manual lod levels kills the game. + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, size, size, 0, format, type, NULL); + } + + glGenerateMipmap(GL_TEXTURE_CUBE_MAP); + + // Generate framebuffers for rendering + for (int i = 0; i < 6; i++) { + glBindFramebuffer(GL_FRAMEBUFFER, rpi->fbo[i]); + glBindTexture(GL_TEXTURE_2D, rpi->color[i]); + glTexImage2D(GL_TEXTURE_2D, 0, internal_format, size, size, 0, format, type, NULL); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rpi->color[i], 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rpi->depth); + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE); + } + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES2::system_fbo); + } + + return true; +} + +bool RasterizerSceneGLES2::reflection_probe_instance_postprocess_step(RID p_instance) { + ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); + ERR_FAIL_COND_V(!rpi, false); + ERR_FAIL_COND_V(rpi->current_resolution == 0, false); + + int size = rpi->probe_ptr->resolution; + + { + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); + glDepthMask(GL_FALSE); + + for (int i = 0; i < GD_VS::ARRAY_MAX - 1; i++) { + glDisableVertexAttribArray(i); + } + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_CUBE_MAP, rpi->cubemap); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //use linear, no mipmaps so it does not read from what is being written to + + //first of all, copy rendered textures to cubemap + for (int i = 0; i < 6; i++) { + glBindFramebuffer(GL_FRAMEBUFFER, rpi->fbo[i]); + glViewport(0, 0, size, size); + glCopyTexSubImage2D(_cube_side_enum[i], 0, 0, 0, 0, 0, size, size); + } + //do filtering + //vdc cache + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, storage->resources.radical_inverse_vdc_cache_tex); + + // now render to the framebuffer, mipmap level for mipmap level + int lod = 1; + + size >>= 1; + int mipmaps = 6; + + storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_SOURCE_PANORAMA, false); + storage->shaders.cubemap_filter.bind(); + + glBindFramebuffer(GL_FRAMEBUFFER, storage->resources.mipmap_blur_fbo); + + //blur + while (size >= 1) { + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, storage->resources.mipmap_blur_color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, storage->resources.mipmap_blur_color, 0); + glViewport(0, 0, size, size); + glActiveTexture(GL_TEXTURE0); + + for (int i = 0; i < 6; i++) { + storage->bind_quad_array(); + storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::FACE_ID, i); + float roughness = CLAMP(lod / (float)(mipmaps - 1), 0, 1); + storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::ROUGHNESS, roughness); + storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::Z_FLIP, false); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glCopyTexSubImage2D(_cube_side_enum[i], lod, 0, 0, 0, 0, size, size); + } + + size >>= 1; + + lod++; + } + + // restore ranges + glActiveTexture(GL_TEXTURE0); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE3); //back to panorama + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES2::system_fbo); + + return true; +} + +/* ENVIRONMENT API */ + +RID RasterizerSceneGLES2::environment_create() { + Environment *env = memnew(Environment); + + return environment_owner.make_rid(env); +} + +void RasterizerSceneGLES2::environment_set_background(RID p_env, GD_VS::EnvironmentBG p_bg) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + env->bg_mode = p_bg; +} + +void RasterizerSceneGLES2::environment_set_sky(RID p_env, RID p_sky) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->sky = p_sky; +} + +void RasterizerSceneGLES2::environment_set_sky_custom_fov(RID p_env, float p_scale) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->sky_custom_fov = p_scale; +} + +void RasterizerSceneGLES2::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->sky_orientation = p_orientation; +} + +void RasterizerSceneGLES2::environment_set_bg_color(RID p_env, const Color &p_color) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->bg_color = p_color; +} + +void RasterizerSceneGLES2::environment_set_bg_energy(RID p_env, float p_energy) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->bg_energy = p_energy; +} + +void RasterizerSceneGLES2::environment_set_canvas_max_layer(RID p_env, int p_max_layer) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->canvas_max_layer = p_max_layer; +} + +void RasterizerSceneGLES2::environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy, float p_sky_contribution) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->ambient_color = p_color; + env->ambient_energy = p_energy; + env->ambient_sky_contribution = p_sky_contribution; +} + +void RasterizerSceneGLES2::environment_set_camera_feed_id(RID p_env, int p_camera_feed_id) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->camera_feed_id = p_camera_feed_id; +} + +void RasterizerSceneGLES2::environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, GD_VS::EnvironmentDOFBlurQuality p_quality) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->dof_blur_far_enabled = p_enable; + env->dof_blur_far_distance = p_distance; + env->dof_blur_far_transition = p_transition; + env->dof_blur_far_amount = p_amount; + env->dof_blur_far_quality = p_quality; +} + +void RasterizerSceneGLES2::environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, GD_VS::EnvironmentDOFBlurQuality p_quality) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->dof_blur_near_enabled = p_enable; + env->dof_blur_near_distance = p_distance; + env->dof_blur_near_transition = p_transition; + env->dof_blur_near_amount = p_amount; + env->dof_blur_near_quality = p_quality; +} + +void RasterizerSceneGLES2::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_threshold, GD_VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap, bool p_bicubic_upscale) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->glow_enabled = p_enable; + env->glow_levels = p_level_flags; + env->glow_intensity = p_intensity; + env->glow_strength = p_strength; + env->glow_bloom = p_bloom_threshold; + env->glow_blend_mode = p_blend_mode; + env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold; + env->glow_hdr_bleed_scale = p_hdr_bleed_scale; + env->glow_hdr_luminance_cap = p_hdr_luminance_cap; + env->glow_bicubic_upscale = p_bicubic_upscale; +} + +void RasterizerSceneGLES2::environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); +} + +void RasterizerSceneGLES2::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_in, float p_fade_out, float p_depth_tolerance, bool p_roughness) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); +} + +void RasterizerSceneGLES2::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, float p_ao_channel_affect, const Color &p_color, GD_VS::EnvironmentSSAOQuality p_quality, VisualServer::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); +} + +void RasterizerSceneGLES2::environment_set_tonemap(RID p_env, GD_VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); +} + +void RasterizerSceneGLES2::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->adjustments_enabled = p_enable; + env->adjustments_brightness = p_brightness; + env->adjustments_contrast = p_contrast; + env->adjustments_saturation = p_saturation; + env->color_correction = p_ramp; +} + +void RasterizerSceneGLES2::environment_set_fog(RID p_env, bool p_enable, const Color &p_color, const Color &p_sun_color, float p_sun_amount) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->fog_enabled = p_enable; + env->fog_color = p_color; + env->fog_sun_color = p_sun_color; + env->fog_sun_amount = p_sun_amount; +} + +void RasterizerSceneGLES2::environment_set_fog_depth(RID p_env, bool p_enable, float p_depth_begin, float p_depth_end, float p_depth_curve, bool p_transmit, float p_transmit_curve) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->fog_depth_enabled = p_enable; + env->fog_depth_begin = p_depth_begin; + env->fog_depth_end = p_depth_end; + env->fog_depth_curve = p_depth_curve; + env->fog_transmit_enabled = p_transmit; + env->fog_transmit_curve = p_transmit_curve; +} + +void RasterizerSceneGLES2::environment_set_fog_height(RID p_env, bool p_enable, float p_min_height, float p_max_height, float p_height_curve) { + Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND(!env); + + env->fog_height_enabled = p_enable; + env->fog_height_min = p_min_height; + env->fog_height_max = p_max_height; + env->fog_height_curve = p_height_curve; +} +bool RasterizerSceneGLES2::is_environment(RID p_env) { + return environment_owner.owns(p_env); +} + +VS::EnvironmentBG RasterizerSceneGLES2::environment_get_background(RID p_env) { + const Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND_V(!env, GD_VS::ENV_BG_MAX); + + return env->bg_mode; +} + +int RasterizerSceneGLES2::environment_get_canvas_max_layer(RID p_env) { + const Environment *env = environment_owner.getornull(p_env); + ERR_FAIL_COND_V(!env, -1); + + return env->canvas_max_layer; +} + +RID RasterizerSceneGLES2::light_instance_create(RID p_light) { + LightInstance *light_instance = memnew(LightInstance); + + light_instance->last_scene_pass = 0; + + light_instance->light = p_light; + light_instance->light_ptr = storage->light_owner.getornull(p_light); + + light_instance->light_index = 0xFFFF; + + if (!light_instance->light_ptr) { + memdelete(light_instance); + ERR_FAIL_V_MSG(RID(), "Condition ' !light_instance->light_ptr ' is true."); + } + + light_instance->self = light_instance_owner.make_rid(light_instance); + + return light_instance->self; +} + +void RasterizerSceneGLES2::light_instance_set_transform(RID p_light_instance, const Transform3D &p_transform) { + LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); + ERR_FAIL_COND(!light_instance); + + light_instance->transform = p_transform; +} + +void RasterizerSceneGLES2::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform3D &p_transform, float p_far, float p_split, int p_pass, float p_bias_scale) { + LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); + ERR_FAIL_COND(!light_instance); + + if (light_instance->light_ptr->type != GD_VS::LIGHT_DIRECTIONAL) { + p_pass = 0; + } + + ERR_FAIL_INDEX(p_pass, 4); + + light_instance->shadow_transform[p_pass].camera = p_projection; + light_instance->shadow_transform[p_pass].transform = p_transform; + light_instance->shadow_transform[p_pass].farplane = p_far; + light_instance->shadow_transform[p_pass].split = p_split; + light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale; +} + +void RasterizerSceneGLES2::light_instance_mark_visible(RID p_light_instance) { + LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); + ERR_FAIL_COND(!light_instance); + + light_instance->last_scene_pass = scene_pass; +} + +////////////////////// + +RID RasterizerSceneGLES2::gi_probe_instance_create() { + return RID(); +} + +void RasterizerSceneGLES2::gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) { +} +void RasterizerSceneGLES2::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform3D &p_xform) { +} + +void RasterizerSceneGLES2::gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) { +} + +//////////////////////////// +//////////////////////////// +//////////////////////////// + +void RasterizerSceneGLES2::_add_geometry(RasterizerStorageGLES2::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES2::GeometryOwner *p_owner, int p_material, bool p_depth_pass, bool p_shadow_pass) { + RasterizerStorageGLES2::Material *material = NULL; + RID material_src; + + if (p_instance->material_override.is_valid()) { + material_src = p_instance->material_override; + } else if (p_material >= 0) { + material_src = p_instance->materials[p_material]; + } else { + material_src = p_geometry->material; + } + + if (material_src.is_valid()) { + material = storage->material_owner.getornull(material_src); + + if (!material->shader || !material->shader->valid) { + material = NULL; + } + } + + if (!material) { + material = storage->material_owner.getptr(default_material); + } + + ERR_FAIL_COND(!material); + + _add_geometry_with_material(p_geometry, p_instance, p_owner, material, p_depth_pass, p_shadow_pass); + + while (material->next_pass.is_valid()) { + material = storage->material_owner.getornull(material->next_pass); + + if (!material || !material->shader || !material->shader->valid) { + break; + } + + _add_geometry_with_material(p_geometry, p_instance, p_owner, material, p_depth_pass, p_shadow_pass); + } +} +void RasterizerSceneGLES2::_add_geometry_with_material(RasterizerStorageGLES2::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES2::GeometryOwner *p_owner, RasterizerStorageGLES2::Material *p_material, bool p_depth_pass, bool p_shadow_pass) { + bool has_base_alpha = (p_material->shader->spatial.uses_alpha && !p_material->shader->spatial.uses_alpha_scissor) || p_material->shader->spatial.uses_screen_texture || p_material->shader->spatial.uses_depth_texture; + bool has_blend_alpha = p_material->shader->spatial.blend_mode != RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_MIX; + bool has_alpha = has_base_alpha || has_blend_alpha; + + bool mirror = p_instance->mirror; + + if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES2::Shader::Spatial::CULL_MODE_DISABLED) { + mirror = false; + } else if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES2::Shader::Spatial::CULL_MODE_FRONT) { + mirror = !mirror; + } + + //if (p_material->shader->spatial.uses_sss) { + // state.used_sss = true; + //} + + if (p_material->shader->spatial.uses_screen_texture) { + state.used_screen_texture = true; + } + + if (p_depth_pass) { + if (has_blend_alpha || p_material->shader->spatial.uses_depth_texture || (has_base_alpha && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) + return; //bye + + if (!p_material->shader->spatial.uses_alpha_scissor && !p_material->shader->spatial.writes_modelview_or_projection && !p_material->shader->spatial.uses_vertex && !p_material->shader->spatial.uses_discard && p_material->shader->spatial.depth_draw_mode != RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { + //shader does not use discard and does not write a vertex position, use generic material + if (p_instance->cast_shadows == GD_VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED) { + p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material_twosided : default_material_twosided); + mirror = false; + } else { + p_material = storage->material_owner.getptr(!p_shadow_pass && p_material->shader->spatial.uses_world_coordinates ? default_worldcoord_material : default_material); + } + } + + has_alpha = false; + } + + RenderList::Element *e = (has_alpha || p_material->shader->spatial.no_depth_test) ? render_list.add_alpha_element() : render_list.add_element(); + + if (!e) { + return; + } + + e->geometry = p_geometry; + e->material = p_material; + e->instance = p_instance; + e->owner = p_owner; + e->sort_key = 0; + e->depth_key = 0; + e->use_accum = false; + e->light_index = RenderList::MAX_LIGHTS; + e->use_accum_ptr = &e->use_accum; + e->instancing = (e->instance->base_type == GD_VS::INSTANCE_MULTIMESH) ? 1 : 0; + e->front_facing = false; + + if (e->geometry->last_pass != render_pass) { + e->geometry->last_pass = render_pass; + e->geometry->index = current_geometry_index++; + } + + e->geometry_index = e->geometry->index; + + if (e->material->last_pass != render_pass) { + e->material->last_pass = render_pass; + e->material->index = current_material_index++; + + if (e->material->shader->last_pass != render_pass) { + e->material->shader->index = current_shader_index++; + } + } + + e->material_index = e->material->index; + + if (mirror) { + e->front_facing = true; + } + + e->refprobe_0_index = RenderList::MAX_REFLECTION_PROBES; //refprobe disabled by default + e->refprobe_1_index = RenderList::MAX_REFLECTION_PROBES; //refprobe disabled by default + + if (!p_depth_pass) { + e->depth_layer = e->instance->depth_layer; + e->priority = p_material->render_priority; + + if (has_alpha && p_material->shader->spatial.depth_draw_mode == RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { + //add element to opaque + RenderList::Element *eo = render_list.add_element(); + *eo = *e; + eo->use_accum_ptr = &eo->use_accum; + } + + int rpsize = e->instance->reflection_probe_instances.size(); + if (rpsize > 0) { + bool first = true; + rpsize = MIN(rpsize, 2); //more than 2 per object are not supported, this keeps it stable + + for (int i = 0; i < rpsize; i++) { + ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(e->instance->reflection_probe_instances[i]); + if (rpi->last_pass != render_pass) { + continue; + } + if (first) { + e->refprobe_0_index = rpi->index; + first = false; + } else { + e->refprobe_1_index = rpi->index; + break; + } + } + + /* if (e->refprobe_0_index > e->refprobe_1_index) { //if both are valid, swap them to keep order as best as possible + uint64_t tmp = e->refprobe_0_index; + e->refprobe_0_index = e->refprobe_1_index; + e->refprobe_1_index = tmp; + }*/ + } + + //add directional lights + + if (p_material->shader->spatial.unshaded) { + e->light_mode = LIGHTMODE_UNSHADED; + } else { + bool copy = false; + + for (int i = 0; i < render_directional_lights; i++) { + if (copy) { + RenderList::Element *e2 = has_alpha ? render_list.add_alpha_element() : render_list.add_element(); + if (!e2) { + break; + } + *e2 = *e; //this includes accum ptr :) + e = e2; + } + + //directional sort key + e->light_type1 = 0; + e->light_type2 = 1; + e->light_index = i; + + copy = true; + } + + //add omni / spots + + for (int i = 0; i < e->instance->light_instances.size(); i++) { + LightInstance *li = light_instance_owner.getornull(e->instance->light_instances[i]); + + if (!li || li->light_index >= render_light_instance_count || render_light_instances[li->light_index] != li) { + continue; // too many or light_index did not correspond to the light instances to be rendered + } + + if (copy) { + RenderList::Element *e2 = has_alpha ? render_list.add_alpha_element() : render_list.add_element(); + if (!e2) { + break; + } + *e2 = *e; //this includes accum ptr :) + e = e2; + } + + //directional sort key + e->light_type1 = 1; + e->light_type2 = li->light_ptr->type == VisualServer::LIGHT_OMNI ? 0 : 1; + e->light_index = li->light_index; + + copy = true; + } + + if (e->instance->lightmap.is_valid()) { + e->light_mode = LIGHTMODE_LIGHTMAP; + } else if (!e->instance->lightmap_capture_data.empty()) { + e->light_mode = LIGHTMODE_LIGHTMAP_CAPTURE; + } else { + e->light_mode = LIGHTMODE_NORMAL; + } + } + } + + // do not add anything here, as lights are duplicated elements.. + + if (p_material->shader->spatial.uses_time) { + VisualServerRaster::redraw_request(); + } +} + +void RasterizerSceneGLES2::_copy_texture_to_buffer(GLuint p_texture, GLuint p_buffer) { + //copy to front buffer + glBindFramebuffer(GL_FRAMEBUFFER, p_buffer); + + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glColorMask(1, 1, 1, 1); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, p_texture); + + glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); + + storage->shaders.copy.bind(); + + storage->bind_quad_array(); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +void RasterizerSceneGLES2::_fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_depth_pass, bool p_shadow_pass) { + render_pass++; + current_material_index = 0; + current_geometry_index = 0; + current_light_index = 0; + current_refprobe_index = 0; + current_shader_index = 0; + + for (int i = 0; i < p_cull_count; i++) { + InstanceBase *instance = p_cull_result[i]; + + switch (instance->base_type) { + case GD_VS::INSTANCE_MESH: { + RasterizerStorageGLES2::Mesh *mesh = storage->mesh_owner.getornull(instance->base); + ERR_CONTINUE(!mesh); + + int num_surfaces = mesh->surfaces.size(); + + for (int j = 0; j < num_surfaces; j++) { + int material_index = instance->materials[j].is_valid() ? j : -1; + + RasterizerStorageGLES2::Surface *surface = mesh->surfaces[j]; + + _add_geometry(surface, instance, NULL, material_index, p_depth_pass, p_shadow_pass); + } + + } break; + + case GD_VS::INSTANCE_MULTIMESH: { + RasterizerStorageGLES2::MultiMesh *multi_mesh = storage->multimesh_owner.getptr(instance->base); + ERR_CONTINUE(!multi_mesh); + + if (multi_mesh->size == 0 || multi_mesh->visible_instances == 0) + continue; + + RasterizerStorageGLES2::Mesh *mesh = storage->mesh_owner.getptr(multi_mesh->mesh); + if (!mesh) + continue; + + int ssize = mesh->surfaces.size(); + + for (int j = 0; j < ssize; j++) { + RasterizerStorageGLES2::Surface *s = mesh->surfaces[j]; + _add_geometry(s, instance, multi_mesh, -1, p_depth_pass, p_shadow_pass); + } + } break; + + case GD_VS::INSTANCE_IMMEDIATE: { + RasterizerStorageGLES2::Immediate *im = storage->immediate_owner.getptr(instance->base); + ERR_CONTINUE(!im); + + _add_geometry(im, instance, NULL, -1, p_depth_pass, p_shadow_pass); + + } break; + + default: { + } + } + } +} + +static const GLenum gl_primitive[] = { + GL_POINTS, + GL_LINES, + GL_LINE_STRIP, + GL_LINE_LOOP, + GL_TRIANGLES, + GL_TRIANGLE_STRIP, + GL_TRIANGLE_FAN +}; + +void RasterizerSceneGLES2::_set_cull(bool p_front, bool p_disabled, bool p_reverse_cull) { + bool front = p_front; + if (p_reverse_cull) + front = !front; + + if (p_disabled != state.cull_disabled) { + if (p_disabled) + glDisable(GL_CULL_FACE); + else + glEnable(GL_CULL_FACE); + + state.cull_disabled = p_disabled; + } + + if (front != state.cull_front) { + glCullFace(front ? GL_FRONT : GL_BACK); + state.cull_front = front; + } +} + +bool RasterizerSceneGLES2::_setup_material(RasterizerStorageGLES2::Material *p_material, bool p_alpha_pass, Size2i p_skeleton_tex_size) { + // material parameters + + state.scene_shader.set_custom_shader(p_material->shader->custom_code_id); + + if (p_material->shader->spatial.uses_screen_texture && storage->frame.current_rt) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->copy_screen_effect.color); + } + + if (p_material->shader->spatial.uses_depth_texture && storage->frame.current_rt) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); + } + + bool shader_rebind = state.scene_shader.bind(); + + if (p_material->shader->spatial.no_depth_test || p_material->shader->spatial.uses_depth_texture) { + glDisable(GL_DEPTH_TEST); + } else { + glEnable(GL_DEPTH_TEST); + } + + switch (p_material->shader->spatial.depth_draw_mode) { + case RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS: + case RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_OPAQUE: { + glDepthMask(!p_alpha_pass && !p_material->shader->spatial.uses_depth_texture); + } break; + case RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALWAYS: { + glDepthMask(GL_TRUE && !p_material->shader->spatial.uses_depth_texture); + } break; + case RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_NEVER: { + glDepthMask(GL_FALSE); + } break; + } + + int tc = p_material->textures.size(); + const Pair *textures = p_material->textures.ptr(); + + const ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = p_material->shader->texture_hints.ptr(); + + state.scene_shader.set_uniform(SceneShaderGLES2::SKELETON_TEXTURE_SIZE, p_skeleton_tex_size); + + state.current_main_tex = 0; + + for (int i = 0; i < tc; i++) { + glActiveTexture(GL_TEXTURE0 + i); + + RasterizerStorageGLES2::Texture *t = storage->texture_owner.getornull(textures[i].second); + + if (!t) { + switch (texture_hints[i]) { + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: + case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { + glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { + glBindTexture(GL_TEXTURE_2D, storage->resources.aniso_tex); + } break; + case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { + glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); + } break; + default: { + glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); + } break; + } + + continue; + } + + if (t->redraw_if_visible) { //must check before proxy because this is often used with proxies + VisualServerRaster::redraw_request(); + } + + t = t->get_ptr(); + +#ifdef TOOLS_ENABLED + if (t->detect_3d) { + t->detect_3d(t->detect_3d_ud); + } +#endif + +#ifdef TOOLS_ENABLED + if (t->detect_normal && texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL) { + t->detect_normal(t->detect_normal_ud); + } +#endif + if (t->render_target) + t->render_target->used_in_frame = true; + + glBindTexture(t->target, t->tex_id); + if (i == 0) { + state.current_main_tex = t->tex_id; + } + } + state.scene_shader.use_material((void *)p_material); + + return shader_rebind; +} + +void RasterizerSceneGLES2::_setup_geometry(RenderList::Element *p_element, RasterizerStorageGLES2::Skeleton *p_skeleton) { + switch (p_element->instance->base_type) { + case GD_VS::INSTANCE_MESH: { + RasterizerStorageGLES2::Surface *s = static_cast(p_element->geometry); + + glBindBuffer(GL_ARRAY_BUFFER, s->vertex_id); + + if (s->index_array_len > 0) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id); + } + + for (int i = 0; i < GD_VS::ARRAY_MAX - 1; i++) { + if (s->attribs[i].enabled) { + glEnableVertexAttribArray(i); + glVertexAttribPointer(s->attribs[i].index, s->attribs[i].size, s->attribs[i].type, s->attribs[i].normalized, s->attribs[i].stride, CAST_INT_TO_UCHAR_PTR(s->attribs[i].offset)); + } else { + glDisableVertexAttribArray(i); + switch (i) { + case GD_VS::ARRAY_NORMAL: { + glVertexAttrib4f(GD_VS::ARRAY_NORMAL, 0.0, 0.0, 1, 1); + } break; + case GD_VS::ARRAY_COLOR: { + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + + } break; + default: { + } + } + } + } + + bool clear_skeleton_buffer = storage->config.use_skeleton_software; + + if (p_skeleton) { + if (!storage->config.use_skeleton_software) { + //use float texture workflow + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1); + glBindTexture(GL_TEXTURE_2D, p_skeleton->tex_id); + } else { + //use transform buffer workflow + ERR_FAIL_COND(p_skeleton->use_2d); + + PoolVector &transform_buffer = storage->resources.skeleton_transform_cpu_buffer; + + if (!s->attribs[VS::ARRAY_BONES].enabled || !s->attribs[VS::ARRAY_WEIGHTS].enabled) { + break; // the whole instance has a skeleton, but this surface is not affected by it. + } + + // 3 * vec4 per vertex + if (transform_buffer.size() < s->array_len * 12) { + transform_buffer.resize(s->array_len * 12); + } + + const size_t bones_offset = s->attribs[VS::ARRAY_BONES].offset; + const size_t bones_stride = s->attribs[VS::ARRAY_BONES].stride; + const size_t bone_weight_offset = s->attribs[VS::ARRAY_WEIGHTS].offset; + const size_t bone_weight_stride = s->attribs[VS::ARRAY_WEIGHTS].stride; + + { + PoolVector::Write write = transform_buffer.write(); + float *buffer = write.ptr(); + + PoolVector::Read vertex_array_read = s->data.read(); + const uint8_t *vertex_data = vertex_array_read.ptr(); + + for (int i = 0; i < s->array_len; i++) { + // do magic + + size_t bones[4]; + float bone_weight[4]; + + if (s->attribs[VS::ARRAY_BONES].type == GL_UNSIGNED_BYTE) { + // read as byte + const uint8_t *bones_ptr = vertex_data + bones_offset + (i * bones_stride); + bones[0] = bones_ptr[0]; + bones[1] = bones_ptr[1]; + bones[2] = bones_ptr[2]; + bones[3] = bones_ptr[3]; + } else { + // read as short + const uint16_t *bones_ptr = (const uint16_t *)(vertex_data + bones_offset + (i * bones_stride)); + bones[0] = bones_ptr[0]; + bones[1] = bones_ptr[1]; + bones[2] = bones_ptr[2]; + bones[3] = bones_ptr[3]; + } + + if (s->attribs[VS::ARRAY_WEIGHTS].type == GL_FLOAT) { + // read as float + const float *weight_ptr = (const float *)(vertex_data + bone_weight_offset + (i * bone_weight_stride)); + bone_weight[0] = weight_ptr[0]; + bone_weight[1] = weight_ptr[1]; + bone_weight[2] = weight_ptr[2]; + bone_weight[3] = weight_ptr[3]; + } else { + // read as half + const uint16_t *weight_ptr = (const uint16_t *)(vertex_data + bone_weight_offset + (i * bone_weight_stride)); + bone_weight[0] = (weight_ptr[0] / (float)0xFFFF); + bone_weight[1] = (weight_ptr[1] / (float)0xFFFF); + bone_weight[2] = (weight_ptr[2] / (float)0xFFFF); + bone_weight[3] = (weight_ptr[3] / (float)0xFFFF); + } + + Transform3D transform; + + Transform3D bone_transforms[4] = { + storage->skeleton_bone_get_transform(p_element->instance->skeleton, bones[0]), + storage->skeleton_bone_get_transform(p_element->instance->skeleton, bones[1]), + storage->skeleton_bone_get_transform(p_element->instance->skeleton, bones[2]), + storage->skeleton_bone_get_transform(p_element->instance->skeleton, bones[3]), + }; + + transform.origin = + bone_weight[0] * bone_transforms[0].origin + + bone_weight[1] * bone_transforms[1].origin + + bone_weight[2] * bone_transforms[2].origin + + bone_weight[3] * bone_transforms[3].origin; + + transform.basis = + bone_transforms[0].basis * bone_weight[0] + + bone_transforms[1].basis * bone_weight[1] + + bone_transforms[2].basis * bone_weight[2] + + bone_transforms[3].basis * bone_weight[3]; + + float row[3][4] = { + { transform.basis[0][0], transform.basis[0][1], transform.basis[0][2], transform.origin[0] }, + { transform.basis[1][0], transform.basis[1][1], transform.basis[1][2], transform.origin[1] }, + { transform.basis[2][0], transform.basis[2][1], transform.basis[2][2], transform.origin[2] }, + }; + + size_t transform_buffer_offset = i * 12; + + copymem(&buffer[transform_buffer_offset], row, sizeof(row)); + } + } + + storage->_update_skeleton_transform_buffer(transform_buffer, s->array_len * 12); + + //enable transform buffer and bind it + glBindBuffer(GL_ARRAY_BUFFER, storage->resources.skeleton_transform_buffer); + + glEnableVertexAttribArray(INSTANCE_BONE_BASE + 0); + glEnableVertexAttribArray(INSTANCE_BONE_BASE + 1); + glEnableVertexAttribArray(INSTANCE_BONE_BASE + 2); + + glVertexAttribPointer(INSTANCE_BONE_BASE + 0, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 12, (const void *)(sizeof(float) * 4 * 0)); + glVertexAttribPointer(INSTANCE_BONE_BASE + 1, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 12, (const void *)(sizeof(float) * 4 * 1)); + glVertexAttribPointer(INSTANCE_BONE_BASE + 2, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 12, (const void *)(sizeof(float) * 4 * 2)); + + clear_skeleton_buffer = false; + } + } + + if (clear_skeleton_buffer) { + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 0); + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 1); + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 2); + } + + } break; + + case GD_VS::INSTANCE_MULTIMESH: { + RasterizerStorageGLES2::Surface *s = static_cast(p_element->geometry); + + glBindBuffer(GL_ARRAY_BUFFER, s->vertex_id); + + if (s->index_array_len > 0) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id); + } + + for (int i = 0; i < GD_VS::ARRAY_MAX - 1; i++) { + if (s->attribs[i].enabled) { + glEnableVertexAttribArray(i); + glVertexAttribPointer(s->attribs[i].index, s->attribs[i].size, s->attribs[i].type, s->attribs[i].normalized, s->attribs[i].stride, CAST_INT_TO_UCHAR_PTR(s->attribs[i].offset)); + } else { + glDisableVertexAttribArray(i); + switch (i) { + case GD_VS::ARRAY_NORMAL: { + glVertexAttrib4f(GD_VS::ARRAY_NORMAL, 0.0, 0.0, 1, 1); + } break; + case GD_VS::ARRAY_COLOR: { + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + + } break; + default: { + } + } + } + } + + // prepare multimesh (disable) + glDisableVertexAttribArray(INSTANCE_ATTRIB_BASE + 0); + glDisableVertexAttribArray(INSTANCE_ATTRIB_BASE + 1); + glDisableVertexAttribArray(INSTANCE_ATTRIB_BASE + 2); + glDisableVertexAttribArray(INSTANCE_ATTRIB_BASE + 3); + glDisableVertexAttribArray(INSTANCE_ATTRIB_BASE + 4); + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 0); + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 1); + glDisableVertexAttribArray(INSTANCE_BONE_BASE + 2); + + } break; + + case GD_VS::INSTANCE_IMMEDIATE: { + } break; + + default: { + } + } +} + +void RasterizerSceneGLES2::_render_geometry(RenderList::Element *p_element) { + switch (p_element->instance->base_type) { + case GD_VS::INSTANCE_MESH: { + RasterizerStorageGLES2::Surface *s = static_cast(p_element->geometry); + + // drawing + + if (s->index_array_len > 0) { + glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0); + storage->info.render.vertices_count += s->index_array_len; + } else { + glDrawArrays(gl_primitive[s->primitive], 0, s->array_len); + storage->info.render.vertices_count += s->array_len; + } + /* + if (p_element->instance->skeleton.is_valid() && s->attribs[VS::ARRAY_BONES].enabled && s->attribs[VS::ARRAY_WEIGHTS].enabled) { + //clean up after skeleton + glBindBuffer(GL_ARRAY_BUFFER, storage->resources.skeleton_transform_buffer); + + glDisableVertexAttribArray(GD_VS::ARRAY_MAX + 0); + glDisableVertexAttribArray(GD_VS::ARRAY_MAX + 1); + glDisableVertexAttribArray(GD_VS::ARRAY_MAX + 2); + + glVertexAttrib4f(GD_VS::ARRAY_MAX + 0, 1, 0, 0, 0); + glVertexAttrib4f(GD_VS::ARRAY_MAX + 1, 0, 1, 0, 0); + glVertexAttrib4f(GD_VS::ARRAY_MAX + 2, 0, 0, 1, 0); + } +*/ + } break; + + case GD_VS::INSTANCE_MULTIMESH: { + RasterizerStorageGLES2::MultiMesh *multi_mesh = static_cast(p_element->owner); + RasterizerStorageGLES2::Surface *s = static_cast(p_element->geometry); + + int amount = MIN(multi_mesh->size, multi_mesh->visible_instances); + + if (amount == -1) { + amount = multi_mesh->size; + } + + int stride = multi_mesh->color_floats + multi_mesh->custom_data_floats + multi_mesh->xform_floats; + + int color_ofs = multi_mesh->xform_floats; + int custom_data_ofs = color_ofs + multi_mesh->color_floats; + + // drawing + + const float *base_buffer = multi_mesh->data.ptr(); + + for (int i = 0; i < amount; i++) { + const float *buffer = base_buffer + i * stride; + + { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 0, &buffer[0]); + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 1, &buffer[4]); + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 2, &buffer[8]); + } + + if (multi_mesh->color_floats) { + if (multi_mesh->color_format == GD_VS::MULTIMESH_COLOR_8BIT) { + uint8_t *color_data = (uint8_t *)(buffer + color_ofs); + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 3, color_data[0] / 255.0, color_data[1] / 255.0, color_data[2] / 255.0, color_data[3] / 255.0); + } else { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 3, buffer + color_ofs); + } + } else { + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 3, 1.0, 1.0, 1.0, 1.0); + } + + if (multi_mesh->custom_data_floats) { + if (multi_mesh->custom_data_format == GD_VS::MULTIMESH_CUSTOM_DATA_8BIT) { + uint8_t *custom_data = (uint8_t *)(buffer + custom_data_ofs); + glVertexAttrib4f(INSTANCE_ATTRIB_BASE + 4, custom_data[0] / 255.0, custom_data[1] / 255.0, custom_data[2] / 255.0, custom_data[3] / 255.0); + } else { + glVertexAttrib4fv(INSTANCE_ATTRIB_BASE + 4, buffer + custom_data_ofs); + } + } + + if (s->index_array_len > 0) { + glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0); + storage->info.render.vertices_count += s->index_array_len; + } else { + glDrawArrays(gl_primitive[s->primitive], 0, s->array_len); + storage->info.render.vertices_count += s->array_len; + } + } + + } break; + + case GD_VS::INSTANCE_IMMEDIATE: { + const RasterizerStorageGLES2::Immediate *im = static_cast(p_element->geometry); + + if (im->building) { + return; + } + + bool restore_tex = false; + + glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); + + for (const List::Element *E = im->chunks.front(); E; E = E->next()) { + const RasterizerStorageGLES2::Immediate::Chunk &c = E->get(); + + if (c.vertices.empty()) { + continue; + } + + int vertices = c.vertices.size(); + + uint32_t buf_ofs = 0; + + storage->info.render.vertices_count += vertices; + + if (c.texture.is_valid() && storage->texture_owner.owns(c.texture)) { + RasterizerStorageGLES2::Texture *t = storage->texture_owner.get(c.texture); + + if (t->redraw_if_visible) { + VisualServerRaster::redraw_request(); + } + t = t->get_ptr(); + +#ifdef TOOLS_ENABLED + if (t->detect_3d) { + t->detect_3d(t->detect_3d_ud); + } +#endif + if (t->render_target) { + t->render_target->used_in_frame = true; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(t->target, t->tex_id); + restore_tex = true; + } else if (restore_tex) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, state.current_main_tex); + restore_tex = false; + } + + if (!c.normals.empty()) { + glEnableVertexAttribArray(GD_VS::ARRAY_NORMAL); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.normals.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + buf_ofs += sizeof(Vector3) * vertices; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_NORMAL); + } + + if (!c.tangents.empty()) { + glEnableVertexAttribArray(GD_VS::ARRAY_TANGENT); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Plane) * vertices, c.tangents.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_TANGENT, 4, GL_FLOAT, GL_FALSE, sizeof(Plane), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + buf_ofs += sizeof(Plane) * vertices; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TANGENT); + } + + if (!c.colors.empty()) { + glEnableVertexAttribArray(GD_VS::ARRAY_COLOR); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Color) * vertices, c.colors.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + buf_ofs += sizeof(Color) * vertices; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_COLOR); + } + + if (!c.uvs.empty()) { + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uvs.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + buf_ofs += sizeof(Vector2) * vertices; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + } + + if (!c.uv2s.empty()) { + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV2); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector2) * vertices, c.uv2s.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV2, 2, GL_FLOAT, GL_FALSE, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + buf_ofs += sizeof(Vector2) * vertices; + } else { + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV2); + } + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glBufferSubData(GL_ARRAY_BUFFER, buf_ofs, sizeof(Vector3) * vertices, c.vertices.ptr()); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), CAST_INT_TO_UCHAR_PTR(buf_ofs)); + + glDrawArrays(gl_primitive[c.primitive], 0, c.vertices.size()); + } + + if (restore_tex) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, state.current_main_tex); + restore_tex = false; + } + + } break; + default: { + } + } +} + +void RasterizerSceneGLES2::_setup_light_type(LightInstance *p_light, ShadowAtlas *shadow_atlas) { + //turn off all by default + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTING, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SHADOW, false); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_5, false); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_13, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_DIRECTIONAL, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_OMNI, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_SPOT, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM2, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM4, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM_BLEND, false); + + if (!p_light) { //no light, return off + return; + } + + //turn on lighting + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTING, true); + + switch (p_light->light_ptr->type) { + case GD_VS::LIGHT_DIRECTIONAL: { + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_DIRECTIONAL, true); + switch (p_light->light_ptr->directional_shadow_mode) { + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: { + //no need + } break; + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: { + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM2, true); + + } break; + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: { + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM4, true); + } break; + } + + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM_BLEND, p_light->light_ptr->directional_blend_splits); + if (!state.render_no_shadows && p_light->light_ptr->shadow) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SHADOW, true); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); + if (storage->config.use_rgba_3d_shadows) { + glBindTexture(GL_TEXTURE_2D, directional_shadow.color); + } else { + glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); + } + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13); + } + + } break; + case GD_VS::LIGHT_OMNI: { + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_OMNI, true); + if (!state.render_no_shadows && shadow_atlas && p_light->light_ptr->shadow) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SHADOW, true); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); + if (storage->config.use_rgba_3d_shadows) { + glBindTexture(GL_TEXTURE_2D, shadow_atlas->color); + } else { + glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); + } + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13); + } + } break; + case GD_VS::LIGHT_SPOT: { + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_MODE_SPOT, true); + if (!state.render_no_shadows && shadow_atlas && p_light->light_ptr->shadow) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SHADOW, true); + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); + if (storage->config.use_rgba_3d_shadows) { + glBindTexture(GL_TEXTURE_2D, shadow_atlas->color); + } else { + glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); + } + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13); + } + } break; + } +} + +void RasterizerSceneGLES2::_setup_light(LightInstance *light, ShadowAtlas *shadow_atlas, const Transform3D &p_view_transform, bool accum_pass) { + RasterizerStorageGLES2::Light *light_ptr = light->light_ptr; + + //common parameters + float energy = light_ptr->param[VS::LIGHT_PARAM_ENERGY]; + float specular = light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; + float sign = (light_ptr->negative && !accum_pass) ? -1 : 1; //inverse color for base pass lights only + + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SPECULAR, specular); + Color color = light_ptr->color * sign * energy * Math_PI; + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_COLOR, color); + + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_COLOR, light_ptr->shadow_color); + + //specific parameters + + switch (light_ptr->type) { + case GD_VS::LIGHT_DIRECTIONAL: { + //not using inverse for performance, view should be normalized anyway + Vector3 direction = p_view_transform.basis.xform_inv(light->transform.basis.xform(Vector3(0, 0, -1))).normalized(); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_DIRECTION, direction); + + CameraMatrix matrices[4]; + + if (!state.render_no_shadows && light_ptr->shadow && directional_shadow.depth) { + int shadow_count = 0; + Color split_offsets; + + switch (light_ptr->directional_shadow_mode) { + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: { + shadow_count = 1; + } break; + + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: { + shadow_count = 2; + } break; + + case GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: { + shadow_count = 4; + } break; + } + + for (int k = 0; k < shadow_count; k++) { + uint32_t x = light->directional_rect.position.x; + uint32_t y = light->directional_rect.position.y; + uint32_t width = light->directional_rect.size.x; + uint32_t height = light->directional_rect.size.y; + + if (light_ptr->directional_shadow_mode == GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { + width /= 2; + height /= 2; + + if (k == 1) { + x += width; + } else if (k == 2) { + y += height; + } else if (k == 3) { + x += width; + y += height; + } + + } else if (light_ptr->directional_shadow_mode == GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { + height /= 2; + + if (k != 0) { + y += height; + } + } + + split_offsets[k] = light->shadow_transform[k].split; + + Transform3D modelview = (p_view_transform.inverse() * light->shadow_transform[k].transform).affine_inverse(); + + CameraMatrix bias; + bias.set_light_bias(); + CameraMatrix rectm; + Rect2 atlas_rect = Rect2(float(x) / directional_shadow.size, float(y) / directional_shadow.size, float(width) / directional_shadow.size, float(height) / directional_shadow.size); + rectm.set_light_atlas_rect(atlas_rect); + + CameraMatrix shadow_mtx = rectm * bias * light->shadow_transform[k].camera * modelview; + matrices[k] = shadow_mtx; + + /*Color light_clamp; + light_clamp[0] = atlas_rect.position.x; + light_clamp[1] = atlas_rect.position.y; + light_clamp[2] = atlas_rect.size.x; + light_clamp[3] = atlas_rect.size.y;*/ + } + + // state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_CLAMP, light_clamp); + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_PIXEL_SIZE, Size2(1.0 / directional_shadow.size, 1.0 / directional_shadow.size)); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SPLIT_OFFSETS, split_offsets); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX, matrices[0]); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX2, matrices[1]); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX3, matrices[2]); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX4, matrices[3]); + } + } break; + case GD_VS::LIGHT_OMNI: { + Vector3 position = p_view_transform.xform_inv(light->transform.origin); + + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_POSITION, position); + + float range = light_ptr->param[VS::LIGHT_PARAM_RANGE]; + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_RANGE, range); + + float attenuation = light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_ATTENUATION, attenuation); + + if (!state.render_no_shadows && light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(light->self)) { + uint32_t key = shadow_atlas->shadow_owners[light->self]; + + uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x03; + uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; + + ERR_BREAK(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size()); + + uint32_t atlas_size = shadow_atlas->size; + uint32_t quadrant_size = atlas_size >> 1; + + uint32_t x = (quadrant & 1) * quadrant_size; + uint32_t y = (quadrant >> 1) * quadrant_size; + + uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); + x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + + uint32_t width = shadow_size; + uint32_t height = shadow_size; + + if (light->light_ptr->omni_shadow_detail == GD_VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { + height /= 2; + } else { + width /= 2; + } + + Transform3D proj = (p_view_transform.inverse() * light->transform).inverse(); + + Color light_clamp; + light_clamp[0] = float(x) / atlas_size; + light_clamp[1] = float(y) / atlas_size; + light_clamp[2] = float(width) / atlas_size; + light_clamp[3] = float(height) / atlas_size; + + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_PIXEL_SIZE, Size2(1.0 / shadow_atlas->size, 1.0 / shadow_atlas->size)); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX, proj); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_CLAMP, light_clamp); + } + } break; + + case GD_VS::LIGHT_SPOT: { + Vector3 position = p_view_transform.xform_inv(light->transform.origin); + + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_POSITION, position); + + Vector3 direction = p_view_transform.inverse().basis.xform(light->transform.basis.xform(Vector3(0, 0, -1))).normalized(); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_DIRECTION, direction); + float attenuation = light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; + float range = light_ptr->param[VS::LIGHT_PARAM_RANGE]; + float spot_attenuation = light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION]; + float angle = light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE]; + angle = Math::cos(Math::deg2rad(angle)); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_ATTENUATION, attenuation); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SPOT_ATTENUATION, spot_attenuation); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SPOT_RANGE, spot_attenuation); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SPOT_ANGLE, angle); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_RANGE, range); + + if (!state.render_no_shadows && light->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(light->self)) { + uint32_t key = shadow_atlas->shadow_owners[light->self]; + + uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x03; + uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; + + ERR_BREAK(shadow >= (uint32_t)shadow_atlas->quadrants[quadrant].shadows.size()); + + uint32_t atlas_size = shadow_atlas->size; + uint32_t quadrant_size = atlas_size >> 1; + + uint32_t x = (quadrant & 1) * quadrant_size; + uint32_t y = (quadrant >> 1) * quadrant_size; + + uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); + x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + + uint32_t width = shadow_size; + uint32_t height = shadow_size; + + Rect2 rect(float(x) / atlas_size, float(y) / atlas_size, float(width) / atlas_size, float(height) / atlas_size); + + Color light_clamp; + light_clamp[0] = rect.position.x; + light_clamp[1] = rect.position.y; + light_clamp[2] = rect.size.x; + light_clamp[3] = rect.size.y; + + Transform3D modelview = (p_view_transform.inverse() * light->transform).inverse(); + + CameraMatrix bias; + bias.set_light_bias(); + + CameraMatrix rectm; + rectm.set_light_atlas_rect(rect); + + CameraMatrix shadow_matrix = rectm * bias * light->shadow_transform[0].camera * modelview; + + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_PIXEL_SIZE, Size2(1.0 / shadow_atlas->size, 1.0 / shadow_atlas->size)); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_SHADOW_MATRIX, shadow_matrix); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_CLAMP, light_clamp); + } + + } break; + default: { + } + } +} + +void RasterizerSceneGLES2::_setup_refprobes(ReflectionProbeInstance *p_refprobe1, ReflectionProbeInstance *p_refprobe2, const Transform3D &p_view_transform, Environment *p_env) { + if (p_refprobe1) { + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_USE_BOX_PROJECT, p_refprobe1->probe_ptr->box_projection); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_BOX_EXTENTS, p_refprobe1->probe_ptr->extents); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_BOX_OFFSET, p_refprobe1->probe_ptr->origin_offset); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_EXTERIOR, !p_refprobe1->probe_ptr->interior); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_INTENSITY, p_refprobe1->probe_ptr->intensity); + + Color ambient; + if (p_refprobe1->probe_ptr->interior) { + ambient = p_refprobe1->probe_ptr->interior_ambient * p_refprobe1->probe_ptr->interior_ambient_energy; + ambient.a = p_refprobe1->probe_ptr->interior_ambient_probe_contrib; + } else if (p_env) { + ambient = p_env->ambient_color * p_env->ambient_energy; + ambient.a = p_env->ambient_sky_contribution; + } + + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_AMBIENT, ambient); + + Transform3D proj = (p_view_transform.inverse() * p_refprobe1->transform).affine_inverse(); + + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE1_LOCAL_MATRIX, proj); + } + + if (p_refprobe2) { + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_USE_BOX_PROJECT, p_refprobe2->probe_ptr->box_projection); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_BOX_EXTENTS, p_refprobe2->probe_ptr->extents); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_BOX_OFFSET, p_refprobe2->probe_ptr->origin_offset); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_EXTERIOR, p_refprobe2->probe_ptr->interior); + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_INTENSITY, p_refprobe2->probe_ptr->intensity); + + Color ambient; + if (p_refprobe2->probe_ptr->interior) { + ambient = p_refprobe2->probe_ptr->interior_ambient * p_refprobe2->probe_ptr->interior_ambient_energy; + ambient.a = p_refprobe2->probe_ptr->interior_ambient_probe_contrib; + } else if (p_env) { + ambient = p_env->ambient_color * p_env->ambient_energy; + ambient.a = p_env->ambient_sky_contribution; + } + + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_AMBIENT, ambient); + + Transform3D proj = (p_view_transform.inverse() * p_refprobe2->transform).affine_inverse(); + + state.scene_shader.set_uniform(SceneShaderGLES2::REFPROBE2_LOCAL_MATRIX, proj); + } +} + +void RasterizerSceneGLES2::_render_render_list(RenderList::Element **p_elements, int p_element_count, const Transform3D &p_view_transform, const CameraMatrix &p_projection, RID p_shadow_atlas, Environment *p_env, GLuint p_base_env, float p_shadow_bias, float p_shadow_normal_bias, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); + + Vector2 viewport_size = state.viewport_size; + + Vector2 screen_pixel_size = state.screen_pixel_size; + + bool use_radiance_map = false; + if (!p_shadow && p_base_env) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2); + glBindTexture(GL_TEXTURE_CUBE_MAP, p_base_env); + use_radiance_map = true; + state.scene_shader.set_conditional(SceneShaderGLES2::USE_RADIANCE_MAP, true); //since prev unshaded is false, this needs to be true if exists + } + + bool prev_unshaded = false; + bool prev_instancing = false; + bool prev_depth_prepass = false; + state.scene_shader.set_conditional(SceneShaderGLES2::SHADELESS, false); + RasterizerStorageGLES2::Material *prev_material = NULL; + RasterizerStorageGLES2::Geometry *prev_geometry = NULL; + RasterizerStorageGLES2::Skeleton *prev_skeleton = NULL; + RasterizerStorageGLES2::GeometryOwner *prev_owner = NULL; + + Transform3D view_transform_inverse = p_view_transform.inverse(); + CameraMatrix projection_inverse = p_projection.inverse(); + + bool prev_base_pass = false; + LightInstance *prev_light = NULL; + bool prev_vertex_lit = false; + ReflectionProbeInstance *prev_refprobe_1 = NULL; + ReflectionProbeInstance *prev_refprobe_2 = NULL; + + int prev_blend_mode = -2; //will always catch the first go + + state.cull_front = false; + state.cull_disabled = false; + glCullFace(GL_BACK); + glEnable(GL_CULL_FACE); + + if (p_alpha_pass) { + glEnable(GL_BLEND); + } else { + glDisable(GL_BLEND); + } + + float fog_max_distance = 0; + bool using_fog = false; + if (p_env && !p_shadow && p_env->fog_enabled && (p_env->fog_depth_enabled || p_env->fog_height_enabled)) { + state.scene_shader.set_conditional(SceneShaderGLES2::FOG_DEPTH_ENABLED, p_env->fog_depth_enabled); + state.scene_shader.set_conditional(SceneShaderGLES2::FOG_HEIGHT_ENABLED, p_env->fog_height_enabled); + if (p_env->fog_depth_end > 0) { + fog_max_distance = p_env->fog_depth_end; + } else { + fog_max_distance = p_projection.get_z_far(); + } + using_fog = true; + } + + RasterizerStorageGLES2::Texture *prev_lightmap = NULL; + float lightmap_energy = 1.0; + bool prev_use_lightmap_capture = false; + + storage->info.render.draw_call_count += p_element_count; + + for (int i = 0; i < p_element_count; i++) { + RenderList::Element *e = p_elements[i]; + + RasterizerStorageGLES2::Material *material = e->material; + + bool rebind = false; + bool accum_pass = *e->use_accum_ptr; + *e->use_accum_ptr = true; //set to accum for next time this is found + LightInstance *light = NULL; + ReflectionProbeInstance *refprobe_1 = NULL; + ReflectionProbeInstance *refprobe_2 = NULL; + RasterizerStorageGLES2::Texture *lightmap = NULL; + bool use_lightmap_capture = false; + bool rebind_light = false; + bool rebind_reflection = false; + bool rebind_lightmap = false; + + if (!p_shadow && material->shader) { + bool unshaded = material->shader->spatial.unshaded; + + if (unshaded != prev_unshaded) { + rebind = true; + if (unshaded) { + state.scene_shader.set_conditional(SceneShaderGLES2::SHADELESS, true); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_RADIANCE_MAP, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTING, false); + } else { + state.scene_shader.set_conditional(SceneShaderGLES2::SHADELESS, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_RADIANCE_MAP, use_radiance_map); + } + + prev_unshaded = unshaded; + } + + bool base_pass = !accum_pass && !unshaded; //conditions for a base pass + + if (base_pass != prev_base_pass) { + state.scene_shader.set_conditional(SceneShaderGLES2::BASE_PASS, base_pass); + rebind = true; + prev_base_pass = base_pass; + } + + if (!unshaded && e->light_index < RenderList::MAX_LIGHTS) { + light = render_light_instances[e->light_index]; + if (e->light_mode == LightMode::LIGHTMODE_LIGHTMAP && light->light_ptr->bake_mode == GD_VS::LIGHT_BAKE_ALL) { + light = NULL; // Don't use this light, it is already included in the lightmap + } + } + + if (light != prev_light) { + _setup_light_type(light, shadow_atlas); + rebind = true; + rebind_light = true; + } + + int blend_mode = p_alpha_pass ? material->shader->spatial.blend_mode : -1; // -1 no blend, no mix + + if (accum_pass) { //accum pass force pass + blend_mode = RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_ADD; + if (light && light->light_ptr->negative) { + blend_mode = RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_SUB; + } + } + + if (prev_blend_mode != blend_mode) { + if (prev_blend_mode == -1 && blend_mode != -1) { + //does blend + glEnable(GL_BLEND); + } else if (blend_mode == -1 && prev_blend_mode != -1) { + //do not blend + glDisable(GL_BLEND); + } + + switch (blend_mode) { + //-1 not handled because not blend is enabled anyway + case RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_MIX: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + } break; + case RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_ADD: { + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(p_alpha_pass ? GL_SRC_ALPHA : GL_ONE, GL_ONE); + + } break; + case RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_SUB: { + glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + } break; + case RasterizerStorageGLES2::Shader::Spatial::BLEND_MODE_MUL: { + glBlendEquation(GL_FUNC_ADD); + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_DST_ALPHA, GL_ZERO); + } else { + glBlendFuncSeparate(GL_DST_COLOR, GL_ZERO, GL_ZERO, GL_ONE); + } + + } break; + } + + prev_blend_mode = blend_mode; + } + + //condition to enable vertex lighting on this object + bool vertex_lit = (material->shader->spatial.uses_vertex_lighting || storage->config.force_vertex_shading) && ((!unshaded && light) || using_fog); //fog forces vertex lighting because it still applies even if unshaded or no fog + + if (vertex_lit != prev_vertex_lit) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_VERTEX_LIGHTING, vertex_lit); + prev_vertex_lit = vertex_lit; + rebind = true; + } + + if (!unshaded && !accum_pass && e->refprobe_0_index != RenderList::MAX_REFLECTION_PROBES) { + ERR_FAIL_INDEX(e->refprobe_0_index, reflection_probe_count); + refprobe_1 = reflection_probe_instances[e->refprobe_0_index]; + } + if (!unshaded && !accum_pass && e->refprobe_1_index != RenderList::MAX_REFLECTION_PROBES) { + ERR_FAIL_INDEX(e->refprobe_1_index, reflection_probe_count); + refprobe_2 = reflection_probe_instances[e->refprobe_1_index]; + } + + if (refprobe_1 != prev_refprobe_1 || refprobe_2 != prev_refprobe_2) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_REFLECTION_PROBE1, refprobe_1 != NULL); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_REFLECTION_PROBE2, refprobe_2 != NULL); + if (refprobe_1 != NULL && refprobe_1 != prev_refprobe_1) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 5); + glBindTexture(GL_TEXTURE_CUBE_MAP, refprobe_1->cubemap); + } + if (refprobe_2 != NULL && refprobe_2 != prev_refprobe_2) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 6); + glBindTexture(GL_TEXTURE_CUBE_MAP, refprobe_2->cubemap); + } + rebind = true; + rebind_reflection = true; + } + + use_lightmap_capture = !unshaded && !accum_pass && !e->instance->lightmap_capture_data.empty(); + + if (use_lightmap_capture != prev_use_lightmap_capture) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTMAP_CAPTURE, use_lightmap_capture); + rebind = true; + } + + if (!unshaded && !accum_pass && e->instance->lightmap.is_valid()) { + lightmap = storage->texture_owner.getornull(e->instance->lightmap); + lightmap_energy = 1.0; + if (lightmap) { + RasterizerStorageGLES2::LightmapCapture *capture = storage->lightmap_capture_data_owner.getornull(e->instance->lightmap_capture->base); + if (capture) { + lightmap_energy = capture->energy; + } + } + } + + if (lightmap != prev_lightmap) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTMAP, lightmap != NULL); + if (lightmap != NULL) { + glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4); + glBindTexture(GL_TEXTURE_2D, lightmap->tex_id); + } + rebind = true; + rebind_lightmap = true; + } + } + + bool depth_prepass = false; + + if (!p_alpha_pass && material->shader->spatial.depth_draw_mode == RasterizerStorageGLES2::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { + depth_prepass = true; + } + + if (depth_prepass != prev_depth_prepass) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_DEPTH_PREPASS, depth_prepass); + prev_depth_prepass = depth_prepass; + rebind = true; + } + + bool instancing = e->instance->base_type == GD_VS::INSTANCE_MULTIMESH; + + if (instancing != prev_instancing) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_INSTANCING, instancing); + rebind = true; + } + + RasterizerStorageGLES2::Skeleton *skeleton = storage->skeleton_owner.getornull(e->instance->skeleton); + + if (skeleton != prev_skeleton) { + if ((prev_skeleton == NULL) != (skeleton == NULL)) { + if (skeleton) { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SKELETON, true); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SKELETON_SOFTWARE, storage->config.use_skeleton_software); + } else { + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SKELETON, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SKELETON_SOFTWARE, false); + } + } + rebind = true; + } + + if (e->owner != prev_owner || e->geometry != prev_geometry || skeleton != prev_skeleton) { + _setup_geometry(e, skeleton); + storage->info.render.surface_switch_count++; + } + + bool shader_rebind = false; + if (rebind || material != prev_material) { + storage->info.render.material_switch_count++; + shader_rebind = _setup_material(material, p_alpha_pass, Size2i(skeleton ? skeleton->size * 3 : 0, 0)); + if (shader_rebind) { + storage->info.render.shader_rebind_count++; + } + } + + _set_cull(e->front_facing, material->shader->spatial.cull_mode == RasterizerStorageGLES2::Shader::Spatial::CULL_MODE_DISABLED, p_reverse_cull); + + if (i == 0 || shader_rebind) { //first time must rebind + + if (p_shadow) { + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_BIAS, p_shadow_bias); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHT_NORMAL_BIAS, p_shadow_normal_bias); + if (state.shadow_is_dual_parabolloid) { + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_DUAL_PARABOLOID_RENDER_SIDE, state.dual_parbolloid_direction); + state.scene_shader.set_uniform(SceneShaderGLES2::SHADOW_DUAL_PARABOLOID_RENDER_ZFAR, state.dual_parbolloid_zfar); + } + } else { + if (use_radiance_map) { + if (p_env) { + Transform3D sky_orientation(p_env->sky_orientation, Vector3(0.0, 0.0, 0.0)); + state.scene_shader.set_uniform(SceneShaderGLES2::RADIANCE_INVERSE_XFORM, sky_orientation.affine_inverse() * p_view_transform); + } else { + // would be a bit weird if we don't have this... + state.scene_shader.set_uniform(SceneShaderGLES2::RADIANCE_INVERSE_XFORM, p_view_transform); + } + } + + if (p_env) { + state.scene_shader.set_uniform(SceneShaderGLES2::BG_ENERGY, p_env->bg_energy); + state.scene_shader.set_uniform(SceneShaderGLES2::BG_COLOR, p_env->bg_color); + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_SKY_CONTRIBUTION, p_env->ambient_sky_contribution); + + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_COLOR, p_env->ambient_color); + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_ENERGY, p_env->ambient_energy); + + } else { + state.scene_shader.set_uniform(SceneShaderGLES2::BG_ENERGY, 1.0); + state.scene_shader.set_uniform(SceneShaderGLES2::BG_COLOR, state.default_bg); + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_SKY_CONTRIBUTION, 1.0); + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_COLOR, state.default_ambient); + state.scene_shader.set_uniform(SceneShaderGLES2::AMBIENT_ENERGY, 1.0); + } + + //rebind all these + rebind_light = true; + rebind_reflection = true; + rebind_lightmap = true; + + if (using_fog) { + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_COLOR_BASE, p_env->fog_color); + Color sun_color_amount = p_env->fog_sun_color; + sun_color_amount.a = p_env->fog_sun_amount; + + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_SUN_COLOR_AMOUNT, sun_color_amount); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_TRANSMIT_ENABLED, p_env->fog_transmit_enabled); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_TRANSMIT_CURVE, p_env->fog_transmit_curve); + + if (p_env->fog_depth_enabled) { + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_DEPTH_BEGIN, p_env->fog_depth_begin); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_DEPTH_CURVE, p_env->fog_depth_curve); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_MAX_DISTANCE, fog_max_distance); + } + + if (p_env->fog_height_enabled) { + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_HEIGHT_MIN, p_env->fog_height_min); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_HEIGHT_MAX, p_env->fog_height_max); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_HEIGHT_MAX, p_env->fog_height_max); + state.scene_shader.set_uniform(SceneShaderGLES2::FOG_HEIGHT_CURVE, p_env->fog_height_curve); + } + } + } + + state.scene_shader.set_uniform(SceneShaderGLES2::CAMERA_MATRIX, p_view_transform); + state.scene_shader.set_uniform(SceneShaderGLES2::CAMERA_INVERSE_MATRIX, view_transform_inverse); + state.scene_shader.set_uniform(SceneShaderGLES2::PROJECTION_MATRIX, p_projection); + state.scene_shader.set_uniform(SceneShaderGLES2::PROJECTION_INVERSE_MATRIX, projection_inverse); + + state.scene_shader.set_uniform(SceneShaderGLES2::TIME, storage->frame.time[0]); + + state.scene_shader.set_uniform(SceneShaderGLES2::VIEWPORT_SIZE, viewport_size); + + state.scene_shader.set_uniform(SceneShaderGLES2::SCREEN_PIXEL_SIZE, screen_pixel_size); + } + + if (rebind_light && light) { + _setup_light(light, shadow_atlas, p_view_transform, accum_pass); + } + + if (rebind_reflection && (refprobe_1 || refprobe_2)) { + _setup_refprobes(refprobe_1, refprobe_2, p_view_transform, p_env); + } + + if (rebind_lightmap && lightmap) { + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHTMAP_ENERGY, lightmap_energy); + } + + state.scene_shader.set_uniform(SceneShaderGLES2::WORLD_TRANSFORM, e->instance->transform); + + if (use_lightmap_capture) { //this is per instance, must be set always if present + glUniform4fv(state.scene_shader.get_uniform_location(SceneShaderGLES2::LIGHTMAP_CAPTURES), 12, (const GLfloat *)e->instance->lightmap_capture_data.ptr()); + state.scene_shader.set_uniform(SceneShaderGLES2::LIGHTMAP_CAPTURE_SKY, false); + } + + _render_geometry(e); + + prev_geometry = e->geometry; + prev_owner = e->owner; + prev_material = material; + prev_skeleton = skeleton; + prev_instancing = instancing; + prev_light = light; + prev_refprobe_1 = refprobe_1; + prev_refprobe_2 = refprobe_2; + prev_lightmap = lightmap; + prev_use_lightmap_capture = use_lightmap_capture; + } + + _setup_light_type(NULL, NULL); //clear light stuff + state.scene_shader.set_conditional(SceneShaderGLES2::USE_SKELETON, false); + state.scene_shader.set_conditional(SceneShaderGLES2::SHADELESS, false); + state.scene_shader.set_conditional(SceneShaderGLES2::BASE_PASS, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_INSTANCING, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_RADIANCE_MAP, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM4, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM2, false); + state.scene_shader.set_conditional(SceneShaderGLES2::LIGHT_USE_PSSM_BLEND, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_VERTEX_LIGHTING, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_REFLECTION_PROBE1, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_REFLECTION_PROBE2, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTMAP, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_LIGHTMAP_CAPTURE, false); + state.scene_shader.set_conditional(SceneShaderGLES2::FOG_DEPTH_ENABLED, false); + state.scene_shader.set_conditional(SceneShaderGLES2::FOG_HEIGHT_ENABLED, false); + state.scene_shader.set_conditional(SceneShaderGLES2::USE_DEPTH_PREPASS, false); +} + +void RasterizerSceneGLES2::_draw_sky(RasterizerStorageGLES2::Sky *p_sky, const CameraMatrix &p_projection, const Transform3D &p_transform, bool p_vflip, float p_custom_fov, float p_energy, const Basis &p_sky_orientation) { + ERR_FAIL_COND(!p_sky); + + RasterizerStorageGLES2::Texture *tex = storage->texture_owner.getornull(p_sky->panorama); + ERR_FAIL_COND(!tex); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(tex->target, tex->tex_id); + + glDepthMask(GL_TRUE); + glEnable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + + // Camera + CameraMatrix camera; + + if (p_custom_fov) { + float near_plane = p_projection.get_z_near(); + float far_plane = p_projection.get_z_far(); + float aspect = p_projection.get_aspect(); + + camera.set_perspective(p_custom_fov, aspect, near_plane, far_plane); + } else { + camera = p_projection; + } + + float flip_sign = p_vflip ? -1 : 1; + + // If matrix[2][0] or matrix[2][1] we're dealing with an asymmetrical projection matrix. This is the case for stereoscopic rendering (i.e. VR). + // To ensure the image rendered is perspective correct we need to move some logic into the shader. For this the USE_ASYM_PANO option is introduced. + // It also means the uv coordinates are ignored in this mode and we don't need our loop. + bool asymmetrical = ((camera.matrix[2][0] != 0.0) || (camera.matrix[2][1] != 0.0)); + + Vector3 vertices[8] = { + Vector3(-1, -1 * flip_sign, 1), + Vector3(0, 1, 0), + Vector3(1, -1 * flip_sign, 1), + Vector3(1, 1, 0), + Vector3(1, 1 * flip_sign, 1), + Vector3(1, 0, 0), + Vector3(-1, 1 * flip_sign, 1), + Vector3(0, 0, 0), + }; + + if (!asymmetrical) { + Vector2 vp_he = camera.get_viewport_half_extents(); + float zn; + zn = p_projection.get_z_near(); + + for (int i = 0; i < 4; i++) { + Vector3 uv = vertices[i * 2 + 1]; + uv.x = (uv.x * 2.0 - 1.0) * vp_he.x; + uv.y = -(uv.y * 2.0 - 1.0) * vp_he.y; + uv.z = -zn; + vertices[i * 2 + 1] = p_transform.basis.xform(uv).normalized(); + vertices[i * 2 + 1].z = -vertices[i * 2 + 1].z; + } + } + + glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts); + glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, vertices, GL_DYNAMIC_DRAW); + + // bind sky vertex array.... + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, 0); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, CAST_INT_TO_UCHAR_PTR(sizeof(Vector3))); + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_ASYM_PANO, asymmetrical); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, !asymmetrical); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, true); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, false); + storage->shaders.copy.bind(); + storage->shaders.copy.set_uniform(CopyShaderGLES2::MULTIPLIER, p_energy); + + // don't know why but I always have problems setting a uniform mat3, so we're using a transform + storage->shaders.copy.set_uniform(CopyShaderGLES2::SKY_TRANSFORM, Transform3D(p_sky_orientation, Vector3(0.0, 0.0, 0.0)).affine_inverse()); + + if (asymmetrical) { + // pack the bits we need from our projection matrix + storage->shaders.copy.set_uniform(CopyShaderGLES2::ASYM_PROJ, camera.matrix[2][0], camera.matrix[0][0], camera.matrix[2][1], camera.matrix[1][1]); + ///@TODO I couldn't get mat3 + p_transform.basis to work, that would be better here. + storage->shaders.copy.set_uniform(CopyShaderGLES2::PANO_TRANSFORM, p_transform); + } + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + glDisableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_ASYM_PANO, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); +} + +void RasterizerSceneGLES2::_post_process(Environment *env, const CameraMatrix &p_cam_projection) { + //copy to front buffer + + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glColorMask(1, 1, 1, 1); + + //no post process on small, transparent or render targets without an env + bool use_post_process = env && !storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]; + use_post_process = use_post_process && storage->frame.current_rt->width >= 4 && storage->frame.current_rt->height >= 4; + use_post_process = use_post_process && storage->frame.current_rt->mip_maps_allocated; + + if (env) { + use_post_process = use_post_process && (env->adjustments_enabled || env->glow_enabled || env->dof_blur_far_enabled || env->dof_blur_near_enabled); + } + use_post_process = use_post_process || storage->frame.current_rt->use_fxaa; + + GLuint next_buffer; + + if (use_post_process) { + next_buffer = storage->frame.current_rt->mip_maps[0].sizes[0].fbo; + } else if (storage->frame.current_rt->external.fbo != 0) { + next_buffer = storage->frame.current_rt->external.fbo; + } else { + // set next_buffer to front buffer so multisample blit can happen if needed + next_buffer = storage->frame.current_rt->fbo; + } + + // If using multisample buffer, resolve to post_process_effect buffer or to front buffer + if (storage->frame.current_rt && storage->frame.current_rt->multisample_active) { +#ifdef GLES_OVER_GL + + glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->multisample_fbo); + glReadBuffer(GL_COLOR_ATTACHMENT0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, next_buffer); + glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +#elif IPHONE_ENABLED + + glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->multisample_fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, next_buffer); + glResolveMultisampleFramebufferAPPLE(); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +#elif ANDROID_ENABLED + + // In GLES2 Android Blit is not available, so just copy color texture manually + _copy_texture_to_buffer(storage->frame.current_rt->multisample_color, next_buffer); +#else + // TODO: any other platform not supported? this will fail.. maybe we should just call _copy_texture_to_buffer here as well? +#endif + } else if (use_post_process) { + if (storage->frame.current_rt->external.fbo != 0) { + _copy_texture_to_buffer(storage->frame.current_rt->external.color, storage->frame.current_rt->mip_maps[0].sizes[0].fbo); + } else { + _copy_texture_to_buffer(storage->frame.current_rt->color, storage->frame.current_rt->mip_maps[0].sizes[0].fbo); + } + } + + if (!use_post_process) { + return; + } + + // Order of operation + //1) DOF Blur (first blur, then copy to buffer applying the blur) //only on desktop + //2) FXAA + //3) Bloom (Glow) //only on desktop + //4) Adjustments + + // DOF Blur + + if (env && env->dof_blur_far_enabled) { + int vp_h = storage->frame.current_rt->height; + int vp_w = storage->frame.current_rt->width; + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_FAR_BLUR, true); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_LOW, env->dof_blur_far_quality == GD_VS::ENV_DOF_BLUR_QUALITY_LOW); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_MEDIUM, env->dof_blur_far_quality == GD_VS::ENV_DOF_BLUR_QUALITY_MEDIUM); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_HIGH, env->dof_blur_far_quality == GD_VS::ENV_DOF_BLUR_QUALITY_HIGH); + + state.effect_blur_shader.bind(); + int qsteps[3] = { 4, 10, 20 }; + + float radius = (env->dof_blur_far_amount * env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality]; + + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_BEGIN, env->dof_blur_far_distance); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_END, env->dof_blur_far_distance + env->dof_blur_far_transition); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_DIR, Vector2(1, 0)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_RADIUS, radius); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_FAR, p_cam_projection.get_z_far()); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); + + glActiveTexture(GL_TEXTURE0); + + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[0].color); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first + + storage->_copy_screen(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_DIR, Vector2(0, 1)); + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->mip_maps[0].sizes[0].fbo); // copy to base level + storage->_copy_screen(); + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_FAR_BLUR, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_LOW, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_MEDIUM, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_HIGH, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::USE_ORTHOGONAL_PROJECTION, false); + } + + if (env && env->dof_blur_near_enabled) { + //convert texture to RGBA format if not already + if (!storage->frame.current_rt->used_dof_blur_near) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + } + + int vp_h = storage->frame.current_rt->height; + int vp_w = storage->frame.current_rt->width; + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::USE_ORTHOGONAL_PROJECTION, p_cam_projection.is_orthogonal()); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_NEAR_BLUR, true); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_NEAR_FIRST_TAP, true); + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_LOW, env->dof_blur_near_quality == GD_VS::ENV_DOF_BLUR_QUALITY_LOW); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_MEDIUM, env->dof_blur_near_quality == GD_VS::ENV_DOF_BLUR_QUALITY_MEDIUM); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_HIGH, env->dof_blur_near_quality == GD_VS::ENV_DOF_BLUR_QUALITY_HIGH); + + state.effect_blur_shader.bind(); + int qsteps[3] = { 4, 10, 20 }; + + float radius = (env->dof_blur_near_amount * env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality]; + + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_BEGIN, env->dof_blur_near_distance); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_DIR, Vector2(1, 0)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_RADIUS, radius); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_FAR, p_cam_projection.get_z_far()); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth); + + glActiveTexture(GL_TEXTURE0); + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[0].color); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first + + storage->_copy_screen(); + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_NEAR_FIRST_TAP, false); + state.effect_blur_shader.bind(); + + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_BEGIN, env->dof_blur_near_distance); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_DIR, Vector2(0, 1)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::DOF_RADIUS, radius); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_NEAR, p_cam_projection.get_z_near()); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::CAMERA_Z_FAR, p_cam_projection.get_z_far()); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); + + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->mip_maps[0].sizes[0].fbo); // copy to base level + + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + storage->_copy_screen(); + + glDisable(GL_BLEND); + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_NEAR_BLUR, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_NEAR_FIRST_TAP, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_LOW, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_MEDIUM, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::DOF_QUALITY_HIGH, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::USE_ORTHOGONAL_PROJECTION, false); + storage->frame.current_rt->used_dof_blur_near = true; + } + + if (env && (env->dof_blur_near_enabled || env->dof_blur_far_enabled)) { + //these needed to disable filtering, reenamble + glActiveTexture(GL_TEXTURE0); + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[0].color); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + + //glow + + int max_glow_level = -1; + int glow_mask = 0; + + if (env && env->glow_enabled) { + for (int i = 0; i < GD_VS::MAX_GLOW_LEVELS; i++) { + if (env->glow_levels & (1 << i)) { + if (i >= storage->frame.current_rt->mip_maps[1].sizes.size()) { + max_glow_level = storage->frame.current_rt->mip_maps[1].sizes.size() - 1; + glow_mask |= 1 << max_glow_level; + + } else { + max_glow_level = i; + glow_mask |= (1 << i); + } + } + } + + // If max_texture_image_units is 8, our max glow level is 5, which allows 6 layers of glow + max_glow_level = MIN(max_glow_level, storage->config.max_texture_image_units - 3); + + for (int i = 0; i < (max_glow_level + 1); i++) { + int vp_w = storage->frame.current_rt->mip_maps[1].sizes[i].width; + int vp_h = storage->frame.current_rt->mip_maps[1].sizes[i].height; + glViewport(0, 0, vp_w, vp_h); + //horizontal pass + if (i == 0) { + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_FIRST_PASS, true); + } + + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_GAUSSIAN_HORIZONTAL, true); + state.effect_blur_shader.bind(); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::LOD, storage->frame.current_rt->mip_maps[0].color ? float(i) : 0.0); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::GLOW_STRENGTH, env->glow_strength); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::LUMINANCE_CAP, env->glow_hdr_luminance_cap); + + glActiveTexture(GL_TEXTURE0); + + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[i].color); + } + + if (i == 0) { + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::GLOW_BLOOM, env->glow_bloom); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::GLOW_HDR_THRESHOLD, env->glow_hdr_bleed_threshold); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::GLOW_HDR_SCALE, env->glow_hdr_bleed_scale); + } + + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->mip_maps[1].sizes[i].fbo); + storage->_copy_screen(); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_GAUSSIAN_HORIZONTAL, false); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_FIRST_PASS, false); + + //vertical pass + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_GAUSSIAN_VERTICAL, true); + state.effect_blur_shader.bind(); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::LOD, storage->frame.current_rt->mip_maps[0].color ? float(i) : 0.0); + state.effect_blur_shader.set_uniform(EffectBlurShaderGLES2::GLOW_STRENGTH, env->glow_strength); + glActiveTexture(GL_TEXTURE0); + + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[1].color); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[1].sizes[i].color); + } + + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger + storage->_copy_screen(); + state.effect_blur_shader.set_conditional(EffectBlurShaderGLES2::GLOW_GAUSSIAN_VERTICAL, false); + } + + glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); + } + + if (storage->frame.current_rt->external.fbo != 0) { + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->external.fbo); + } else { + glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); + } + + glActiveTexture(GL_TEXTURE0); + if (storage->frame.current_rt->mip_maps[0].color) { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + } else { + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[0].color); + } + + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_FXAA, storage->frame.current_rt->use_fxaa); + + if (env) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_FILTER_BICUBIC, env->glow_bicubic_upscale); + + if (max_glow_level >= 0) { + if (storage->frame.current_rt->mip_maps[0].color) { + for (int i = 0; i < (max_glow_level + 1); i++) { + if (glow_mask & (1 << i)) { + if (i == 0) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL1, true); + } + if (i == 1) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL2, true); + } + if (i == 2) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL3, true); + } + if (i == 3) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL4, true); + } + if (i == 4) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL5, true); + } + if (i == 5) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL6, true); + } + if (i == 6) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL7, true); + } + } + } + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].color); + } else { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_MULTI_TEXTURE_GLOW, true); + int active_glow_level = 0; + for (int i = 0; i < (max_glow_level + 1); i++) { + if (glow_mask & (1 << i)) { + active_glow_level++; + glActiveTexture(GL_TEXTURE1 + active_glow_level); + glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->mip_maps[0].sizes[i + 1].color); + if (active_glow_level == 1) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL1, true); + } + if (active_glow_level == 2) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL2, true); + } + if (active_glow_level == 3) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL3, true); + } + if (active_glow_level == 4) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL4, true); + } + if (active_glow_level == 5) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL5, true); + } + if (active_glow_level == 6) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL6, true); + } + if (active_glow_level == 7) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL7, true); + } + } + } + } + + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_SCREEN, env->glow_blend_mode == GD_VS::GLOW_BLEND_MODE_SCREEN); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_SOFTLIGHT, env->glow_blend_mode == GD_VS::GLOW_BLEND_MODE_SOFTLIGHT); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_REPLACE, env->glow_blend_mode == GD_VS::GLOW_BLEND_MODE_REPLACE); + } + } + + //Adjustments + if (env && env->adjustments_enabled) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_BCS, true); + RasterizerStorageGLES2::Texture *tex = storage->texture_owner.getornull(env->color_correction); + if (tex) { + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_COLOR_CORRECTION, true); + glActiveTexture(GL_TEXTURE1); + glBindTexture(tex->target, tex->tex_id); + } + } + + state.tonemap_shader.bind(); + if (env) { + if (max_glow_level >= 0) { + state.tonemap_shader.set_uniform(TonemapShaderGLES2::GLOW_INTENSITY, env->glow_intensity); + int ss[2] = { + storage->frame.current_rt->width, + storage->frame.current_rt->height, + }; + glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES2::GLOW_TEXTURE_SIZE), 1, ss); + } + + if (env->adjustments_enabled) { + state.tonemap_shader.set_uniform(TonemapShaderGLES2::BCS, Vector3(env->adjustments_brightness, env->adjustments_contrast, env->adjustments_saturation)); + } + } + + if (storage->frame.current_rt->use_fxaa) { + state.tonemap_shader.set_uniform(TonemapShaderGLES2::PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height)); + } + + storage->_copy_screen(); + + //turn off everything used + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_FXAA, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL1, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL2, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL3, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL4, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL5, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL6, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_LEVEL7, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_REPLACE, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_SCREEN, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_SOFTLIGHT, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_GLOW_FILTER_BICUBIC, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_MULTI_TEXTURE_GLOW, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_BCS, false); + state.tonemap_shader.set_conditional(TonemapShaderGLES2::USE_COLOR_CORRECTION, false); +} + +void RasterizerSceneGLES2::render_scene(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) { + Transform3D cam_transform = p_cam_transform; + + storage->info.render.object_count += p_cull_count; + + GLuint current_fb = 0; + Environment *env = NULL; + + int viewport_width, viewport_height; + int viewport_x = 0; + int viewport_y = 0; + bool probe_interior = false; + bool reverse_cull = false; + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) { + cam_transform.basis.set_axis(1, -cam_transform.basis.get_axis(1)); + reverse_cull = true; + } + + if (p_reflection_probe.is_valid()) { + ReflectionProbeInstance *probe = reflection_probe_instance_owner.getornull(p_reflection_probe); + ERR_FAIL_COND(!probe); + state.render_no_shadows = !probe->probe_ptr->enable_shadows; + + if (!probe->probe_ptr->interior) { //use env only if not interior + env = environment_owner.getornull(p_environment); + } + + current_fb = probe->fbo[p_reflection_probe_pass]; + + viewport_width = probe->probe_ptr->resolution; + viewport_height = probe->probe_ptr->resolution; + + probe_interior = probe->probe_ptr->interior; + + } else { + state.render_no_shadows = false; + if (storage->frame.current_rt->multisample_active) { + current_fb = storage->frame.current_rt->multisample_fbo; + } else if (storage->frame.current_rt->external.fbo != 0) { + current_fb = storage->frame.current_rt->external.fbo; + } else { + current_fb = storage->frame.current_rt->fbo; + } + env = environment_owner.getornull(p_environment); + + viewport_width = storage->frame.current_rt->width; + viewport_height = storage->frame.current_rt->height; + viewport_x = storage->frame.current_rt->x; + + if (storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + viewport_y = OS::get_singleton()->get_window_size().height - viewport_height - storage->frame.current_rt->y; + } else { + viewport_y = storage->frame.current_rt->y; + } + } + + state.used_screen_texture = false; + state.viewport_size.x = viewport_width; + state.viewport_size.y = viewport_height; + state.screen_pixel_size.x = 1.0 / viewport_width; + state.screen_pixel_size.y = 1.0 / viewport_height; + + //push back the directional lights + + if (p_light_cull_count) { + //hardcoded limit of 256 lights + render_light_instance_count = MIN(RenderList::MAX_LIGHTS, p_light_cull_count); + render_light_instances = (LightInstance **)alloca(sizeof(LightInstance *) * render_light_instance_count); + render_directional_lights = 0; + + //doing this because directional lights are at the end, put them at the beginning + int index = 0; + for (int i = render_light_instance_count - 1; i >= 0; i--) { + RID light_rid = p_light_cull_result[i]; + + LightInstance *light = light_instance_owner.getornull(light_rid); + + if (light->light_ptr->type == GD_VS::LIGHT_DIRECTIONAL) { + render_directional_lights++; + //as going in reverse, directional lights are always first anyway + } + + light->light_index = index; + render_light_instances[index] = light; + + index++; + } + + } else { + render_light_instances = NULL; + render_directional_lights = 0; + render_light_instance_count = 0; + } + + if (p_reflection_probe_cull_count) { + reflection_probe_instances = (ReflectionProbeInstance **)alloca(sizeof(ReflectionProbeInstance *) * p_reflection_probe_cull_count); + reflection_probe_count = p_reflection_probe_cull_count; + for (int i = 0; i < p_reflection_probe_cull_count; i++) { + ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]); + ERR_CONTINUE(!rpi); + rpi->last_pass = render_pass + 1; //will be incremented later + rpi->index = i; + reflection_probe_instances[i] = rpi; + } + + } else { + reflection_probe_instances = NULL; + reflection_probe_count = 0; + } + + if (env && env->bg_mode == GD_VS::ENV_BG_CANVAS) { + // If using canvas background, copy 2d to screen copy texture + // TODO: When GLES2 renders to current_rt->mip_maps[], this copy will no longer be needed + _copy_texture_to_buffer(storage->frame.current_rt->color, storage->frame.current_rt->copy_screen_effect.fbo); + } + + // render list stuff + + render_list.clear(); + _fill_render_list(p_cull_result, p_cull_count, false, false); + + // other stuff + + glBindFramebuffer(GL_FRAMEBUFFER, current_fb); + glViewport(viewport_x, viewport_y, viewport_width, viewport_height); + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + glScissor(viewport_x, viewport_y, viewport_width, viewport_height); + glEnable(GL_SCISSOR_TEST); + } + + glDepthFunc(GL_LEQUAL); + glDepthMask(GL_TRUE); + glClearDepth(1.0f); + glEnable(GL_DEPTH_TEST); + glClear(GL_DEPTH_BUFFER_BIT); + + // clear color + + Color clear_color(0, 0, 0, 1); + Ref feed; + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + clear_color = Color(0, 0, 0, 0); + storage->frame.clear_request = false; + } else if (!env || env->bg_mode == GD_VS::ENV_BG_CLEAR_COLOR || env->bg_mode == GD_VS::ENV_BG_SKY) { + if (storage->frame.clear_request) { + clear_color = storage->frame.clear_request_color; + storage->frame.clear_request = false; + } + } else if (env->bg_mode == GD_VS::ENV_BG_CANVAS || env->bg_mode == GD_VS::ENV_BG_COLOR || env->bg_mode == GD_VS::ENV_BG_COLOR_SKY) { + clear_color = env->bg_color; + storage->frame.clear_request = false; + } else if (env->bg_mode == GD_VS::ENV_BG_CAMERA_FEED) { + feed = CameraServer::get_singleton()->get_feed_by_id(env->camera_feed_id); + storage->frame.clear_request = false; + } else { + storage->frame.clear_request = false; + } + + if (!env || env->bg_mode != GD_VS::ENV_BG_KEEP) { + glClearColor(clear_color.r, clear_color.g, clear_color.b, clear_color.a); + glClear(GL_COLOR_BUFFER_BIT); + } + + state.default_ambient = Color(clear_color.r, clear_color.g, clear_color.b, 1.0); + state.default_bg = Color(clear_color.r, clear_color.g, clear_color.b, 1.0); + + if (storage->frame.current_rt && storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_DIRECT_TO_SCREEN]) { + glDisable(GL_SCISSOR_TEST); + } + + glVertexAttrib4f(GD_VS::ARRAY_COLOR, 1, 1, 1, 1); + + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // render sky + RasterizerStorageGLES2::Sky *sky = NULL; + GLuint env_radiance_tex = 0; + if (env) { + switch (env->bg_mode) { + case GD_VS::ENV_BG_COLOR_SKY: + case GD_VS::ENV_BG_SKY: { + sky = storage->sky_owner.getornull(env->sky); + + if (sky) { + env_radiance_tex = sky->radiance; + } + } break; + case GD_VS::ENV_BG_CAMERA_FEED: { + if (feed.is_valid() && (feed->get_base_width() > 0) && (feed->get_base_height() > 0)) { + // copy our camera feed to our background + + glDisable(GL_BLEND); + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, true); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_DISPLAY_TRANSFORM, true); + + if (feed->get_datatype() == CameraFeed::FEED_RGB) { + RID camera_RGBA = feed->get_texture(CameraServer::FEED_RGBA_IMAGE); + + VS::get_singleton()->texture_bind(camera_RGBA, 0); + + } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR) { + RID camera_YCbCr = feed->get_texture(CameraServer::FEED_YCBCR_IMAGE); + + VS::get_singleton()->texture_bind(camera_YCbCr, 0); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::YCBCR_TO_RGB, true); + + } else if (feed->get_datatype() == CameraFeed::FEED_YCBCR_SEP) { + RID camera_Y = feed->get_texture(CameraServer::FEED_Y_IMAGE); + RID camera_CbCr = feed->get_texture(CameraServer::FEED_CBCR_IMAGE); + + VS::get_singleton()->texture_bind(camera_Y, 0); + VS::get_singleton()->texture_bind(camera_CbCr, 1); + + storage->shaders.copy.set_conditional(CopyShaderGLES2::SEP_CBCR_TEXTURE, true); + storage->shaders.copy.set_conditional(CopyShaderGLES2::YCBCR_TO_RGB, true); + }; + + storage->shaders.copy.bind(); + storage->shaders.copy.set_uniform(CopyShaderGLES2::DISPLAY_TRANSFORM, feed->get_transform()); + + storage->bind_quad_array(); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glDisableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glDisableVertexAttribArray(GD_VS::ARRAY_TEX_UV); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + // turn off everything used + storage->shaders.copy.set_conditional(CopyShaderGLES2::SEP_CBCR_TEXTURE, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::YCBCR_TO_RGB, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_DISPLAY_TRANSFORM, false); + + //restore + glEnable(GL_BLEND); + glDepthMask(GL_TRUE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + } else { + // don't have a feed, just show greenscreen :) + clear_color = Color(0.0, 1.0, 0.0, 1.0); + } + } break; + case GD_VS::ENV_BG_CANVAS: { + // use screen copy as background + _copy_texture_to_buffer(storage->frame.current_rt->copy_screen_effect.color, current_fb); + } break; + default: { + } break; + } + } + + if (probe_interior) { + env_radiance_tex = 0; //do not use radiance texture on interiors + state.default_ambient = Color(0, 0, 0, 1); //black as default ambient for interior + state.default_bg = Color(0, 0, 0, 1); //black as default background for interior + } + + // render opaque things first + render_list.sort_by_key(false); + _render_render_list(render_list.elements, render_list.element_count, cam_transform, p_cam_projection, p_shadow_atlas, env, env_radiance_tex, 0.0, 0.0, reverse_cull, false, false); + + // then draw the sky after + if (env && env->bg_mode == GD_VS::ENV_BG_SKY && (!storage->frame.current_rt || !storage->frame.current_rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT])) { + if (sky && sky->panorama.is_valid()) { + _draw_sky(sky, p_cam_projection, cam_transform, false, env->sky_custom_fov, env->bg_energy, env->sky_orientation); + } + } + + if (storage->frame.current_rt && state.used_screen_texture) { + //copy screen texture + + if (storage->frame.current_rt->multisample_active) { + // Resolve framebuffer to front buffer before copying +#ifdef GLES_OVER_GL + + glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->multisample_fbo); + glReadBuffer(GL_COLOR_ATTACHMENT0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); + glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +#elif IPHONE_ENABLED + + glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->multisample_fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); + glResolveMultisampleFramebufferAPPLE(); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +#elif ANDROID_ENABLED + + // In GLES2 AndroidBlit is not available, so just copy color texture manually + _copy_texture_to_buffer(storage->frame.current_rt->multisample_color, storage->frame.current_rt->fbo); +#endif + } + + storage->canvas->_copy_screen(Rect2()); + + if (storage->frame.current_rt && storage->frame.current_rt->multisample_active) { + // Rebind the current framebuffer + glBindFramebuffer(GL_FRAMEBUFFER, current_fb); + glViewport(0, 0, viewport_width, viewport_height); + } + } + // alpha pass + + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + render_list.sort_by_reverse_depth_and_priority(true); + + _render_render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, cam_transform, p_cam_projection, p_shadow_atlas, env, env_radiance_tex, 0.0, 0.0, reverse_cull, true, false); + + if (p_reflection_probe.is_valid()) { + // Rendering to a probe so no need for post_processing + return; + } + + //post process + _post_process(env, p_cam_projection); + + //#define GLES2_SHADOW_ATLAS_DEBUG_VIEW + +#ifdef GLES2_SHADOW_ATLAS_DEBUG_VIEW + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); + if (shadow_atlas) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); + + glViewport(0, 0, storage->frame.current_rt->width / 4, storage->frame.current_rt->height / 4); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, false); + storage->shaders.copy.bind(); + + storage->_copy_screen(); + } +#endif + + //#define GLES2_SHADOW_DIRECTIONAL_DEBUG_VIEW + +#ifdef GLES2_SHADOW_DIRECTIONAL_DEBUG_VIEW + if (true) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); + + glViewport(0, 0, storage->frame.current_rt->width / 4, storage->frame.current_rt->height / 4); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_COPY_SECTION, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_MULTIPLIER, false); + storage->shaders.copy.set_conditional(CopyShaderGLES2::USE_PANORAMA, false); + storage->shaders.copy.bind(); + + storage->_copy_screen(); + } +#endif +} + +void RasterizerSceneGLES2::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) { + state.render_no_shadows = false; + + LightInstance *light_instance = light_instance_owner.getornull(p_light); + ERR_FAIL_COND(!light_instance); + + RasterizerStorageGLES2::Light *light = light_instance->light_ptr; + ERR_FAIL_COND(!light); + + uint32_t x; + uint32_t y; + uint32_t width; + uint32_t height; + + float zfar = 0; + bool flip_facing = false; + int custom_vp_size = 0; + GLuint fbo = 0; + state.shadow_is_dual_parabolloid = false; + state.dual_parbolloid_direction = 0.0; + + int current_cubemap = -1; + float bias = 0; + float normal_bias = 0; + + CameraMatrix light_projection; + Transform3D light_transform; + + // TODO directional light + + if (light->type == GD_VS::LIGHT_DIRECTIONAL) { + // set pssm stuff + + // TODO set this only when changed + + light_instance->light_directional_index = directional_shadow.current_light; + light_instance->last_scene_shadow_pass = scene_pass; + + directional_shadow.current_light++; + + if (directional_shadow.light_count == 1) { + light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size); + } else if (directional_shadow.light_count == 2) { + light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size / 2); + if (light_instance->light_directional_index == 1) { + light_instance->directional_rect.position.x += light_instance->directional_rect.size.x; + } + } else { //3 and 4 + light_instance->directional_rect = Rect2(0, 0, directional_shadow.size / 2, directional_shadow.size / 2); + if (light_instance->light_directional_index & 1) { + light_instance->directional_rect.position.x += light_instance->directional_rect.size.x; + } + if (light_instance->light_directional_index / 2) { + light_instance->directional_rect.position.y += light_instance->directional_rect.size.y; + } + } + + light_projection = light_instance->shadow_transform[p_pass].camera; + light_transform = light_instance->shadow_transform[p_pass].transform; + + x = light_instance->directional_rect.position.x; + y = light_instance->directional_rect.position.y; + width = light_instance->directional_rect.size.width; + height = light_instance->directional_rect.size.height; + + if (light->directional_shadow_mode == GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { + width /= 2; + height /= 2; + + if (p_pass == 1) { + x += width; + } else if (p_pass == 2) { + y += height; + } else if (p_pass == 3) { + x += width; + y += height; + } + + } else if (light->directional_shadow_mode == GD_VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { + height /= 2; + + if (p_pass == 0) { + } else { + y += height; + } + } + + float bias_mult = Math::lerp(1.0f, light_instance->shadow_transform[p_pass].bias_scale, light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE]); + zfar = light->param[VS::LIGHT_PARAM_RANGE]; + bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS] * bias_mult; + normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS] * bias_mult; + + fbo = directional_shadow.fbo; + } else { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); + ERR_FAIL_COND(!shadow_atlas); + ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light)); + + fbo = shadow_atlas->fbo; + + uint32_t key = shadow_atlas->shadow_owners[p_light]; + + uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x03; + uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; + + ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size()); + + uint32_t quadrant_size = shadow_atlas->size >> 1; + + x = (quadrant & 1) * quadrant_size; + y = (quadrant >> 1) * quadrant_size; + + uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); + x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; + + width = shadow_size; + height = shadow_size; + + if (light->type == GD_VS::LIGHT_OMNI) { + // cubemap only + if (light->omni_shadow_mode == GD_VS::LIGHT_OMNI_SHADOW_CUBE && storage->config.support_shadow_cubemaps) { + int cubemap_index = shadow_cubemaps.size() - 1; + + // find an appropriate cubemap to render to + for (int i = shadow_cubemaps.size() - 1; i >= 0; i--) { + if (shadow_cubemaps[i].size > shadow_size * 2) { + break; + } + + cubemap_index = i; + } + + fbo = shadow_cubemaps[cubemap_index].fbo[p_pass]; + light_projection = light_instance->shadow_transform[0].camera; + light_transform = light_instance->shadow_transform[0].transform; + + custom_vp_size = shadow_cubemaps[cubemap_index].size; + zfar = light->param[VS::LIGHT_PARAM_RANGE]; + + current_cubemap = cubemap_index; + } else { + //dual parabolloid + state.shadow_is_dual_parabolloid = true; + light_projection = light_instance->shadow_transform[0].camera; + light_transform = light_instance->shadow_transform[0].transform; + + if (light->omni_shadow_detail == GD_VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { + height /= 2; + y += p_pass * height; + } else { + width /= 2; + x += p_pass * width; + } + + state.dual_parbolloid_direction = p_pass == 0 ? 1.0 : -1.0; + flip_facing = (p_pass == 1); + zfar = light->param[VS::LIGHT_PARAM_RANGE]; + bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; + + state.dual_parbolloid_zfar = zfar; + + state.scene_shader.set_conditional(SceneShaderGLES2::RENDER_DEPTH_DUAL_PARABOLOID, true); + } + + } else if (light->type == GD_VS::LIGHT_SPOT) { + light_projection = light_instance->shadow_transform[0].camera; + light_transform = light_instance->shadow_transform[0].transform; + + flip_facing = false; + zfar = light->param[VS::LIGHT_PARAM_RANGE]; + bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; + normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]; + } + } + + render_list.clear(); + + _fill_render_list(p_cull_result, p_cull_count, true, true); + + render_list.sort_by_depth(false); + + glDisable(GL_BLEND); + glDisable(GL_DITHER); + glEnable(GL_DEPTH_TEST); + + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + + glDepthMask(GL_TRUE); + if (!storage->config.use_rgba_3d_shadows) { + glColorMask(0, 0, 0, 0); + } + + if (custom_vp_size) { + glViewport(0, 0, custom_vp_size, custom_vp_size); + glScissor(0, 0, custom_vp_size, custom_vp_size); + } else { + glViewport(x, y, width, height); + glScissor(x, y, width, height); + } + + glEnable(GL_SCISSOR_TEST); + glClearDepth(1.0f); + glClear(GL_DEPTH_BUFFER_BIT); + if (storage->config.use_rgba_3d_shadows) { + glClearColor(1.0, 1.0, 1.0, 1.0); + glClear(GL_COLOR_BUFFER_BIT); + } + glDisable(GL_SCISSOR_TEST); + + if (light->reverse_cull) { + flip_facing = !flip_facing; + } + + state.scene_shader.set_conditional(SceneShaderGLES2::RENDER_DEPTH, true); + + _render_render_list(render_list.elements, render_list.element_count, light_transform, light_projection, RID(), NULL, 0, bias, normal_bias, flip_facing, false, true); + + state.scene_shader.set_conditional(SceneShaderGLES2::RENDER_DEPTH, false); + state.scene_shader.set_conditional(SceneShaderGLES2::RENDER_DEPTH_DUAL_PARABOLOID, false); + + // convert cubemap to dual paraboloid if needed + if (light->type == GD_VS::LIGHT_OMNI && (light->omni_shadow_mode == GD_VS::LIGHT_OMNI_SHADOW_CUBE && storage->config.support_shadow_cubemaps) && p_pass == 5) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); + + glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo); + state.cube_to_dp_shader.bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_cubemaps[current_cubemap].cubemap); + + glDisable(GL_CULL_FACE); + + for (int i = 0; i < 2; i++) { + state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES2::Z_FLIP, i == 1); + state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES2::Z_NEAR, light_projection.get_z_near()); + state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES2::Z_FAR, light_projection.get_z_far()); + state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES2::BIAS, light->param[VS::LIGHT_PARAM_SHADOW_BIAS]); + + uint32_t local_width = width; + uint32_t local_height = height; + uint32_t local_x = x; + uint32_t local_y = y; + + if (light->omni_shadow_detail == GD_VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { + local_height /= 2; + local_y += i * local_height; + } else { + local_width /= 2; + local_x += i * local_width; + } + + glViewport(local_x, local_y, local_width, local_height); + glScissor(local_x, local_y, local_width, local_height); + + glEnable(GL_SCISSOR_TEST); + + glClearDepth(1.0f); + + glClear(GL_DEPTH_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + + glDisable(GL_BLEND); + + storage->_copy_screen(); + } + } + + if (storage->frame.current_rt) { + glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); + } + if (!storage->config.use_rgba_3d_shadows) { + glColorMask(1, 1, 1, 1); + } +} + +void RasterizerSceneGLES2::set_scene_pass(uint64_t p_pass) { + scene_pass = p_pass; +} + +bool RasterizerSceneGLES2::free(RID p_rid) { + if (light_instance_owner.owns(p_rid)) { + LightInstance *light_instance = light_instance_owner.getptr(p_rid); + + //remove from shadow atlases.. + for (Set::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(E->get()); + ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid)); + uint32_t key = shadow_atlas->shadow_owners[p_rid]; + uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3; + uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK; + + shadow_atlas->quadrants[q].shadows.write[s].owner = RID(); + shadow_atlas->shadow_owners.erase(p_rid); + } + + light_instance_owner.free(p_rid); + memdelete(light_instance); + + } else if (shadow_atlas_owner.owns(p_rid)) { + ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(p_rid); + shadow_atlas_set_size(p_rid, 0); + shadow_atlas_owner.free(p_rid); + memdelete(shadow_atlas); + } else if (reflection_probe_instance_owner.owns(p_rid)) { + ReflectionProbeInstance *reflection_instance = reflection_probe_instance_owner.get(p_rid); + + for (int i = 0; i < 6; i++) { + glDeleteFramebuffers(1, &reflection_instance->fbo[i]); + glDeleteTextures(1, &reflection_instance->color[i]); + } + + if (reflection_instance->cubemap != 0) { + glDeleteTextures(1, &reflection_instance->cubemap); + } + glDeleteRenderbuffers(1, &reflection_instance->depth); + + reflection_probe_release_atlas_index(p_rid); + reflection_probe_instance_owner.free(p_rid); + memdelete(reflection_instance); + + } else { + return false; + } + + return true; +} + +void RasterizerSceneGLES2::set_debug_draw_mode(GD_VS::ViewportDebugDraw p_debug_draw) { +} + +void RasterizerSceneGLES2::initialize() { + state.scene_shader.init(); + + state.scene_shader.set_conditional(SceneShaderGLES2::USE_RGBA_SHADOWS, storage->config.use_rgba_3d_shadows); + state.cube_to_dp_shader.init(); + state.effect_blur_shader.init(); + state.tonemap_shader.init(); + + render_list.init(); + + render_pass = 1; + + shadow_atlas_realloc_tolerance_msec = 500; + + { + //default material and shader + + default_shader = storage->shader_create(); + storage->shader_set_code(default_shader, "shader_type spatial;\n"); + default_material = storage->material_create(); + storage->material_set_shader(default_material, default_shader); + + default_shader_twosided = storage->shader_create(); + default_material_twosided = storage->material_create(); + storage->shader_set_code(default_shader_twosided, "shader_type spatial; render_mode cull_disabled;\n"); + storage->material_set_shader(default_material_twosided, default_shader_twosided); + } + + { + default_worldcoord_shader = storage->shader_create(); + storage->shader_set_code(default_worldcoord_shader, "shader_type spatial; render_mode world_vertex_coords;\n"); + default_worldcoord_material = storage->material_create(); + storage->material_set_shader(default_worldcoord_material, default_worldcoord_shader); + + default_worldcoord_shader_twosided = storage->shader_create(); + default_worldcoord_material_twosided = storage->material_create(); + storage->shader_set_code(default_worldcoord_shader_twosided, "shader_type spatial; render_mode cull_disabled,world_vertex_coords;\n"); + storage->material_set_shader(default_worldcoord_material_twosided, default_worldcoord_shader_twosided); + } + + { + //default material and shader + + default_overdraw_shader = storage->shader_create(); + storage->shader_set_code(default_overdraw_shader, "shader_type spatial;\nrender_mode blend_add,unshaded;\n void fragment() { ALBEDO=vec3(0.4,0.8,0.8); ALPHA=0.2; }"); + default_overdraw_material = storage->material_create(); + storage->material_set_shader(default_overdraw_material, default_overdraw_shader); + } + + { + glGenBuffers(1, &state.sky_verts); + glBindBuffer(GL_ARRAY_BUFFER, state.sky_verts); + glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, NULL, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + + { + uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/limits/buffers/immediate_buffer_size_kb", 2048); + ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/immediate_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/immediate_buffer_size_kb", PROPERTY_HINT_RANGE, "0,8192,1,or_greater")); + + glGenBuffers(1, &state.immediate_buffer); + glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); + glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size * 1024, NULL, GL_DYNAMIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + + // cubemaps for shadows + if (storage->config.support_shadow_cubemaps) { //not going to be used + int max_shadow_cubemap_sampler_size = 512; + + int cube_size = max_shadow_cubemap_sampler_size; + + glActiveTexture(GL_TEXTURE0); + + while (cube_size >= 32) { + ShadowCubeMap cube; + + cube.size = cube_size; + + glGenTextures(1, &cube.cubemap); + glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap); + + for (int i = 0; i < 6; i++) { + glTexImage2D(_cube_side_enum[i], 0, storage->config.depth_internalformat, cube_size, cube_size, 0, GL_DEPTH_COMPONENT, storage->config.depth_type, NULL); + } + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glGenFramebuffers(6, cube.fbo); + for (int i = 0; i < 6; i++) { + glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo[i]); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _cube_side_enum[i], cube.cubemap, 0); + } + + shadow_cubemaps.push_back(cube); + + cube_size >>= 1; + } + } + + { + // directional shadows + + directional_shadow.light_count = 0; + directional_shadow.size = next_power_of_2(GLOBAL_GET("rendering/quality/directional_shadow/size")); + + glGenFramebuffers(1, &directional_shadow.fbo); + glBindFramebuffer(GL_FRAMEBUFFER, directional_shadow.fbo); + + if (storage->config.use_rgba_3d_shadows) { + //maximum compatibility, renderbuffer and RGBA shadow + glGenRenderbuffers(1, &directional_shadow.depth); + glBindRenderbuffer(GL_RENDERBUFFER, directional_shadow.depth); + glRenderbufferStorage(GL_RENDERBUFFER, storage->config.depth_buffer_internalformat, directional_shadow.size, directional_shadow.size); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, directional_shadow.depth); + + glGenTextures(1, &directional_shadow.color); + glBindTexture(GL_TEXTURE_2D, directional_shadow.color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, directional_shadow.size, directional_shadow.size, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, directional_shadow.color, 0); + } else { + //just a depth buffer + glGenTextures(1, &directional_shadow.depth); + glBindTexture(GL_TEXTURE_2D, directional_shadow.depth); + + glTexImage2D(GL_TEXTURE_2D, 0, storage->config.depth_internalformat, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, storage->config.depth_type, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, directional_shadow.depth, 0); + } + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + ERR_PRINT("Directional shadow framebuffer status invalid"); + } + } + + shadow_filter_mode = SHADOW_FILTER_NEAREST; + + glFrontFace(GL_CW); +} + +void RasterizerSceneGLES2::iteration() { + shadow_filter_mode = ShadowFilterMode(int(GLOBAL_GET("rendering/quality/shadows/filter_mode"))); +} + +void RasterizerSceneGLES2::finalize() { +} + +RasterizerSceneGLES2::RasterizerSceneGLES2() { +} + +#endif // godot 3 + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_scene_gles2.h b/drivers/gles2/rasterizer_scene_gles2.h new file mode 100644 index 00000000000..2181186e712 --- /dev/null +++ b/drivers/gles2/rasterizer_scene_gles2.h @@ -0,0 +1,793 @@ +/*************************************************************************/ +/* rasterizer_scene_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once +// dummy + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/math/camera_matrix.h" +#include "core/templates/rid_owner.h" +#include "core/templates/self_list.h" +#include "drivers/gles_common/rasterizer_common_stubs.h" +#include "scene/resources/mesh.h" +#include "servers/rendering/renderer_compositor.h" +#include "servers/rendering_server.h" +#include "shaders/scene.glsl.gen.h" + +class RasterizerSceneGLES2 : public StubsScene { +public: + struct State { + SceneShaderGLES2 scene_shader; + + } state; + +public: + RasterizerSceneGLES2() {} + ~RasterizerSceneGLES2() {} +}; + +#ifdef GODOT_3 + +/* Must come before shaders or the Windows build fails... */ +#include "drivers/gles_common/rasterizer_version.h" +#include "rasterizer_storage_gles2.h" + +#include "shaders/cube_to_dp.glsl.gen.h" +#include "shaders/effect_blur.glsl.gen.h" +#include "shaders/scene.glsl.gen.h" +#include "shaders/tonemap.glsl.gen.h" +/* + +#include "drivers/gles3/shaders/exposure.glsl.gen.h" +#include "drivers/gles3/shaders/resolve.glsl.gen.h" +#include "drivers/gles3/shaders/scene.glsl.gen.h" +#include "drivers/gles3/shaders/screen_space_reflection.glsl.gen.h" +#include "drivers/gles3/shaders/ssao.glsl.gen.h" +#include "drivers/gles3/shaders/ssao_blur.glsl.gen.h" +#include "drivers/gles3/shaders/ssao_minify.glsl.gen.h" +#include "drivers/gles3/shaders/subsurf_scattering.glsl.gen.h" + +*/ + +class RasterizerSceneGLES2 : public RasterizerScene { +public: + enum ShadowFilterMode { + SHADOW_FILTER_NEAREST, + SHADOW_FILTER_PCF5, + SHADOW_FILTER_PCF13, + }; + + enum { + INSTANCE_ATTRIB_BASE = 8, + INSTANCE_BONE_BASE = 13, + }; + + ShadowFilterMode shadow_filter_mode; + + RID default_material; + RID default_material_twosided; + RID default_shader; + RID default_shader_twosided; + + RID default_worldcoord_material; + RID default_worldcoord_material_twosided; + RID default_worldcoord_shader; + RID default_worldcoord_shader_twosided; + + RID default_overdraw_material; + RID default_overdraw_shader; + + uint64_t render_pass; + uint64_t scene_pass; + uint32_t current_material_index; + uint32_t current_geometry_index; + uint32_t current_light_index; + uint32_t current_refprobe_index; + uint32_t current_shader_index; + + RasterizerStorageGLES2 *storage; + struct State { + bool texscreen_copied; + int current_blend_mode; + float current_line_width; + int current_depth_draw; + bool current_depth_test; + GLuint current_main_tex; + + SceneShaderGLES2 scene_shader; + CubeToDpShaderGLES2 cube_to_dp_shader; + TonemapShaderGLES2 tonemap_shader; + EffectBlurShaderGLES2 effect_blur_shader; + + GLuint sky_verts; + + GLuint immediate_buffer; + Color default_ambient; + Color default_bg; + + // ResolveShaderGLES3 resolve_shader; + // ScreenSpaceReflectionShaderGLES3 ssr_shader; + // EffectBlurShaderGLES3 effect_blur_shader; + // SubsurfScatteringShaderGLES3 sss_shader; + // SsaoMinifyShaderGLES3 ssao_minify_shader; + // SsaoShaderGLES3 ssao_shader; + // SsaoBlurShaderGLES3 ssao_blur_shader; + // ExposureShaderGLES3 exposure_shader; + + /* + struct SceneDataUBO { + //this is a std140 compatible struct. Please read the OpenGL 3.3 Specificaiton spec before doing any changes + float projection_matrix[16]; + float inv_projection_matrix[16]; + float camera_inverse_matrix[16]; + float camera_matrix[16]; + float ambient_light_color[4]; + float bg_color[4]; + float fog_color_enabled[4]; + float fog_sun_color_amount[4]; + + float ambient_energy; + float bg_energy; + float z_offset; + float z_slope_scale; + float shadow_dual_paraboloid_render_zfar; + float shadow_dual_paraboloid_render_side; + float viewport_size[2]; + float screen_pixel_size[2]; + float shadow_atlas_pixel_size[2]; + float shadow_directional_pixel_size[2]; + + float time; + float z_far; + float reflection_multiplier; + float subsurface_scatter_width; + float ambient_occlusion_affect_light; + + uint32_t fog_depth_enabled; + float fog_depth_begin; + float fog_depth_curve; + uint32_t fog_transmit_enabled; + float fog_transmit_curve; + uint32_t fog_height_enabled; + float fog_height_min; + float fog_height_max; + float fog_height_curve; + // make sure this struct is padded to be a multiple of 16 bytes for webgl + + } ubo_data; + + GLuint scene_ubo; + + struct EnvironmentRadianceUBO { + float transform[16]; + float ambient_contribution; + uint8_t padding[12]; + + } env_radiance_data; + + GLuint env_radiance_ubo; + + GLuint sky_array; + + GLuint directional_ubo; + + GLuint spot_array_ubo; + GLuint omni_array_ubo; + GLuint reflection_array_ubo; + + GLuint immediate_buffer; + GLuint immediate_array; + + uint32_t ubo_light_size; + uint8_t *spot_array_tmp; + uint8_t *omni_array_tmp; + uint8_t *reflection_array_tmp; + + int max_ubo_lights; + int max_forward_lights_per_object; + int max_ubo_reflections; + int max_skeleton_bones; + + bool used_contact_shadows; + + int spot_light_count; + int omni_light_count; + int directional_light_count; + int reflection_probe_count; + + bool used_sss; + bool using_contact_shadows; + + VS::ViewportDebugDraw debug_draw; + */ + + bool cull_front; + bool cull_disabled; + + bool used_screen_texture; + bool shadow_is_dual_parabolloid; + float dual_parbolloid_direction; + float dual_parbolloid_zfar; + + bool render_no_shadows; + + Vector2 viewport_size; + + Vector2 screen_pixel_size; + } state; + + /* SHADOW ATLAS API */ + + uint64_t shadow_atlas_realloc_tolerance_msec; + + struct ShadowAtlas : public RID_Data { + enum { + QUADRANT_SHIFT = 27, + SHADOW_INDEX_MASK = (1 << QUADRANT_SHIFT) - 1, + SHADOW_INVALID = 0xFFFFFFFF, + }; + + struct Quadrant { + uint32_t subdivision; + + struct Shadow { + RID owner; + uint64_t version; + uint64_t alloc_tick; + + Shadow() { + version = 0; + alloc_tick = 0; + } + }; + + Vector shadows; + + Quadrant() { + subdivision = 0; + } + } quadrants[4]; + + int size_order[4]; + uint32_t smallest_subdiv; + + int size; + + GLuint fbo; + GLuint depth; + GLuint color; + + Map shadow_owners; + }; + + struct ShadowCubeMap { + GLuint fbo[6]; + GLuint cubemap; + uint32_t size; + }; + + Vector shadow_cubemaps; + + RID_Owner shadow_atlas_owner; + + RID shadow_atlas_create(); + void shadow_atlas_set_size(RID p_atlas, int p_size); + void shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision); + bool _shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow); + bool shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version); + + struct DirectionalShadow { + GLuint fbo; + GLuint depth; + GLuint color; + + int light_count; + int size; + int current_light; + } directional_shadow; + + virtual int get_directional_light_shadow_size(RID p_light_intance); + virtual void set_directional_shadow_count(int p_count); + + /* REFLECTION PROBE ATLAS API */ + + virtual RID reflection_atlas_create(); + virtual void reflection_atlas_set_size(RID p_ref_atlas, int p_size); + virtual void reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv); + + /* REFLECTION CUBEMAPS */ + + /* REFLECTION PROBE INSTANCE */ + + struct ReflectionProbeInstance : public RID_Data { + RasterizerStorageGLES2::ReflectionProbe *probe_ptr; + RID probe; + RID self; + RID atlas; + + int reflection_atlas_index; + + int render_step; + int reflection_index; + + GLuint fbo[6]; + GLuint color[6]; + GLuint depth; + GLuint cubemap; + + int current_resolution; + mutable bool dirty; + + uint64_t last_pass; + uint32_t index; + + Transform3D transform; + }; + + mutable RID_Owner reflection_probe_instance_owner; + + ReflectionProbeInstance **reflection_probe_instances; + int reflection_probe_count; + + virtual RID reflection_probe_instance_create(RID p_probe); + virtual void reflection_probe_instance_set_transform(RID p_instance, const Transform3D &p_transform); + virtual void reflection_probe_release_atlas_index(RID p_instance); + virtual bool reflection_probe_instance_needs_redraw(RID p_instance); + virtual bool reflection_probe_instance_has_reflection(RID p_instance); + virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas); + virtual bool reflection_probe_instance_postprocess_step(RID p_instance); + + /* ENVIRONMENT API */ + + struct Environment : public RID_Data { + VS::EnvironmentBG bg_mode; + + RID sky; + float sky_custom_fov; + Basis sky_orientation; + + Color bg_color; + float bg_energy; + float sky_ambient; + + int camera_feed_id; + + Color ambient_color; + float ambient_energy; + float ambient_sky_contribution; + + int canvas_max_layer; + + bool glow_enabled; + int glow_levels; + float glow_intensity; + float glow_strength; + float glow_bloom; + VS::EnvironmentGlowBlendMode glow_blend_mode; + float glow_hdr_bleed_threshold; + float glow_hdr_bleed_scale; + float glow_hdr_luminance_cap; + bool glow_bicubic_upscale; + + bool dof_blur_far_enabled; + float dof_blur_far_distance; + float dof_blur_far_transition; + float dof_blur_far_amount; + VS::EnvironmentDOFBlurQuality dof_blur_far_quality; + + bool dof_blur_near_enabled; + float dof_blur_near_distance; + float dof_blur_near_transition; + float dof_blur_near_amount; + VS::EnvironmentDOFBlurQuality dof_blur_near_quality; + + bool adjustments_enabled; + float adjustments_brightness; + float adjustments_contrast; + float adjustments_saturation; + RID color_correction; + + bool fog_enabled; + Color fog_color; + Color fog_sun_color; + float fog_sun_amount; + + bool fog_depth_enabled; + float fog_depth_begin; + float fog_depth_end; + float fog_depth_curve; + bool fog_transmit_enabled; + float fog_transmit_curve; + bool fog_height_enabled; + float fog_height_min; + float fog_height_max; + float fog_height_curve; + + Environment() : + bg_mode(GD_VS::ENV_BG_CLEAR_COLOR), + sky_custom_fov(0.0), + bg_energy(1.0), + sky_ambient(0), + camera_feed_id(0), + ambient_energy(1.0), + ambient_sky_contribution(0.0), + canvas_max_layer(0), + glow_enabled(false), + glow_levels((1 << 2) | (1 << 4)), + glow_intensity(0.8), + glow_strength(1.0), + glow_bloom(0.0), + glow_blend_mode(GD_VS::GLOW_BLEND_MODE_SOFTLIGHT), + glow_hdr_bleed_threshold(1.0), + glow_hdr_bleed_scale(2.0), + glow_hdr_luminance_cap(12.0), + glow_bicubic_upscale(false), + dof_blur_far_enabled(false), + dof_blur_far_distance(10), + dof_blur_far_transition(5), + dof_blur_far_amount(0.1), + dof_blur_far_quality(GD_VS::ENV_DOF_BLUR_QUALITY_MEDIUM), + dof_blur_near_enabled(false), + dof_blur_near_distance(2), + dof_blur_near_transition(1), + dof_blur_near_amount(0.1), + dof_blur_near_quality(GD_VS::ENV_DOF_BLUR_QUALITY_MEDIUM), + adjustments_enabled(false), + adjustments_brightness(1.0), + adjustments_contrast(1.0), + adjustments_saturation(1.0), + fog_enabled(false), + fog_color(Color(0.5, 0.5, 0.5)), + fog_sun_color(Color(0.8, 0.8, 0.0)), + fog_sun_amount(0), + fog_depth_enabled(true), + fog_depth_begin(10), + fog_depth_end(0), + fog_depth_curve(1), + fog_transmit_enabled(true), + fog_transmit_curve(1), + fog_height_enabled(false), + fog_height_min(10), + fog_height_max(0), + fog_height_curve(1) { + } + }; + + mutable RID_Owner environment_owner; + + virtual RID environment_create(); + + virtual void environment_set_background(RID p_env, GD_VS::EnvironmentBG p_bg); + virtual void environment_set_sky(RID p_env, RID p_sky); + virtual void environment_set_sky_custom_fov(RID p_env, float p_scale); + virtual void environment_set_sky_orientation(RID p_env, const Basis &p_orientation); + virtual void environment_set_bg_color(RID p_env, const Color &p_color); + virtual void environment_set_bg_energy(RID p_env, float p_energy); + virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer); + virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_sky_contribution = 0.0); + virtual void environment_set_camera_feed_id(RID p_env, int p_camera_feed_id); + + virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, GD_VS::EnvironmentDOFBlurQuality p_quality); + virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, GD_VS::EnvironmentDOFBlurQuality p_quality); + + virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_threshold, GD_VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap, bool p_bicubic_upscale); + virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture); + + virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_in, float p_fade_out, float p_depth_tolerance, bool p_roughness); + virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, float p_ao_channel_affect, const Color &p_color, GD_VS::EnvironmentSSAOQuality p_quality, GD_VS::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness); + + virtual void environment_set_tonemap(RID p_env, GD_VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale); + + virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp); + + virtual void environment_set_fog(RID p_env, bool p_enable, const Color &p_color, const Color &p_sun_color, float p_sun_amount); + virtual void environment_set_fog_depth(RID p_env, bool p_enable, float p_depth_begin, float p_depth_end, float p_depth_curve, bool p_transmit, float p_transmit_curve); + virtual void environment_set_fog_height(RID p_env, bool p_enable, float p_min_height, float p_max_height, float p_height_curve); + + virtual bool is_environment(RID p_env); + + virtual GD_VS::EnvironmentBG environment_get_background(RID p_env); + virtual int environment_get_canvas_max_layer(RID p_env); + + /* LIGHT INSTANCE */ + + struct LightInstance : public RID_Data { + struct ShadowTransform { + CameraMatrix camera; + Transform3D transform; + float farplane; + float split; + float bias_scale; + }; + + ShadowTransform shadow_transform[4]; + + RID self; + RID light; + + RasterizerStorageGLES2::Light *light_ptr; + Transform3D transform; + + Vector3 light_vector; + Vector3 spot_vector; + float linear_att; + + // TODO passes and all that stuff ? + uint64_t last_scene_pass; + uint64_t last_scene_shadow_pass; + + uint16_t light_index; + uint16_t light_directional_index; + + Rect2 directional_rect; + + Set shadow_atlases; // atlases where this light is registered + }; + + mutable RID_Owner light_instance_owner; + + virtual RID light_instance_create(RID p_light); + virtual void light_instance_set_transform(RID p_light_instance, const Transform3D &p_transform); + virtual void light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform3D &p_transform, float p_far, float p_split, int p_pass, float p_bias_scale = 1.0); + virtual void light_instance_mark_visible(RID p_light_instance); + virtual bool light_instances_can_render_shadow_cube() const { return storage->config.support_shadow_cubemaps; } + + LightInstance **render_light_instances; + int render_directional_lights; + int render_light_instance_count; + + /* REFLECTION INSTANCE */ + + virtual RID gi_probe_instance_create(); + virtual void gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data); + virtual void gi_probe_instance_set_transform_to_data(RID p_probe, const Transform3D &p_xform); + virtual void gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds); + + /* RENDER LIST */ + + enum LightMode { + LIGHTMODE_NORMAL, + LIGHTMODE_UNSHADED, + LIGHTMODE_LIGHTMAP, + LIGHTMODE_LIGHTMAP_CAPTURE, + }; + + struct RenderList { + enum { + MAX_LIGHTS = 255, + MAX_REFLECTION_PROBES = 255, + DEFAULT_MAX_ELEMENTS = 65536 + }; + + int max_elements; + + struct Element { + InstanceBaseDependency *instance; + + RasterizerStorageGLES2::Geometry *geometry; + RasterizerStorageGLES2::Material *material; + RasterizerStorageGLES2::GeometryOwner *owner; + + bool use_accum; //is this an add pass for multipass + bool *use_accum_ptr; + bool front_facing; + + union { + //TODO: should be endian swapped on big endian + struct { + int32_t depth_layer : 16; + int32_t priority : 16; + }; + + uint32_t depth_key; + }; + + union { + struct { + //from least significant to most significant in sort, TODO: should be endian swapped on big endian + + uint64_t geometry_index : 14; + uint64_t instancing : 1; + uint64_t skeleton : 1; + uint64_t shader_index : 10; + uint64_t material_index : 10; + uint64_t light_index : 8; + uint64_t light_type2 : 1; // if 1==0 : nolight/directional, else omni/spot + uint64_t refprobe_1_index : 8; + uint64_t refprobe_0_index : 8; + uint64_t light_type1 : 1; //no light, directional is 0, omni spot is 1 + uint64_t light_mode : 2; // LightMode enum + }; + + uint64_t sort_key; + }; + }; + + Element *base_elements; + Element **elements; + + int element_count; + int alpha_element_count; + + void clear() { + element_count = 0; + alpha_element_count = 0; + } + + // sorts + + struct SortByKey { + _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const { + if (A->depth_key == B->depth_key) { + return A->sort_key < B->sort_key; + } else { + return A->depth_key < B->depth_key; + } + } + }; + + void sort_by_key(bool p_alpha) { + SortArray sorter; + + if (p_alpha) { + sorter.sort(&elements[max_elements - alpha_element_count], alpha_element_count); + } else { + sorter.sort(elements, element_count); + } + } + + struct SortByDepth { + _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const { + return A->instance->depth < B->instance->depth; + } + }; + + void sort_by_depth(bool p_alpha) { //used for shadows + + SortArray sorter; + if (p_alpha) { + sorter.sort(&elements[max_elements - alpha_element_count], alpha_element_count); + } else { + sorter.sort(elements, element_count); + } + } + + struct SortByReverseDepthAndPriority { + _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const { + if (A->priority == B->priority) { + return A->instance->depth > B->instance->depth; + } else { + return A->priority < B->priority; + } + } + }; + + void sort_by_reverse_depth_and_priority(bool p_alpha) { //used for alpha + + SortArray sorter; + if (p_alpha) { + sorter.sort(&elements[max_elements - alpha_element_count], alpha_element_count); + } else { + sorter.sort(elements, element_count); + } + } + + // element adding and stuff + + _FORCE_INLINE_ Element *add_element() { + if (element_count + alpha_element_count >= max_elements) + return NULL; + + elements[element_count] = &base_elements[element_count]; + return elements[element_count++]; + } + + _FORCE_INLINE_ Element *add_alpha_element() { + if (element_count + alpha_element_count >= max_elements) { + return NULL; + } + + int idx = max_elements - alpha_element_count - 1; + elements[idx] = &base_elements[idx]; + alpha_element_count++; + return elements[idx]; + } + + void init() { + element_count = 0; + alpha_element_count = 0; + + elements = memnew_arr(Element *, max_elements); + base_elements = memnew_arr(Element, max_elements); + + for (int i = 0; i < max_elements; i++) { + elements[i] = &base_elements[i]; + } + } + + RenderList() { + max_elements = DEFAULT_MAX_ELEMENTS; + } + + ~RenderList() { + memdelete_arr(elements); + memdelete_arr(base_elements); + } + }; + + RenderList render_list; + + void _add_geometry(RasterizerStorageGLES2::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES2::GeometryOwner *p_owner, int p_material, bool p_depth_pass, bool p_shadow_pass); + void _add_geometry_with_material(RasterizerStorageGLES2::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES2::GeometryOwner *p_owner, RasterizerStorageGLES2::Material *p_material, bool p_depth_pass, bool p_shadow_pass); + + void _copy_texture_to_buffer(GLuint p_texture, GLuint p_buffer); + void _fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_depth_pass, bool p_shadow_pass); + void _render_render_list(RenderList::Element **p_elements, int p_element_count, + const Transform3D &p_view_transform, + const CameraMatrix &p_projection, + RID p_shadow_atlas, + Environment *p_env, + GLuint p_base_env, + float p_shadow_bias, + float p_shadow_normal_bias, + bool p_reverse_cull, + bool p_alpha_pass, + bool p_shadow); + + void _draw_sky(RasterizerStorageGLES2::Sky *p_sky, const CameraMatrix &p_projection, const Transform3D &p_transform, bool p_vflip, float p_custom_fov, float p_energy, const Basis &p_sky_orientation); + + _FORCE_INLINE_ void _set_cull(bool p_front, bool p_disabled, bool p_reverse_cull); + _FORCE_INLINE_ bool _setup_material(RasterizerStorageGLES2::Material *p_material, bool p_alpha_pass, Size2i p_skeleton_tex_size = Size2i(0, 0)); + _FORCE_INLINE_ void _setup_geometry(RenderList::Element *p_element, RasterizerStorageGLES2::Skeleton *p_skeleton); + _FORCE_INLINE_ void _setup_light_type(LightInstance *p_light, ShadowAtlas *shadow_atlas); + _FORCE_INLINE_ void _setup_light(LightInstance *p_light, ShadowAtlas *shadow_atlas, const Transform3D &p_view_transform, bool accum_pass); + _FORCE_INLINE_ void _setup_refprobes(ReflectionProbeInstance *p_refprobe1, ReflectionProbeInstance *p_refprobe2, const Transform3D &p_view_transform, Environment *p_env); + _FORCE_INLINE_ void _render_geometry(RenderList::Element *p_element); + + void _post_process(Environment *env, const CameraMatrix &p_cam_projection); + + virtual void render_scene(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass); + virtual void render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count); + virtual bool free(RID p_rid); + + virtual void set_scene_pass(uint64_t p_pass); + virtual void set_debug_draw_mode(GD_VS::ViewportDebugDraw p_debug_draw); + + void iteration(); + void initialize(); + void finalize(); + RasterizerSceneGLES2(); +}; + +#endif // godot 3 + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_storage_gles2.cpp b/drivers/gles2/rasterizer_storage_gles2.cpp new file mode 100644 index 00000000000..046a9d5b967 --- /dev/null +++ b/drivers/gles2/rasterizer_storage_gles2.cpp @@ -0,0 +1,3922 @@ +/*************************************************************************/ +/* rasterizer_storage_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +//#define GLES2_DISABLE_RENDER_TARGETS + +#include "rasterizer_storage_gles2.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/config/project_settings.h" +#include "core/math/transform_3d.h" +#include "drivers/gles_common/rasterizer_storage_common.h" +#include "rasterizer_canvas_gles2.h" +#include "rasterizer_scene_gles2.h" +#include "servers/rendering/shader_language.h" + +GLuint RasterizerStorageGLES2::system_fbo = 0; + +/* TEXTURE API */ + +#define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 + +#define _EXT_COMPRESSED_RED_RGTC1_EXT 0x8DBB +#define _EXT_COMPRESSED_RED_RGTC1 0x8DBB +#define _EXT_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define _EXT_COMPRESSED_RG_RGTC2 0x8DBD +#define _EXT_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define _EXT_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC +#define _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD +#define _EXT_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#define _EXT_ETC1_RGB8_OES 0x8D64 + +#define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 +#define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01 +#define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 +#define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 + +#define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54 +#define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55 +#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56 +#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57 + +#define _EXT_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C +#define _EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D +#define _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#define _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F + +#define _GL_TEXTURE_EXTERNAL_OES 0x8D65 + +#ifdef GLES_OVER_GL +#define _GL_HALF_FLOAT_OES 0x140B +#else +#define _GL_HALF_FLOAT_OES 0x8D61 +#endif + +#define _EXT_TEXTURE_CUBE_MAP_SEAMLESS 0x884F + +#define _RED_OES 0x1903 + +#define _DEPTH_COMPONENT24_OES 0x81A6 + +#ifndef GLES_OVER_GL +#define glClearDepth glClearDepthf + +// enable extensions manually for android and ios +#ifndef UWP_ENABLED +#include // needed to load extensions +#endif + +#ifdef IPHONE_ENABLED + +#include +//void *glRenderbufferStorageMultisampleAPPLE; +//void *glResolveMultisampleFramebufferAPPLE; +#define glRenderbufferStorageMultisample glRenderbufferStorageMultisampleAPPLE +#elif defined(ANDROID_ENABLED) + +#include +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisampleEXT; +PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC glFramebufferTexture2DMultisampleEXT; +#define glRenderbufferStorageMultisample glRenderbufferStorageMultisampleEXT +#define glFramebufferTexture2DMultisample glFramebufferTexture2DMultisampleEXT + +#elif defined(UWP_ENABLED) +#include +#define glRenderbufferStorageMultisample glRenderbufferStorageMultisampleANGLE +#define glFramebufferTexture2DMultisample glFramebufferTexture2DMultisampleANGLE +#endif + +#define GL_TEXTURE_3D 0x806F +#define GL_MAX_SAMPLES 0x8D57 +#endif //!GLES_OVER_GL + +void RasterizerStorageGLES2::bind_quad_array() const { + glBindBuffer(GL_ARRAY_BUFFER, resources.quadie); + glVertexAttribPointer(GD_VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0); + glVertexAttribPointer(GD_VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8)); + + glEnableVertexAttribArray(GD_VS::ARRAY_VERTEX); + glEnableVertexAttribArray(GD_VS::ARRAY_TEX_UV); +} + +Ref RasterizerStorageGLES2::_get_gl_image_and_format(const Ref &p_image, Image::Format p_format, uint32_t p_flags, Image::Format &r_real_format, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool p_force_decompress) const { + r_gl_format = 0; + Ref image = p_image; + r_compressed = false; + r_real_format = p_format; + + bool need_decompress = false; + + switch (p_format) { + case Image::FORMAT_L8: { + r_gl_internal_format = GL_LUMINANCE; + r_gl_format = GL_LUMINANCE; + r_gl_type = GL_UNSIGNED_BYTE; + } break; + case Image::FORMAT_LA8: { + r_gl_internal_format = GL_LUMINANCE_ALPHA; + r_gl_format = GL_LUMINANCE_ALPHA; + r_gl_type = GL_UNSIGNED_BYTE; + } break; + case Image::FORMAT_R8: { + r_gl_internal_format = GL_ALPHA; + r_gl_format = GL_ALPHA; + r_gl_type = GL_UNSIGNED_BYTE; + + } break; + case Image::FORMAT_RG8: { + ERR_PRINT("RG texture not supported, converting to RGB8."); + if (image.is_valid()) + image->convert(Image::FORMAT_RGB8); + r_real_format = Image::FORMAT_RGB8; + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + + } break; + case Image::FORMAT_RGB8: { + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + + } break; + case Image::FORMAT_RGBA8: { + r_gl_format = GL_RGBA; + r_gl_internal_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + + } break; + case Image::FORMAT_RGBA4444: { + r_gl_internal_format = GL_RGBA; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_SHORT_4_4_4_4; + + } break; + // case Image::FORMAT_RGBA5551: { + // r_gl_internal_format = GL_RGB5_A1; + // r_gl_format = GL_RGBA; + // r_gl_type = GL_UNSIGNED_SHORT_5_5_5_1; + + // } break; + case Image::FORMAT_RF: { + if (!config.float_texture_supported) { + ERR_PRINT("R float texture not supported, converting to RGB8."); + if (image.is_valid()) + image->convert(Image::FORMAT_RGB8); + r_real_format = Image::FORMAT_RGB8; + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + } else { + r_gl_internal_format = GL_ALPHA; + r_gl_format = GL_ALPHA; + r_gl_type = GL_FLOAT; + } + } break; + case Image::FORMAT_RGF: { + ERR_PRINT("RG float texture not supported, converting to RGB8."); + if (image.is_valid()) + image->convert(Image::FORMAT_RGB8); + r_real_format = Image::FORMAT_RGB8; + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + } break; + case Image::FORMAT_RGBF: { + if (!config.float_texture_supported) { + ERR_PRINT("RGB float texture not supported, converting to RGB8."); + if (image.is_valid()) + image->convert(Image::FORMAT_RGB8); + r_real_format = Image::FORMAT_RGB8; + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + } else { + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_FLOAT; + } + } break; + case Image::FORMAT_RGBAF: { + if (!config.float_texture_supported) { + ERR_PRINT("RGBA float texture not supported, converting to RGBA8."); + if (image.is_valid()) + image->convert(Image::FORMAT_RGBA8); + r_real_format = Image::FORMAT_RGBA8; + r_gl_internal_format = GL_RGBA; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + } else { + r_gl_internal_format = GL_RGBA; + r_gl_format = GL_RGBA; + r_gl_type = GL_FLOAT; + } + } break; + case Image::FORMAT_RH: { + need_decompress = true; + } break; + case Image::FORMAT_RGH: { + need_decompress = true; + } break; + case Image::FORMAT_RGBH: { + need_decompress = true; + } break; + case Image::FORMAT_RGBAH: { + need_decompress = true; + } break; + case Image::FORMAT_RGBE9995: { + r_gl_internal_format = GL_RGB; + r_gl_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + + if (image.is_valid()) + + image = image->rgbe_to_srgb(); + + return image; + + } break; + case Image::FORMAT_DXT1: { + if (config.s3tc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_DXT3: { + if (config.s3tc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_DXT5: { + if (config.s3tc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_RGTC_R: { + if (config.rgtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RED_RGTC1_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_RGTC_RG: { + if (config.rgtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_BPTC_RGBA: { + if (config.bptc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_BPTC_UNORM; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + } break; + case Image::FORMAT_BPTC_RGBF: { + if (config.bptc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT; + r_gl_format = GL_RGB; + r_gl_type = GL_FLOAT; + r_compressed = true; + } else { + need_decompress = true; + } + } break; + case Image::FORMAT_BPTC_RGBFU: { + if (config.bptc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT; + r_gl_format = GL_RGB; + r_gl_type = GL_FLOAT; + r_compressed = true; + } else { + need_decompress = true; + } + } break; +#if 0 + // these have changed in the enum, no idea about PVR formats so left out for now + // FTODO + case Image::FORMAT_PVRTC2: { + if (config.pvrtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + } break; + case Image::FORMAT_PVRTC2A: { + if (config.pvrtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_PVRTC4: { + if (config.pvrtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + + } break; + case Image::FORMAT_PVRTC4A: { + if (config.pvrtc_supported) { + r_gl_internal_format = _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + + } else { + need_decompress = true; + } + + } break; +#endif + case Image::FORMAT_ETC: { + if (config.etc1_supported) { + r_gl_internal_format = _EXT_ETC1_RGB8_OES; + r_gl_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_compressed = true; + } else { + need_decompress = true; + } + } break; + case Image::FORMAT_ETC2_R11: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_R11S: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_RG11: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_RG11S: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_RGB8: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_RGBA8: { + need_decompress = true; + } break; + case Image::FORMAT_ETC2_RGB8A1: { + need_decompress = true; + } break; + default: { + ERR_FAIL_V(Ref()); + } + } + + if (need_decompress || p_force_decompress) { + if (!image.is_null()) { + image = image->duplicate(); + image->decompress(); + ERR_FAIL_COND_V(image->is_compressed(), image); + switch (image->get_format()) { + case Image::FORMAT_RGB8: { + r_gl_format = GL_RGB; + r_gl_internal_format = GL_RGB; + r_gl_type = GL_UNSIGNED_BYTE; + r_real_format = Image::FORMAT_RGB8; + r_compressed = false; + } break; + case Image::FORMAT_RGBA8: { + r_gl_format = GL_RGBA; + r_gl_internal_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_real_format = Image::FORMAT_RGBA8; + r_compressed = false; + } break; + default: { + image->convert(Image::FORMAT_RGBA8); + r_gl_format = GL_RGBA; + r_gl_internal_format = GL_RGBA; + r_gl_type = GL_UNSIGNED_BYTE; + r_real_format = Image::FORMAT_RGBA8; + r_compressed = false; + + } break; + } + } + + return image; + } + + return p_image; +} + +static const GLenum _cube_side_enum[6] = { + GL_TEXTURE_CUBE_MAP_NEGATIVE_X, + GL_TEXTURE_CUBE_MAP_POSITIVE_X, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, + GL_TEXTURE_CUBE_MAP_POSITIVE_Y, + GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, + GL_TEXTURE_CUBE_MAP_POSITIVE_Z, +}; + +RID RasterizerStorageGLES2::texture_allocate() { + RID id = texture_create(); + ERR_FAIL_COND_V(id == RID(), id); + return id; +} + +void RasterizerStorageGLES2::texture_2d_initialize(RID p_texture, const Ref &p_image) { + // Texture *tex = texture_owner.getornull(p_texture); + // ERR_FAIL_COND(!tex); + + int w = p_image->get_width(); + int h = p_image->get_height(); + + _texture_allocate_internal(p_texture, w, h, 1, p_image->get_format(), GD_RD::TEXTURE_TYPE_2D, 0); + texture_set_data(p_texture, p_image); +} + +//RID RasterizerStorageGLES2::texture_2d_create(const Ref &p_image) { +// RID id = texture_create(); +// ERR_FAIL_COND_V(id == RID(), id); + +// int w = p_image->get_width(); +// int h = p_image->get_height(); + +// texture_allocate(id, w, h, 1, p_image->get_format(), GD_RD::TEXTURE_TYPE_2D, 0); + +// texture_set_data(id, p_image); + +// return id; +//} + +//RID RasterizerStorageGLES2::texture_2d_layered_create(const Vector> &p_layers, RS::TextureLayeredType p_layered_type) { +// return RID(); +//} + +//RID RasterizerStorageGLES2::texture_proxy_create(RID p_base) { +// RID link = texture_create(); +// texture_set_proxy(link, p_base); +// return link; +//} + +//void RasterizerStorageGLES2::texture_2d_update_immediate(RID p_texture, const Ref &p_image, int p_layer) { +// // only 1 layer so far +// texture_set_data(p_texture, p_image); +//} +void RasterizerStorageGLES2::texture_2d_update(RID p_texture, const Ref &p_image, int p_layer) { + // only 1 layer so far + texture_set_data(p_texture, p_image); +} + +//RID RasterizerStorageGLES2::texture_2d_placeholder_create() { +// return RID(); +//} + +Ref RasterizerStorageGLES2::texture_2d_get(RID p_texture) const { + Texture *tex = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!tex, Ref()); + + /* +#ifdef TOOLS_ENABLED + if (tex->image_cache_2d.is_valid()) { + return tex->image_cache_2d; + } +#endif + Vector data = RD::get_singleton()->texture_get_data(tex->rd_texture, 0); + ERR_FAIL_COND_V(data.size() == 0, Ref()); + Ref image; + image.instance(); + image->create(tex->width, tex->height, tex->mipmaps > 1, tex->validated_format, data); + ERR_FAIL_COND_V(image->empty(), Ref()); + if (tex->format != tex->validated_format) { + image->convert(tex->format); + } + +#ifdef TOOLS_ENABLED + if (Engine::get_singleton()->is_editor_hint()) { + tex->image_cache_2d = image; + } +#endif +*/ + ERR_FAIL_COND_V(!tex->images.size(), Ref()); + + return tex->images[0]; + + // return image; + + // return Ref(); +} + +void RasterizerStorageGLES2::texture_replace(RID p_texture, RID p_by_texture) { + Texture *tex_to = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!tex_to); + Texture *tex_from = texture_owner.getornull(p_by_texture); + ERR_FAIL_COND(!tex_from); + + tex_to->destroy(); + tex_to->copy_from(*tex_from); + + // copy image data and upload to GL + tex_to->images.resize(tex_from->images.size()); + + for (int n = 0; n < tex_from->images.size(); n++) { + texture_set_data(p_texture, tex_from->images[n], n); + } +} + +bool RasterizerStorageGLES2::_is_main_thread() { + //#if defined DEBUG_ENABLED && defined TOOLS_ENABLED + // must be called from main thread in OpenGL + bool is_main_thread = _main_thread_id == Thread::get_caller_id(); + //#endif + return is_main_thread; +} + +RID RasterizerStorageGLES2::texture_create() { + ERR_FAIL_COND_V(!_is_main_thread(), RID()); + + Texture *texture = memnew(Texture); + ERR_FAIL_COND_V(!texture, RID()); + glGenTextures(1, &texture->tex_id); + texture->active = false; + texture->total_data_size = 0; + + return texture_owner.make_rid(texture); +} + +void RasterizerStorageGLES2::_texture_allocate_internal(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, GD_RD::TextureType p_type, uint32_t p_flags) { + // GLenum format; + // GLenum internal_format; + // GLenum type; + + // bool compressed = false; + + if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) { + p_flags &= ~TEXTURE_FLAG_MIPMAPS; // no mipies for video + } + + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + texture->width = p_width; + texture->height = p_height; + texture->format = p_format; + texture->flags = p_flags; + texture->stored_cube_sides = 0; + texture->type = p_type; + + switch (p_type) { + case GD_RD::TEXTURE_TYPE_2D: { + texture->target = GL_TEXTURE_2D; + texture->images.resize(1); + } break; + // case GD_RD::TEXTURE_TYPE_EXTERNAL: { + //#ifdef ANDROID_ENABLED + // texture->target = _GL_TEXTURE_EXTERNAL_OES; + //#else + // texture->target = GL_TEXTURE_2D; + //#endif + // texture->images.resize(0); + // } break; + case GD_RD::TEXTURE_TYPE_CUBE: { + texture->target = GL_TEXTURE_CUBE_MAP; + texture->images.resize(6); + } break; + case GD_RD::TEXTURE_TYPE_2D_ARRAY: + case GD_RD::TEXTURE_TYPE_3D: { + texture->target = GL_TEXTURE_3D; + ERR_PRINT("3D textures and Texture Arrays are not supported in GLES2. Please switch to the GLES3 backend."); + return; + } break; + default: { + ERR_PRINT("Unknown texture type!"); + return; + } + } + +#if 0 + // if (p_type != GD_VS::TEXTURE_TYPE_EXTERNAL) { + if (p_type == GD_RD::TEXTURE_TYPE_2D) { + texture->alloc_width = texture->width; + texture->alloc_height = texture->height; + texture->resize_to_po2 = false; + if (!config.support_npot_repeat_mipmap) { + int po2_width = next_power_of_2(p_width); + int po2_height = next_power_of_2(p_height); + + bool is_po2 = p_width == po2_width && p_height == po2_height; + + if (!is_po2 && (p_flags & TEXTURE_FLAG_REPEAT || p_flags & TEXTURE_FLAG_MIPMAPS)) { + if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) { + //not supported + ERR_PRINT("Streaming texture for non power of 2 or has mipmaps on this hardware: " + texture->path + "'. Mipmaps and repeat disabled."); + texture->flags &= ~(TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS); + } else { + texture->alloc_height = po2_height; + texture->alloc_width = po2_width; + texture->resize_to_po2 = true; + } + } + } + + GLenum format; + GLenum internal_format; + GLenum type; + bool compressed = false; + + Image::Format real_format; + _get_gl_image_and_format(Ref(), + texture->format, + texture->flags, + real_format, + format, + internal_format, + type, + compressed, + texture->resize_to_po2); + + texture->gl_format_cache = format; + texture->gl_type_cache = type; + texture->gl_internal_format_cache = internal_format; + texture->data_size = 0; + texture->mipmaps = 1; + + texture->compressed = compressed; + } +#endif + + glActiveTexture(GL_TEXTURE0); + glBindTexture(texture->target, texture->tex_id); + + // if (p_type == GD_VS::TEXTURE_TYPE_EXTERNAL) { + // glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + // glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + // glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + // glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + // } else if (p_flags & TEXTURE_FLAG_USED_FOR_STREAMING) { + // //prealloc if video + // glTexImage2D(texture->target, 0, internal_format, texture->alloc_width, texture->alloc_height, 0, format, type, NULL); + // } + + texture->active = true; +} + +void RasterizerStorageGLES2::texture_set_data(RID p_texture, const Ref &p_image, int p_layer) { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND(!_is_main_thread()); + + ERR_FAIL_COND(!texture); + if (texture->target == GL_TEXTURE_3D) { + // Target is set to a 3D texture or array texture, exit early to avoid spamming errors + return; + } + ERR_FAIL_COND(!texture->active); + ERR_FAIL_COND(texture->render_target); + ERR_FAIL_COND(p_image.is_null()); + ERR_FAIL_COND(texture->format != p_image->get_format()); + + ERR_FAIL_COND(!p_image->get_width()); + ERR_FAIL_COND(!p_image->get_height()); + + // ERR_FAIL_COND(texture->type == GD_VS::TEXTURE_TYPE_EXTERNAL); + + GLenum type; + GLenum format; + GLenum internal_format; + bool compressed = false; + + if (config.keep_original_textures && !(texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING)) { + texture->images.write[p_layer] = p_image; + } + + // print_line("texture_set_data width " + itos (p_image->get_width()) + " height " + itos(p_image->get_height())); + + Image::Format real_format; + Ref img = _get_gl_image_and_format(p_image, p_image->get_format(), texture->flags, real_format, format, internal_format, type, compressed, texture->resize_to_po2); + + if (texture->resize_to_po2) { + if (p_image->is_compressed()) { + ERR_PRINT("Texture '" + texture->path + "' is required to be a power of 2 because it uses either mipmaps or repeat, so it was decompressed. This will hurt performance and memory usage."); + } + + if (img == p_image) { + img = img->duplicate(); + } + img->resize_to_po2(false); + } + + if (config.shrink_textures_x2 && (p_image->has_mipmaps() || !p_image->is_compressed()) && !(texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING)) { + texture->alloc_height = MAX(1, texture->alloc_height / 2); + texture->alloc_width = MAX(1, texture->alloc_width / 2); + + if (texture->alloc_width == img->get_width() / 2 && texture->alloc_height == img->get_height() / 2) { + img->shrink_x2(); + } else if (img->get_format() <= Image::FORMAT_RGBA8) { + img->resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR); + } + } + + GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_layer] : GL_TEXTURE_2D; + + texture->data_size = img->get_data().size(); + Vector read = img->get_data(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(texture->target, texture->tex_id); + + texture->ignore_mipmaps = compressed && !img->has_mipmaps(); + + // set filtering and repeat state + _texture_set_state_from_flags(texture); + + int mipmaps = ((texture->flags & TEXTURE_FLAG_MIPMAPS) && img->has_mipmaps()) ? img->get_mipmap_count() + 1 : 1; + + int w = img->get_width(); + int h = img->get_height(); + + int tsize = 0; + + for (int i = 0; i < mipmaps; i++) { + int size, ofs; + img->get_mipmap_offset_and_size(i, ofs, size); + + if (compressed) { + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + + int bw = w; + int bh = h; + + glCompressedTexImage2D(blit_target, i, internal_format, bw, bh, 0, size, &read[ofs]); + } else { + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + if (texture->flags & TEXTURE_FLAG_USED_FOR_STREAMING) { + glTexSubImage2D(blit_target, i, 0, 0, w, h, format, type, &read[ofs]); + } else { + glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]); + } + } + + tsize += size; + + w = MAX(1, w >> 1); + h = MAX(1, h >> 1); + } + + info.texture_mem -= texture->total_data_size; + texture->total_data_size = tsize; + info.texture_mem += texture->total_data_size; + + // printf("texture: %i x %i - size: %i - total: %i\n", texture->width, texture->height, tsize, info.texture_mem); + + texture->stored_cube_sides |= (1 << p_layer); + + if ((texture->flags & TEXTURE_FLAG_MIPMAPS) && mipmaps == 1 && !texture->ignore_mipmaps && (texture->type != GD_RD::TEXTURE_TYPE_CUBE || texture->stored_cube_sides == (1 << 6) - 1)) { + //generate mipmaps if they were requested and the image does not contain them + glGenerateMipmap(texture->target); + } + + texture->mipmaps = mipmaps; +} + +void RasterizerStorageGLES2::texture_set_data_partial(RID p_texture, const Ref &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_layer) { + // TODO + ERR_PRINT("Not implemented (ask Karroffel to do it :p)"); +} + +/* +Ref RasterizerStorageGLES2::texture_get_data(RID p_texture, int p_layer) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, Ref()); + ERR_FAIL_COND_V(!texture->active, Ref()); + ERR_FAIL_COND_V(texture->data_size == 0 && !texture->render_target, Ref()); + + if (texture->type == GD_VS::TEXTURE_TYPE_CUBEMAP && p_layer < 6 && p_layer >= 0 && !texture->images[p_layer].is_null()) { + return texture->images[p_layer]; + } + +#ifdef GLES_OVER_GL + + Image::Format real_format; + GLenum gl_format; + GLenum gl_internal_format; + GLenum gl_type; + bool compressed; + _get_gl_image_and_format(Ref(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed, false); + + PoolVector data; + + int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, real_format, texture->mipmaps > 1); + + data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers + PoolVector::Write wb = data.write(); + + glActiveTexture(GL_TEXTURE0); + + glBindTexture(texture->target, texture->tex_id); + + glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); + + for (int i = 0; i < texture->mipmaps; i++) { + int ofs = Image::get_image_mipmap_offset(texture->alloc_width, texture->alloc_height, real_format, i); + + if (texture->compressed) { + glPixelStorei(GL_PACK_ALIGNMENT, 4); + glGetCompressedTexImage(texture->target, i, &wb[ofs]); + } else { + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glGetTexImage(texture->target, i, texture->gl_format_cache, texture->gl_type_cache, &wb[ofs]); + } + } + + wb.release(); + + data.resize(data_size); + + Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, texture->mipmaps > 1, real_format, data)); + + return Ref(img); +#else + + Image::Format real_format; + GLenum gl_format; + GLenum gl_internal_format; + GLenum gl_type; + bool compressed; + _get_gl_image_and_format(Ref(), texture->format, texture->flags, real_format, gl_format, gl_internal_format, gl_type, compressed, texture->resize_to_po2); + + PoolVector data; + + int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, Image::FORMAT_RGBA8, false); + + data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers + PoolVector::Write wb = data.write(); + + GLuint temp_framebuffer; + glGenFramebuffers(1, &temp_framebuffer); + + GLuint temp_color_texture; + glGenTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, temp_framebuffer); + + glBindTexture(GL_TEXTURE_2D, temp_color_texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->alloc_width, texture->alloc_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_color_texture, 0); + + glDepthMask(GL_FALSE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glColorMask(1, 1, 1, 1); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture->tex_id); + + glViewport(0, 0, texture->alloc_width, texture->alloc_height); + + shaders.copy.bind(); + + glClearColor(0.0, 0.0, 0.0, 0.0); + glClear(GL_COLOR_BUFFER_BIT); + bind_quad_array(); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + glReadPixels(0, 0, texture->alloc_width, texture->alloc_height, GL_RGBA, GL_UNSIGNED_BYTE, &wb[0]); + + glDeleteTextures(1, &temp_color_texture); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &temp_framebuffer); + + wb.release(); + + data.resize(data_size); + + Image *img = memnew(Image(texture->alloc_width, texture->alloc_height, false, Image::FORMAT_RGBA8, data)); + if (!texture->compressed) { + img->convert(real_format); + } + + return Ref(img); + +#endif +} +*/ + +void RasterizerStorageGLES2::_texture_set_state_from_flags(Texture *p_tex) { + if ((p_tex->flags & TEXTURE_FLAG_MIPMAPS) && !p_tex->ignore_mipmaps) + if (p_tex->flags & TEXTURE_FLAG_FILTER) { + // these do not exactly correspond ... + p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS); + //texture->glTexParam_MinFilter(texture->target, config.use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR); + } else { + p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS); + //texture->glTexParam_MinFilter(texture->target, config.use_fast_texture_filter ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR); + } + else { + if (p_tex->flags & TEXTURE_FLAG_FILTER) { + p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR); + //texture->glTexParam_MinFilter(texture->target, GL_LINEAR); + } else { + p_tex->GLSetFilter(p_tex->target, RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST); + // texture->glTexParam_MinFilter(texture->target, GL_NEAREST); + } + } + + if (((p_tex->flags & TEXTURE_FLAG_REPEAT) || (p_tex->flags & TEXTURE_FLAG_MIRRORED_REPEAT)) && p_tex->target != GL_TEXTURE_CUBE_MAP) { + if (p_tex->flags & TEXTURE_FLAG_MIRRORED_REPEAT) { + p_tex->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_MIRROR); + } else { + p_tex->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED); + } + } else { + p_tex->GLSetRepeat(RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED); + } +} + +void RasterizerStorageGLES2::texture_set_flags(RID p_texture, uint32_t p_flags) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + bool had_mipmaps = texture->flags & TEXTURE_FLAG_MIPMAPS; + + texture->flags = p_flags; + + glActiveTexture(GL_TEXTURE0); + glBindTexture(texture->target, texture->tex_id); + + // set filtering and repeat state + _texture_set_state_from_flags(texture); + + if ((texture->flags & TEXTURE_FLAG_MIPMAPS) && !texture->ignore_mipmaps) { + if (!had_mipmaps && texture->mipmaps == 1) { + glGenerateMipmap(texture->target); + } + } +} + +uint32_t RasterizerStorageGLES2::texture_get_flags(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, 0); + + return texture->flags; +} + +Image::Format RasterizerStorageGLES2::texture_get_format(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, Image::FORMAT_L8); + + return texture->format; +} + +GD_RD::TextureType RasterizerStorageGLES2::texture_get_type(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, GD_RD::TEXTURE_TYPE_2D); + + return texture->type; +} + +uint32_t RasterizerStorageGLES2::texture_get_texid(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, 0); + + return texture->tex_id; +} + +void RasterizerStorageGLES2::texture_bind(RID p_texture, uint32_t p_texture_no) { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND(!texture); + + glActiveTexture(GL_TEXTURE0 + p_texture_no); + glBindTexture(texture->target, texture->tex_id); +} + +uint32_t RasterizerStorageGLES2::texture_get_width(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, 0); + + return texture->width; +} + +uint32_t RasterizerStorageGLES2::texture_get_height(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, 0); + + return texture->height; +} + +uint32_t RasterizerStorageGLES2::texture_get_depth(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND_V(!texture, 0); + + return texture->depth; +} + +void RasterizerStorageGLES2::texture_set_size_override(RID p_texture, int p_width, int p_height) { + Texture *texture = texture_owner.getornull(p_texture); + + ERR_FAIL_COND(!texture); + ERR_FAIL_COND(texture->render_target); + + ERR_FAIL_COND(p_width <= 0 || p_width > 16384); + ERR_FAIL_COND(p_height <= 0 || p_height > 16384); + //real texture size is in alloc width and height + texture->width = p_width; + texture->height = p_height; +} + +void RasterizerStorageGLES2::texture_set_path(RID p_texture, const String &p_path) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + texture->path = p_path; +} + +String RasterizerStorageGLES2::texture_get_path(RID p_texture) const { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!texture, ""); + + return texture->path; +} + +void RasterizerStorageGLES2::texture_debug_usage(List *r_info) { + List textures; + texture_owner.get_owned_list(&textures); + + for (List::Element *E = textures.front(); E; E = E->next()) { + Texture *t = texture_owner.getornull(E->get()); + if (!t) + continue; + GD_VS::TextureInfo tinfo; + tinfo.path = t->path; + tinfo.format = t->format; + tinfo.width = t->alloc_width; + tinfo.height = t->alloc_height; + tinfo.depth = 0; + tinfo.bytes = t->total_data_size; + r_info->push_back(tinfo); + } +} + +void RasterizerStorageGLES2::texture_set_shrink_all_x2_on_set_data(bool p_enable) { + config.shrink_textures_x2 = p_enable; +} + +void RasterizerStorageGLES2::textures_keep_original(bool p_enable) { + config.keep_original_textures = p_enable; +} + +Size2 RasterizerStorageGLES2::texture_size_with_proxy(RID p_texture) { + const Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!texture, Size2()); + if (texture->proxy) { + return Size2(texture->proxy->width, texture->proxy->height); + } else { + return Size2(texture->width, texture->height); + } +} + +// example use in 3.2 +// VS::get_singleton()->texture_set_proxy(default_texture->proxy, texture_rid); + +// p_proxy is the source (pre-existing) texture? +// and p_texture is the one that is being made into a proxy? +//This naming is confusing. Comments!!! + +// The naming of the parameters seemed to be reversed? +// The p_proxy is the source texture +// and p_texture is actually the proxy???? + +void RasterizerStorageGLES2::texture_set_proxy(RID p_texture, RID p_proxy) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + if (texture->proxy) { + texture->proxy->proxy_owners.erase(texture); + texture->proxy = NULL; + } + + if (p_proxy.is_valid()) { + Texture *proxy = texture_owner.getornull(p_proxy); + ERR_FAIL_COND(!proxy); + ERR_FAIL_COND(proxy == texture); + proxy->proxy_owners.insert(texture); + texture->proxy = proxy; + } +} + +void RasterizerStorageGLES2::texture_set_force_redraw_if_visible(RID p_texture, bool p_enable) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + texture->redraw_if_visible = p_enable; +} + +void RasterizerStorageGLES2::texture_set_detect_3d_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + texture->detect_3d = p_callback; + texture->detect_3d_ud = p_userdata; +} + +void RasterizerStorageGLES2::texture_set_detect_srgb_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + texture->detect_srgb = p_callback; + texture->detect_srgb_ud = p_userdata; +} + +void RasterizerStorageGLES2::texture_set_detect_normal_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata) { + Texture *texture = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!texture); + + texture->detect_normal = p_callback; + texture->detect_normal_ud = p_userdata; +} + +RID RasterizerStorageGLES2::texture_create_radiance_cubemap(RID p_source, int p_resolution) const { + return RID(); +} + +RID RasterizerStorageGLES2::sky_create() { + Sky *sky = memnew(Sky); + sky->radiance = 0; + return sky_owner.make_rid(sky); +} + +void RasterizerStorageGLES2::sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size) { + Sky *sky = sky_owner.getornull(p_sky); + ERR_FAIL_COND(!sky); + + if (sky->panorama.is_valid()) { + sky->panorama = RID(); + glDeleteTextures(1, &sky->radiance); + sky->radiance = 0; + } + + sky->panorama = p_panorama; + if (!sky->panorama.is_valid()) { + return; // the panorama was cleared + } + + Texture *texture = texture_owner.getornull(sky->panorama); + if (!texture) { + sky->panorama = RID(); + ERR_FAIL_COND(!texture); + } + + // glBindVertexArray(0) and more + { + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_BLEND); + + for (int i = 0; i < GD_VS::ARRAY_MAX - 1; i++) { + glDisableVertexAttribArray(i); + } + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(texture->target, texture->tex_id); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //need this for proper sampling + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, resources.radical_inverse_vdc_cache_tex); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + // New cubemap that will hold the mipmaps with different roughness values + glActiveTexture(GL_TEXTURE2); + glGenTextures(1, &sky->radiance); + glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance); + + int size = p_radiance_size / 2; //divide by two because its a cubemap (this is an approximation because GLES3 uses a dual paraboloid) + + GLenum internal_format = GL_RGB; + GLenum format = GL_RGB; + GLenum type = GL_UNSIGNED_BYTE; + + // Set the initial (empty) mipmaps + // Mobile hardware (PowerVR specially) prefers this approach, + // the previous approach with manual lod levels kills the game. + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internal_format, size, size, 0, format, type, NULL); + } + + glGenerateMipmap(GL_TEXTURE_CUBE_MAP); + + // No filters for now + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + // Framebuffer + + bind_framebuffer(resources.mipmap_blur_fbo); + + int mipmaps = 6; + int lod = 0; + int mm_level = mipmaps; + size = p_radiance_size / 2; + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_SOURCE_PANORAMA, true); + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_DIRECT_WRITE, true); + shaders.cubemap_filter.bind(); + + // third, render to the framebuffer using separate textures, then copy to mipmaps + while (size >= 1) { + //make framebuffer size the texture size, need to use a separate texture for compatibility + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, resources.mipmap_blur_color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, resources.mipmap_blur_color, 0); + + if (lod == 1) { + //bind panorama for smaller lods + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_CUBE_MAP, sky->radiance); + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_SOURCE_PANORAMA, false); + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_DIRECT_WRITE, false); + shaders.cubemap_filter.bind(); + } + glViewport(0, 0, size, size); + bind_quad_array(); + + glActiveTexture(GL_TEXTURE2); //back to panorama + + for (int i = 0; i < 6; i++) { + shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::FACE_ID, i); + + float roughness = mm_level >= 0 ? lod / (float)(mipmaps - 1) : 1; + roughness = MIN(1.0, roughness); //keep max at 1 + shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::ROUGHNESS, roughness); + shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES2::Z_FLIP, false); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + glCopyTexSubImage2D(_cube_side_enum[i], lod, 0, 0, 0, 0, size, size); + } + + size >>= 1; + + mm_level--; + + lod++; + } + + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_SOURCE_PANORAMA, false); + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::USE_DIRECT_WRITE, false); + + // restore ranges + glActiveTexture(GL_TEXTURE2); //back to panorama + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE3); //back to panorama + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, 0); + + //reset flags on Sky Texture that may have changed + texture_set_flags(sky->panorama, texture->flags); + + // Framebuffer did its job. thank mr framebuffer + glActiveTexture(GL_TEXTURE0); //back to panorama + bind_framebuffer_system(); +} + +/* SHADER API */ + +RID RasterizerStorageGLES2::shader_allocate() { + Shader *shader = memnew(Shader); + shader->mode = GD_VS::SHADER_SPATIAL; + shader->shader = &scene->state.scene_shader; + RID rid = shader_owner.make_rid(shader); + _shader_make_dirty(shader); + shader->self = rid; + + return rid; +} + +void RasterizerStorageGLES2::shader_initialize(RID p_rid) { + // noop +} + +//RID RasterizerStorageGLES2::shader_create() { +// Shader *shader = memnew(Shader); +// shader->mode = GD_VS::SHADER_SPATIAL; +// shader->shader = &scene->state.scene_shader; +// RID rid = shader_owner.make_rid(shader); +// _shader_make_dirty(shader); +// shader->self = rid; + +// return rid; +//} + +void RasterizerStorageGLES2::_shader_make_dirty(Shader *p_shader) { + if (p_shader->dirty_list.in_list()) + return; + + _shader_dirty_list.add(&p_shader->dirty_list); +} + +void RasterizerStorageGLES2::shader_set_code(RID p_shader, const String &p_code) { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + + shader->code = p_code; + + String mode_string = ShaderLanguage::get_shader_type(p_code); + GD_VS::ShaderMode mode; + + if (mode_string == "canvas_item") + mode = GD_VS::SHADER_CANVAS_ITEM; + else if (mode_string == "particles") + mode = GD_VS::SHADER_PARTICLES; + else + mode = GD_VS::SHADER_SPATIAL; + + if (shader->custom_code_id && mode != shader->mode) { + shader->shader->free_custom_shader(shader->custom_code_id); + shader->custom_code_id = 0; + } + + shader->mode = mode; + + // TODO handle all shader types + if (mode == GD_VS::SHADER_CANVAS_ITEM) { + shader->shader = &canvas->state.canvas_shader; + + } else if (mode == GD_VS::SHADER_SPATIAL) { + shader->shader = &scene->state.scene_shader; + } else { + return; + } + + if (shader->custom_code_id == 0) { + shader->custom_code_id = shader->shader->create_custom_shader(); + } + + _shader_make_dirty(shader); +} + +String RasterizerStorageGLES2::shader_get_code(RID p_shader) const { + const Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND_V(!shader, ""); + + return shader->code; +} + +void RasterizerStorageGLES2::_update_shader(Shader *p_shader) const { + _shader_dirty_list.remove(&p_shader->dirty_list); + + p_shader->valid = false; + + p_shader->uniforms.clear(); + + if (p_shader->code == String()) { + return; //just invalid, but no error + } + + ShaderCompilerGLES2::GeneratedCode gen_code; + ShaderCompilerGLES2::IdentifierActions *actions = NULL; + + switch (p_shader->mode) { + case GD_VS::SHADER_CANVAS_ITEM: { + p_shader->canvas_item.light_mode = Shader::CanvasItem::LIGHT_MODE_NORMAL; + p_shader->canvas_item.blend_mode = Shader::CanvasItem::BLEND_MODE_MIX; + + p_shader->canvas_item.uses_screen_texture = false; + p_shader->canvas_item.uses_screen_uv = false; + p_shader->canvas_item.uses_time = false; + p_shader->canvas_item.uses_modulate = false; + p_shader->canvas_item.uses_color = false; + p_shader->canvas_item.uses_vertex = false; + p_shader->canvas_item.batch_flags = 0; + + p_shader->canvas_item.uses_world_matrix = false; + p_shader->canvas_item.uses_extra_matrix = false; + p_shader->canvas_item.uses_projection_matrix = false; + p_shader->canvas_item.uses_instance_custom = false; + + shaders.actions_canvas.render_mode_values["blend_add"] = Pair(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_ADD); + shaders.actions_canvas.render_mode_values["blend_mix"] = Pair(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MIX); + shaders.actions_canvas.render_mode_values["blend_sub"] = Pair(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_SUB); + shaders.actions_canvas.render_mode_values["blend_mul"] = Pair(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MUL); + shaders.actions_canvas.render_mode_values["blend_premul_alpha"] = Pair(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_PMALPHA); + + shaders.actions_canvas.render_mode_values["unshaded"] = Pair(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_UNSHADED); + shaders.actions_canvas.render_mode_values["light_only"] = Pair(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY); + + shaders.actions_canvas.usage_flag_pointers["SCREEN_UV"] = &p_shader->canvas_item.uses_screen_uv; + shaders.actions_canvas.usage_flag_pointers["SCREEN_PIXEL_SIZE"] = &p_shader->canvas_item.uses_screen_uv; + shaders.actions_canvas.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->canvas_item.uses_screen_texture; + shaders.actions_canvas.usage_flag_pointers["TIME"] = &p_shader->canvas_item.uses_time; + shaders.actions_canvas.usage_flag_pointers["MODULATE"] = &p_shader->canvas_item.uses_modulate; + shaders.actions_canvas.usage_flag_pointers["COLOR"] = &p_shader->canvas_item.uses_color; + + shaders.actions_canvas.usage_flag_pointers["VERTEX"] = &p_shader->canvas_item.uses_vertex; + + shaders.actions_canvas.usage_flag_pointers["WORLD_MATRIX"] = &p_shader->canvas_item.uses_world_matrix; + shaders.actions_canvas.usage_flag_pointers["EXTRA_MATRIX"] = &p_shader->canvas_item.uses_extra_matrix; + shaders.actions_canvas.usage_flag_pointers["PROJECTION_MATRIX"] = &p_shader->canvas_item.uses_projection_matrix; + shaders.actions_canvas.usage_flag_pointers["INSTANCE_CUSTOM"] = &p_shader->canvas_item.uses_instance_custom; + + actions = &shaders.actions_canvas; + actions->uniforms = &p_shader->uniforms; + } break; + + case GD_VS::SHADER_SPATIAL: { + p_shader->spatial.blend_mode = Shader::Spatial::BLEND_MODE_MIX; + p_shader->spatial.depth_draw_mode = Shader::Spatial::DEPTH_DRAW_OPAQUE; + p_shader->spatial.cull_mode = Shader::Spatial::CULL_MODE_BACK; + p_shader->spatial.uses_alpha = false; + p_shader->spatial.uses_alpha_scissor = false; + p_shader->spatial.uses_discard = false; + p_shader->spatial.unshaded = false; + p_shader->spatial.no_depth_test = false; + p_shader->spatial.uses_sss = false; + p_shader->spatial.uses_time = false; + p_shader->spatial.uses_vertex_lighting = false; + p_shader->spatial.uses_screen_texture = false; + p_shader->spatial.uses_depth_texture = false; + p_shader->spatial.uses_vertex = false; + p_shader->spatial.uses_tangent = false; + p_shader->spatial.uses_ensure_correct_normals = false; + p_shader->spatial.writes_modelview_or_projection = false; + p_shader->spatial.uses_world_coordinates = false; + + shaders.actions_scene.render_mode_values["blend_add"] = Pair(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_ADD); + shaders.actions_scene.render_mode_values["blend_mix"] = Pair(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MIX); + shaders.actions_scene.render_mode_values["blend_sub"] = Pair(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_SUB); + shaders.actions_scene.render_mode_values["blend_mul"] = Pair(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MUL); + + shaders.actions_scene.render_mode_values["depth_draw_opaque"] = Pair(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_OPAQUE); + shaders.actions_scene.render_mode_values["depth_draw_always"] = Pair(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALWAYS); + shaders.actions_scene.render_mode_values["depth_draw_never"] = Pair(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_NEVER); + shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"] = Pair(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS); + + shaders.actions_scene.render_mode_values["cull_front"] = Pair(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_FRONT); + shaders.actions_scene.render_mode_values["cull_back"] = Pair(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_BACK); + shaders.actions_scene.render_mode_values["cull_disabled"] = Pair(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_DISABLED); + + shaders.actions_scene.render_mode_flags["unshaded"] = &p_shader->spatial.unshaded; + shaders.actions_scene.render_mode_flags["depth_test_disable"] = &p_shader->spatial.no_depth_test; + + shaders.actions_scene.render_mode_flags["vertex_lighting"] = &p_shader->spatial.uses_vertex_lighting; + + shaders.actions_scene.render_mode_flags["world_vertex_coords"] = &p_shader->spatial.uses_world_coordinates; + + shaders.actions_scene.render_mode_flags["ensure_correct_normals"] = &p_shader->spatial.uses_ensure_correct_normals; + + shaders.actions_scene.usage_flag_pointers["ALPHA"] = &p_shader->spatial.uses_alpha; + shaders.actions_scene.usage_flag_pointers["ALPHA_SCISSOR"] = &p_shader->spatial.uses_alpha_scissor; + + shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"] = &p_shader->spatial.uses_sss; + shaders.actions_scene.usage_flag_pointers["DISCARD"] = &p_shader->spatial.uses_discard; + shaders.actions_scene.usage_flag_pointers["SCREEN_TEXTURE"] = &p_shader->spatial.uses_screen_texture; + shaders.actions_scene.usage_flag_pointers["DEPTH_TEXTURE"] = &p_shader->spatial.uses_depth_texture; + shaders.actions_scene.usage_flag_pointers["TIME"] = &p_shader->spatial.uses_time; + + // Use of any of these BUILTINS indicate the need for transformed tangents. + // This is needed to know when to transform tangents in software skinning. + shaders.actions_scene.usage_flag_pointers["TANGENT"] = &p_shader->spatial.uses_tangent; + shaders.actions_scene.usage_flag_pointers["NORMALMAP"] = &p_shader->spatial.uses_tangent; + + shaders.actions_scene.write_flag_pointers["MODELVIEW_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection; + shaders.actions_scene.write_flag_pointers["PROJECTION_MATRIX"] = &p_shader->spatial.writes_modelview_or_projection; + shaders.actions_scene.write_flag_pointers["VERTEX"] = &p_shader->spatial.uses_vertex; + + actions = &shaders.actions_scene; + actions->uniforms = &p_shader->uniforms; + + if (p_shader->spatial.uses_screen_texture && p_shader->spatial.uses_depth_texture) { + ERR_PRINT_ONCE("Using both SCREEN_TEXTURE and DEPTH_TEXTURE is not supported in GLES2"); + } + + if (p_shader->spatial.uses_depth_texture && !config.support_depth_texture) { + ERR_PRINT_ONCE("Using DEPTH_TEXTURE is not permitted on this hardware, operation will fail."); + } + } break; + + default: { + return; + } break; + } + + Error err = shaders.compiler.compile(p_shader->mode, p_shader->code, actions, p_shader->path, gen_code); + if (err != OK) { + return; + } + + p_shader->shader->set_custom_shader_code(p_shader->custom_code_id, gen_code.vertex, gen_code.vertex_global, gen_code.fragment, gen_code.light, gen_code.fragment_global, gen_code.uniforms, gen_code.texture_uniforms, gen_code.custom_defines); + + p_shader->texture_count = gen_code.texture_uniforms.size(); + p_shader->texture_hints = gen_code.texture_hints; + + p_shader->uses_vertex_time = gen_code.uses_vertex_time; + p_shader->uses_fragment_time = gen_code.uses_fragment_time; + + // some logic for batching + if (p_shader->mode == GD_VS::SHADER_CANVAS_ITEM) { + if (p_shader->canvas_item.uses_modulate | p_shader->canvas_item.uses_color) { + p_shader->canvas_item.batch_flags |= RasterizerStorageCommon::PREVENT_COLOR_BAKING; + } + if (p_shader->canvas_item.uses_vertex) { + p_shader->canvas_item.batch_flags |= RasterizerStorageCommon::PREVENT_VERTEX_BAKING; + } + if (p_shader->canvas_item.uses_world_matrix | p_shader->canvas_item.uses_extra_matrix | p_shader->canvas_item.uses_projection_matrix | p_shader->canvas_item.uses_instance_custom) { + p_shader->canvas_item.batch_flags |= RasterizerStorageCommon::PREVENT_ITEM_JOINING; + } + } + + p_shader->shader->set_custom_shader(p_shader->custom_code_id); + p_shader->shader->bind(); + + // cache uniform locations + + for (SelfList *E = p_shader->materials.first(); E; E = E->next()) { + _material_make_dirty(E->self()); + } + + p_shader->valid = true; + p_shader->version++; +} + +void RasterizerStorageGLES2::update_dirty_shaders() { + while (_shader_dirty_list.first()) { + _update_shader(_shader_dirty_list.first()->self()); + } +} + +void RasterizerStorageGLES2::shader_get_param_list(RID p_shader, List *p_param_list) const { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + + if (shader->dirty_list.in_list()) { + _update_shader(shader); + } + + Map order; + + for (Map::Element *E = shader->uniforms.front(); E; E = E->next()) { + if (E->get().texture_order >= 0) { + order[E->get().texture_order + 100000] = E->key(); + } else { + order[E->get().order] = E->key(); + } + } + + for (Map::Element *E = order.front(); E; E = E->next()) { + PropertyInfo pi; + ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[E->get()]; + + pi.name = E->get(); + + switch (u.type) { + case ShaderLanguage::TYPE_VOID: { + pi.type = Variant::NIL; + } break; + + case ShaderLanguage::TYPE_BOOL: { + pi.type = Variant::BOOL; + } break; + + // bool vectors + case ShaderLanguage::TYPE_BVEC2: { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y"; + } break; + case ShaderLanguage::TYPE_BVEC3: { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y,z"; + } break; + case ShaderLanguage::TYPE_BVEC4: { + pi.type = Variant::INT; + pi.hint = PROPERTY_HINT_FLAGS; + pi.hint_string = "x,y,z,w"; + } break; + + // int stuff + case ShaderLanguage::TYPE_UINT: + case ShaderLanguage::TYPE_INT: { + pi.type = Variant::INT; + + if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { + pi.hint = PROPERTY_HINT_RANGE; + pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]); + } + } break; + + case ShaderLanguage::TYPE_IVEC2: + case ShaderLanguage::TYPE_UVEC2: + case ShaderLanguage::TYPE_IVEC3: + case ShaderLanguage::TYPE_UVEC3: + case ShaderLanguage::TYPE_IVEC4: + case ShaderLanguage::TYPE_UVEC4: { + // not sure what this should be in godot 4 + // pi.type = Variant::POOL_INT_ARRAY; + pi.type = Variant::PACKED_INT32_ARRAY; + } break; + + case ShaderLanguage::TYPE_FLOAT: { + pi.type = Variant::FLOAT; + if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { + pi.hint = PROPERTY_HINT_RANGE; + pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]); + } + } break; + + case ShaderLanguage::TYPE_VEC2: { + pi.type = Variant::VECTOR2; + } break; + case ShaderLanguage::TYPE_VEC3: { + pi.type = Variant::VECTOR3; + } break; + + case ShaderLanguage::TYPE_VEC4: { + if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { + pi.type = Variant::COLOR; + } else { + pi.type = Variant::PLANE; + } + } break; + + case ShaderLanguage::TYPE_MAT2: { + pi.type = Variant::TRANSFORM2D; + } break; + + case ShaderLanguage::TYPE_MAT3: { + pi.type = Variant::BASIS; + } break; + + case ShaderLanguage::TYPE_MAT4: { + pi.type = Variant::TRANSFORM3D; + } break; + + case ShaderLanguage::TYPE_SAMPLER2D: + // case ShaderLanguage::TYPE_SAMPLEREXT: + case ShaderLanguage::TYPE_ISAMPLER2D: + case ShaderLanguage::TYPE_USAMPLER2D: { + pi.type = Variant::OBJECT; + pi.hint = PROPERTY_HINT_RESOURCE_TYPE; + pi.hint_string = "Texture"; + } break; + + case ShaderLanguage::TYPE_SAMPLERCUBE: { + pi.type = Variant::OBJECT; + pi.hint = PROPERTY_HINT_RESOURCE_TYPE; + pi.hint_string = "CubeMap"; + } break; + + case ShaderLanguage::TYPE_SAMPLER2DARRAY: + case ShaderLanguage::TYPE_ISAMPLER2DARRAY: + case ShaderLanguage::TYPE_USAMPLER2DARRAY: + case ShaderLanguage::TYPE_SAMPLER3D: + case ShaderLanguage::TYPE_ISAMPLER3D: + case ShaderLanguage::TYPE_USAMPLER3D: { + // Not implemented in GLES2 + } break; + // new for godot 4 + case ShaderLanguage::TYPE_SAMPLERCUBEARRAY: + case ShaderLanguage::TYPE_STRUCT: + case ShaderLanguage::TYPE_MAX: { + } break; + } + + p_param_list->push_back(pi); + } +} + +void RasterizerStorageGLES2::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + ERR_FAIL_COND(p_texture.is_valid() && !texture_owner.owns(p_texture)); + + if (p_texture.is_valid()) { + shader->default_textures[p_name] = p_texture; + } else { + shader->default_textures.erase(p_name); + } + + _shader_make_dirty(shader); +} + +RID RasterizerStorageGLES2::shader_get_default_texture_param(RID p_shader, const StringName &p_name) const { + const Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND_V(!shader, RID()); + + const Map::Element *E = shader->default_textures.find(p_name); + + if (!E) { + return RID(); + } + + return E->get(); +} + +void RasterizerStorageGLES2::shader_add_custom_define(RID p_shader, const String &p_define) { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + + shader->shader->add_custom_define(p_define); + + _shader_make_dirty(shader); +} + +void RasterizerStorageGLES2::shader_get_custom_defines(RID p_shader, Vector *p_defines) const { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + + shader->shader->get_custom_defines(p_defines); +} + +void RasterizerStorageGLES2::shader_remove_custom_define(RID p_shader, const String &p_define) { + Shader *shader = shader_owner.getornull(p_shader); + ERR_FAIL_COND(!shader); + + shader->shader->remove_custom_define(p_define); + + _shader_make_dirty(shader); +} + +/* COMMON MATERIAL API */ + +void RasterizerStorageGLES2::_material_make_dirty(Material *p_material) const { + if (p_material->dirty_list.in_list()) + return; + + _material_dirty_list.add(&p_material->dirty_list); +} + +RID RasterizerStorageGLES2::material_allocate() { + Material *material = memnew(Material); + return material_owner.make_rid(material); +} + +void RasterizerStorageGLES2::material_initialize(RID p_rid) { +} + +//RID RasterizerStorageGLES2::material_create() { +// Material *material = memnew(Material); + +// return material_owner.make_rid(material); +//} + +void RasterizerStorageGLES2::material_set_shader(RID p_material, RID p_shader) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + Shader *shader = shader_owner.getornull(p_shader); + + if (material->shader) { + // if a shader is present, remove the old shader + material->shader->materials.remove(&material->list); + } + + material->shader = shader; + + if (shader) { + shader->materials.add(&material->list); + } + + _material_make_dirty(material); +} + +RID RasterizerStorageGLES2::material_get_shader(RID p_material) const { + const Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, RID()); + + if (material->shader) { + return material->shader->self; + } + + return RID(); +} + +void RasterizerStorageGLES2::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + if (p_value.get_type() == Variant::NIL) { + material->params.erase(p_param); + } else { + material->params[p_param] = p_value; + } + + _material_make_dirty(material); +} + +Variant RasterizerStorageGLES2::material_get_param(RID p_material, const StringName &p_param) const { + const Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, RID()); + + if (material->params.has(p_param)) { + return material->params[p_param]; + } + + return material_get_param_default(p_material, p_param); +} + +Variant RasterizerStorageGLES2::material_get_param_default(RID p_material, const StringName &p_param) const { + const Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, Variant()); + + if (material->shader) { + if (material->shader->uniforms.has(p_param)) { + ShaderLanguage::ShaderNode::Uniform uniform = material->shader->uniforms[p_param]; + Vector default_value = uniform.default_value; + return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint); + } + } + return Variant(); +} + +void RasterizerStorageGLES2::material_set_line_width(RID p_material, float p_width) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + material->line_width = p_width; +} + +void RasterizerStorageGLES2::material_set_next_pass(RID p_material, RID p_next_material) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + material->next_pass = p_next_material; +} + +bool RasterizerStorageGLES2::material_is_animated(RID p_material) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, false); + if (material->dirty_list.in_list()) { + _update_material(material); + } + + bool animated = material->is_animated_cache; + if (!animated && material->next_pass.is_valid()) { + animated = material_is_animated(material->next_pass); + } + return animated; +} + +bool RasterizerStorageGLES2::material_casts_shadows(RID p_material) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, false); + if (material->dirty_list.in_list()) { + _update_material(material); + } + + bool casts_shadows = material->can_cast_shadow_cache; + + if (!casts_shadows && material->next_pass.is_valid()) { + casts_shadows = material_casts_shadows(material->next_pass); + } + + return casts_shadows; +} + +bool RasterizerStorageGLES2::material_uses_tangents(RID p_material) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, false); + + if (!material->shader) { + return false; + } + + if (material->shader->dirty_list.in_list()) { + _update_shader(material->shader); + } + + return material->shader->spatial.uses_tangent; +} + +bool RasterizerStorageGLES2::material_uses_ensure_correct_normals(RID p_material) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND_V(!material, false); + + if (!material->shader) { + return false; + } + + if (material->shader->dirty_list.in_list()) { + _update_shader(material->shader); + } + + return material->shader->spatial.uses_ensure_correct_normals; +} + +void RasterizerStorageGLES2::material_add_instance_owner(RID p_material, DependencyTracker *p_instance) { + /* + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + Map::Element *E = material->instance_owners.find(p_instance); + if (E) { + E->get()++; + } else { + material->instance_owners[p_instance] = 1; + } +*/ +} + +void RasterizerStorageGLES2::material_remove_instance_owner(RID p_material, DependencyTracker *p_instance) { + /* + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + Map::Element *E = material->instance_owners.find(p_instance); + ERR_FAIL_COND(!E); + + E->get()--; + + if (E->get() == 0) { + material->instance_owners.erase(E); + } +*/ +} + +void RasterizerStorageGLES2::material_set_render_priority(RID p_material, int priority) { + ERR_FAIL_COND(priority < GD_VS::MATERIAL_RENDER_PRIORITY_MIN); + ERR_FAIL_COND(priority > GD_VS::MATERIAL_RENDER_PRIORITY_MAX); + + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + material->render_priority = priority; +} + +void RasterizerStorageGLES2::_update_material(Material *p_material) { + if (p_material->dirty_list.in_list()) { + _material_dirty_list.remove(&p_material->dirty_list); + } + + if (p_material->shader && p_material->shader->dirty_list.in_list()) { + _update_shader(p_material->shader); + } + + if (p_material->shader && !p_material->shader->valid) { + return; + } + + { + bool can_cast_shadow = false; + bool is_animated = false; + + if (p_material->shader && p_material->shader->mode == GD_VS::SHADER_SPATIAL) { + if (p_material->shader->spatial.blend_mode == Shader::Spatial::BLEND_MODE_MIX && + (!p_material->shader->spatial.uses_alpha || p_material->shader->spatial.depth_draw_mode == Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) { + can_cast_shadow = true; + } + + if (p_material->shader->spatial.uses_discard && p_material->shader->uses_fragment_time) { + is_animated = true; + } + + if (p_material->shader->spatial.uses_vertex && p_material->shader->uses_vertex_time) { + is_animated = true; + } + + if (can_cast_shadow != p_material->can_cast_shadow_cache || is_animated != p_material->is_animated_cache) { + p_material->can_cast_shadow_cache = can_cast_shadow; + p_material->is_animated_cache = is_animated; + + /* + for (Map::Element *E = p_material->geometry_owners.front(); E; E = E->next()) { + E->key()->material_changed_notify(); + } + + for (Map::Element *E = p_material->instance_owners.front(); E; E = E->next()) { + E->key()->base_changed(false, true); + } + */ + } + } + } + + // uniforms and other things will be set in the use_material method in ShaderGLES2 + + if (p_material->shader && p_material->shader->texture_count > 0) { + p_material->textures.resize(p_material->shader->texture_count); + + for (Map::Element *E = p_material->shader->uniforms.front(); E; E = E->next()) { + if (E->get().texture_order < 0) + continue; // not a texture, does not go here + + RID texture; + + Map::Element *V = p_material->params.find(E->key()); + + if (V) { + texture = V->get(); + } + + if (!texture.is_valid()) { + Map::Element *W = p_material->shader->default_textures.find(E->key()); + + if (W) { + texture = W->get(); + } + } + + p_material->textures.write[E->get().texture_order] = Pair(E->key(), texture); + } + } else { + p_material->textures.clear(); + } +} +/* +void RasterizerStorageGLES2::_material_add_geometry(RID p_material, Geometry *p_geometry) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + Map::Element *I = material->geometry_owners.find(p_geometry); + + if (I) { + I->get()++; + } else { + material->geometry_owners[p_geometry] = 1; + } +} + +void RasterizerStorageGLES2::_material_remove_geometry(RID p_material, Geometry *p_geometry) { + Material *material = material_owner.getornull(p_material); + ERR_FAIL_COND(!material); + + Map::Element *I = material->geometry_owners.find(p_geometry); + ERR_FAIL_COND(!I); + + I->get()--; + + if (I->get() == 0) { + material->geometry_owners.erase(I); + } +} +*/ +void RasterizerStorageGLES2::update_dirty_materials() { + while (_material_dirty_list.first()) { + Material *material = _material_dirty_list.first()->self(); + _update_material(material); + } +} + +/* RENDER TARGET */ + +void RasterizerStorageGLES2::_set_current_render_target(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + + // FTODO + // if (!p_render_target.is_valid() && storage->frame.current_rt && storage->frame.clear_request) { + // // pending clear request. Do that first. + // glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); + // glClearColor(storage->frame.clear_request_color.r, + // storage->frame.clear_request_color.g, + // storage->frame.clear_request_color.b, + // storage->frame.clear_request_color.a); + // glClear(GL_COLOR_BUFFER_BIT); + // } + + if (rt) { + if (rt->allocate_is_dirty) { + rt->allocate_is_dirty = false; + _render_target_allocate(rt); + } + + // if (p_render_target.is_valid()) { + // RasterizerStorageGLES2::RenderTarget *rt = storage.render_target_owner.getornull(p_render_target); + frame.current_rt = rt; + ERR_FAIL_COND(!rt); + frame.clear_request = false; + + glViewport(0, 0, rt->width, rt->height); + + // print_line("_set_current_render_target w " + itos(rt->width) + " h " + itos(rt->height)); + + _dims.rt_width = rt->width; + _dims.rt_height = rt->height; + _dims.win_width = rt->width; + _dims.win_height = rt->height; + + } else { + frame.current_rt = NULL; + frame.clear_request = false; + // FTODO + // glViewport(0, 0, OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height); + bind_framebuffer_system(); + } +} + +void RasterizerStorageGLES2::_render_target_allocate(RenderTarget *rt) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + // do not allocate a render target with no size + if (rt->width <= 0 || rt->height <= 0) + return; + + // do not allocate a render target that is attached to the screen + if (rt->flags[RENDER_TARGET_DIRECT_TO_SCREEN]) { + rt->fbo = RasterizerStorageGLES2::system_fbo; + return; + } + + GLuint color_internal_format; + GLuint color_format; + GLuint color_type = GL_UNSIGNED_BYTE; + Image::Format image_format; + + if (rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { +#ifdef GLES_OVER_GL + color_internal_format = GL_RGBA8; +#else + color_internal_format = GL_RGBA; +#endif + color_format = GL_RGBA; + image_format = Image::FORMAT_RGBA8; + } else { +#ifdef GLES_OVER_GL + color_internal_format = GL_RGB8; +#else + color_internal_format = GL_RGB; +#endif + color_format = GL_RGB; + image_format = Image::FORMAT_RGB8; + } + + rt->used_dof_blur_near = false; + rt->mip_maps_allocated = false; + + { + /* Front FBO */ + + Texture *texture = texture_owner.getornull(rt->texture); + ERR_FAIL_COND(!texture); + + // framebuffer + glGenFramebuffers(1, &rt->fbo); + bind_framebuffer(rt->fbo); + + // color + glGenTextures(1, &rt->color); + glBindTexture(GL_TEXTURE_2D, rt->color); + + glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL); + + if (texture->flags & TEXTURE_FLAG_FILTER) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0); + + // depth + + if (config.support_depth_texture) { + glGenTextures(1, &rt->depth); + glBindTexture(GL_TEXTURE_2D, rt->depth); + glTexImage2D(GL_TEXTURE_2D, 0, config.depth_internalformat, rt->width, rt->height, 0, GL_DEPTH_COMPONENT, config.depth_type, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0); + } else { + glGenRenderbuffers(1, &rt->depth); + glBindRenderbuffer(GL_RENDERBUFFER, rt->depth); + + glRenderbufferStorage(GL_RENDERBUFFER, config.depth_buffer_internalformat, rt->width, rt->height); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth); + } + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + glDeleteFramebuffers(1, &rt->fbo); + if (config.support_depth_texture) { + glDeleteTextures(1, &rt->depth); + } else { + glDeleteRenderbuffers(1, &rt->depth); + } + + glDeleteTextures(1, &rt->color); + rt->fbo = 0; + rt->width = 0; + rt->height = 0; + rt->color = 0; + rt->depth = 0; + texture->tex_id = 0; + texture->active = false; + WARN_PRINT("Could not create framebuffer!!"); + return; + } + + texture->format = image_format; + texture->gl_format_cache = color_format; + texture->gl_type_cache = GL_UNSIGNED_BYTE; + texture->gl_internal_format_cache = color_internal_format; + texture->tex_id = rt->color; + texture->width = rt->width; + texture->alloc_width = rt->width; + texture->height = rt->height; + texture->alloc_height = rt->height; + texture->active = true; + + texture_set_flags(rt->texture, texture->flags); + } + + /* BACK FBO */ + /* For MSAA */ + +#ifndef JAVASCRIPT_ENABLED + if (rt->msaa >= GD_VS::VIEWPORT_MSAA_2X && rt->msaa <= GD_VS::VIEWPORT_MSAA_8X && config.multisample_supported) { + rt->multisample_active = true; + + static const int msaa_value[] = { 0, 2, 4, 8, 16 }; + int msaa = msaa_value[rt->msaa]; + + int max_samples = 0; + glGetIntegerv(GL_MAX_SAMPLES, &max_samples); + if (msaa > max_samples) { + WARN_PRINT("MSAA must be <= GL_MAX_SAMPLES, falling-back to GL_MAX_SAMPLES = " + itos(max_samples)); + msaa = max_samples; + } + + //regular fbo + glGenFramebuffers(1, &rt->multisample_fbo); + bind_framebuffer(rt->multisample_fbo); + + glGenRenderbuffers(1, &rt->multisample_depth); + glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_depth); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, config.depth_buffer_internalformat, rt->width, rt->height); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->multisample_depth); + +#if defined(GLES_OVER_GL) || defined(IPHONE_ENABLED) + + glGenRenderbuffers(1, &rt->multisample_color); + glBindRenderbuffer(GL_RENDERBUFFER, rt->multisample_color); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rt->multisample_color); +#elif ANDROID_ENABLED + // Render to a texture in android + glGenTextures(1, &rt->multisample_color); + glBindTexture(GL_TEXTURE_2D, rt->multisample_color); + + glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL); + + // multisample buffer is same size as front buffer, so just use nearest + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + glFramebufferTexture2DMultisample(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->multisample_color, 0, msaa); +#endif + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + // Delete allocated resources and default to no MSAA + WARN_PRINT_ONCE("Cannot allocate back framebuffer for MSAA"); + printf("err status: %x\n", status); + config.multisample_supported = false; + rt->multisample_active = false; + + glDeleteFramebuffers(1, &rt->multisample_fbo); + rt->multisample_fbo = 0; + + glDeleteRenderbuffers(1, &rt->multisample_depth); + rt->multisample_depth = 0; +#ifdef ANDROID_ENABLED + glDeleteTextures(1, &rt->multisample_color); +#else + glDeleteRenderbuffers(1, &rt->multisample_color); +#endif + rt->multisample_color = 0; + } + + glBindRenderbuffer(GL_RENDERBUFFER, 0); + bind_framebuffer(0); +#ifdef ANDROID_ENABLED + glBindTexture(GL_TEXTURE_2D, 0); +#endif + + } else +#endif // JAVASCRIPT_ENABLED + { + rt->multisample_active = false; + } + + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + // copy texscreen buffers + // if (!(rt->flags[RendererStorage::RENDER_TARGET_NO_SAMPLING])) { + if (true) { + glGenTextures(1, &rt->copy_screen_effect.color); + glBindTexture(GL_TEXTURE_2D, rt->copy_screen_effect.color); + + if (rt->flags[RendererStorage::RENDER_TARGET_TRANSPARENT]) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rt->width, rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + } else { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rt->width, rt->height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glGenFramebuffers(1, &rt->copy_screen_effect.fbo); + bind_framebuffer(rt->copy_screen_effect.fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->copy_screen_effect.color, 0); + + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + _render_target_clear(rt); + ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE); + } + } + + // Allocate mipmap chains for post_process effects + // if (!rt->flags[RendererStorage::RENDER_TARGET_NO_3D] && rt->width >= 2 && rt->height >= 2) { + if (rt->width >= 2 && rt->height >= 2) { + for (int i = 0; i < 2; i++) { + ERR_FAIL_COND(rt->mip_maps[i].sizes.size()); + int w = rt->width; + int h = rt->height; + + if (i > 0) { + w >>= 1; + h >>= 1; + } + + int level = 0; + int fb_w = w; + int fb_h = h; + + while (true) { + RenderTarget::MipMaps::Size mm; + mm.width = w; + mm.height = h; + rt->mip_maps[i].sizes.push_back(mm); + + w >>= 1; + h >>= 1; + + if (w < 2 || h < 2) + break; + + level++; + } + + GLsizei width = fb_w; + GLsizei height = fb_h; + + if (config.render_to_mipmap_supported) { + glGenTextures(1, &rt->mip_maps[i].color); + glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].color); + + for (int l = 0; l < level + 1; l++) { + glTexImage2D(GL_TEXTURE_2D, l, color_internal_format, width, height, 0, color_format, color_type, NULL); + width = MAX(1, (width / 2)); + height = MAX(1, (height / 2)); + } +#ifdef GLES_OVER_GL + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level); +#endif + } else { + // Can't render to specific levels of a mipmap in ES 2.0 or Webgl so create a texture for each level + for (int l = 0; l < level + 1; l++) { + glGenTextures(1, &rt->mip_maps[i].sizes.write[l].color); + glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].sizes[l].color); + glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, width, height, 0, color_format, color_type, NULL); + width = MAX(1, (width / 2)); + height = MAX(1, (height / 2)); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + } + + glDisable(GL_SCISSOR_TEST); + glColorMask(1, 1, 1, 1); + glDepthMask(GL_TRUE); + + for (int j = 0; j < rt->mip_maps[i].sizes.size(); j++) { + RenderTarget::MipMaps::Size &mm = rt->mip_maps[i].sizes.write[j]; + + glGenFramebuffers(1, &mm.fbo); + bind_framebuffer(mm.fbo); + + if (config.render_to_mipmap_supported) { + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->mip_maps[i].color, j); + } else { + glBindTexture(GL_TEXTURE_2D, rt->mip_maps[i].sizes[j].color); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->mip_maps[i].sizes[j].color, 0); + } + + bool used_depth = false; + if (j == 0 && i == 0) { //use always + if (config.support_depth_texture) { + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0); + } else { + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth); + } + used_depth = true; + } + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + WARN_PRINT_ONCE("Cannot allocate mipmaps for 3D post processing effects"); + bind_framebuffer_system(); + return; + } + + glClearColor(1.0, 0.0, 1.0, 0.0); + glClear(GL_COLOR_BUFFER_BIT); + if (used_depth) { + glClearDepth(1.0); + glClear(GL_DEPTH_BUFFER_BIT); + } + } + + rt->mip_maps[i].levels = level; + + if (config.render_to_mipmap_supported) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + } + rt->mip_maps_allocated = true; + } + + bind_framebuffer_system(); +} + +void RasterizerStorageGLES2::_render_target_clear(RenderTarget *rt) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + // there is nothing to clear when DIRECT_TO_SCREEN is used + if (rt->flags[RENDER_TARGET_DIRECT_TO_SCREEN]) + return; + + if (rt->fbo) { + glDeleteFramebuffers(1, &rt->fbo); + glDeleteTextures(1, &rt->color); + rt->fbo = 0; + } + + if (rt->external.fbo != 0) { + // free this + glDeleteFramebuffers(1, &rt->external.fbo); + + // clean up our texture + Texture *t = texture_owner.getornull(rt->external.texture); + t->alloc_height = 0; + t->alloc_width = 0; + t->width = 0; + t->height = 0; + t->active = false; + texture_owner.free(rt->external.texture); + memdelete(t); + + rt->external.fbo = 0; + } + + if (rt->depth) { + if (config.support_depth_texture) { + glDeleteTextures(1, &rt->depth); + } else { + glDeleteRenderbuffers(1, &rt->depth); + } + + rt->depth = 0; + } + + Texture *tex = texture_owner.getornull(rt->texture); + tex->alloc_height = 0; + tex->alloc_width = 0; + tex->width = 0; + tex->height = 0; + tex->active = false; + + if (rt->copy_screen_effect.color) { + glDeleteFramebuffers(1, &rt->copy_screen_effect.fbo); + rt->copy_screen_effect.fbo = 0; + + glDeleteTextures(1, &rt->copy_screen_effect.color); + rt->copy_screen_effect.color = 0; + } + + for (int i = 0; i < 2; i++) { + if (rt->mip_maps[i].sizes.size()) { + for (int j = 0; j < rt->mip_maps[i].sizes.size(); j++) { + glDeleteFramebuffers(1, &rt->mip_maps[i].sizes[j].fbo); + glDeleteTextures(1, &rt->mip_maps[i].sizes[j].color); + } + + glDeleteTextures(1, &rt->mip_maps[i].color); + rt->mip_maps[i].sizes.clear(); + rt->mip_maps[i].levels = 0; + rt->mip_maps[i].color = 0; + } + } + + if (rt->multisample_active) { + glDeleteFramebuffers(1, &rt->multisample_fbo); + rt->multisample_fbo = 0; + + glDeleteRenderbuffers(1, &rt->multisample_depth); + rt->multisample_depth = 0; +#ifdef ANDROID_ENABLED + glDeleteTextures(1, &rt->multisample_color); +#else + glDeleteRenderbuffers(1, &rt->multisample_color); +#endif + rt->multisample_color = 0; + } +} + +RID RasterizerStorageGLES2::render_target_create() { +#ifdef GLES2_DISABLE_RENDER_TARGETS +// return RID(); +#endif + + RenderTarget *rt = memnew(RenderTarget); + Texture *t = memnew(Texture); + + t->type = GD_RD::TEXTURE_TYPE_2D; + t->flags = 0; + t->width = 0; + t->height = 0; + t->alloc_height = 0; + t->alloc_width = 0; + t->format = Image::FORMAT_R8; + t->target = GL_TEXTURE_2D; + t->gl_format_cache = 0; + t->gl_internal_format_cache = 0; + t->gl_type_cache = 0; + t->data_size = 0; + t->total_data_size = 0; + t->ignore_mipmaps = false; + t->compressed = false; + t->mipmaps = 1; + t->active = true; + t->tex_id = 0; + t->render_target = rt; + + rt->texture = texture_owner.make_rid(t); + return render_target_owner.make_rid(rt); +} + +void RasterizerStorageGLES2::render_target_set_position(RID p_render_target, int p_x, int p_y) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + rt->x = p_x; + rt->y = p_y; +} + +void RasterizerStorageGLES2::render_target_set_size(RID p_render_target, int p_width, int p_height, uint32_t p_view_count) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + if (p_width == rt->width && p_height == rt->height) + return; + + _render_target_clear(rt); + + rt->width = p_width; + rt->height = p_height; + + // print_line("render_target_set_size " + itos(p_render_target.get_id()) + ", w " + itos(p_width) + " h " + itos(p_height)); + + rt->allocate_is_dirty = true; + //_render_target_allocate(rt); +} + +RID RasterizerStorageGLES2::render_target_get_texture(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return RID(); +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND_V(!rt, RID()); + + if (rt->external.fbo == 0) { + return rt->texture; + } else { + return rt->external.texture; + } +} + +void RasterizerStorageGLES2::render_target_set_external_texture(RID p_render_target, unsigned int p_texture_id) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + if (p_texture_id == 0) { + if (rt->external.fbo != 0) { + // free this + glDeleteFramebuffers(1, &rt->external.fbo); + + // and this + if (rt->external.depth != 0) { + glDeleteRenderbuffers(1, &rt->external.depth); + } + + // clean up our texture + Texture *t = texture_owner.getornull(rt->external.texture); + t->alloc_height = 0; + t->alloc_width = 0; + t->width = 0; + t->height = 0; + t->active = false; + texture_owner.free(rt->external.texture); + memdelete(t); + + rt->external.fbo = 0; + rt->external.color = 0; + rt->external.depth = 0; + } + } else { + Texture *t; + + if (rt->external.fbo == 0) { + // create our fbo + glGenFramebuffers(1, &rt->external.fbo); + bind_framebuffer(rt->external.fbo); + + // allocate a texture + t = memnew(Texture); + + t->type = GD_RD::TEXTURE_TYPE_2D; + t->flags = 0; + t->width = 0; + t->height = 0; + t->alloc_height = 0; + t->alloc_width = 0; + t->format = Image::FORMAT_RGBA8; + t->target = GL_TEXTURE_2D; + t->gl_format_cache = 0; + t->gl_internal_format_cache = 0; + t->gl_type_cache = 0; + t->data_size = 0; + t->compressed = false; + t->srgb = false; + t->total_data_size = 0; + t->ignore_mipmaps = false; + t->mipmaps = 1; + t->active = true; + t->tex_id = 0; + t->render_target = rt; + + rt->external.texture = texture_owner.make_rid(t); + + } else { + // bind our frame buffer + bind_framebuffer(rt->external.fbo); + + // find our texture + t = texture_owner.getornull(rt->external.texture); + } + + // set our texture + t->tex_id = p_texture_id; + rt->external.color = p_texture_id; + + // size shouldn't be different + t->width = rt->width; + t->height = rt->height; + t->alloc_height = rt->width; + t->alloc_width = rt->height; + + // Switch our texture on our frame buffer +#if ANDROID_ENABLED + if (rt->msaa >= GD_VS::VIEWPORT_MSAA_2X && rt->msaa <= GD_VS::VIEWPORT_MSAA_4X) { + // This code only applies to the Oculus Go and Oculus Quest. Due to the the tiled nature + // of the GPU we can do a single render pass by rendering directly into our texture chains + // texture and apply MSAA as we render. + + // On any other hardware these two modes are ignored and we do not have any MSAA, + // the normal MSAA modes need to be used to enable our two pass approach + + static const int msaa_value[] = { 2, 4 }; + int msaa = msaa_value[rt->msaa - GD_VS::VIEWPORT_MSAA_2X]; + + if (rt->external.depth == 0) { + // create a multisample depth buffer, we're not reusing Godots because Godot's didn't get created.. + glGenRenderbuffers(1, &rt->external.depth); + glBindRenderbuffer(GL_RENDERBUFFER, rt->external.depth); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, config.depth_buffer_internalformat, rt->width, rt->height); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->external.depth); + } + + // and set our external texture as the texture... + glFramebufferTexture2DMultisample(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, p_texture_id, 0, msaa); + + } else +#endif + { + // set our texture as the destination for our framebuffer + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, p_texture_id, 0); + + // seeing we're rendering into this directly, better also use our depth buffer, just use our existing one :) + if (config.support_depth_texture) { + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0); + } else { + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth); + } + } + + // check status and unbind + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + bind_framebuffer_system(); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + printf("framebuffer fail, status: %x\n", status); + } + + ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE); + } +} + +void RasterizerStorageGLES2::render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + // When setting DIRECT_TO_SCREEN, you need to clear before the value is set, but allocate after as + // those functions change how they operate depending on the value of DIRECT_TO_SCREEN + if (p_flag == RENDER_TARGET_DIRECT_TO_SCREEN && p_value != rt->flags[RENDER_TARGET_DIRECT_TO_SCREEN]) { + _render_target_clear(rt); + rt->flags[p_flag] = p_value; + _render_target_allocate(rt); + } + + rt->flags[p_flag] = p_value; + + switch (p_flag) { + case RENDER_TARGET_TRANSPARENT: + /* + case RENDER_TARGET_HDR: + case RENDER_TARGET_NO_3D: + case RENDER_TARGET_NO_SAMPLING: + case RENDER_TARGET_NO_3D_EFFECTS: */ + { + //must reset for these formats + _render_target_clear(rt); + _render_target_allocate(rt); + } + break; + default: { + } + } +} + +bool RasterizerStorageGLES2::render_target_was_used(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return false; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND_V(!rt, false); + + return rt->used_in_frame; +} + +void RasterizerStorageGLES2::render_target_clear_used(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + rt->used_in_frame = false; +} + +void RasterizerStorageGLES2::render_target_set_msaa(RID p_render_target, GD_VS::ViewportMSAA p_msaa) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + if (rt->msaa == p_msaa) + return; + + if (!config.multisample_supported) { + ERR_PRINT("MSAA not supported on this hardware."); + return; + } + + _render_target_clear(rt); + rt->msaa = p_msaa; + _render_target_allocate(rt); +} + +//RasterizerStorageGLES2::RenderTarget * RasterizerStorageGLES2::render_target_get(RID p_render_target) +//{ +// return render_target_owner.getornull(p_render_target); +//} + +void RasterizerStorageGLES2::render_target_set_use_fxaa(RID p_render_target, bool p_fxaa) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + rt->use_fxaa = p_fxaa; +} + +void RasterizerStorageGLES2::render_target_set_use_debanding(RID p_render_target, bool p_debanding) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + + if (p_debanding) { + WARN_PRINT_ONCE("Debanding is not supported in the GLES2 backend. Switch to the GLES3 backend and make sure HDR is enabled."); + } + + rt->use_debanding = p_debanding; +} + +void RasterizerStorageGLES2::render_target_request_clear(RID p_render_target, const Color &p_clear_color) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + rt->clear_requested = true; + rt->clear_color = p_clear_color; + + // ERR_FAIL_COND(!frame.current_rt); + // frame.clear_request = true; + // frame.clear_request_color = p_color; +} + +bool RasterizerStorageGLES2::render_target_is_clear_requested(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return false; +#endif + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND_V(!rt, false); + return rt->clear_requested; +} +Color RasterizerStorageGLES2::render_target_get_clear_request_color(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return Color(); +#endif + + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND_V(!rt, Color()); + return rt->clear_color; +} + +void RasterizerStorageGLES2::render_target_disable_clear_request(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + rt->clear_requested = false; +} + +void RasterizerStorageGLES2::render_target_do_clear_request(RID p_render_target) { +#ifdef GLES2_DISABLE_RENDER_TARGETS + return; +#endif + + // NEW for GLES... + // This is being called at the wrong time. Instead it will be performed + // at canvas begin + return; + + /* + RenderTarget *rt = render_target_owner.getornull(p_render_target); + ERR_FAIL_COND(!rt); + if (!rt->clear_requested) { + return; + } + + const Color &c = rt->clear_color; + + glClearColor(c.r, c.g, c.b, c.a); + // more bits? + glClear(GL_COLOR_BUFFER_BIT); + */ +} + +/* CANVAS SHADOW */ + +RID RasterizerStorageGLES2::canvas_light_shadow_buffer_create(int p_width) { + CanvasLightShadow *cls = memnew(CanvasLightShadow); + + if (p_width > config.max_texture_size) + p_width = config.max_texture_size; + + cls->size = p_width; + cls->height = 16; + + glActiveTexture(GL_TEXTURE0); + + glGenFramebuffers(1, &cls->fbo); + bind_framebuffer(cls->fbo); + + glGenRenderbuffers(1, &cls->depth); + glBindRenderbuffer(GL_RENDERBUFFER, cls->depth); + glRenderbufferStorage(GL_RENDERBUFFER, config.depth_buffer_internalformat, cls->size, cls->height); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, cls->depth); + + glGenTextures(1, &cls->distance); + glBindTexture(GL_TEXTURE_2D, cls->distance); + if (config.use_rgba_2d_shadows) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + } else { +#ifdef GLES_OVER_GL + glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, _RED_OES, GL_FLOAT, NULL); +#else + glTexImage2D(GL_TEXTURE_2D, 0, GL_FLOAT, cls->size, cls->height, 0, _RED_OES, GL_FLOAT, NULL); +#endif + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cls->distance, 0); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + //printf("errnum: %x\n",status); + bind_framebuffer_system(); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + memdelete(cls); + ERR_FAIL_COND_V(status != GL_FRAMEBUFFER_COMPLETE, RID()); + } + + return canvas_light_shadow_owner.make_rid(cls); +} + +/* LIGHT SHADOW MAPPING */ +/* + +RID RasterizerStorageGLES2::canvas_light_occluder_create() { + CanvasOccluder *co = memnew(CanvasOccluder); + co->index_id = 0; + co->vertex_id = 0; + co->len = 0; + + return canvas_occluder_owner.make_rid(co); +} + +void RasterizerStorageGLES2::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector &p_lines) { + CanvasOccluder *co = canvas_occluder_owner.get(p_occluder); + ERR_FAIL_COND(!co); + + co->lines = p_lines; + + if (p_lines.size() != co->len) { + if (co->index_id) + glDeleteBuffers(1, &co->index_id); + if (co->vertex_id) + glDeleteBuffers(1, &co->vertex_id); + + co->index_id = 0; + co->vertex_id = 0; + co->len = 0; + } + + if (p_lines.size()) { + PoolVector geometry; + PoolVector indices; + int lc = p_lines.size(); + + geometry.resize(lc * 6); + indices.resize(lc * 3); + + PoolVector::Write vw = geometry.write(); + PoolVector::Write iw = indices.write(); + + PoolVector::Read lr = p_lines.read(); + + const int POLY_HEIGHT = 16384; + + for (int i = 0; i < lc / 2; i++) { + vw[i * 12 + 0] = lr[i * 2 + 0].x; + vw[i * 12 + 1] = lr[i * 2 + 0].y; + vw[i * 12 + 2] = POLY_HEIGHT; + + vw[i * 12 + 3] = lr[i * 2 + 1].x; + vw[i * 12 + 4] = lr[i * 2 + 1].y; + vw[i * 12 + 5] = POLY_HEIGHT; + + vw[i * 12 + 6] = lr[i * 2 + 1].x; + vw[i * 12 + 7] = lr[i * 2 + 1].y; + vw[i * 12 + 8] = -POLY_HEIGHT; + + vw[i * 12 + 9] = lr[i * 2 + 0].x; + vw[i * 12 + 10] = lr[i * 2 + 0].y; + vw[i * 12 + 11] = -POLY_HEIGHT; + + iw[i * 6 + 0] = i * 4 + 0; + iw[i * 6 + 1] = i * 4 + 1; + iw[i * 6 + 2] = i * 4 + 2; + + iw[i * 6 + 3] = i * 4 + 2; + iw[i * 6 + 4] = i * 4 + 3; + iw[i * 6 + 5] = i * 4 + 0; + } + + //if same buffer len is being set, just use BufferSubData to avoid a pipeline flush + + if (!co->vertex_id) { + glGenBuffers(1, &co->vertex_id); + glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id); + glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(real_t), vw.ptr(), GL_STATIC_DRAW); + } else { + glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id); + glBufferSubData(GL_ARRAY_BUFFER, 0, lc * 6 * sizeof(real_t), vw.ptr()); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind + + if (!co->index_id) { + glGenBuffers(1, &co->index_id); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, lc * 3 * sizeof(uint16_t), iw.ptr(), GL_DYNAMIC_DRAW); + } else { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id); + glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, lc * 3 * sizeof(uint16_t), iw.ptr()); + } + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind + + co->len = lc; + } +} +*/ + +GD_VS::InstanceType RasterizerStorageGLES2::get_base_type(RID p_rid) const { + return GD_VS::INSTANCE_NONE; + + /* + if (mesh_owner.owns(p_rid)) { + return GD_VS::INSTANCE_MESH; + } else if (light_owner.owns(p_rid)) { + return GD_VS::INSTANCE_LIGHT; + } else if (multimesh_owner.owns(p_rid)) { + return GD_VS::INSTANCE_MULTIMESH; + } else if (immediate_owner.owns(p_rid)) { + return GD_VS::INSTANCE_IMMEDIATE; + } else if (reflection_probe_owner.owns(p_rid)) { + return GD_VS::INSTANCE_REFLECTION_PROBE; + } else if (lightmap_capture_data_owner.owns(p_rid)) { + return GD_VS::INSTANCE_LIGHTMAP_CAPTURE; + } else { + return GD_VS::INSTANCE_NONE; + } +*/ +} + +bool RasterizerStorageGLES2::free(RID p_rid) { + if (render_target_owner.owns(p_rid)) { + RenderTarget *rt = render_target_owner.getornull(p_rid); + _render_target_clear(rt); + + Texture *t = texture_owner.getornull(rt->texture); + if (t) { + texture_owner.free(rt->texture); + memdelete(t); + } + render_target_owner.free(p_rid); + memdelete(rt); + + return true; + } else if (texture_owner.owns(p_rid)) { + Texture *t = texture_owner.getornull(p_rid); + // can't free a render target texture + ERR_FAIL_COND_V(t->render_target, true); + + info.texture_mem -= t->total_data_size; + texture_owner.free(p_rid); + memdelete(t); + + return true; + } else if (sky_owner.owns(p_rid)) { + Sky *sky = sky_owner.getornull(p_rid); + sky_set_texture(p_rid, RID(), 256); + sky_owner.free(p_rid); + memdelete(sky); + + return true; + } else if (shader_owner.owns(p_rid)) { + Shader *shader = shader_owner.getornull(p_rid); + + if (shader->shader && shader->custom_code_id) { + shader->shader->free_custom_shader(shader->custom_code_id); + } + + if (shader->dirty_list.in_list()) { + _shader_dirty_list.remove(&shader->dirty_list); + } + + while (shader->materials.first()) { + Material *m = shader->materials.first()->self(); + + m->shader = NULL; + _material_make_dirty(m); + + shader->materials.remove(shader->materials.first()); + } + + shader_owner.free(p_rid); + memdelete(shader); + + return true; + } else if (material_owner.owns(p_rid)) { + Material *m = material_owner.getornull(p_rid); + + if (m->shader) { + m->shader->materials.remove(&m->list); + } + + /* + for (Map::Element *E = m->geometry_owners.front(); E; E = E->next()) { + Geometry *g = E->key(); + g->material = RID(); + } + + for (Map::Element *E = m->instance_owners.front(); E; E = E->next()) { + InstanceBaseDependency *ins = E->key(); + + if (ins->material_override == p_rid) { + ins->material_override = RID(); + } + + for (int i = 0; i < ins->materials.size(); i++) { + if (ins->materials[i] == p_rid) { + ins->materials.write[i] = RID(); + } + } + } +*/ + + material_owner.free(p_rid); + memdelete(m); + + return true; + + } else { + return false; + } + /* + } else if (skeleton_owner.owns(p_rid)) { + Skeleton *s = skeleton_owner.getornull(p_rid); + + if (s->update_list.in_list()) { + skeleton_update_list.remove(&s->update_list); + } + + for (Set::Element *E = s->instances.front(); E; E = E->next()) { + E->get()->skeleton = RID(); + } + + skeleton_allocate(p_rid, 0, false); + + if (s->tex_id) { + glDeleteTextures(1, &s->tex_id); + } + + skeleton_owner.free(p_rid); + memdelete(s); + + return true; + } else if (mesh_owner.owns(p_rid)) { + Mesh *mesh = mesh_owner.getornull(p_rid); + + mesh->instance_remove_deps(); + mesh_clear(p_rid); + + while (mesh->multimeshes.first()) { + MultiMesh *multimesh = mesh->multimeshes.first()->self(); + multimesh->mesh = RID(); + multimesh->dirty_aabb = true; + + mesh->multimeshes.remove(mesh->multimeshes.first()); + + if (!multimesh->update_list.in_list()) { + multimesh_update_list.add(&multimesh->update_list); + } + } + + mesh_owner.free(p_rid); + memdelete(mesh); + + return true; + } else if (multimesh_owner.owns(p_rid)) { + MultiMesh *multimesh = multimesh_owner.getornull(p_rid); + multimesh->instance_remove_deps(); + + if (multimesh->mesh.is_valid()) { + Mesh *mesh = mesh_owner.getornull(multimesh->mesh); + if (mesh) { + mesh->multimeshes.remove(&multimesh->mesh_list); + } + } + + multimesh_allocate(p_rid, 0, GD_VS::MULTIMESH_TRANSFORM_3D, GD_VS::MULTIMESH_COLOR_NONE); + + update_dirty_multimeshes(); + + multimesh_owner.free(p_rid); + memdelete(multimesh); + + return true; + } else if (immediate_owner.owns(p_rid)) { + Immediate *im = immediate_owner.getornull(p_rid); + im->instance_remove_deps(); + + immediate_owner.free(p_rid); + memdelete(im); + + return true; + } else if (light_owner.owns(p_rid)) { + Light *light = light_owner.getornull(p_rid); + light->instance_remove_deps(); + + light_owner.free(p_rid); + memdelete(light); + + return true; + } else if (reflection_probe_owner.owns(p_rid)) { + // delete the texture + ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_rid); + reflection_probe->instance_remove_deps(); + + reflection_probe_owner.free(p_rid); + memdelete(reflection_probe); + + return true; + } else if (lightmap_capture_data_owner.owns(p_rid)) { + // delete the texture + LightmapCapture *lightmap_capture = lightmap_capture_data_owner.getornull(p_rid); + lightmap_capture->instance_remove_deps(); + + lightmap_capture_data_owner.free(p_rid); + memdelete(lightmap_capture); + return true; + + } else if (canvas_occluder_owner.owns(p_rid)) { + CanvasOccluder *co = canvas_occluder_owner.getornull(p_rid); + if (co->index_id) + glDeleteBuffers(1, &co->index_id); + if (co->vertex_id) + glDeleteBuffers(1, &co->vertex_id); + + canvas_occluder_owner.free(p_rid); + memdelete(co); + + return true; + + } else if (canvas_light_shadow_owner.owns(p_rid)) { + CanvasLightShadow *cls = canvas_light_shadow_owner.getornull(p_rid); + glDeleteFramebuffers(1, &cls->fbo); + glDeleteRenderbuffers(1, &cls->depth); + glDeleteTextures(1, &cls->distance); + canvas_light_shadow_owner.free(p_rid); + memdelete(cls); + + return true; + */ +} + +bool RasterizerStorageGLES2::has_os_feature(const String &p_feature) const { + if (p_feature == "pvrtc") + return config.pvrtc_supported; + + if (p_feature == "s3tc") + return config.s3tc_supported; + + if (p_feature == "etc") + return config.etc1_supported; + + if (p_feature == "skinning_fallback") + return config.use_skeleton_software; + + return false; +} + +//////////////////////////////////////////// + +void RasterizerStorageGLES2::set_debug_generate_wireframes(bool p_generate) { +} + +//void RasterizerStorageGLES2::render_info_begin_capture() { +// info.snap = info.render; +//} + +//void RasterizerStorageGLES2::render_info_end_capture() { +// info.snap.object_count = info.render.object_count - info.snap.object_count; +// info.snap.draw_call_count = info.render.draw_call_count - info.snap.draw_call_count; +// info.snap.material_switch_count = info.render.material_switch_count - info.snap.material_switch_count; +// info.snap.surface_switch_count = info.render.surface_switch_count - info.snap.surface_switch_count; +// info.snap.shader_rebind_count = info.render.shader_rebind_count - info.snap.shader_rebind_count; +// info.snap.vertices_count = info.render.vertices_count - info.snap.vertices_count; +// info.snap._2d_item_count = info.render._2d_item_count - info.snap._2d_item_count; +// info.snap._2d_draw_call_count = info.render._2d_draw_call_count - info.snap._2d_draw_call_count; +//} + +//int RasterizerStorageGLES2::get_captured_render_info(GD_VS::RenderInfo p_info) { +// switch (p_info) { +// case GD_VS::INFO_OBJECTS_IN_FRAME: { +// return info.snap.object_count; +// } break; +// case GD_VS::INFO_VERTICES_IN_FRAME: { +// return info.snap.vertices_count; +// } break; +// case GD_VS::INFO_MATERIAL_CHANGES_IN_FRAME: { +// return info.snap.material_switch_count; +// } break; +// case GD_VS::INFO_SHADER_CHANGES_IN_FRAME: { +// return info.snap.shader_rebind_count; +// } break; +// case GD_VS::INFO_SURFACE_CHANGES_IN_FRAME: { +// return info.snap.surface_switch_count; +// } break; +// case GD_VS::INFO_DRAW_CALLS_IN_FRAME: { +// return info.snap.draw_call_count; +// } break; +// /* +// case GD_VS::INFO_2D_ITEMS_IN_FRAME: { +// return info.snap._2d_item_count; +// } break; +// case GD_VS::INFO_2D_DRAW_CALLS_IN_FRAME: { +// return info.snap._2d_draw_call_count; +// } break; +// */ +// default: { +// return get_render_info(p_info); +// } +// } +//} + +//int RasterizerStorageGLES2::get_render_info(GD_VS::RenderInfo p_info) { +// switch (p_info) { +// case GD_VS::INFO_OBJECTS_IN_FRAME: +// return info.render_final.object_count; +// case GD_VS::INFO_VERTICES_IN_FRAME: +// return info.render_final.vertices_count; +// case GD_VS::INFO_MATERIAL_CHANGES_IN_FRAME: +// return info.render_final.material_switch_count; +// case GD_VS::INFO_SHADER_CHANGES_IN_FRAME: +// return info.render_final.shader_rebind_count; +// case GD_VS::INFO_SURFACE_CHANGES_IN_FRAME: +// return info.render_final.surface_switch_count; +// case GD_VS::INFO_DRAW_CALLS_IN_FRAME: +// return info.render_final.draw_call_count; +// /* +// case GD_VS::INFO_2D_ITEMS_IN_FRAME: +// return info.render_final._2d_item_count; +// case GD_VS::INFO_2D_DRAW_CALLS_IN_FRAME: +// return info.render_final._2d_draw_call_count; +//*/ +// case GD_VS::INFO_USAGE_VIDEO_MEM_TOTAL: +// return 0; //no idea +// case GD_VS::INFO_VIDEO_MEM_USED: +// return info.vertex_mem + info.texture_mem; +// case GD_VS::INFO_TEXTURE_MEM_USED: +// return info.texture_mem; +// case GD_VS::INFO_VERTEX_MEM_USED: +// return info.vertex_mem; +// default: +// return 0; //no idea either +// } +//} + +String RasterizerStorageGLES2::get_video_adapter_name() const { + return (const char *)glGetString(GL_RENDERER); +} + +String RasterizerStorageGLES2::get_video_adapter_vendor() const { + return (const char *)glGetString(GL_VENDOR); +} + +void RasterizerStorageGLES2::initialize() { + RasterizerStorageGLES2::system_fbo = 0; + + { + const GLubyte *extension_string = glGetString(GL_EXTENSIONS); + + Vector extensions = String((const char *)extension_string).split(" "); + + for (int i = 0; i < extensions.size(); i++) { + config.extensions.insert(extensions[i]); + } + } + + // FTODO + config.keep_original_textures = true; // false + config.shrink_textures_x2 = false; + config.depth_internalformat = GL_DEPTH_COMPONENT; + config.depth_type = GL_UNSIGNED_INT; + +#ifdef GLES_OVER_GL + config.float_texture_supported = true; + config.s3tc_supported = true; + config.pvrtc_supported = false; + config.etc1_supported = false; + config.support_npot_repeat_mipmap = true; + config.depth_buffer_internalformat = GL_DEPTH_COMPONENT24; +#else + config.float_texture_supported = config.extensions.has("GL_ARB_texture_float") || config.extensions.has("GL_OES_texture_float"); + config.s3tc_supported = config.extensions.has("GL_EXT_texture_compression_s3tc") || config.extensions.has("WEBGL_compressed_texture_s3tc"); + config.etc1_supported = config.extensions.has("GL_OES_compressed_ETC1_RGB8_texture") || config.extensions.has("WEBGL_compressed_texture_etc1"); + config.pvrtc_supported = config.extensions.has("GL_IMG_texture_compression_pvrtc") || config.extensions.has("WEBGL_compressed_texture_pvrtc"); + config.support_npot_repeat_mipmap = config.extensions.has("GL_OES_texture_npot"); + +#ifdef JAVASCRIPT_ENABLED + // RenderBuffer internal format must be 16 bits in WebGL, + // but depth_texture should default to 32 always + // if the implementation doesn't support 32, it should just quietly use 16 instead + // https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/ + config.depth_buffer_internalformat = GL_DEPTH_COMPONENT16; + config.depth_type = GL_UNSIGNED_INT; +#else + // on mobile check for 24 bit depth support for RenderBufferStorage + if (config.extensions.has("GL_OES_depth24")) { + config.depth_buffer_internalformat = _DEPTH_COMPONENT24_OES; + config.depth_type = GL_UNSIGNED_INT; + } else { + config.depth_buffer_internalformat = GL_DEPTH_COMPONENT16; + config.depth_type = GL_UNSIGNED_SHORT; + } +#endif +#endif + +#ifndef GLES_OVER_GL + //Manually load extensions for android and ios + +#ifdef IPHONE_ENABLED + // appears that IPhone doesn't need to dlopen TODO: test this rigorously before removing + //void *gles2_lib = dlopen(NULL, RTLD_LAZY); + //glRenderbufferStorageMultisampleAPPLE = dlsym(gles2_lib, "glRenderbufferStorageMultisampleAPPLE"); + //glResolveMultisampleFramebufferAPPLE = dlsym(gles2_lib, "glResolveMultisampleFramebufferAPPLE"); +#elif ANDROID_ENABLED + + void *gles2_lib = dlopen("libGLESv2.so", RTLD_LAZY); + glRenderbufferStorageMultisampleEXT = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)dlsym(gles2_lib, "glRenderbufferStorageMultisampleEXT"); + glFramebufferTexture2DMultisampleEXT = (PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC)dlsym(gles2_lib, "glFramebufferTexture2DMultisampleEXT"); +#endif +#endif + + // Check for multisample support + config.multisample_supported = config.extensions.has("GL_EXT_framebuffer_multisample") || config.extensions.has("GL_EXT_multisampled_render_to_texture") || config.extensions.has("GL_APPLE_framebuffer_multisample"); + +#ifdef GLES_OVER_GL + //TODO: causes huge problems with desktop video drivers. Making false for now, needs to be true to render SCREEN_TEXTURE mipmaps + config.render_to_mipmap_supported = false; +#else + //check if mipmaps can be used for SCREEN_TEXTURE and Glow on Mobile and web platforms + config.render_to_mipmap_supported = config.extensions.has("GL_OES_fbo_render_mipmap") && config.extensions.has("GL_EXT_texture_lod"); +#endif + +#ifdef GLES_OVER_GL + config.use_rgba_2d_shadows = false; + config.support_depth_texture = true; + config.use_rgba_3d_shadows = false; + config.support_depth_cubemaps = true; +#else + config.use_rgba_2d_shadows = !(config.float_texture_supported && config.extensions.has("GL_EXT_texture_rg")); + config.support_depth_texture = config.extensions.has("GL_OES_depth_texture") || config.extensions.has("WEBGL_depth_texture"); + config.use_rgba_3d_shadows = !config.support_depth_texture; + config.support_depth_cubemaps = config.extensions.has("GL_OES_depth_texture_cube_map"); +#endif + +#ifdef GLES_OVER_GL + config.support_32_bits_indices = true; +#else + config.support_32_bits_indices = config.extensions.has("GL_OES_element_index_uint"); +#endif + +#ifdef GLES_OVER_GL + config.support_write_depth = true; +#elif defined(JAVASCRIPT_ENABLED) + config.support_write_depth = false; +#else + config.support_write_depth = config.extensions.has("GL_EXT_frag_depth"); +#endif + + config.support_half_float_vertices = true; +//every platform should support this except web, iOS has issues with their support, so add option to disable +#ifdef JAVASCRIPT_ENABLED + config.support_half_float_vertices = false; +#endif + bool disable_half_float = GLOBAL_GET("rendering/gles2/compatibility/disable_half_float"); + if (disable_half_float) { + config.support_half_float_vertices = false; + } + + config.rgtc_supported = config.extensions.has("GL_EXT_texture_compression_rgtc") || config.extensions.has("GL_ARB_texture_compression_rgtc") || config.extensions.has("EXT_texture_compression_rgtc"); + config.bptc_supported = config.extensions.has("GL_ARB_texture_compression_bptc") || config.extensions.has("EXT_texture_compression_bptc"); + + //determine formats for depth textures (or renderbuffers) + if (config.support_depth_texture) { + // Will use texture for depth + // have to manually see if we can create a valid framebuffer texture using UNSIGNED_INT, + // as there is no extension to test for this. + GLuint fbo; + glGenFramebuffers(1, &fbo); + bind_framebuffer(fbo); + GLuint depth; + glGenTextures(1, &depth); + glBindTexture(GL_TEXTURE_2D, depth); + glTexImage2D(GL_TEXTURE_2D, 0, config.depth_internalformat, 32, 32, 0, GL_DEPTH_COMPONENT, config.depth_type, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + bind_framebuffer_system(); + glDeleteFramebuffers(1, &fbo); + glBindTexture(GL_TEXTURE_2D, 0); + glDeleteTextures(1, &depth); + + if (status != GL_FRAMEBUFFER_COMPLETE) { + // If it fails, test to see if it supports a framebuffer texture using UNSIGNED_SHORT + // This is needed because many OSX devices don't support either UNSIGNED_INT or UNSIGNED_SHORT +#ifdef GLES_OVER_GL + config.depth_internalformat = GL_DEPTH_COMPONENT16; +#else + // OES_depth_texture extension only specifies GL_DEPTH_COMPONENT. + config.depth_internalformat = GL_DEPTH_COMPONENT; +#endif + config.depth_type = GL_UNSIGNED_SHORT; + + glGenFramebuffers(1, &fbo); + bind_framebuffer(fbo); + + glGenTextures(1, &depth); + glBindTexture(GL_TEXTURE_2D, depth); + glTexImage2D(GL_TEXTURE_2D, 0, config.depth_internalformat, 32, 32, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0); + + status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + //if it fails again depth textures aren't supported, use rgba shadows and renderbuffer for depth + config.support_depth_texture = false; + config.use_rgba_3d_shadows = true; + } + + bind_framebuffer_system(); + glDeleteFramebuffers(1, &fbo); + glBindTexture(GL_TEXTURE_2D, 0); + glDeleteTextures(1, &depth); + } + } + + //picky requirements for these + config.support_shadow_cubemaps = config.support_depth_texture && config.support_write_depth && config.support_depth_cubemaps; + + frame.count = 0; + frame.delta = 0; + frame.current_rt = NULL; + frame.clear_request = false; + + glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &config.max_vertex_texture_image_units); + glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &config.max_texture_image_units); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &config.max_texture_size); + + // the use skeleton software path should be used if either float texture is not supported, + // OR max_vertex_texture_image_units is zero + config.use_skeleton_software = (config.float_texture_supported == false) || (config.max_vertex_texture_image_units == 0); + + shaders.copy.init(); + shaders.cubemap_filter.init(); + bool ggx_hq = GLOBAL_GET("rendering/quality/reflections/high_quality_ggx"); + shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES2::LOW_QUALITY, !ggx_hq); + + { + // quad for copying stuff + + glGenBuffers(1, &resources.quadie); + glBindBuffer(GL_ARRAY_BUFFER, resources.quadie); + { + const float qv[16] = { + -1, + -1, + 0, + 0, + -1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + -1, + 1, + 0, + }; + + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + } + + { + //default textures + + glGenTextures(1, &resources.white_tex); + unsigned char whitetexdata[8 * 8 * 3]; + for (int i = 0; i < 8 * 8 * 3; i++) { + whitetexdata[i] = 255; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, resources.white_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata); + glGenerateMipmap(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + + glGenTextures(1, &resources.black_tex); + unsigned char blacktexdata[8 * 8 * 3]; + for (int i = 0; i < 8 * 8 * 3; i++) { + blacktexdata[i] = 0; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, resources.black_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, blacktexdata); + glGenerateMipmap(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + + glGenTextures(1, &resources.normal_tex); + unsigned char normaltexdata[8 * 8 * 3]; + for (int i = 0; i < 8 * 8 * 3; i += 3) { + normaltexdata[i + 0] = 128; + normaltexdata[i + 1] = 128; + normaltexdata[i + 2] = 255; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, resources.normal_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, normaltexdata); + glGenerateMipmap(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + + glGenTextures(1, &resources.aniso_tex); + unsigned char anisotexdata[8 * 8 * 3]; + for (int i = 0; i < 8 * 8 * 3; i += 3) { + anisotexdata[i + 0] = 255; + anisotexdata[i + 1] = 128; + anisotexdata[i + 2] = 0; + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, resources.aniso_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, anisotexdata); + glGenerateMipmap(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + } + + // skeleton buffer + { + resources.skeleton_transform_buffer_size = 0; + glGenBuffers(1, &resources.skeleton_transform_buffer); + } + + // radical inverse vdc cache texture + // used for cubemap filtering + if (true /*||config.float_texture_supported*/) { //uint8 is similar and works everywhere + glGenTextures(1, &resources.radical_inverse_vdc_cache_tex); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, resources.radical_inverse_vdc_cache_tex); + + uint8_t radical_inverse[512]; + + for (uint32_t i = 0; i < 512; i++) { + uint32_t bits = i; + + bits = (bits << 16) | (bits >> 16); + bits = ((bits & 0x55555555) << 1) | ((bits & 0xAAAAAAAA) >> 1); + bits = ((bits & 0x33333333) << 2) | ((bits & 0xCCCCCCCC) >> 2); + bits = ((bits & 0x0F0F0F0F) << 4) | ((bits & 0xF0F0F0F0) >> 4); + bits = ((bits & 0x00FF00FF) << 8) | ((bits & 0xFF00FF00) >> 8); + + float value = float(bits) * 2.3283064365386963e-10; + radical_inverse[i] = uint8_t(CLAMP(value * 255.0, 0, 255)); + } + + glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 512, 1, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, radical_inverse); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //need this for proper sampling + + glBindTexture(GL_TEXTURE_2D, 0); + } + + { + glGenFramebuffers(1, &resources.mipmap_blur_fbo); + glGenTextures(1, &resources.mipmap_blur_color); + } + +#ifdef GLES_OVER_GL + //this needs to be enabled manually in OpenGL 2.1 + + if (config.extensions.has("GL_ARB_seamless_cube_map")) { + glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS); + } + glEnable(GL_POINT_SPRITE); + glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); +#endif + + config.force_vertex_shading = GLOBAL_GET("rendering/quality/shading/force_vertex_shading"); + config.use_fast_texture_filter = GLOBAL_GET("rendering/quality/filters/use_nearest_mipmap_filter"); + //config.should_orphan = GLOBAL_GET("rendering/options/api_usage_legacy/orphan_buffers"); +} + +void RasterizerStorageGLES2::finalize() { +} + +void RasterizerStorageGLES2::_copy_screen() { + bind_quad_array(); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); +} + +void RasterizerStorageGLES2::update_dirty_resources() { + update_dirty_shaders(); + update_dirty_materials(); + // update_dirty_skeletons(); + // update_dirty_multimeshes(); +} + +RasterizerStorageGLES2::RasterizerStorageGLES2() { + RasterizerStorageGLES2::system_fbo = 0; + config.should_orphan = true; +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/rasterizer_storage_gles2.h b/drivers/gles2/rasterizer_storage_gles2.h new file mode 100644 index 00000000000..e2db7feefb2 --- /dev/null +++ b/drivers/gles2/rasterizer_storage_gles2.h @@ -0,0 +1,1093 @@ +/*************************************************************************/ +/* rasterizer_storage_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZERSTORAGEGLES2_H +#define RASTERIZERSTORAGEGLES2_H + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/templates/local_vector.h" +#include "core/templates/rid_owner.h" +#include "core/templates/self_list.h" +#include "drivers/gles_common/rasterizer_asserts.h" +#include "drivers/gles_common/rasterizer_common_stubs.h" +#include "drivers/gles_common/rasterizer_version.h" +#include "servers/rendering/renderer_compositor.h" +#include "servers/rendering/shader_language.h" +#include "shader_compiler_gles2.h" +#include "shader_gles2.h" + +#include "shaders/copy.glsl.gen.h" +#include "shaders/cubemap_filter.glsl.gen.h" + +class RasterizerCanvasGLES2; +class RasterizerSceneGLES2; + +class RasterizerStorageGLES2 : public StubsStorage { + friend class RasterizerGLES2; + + Thread::ID _main_thread_id = 0; + bool _is_main_thread(); + +public: + RasterizerCanvasGLES2 *canvas; + RasterizerSceneGLES2 *scene; + + static GLuint system_fbo; + + struct Config { + bool shrink_textures_x2; + bool use_fast_texture_filter; + bool use_skeleton_software; + + int max_vertex_texture_image_units; + int max_texture_image_units; + int max_texture_size; + + // TODO implement wireframe in GLES2 + // bool generate_wireframes; + + Set extensions; + + bool float_texture_supported; + bool s3tc_supported; + bool etc1_supported; + bool pvrtc_supported; + bool rgtc_supported; + bool bptc_supported; + + bool keep_original_textures; + + bool force_vertex_shading; + + bool use_rgba_2d_shadows; + bool use_rgba_3d_shadows; + + bool support_32_bits_indices; + bool support_write_depth; + bool support_half_float_vertices; + bool support_npot_repeat_mipmap; + bool support_depth_texture; + bool support_depth_cubemaps; + + bool support_shadow_cubemaps; + + bool multisample_supported; + bool render_to_mipmap_supported; + + GLuint depth_internalformat; + GLuint depth_type; + GLuint depth_buffer_internalformat; + + // in some cases the legacy render didn't orphan. We will mark these + // so the user can switch orphaning off for them. + bool should_orphan; + } config; + + struct Resources { + GLuint white_tex; + GLuint black_tex; + GLuint normal_tex; + GLuint aniso_tex; + + GLuint mipmap_blur_fbo; + GLuint mipmap_blur_color; + + GLuint radical_inverse_vdc_cache_tex; + bool use_rgba_2d_shadows; + + GLuint quadie; + + size_t skeleton_transform_buffer_size; + GLuint skeleton_transform_buffer; + LocalVector skeleton_transform_cpu_buffer; + + } resources; + + mutable struct Shaders { + ShaderCompilerGLES2 compiler; + + CopyShaderGLES2 copy; + CubemapFilterShaderGLES2 cubemap_filter; + + ShaderCompilerGLES2::IdentifierActions actions_canvas; + ShaderCompilerGLES2::IdentifierActions actions_scene; + ShaderCompilerGLES2::IdentifierActions actions_particles; + + } shaders; + + struct Info { + uint64_t texture_mem; + uint64_t vertex_mem; + + struct Render { + uint32_t object_count; + uint32_t draw_call_count; + uint32_t material_switch_count; + uint32_t surface_switch_count; + uint32_t shader_rebind_count; + uint32_t vertices_count; + uint32_t _2d_item_count; + uint32_t _2d_draw_call_count; + + void reset() { + object_count = 0; + draw_call_count = 0; + material_switch_count = 0; + surface_switch_count = 0; + shader_rebind_count = 0; + vertices_count = 0; + _2d_item_count = 0; + _2d_draw_call_count = 0; + } + } render, render_final, snap; + + Info() : + texture_mem(0), + vertex_mem(0) { + render.reset(); + render_final.reset(); + } + + } info; + + void bind_quad_array() const; + + ///////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////DATA/////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + struct Instantiable { + RID self; + + SelfList::List instance_list; + + _FORCE_INLINE_ void instance_change_notify(bool p_aabb, bool p_materials) { + SelfList *instances = instance_list.first(); + while (instances) { + instances->self()->base_changed(p_aabb, p_materials); + instances = instances->next(); + } + } + + _FORCE_INLINE_ void instance_remove_deps() { + SelfList *instances = instance_list.first(); + + while (instances) { + instances->self()->base_removed(); + instances = instances->next(); + } + } + + Instantiable() {} + + virtual ~Instantiable() {} + }; + + struct GeometryOwner : public Instantiable { + }; + + struct Geometry : public Instantiable { + enum Type { + GEOMETRY_INVALID, + GEOMETRY_SURFACE, + GEOMETRY_IMMEDIATE, + GEOMETRY_MULTISURFACE + }; + + Type type; + RID material; + uint64_t last_pass; + uint32_t index; + + virtual void material_changed_notify() {} + + Geometry() { + last_pass = 0; + index = 0; + } + }; +*/ + ///////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////API//////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////// + + // TEXTURE API + + enum GLESTextureFlags { + TEXTURE_FLAG_MIPMAPS = 1, /// Enable automatic mipmap generation - when available + TEXTURE_FLAG_REPEAT = 2, /// Repeat texture (Tiling), otherwise Clamping + TEXTURE_FLAG_FILTER = 4, /// Create texture with linear (or available) filter + TEXTURE_FLAG_ANISOTROPIC_FILTER = 8, + TEXTURE_FLAG_CONVERT_TO_LINEAR = 16, + TEXTURE_FLAG_MIRRORED_REPEAT = 32, /// Repeat texture, with alternate sections mirrored + TEXTURE_FLAG_USED_FOR_STREAMING = 2048, + TEXTURE_FLAGS_DEFAULT = TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS | TEXTURE_FLAG_FILTER + }; + + struct RenderTarget; + + struct Texture { + RID self; + + Texture *proxy; + Set proxy_owners; + + String path; + uint32_t flags; + int width, height, depth; + int alloc_width, alloc_height; + Image::Format format; + GD_RD::TextureType type; + + GLenum target; + GLenum gl_format_cache; + GLenum gl_internal_format_cache; + GLenum gl_type_cache; + + int data_size; + int total_data_size; + bool ignore_mipmaps; + + bool compressed; + + bool srgb; + + int mipmaps; + + bool resize_to_po2; + + bool active; + GLenum tex_id; + + uint16_t stored_cube_sides; + + RenderTarget *render_target; + + Vector> images; + + bool redraw_if_visible; + + GD_VS::TextureDetectCallback detect_3d; + void *detect_3d_ud; + + GD_VS::TextureDetectCallback detect_srgb; + void *detect_srgb_ud; + + GD_VS::TextureDetectCallback detect_normal; + void *detect_normal_ud; + + // some silly opengl shenanigans where + // texture coords start from bottom left, means we need to draw render target textures upside down + // to be compatible with vulkan etc. + bool is_upside_down() const { + if (proxy) + return proxy->is_upside_down(); + + return render_target != nullptr; + } + + Texture() { + create(); + } + + _ALWAYS_INLINE_ Texture *get_ptr() { + if (proxy) { + return proxy; //->get_ptr(); only one level of indirection, else not inlining possible. + } else { + return this; + } + } + + ~Texture() { + destroy(); + + if (tex_id != 0) { + glDeleteTextures(1, &tex_id); + } + } + + void copy_from(const Texture &o) { + proxy = o.proxy; + flags = o.flags; + width = o.width; + height = o.height; + alloc_width = o.alloc_width; + alloc_height = o.alloc_height; + format = o.format; + type = o.type; + target = o.target; + data_size = o.data_size; + total_data_size = o.total_data_size; + ignore_mipmaps = o.ignore_mipmaps; + compressed = o.compressed; + mipmaps = o.mipmaps; + resize_to_po2 = o.resize_to_po2; + active = o.active; + tex_id = o.tex_id; + stored_cube_sides = o.stored_cube_sides; + render_target = o.render_target; + redraw_if_visible = o.redraw_if_visible; + detect_3d = o.detect_3d; + detect_3d_ud = o.detect_3d_ud; + detect_srgb = o.detect_srgb; + detect_srgb_ud = o.detect_srgb_ud; + detect_normal = o.detect_normal; + detect_normal_ud = o.detect_normal_ud; + + images.clear(); + } + + void create() { + proxy = nullptr; + flags = 0; + width = 0; + height = 0; + alloc_width = 0; + alloc_height = 0; + format = Image::FORMAT_L8; + type = GD_RD::TEXTURE_TYPE_2D; + target = 0; + data_size = 0; + total_data_size = 0; + ignore_mipmaps = false; + compressed = false; + mipmaps = 0; + resize_to_po2 = false; + active = false; + tex_id = 0; + stored_cube_sides = 0; + render_target = nullptr; + redraw_if_visible = false; + detect_3d = nullptr; + detect_3d_ud = nullptr; + detect_srgb = nullptr; + detect_srgb_ud = nullptr; + detect_normal = nullptr; + detect_normal_ud = nullptr; + } + void destroy() { + images.clear(); + + for (Set::Element *E = proxy_owners.front(); E; E = E->next()) { + E->get()->proxy = NULL; + } + + if (proxy) { + proxy->proxy_owners.erase(this); + } + } + + // texture state + void GLSetFilter(GLenum p_target, RS::CanvasItemTextureFilter p_filter) { + if (p_filter == state_filter) + return; + state_filter = p_filter; + GLint pmin = GL_LINEAR; // param min + GLint pmag = GL_LINEAR; // param mag + switch (state_filter) { + default: { + } break; + case RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS: { + pmin = GL_LINEAR_MIPMAP_LINEAR; + pmag = GL_LINEAR; + } break; + case RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST: { + pmin = GL_NEAREST; + pmag = GL_NEAREST; + } break; + case RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS: { + pmin = GL_NEAREST_MIPMAP_NEAREST; + pmag = GL_NEAREST; + } break; + } + glTexParameteri(p_target, GL_TEXTURE_MIN_FILTER, pmin); + glTexParameteri(p_target, GL_TEXTURE_MAG_FILTER, pmag); + } + void GLSetRepeat(RS::CanvasItemTextureRepeat p_repeat) { + if (p_repeat == state_repeat) + return; + state_repeat = p_repeat; + GLint prep = GL_CLAMP_TO_EDGE; // parameter repeat + switch (state_repeat) { + default: { + } break; + case RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED: { + prep = GL_REPEAT; + } break; + case RS::CANVAS_ITEM_TEXTURE_REPEAT_MIRROR: { + prep = GL_MIRRORED_REPEAT; + } break; + } + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, prep); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, prep); + } + + private: + RS::CanvasItemTextureFilter state_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR; + RS::CanvasItemTextureRepeat state_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED; + }; + + mutable RID_PtrOwner texture_owner; + + Ref _get_gl_image_and_format(const Ref &p_image, Image::Format p_format, uint32_t p_flags, Image::Format &r_real_format, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool p_force_decompress) const; + + void _texture_set_state_from_flags(Texture *p_tex); + + // new + RID texture_allocate() override; + void texture_2d_initialize(RID p_texture, const Ref &p_image) override; + + // RID texture_2d_create(const Ref &p_image) override; + // RID texture_2d_layered_create(const Vector> &p_layers, RS::TextureLayeredType p_layered_type) override; + // RID texture_3d_create(Image::Format, int p_width, int p_height, int p_depth, bool p_mipmaps, const Vector> &p_data) override { return RID(); } + //RID texture_proxy_create(RID p_base) override; + + //void texture_2d_update_immediate(RID p_texture, const Ref &p_image, int p_layer = 0) override; + void texture_2d_update(RID p_texture, const Ref &p_image, int p_layer = 0) override; + void texture_3d_update(RID p_texture, const Vector> &p_data) override {} + void texture_proxy_update(RID p_proxy, RID p_base) override {} + + //RID texture_2d_placeholder_create() override; + //RID texture_2d_layered_placeholder_create(RenderingServer::TextureLayeredType p_layered_type) override { return RID(); } + //RID texture_3d_placeholder_create() override { return RID(); } + + Ref texture_2d_get(RID p_texture) const override; + Ref texture_2d_layer_get(RID p_texture, int p_layer) const override { return Ref(); } + Vector> texture_3d_get(RID p_texture) const override { return Vector>(); } + + void texture_replace(RID p_texture, RID p_by_texture) override; + //void texture_set_size_override(RID p_texture, int p_width, int p_height) override {} + + void texture_add_to_decal_atlas(RID p_texture, bool p_panorama_to_dp = false) override {} + void texture_remove_from_decal_atlas(RID p_texture, bool p_panorama_to_dp = false) override {} + + // old + virtual uint32_t texture_get_width(RID p_texture) const; + virtual uint32_t texture_get_height(RID p_texture) const; + +private: + virtual RID texture_create(); + + //virtual void texture_allocate(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, GD_RD::TextureType p_type, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT); + void _texture_allocate_internal(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, GD_RD::TextureType p_type, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT); + + virtual void texture_set_data(RID p_texture, const Ref &p_image, int p_layer = 0); + virtual void texture_set_data_partial(RID p_texture, const Ref &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_layer = 0); + //virtual Ref texture_get_data(RID p_texture, int p_layer = 0) const; + virtual void texture_set_flags(RID p_texture, uint32_t p_flags); + virtual uint32_t texture_get_flags(RID p_texture) const; + virtual Image::Format texture_get_format(RID p_texture) const; + virtual GD_RD::TextureType texture_get_type(RID p_texture) const; + virtual uint32_t texture_get_texid(RID p_texture) const; + virtual uint32_t texture_get_depth(RID p_texture) const; + void texture_set_size_override(RID p_texture, int p_width, int p_height) override; + + virtual void texture_bind(RID p_texture, uint32_t p_texture_no); + + virtual void texture_set_path(RID p_texture, const String &p_path) override; + virtual String texture_get_path(RID p_texture) const override; + + virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable); + + virtual void texture_debug_usage(List *r_info) override; + + virtual RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const; + + virtual void textures_keep_original(bool p_enable); + + virtual void texture_set_proxy(RID p_texture, RID p_proxy); + virtual Size2 texture_size_with_proxy(RID p_texture) override; + + virtual void texture_set_detect_3d_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata) override; + virtual void texture_set_detect_srgb_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata); + virtual void texture_set_detect_normal_callback(RID p_texture, GD_VS::TextureDetectCallback p_callback, void *p_userdata) override; + void texture_set_detect_roughness_callback(RID p_texture, RS::TextureDetectRoughnessCallback p_callback, void *p_userdata) override {} + + virtual void texture_set_force_redraw_if_visible(RID p_texture, bool p_enable) override; + +public: + // CANVAS TEXTURE API + /* + RID canvas_texture_create() override { return RID(); } + void canvas_texture_set_channel(RID p_canvas_texture, RS::CanvasTextureChannel p_channel, RID p_texture) override {} + void canvas_texture_set_shading_parameters(RID p_canvas_texture, const Color &p_base_color, float p_shininess) override {} + + void canvas_texture_set_texture_filter(RID p_item, RS::CanvasItemTextureFilter p_filter) override {} + void canvas_texture_set_texture_repeat(RID p_item, RS::CanvasItemTextureRepeat p_repeat) override {} + */ + /* SKY API */ + // not sure if used in godot 4? + struct Sky { + RID self; + RID panorama; + GLuint radiance; + int radiance_size; + }; + + mutable RID_PtrOwner sky_owner; + + virtual RID sky_create(); + virtual void sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size); + + // SHADER API + + struct Material; + + struct Shader { + RID self; + + GD_VS::ShaderMode mode; + ShaderGLES2 *shader; + String code; + SelfList::List materials; + + Map uniforms; + + uint32_t texture_count; + + uint32_t custom_code_id; + uint32_t version; + + SelfList dirty_list; + + Map default_textures; + + Vector texture_hints; + + bool valid; + + String path; + + uint32_t index; + uint64_t last_pass; + + struct CanvasItem { + enum BlendMode { + BLEND_MODE_MIX, + BLEND_MODE_ADD, + BLEND_MODE_SUB, + BLEND_MODE_MUL, + BLEND_MODE_PMALPHA, + }; + + int blend_mode; + + enum LightMode { + LIGHT_MODE_NORMAL, + LIGHT_MODE_UNSHADED, + LIGHT_MODE_LIGHT_ONLY + }; + + int light_mode; + + // these flags are specifically for batching + // some of the logic is thus in rasterizer_storage.cpp + // we could alternatively set bitflags for each 'uses' and test on the fly + // defined in RasterizerStorageCommon::BatchFlags + unsigned int batch_flags; + + bool uses_screen_texture; + bool uses_screen_uv; + bool uses_time; + bool uses_modulate; + bool uses_color; + bool uses_vertex; + + // all these should disable item joining if used in a custom shader + bool uses_world_matrix; + bool uses_extra_matrix; + bool uses_projection_matrix; + bool uses_instance_custom; + + } canvas_item; + + struct Spatial { + enum BlendMode { + BLEND_MODE_MIX, + BLEND_MODE_ADD, + BLEND_MODE_SUB, + BLEND_MODE_MUL, + }; + + int blend_mode; + + enum DepthDrawMode { + DEPTH_DRAW_OPAQUE, + DEPTH_DRAW_ALWAYS, + DEPTH_DRAW_NEVER, + DEPTH_DRAW_ALPHA_PREPASS, + }; + + int depth_draw_mode; + + enum CullMode { + CULL_MODE_FRONT, + CULL_MODE_BACK, + CULL_MODE_DISABLED, + }; + + int cull_mode; + + bool uses_alpha; + bool uses_alpha_scissor; + bool unshaded; + bool no_depth_test; + bool uses_vertex; + bool uses_discard; + bool uses_sss; + bool uses_screen_texture; + bool uses_depth_texture; + bool uses_time; + bool uses_tangent; + bool uses_ensure_correct_normals; + bool writes_modelview_or_projection; + bool uses_vertex_lighting; + bool uses_world_coordinates; + + } spatial; + + struct Particles { + } particles; + + bool uses_vertex_time; + bool uses_fragment_time; + + Shader() : + dirty_list(this) { + shader = NULL; + valid = false; + custom_code_id = 0; + version = 1; + last_pass = 0; + } + }; + + mutable RID_PtrOwner shader_owner; + mutable SelfList::List _shader_dirty_list; + + void _shader_make_dirty(Shader *p_shader); + + RID shader_allocate() override; + void shader_initialize(RID p_rid) override; + + //virtual RID shader_create() override; + + virtual void shader_set_code(RID p_shader, const String &p_code) override; + virtual String shader_get_code(RID p_shader) const override; + virtual void shader_get_param_list(RID p_shader, List *p_param_list) const override; + + virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) override; + virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const override; + + virtual RS::ShaderNativeSourceCode shader_get_native_source_code(RID p_shader) const override { return RS::ShaderNativeSourceCode(); }; + + virtual void shader_add_custom_define(RID p_shader, const String &p_define); + virtual void shader_get_custom_defines(RID p_shader, Vector *p_defines) const; + virtual void shader_remove_custom_define(RID p_shader, const String &p_define); + + void _update_shader(Shader *p_shader) const; + void update_dirty_shaders(); + + // new + Variant shader_get_param_default(RID p_material, const StringName &p_param) const override { return Variant(); } + + // COMMON MATERIAL API + + struct Material { + RID self; + Shader *shader; + Map params; + SelfList list; + SelfList dirty_list; + Vector> textures; + float line_width; + int render_priority; + + RID next_pass; + + uint32_t index; + uint64_t last_pass; + + // Map geometry_owners; + // Map instance_owners; + + bool can_cast_shadow_cache; + bool is_animated_cache; + + Material() : + list(this), + dirty_list(this) { + can_cast_shadow_cache = false; + is_animated_cache = false; + shader = NULL; + line_width = 1.0; + last_pass = 0; + render_priority = 0; + } + }; + + mutable SelfList::List _material_dirty_list; + void _material_make_dirty(Material *p_material) const; + + // void _material_add_geometry(RID p_material, Geometry *p_geometry); + // void _material_remove_geometry(RID p_material, Geometry *p_geometry); + + void _update_material(Material *p_material); + + mutable RID_PtrOwner material_owner; + + // new + void material_get_instance_shader_parameters(RID p_material, List *r_parameters) override {} + void material_update_dependency(RID p_material, DependencyTracker *p_instance) override {} + + // old + RID material_allocate() override; + void material_initialize(RID p_rid) override; + + //virtual RID material_create() override; + + virtual void material_set_shader(RID p_material, RID p_shader) override; + virtual RID material_get_shader(RID p_material) const; + + virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) override; + virtual Variant material_get_param(RID p_material, const StringName &p_param) const override; + virtual Variant material_get_param_default(RID p_material, const StringName &p_param) const; + + virtual void material_set_line_width(RID p_material, float p_width); + virtual void material_set_next_pass(RID p_material, RID p_next_material) override; + + virtual bool material_is_animated(RID p_material) override; + virtual bool material_casts_shadows(RID p_material) override; + virtual bool material_uses_tangents(RID p_material); + virtual bool material_uses_ensure_correct_normals(RID p_material); + + virtual void material_add_instance_owner(RID p_material, DependencyTracker *p_instance); + virtual void material_remove_instance_owner(RID p_material, DependencyTracker *p_instance); + + virtual void material_set_render_priority(RID p_material, int priority) override; + + void update_dirty_materials(); + + // RENDER TARGET + + struct RenderTarget { + RID self; + GLuint fbo; + GLuint color; + GLuint depth; + + GLuint multisample_fbo; + GLuint multisample_color; + GLuint multisample_depth; + bool multisample_active; + + struct Effect { + GLuint fbo; + int width; + int height; + + GLuint color; + + Effect() : + fbo(0), + width(0), + height(0), + color(0) { + } + }; + + Effect copy_screen_effect; + + struct MipMaps { + struct Size { + GLuint fbo; + GLuint color; + int width; + int height; + }; + + Vector sizes; + GLuint color; + int levels; + + MipMaps() : + color(0), + levels(0) { + } + }; + + MipMaps mip_maps[2]; + + struct External { + GLuint fbo; + GLuint color; + GLuint depth; + RID texture; + + External() : + fbo(0), + color(0), + depth(0) { + } + } external; + + int x, y, width, height; + + bool flags[RENDER_TARGET_FLAG_MAX]; + + // instead of allocating sized render targets immediately, + // defer this for faster startup + bool allocate_is_dirty = false; + bool used_in_frame; + GD_VS::ViewportMSAA msaa; + + bool use_fxaa; + bool use_debanding; + + RID texture; + + bool used_dof_blur_near; + bool mip_maps_allocated; + + Color clear_color; + bool clear_requested; + + RenderTarget() : + fbo(0), + color(0), + depth(0), + multisample_fbo(0), + multisample_color(0), + multisample_depth(0), + multisample_active(false), + x(0), + y(0), + width(0), + height(0), + used_in_frame(false), + msaa(GD_VS::VIEWPORT_MSAA_DISABLED), + use_fxaa(false), + use_debanding(false), + used_dof_blur_near(false), + mip_maps_allocated(false), + clear_color(Color(1, 1, 1, 1)), + clear_requested(false) { + for (int i = 0; i < RENDER_TARGET_FLAG_MAX; ++i) { + flags[i] = false; + } + external.fbo = 0; + } + }; + + mutable RID_PtrOwner render_target_owner; + + void _render_target_clear(RenderTarget *rt); + void _render_target_allocate(RenderTarget *rt); + void _set_current_render_target(RID p_render_target); + + virtual RID render_target_create() override; + virtual void render_target_set_position(RID p_render_target, int p_x, int p_y) override; + virtual void render_target_set_size(RID p_render_target, int p_width, int p_height, uint32_t p_view_count) override; + virtual RID render_target_get_texture(RID p_render_target) override; + virtual void render_target_set_external_texture(RID p_render_target, unsigned int p_texture_id) override; + + virtual void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) override; + virtual bool render_target_was_used(RID p_render_target) override; + virtual void render_target_clear_used(RID p_render_target); + virtual void render_target_set_msaa(RID p_render_target, GD_VS::ViewportMSAA p_msaa); + virtual void render_target_set_use_fxaa(RID p_render_target, bool p_fxaa); + virtual void render_target_set_use_debanding(RID p_render_target, bool p_debanding); + + // new + void render_target_set_as_unused(RID p_render_target) override { render_target_clear_used(p_render_target); } + + void render_target_request_clear(RID p_render_target, const Color &p_clear_color) override; + bool render_target_is_clear_requested(RID p_render_target) override; + Color render_target_get_clear_request_color(RID p_render_target) override; + void render_target_disable_clear_request(RID p_render_target) override; + void render_target_do_clear_request(RID p_render_target) override; + + // access from canvas + // RenderTarget * render_target_get(RID p_render_target); + + /* CANVAS SHADOW */ + + struct CanvasLightShadow { + RID self; + int size; + int height; + GLuint fbo; + GLuint depth; + GLuint distance; //for older devices + }; + + RID_PtrOwner canvas_light_shadow_owner; + + virtual RID canvas_light_shadow_buffer_create(int p_width); + + /* LIGHT SHADOW MAPPING */ + /* + struct CanvasOccluder { + RID self; + + GLuint vertex_id; // 0 means, unconfigured + GLuint index_id; // 0 means, unconfigured + LocalVector lines; + int len; + }; + + RID_Owner canvas_occluder_owner; + + virtual RID canvas_light_occluder_create(); + virtual void canvas_light_occluder_set_polylines(RID p_occluder, const LocalVector &p_lines); +*/ + + virtual GD_VS::InstanceType get_base_type(RID p_rid) const override; + + virtual bool free(RID p_rid) override; + + struct Frame { + RenderTarget *current_rt; + + // these 2 may have been superceded by the equivalents in the render target. + // these may be able to be removed. + bool clear_request; + Color clear_request_color; + + float time[4]; + float delta; + uint64_t count; + + Frame() { + // current_rt = nullptr; + // clear_request = false; + } + } frame; + + void initialize(); + void finalize(); + + void _copy_screen(); + + virtual bool has_os_feature(const String &p_feature) const override; + + virtual void update_dirty_resources() override; + + virtual void set_debug_generate_wireframes(bool p_generate) override; + + // virtual void render_info_begin_capture() override; + // virtual void render_info_end_capture() override; + // virtual int get_captured_render_info(GD_VS::RenderInfo p_info) override; + + // virtual int get_render_info(GD_VS::RenderInfo p_info) override; + virtual String get_video_adapter_name() const override; + virtual String get_video_adapter_vendor() const override; + + void capture_timestamps_begin() override {} + void capture_timestamp(const String &p_name) override {} + uint32_t get_captured_timestamps_count() const override { return 0; } + uint64_t get_captured_timestamps_frame() const override { return 0; } + uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const override { return 0; } + uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const override { return 0; } + String get_captured_timestamp_name(uint32_t p_index) const override { return String(); } + + // make access easier to these + struct Dimensions { + // render target + int rt_width; + int rt_height; + + // window + int win_width; + int win_height; + Dimensions() { + rt_width = 0; + rt_height = 0; + win_width = 0; + win_height = 0; + } + } _dims; + + void buffer_orphan_and_upload(unsigned int p_buffer_size, unsigned int p_offset, unsigned int p_data_size, const void *p_data, GLenum p_target = GL_ARRAY_BUFFER, GLenum p_usage = GL_DYNAMIC_DRAW, bool p_optional_orphan = false) const; + bool safe_buffer_sub_data(unsigned int p_total_buffer_size, GLenum p_target, unsigned int p_offset, unsigned int p_data_size, const void *p_data, unsigned int &r_offset_after) const; + + void bind_framebuffer(GLuint framebuffer) { + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); + } + + void bind_framebuffer_system() { + glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES2::system_fbo); + } + + RasterizerStorageGLES2(); +}; + +inline bool RasterizerStorageGLES2::safe_buffer_sub_data(unsigned int p_total_buffer_size, GLenum p_target, unsigned int p_offset, unsigned int p_data_size, const void *p_data, unsigned int &r_offset_after) const { + r_offset_after = p_offset + p_data_size; +#ifdef DEBUG_ENABLED + // we are trying to write across the edge of the buffer + if (r_offset_after > p_total_buffer_size) + return false; +#endif + glBufferSubData(p_target, p_offset, p_data_size, p_data); + return true; +} + +// standardize the orphan / upload in one place so it can be changed per platform as necessary, and avoid future +// bugs causing pipeline stalls +inline void RasterizerStorageGLES2::buffer_orphan_and_upload(unsigned int p_buffer_size, unsigned int p_offset, unsigned int p_data_size, const void *p_data, GLenum p_target, GLenum p_usage, bool p_optional_orphan) const { + // Orphan the buffer to avoid CPU/GPU sync points caused by glBufferSubData + // Was previously #ifndef GLES_OVER_GL however this causes stalls on desktop mac also (and possibly other) + if (!p_optional_orphan || (config.should_orphan)) { + glBufferData(p_target, p_buffer_size, NULL, p_usage); +#ifdef RASTERIZER_EXTRA_CHECKS + // fill with garbage off the end of the array + if (p_buffer_size) { + unsigned int start = p_offset + p_data_size; + unsigned int end = start + 1024; + if (end < p_buffer_size) { + uint8_t *garbage = (uint8_t *)alloca(1024); + for (int n = 0; n < 1024; n++) { + garbage[n] = Math::random(0, 255); + } + glBufferSubData(p_target, start, 1024, garbage); + } + } +#endif + } + RAST_DEV_DEBUG_ASSERT((p_offset + p_data_size) <= p_buffer_size); + glBufferSubData(p_target, p_offset, p_data_size, p_data); +} + +#endif // GLES2_BACKEND_ENABLED +#endif // RASTERIZERSTORAGEGLES2_H diff --git a/drivers/gles2/shader_compiler_gles2.cpp b/drivers/gles2/shader_compiler_gles2.cpp new file mode 100644 index 00000000000..2784b156fc9 --- /dev/null +++ b/drivers/gles2/shader_compiler_gles2.cpp @@ -0,0 +1,1125 @@ +/*************************************************************************/ +/* shader_compiler_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "shader_compiler_gles2.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/os/os.h" + +//#ifdef GODOT_3 + +#ifdef GODOT_3 +#include "core/project_settings.h" +#include "core/string_buffer.h" +#include "core/string_builder.h" +#else +#include "core/config/project_settings.h" +#include "core/string/string_buffer.h" +#include "core/string/string_builder.h" + +#endif + +#define SL ShaderLanguage + +static String _mktab(int p_level) { + String tb; + for (int i = 0; i < p_level; i++) { + tb += "\t"; + } + + return tb; +} + +static String _typestr(SL::DataType p_type) { + return ShaderLanguage::get_datatype_name(p_type); +} + +static String _prestr(SL::DataPrecision p_pres) { + switch (p_pres) { + case SL::PRECISION_LOWP: + return "lowp "; + case SL::PRECISION_MEDIUMP: + return "mediump "; + case SL::PRECISION_HIGHP: + return "highp "; + case SL::PRECISION_DEFAULT: + return ""; + } + return ""; +} + +static String _qualstr(SL::ArgumentQualifier p_qual) { + switch (p_qual) { + case SL::ARGUMENT_QUALIFIER_IN: + return "in "; + case SL::ARGUMENT_QUALIFIER_OUT: + return "out "; + case SL::ARGUMENT_QUALIFIER_INOUT: + return "inout "; + } + return ""; +} + +static String _opstr(SL::Operator p_op) { + return SL::get_operator_text(p_op); +} + +static String _mkid(const String &p_id) { + String id = "m_" + p_id.replace("__", "_dus_"); + return id.replace("__", "_dus_"); //doubleunderscore is reserved in glsl +} + +static String f2sp0(float p_float) { + String num = rtoss(p_float); + if (num.find(".") == -1 && num.find("e") == -1) { + num += ".0"; + } + return num; +} + +static String get_constant_text(SL::DataType p_type, const Vector &p_values) { + switch (p_type) { + case SL::TYPE_BOOL: + return p_values[0].boolean ? "true" : "false"; + case SL::TYPE_BVEC2: + case SL::TYPE_BVEC3: + case SL::TYPE_BVEC4: { + StringBuffer<> text; + + text += "bvec"; + text += itos(p_type - SL::TYPE_BOOL + 1); + text += "("; + + for (int i = 0; i < p_values.size(); i++) { + if (i > 0) + text += ","; + + text += p_values[i].boolean ? "true" : "false"; + } + text += ")"; + return text.as_string(); + } + + // GLSL ES 2 doesn't support uints, so we just use signed ints instead... + case SL::TYPE_UINT: + return itos(p_values[0].uint); + case SL::TYPE_UVEC2: + case SL::TYPE_UVEC3: + case SL::TYPE_UVEC4: { + StringBuffer<> text; + + text += "ivec"; + text += itos(p_type - SL::TYPE_UINT + 1); + text += "("; + + for (int i = 0; i < p_values.size(); i++) { + if (i > 0) + text += ","; + + text += itos(p_values[i].uint); + } + text += ")"; + return text.as_string(); + + } break; + + case SL::TYPE_INT: + return itos(p_values[0].sint); + case SL::TYPE_IVEC2: + case SL::TYPE_IVEC3: + case SL::TYPE_IVEC4: { + StringBuffer<> text; + + text += "ivec"; + text += itos(p_type - SL::TYPE_INT + 1); + text += "("; + + for (int i = 0; i < p_values.size(); i++) { + if (i > 0) + text += ","; + + text += itos(p_values[i].sint); + } + text += ")"; + return text.as_string(); + + } break; + case SL::TYPE_FLOAT: + return f2sp0(p_values[0].real); + case SL::TYPE_VEC2: + case SL::TYPE_VEC3: + case SL::TYPE_VEC4: { + StringBuffer<> text; + + text += "vec"; + text += itos(p_type - SL::TYPE_FLOAT + 1); + text += "("; + + for (int i = 0; i < p_values.size(); i++) { + if (i > 0) + text += ","; + + text += f2sp0(p_values[i].real); + } + text += ")"; + return text.as_string(); + + } break; + case SL::TYPE_MAT2: + case SL::TYPE_MAT3: + case SL::TYPE_MAT4: { + StringBuffer<> text; + + text += "mat"; + text += itos(p_type - SL::TYPE_MAT2 + 2); + text += "("; + + for (int i = 0; i < p_values.size(); i++) { + if (i > 0) + text += ","; + + text += f2sp0(p_values[i].real); + } + text += ")"; + return text.as_string(); + + } break; + default: + ERR_FAIL_V(String()); + } +} + +void ShaderCompilerGLES2::_dump_function_deps(SL::ShaderNode *p_node, const StringName &p_for_func, const Map &p_func_code, StringBuilder &r_to_add, Set &r_added) { + int fidx = -1; + + for (int i = 0; i < p_node->functions.size(); i++) { + if (p_node->functions[i].name == p_for_func) { + fidx = i; + break; + } + } + + ERR_FAIL_COND(fidx == -1); + + for (Set::Element *E = p_node->functions[fidx].uses_function.front(); E; E = E->next()) { + if (r_added.has(E->get())) { + continue; + } + + _dump_function_deps(p_node, E->get(), p_func_code, r_to_add, r_added); + + SL::FunctionNode *fnode = NULL; + + for (int i = 0; i < p_node->functions.size(); i++) { + if (p_node->functions[i].name == E->get()) { + fnode = p_node->functions[i].function; + break; + } + } + + ERR_FAIL_COND(!fnode); + + r_to_add += "\n"; + + StringBuffer<128> header; + + header += _typestr(fnode->return_type); + header += " "; + header += _mkid(fnode->name); + header += "("; + + for (int i = 0; i < fnode->arguments.size(); i++) { + if (i > 0) + header += ", "; + + header += _qualstr(fnode->arguments[i].qualifier); + header += _prestr(fnode->arguments[i].precision); + header += _typestr(fnode->arguments[i].type); + header += " "; + header += _mkid(fnode->arguments[i].name); + } + + header += ")\n"; + r_to_add += header.as_string(); + r_to_add += p_func_code[E->get()]; + + r_added.insert(E->get()); + } +} + +String ShaderCompilerGLES2::_dump_node_code(SL::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions, bool p_assigning, bool p_use_scope) { + StringBuilder code; + + switch (p_node->type) { + default: { + } break; + case SL::Node::TYPE_SHADER: { + SL::ShaderNode *snode = (SL::ShaderNode *)p_node; + + for (int i = 0; i < snode->render_modes.size(); i++) { + if (p_default_actions.render_mode_defines.has(snode->render_modes[i]) && !used_rmode_defines.has(snode->render_modes[i])) { + r_gen_code.custom_defines.push_back(p_default_actions.render_mode_defines[snode->render_modes[i]].utf8()); + used_rmode_defines.insert(snode->render_modes[i]); + } + + if (p_actions.render_mode_flags.has(snode->render_modes[i])) { + *p_actions.render_mode_flags[snode->render_modes[i]] = true; + } + + if (p_actions.render_mode_values.has(snode->render_modes[i])) { + Pair &p = p_actions.render_mode_values[snode->render_modes[i]]; + *p.first = p.second; + } + } + + int max_texture_uniforms = 0; + int max_uniforms = 0; + + for (Map::Element *E = snode->uniforms.front(); E; E = E->next()) { + if (SL::is_sampler_type(E->get().type)) + max_texture_uniforms++; + else + max_uniforms++; + } + + r_gen_code.texture_uniforms.resize(max_texture_uniforms); + r_gen_code.texture_hints.resize(max_texture_uniforms); + + r_gen_code.uniforms.resize(max_uniforms + max_texture_uniforms); + + StringBuilder vertex_global; + StringBuilder fragment_global; + + // uniforms + + for (Map::Element *E = snode->uniforms.front(); E; E = E->next()) { + StringBuffer<> uniform_code; + + // use highp if no precision is specified to prevent different default values in fragment and vertex shader + SL::DataPrecision precision = E->get().precision; + if (precision == SL::PRECISION_DEFAULT && E->get().type != SL::TYPE_BOOL) { + precision = SL::PRECISION_HIGHP; + } + + uniform_code += "uniform "; + uniform_code += _prestr(precision); + uniform_code += _typestr(E->get().type); + uniform_code += " "; + uniform_code += _mkid(E->key()); + uniform_code += ";\n"; + + if (SL::is_sampler_type(E->get().type)) { + r_gen_code.texture_uniforms.write[E->get().texture_order] = E->key(); + r_gen_code.texture_hints.write[E->get().texture_order] = E->get().hint; + } else { + r_gen_code.uniforms.write[E->get().order] = E->key(); + } + + vertex_global += uniform_code.as_string(); + fragment_global += uniform_code.as_string(); + + p_actions.uniforms->insert(E->key(), E->get()); + } + + // varyings + + for (Map::Element *E = snode->varyings.front(); E; E = E->next()) { + StringBuffer<> varying_code; + + varying_code += "varying "; + varying_code += _prestr(E->get().precision); + varying_code += _typestr(E->get().type); + varying_code += " "; + varying_code += _mkid(E->key()); + if (E->get().array_size > 0) { + varying_code += "["; + varying_code += itos(E->get().array_size); + varying_code += "]"; + } + varying_code += ";\n"; + + String final_code = varying_code.as_string(); + + vertex_global += final_code; + fragment_global += final_code; + } + + // constants + + for (int i = 0; i < snode->vconstants.size(); i++) { + String gcode; + gcode += "const "; + gcode += _prestr(snode->vconstants[i].precision); + gcode += _typestr(snode->vconstants[i].type); + gcode += " " + _mkid(String(snode->vconstants[i].name)); + gcode += "="; + gcode += _dump_node_code(snode->vconstants[i].initializer, p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + gcode += ";\n"; + vertex_global += gcode; + fragment_global += gcode; + } + + // functions + + Map function_code; + + for (int i = 0; i < snode->functions.size(); i++) { + SL::FunctionNode *fnode = snode->functions[i].function; + current_func_name = fnode->name; + function_code[fnode->name] = _dump_node_code(fnode->body, 1, r_gen_code, p_actions, p_default_actions, p_assigning); + } + + Set added_vertex; + Set added_fragment; + + for (int i = 0; i < snode->functions.size(); i++) { + SL::FunctionNode *fnode = snode->functions[i].function; + + current_func_name = fnode->name; + + if (fnode->name == vertex_name) { + _dump_function_deps(snode, fnode->name, function_code, vertex_global, added_vertex); + r_gen_code.vertex = function_code[vertex_name]; + + } else if (fnode->name == fragment_name) { + _dump_function_deps(snode, fnode->name, function_code, fragment_global, added_fragment); + r_gen_code.fragment = function_code[fragment_name]; + + } else if (fnode->name == light_name) { + _dump_function_deps(snode, fnode->name, function_code, fragment_global, added_fragment); + r_gen_code.light = function_code[light_name]; + } + } + + r_gen_code.vertex_global = vertex_global.as_string(); + r_gen_code.fragment_global = fragment_global.as_string(); + + } break; + + case SL::Node::TYPE_FUNCTION: { + } break; + + case SL::Node::TYPE_BLOCK: { + SL::BlockNode *bnode = (SL::BlockNode *)p_node; + + if (!bnode->single_statement) { + code += _mktab(p_level - 1); + code += "{\n"; + } + + for (int i = 0; i < bnode->statements.size(); i++) { + String statement_code = _dump_node_code(bnode->statements[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + + if (bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW || bnode->single_statement) { + code += statement_code; + } else { + code += _mktab(p_level); + code += statement_code; + code += ";\n"; + } + } + + if (!bnode->single_statement) { + code += _mktab(p_level - 1); + code += "}\n"; + } + } break; + + case SL::Node::TYPE_VARIABLE_DECLARATION: { + SL::VariableDeclarationNode *var_dec_node = (SL::VariableDeclarationNode *)p_node; + + StringBuffer<> declaration; + if (var_dec_node->is_const) { + declaration += "const "; + } + declaration += _prestr(var_dec_node->precision); + declaration += _typestr(var_dec_node->datatype); + + for (int i = 0; i < var_dec_node->declarations.size(); i++) { + if (i > 0) { + declaration += ","; + } + + declaration += " "; + + declaration += _mkid(var_dec_node->declarations[i].name); + + if (var_dec_node->declarations[i].initializer) { + declaration += " = "; + declaration += _dump_node_code(var_dec_node->declarations[i].initializer, p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + } + } + + code += declaration.as_string(); + } break; + + case SL::Node::TYPE_VARIABLE: { + SL::VariableNode *var_node = (SL::VariableNode *)p_node; + + if (p_assigning && p_actions.write_flag_pointers.has(var_node->name)) { + *p_actions.write_flag_pointers[var_node->name] = true; + } + + if (p_default_actions.usage_defines.has(var_node->name) && !used_name_defines.has(var_node->name)) { + String define = p_default_actions.usage_defines[var_node->name]; + String node_name = define.substr(1, define.length()); + + if (define.begins_with("@")) { + define = p_default_actions.usage_defines[node_name]; + } + + if (!used_name_defines.has(node_name)) { + r_gen_code.custom_defines.push_back(define.utf8()); + } + used_name_defines.insert(var_node->name); + } + + if (p_actions.usage_flag_pointers.has(var_node->name) && !used_flag_pointers.has(var_node->name)) { + *p_actions.usage_flag_pointers[var_node->name] = true; + used_flag_pointers.insert(var_node->name); + } + + if (p_default_actions.renames.has(var_node->name)) { + code += p_default_actions.renames[var_node->name]; + } else { + code += _mkid(var_node->name); + } + + if (var_node->name == time_name) { + if (current_func_name == vertex_name) { + r_gen_code.uses_vertex_time = true; + } + if (current_func_name == fragment_name || current_func_name == light_name) { + r_gen_code.uses_fragment_time = true; + } + } + } break; + case SL::Node::TYPE_ARRAY_DECLARATION: { + SL::ArrayDeclarationNode *arr_dec_node = (SL::ArrayDeclarationNode *)p_node; + + StringBuffer<> declaration; + declaration += _prestr(arr_dec_node->precision); + declaration += _typestr(arr_dec_node->datatype); + + for (int i = 0; i < arr_dec_node->declarations.size(); i++) { + if (i > 0) { + declaration += ","; + } + + declaration += " "; + + declaration += _mkid(arr_dec_node->declarations[i].name); + declaration += "["; + declaration += itos(arr_dec_node->declarations[i].size); + declaration += "]"; + } + + code += declaration.as_string(); + } break; + case SL::Node::TYPE_ARRAY: { + SL::ArrayNode *arr_node = (SL::ArrayNode *)p_node; + + if (p_assigning && p_actions.write_flag_pointers.has(arr_node->name)) { + *p_actions.write_flag_pointers[arr_node->name] = true; + } + + if (p_default_actions.usage_defines.has(arr_node->name) && !used_name_defines.has(arr_node->name)) { + String define = p_default_actions.usage_defines[arr_node->name]; + String node_name = define.substr(1, define.length()); + + if (define.begins_with("@")) { + define = p_default_actions.usage_defines[node_name]; + } + + if (!used_name_defines.has(node_name)) { + r_gen_code.custom_defines.push_back(define.utf8()); + } + used_name_defines.insert(arr_node->name); + } + + if (p_actions.usage_flag_pointers.has(arr_node->name) && !used_flag_pointers.has(arr_node->name)) { + *p_actions.usage_flag_pointers[arr_node->name] = true; + used_flag_pointers.insert(arr_node->name); + } + + if (p_default_actions.renames.has(arr_node->name)) { + code += p_default_actions.renames[arr_node->name]; + } else { + code += _mkid(arr_node->name); + } + + if (arr_node->call_expression != NULL) { + code += "."; + code += _dump_node_code(arr_node->call_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning, false); + } + + if (arr_node->index_expression != NULL) { + code += "["; + code += _dump_node_code(arr_node->index_expression, p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "]"; + } + + if (arr_node->name == time_name) { + if (current_func_name == vertex_name) { + r_gen_code.uses_vertex_time = true; + } + if (current_func_name == fragment_name || current_func_name == light_name) { + r_gen_code.uses_fragment_time = true; + } + } + + } break; + case SL::Node::TYPE_CONSTANT: { + SL::ConstantNode *const_node = (SL::ConstantNode *)p_node; + + return get_constant_text(const_node->datatype, const_node->values); + } break; + + case SL::Node::TYPE_OPERATOR: { + SL::OperatorNode *op_node = (SL::OperatorNode *)p_node; + + switch (op_node->op) { + case SL::OP_ASSIGN: + case SL::OP_ASSIGN_ADD: + case SL::OP_ASSIGN_SUB: + case SL::OP_ASSIGN_MUL: + case SL::OP_ASSIGN_DIV: + case SL::OP_ASSIGN_SHIFT_LEFT: + case SL::OP_ASSIGN_SHIFT_RIGHT: + case SL::OP_ASSIGN_BIT_AND: + case SL::OP_ASSIGN_BIT_OR: + case SL::OP_ASSIGN_BIT_XOR: { + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, true); + code += " "; + code += _opstr(op_node->op); + code += " "; + code += _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + } break; + + case SL::OP_ASSIGN_MOD: { + String a = _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + String n = _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += a + " = " + n + " == 0 ? 0 : "; + code += a + " - " + n + " * (" + a + " / " + n + ")"; + } break; + + case SL::OP_BIT_INVERT: + case SL::OP_NEGATE: + case SL::OP_NOT: + case SL::OP_DECREMENT: + case SL::OP_INCREMENT: { + code += _opstr(op_node->op); + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + } break; + + case SL::OP_POST_DECREMENT: + case SL::OP_POST_INCREMENT: { + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += _opstr(op_node->op); + } break; + + case SL::OP_CALL: + case SL::OP_CONSTRUCT: { + ERR_FAIL_COND_V(op_node->arguments[0]->type != SL::Node::TYPE_VARIABLE, String()); + + SL::VariableNode *var_node = (SL::VariableNode *)op_node->arguments[0]; + + if (op_node->op == SL::OP_CONSTRUCT) { + code += var_node->name; + } else { + if (var_node->name == "texture") { + // emit texture call + + if (op_node->arguments[1]->get_datatype() == SL::TYPE_SAMPLER2D) { // || + // op_node->arguments[1]->get_datatype() == SL::TYPE_SAMPLEREXT) { + code += "texture2D"; + } else if (op_node->arguments[1]->get_datatype() == SL::TYPE_SAMPLERCUBE) { + code += "textureCube"; + } + + } else if (var_node->name == "textureLod") { + // emit texture call + + if (op_node->arguments[1]->get_datatype() == SL::TYPE_SAMPLER2D) { + code += "texture2DLod"; + } else if (op_node->arguments[1]->get_datatype() == SL::TYPE_SAMPLERCUBE) { + code += "textureCubeLod"; + } + + } else if (var_node->name == "mix") { + switch (op_node->arguments[3]->get_datatype()) { + case SL::TYPE_BVEC2: { + code += "select2"; + } break; + + case SL::TYPE_BVEC3: { + code += "select3"; + } break; + + case SL::TYPE_BVEC4: { + code += "select4"; + } break; + + case SL::TYPE_VEC2: + case SL::TYPE_VEC3: + case SL::TYPE_VEC4: + case SL::TYPE_FLOAT: { + code += "mix"; + } break; + + default: { + SL::DataType type = op_node->arguments[3]->get_datatype(); + // FIXME: Proper error print or graceful handling + print_line(String("uhhhh invalid mix with type: ") + itos(type)); + } break; + } + + } else if (p_default_actions.renames.has(var_node->name)) { + code += p_default_actions.renames[var_node->name]; + } else if (internal_functions.has(var_node->name)) { + code += var_node->name; + } else { + code += _mkid(var_node->name); + } + } + + code += "("; + + for (int i = 1; i < op_node->arguments.size(); i++) { + if (i > 1) { + code += ", "; + } + + code += _dump_node_code(op_node->arguments[i], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + } + + code += ")"; + + if (p_default_actions.usage_defines.has(var_node->name) && !used_name_defines.has(var_node->name)) { + String define = p_default_actions.usage_defines[var_node->name]; + String node_name = define.substr(1, define.length()); + + if (define.begins_with("@")) { + define = p_default_actions.usage_defines[node_name]; + } + + if (!used_name_defines.has(node_name)) { + r_gen_code.custom_defines.push_back(define.utf8()); + } + used_name_defines.insert(var_node->name); + } + + } break; + + case SL::OP_INDEX: { + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "["; + code += _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "]"; + } break; + + case SL::OP_SELECT_IF: { + code += "("; + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += " ? "; + code += _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += " : "; + code += _dump_node_code(op_node->arguments[2], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += ")"; + } break; + + case SL::OP_MOD: { + String a = _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + String n = _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "(" + n + " == 0 ? 0 : "; + code += a + " - " + n + " * (" + a + " / " + n + "))"; + } break; + + default: { + if (p_use_scope) { + code += "("; + } + code += _dump_node_code(op_node->arguments[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += " "; + code += _opstr(op_node->op); + code += " "; + code += _dump_node_code(op_node->arguments[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + if (p_use_scope) { + code += ")"; + } + } break; + } + } break; + + case SL::Node::TYPE_CONTROL_FLOW: { + SL::ControlFlowNode *cf_node = (SL::ControlFlowNode *)p_node; + + if (cf_node->flow_op == SL::FLOW_OP_IF) { + code += _mktab(p_level); + code += "if ("; + code += _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += ")\n"; + code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning); + + if (cf_node->blocks.size() == 2) { + code += _mktab(p_level); + code += "else\n"; + code += _dump_node_code(cf_node->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning); + } + } else if (cf_node->flow_op == SL::FLOW_OP_DO) { + code += _mktab(p_level); + code += "do"; + code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning); + code += _mktab(p_level); + code += "while ("; + code += _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += ");"; + } else if (cf_node->flow_op == SL::FLOW_OP_WHILE) { + code += _mktab(p_level); + code += "while ("; + code += _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += ")\n"; + code += _dump_node_code(cf_node->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions, p_assigning); + } else if (cf_node->flow_op == SL::FLOW_OP_FOR) { + code += _mktab(p_level); + code += "for ("; + code += _dump_node_code(cf_node->blocks[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "; "; + code += _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "; "; + code += _dump_node_code(cf_node->expressions[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += ")\n"; + + code += _dump_node_code(cf_node->blocks[1], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + + } else if (cf_node->flow_op == SL::FLOW_OP_RETURN) { + code += _mktab(p_level); + code += "return"; + + if (cf_node->expressions.size()) { + code += " "; + code += _dump_node_code(cf_node->expressions[0], p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + } + code += ";\n"; + } else if (cf_node->flow_op == SL::FLOW_OP_DISCARD) { + if (p_actions.usage_flag_pointers.has("DISCARD") && !used_flag_pointers.has("DISCARD")) { + *p_actions.usage_flag_pointers["DISCARD"] = true; + used_flag_pointers.insert("DISCARD"); + } + code += "discard;"; + } else if (cf_node->flow_op == SL::FLOW_OP_CONTINUE) { + code += "continue;"; + } else if (cf_node->flow_op == SL::FLOW_OP_BREAK) { + code += "break;"; + } + } break; + + case SL::Node::TYPE_MEMBER: { + SL::MemberNode *member_node = (SL::MemberNode *)p_node; + code += _dump_node_code(member_node->owner, p_level, r_gen_code, p_actions, p_default_actions, p_assigning); + code += "."; + code += member_node->name; + } break; + } + + return code.as_string(); +} + +ShaderLanguage::DataType ShaderCompilerGLES2::_get_variable_type(const StringName &p_type) { + // RS::GlobalVariableType gvt = ((RasterizerStorageRD *)(RendererStorage::base_singleton))->global_variable_get_type_internal(p_type); + RS::GlobalVariableType gvt = RS::GLOBAL_VAR_TYPE_MAX; + return RS::global_variable_type_get_shader_datatype(gvt); +} + +Error ShaderCompilerGLES2::compile(GD_VS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code) { + + ShaderLanguage::VaryingFunctionNames var_names; + + Error err = parser.compile(p_code, ShaderTypes::get_singleton()->get_functions(p_mode), ShaderTypes::get_singleton()->get_modes(p_mode), var_names, ShaderTypes::get_singleton()->get_types(), _get_variable_type); + + // Error ShaderLanguage::compile(const String &p_code, const Map &p_functions, const Vector &p_render_modes, const Set &p_shader_types, GlobalVariableGetTypeFunc p_global_variable_type_func) { + if (err != OK) { + Vector shader = p_code.split("\n"); + for (int i = 0; i < shader.size(); i++) { + print_line(itos(i + 1) + " " + shader[i]); + } + + _err_print_error(NULL, p_path.utf8().get_data(), parser.get_error_line(), parser.get_error_text().utf8().get_data(), ERR_HANDLER_SHADER); + return err; + } + + r_gen_code.custom_defines.clear(); + r_gen_code.uniforms.clear(); + r_gen_code.texture_uniforms.clear(); + r_gen_code.texture_hints.clear(); + r_gen_code.vertex = String(); + r_gen_code.vertex_global = String(); + r_gen_code.fragment = String(); + r_gen_code.fragment_global = String(); + r_gen_code.light = String(); + r_gen_code.uses_fragment_time = false; + r_gen_code.uses_vertex_time = false; + + used_name_defines.clear(); + used_rmode_defines.clear(); + used_flag_pointers.clear(); + + _dump_node_code(parser.get_shader(), 1, r_gen_code, *p_actions, actions[p_mode], false); + + return OK; +} + +ShaderCompilerGLES2::ShaderCompilerGLES2() { + /** CANVAS ITEM SHADER **/ + + actions[GD_VS::SHADER_CANVAS_ITEM].renames["VERTEX"] = "outvec.xy"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["UV"] = "uv"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["POINT_SIZE"] = "point_size"; + + actions[GD_VS::SHADER_CANVAS_ITEM].renames["WORLD_MATRIX"] = "modelview_matrix"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["PROJECTION_MATRIX"] = "projection_matrix"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["EXTRA_MATRIX"] = "extra_matrix_instance"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["TIME"] = "time"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["AT_LIGHT_PASS"] = "at_light_pass"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["INSTANCE_CUSTOM"] = "instance_custom"; + + actions[GD_VS::SHADER_CANVAS_ITEM].renames["COLOR"] = "color"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["MODULATE"] = "final_modulate"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["NORMAL"] = "normal"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"] = "normal_map"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"] = "normal_depth"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["TEXTURE"] = "color_texture"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"] = "color_texpixel_size"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["NORMAL_TEXTURE"] = "normal_texture"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["SCREEN_UV"] = "screen_uv"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["SCREEN_TEXTURE"] = "screen_texture"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["SCREEN_PIXEL_SIZE"] = "screen_pixel_size"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["FRAGCOORD"] = "gl_FragCoord"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["POINT_COORD"] = "gl_PointCoord"; + + actions[GD_VS::SHADER_CANVAS_ITEM].renames["LIGHT_VEC"] = "light_vec"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["LIGHT_HEIGHT"] = "light_height"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["LIGHT_COLOR"] = "light_color"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["LIGHT_UV"] = "light_uv"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["LIGHT"] = "light"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["SHADOW_COLOR"] = "shadow_color"; + actions[GD_VS::SHADER_CANVAS_ITEM].renames["SHADOW_VEC"] = "shadow_vec"; + + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["COLOR"] = "#define COLOR_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["MODULATE"] = "#define MODULATE_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["NORMAL"] = "#define NORMAL_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["NORMALMAP"] = "#define NORMALMAP_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["SHADOW_VEC"] = "#define SHADOW_VEC_USED\n"; + + // Ported from GLES3 + + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["sinh"] = "#define SINH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["cosh"] = "#define COSH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["tanh"] = "#define TANH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["asinh"] = "#define ASINH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["acosh"] = "#define ACOSH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["atanh"] = "#define ATANH_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["determinant"] = "#define DETERMINANT_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["transpose"] = "#define TRANSPOSE_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["outerProduct"] = "#define OUTER_PRODUCT_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["round"] = "#define ROUND_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["roundEven"] = "#define ROUND_EVEN_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["inverse"] = "#define INVERSE_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["isinf"] = "#define IS_INF_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["isnan"] = "#define IS_NAN_USED\n"; + actions[GD_VS::SHADER_CANVAS_ITEM].usage_defines["trunc"] = "#define TRUNC_USED\n"; + + /** SPATIAL SHADER **/ + + actions[GD_VS::SHADER_SPATIAL].renames["WORLD_MATRIX"] = "world_transform"; + actions[GD_VS::SHADER_SPATIAL].renames["INV_CAMERA_MATRIX"] = "camera_inverse_matrix"; + actions[GD_VS::SHADER_SPATIAL].renames["CAMERA_MATRIX"] = "camera_matrix"; + actions[GD_VS::SHADER_SPATIAL].renames["PROJECTION_MATRIX"] = "projection_matrix"; + actions[GD_VS::SHADER_SPATIAL].renames["INV_PROJECTION_MATRIX"] = "projection_inverse_matrix"; + actions[GD_VS::SHADER_SPATIAL].renames["MODELVIEW_MATRIX"] = "modelview"; + + actions[GD_VS::SHADER_SPATIAL].renames["VERTEX"] = "vertex.xyz"; + actions[GD_VS::SHADER_SPATIAL].renames["NORMAL"] = "normal"; + actions[GD_VS::SHADER_SPATIAL].renames["TANGENT"] = "tangent"; + actions[GD_VS::SHADER_SPATIAL].renames["BINORMAL"] = "binormal"; + actions[GD_VS::SHADER_SPATIAL].renames["POSITION"] = "position"; + actions[GD_VS::SHADER_SPATIAL].renames["UV"] = "uv_interp"; + actions[GD_VS::SHADER_SPATIAL].renames["UV2"] = "uv2_interp"; + actions[GD_VS::SHADER_SPATIAL].renames["COLOR"] = "color_interp"; + actions[GD_VS::SHADER_SPATIAL].renames["POINT_SIZE"] = "point_size"; + // gl_InstanceID is not available in OpenGL ES 2.0 + actions[GD_VS::SHADER_SPATIAL].renames["INSTANCE_ID"] = "0"; + + //builtins + + actions[GD_VS::SHADER_SPATIAL].renames["TIME"] = "time"; + actions[GD_VS::SHADER_SPATIAL].renames["VIEWPORT_SIZE"] = "viewport_size"; + + actions[GD_VS::SHADER_SPATIAL].renames["FRAGCOORD"] = "gl_FragCoord"; + actions[GD_VS::SHADER_SPATIAL].renames["FRONT_FACING"] = "gl_FrontFacing"; + actions[GD_VS::SHADER_SPATIAL].renames["NORMALMAP"] = "normalmap"; + actions[GD_VS::SHADER_SPATIAL].renames["NORMALMAP_DEPTH"] = "normaldepth"; + actions[GD_VS::SHADER_SPATIAL].renames["ALBEDO"] = "albedo"; + actions[GD_VS::SHADER_SPATIAL].renames["ALPHA"] = "alpha"; + actions[GD_VS::SHADER_SPATIAL].renames["METALLIC"] = "metallic"; + actions[GD_VS::SHADER_SPATIAL].renames["SPECULAR"] = "specular"; + actions[GD_VS::SHADER_SPATIAL].renames["ROUGHNESS"] = "roughness"; + actions[GD_VS::SHADER_SPATIAL].renames["RIM"] = "rim"; + actions[GD_VS::SHADER_SPATIAL].renames["RIM_TINT"] = "rim_tint"; + actions[GD_VS::SHADER_SPATIAL].renames["CLEARCOAT"] = "clearcoat"; + actions[GD_VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"] = "clearcoat_gloss"; + actions[GD_VS::SHADER_SPATIAL].renames["ANISOTROPY"] = "anisotropy"; + actions[GD_VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"] = "anisotropy_flow"; + actions[GD_VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength"; + actions[GD_VS::SHADER_SPATIAL].renames["TRANSMISSION"] = "transmission"; + actions[GD_VS::SHADER_SPATIAL].renames["AO"] = "ao"; + actions[GD_VS::SHADER_SPATIAL].renames["AO_LIGHT_AFFECT"] = "ao_light_affect"; + actions[GD_VS::SHADER_SPATIAL].renames["EMISSION"] = "emission"; + actions[GD_VS::SHADER_SPATIAL].renames["POINT_COORD"] = "gl_PointCoord"; + actions[GD_VS::SHADER_SPATIAL].renames["INSTANCE_CUSTOM"] = "instance_custom"; + actions[GD_VS::SHADER_SPATIAL].renames["SCREEN_UV"] = "screen_uv"; + actions[GD_VS::SHADER_SPATIAL].renames["SCREEN_TEXTURE"] = "screen_texture"; + actions[GD_VS::SHADER_SPATIAL].renames["DEPTH_TEXTURE"] = "depth_texture"; + // Defined in GLES3, but not available in GLES2 + //actions[GD_VS::SHADER_SPATIAL].renames["DEPTH"] = "gl_FragDepth"; + actions[GD_VS::SHADER_SPATIAL].renames["ALPHA_SCISSOR"] = "alpha_scissor"; + actions[GD_VS::SHADER_SPATIAL].renames["OUTPUT_IS_SRGB"] = "SHADER_IS_SRGB"; + + //for light + actions[GD_VS::SHADER_SPATIAL].renames["VIEW"] = "view"; + actions[GD_VS::SHADER_SPATIAL].renames["LIGHT_COLOR"] = "light_color"; + actions[GD_VS::SHADER_SPATIAL].renames["LIGHT"] = "light"; + actions[GD_VS::SHADER_SPATIAL].renames["ATTENUATION"] = "attenuation"; + actions[GD_VS::SHADER_SPATIAL].renames["DIFFUSE_LIGHT"] = "diffuse_light"; + actions[GD_VS::SHADER_SPATIAL].renames["SPECULAR_LIGHT"] = "specular_light"; + + actions[GD_VS::SHADER_SPATIAL].usage_defines["TANGENT"] = "#define ENABLE_TANGENT_INTERP\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["BINORMAL"] = "@TANGENT"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["RIM"] = "#define LIGHT_USE_RIM\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["RIM_TINT"] = "@RIM"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["CLEARCOAT"] = "#define LIGHT_USE_CLEARCOAT\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["CLEARCOAT_GLOSS"] = "@CLEARCOAT"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["ANISOTROPY"] = "#define LIGHT_USE_ANISOTROPY\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["ANISOTROPY_FLOW"] = "@ANISOTROPY"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["AO"] = "#define ENABLE_AO\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["AO_LIGHT_AFFECT"] = "#define ENABLE_AO\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["UV"] = "#define ENABLE_UV_INTERP\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["UV2"] = "#define ENABLE_UV2_INTERP\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["NORMALMAP"] = "#define ENABLE_NORMALMAP\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["NORMALMAP_DEPTH"] = "@NORMALMAP"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["COLOR"] = "#define ENABLE_COLOR_INTERP\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["INSTANCE_CUSTOM"] = "#define ENABLE_INSTANCE_CUSTOM\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["ALPHA_SCISSOR"] = "#define ALPHA_SCISSOR_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["POSITION"] = "#define OVERRIDE_POSITION\n"; + + actions[GD_VS::SHADER_SPATIAL].usage_defines["SSS_STRENGTH"] = "#define ENABLE_SSS\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["TRANSMISSION"] = "#define TRANSMISSION_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["DEPTH_TEXTURE"] = "#define DEPTH_TEXTURE_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n"; + + actions[GD_VS::SHADER_SPATIAL].usage_defines["DIFFUSE_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["SPECULAR_LIGHT"] = "#define USE_LIGHT_SHADER_CODE\n"; + + // Ported from GLES3 + + actions[GD_VS::SHADER_SPATIAL].usage_defines["sinh"] = "#define SINH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["cosh"] = "#define COSH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["tanh"] = "#define TANH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["asinh"] = "#define ASINH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["acosh"] = "#define ACOSH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["atanh"] = "#define ATANH_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["determinant"] = "#define DETERMINANT_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["transpose"] = "#define TRANSPOSE_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["outerProduct"] = "#define OUTER_PRODUCT_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["round"] = "#define ROUND_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["roundEven"] = "#define ROUND_EVEN_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["inverse"] = "#define INVERSE_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["isinf"] = "#define IS_INF_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["isnan"] = "#define IS_NAN_USED\n"; + actions[GD_VS::SHADER_SPATIAL].usage_defines["trunc"] = "#define TRUNC_USED\n"; + + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["world_vertex_coords"] = "#define VERTEX_WORLD_COORDS_USED\n"; + + // Defined in GLES3, could be implemented in GLES2 too if there's a need for it + //actions[GD_VS::SHADER_SPATIAL].render_mode_defines["ensure_correct_normals"] = "#define ENSURE_CORRECT_NORMALS\n"; + // Defined in GLES3, might not be possible in GLES2 as gl_FrontFacing is not available + //actions[GD_VS::SHADER_SPATIAL].render_mode_defines["cull_front"] = "#define DO_SIDE_CHECK\n"; + //actions[GD_VS::SHADER_SPATIAL].render_mode_defines["cull_disabled"] = "#define DO_SIDE_CHECK\n"; + + bool force_lambert = GLOBAL_GET("rendering/quality/shading/force_lambert_over_burley"); + + if (!force_lambert) { + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["diffuse_burley"] = "#define DIFFUSE_BURLEY\n"; + } + + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["diffuse_oren_nayar"] = "#define DIFFUSE_OREN_NAYAR\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["diffuse_lambert_wrap"] = "#define DIFFUSE_LAMBERT_WRAP\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["diffuse_toon"] = "#define DIFFUSE_TOON\n"; + + bool force_blinn = GLOBAL_GET("rendering/quality/shading/force_blinn_over_ggx"); + + if (!force_blinn) { + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_SCHLICK_GGX\n"; + } else { + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_schlick_ggx"] = "#define SPECULAR_BLINN\n"; + } + + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_blinn"] = "#define SPECULAR_BLINN\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_phong"] = "#define SPECULAR_PHONG\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_toon"] = "#define SPECULAR_TOON\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["specular_disabled"] = "#define SPECULAR_DISABLED\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["shadows_disabled"] = "#define SHADOWS_DISABLED\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["ambient_light_disabled"] = "#define AMBIENT_LIGHT_DISABLED\n"; + actions[GD_VS::SHADER_SPATIAL].render_mode_defines["shadow_to_opacity"] = "#define USE_SHADOW_TO_OPACITY\n"; + + // No defines for particle shaders in GLES2, there are no GPU particles + + vertex_name = "vertex"; + fragment_name = "fragment"; + light_name = "light"; + time_name = "TIME"; + + List func_list; + + ShaderLanguage::get_builtin_funcs(&func_list); + + for (List::Element *E = func_list.front(); E; E = E->next()) { + internal_functions.insert(E->get()); + } +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/shader_compiler_gles2.h b/drivers/gles2/shader_compiler_gles2.h new file mode 100644 index 00000000000..580719c47ae --- /dev/null +++ b/drivers/gles2/shader_compiler_gles2.h @@ -0,0 +1,112 @@ +/*************************************************************************/ +/* shader_compiler_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "drivers/gles_common/rasterizer_version.h" +#ifdef GODOT_3 +#include "core/pair.h" +#include "core/string_builder.h" +#include "servers/visual/shader_language.h" +#include "servers/visual/shader_types.h" +#include "servers/visual_server.h" +#else +#include "core/string/string_builder.h" +#include "core/templates/pair.h" +#include "servers/rendering/shader_language.h" +#include "servers/rendering/shader_types.h" +#include "servers/rendering_server.h" +#endif + +class ShaderCompilerGLES2 { +public: + struct IdentifierActions { + Map> render_mode_values; + Map render_mode_flags; + Map usage_flag_pointers; + Map write_flag_pointers; + + Map *uniforms; + }; + + struct GeneratedCode { + Vector custom_defines; + Vector uniforms; + Vector texture_uniforms; + Vector texture_hints; + + String vertex_global; + String vertex; + String fragment_global; + String fragment; + String light; + + bool uses_fragment_time; + bool uses_vertex_time; + }; + +private: + ShaderLanguage parser; + + struct DefaultIdentifierActions { + Map renames; + Map render_mode_defines; + Map usage_defines; + }; + + void _dump_function_deps(ShaderLanguage::ShaderNode *p_node, const StringName &p_for_func, const Map &p_func_code, StringBuilder &r_to_add, Set &r_added); + String _dump_node_code(ShaderLanguage::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions, bool p_assigning, bool p_use_scope = true); + + StringName current_func_name; + StringName vertex_name; + StringName fragment_name; + StringName light_name; + StringName time_name; + + Set used_name_defines; + Set used_flag_pointers; + Set used_rmode_defines; + Set internal_functions; + + DefaultIdentifierActions actions[GD_VS::SHADER_MAX]; + + // compatibility with godot 4 + static ShaderLanguage::DataType _get_variable_type(const StringName &p_type); + +public: + Error compile(GD_VS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code); + + ShaderCompilerGLES2(); +}; + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/shader_gles2.cpp b/drivers/gles2/shader_gles2.cpp new file mode 100644 index 00000000000..ca493a219be --- /dev/null +++ b/drivers/gles2/shader_gles2.cpp @@ -0,0 +1,1136 @@ +/*************************************************************************/ +/* shader_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "shader_gles2.h" +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/os/memory.h" +#include "rasterizer_gles2.h" +#include "rasterizer_storage_gles2.h" + +#ifdef GODOT_3 +#include "core/print_string.h" +#include "core/project_settings.h" +#include "core/string_builder.h" +#else +#include "core/config/project_settings.h" +#include "core/string/print_string.h" +#include "core/string/string_builder.h" +#endif + +// #define DEBUG_OPENGL + +// #include "shaders/copy.glsl.gen.h" + +#ifdef DEBUG_OPENGL + +#define DEBUG_TEST_ERROR(m_section) \ + { \ + uint32_t err = glGetError(); \ + if (err) { \ + print_line("OpenGL Error #" + itos(err) + " at: " + m_section); \ + } \ + } +#else + +#define DEBUG_TEST_ERROR(m_section) + +#endif + +ShaderGLES2 *ShaderGLES2::active = NULL; + +//#define DEBUG_SHADER + +#ifdef DEBUG_SHADER + +#define DEBUG_PRINT(m_text) print_line(m_text); + +#else + +#define DEBUG_PRINT(m_text) + +#endif + +GLint ShaderGLES2::get_uniform_location(int p_index) const { + ERR_FAIL_COND_V(!version, -1); + + return version->uniform_location[p_index]; +} + +//#ifdef GODOT_3 + +bool ShaderGLES2::bind() { + if (active != this || !version || new_conditional_version.key != conditional_version.key) { + conditional_version = new_conditional_version; + version = get_current_version(); + } else { + return false; + } + + ERR_FAIL_COND_V(!version, false); + + if (!version->ok) { //broken, unable to bind (do not throw error, you saw it before already when it failed compilation). + glUseProgram(0); + return false; + } + + glUseProgram(version->id); + + DEBUG_TEST_ERROR("use program"); + + active = this; + uniforms_dirty = true; + + return true; +} + +void ShaderGLES2::unbind() { + version = NULL; + glUseProgram(0); + uniforms_dirty = true; + active = NULL; +} + +static void _display_error_with_code(const String &p_error, const Vector &p_code) { + int line = 1; + String total_code; + + for (int i = 0; i < p_code.size(); i++) { + total_code += String(p_code[i]); + } + + Vector lines = String(total_code).split("\n"); + + for (int j = 0; j < lines.size(); j++) { + print_line(itos(line) + ": " + lines[j]); + line++; + } + + ERR_PRINT(p_error); +} + +static String _mkid(const String &p_id) { + String id = "m_" + p_id; + return id.replace("__", "_dus_"); //doubleunderscore is reserved in glsl +} + +ShaderGLES2::Version *ShaderGLES2::get_current_version() { + if (!valid) + return nullptr; + + Version *_v = version_map.getptr(conditional_version); + + if (_v) { + if (conditional_version.code_version != 0) { + CustomCode *cc = custom_code_map.getptr(conditional_version.code_version); + ERR_FAIL_COND_V(!cc, _v); + if (cc->version == _v->code_version) + return _v; + } else { + return _v; + } + } + + if (!_v) + version_map[conditional_version] = Version(); + + Version &v = version_map[conditional_version]; + + if (!_v) { + v.uniform_location = memnew_arr(GLint, uniform_count); + } else { + if (v.ok) { + glDeleteShader(v.vert_id); + glDeleteShader(v.frag_id); + glDeleteProgram(v.id); + v.id = 0; + } + } + + v.ok = false; + + Vector strings; + +#ifdef GLES_OVER_GL + strings.push_back("#version 120\n"); + strings.push_back("#define USE_GLES_OVER_GL\n"); + + // test + strings.push_back("#define highp\n"); + //#ifdef USE_GLES_OVER_GL + //#define lowp + //#define mediump + //#define highp + //#else + // precision highp float; + // precision highp int; + //#endif + +#else + strings.push_back("#version 100\n"); +//angle does not like +#ifdef JAVASCRIPT_ENABLED + strings.push_back("#define USE_HIGHP_PRECISION\n"); +#endif + + if (GLOBAL_GET("rendering/gles2/compatibility/enable_high_float.Android")) { + // enable USE_HIGHP_PRECISION but safeguarded by an availability check as highp support is optional in GLES2 + // see Section 4.5.4 of the GLSL_ES_Specification_1.00 + strings.push_back("#ifdef GL_FRAGMENT_PRECISION_HIGH\n #define USE_HIGHP_PRECISION\n#endif\n"); + } + +#endif + +#ifdef ANDROID_ENABLED + strings.push_back("#define ANDROID_ENABLED\n"); +#endif + + for (int i = 0; i < custom_defines.size(); i++) { + strings.push_back(custom_defines[i].get_data()); + strings.push_back("\n"); + } + + for (int j = 0; j < conditional_count; j++) { + bool enable = (conditional_version.version & (1 << j)) > 0; + + if (enable) { + strings.push_back(conditional_defines[j]); + DEBUG_PRINT(conditional_defines[j]); + } + } + + // keep them around during the function + CharString code_string; + CharString code_string2; + CharString code_globals; + + CustomCode *cc = NULL; + + if (conditional_version.code_version > 0) { + cc = custom_code_map.getptr(conditional_version.code_version); + + ERR_FAIL_COND_V(!cc, NULL); + v.code_version = cc->version; + } + + // program + + v.id = glCreateProgram(); + ERR_FAIL_COND_V(v.id == 0, NULL); + + if (cc) { + for (int i = 0; i < cc->custom_defines.size(); i++) { + strings.push_back(cc->custom_defines.write[i]); + DEBUG_PRINT("CD #" + itos(i) + ": " + String(cc->custom_defines[i].get_data())); + } + } + + // vertex shader + + int string_base_size = strings.size(); + + strings.push_back(vertex_code0.get_data()); + + if (cc) { + code_globals = cc->vertex_globals.ascii(); + strings.push_back(code_globals.get_data()); + } + + strings.push_back(vertex_code1.get_data()); + + if (cc) { + code_string = cc->vertex.ascii(); + strings.push_back(code_string.get_data()); + } + + strings.push_back(vertex_code2.get_data()); + +#ifdef DEBUG_SHADER + + DEBUG_PRINT("\nVertex Code:\n\n" + String(code_string.get_data())); + +#endif + + v.vert_id = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(v.vert_id, strings.size(), &strings[0], NULL); + glCompileShader(v.vert_id); + + GLint status; + + glGetShaderiv(v.vert_id, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { + GLsizei iloglen; + glGetShaderiv(v.vert_id, GL_INFO_LOG_LENGTH, &iloglen); + + if (iloglen < 0) { + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + + ERR_PRINT("No OpenGL vertex shader compiler log. What the frick?"); + } else { + if (iloglen == 0) { + iloglen = 4096; // buggy driver (Adreno 220+) + } + + char *ilogmem = (char *)Memory::alloc_static(iloglen + 1); + ilogmem[iloglen] = '\0'; + glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem); + + String err_string = get_shader_name() + ": Vertex shader compilation failed:\n"; + + err_string += ilogmem; + + _display_error_with_code(err_string, strings); + + Memory::free_static(ilogmem); + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + } + + ERR_FAIL_V(NULL); + } + + strings.resize(string_base_size); + + // fragment shader + + strings.push_back(fragment_code0.get_data()); + + if (cc) { + code_globals = cc->fragment_globals.ascii(); + strings.push_back(code_globals.get_data()); + } + + strings.push_back(fragment_code1.get_data()); + + if (cc) { + code_string = cc->light.ascii(); + strings.push_back(code_string.get_data()); + } + + strings.push_back(fragment_code2.get_data()); + + if (cc) { + code_string2 = cc->fragment.ascii(); + strings.push_back(code_string2.get_data()); + } + + strings.push_back(fragment_code3.get_data()); + +#ifdef DEBUG_SHADER + + if (cc) { + DEBUG_PRINT("\nFragment Code:\n\n" + String(cc->fragment_globals)); + } + DEBUG_PRINT("\nFragment Code:\n\n" + String(code_string.get_data())); +#endif + + v.frag_id = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(v.frag_id, strings.size(), &strings[0], NULL); + glCompileShader(v.frag_id); + + glGetShaderiv(v.frag_id, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { + GLsizei iloglen; + glGetShaderiv(v.frag_id, GL_INFO_LOG_LENGTH, &iloglen); + + if (iloglen < 0) { + glDeleteShader(v.frag_id); + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + + ERR_PRINT("No OpenGL fragment shader compiler log. What the frick?"); + } else { + if (iloglen == 0) { + iloglen = 4096; // buggy driver (Adreno 220+) + } + + char *ilogmem = (char *)Memory::alloc_static(iloglen + 1); + ilogmem[iloglen] = '\0'; + glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem); + + String err_string = get_shader_name() + ": Fragment shader compilation failed:\n"; + + err_string += ilogmem; + + _display_error_with_code(err_string, strings); + + Memory::free_static(ilogmem); + glDeleteShader(v.frag_id); + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + } + + ERR_FAIL_V(NULL); + } + + glAttachShader(v.id, v.frag_id); + glAttachShader(v.id, v.vert_id); + + // bind the attribute locations. This has to be done before linking so that the + // linker doesn't assign some random indices + + for (int i = 0; i < attribute_pair_count; i++) { + glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name); + } + + glLinkProgram(v.id); + + glGetProgramiv(v.id, GL_LINK_STATUS, &status); + if (status == GL_FALSE) { + GLsizei iloglen; + glGetProgramiv(v.id, GL_INFO_LOG_LENGTH, &iloglen); + + if (iloglen < 0) { + glDeleteShader(v.frag_id); + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + + ERR_PRINT("No OpenGL program link log. What the frick?"); + ERR_FAIL_V(NULL); + } + + if (iloglen == 0) { + iloglen = 4096; // buggy driver (Adreno 220+) + } + + char *ilogmem = (char *)Memory::alloc_static(iloglen + 1); + ilogmem[iloglen] = '\0'; + glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem); + + String err_string = get_shader_name() + ": Program linking failed:\n"; + + err_string += ilogmem; + + _display_error_with_code(err_string, strings); + + Memory::free_static(ilogmem); + glDeleteShader(v.frag_id); + glDeleteShader(v.vert_id); + glDeleteProgram(v.id); + v.id = 0; + + ERR_FAIL_V(NULL); + } + + // get uniform locations + + glUseProgram(v.id); + + for (int i = 0; i < uniform_count; i++) { + v.uniform_location[i] = glGetUniformLocation(v.id, uniform_names[i]); + } + + for (int i = 0; i < texunit_pair_count; i++) { + GLint loc = glGetUniformLocation(v.id, texunit_pairs[i].name); + if (loc >= 0) { + if (texunit_pairs[i].index < 0) { + glUniform1i(loc, max_image_units + texunit_pairs[i].index); + } else { + glUniform1i(loc, texunit_pairs[i].index); + } + } + } + + if (cc) { + // uniforms + for (int i = 0; i < cc->custom_uniforms.size(); i++) { + String native_uniform_name = _mkid(cc->custom_uniforms[i]); + GLint location = glGetUniformLocation(v.id, (native_uniform_name).ascii().get_data()); + v.custom_uniform_locations[cc->custom_uniforms[i]] = location; + } + + // textures + for (int i = 0; i < cc->texture_uniforms.size(); i++) { + String native_uniform_name = _mkid(cc->texture_uniforms[i]); + GLint location = glGetUniformLocation(v.id, (native_uniform_name).ascii().get_data()); + v.custom_uniform_locations[cc->texture_uniforms[i]] = location; + glUniform1i(location, i); + } + } + + glUseProgram(0); + v.ok = true; + + if (cc) { + cc->versions.insert(conditional_version.version); + } + + return &v; +} + +GLint ShaderGLES2::get_uniform_location(const String &p_name) const { + ERR_FAIL_COND_V(!version, -1); + return glGetUniformLocation(version->id, p_name.ascii().get_data()); +} + +void ShaderGLES2::setup( + const char **p_conditional_defines, + int p_conditional_count, + const char **p_uniform_names, + int p_uniform_count, + const AttributePair *p_attribute_pairs, + int p_attribute_count, + const TexUnitPair *p_texunit_pairs, + int p_texunit_pair_count, + const char *p_vertex_code, + const char *p_fragment_code, + int p_vertex_code_start, + int p_fragment_code_start) { + ERR_FAIL_COND(version); + + conditional_version.key = 0; + new_conditional_version.key = 0; + uniform_count = p_uniform_count; + conditional_count = p_conditional_count; + conditional_defines = p_conditional_defines; + uniform_names = p_uniform_names; + vertex_code = p_vertex_code; + fragment_code = p_fragment_code; + texunit_pairs = p_texunit_pairs; + texunit_pair_count = p_texunit_pair_count; + vertex_code_start = p_vertex_code_start; + fragment_code_start = p_fragment_code_start; + attribute_pairs = p_attribute_pairs; + attribute_pair_count = p_attribute_count; + + { + String globals_tag = "\nVERTEX_SHADER_GLOBALS"; + String code_tag = "\nVERTEX_SHADER_CODE"; + String code = vertex_code; + int cpos = code.find(globals_tag); + if (cpos == -1) { + vertex_code0 = code.ascii(); + } else { + vertex_code0 = code.substr(0, cpos).ascii(); + code = code.substr(cpos + globals_tag.length(), code.length()); + + cpos = code.find(code_tag); + + if (cpos == -1) { + vertex_code1 = code.ascii(); + } else { + vertex_code1 = code.substr(0, cpos).ascii(); + vertex_code2 = code.substr(cpos + code_tag.length(), code.length()).ascii(); + } + } + } + + { + String globals_tag = "\nFRAGMENT_SHADER_GLOBALS"; + String code_tag = "\nFRAGMENT_SHADER_CODE"; + String light_code_tag = "\nLIGHT_SHADER_CODE"; + String code = fragment_code; + int cpos = code.find(globals_tag); + if (cpos == -1) { + fragment_code0 = code.ascii(); + } else { + fragment_code0 = code.substr(0, cpos).ascii(); + code = code.substr(cpos + globals_tag.length(), code.length()); + + cpos = code.find(light_code_tag); + + String code2; + + if (cpos != -1) { + fragment_code1 = code.substr(0, cpos).ascii(); + code2 = code.substr(cpos + light_code_tag.length(), code.length()); + } else { + code2 = code; + } + + cpos = code2.find(code_tag); + if (cpos == -1) { + fragment_code2 = code2.ascii(); + } else { + fragment_code2 = code2.substr(0, cpos).ascii(); + fragment_code3 = code2.substr(cpos + code_tag.length(), code2.length()).ascii(); + } + } + } + + glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_image_units); + + valid = true; +} + +void ShaderGLES2::finish() { + const VersionKey *V = NULL; + + while ((V = version_map.next(V))) { + Version &v = version_map[*V]; + glDeleteShader(v.vert_id); + glDeleteShader(v.frag_id); + glDeleteProgram(v.id); + + if (v.uniform_location) + memdelete_arr(v.uniform_location); + } +} + +void ShaderGLES2::clear_caches() { + const VersionKey *V = NULL; + + while ((V = version_map.next(V))) { + Version &v = version_map[*V]; + glDeleteShader(v.vert_id); + glDeleteShader(v.frag_id); + glDeleteProgram(v.id); + memdelete_arr(v.uniform_location); + } + + version_map.clear(); + + custom_code_map.clear(); + version = NULL; + last_custom_code = 1; + uniforms_dirty = true; +} + +uint32_t ShaderGLES2::create_custom_shader() { + custom_code_map[last_custom_code] = CustomCode(); + custom_code_map[last_custom_code].version = 1; + return last_custom_code++; +} + +void ShaderGLES2::set_custom_shader_code(uint32_t p_code_id, + const String &p_vertex, + const String &p_vertex_globals, + const String &p_fragment, + const String &p_light, + const String &p_fragment_globals, + const Vector &p_uniforms, + const Vector &p_texture_uniforms, + const Vector &p_custom_defines) { + CustomCode *cc = custom_code_map.getptr(p_code_id); + ERR_FAIL_COND(!cc); + + cc->vertex = p_vertex; + cc->vertex_globals = p_vertex_globals; + cc->fragment = p_fragment; + cc->fragment_globals = p_fragment_globals; + cc->light = p_light; + cc->custom_uniforms = p_uniforms; + cc->custom_defines = p_custom_defines; + cc->texture_uniforms = p_texture_uniforms; + cc->version++; +} + +void ShaderGLES2::set_custom_shader(uint32_t p_code_id) { + new_conditional_version.code_version = p_code_id; +} + +void ShaderGLES2::free_custom_shader(uint32_t p_code_id) { + ERR_FAIL_COND(!custom_code_map.has(p_code_id)); + if (conditional_version.code_version == p_code_id) { + conditional_version.code_version = 0; //do not keep using a version that is going away + unbind(); + } + + VersionKey key; + key.code_version = p_code_id; + for (Set::Element *E = custom_code_map[p_code_id].versions.front(); E; E = E->next()) { + key.version = E->get(); + ERR_CONTINUE(!version_map.has(key)); + Version &v = version_map[key]; + + glDeleteShader(v.vert_id); + glDeleteShader(v.frag_id); + glDeleteProgram(v.id); + memdelete_arr(v.uniform_location); + v.id = 0; + + version_map.erase(key); + } + + custom_code_map.erase(p_code_id); +} + +void ShaderGLES2::use_material(void *p_material) { + RasterizerStorageGLES2::Material *material = (RasterizerStorageGLES2::Material *)p_material; + + if (!material) { + return; + } + + if (!material->shader) { + return; + } + + Version *v = version_map.getptr(conditional_version); + + // bind uniforms + for (Map::Element *E = material->shader->uniforms.front(); E; E = E->next()) { + if (E->get().texture_order >= 0) + continue; // this is a texture, doesn't go here + + Map::Element *L = v->custom_uniform_locations.find(E->key()); + if (!L || L->get() < 0) + continue; //uniform not valid + + GLuint location = L->get(); + + Map::Element *V = material->params.find(E->key()); + + if (V) { + switch (E->get().type) { + case ShaderLanguage::TYPE_BOOL: { + bool boolean = V->get(); + glUniform1i(location, boolean ? 1 : 0); + } break; + + case ShaderLanguage::TYPE_BVEC2: { + int flags = V->get(); + glUniform2i(location, (flags & 1) ? 1 : 0, (flags & 2) ? 1 : 0); + } break; + + case ShaderLanguage::TYPE_BVEC3: { + int flags = V->get(); + glUniform3i(location, (flags & 1) ? 1 : 0, (flags & 2) ? 1 : 0, (flags & 4) ? 1 : 0); + + } break; + + case ShaderLanguage::TYPE_BVEC4: { + int flags = V->get(); + glUniform4i(location, (flags & 1) ? 1 : 0, (flags & 2) ? 1 : 0, (flags & 4) ? 1 : 0, (flags & 8) ? 1 : 0); + + } break; + + case ShaderLanguage::TYPE_INT: + case ShaderLanguage::TYPE_UINT: { + int value = V->get(); + glUniform1i(location, value); + } break; + + case ShaderLanguage::TYPE_IVEC2: + case ShaderLanguage::TYPE_UVEC2: { + Array r = V->get(); + const int count = 2; + if (r.size() == count) { + int values[count]; + for (int i = 0; i < count; i++) { + values[i] = r[i]; + } + glUniform2i(location, values[0], values[1]); + } + + } break; + + case ShaderLanguage::TYPE_IVEC3: + case ShaderLanguage::TYPE_UVEC3: { + Array r = V->get(); + const int count = 3; + if (r.size() == count) { + int values[count]; + for (int i = 0; i < count; i++) { + values[i] = r[i]; + } + glUniform3i(location, values[0], values[1], values[2]); + } + + } break; + + case ShaderLanguage::TYPE_IVEC4: + case ShaderLanguage::TYPE_UVEC4: { + Array r = V->get(); + const int count = 4; + if (r.size() == count) { + int values[count]; + for (int i = 0; i < count; i++) { + values[i] = r[i]; + } + glUniform4i(location, values[0], values[1], values[2], values[3]); + } + + } break; + + case ShaderLanguage::TYPE_FLOAT: { + float value = V->get(); + glUniform1f(location, value); + + } break; + + case ShaderLanguage::TYPE_VEC2: { + Vector2 value = V->get(); + glUniform2f(location, value.x, value.y); + } break; + + case ShaderLanguage::TYPE_VEC3: { + Vector3 value = V->get(); + glUniform3f(location, value.x, value.y, value.z); + } break; + + case ShaderLanguage::TYPE_VEC4: { + if (V->get().get_type() == Variant::COLOR) { + Color value = V->get(); + glUniform4f(location, value.r, value.g, value.b, value.a); + } else if (V->get().get_type() == Variant::QUATERNION) { + Quaternion value = V->get(); + glUniform4f(location, value.x, value.y, value.z, value.w); + } else { + Plane value = V->get(); + glUniform4f(location, value.normal.x, value.normal.y, value.normal.z, value.d); + } + + } break; + + case ShaderLanguage::TYPE_MAT2: { + Transform2D tr = V->get(); + GLfloat matrix[4] = { + /* build a 16x16 matrix */ + tr.elements[0][0], + tr.elements[0][1], + tr.elements[1][0], + tr.elements[1][1], + }; + glUniformMatrix2fv(location, 1, GL_FALSE, matrix); + + } break; + + case ShaderLanguage::TYPE_MAT3: { + Basis val = V->get(); + + GLfloat mat[9] = { + val.elements[0][0], + val.elements[1][0], + val.elements[2][0], + val.elements[0][1], + val.elements[1][1], + val.elements[2][1], + val.elements[0][2], + val.elements[1][2], + val.elements[2][2], + }; + + glUniformMatrix3fv(location, 1, GL_FALSE, mat); + + } break; + + case ShaderLanguage::TYPE_MAT4: { + Transform2D tr = V->get(); + GLfloat matrix[16] = { /* build a 16x16 matrix */ + tr.elements[0][0], + tr.elements[0][1], + 0, + 0, + tr.elements[1][0], + tr.elements[1][1], + 0, + 0, + 0, + 0, + 1, + 0, + tr.elements[2][0], + tr.elements[2][1], + 0, + 1 + }; + + glUniformMatrix4fv(location, 1, GL_FALSE, matrix); + + } break; + + default: { + ERR_PRINT("ShaderNode type missing, bug?"); + } break; + } + } else if (E->get().default_value.size()) { + const Vector &values = E->get().default_value; + switch (E->get().type) { + case ShaderLanguage::TYPE_BOOL: { + glUniform1i(location, values[0].boolean); + } break; + + case ShaderLanguage::TYPE_BVEC2: { + glUniform2i(location, values[0].boolean, values[1].boolean); + } break; + + case ShaderLanguage::TYPE_BVEC3: { + glUniform3i(location, values[0].boolean, values[1].boolean, values[2].boolean); + } break; + + case ShaderLanguage::TYPE_BVEC4: { + glUniform4i(location, values[0].boolean, values[1].boolean, values[2].boolean, values[3].boolean); + } break; + + case ShaderLanguage::TYPE_INT: { + glUniform1i(location, values[0].sint); + } break; + + case ShaderLanguage::TYPE_IVEC2: { + glUniform2i(location, values[0].sint, values[1].sint); + } break; + + case ShaderLanguage::TYPE_IVEC3: { + glUniform3i(location, values[0].sint, values[1].sint, values[2].sint); + } break; + + case ShaderLanguage::TYPE_IVEC4: { + glUniform4i(location, values[0].sint, values[1].sint, values[2].sint, values[3].sint); + } break; + + case ShaderLanguage::TYPE_UINT: { + glUniform1i(location, values[0].uint); + } break; + + case ShaderLanguage::TYPE_UVEC2: { + glUniform2i(location, values[0].uint, values[1].uint); + } break; + + case ShaderLanguage::TYPE_UVEC3: { + glUniform3i(location, values[0].uint, values[1].uint, values[2].uint); + } break; + + case ShaderLanguage::TYPE_UVEC4: { + glUniform4i(location, values[0].uint, values[1].uint, values[2].uint, values[3].uint); + } break; + + case ShaderLanguage::TYPE_FLOAT: { + glUniform1f(location, values[0].real); + } break; + + case ShaderLanguage::TYPE_VEC2: { + glUniform2f(location, values[0].real, values[1].real); + } break; + + case ShaderLanguage::TYPE_VEC3: { + glUniform3f(location, values[0].real, values[1].real, values[2].real); + } break; + + case ShaderLanguage::TYPE_VEC4: { + glUniform4f(location, values[0].real, values[1].real, values[2].real, values[3].real); + } break; + + case ShaderLanguage::TYPE_MAT2: { + GLfloat mat[4]; + + for (int i = 0; i < 4; i++) { + mat[i] = values[i].real; + } + + glUniformMatrix2fv(location, 1, GL_FALSE, mat); + } break; + + case ShaderLanguage::TYPE_MAT3: { + GLfloat mat[9]; + + for (int i = 0; i < 9; i++) { + mat[i] = values[i].real; + } + + glUniformMatrix3fv(location, 1, GL_FALSE, mat); + + } break; + + case ShaderLanguage::TYPE_MAT4: { + GLfloat mat[16]; + + for (int i = 0; i < 16; i++) { + mat[i] = values[i].real; + } + + glUniformMatrix4fv(location, 1, GL_FALSE, mat); + + } break; + + case ShaderLanguage::TYPE_SAMPLER2D: { + } break; + + /* + case ShaderLanguage::TYPE_SAMPLEREXT: { + } break; +*/ + case ShaderLanguage::TYPE_ISAMPLER2D: { + } break; + + case ShaderLanguage::TYPE_USAMPLER2D: { + } break; + + case ShaderLanguage::TYPE_SAMPLERCUBE: { + } break; + + case ShaderLanguage::TYPE_SAMPLER2DARRAY: + case ShaderLanguage::TYPE_ISAMPLER2DARRAY: + case ShaderLanguage::TYPE_USAMPLER2DARRAY: + case ShaderLanguage::TYPE_SAMPLER3D: + case ShaderLanguage::TYPE_ISAMPLER3D: + case ShaderLanguage::TYPE_USAMPLER3D: { + // Not implemented in GLES2 + } break; + + case ShaderLanguage::TYPE_VOID: { + // Nothing to do? + } break; + default: { + ERR_PRINT("ShaderNode type missing, bug?"); + } break; + } + } else { //zero + + switch (E->get().type) { + case ShaderLanguage::TYPE_BOOL: { + glUniform1i(location, GL_FALSE); + } break; + + case ShaderLanguage::TYPE_BVEC2: { + glUniform2i(location, GL_FALSE, GL_FALSE); + } break; + + case ShaderLanguage::TYPE_BVEC3: { + glUniform3i(location, GL_FALSE, GL_FALSE, GL_FALSE); + } break; + + case ShaderLanguage::TYPE_BVEC4: { + glUniform4i(location, GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + } break; + + case ShaderLanguage::TYPE_INT: { + glUniform1i(location, 0); + } break; + + case ShaderLanguage::TYPE_IVEC2: { + glUniform2i(location, 0, 0); + } break; + + case ShaderLanguage::TYPE_IVEC3: { + glUniform3i(location, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_IVEC4: { + glUniform4i(location, 0, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_UINT: { + glUniform1i(location, 0); + } break; + + case ShaderLanguage::TYPE_UVEC2: { + glUniform2i(location, 0, 0); + } break; + + case ShaderLanguage::TYPE_UVEC3: { + glUniform3i(location, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_UVEC4: { + glUniform4i(location, 0, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_FLOAT: { + glUniform1f(location, 0); + } break; + + case ShaderLanguage::TYPE_VEC2: { + glUniform2f(location, 0, 0); + } break; + + case ShaderLanguage::TYPE_VEC3: { + glUniform3f(location, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_VEC4: { + glUniform4f(location, 0, 0, 0, 0); + } break; + + case ShaderLanguage::TYPE_MAT2: { + GLfloat mat[4] = { 0, 0, 0, 0 }; + + glUniformMatrix2fv(location, 1, GL_FALSE, mat); + } break; + + case ShaderLanguage::TYPE_MAT3: { + GLfloat mat[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + glUniformMatrix3fv(location, 1, GL_FALSE, mat); + + } break; + + case ShaderLanguage::TYPE_MAT4: { + GLfloat mat[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + glUniformMatrix4fv(location, 1, GL_FALSE, mat); + + } break; + + case ShaderLanguage::TYPE_SAMPLER2D: { + } break; + + /* + case ShaderLanguage::TYPE_SAMPLEREXT: { + } break; +*/ + + case ShaderLanguage::TYPE_ISAMPLER2D: { + } break; + + case ShaderLanguage::TYPE_USAMPLER2D: { + } break; + + case ShaderLanguage::TYPE_SAMPLERCUBE: { + } break; + + case ShaderLanguage::TYPE_SAMPLER2DARRAY: + case ShaderLanguage::TYPE_ISAMPLER2DARRAY: + case ShaderLanguage::TYPE_USAMPLER2DARRAY: + case ShaderLanguage::TYPE_SAMPLER3D: + case ShaderLanguage::TYPE_ISAMPLER3D: + case ShaderLanguage::TYPE_USAMPLER3D: { + // Not implemented in GLES2 + } break; + + case ShaderLanguage::TYPE_VOID: { + // Nothing to do? + } break; + default: { + ERR_PRINT("ShaderNode type missing, bug?"); + } break; + } + } + } +} + +ShaderGLES2::ShaderGLES2() { + version = NULL; + last_custom_code = 1; + uniforms_dirty = true; +} + +ShaderGLES2::~ShaderGLES2() { + finish(); +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/shader_gles2.h b/drivers/gles2/shader_gles2.h new file mode 100644 index 00000000000..4f327c27076 --- /dev/null +++ b/drivers/gles2/shader_gles2.h @@ -0,0 +1,283 @@ +/*************************************************************************/ +/* shader_gles2.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED + +// This must come first to avoid windows.h mess +#include "platform_config.h" +#ifndef GLES2_INCLUDE_H +#include +#else +#include GLES2_INCLUDE_H +#endif + +#include "core/math/camera_matrix.h" +#ifdef GODOT_3 +#include "core/hash_map.h" +#include "core/map.h" +#include "core/pair.h" +#include "core/variant.h" +#include "servers/visual/shader_language.h" +#else +#include "core/templates/hash_map.h" +#include "core/templates/map.h" +#include "core/templates/pair.h" +#include "core/variant/variant.h" +#include "servers/rendering/shader_language.h" +#endif + +#include + +class RasterizerStorageGLES2; +//#ifdef GODOT_3 + +class ShaderGLES2 { +protected: + struct Enum { + uint64_t mask; + uint64_t shift; + const char *defines[16]; + }; + + struct EnumValue { + uint64_t set_mask; + uint64_t clear_mask; + }; + + struct AttributePair { + const char *name; + int index; + }; + + struct UniformPair { + const char *name; + Variant::Type type_hint; + }; + + struct TexUnitPair { + const char *name; + int index; + }; + + bool uniforms_dirty; + +private: + bool valid = false; + + //@TODO Optimize to a fixed set of shader pools and use a LRU + int uniform_count; + int texunit_pair_count; + int conditional_count; + int vertex_code_start; + int fragment_code_start; + int attribute_pair_count; + + struct CustomCode { + String vertex; + String vertex_globals; + String fragment; + String fragment_globals; + String light; + uint32_t version; + Vector texture_uniforms; + Vector custom_uniforms; + Vector custom_defines; + Set versions; + }; + + struct Version { + GLuint id; + GLuint vert_id; + GLuint frag_id; + GLint *uniform_location; + Vector texture_uniform_locations; + Map custom_uniform_locations; + uint32_t code_version; + bool ok; + Version() { + id = 0; + vert_id = 0; + frag_id = 0; + uniform_location = NULL; + code_version = 0; + ok = false; + } + }; + + Version *version; + + union VersionKey { + struct { + uint32_t version; + uint32_t code_version; + }; + uint64_t key; + bool operator==(const VersionKey &p_key) const { return key == p_key.key; } + bool operator<(const VersionKey &p_key) const { return key < p_key.key; } + }; + + struct VersionKeyHash { + static _FORCE_INLINE_ uint32_t hash(const VersionKey &p_key) { return HashMapHasherDefault::hash(p_key.key); } + }; + + //this should use a way more cachefriendly version.. + HashMap version_map; + + HashMap custom_code_map; + uint32_t last_custom_code; + + VersionKey conditional_version; + VersionKey new_conditional_version; + + virtual String get_shader_name() const = 0; + + const char **conditional_defines; + const char **uniform_names; + const AttributePair *attribute_pairs; + const TexUnitPair *texunit_pairs; + const char *vertex_code; + const char *fragment_code; + CharString fragment_code0; + CharString fragment_code1; + CharString fragment_code2; + CharString fragment_code3; + + CharString vertex_code0; + CharString vertex_code1; + CharString vertex_code2; + + Vector custom_defines; + + Version *get_current_version(); + + static ShaderGLES2 *active; + + int max_image_units; + + Map>> uniform_values; + +protected: + _FORCE_INLINE_ int _get_uniform(int p_which) const; + _FORCE_INLINE_ void _set_conditional(int p_which, bool p_value); + + void setup(const char **p_conditional_defines, + int p_conditional_count, + const char **p_uniform_names, + int p_uniform_count, + const AttributePair *p_attribute_pairs, + int p_attribute_count, + const TexUnitPair *p_texunit_pairs, + int p_texunit_pair_count, + const char *p_vertex_code, + const char *p_fragment_code, + int p_vertex_code_start, + int p_fragment_code_start); + + ShaderGLES2(); + +public: + enum { + CUSTOM_SHADER_DISABLED = 0 + }; + + GLint get_uniform_location(const String &p_name) const; + GLint get_uniform_location(int p_index) const; + + static _FORCE_INLINE_ ShaderGLES2 *get_active() { return active; } + bool bind(); + void unbind(); + + inline GLuint get_program() const { return version ? version->id : 0; } + + void clear_caches(); + + uint32_t create_custom_shader(); + void set_custom_shader_code(uint32_t p_code_id, + const String &p_vertex, + const String &p_vertex_globals, + const String &p_fragment, + const String &p_light, + const String &p_fragment_globals, + const Vector &p_uniforms, + const Vector &p_texture_uniforms, + const Vector &p_custom_defines); + + void set_custom_shader(uint32_t p_code_id); + void free_custom_shader(uint32_t p_code_id); + + uint32_t get_version_key() const { return conditional_version.version; } + + // this void* is actually a RasterizerStorageGLES2::Material, but C++ doesn't + // like forward declared nested classes. + void use_material(void *p_material); + + _FORCE_INLINE_ uint32_t get_version() const { return new_conditional_version.version; } + _FORCE_INLINE_ bool is_version_valid() const { return version && version->ok; } + + virtual void init() = 0; + void finish(); + + void add_custom_define(const String &p_define) { + custom_defines.push_back(p_define.utf8()); + } + + void get_custom_defines(Vector *p_defines) { + for (int i = 0; i < custom_defines.size(); i++) { + p_defines->push_back(custom_defines[i].get_data()); + } + } + + void remove_custom_define(const String &p_define) { + custom_defines.erase(p_define.utf8()); + } + + virtual ~ShaderGLES2(); +}; + +// called a lot, made inline + +int ShaderGLES2::_get_uniform(int p_which) const { + ERR_FAIL_INDEX_V(p_which, uniform_count, -1); + ERR_FAIL_COND_V(!version, -1); + return version->uniform_location[p_which]; +} + +void ShaderGLES2::_set_conditional(int p_which, bool p_value) { + ERR_FAIL_INDEX(p_which, conditional_count); + if (p_value) + new_conditional_version.version |= (1 << p_which); + else + new_conditional_version.version &= ~(1 << p_which); +} + +#endif // GLES2_BACKEND_ENABLED diff --git a/drivers/gles2/shaders/SCsub b/drivers/gles2/shaders/SCsub new file mode 100644 index 00000000000..bcd6ea79fbb --- /dev/null +++ b/drivers/gles2/shaders/SCsub @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +Import("env") + +if "GLES2_GLSL" in env["BUILDERS"]: + env.GLES2_GLSL("copy.glsl") + # env.GLES2_GLSL('resolve.glsl'); + env.GLES2_GLSL("canvas.glsl") + env.GLES2_GLSL("canvas_shadow.glsl") + env.GLES2_GLSL("scene.glsl") + env.GLES2_GLSL("cubemap_filter.glsl") + env.GLES2_GLSL("cube_to_dp.glsl") + # env.GLES2_GLSL('blend_shape.glsl'); + # env.GLES2_GLSL('screen_space_reflection.glsl'); + env.GLES2_GLSL("effect_blur.glsl") + # env.GLES2_GLSL('subsurf_scattering.glsl'); + # env.GLES2_GLSL('ssao.glsl'); + # env.GLES2_GLSL('ssao_minify.glsl'); + # env.GLES2_GLSL('ssao_blur.glsl'); + # env.GLES2_GLSL('exposure.glsl'); + env.GLES2_GLSL("tonemap.glsl") + # env.GLES2_GLSL('particles.glsl'); + env.GLES2_GLSL("lens_distorted.glsl") diff --git a/drivers/gles2/shaders/blend_shape.glsl b/drivers/gles2/shaders/blend_shape.glsl new file mode 100644 index 00000000000..247e98c7aad --- /dev/null +++ b/drivers/gles2/shaders/blend_shape.glsl @@ -0,0 +1,192 @@ +/* clang-format off */ +[vertex] + +/* +from VisualServer: + +ARRAY_VERTEX=0, +ARRAY_NORMAL=1, +ARRAY_TANGENT=2, +ARRAY_COLOR=3, +ARRAY_TEX_UV=4, +ARRAY_TEX_UV2=5, +ARRAY_BONES=6, +ARRAY_WEIGHTS=7, +ARRAY_INDEX=8, +*/ + +#ifdef USE_2D_VERTEX +#define VFORMAT vec2 +#else +#define VFORMAT vec3 +#endif + +/* INPUT ATTRIBS */ + +layout(location = 0) in highp VFORMAT vertex_attrib; +/* clang-format on */ +layout(location = 1) in vec3 normal_attrib; + +#ifdef ENABLE_TANGENT +layout(location = 2) in vec4 tangent_attrib; +#endif + +#ifdef ENABLE_COLOR +layout(location = 3) in vec4 color_attrib; +#endif + +#ifdef ENABLE_UV +layout(location = 4) in vec2 uv_attrib; +#endif + +#ifdef ENABLE_UV2 +layout(location = 5) in vec2 uv2_attrib; +#endif + +#ifdef ENABLE_SKELETON +layout(location = 6) in ivec4 bone_attrib; +layout(location = 7) in vec4 weight_attrib; +#endif + +/* BLEND ATTRIBS */ + +#ifdef ENABLE_BLEND + +layout(location = 8) in highp VFORMAT vertex_attrib_blend; +layout(location = 9) in vec3 normal_attrib_blend; + +#ifdef ENABLE_TANGENT +layout(location = 10) in vec4 tangent_attrib_blend; +#endif + +#ifdef ENABLE_COLOR +layout(location = 11) in vec4 color_attrib_blend; +#endif + +#ifdef ENABLE_UV +layout(location = 12) in vec2 uv_attrib_blend; +#endif + +#ifdef ENABLE_UV2 +layout(location = 13) in vec2 uv2_attrib_blend; +#endif + +#ifdef ENABLE_SKELETON +layout(location = 14) in ivec4 bone_attrib_blend; +layout(location = 15) in vec4 weight_attrib_blend; +#endif + +#endif + +/* OUTPUTS */ + +out VFORMAT vertex_out; //tfb: + +#ifdef ENABLE_NORMAL +out vec3 normal_out; //tfb:ENABLE_NORMAL +#endif + +#ifdef ENABLE_TANGENT +out vec4 tangent_out; //tfb:ENABLE_TANGENT +#endif + +#ifdef ENABLE_COLOR +out vec4 color_out; //tfb:ENABLE_COLOR +#endif + +#ifdef ENABLE_UV +out vec2 uv_out; //tfb:ENABLE_UV +#endif + +#ifdef ENABLE_UV2 +out vec2 uv2_out; //tfb:ENABLE_UV2 +#endif + +#ifdef ENABLE_SKELETON +out ivec4 bone_out; //tfb:ENABLE_SKELETON +out vec4 weight_out; //tfb:ENABLE_SKELETON +#endif + +uniform float blend_amount; + +void main() { +#ifdef ENABLE_BLEND + + vertex_out = vertex_attrib_blend + vertex_attrib * blend_amount; + +#ifdef ENABLE_NORMAL + normal_out = normal_attrib_blend + normal_attrib * blend_amount; +#endif + +#ifdef ENABLE_TANGENT + + tangent_out.xyz = tangent_attrib_blend.xyz + tangent_attrib.xyz * blend_amount; + tangent_out.w = tangent_attrib_blend.w; //just copy, no point in blending his +#endif + +#ifdef ENABLE_COLOR + + color_out = color_attrib_blend + color_attrib * blend_amount; +#endif + +#ifdef ENABLE_UV + + uv_out = uv_attrib_blend + uv_attrib * blend_amount; +#endif + +#ifdef ENABLE_UV2 + + uv2_out = uv2_attrib_blend + uv2_attrib * blend_amount; +#endif + +#ifdef ENABLE_SKELETON + + bone_out = bone_attrib_blend; + weight_out = weight_attrib_blend + weight_attrib * blend_amount; +#endif + +#else //ENABLE_BLEND + + vertex_out = vertex_attrib * blend_amount; + +#ifdef ENABLE_NORMAL + normal_out = normal_attrib * blend_amount; +#endif + +#ifdef ENABLE_TANGENT + + tangent_out.xyz = tangent_attrib.xyz * blend_amount; + tangent_out.w = tangent_attrib.w; //just copy, no point in blending his +#endif + +#ifdef ENABLE_COLOR + + color_out = color_attrib * blend_amount; +#endif + +#ifdef ENABLE_UV + + uv_out = uv_attrib * blend_amount; +#endif + +#ifdef ENABLE_UV2 + + uv2_out = uv2_attrib * blend_amount; +#endif + +#ifdef ENABLE_SKELETON + + bone_out = bone_attrib; + weight_out = weight_attrib * blend_amount; +#endif + +#endif + gl_Position = vec4(0.0); +} + +/* clang-format off */ +[fragment] + +void main() { +} +/* clang-format on */ diff --git a/drivers/gles2/shaders/canvas.glsl b/drivers/gles2/shaders/canvas.glsl new file mode 100644 index 00000000000..3dee2faa888 --- /dev/null +++ b/drivers/gles2/shaders/canvas.glsl @@ -0,0 +1,686 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +uniform highp mat4 projection_matrix; +/* clang-format on */ + +#include "stdlib.glsl" + +uniform highp mat4 modelview_matrix; +uniform highp mat4 extra_matrix; +attribute highp vec2 vertex; // attrib:0 + +#ifdef USE_ATTRIB_LIGHT_ANGLE +// shared with tangent, not used in canvas shader +attribute highp float light_angle; // attrib:2 +#endif + +attribute vec4 color_attrib; // attrib:3 +attribute vec2 uv_attrib; // attrib:4 + +#ifdef USE_ATTRIB_MODULATE +attribute highp vec4 modulate_attrib; // attrib:5 +#endif + +#ifdef USE_ATTRIB_LARGE_VERTEX +// shared with skeleton attributes, not used in batched shader +attribute highp vec2 translate_attrib; // attrib:6 +attribute highp vec4 basis_attrib; // attrib:7 +#endif + +#ifdef USE_SKELETON +attribute highp vec4 bone_indices; // attrib:6 +attribute highp vec4 bone_weights; // attrib:7 +#endif + +#ifdef USE_INSTANCING + +attribute highp vec4 instance_xform0; //attrib:8 +attribute highp vec4 instance_xform1; //attrib:9 +attribute highp vec4 instance_xform2; //attrib:10 +attribute highp vec4 instance_color; //attrib:11 + +#ifdef USE_INSTANCE_CUSTOM +attribute highp vec4 instance_custom_data; //attrib:12 +#endif + +#endif + +#ifdef USE_SKELETON +uniform highp sampler2D skeleton_texture; // texunit:-3 +uniform highp ivec2 skeleton_texture_size; +uniform highp mat4 skeleton_transform; +uniform highp mat4 skeleton_transform_inverse; +#endif + +varying vec2 uv_interp; +varying vec4 color_interp; + +#ifdef USE_ATTRIB_MODULATE +// modulate doesn't need interpolating but we need to send it to the fragment shader +varying vec4 modulate_interp; +#endif + +#ifdef MODULATE_USED +uniform vec4 final_modulate; +#endif + +uniform highp vec2 color_texpixel_size; + +#ifdef USE_TEXTURE_RECT + +uniform vec4 dst_rect; +uniform vec4 src_rect; + +#endif + +uniform highp float time; + +#ifdef USE_LIGHTING + +// light matrices +uniform highp mat4 light_matrix; +uniform highp mat4 light_matrix_inverse; +uniform highp mat4 light_local_matrix; +uniform highp mat4 shadow_matrix; +uniform highp vec4 light_color; +uniform highp vec4 light_shadow_color; +uniform highp vec2 light_pos; +uniform highp float shadowpixel_size; +uniform highp float shadow_gradient; +uniform highp float light_height; +uniform highp float light_outside_alpha; +uniform highp float shadow_distance_mult; + +varying vec4 light_uv_interp; +varying vec2 transformed_light_uv; +varying vec4 local_rot; + +#ifdef USE_SHADOWS +varying highp vec2 pos; +#endif + +const bool at_light_pass = true; +#else +const bool at_light_pass = false; +#endif + +/* clang-format off */ + +VERTEX_SHADER_GLOBALS + +/* clang-format on */ + +vec2 select(vec2 a, vec2 b, bvec2 c) { + vec2 ret; + + ret.x = c.x ? b.x : a.x; + ret.y = c.y ? b.y : a.y; + + return ret; +} + +void main() { + vec4 color = color_attrib; + vec2 uv; + +#ifdef USE_INSTANCING + mat4 extra_matrix_instance = extra_matrix * transpose(mat4(instance_xform0, instance_xform1, instance_xform2, vec4(0.0, 0.0, 0.0, 1.0))); + color *= instance_color; + +#ifdef USE_INSTANCE_CUSTOM + vec4 instance_custom = instance_custom_data; +#else + vec4 instance_custom = vec4(0.0); +#endif + +#else + mat4 extra_matrix_instance = extra_matrix; + vec4 instance_custom = vec4(0.0); +#endif + +#ifdef USE_TEXTURE_RECT + + if (dst_rect.z < 0.0) { // Transpose is encoded as negative dst_rect.z + uv = src_rect.xy + abs(src_rect.zw) * vertex.yx; + } else { + uv = src_rect.xy + abs(src_rect.zw) * vertex; + } + + vec4 outvec = vec4(0.0, 0.0, 0.0, 1.0); + + // This is what is done in the GLES 3 bindings and should + // take care of flipped rects. + // + // But it doesn't. + // I don't know why, will need to investigate further. + + outvec.xy = dst_rect.xy + abs(dst_rect.zw) * select(vertex, vec2(1.0, 1.0) - vertex, lessThan(src_rect.zw, vec2(0.0, 0.0))); + + // outvec.xy = dst_rect.xy + abs(dst_rect.zw) * vertex; +#else + vec4 outvec = vec4(vertex.xy, 0.0, 1.0); + + uv = uv_attrib; +#endif + + float point_size = 1.0; + + { + vec2 src_vtx = outvec.xy; + /* clang-format off */ + +VERTEX_SHADER_CODE + + /* clang-format on */ + } + + gl_PointSize = point_size; + +#ifdef USE_ATTRIB_MODULATE + // modulate doesn't need interpolating but we need to send it to the fragment shader + modulate_interp = modulate_attrib; +#endif + +#ifdef USE_ATTRIB_LARGE_VERTEX + // transform is in attributes + vec2 temp; + + temp = outvec.xy; + temp.x = (outvec.x * basis_attrib.x) + (outvec.y * basis_attrib.z); + temp.y = (outvec.x * basis_attrib.y) + (outvec.y * basis_attrib.w); + + temp += translate_attrib; + outvec.xy = temp; + +#else + + // transform is in uniforms +#if !defined(SKIP_TRANSFORM_USED) + outvec = extra_matrix_instance * outvec; + outvec = modelview_matrix * outvec; +#endif + +#endif // not large integer + + color_interp = color; + +#ifdef USE_PIXEL_SNAP + outvec.xy = floor(outvec + 0.5).xy; + // precision issue on some hardware creates artifacts within texture + // offset uv by a small amount to avoid + uv += 1e-5; +#endif + +#ifdef USE_SKELETON + + // look up transform from the "pose texture" + if (bone_weights != vec4(0.0)) { + highp mat4 bone_transform = mat4(0.0); + + for (int i = 0; i < 4; i++) { + ivec2 tex_ofs = ivec2(int(bone_indices[i]) * 2, 0); + + highp mat4 b = mat4( + texel2DFetch(skeleton_texture, skeleton_texture_size, tex_ofs + ivec2(0, 0)), + texel2DFetch(skeleton_texture, skeleton_texture_size, tex_ofs + ivec2(1, 0)), + vec4(0.0, 0.0, 1.0, 0.0), + vec4(0.0, 0.0, 0.0, 1.0)); + + bone_transform += b * bone_weights[i]; + } + + mat4 bone_matrix = skeleton_transform * transpose(bone_transform) * skeleton_transform_inverse; + + outvec = bone_matrix * outvec; + } + +#endif + + uv_interp = uv; + gl_Position = projection_matrix * outvec; + +#ifdef USE_LIGHTING + + light_uv_interp.xy = (light_matrix * outvec).xy; + light_uv_interp.zw = (light_local_matrix * outvec).xy; + + transformed_light_uv = (mat3(light_matrix_inverse) * vec3(light_uv_interp.zw, 0.0)).xy; //for normal mapping + +#ifdef USE_SHADOWS + pos = outvec.xy; +#endif + +#ifdef USE_ATTRIB_LIGHT_ANGLE + // we add a fixed offset because we are using the sign later, + // and don't want floating point error around 0.0 + float la = abs(light_angle) - 1.0; + + // vector light angle + vec4 vla; + vla.xy = vec2(cos(la), sin(la)); + vla.zw = vec2(-vla.y, vla.x); + + // vertical flip encoded in the sign + vla.zw *= sign(light_angle); + + // apply the transform matrix. + // The rotate will be encoded in the transform matrix for single rects, + // and just the flips in the light angle. + // For batching we will encode the rotation and the flips + // in the light angle, and can use the same shader. + local_rot.xy = normalize((modelview_matrix * (extra_matrix_instance * vec4(vla.xy, 0.0, 0.0))).xy); + local_rot.zw = normalize((modelview_matrix * (extra_matrix_instance * vec4(vla.zw, 0.0, 0.0))).xy); +#else + local_rot.xy = normalize((modelview_matrix * (extra_matrix_instance * vec4(1.0, 0.0, 0.0, 0.0))).xy); + local_rot.zw = normalize((modelview_matrix * (extra_matrix_instance * vec4(0.0, 1.0, 0.0, 0.0))).xy); +#ifdef USE_TEXTURE_RECT + local_rot.xy *= sign(src_rect.z); + local_rot.zw *= sign(src_rect.w); +#endif +#endif // not using light angle + +#endif +} + +/* clang-format off */ +[fragment] + +// texture2DLodEXT and textureCubeLodEXT are fragment shader specific. +// Do not copy these defines in the vertex section. +#ifndef USE_GLES_OVER_GL +#ifdef GL_EXT_shader_texture_lod +#extension GL_EXT_shader_texture_lod : enable +#define texture2DLod(img, coord, lod) texture2DLodEXT(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCubeLodEXT(img, coord, lod) +#endif +#endif // !USE_GLES_OVER_GL + +#ifdef GL_ARB_shader_texture_lod +#extension GL_ARB_shader_texture_lod : enable +#endif + +#if !defined(GL_EXT_shader_texture_lod) && !defined(GL_ARB_shader_texture_lod) +#define texture2DLod(img, coord, lod) texture2D(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCube(img, coord, lod) +#endif + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +#include "stdlib.glsl" + +uniform sampler2D color_texture; // texunit:-1 +/* clang-format on */ +uniform highp vec2 color_texpixel_size; +uniform mediump sampler2D normal_texture; // texunit:-2 + +varying mediump vec2 uv_interp; +varying mediump vec4 color_interp; + +#ifdef USE_ATTRIB_MODULATE +varying mediump vec4 modulate_interp; +#endif + +uniform highp float time; + +uniform vec4 final_modulate; + +#ifdef SCREEN_TEXTURE_USED + +uniform sampler2D screen_texture; // texunit:-4 + +#endif + +#ifdef SCREEN_UV_USED + +uniform vec2 screen_pixel_size; + +#endif + +#ifdef USE_LIGHTING + +uniform highp mat4 light_matrix; +uniform highp mat4 light_local_matrix; +uniform highp mat4 shadow_matrix; +uniform highp vec4 light_color; +uniform highp vec4 light_shadow_color; +uniform highp vec2 light_pos; +uniform highp float shadowpixel_size; +uniform highp float shadow_gradient; +uniform highp float light_height; +uniform highp float light_outside_alpha; +uniform highp float shadow_distance_mult; + +uniform lowp sampler2D light_texture; // texunit:-6 +varying vec4 light_uv_interp; +varying vec2 transformed_light_uv; + +varying vec4 local_rot; + +#ifdef USE_SHADOWS + +uniform highp sampler2D shadow_texture; // texunit:-5 +varying highp vec2 pos; + +#endif + +const bool at_light_pass = true; +#else +const bool at_light_pass = false; +#endif + +uniform bool use_default_normal; + +/* clang-format off */ + +FRAGMENT_SHADER_GLOBALS + +/* clang-format on */ + +void light_compute( + inout vec4 light, + inout vec2 light_vec, + inout float light_height, + inout vec4 light_color, + vec2 light_uv, + inout vec4 shadow_color, + inout vec2 shadow_vec, + vec3 normal, + vec2 uv, +#if defined(SCREEN_UV_USED) + vec2 screen_uv, +#endif + vec4 color) { + +#if defined(USE_LIGHT_SHADER_CODE) + + /* clang-format off */ + +LIGHT_SHADER_CODE + + /* clang-format on */ + +#endif +} + +void main() { + vec4 color = color_interp; + vec2 uv = uv_interp; +#ifdef USE_FORCE_REPEAT + //needs to use this to workaround GLES2/WebGL1 forcing tiling that textures that don't support it + uv = mod(uv, vec2(1.0, 1.0)); +#endif + +#if !defined(COLOR_USED) + //default behavior, texture by color + color *= texture2D(color_texture, uv); +#endif + +#ifdef SCREEN_UV_USED + vec2 screen_uv = gl_FragCoord.xy * screen_pixel_size; +#endif + + vec3 normal; + +#if defined(NORMAL_USED) + + bool normal_used = true; +#else + bool normal_used = false; +#endif + + if (use_default_normal) { + normal.xy = texture2D(normal_texture, uv).xy * 2.0 - 1.0; + normal.z = sqrt(1.0 - dot(normal.xy, normal.xy)); + normal_used = true; + } else { + normal = vec3(0.0, 0.0, 1.0); + } + + { + float normal_depth = 1.0; + +#if defined(NORMALMAP_USED) + vec3 normal_map = vec3(0.0, 0.0, 1.0); + normal_used = true; +#endif + + /* clang-format off */ + +FRAGMENT_SHADER_CODE + + /* clang-format on */ + +#if defined(NORMALMAP_USED) + normal = mix(vec3(0.0, 0.0, 1.0), normal_map * vec3(2.0, -2.0, 1.0) - vec3(1.0, -1.0, 0.0), normal_depth); +#endif + } + +#ifdef USE_ATTRIB_MODULATE + color *= modulate_interp; +#else +#if !defined(MODULATE_USED) + color *= final_modulate; +#endif +#endif + +#ifdef USE_LIGHTING + + vec2 light_vec = transformed_light_uv; + vec2 shadow_vec = transformed_light_uv; + + if (normal_used) { + normal.xy = mat2(local_rot.xy, local_rot.zw) * normal.xy; + } + + float att = 1.0; + + vec2 light_uv = light_uv_interp.xy; + vec4 light = texture2D(light_texture, light_uv); + + if (any(lessThan(light_uv_interp.xy, vec2(0.0, 0.0))) || any(greaterThanEqual(light_uv_interp.xy, vec2(1.0, 1.0)))) { + color.a *= light_outside_alpha; //invisible + + } else { + float real_light_height = light_height; + vec4 real_light_color = light_color; + vec4 real_light_shadow_color = light_shadow_color; + +#if defined(USE_LIGHT_SHADER_CODE) + //light is written by the light shader + light_compute( + light, + light_vec, + real_light_height, + real_light_color, + light_uv, + real_light_shadow_color, + shadow_vec, + normal, + uv, +#if defined(SCREEN_UV_USED) + screen_uv, +#endif + color); +#endif + + light *= real_light_color; + + if (normal_used) { + vec3 light_normal = normalize(vec3(light_vec, -real_light_height)); + light *= max(dot(-light_normal, normal), 0.0); + } + + color *= light; + +#ifdef USE_SHADOWS + +#ifdef SHADOW_VEC_USED + mat3 inverse_light_matrix = mat3(light_matrix); + inverse_light_matrix[0] = normalize(inverse_light_matrix[0]); + inverse_light_matrix[1] = normalize(inverse_light_matrix[1]); + inverse_light_matrix[2] = normalize(inverse_light_matrix[2]); + shadow_vec = (inverse_light_matrix * vec3(shadow_vec, 0.0)).xy; +#else + shadow_vec = light_uv_interp.zw; +#endif + + float angle_to_light = -atan(shadow_vec.x, shadow_vec.y); + float PI = 3.14159265358979323846264; + /*int i = int(mod(floor((angle_to_light+7.0*PI/6.0)/(4.0*PI/6.0))+1.0, 3.0)); // +1 pq os indices estao em ordem 2,0,1 nos arrays + float ang*/ + + float su, sz; + + float abs_angle = abs(angle_to_light); + vec2 point; + float sh; + if (abs_angle < 45.0 * PI / 180.0) { + point = shadow_vec; + sh = 0.0 + (1.0 / 8.0); + } else if (abs_angle > 135.0 * PI / 180.0) { + point = -shadow_vec; + sh = 0.5 + (1.0 / 8.0); + } else if (angle_to_light > 0.0) { + point = vec2(shadow_vec.y, -shadow_vec.x); + sh = 0.25 + (1.0 / 8.0); + } else { + point = vec2(-shadow_vec.y, shadow_vec.x); + sh = 0.75 + (1.0 / 8.0); + } + + highp vec4 s = shadow_matrix * vec4(point, 0.0, 1.0); + s.xyz /= s.w; + su = s.x * 0.5 + 0.5; + sz = s.z * 0.5 + 0.5; + //sz=lightlength(light_vec); + + highp float shadow_attenuation = 0.0; + +#ifdef USE_RGBA_SHADOWS +#define SHADOW_DEPTH(m_tex, m_uv) dot(texture2D((m_tex), (m_uv)), vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0)) + +#else + +#define SHADOW_DEPTH(m_tex, m_uv) (texture2D((m_tex), (m_uv)).r) + +#endif + +#ifdef SHADOW_USE_GRADIENT + + /* clang-format off */ + /* GLSL es 100 doesn't support line continuation characters(backslashes) */ +#define SHADOW_TEST(m_ofs) { highp float sd = SHADOW_DEPTH(shadow_texture, vec2(m_ofs, sh)); shadow_attenuation += 1.0 - smoothstep(sd, sd + shadow_gradient, sz); } + +#else + +#define SHADOW_TEST(m_ofs) { highp float sd = SHADOW_DEPTH(shadow_texture, vec2(m_ofs, sh)); shadow_attenuation += step(sz, sd); } + /* clang-format on */ + +#endif + +#ifdef SHADOW_FILTER_NEAREST + + SHADOW_TEST(su); + +#endif + +#ifdef SHADOW_FILTER_PCF3 + + SHADOW_TEST(su + shadowpixel_size); + SHADOW_TEST(su); + SHADOW_TEST(su - shadowpixel_size); + shadow_attenuation /= 3.0; + +#endif + +#ifdef SHADOW_FILTER_PCF5 + + SHADOW_TEST(su + shadowpixel_size * 2.0); + SHADOW_TEST(su + shadowpixel_size); + SHADOW_TEST(su); + SHADOW_TEST(su - shadowpixel_size); + SHADOW_TEST(su - shadowpixel_size * 2.0); + shadow_attenuation /= 5.0; + +#endif + +#ifdef SHADOW_FILTER_PCF7 + + SHADOW_TEST(su + shadowpixel_size * 3.0); + SHADOW_TEST(su + shadowpixel_size * 2.0); + SHADOW_TEST(su + shadowpixel_size); + SHADOW_TEST(su); + SHADOW_TEST(su - shadowpixel_size); + SHADOW_TEST(su - shadowpixel_size * 2.0); + SHADOW_TEST(su - shadowpixel_size * 3.0); + shadow_attenuation /= 7.0; + +#endif + +#ifdef SHADOW_FILTER_PCF9 + + SHADOW_TEST(su + shadowpixel_size * 4.0); + SHADOW_TEST(su + shadowpixel_size * 3.0); + SHADOW_TEST(su + shadowpixel_size * 2.0); + SHADOW_TEST(su + shadowpixel_size); + SHADOW_TEST(su); + SHADOW_TEST(su - shadowpixel_size); + SHADOW_TEST(su - shadowpixel_size * 2.0); + SHADOW_TEST(su - shadowpixel_size * 3.0); + SHADOW_TEST(su - shadowpixel_size * 4.0); + shadow_attenuation /= 9.0; + +#endif + +#ifdef SHADOW_FILTER_PCF13 + + SHADOW_TEST(su + shadowpixel_size * 6.0); + SHADOW_TEST(su + shadowpixel_size * 5.0); + SHADOW_TEST(su + shadowpixel_size * 4.0); + SHADOW_TEST(su + shadowpixel_size * 3.0); + SHADOW_TEST(su + shadowpixel_size * 2.0); + SHADOW_TEST(su + shadowpixel_size); + SHADOW_TEST(su); + SHADOW_TEST(su - shadowpixel_size); + SHADOW_TEST(su - shadowpixel_size * 2.0); + SHADOW_TEST(su - shadowpixel_size * 3.0); + SHADOW_TEST(su - shadowpixel_size * 4.0); + SHADOW_TEST(su - shadowpixel_size * 5.0); + SHADOW_TEST(su - shadowpixel_size * 6.0); + shadow_attenuation /= 13.0; + +#endif + + //color *= shadow_attenuation; + color = mix(real_light_shadow_color, color, shadow_attenuation); +//use shadows +#endif + } + +//use lighting +#endif + + gl_FragColor = color; +} diff --git a/drivers/gles2/shaders/canvas_shadow.glsl b/drivers/gles2/shaders/canvas_shadow.glsl new file mode 100644 index 00000000000..2abcd5e67c5 --- /dev/null +++ b/drivers/gles2/shaders/canvas_shadow.glsl @@ -0,0 +1,60 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute highp vec3 vertex; // attrib:0 + +uniform highp mat4 projection_matrix; +/* clang-format on */ +uniform highp mat4 light_matrix; +uniform highp mat4 world_matrix; +uniform highp float distance_norm; + +varying highp vec4 position_interp; + +void main() { + gl_Position = projection_matrix * (light_matrix * (world_matrix * vec4(vertex, 1.0))); + position_interp = gl_Position; +} + +/* clang-format off */ +[fragment] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +varying highp vec4 position_interp; +/* clang-format on */ + +void main() { + highp float depth = ((position_interp.z / position_interp.w) + 1.0) * 0.5 + 0.0; // bias + +#ifdef USE_RGBA_SHADOWS + + highp vec4 comp = fract(depth * vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0)); + comp -= comp.xxyz * vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0); + gl_FragColor = comp; +#else + + gl_FragColor = vec4(depth); +#endif +} diff --git a/drivers/gles2/shaders/copy.glsl b/drivers/gles2/shaders/copy.glsl new file mode 100644 index 00000000000..e833722ac3d --- /dev/null +++ b/drivers/gles2/shaders/copy.glsl @@ -0,0 +1,191 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute highp vec4 vertex_attrib; // attrib:0 +/* clang-format on */ + +#if defined(USE_CUBEMAP) || defined(USE_PANORAMA) +attribute vec3 cube_in; // attrib:4 +#else +attribute vec2 uv_in; // attrib:4 +#endif + +attribute vec2 uv2_in; // attrib:5 + +#if defined(USE_CUBEMAP) || defined(USE_PANORAMA) +varying vec3 cube_interp; +#else +varying vec2 uv_interp; +#endif +varying vec2 uv2_interp; + +// These definitions are here because the shader-wrapper builder does +// not understand `#elif defined()` +#ifdef USE_DISPLAY_TRANSFORM +#endif + +#ifdef USE_COPY_SECTION +uniform highp vec4 copy_section; +#elif defined(USE_DISPLAY_TRANSFORM) +uniform highp mat4 display_transform; +#endif + +void main() { +#if defined(USE_CUBEMAP) || defined(USE_PANORAMA) + cube_interp = cube_in; +#elif defined(USE_ASYM_PANO) + uv_interp = vertex_attrib.xy; +#else + uv_interp = uv_in; +#endif + + uv2_interp = uv2_in; + gl_Position = vertex_attrib; + +#ifdef USE_COPY_SECTION + uv_interp = copy_section.xy + uv_interp * copy_section.zw; + gl_Position.xy = (copy_section.xy + (gl_Position.xy * 0.5 + 0.5) * copy_section.zw) * 2.0 - 1.0; +#elif defined(USE_DISPLAY_TRANSFORM) + uv_interp = (display_transform * vec4(uv_in, 1.0, 1.0)).xy; +#endif +} + +/* clang-format off */ +[fragment] + +#define M_PI 3.14159265359 + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +#if defined(USE_CUBEMAP) || defined(USE_PANORAMA) +varying vec3 cube_interp; +#else +varying vec2 uv_interp; +#endif +/* clang-format on */ + +#ifdef USE_ASYM_PANO +uniform highp mat4 pano_transform; +uniform highp vec4 asym_proj; +#endif + +#ifdef USE_CUBEMAP +uniform samplerCube source_cube; // texunit:0 +#else +uniform sampler2D source; // texunit:0 +#endif + +#ifdef SEP_CBCR_TEXTURE +uniform sampler2D CbCr; //texunit:1 +#endif + +varying vec2 uv2_interp; + +#ifdef USE_MULTIPLIER +uniform float multiplier; +#endif + +#ifdef USE_CUSTOM_ALPHA +uniform float custom_alpha; +#endif + +#if defined(USE_PANORAMA) || defined(USE_ASYM_PANO) +uniform highp mat4 sky_transform; + +vec4 texturePanorama(sampler2D pano, vec3 normal) { + vec2 st = vec2( + atan(normal.x, normal.z), + acos(normal.y)); + + if (st.x < 0.0) + st.x += M_PI * 2.0; + + st /= vec2(M_PI * 2.0, M_PI); + + return texture2D(pano, st); +} + +#endif + +void main() { +#ifdef USE_PANORAMA + + vec3 cube_normal = normalize(cube_interp); + cube_normal.z = -cube_normal.z; + cube_normal = mat3(sky_transform) * cube_normal; + cube_normal.z = -cube_normal.z; + + vec4 color = texturePanorama(source, cube_normal); + +#elif defined(USE_ASYM_PANO) + + // When an asymmetrical projection matrix is used (applicable for stereoscopic rendering i.e. VR) we need to do this calculation per fragment to get a perspective correct result. + // Asymmetrical projection means the center of projection is no longer in the center of the screen but shifted. + // The Matrix[2][0] (= asym_proj.x) and Matrix[2][1] (= asym_proj.z) values are what provide the right shift in the image. + + vec3 cube_normal; + cube_normal.z = -1.0; + cube_normal.x = (cube_normal.z * (-uv_interp.x - asym_proj.x)) / asym_proj.y; + cube_normal.y = (cube_normal.z * (-uv_interp.y - asym_proj.z)) / asym_proj.a; + cube_normal = mat3(sky_transform) * mat3(pano_transform) * cube_normal; + cube_normal.z = -cube_normal.z; + + vec4 color = texturePanorama(source, normalize(cube_normal.xyz)); + +#elif defined(USE_CUBEMAP) + vec4 color = textureCube(source_cube, normalize(cube_interp)); +#elif defined(SEP_CBCR_TEXTURE) + vec4 color; + color.r = texture2D(source, uv_interp).r; + color.gb = texture2D(CbCr, uv_interp).rg - vec2(0.5, 0.5); + color.a = 1.0; +#else + vec4 color = texture2D(source, uv_interp); +#endif + +#ifdef YCBCR_TO_RGB + // YCbCr -> RGB conversion + + // Using BT.601, which is the standard for SDTV is provided as a reference + color.rgb = mat3( + vec3(1.00000, 1.00000, 1.00000), + vec3(0.00000, -0.34413, 1.77200), + vec3(1.40200, -0.71414, 0.00000)) * + color.rgb; +#endif + +#ifdef USE_NO_ALPHA + color.a = 1.0; +#endif + +#ifdef USE_CUSTOM_ALPHA + color.a = custom_alpha; +#endif + +#ifdef USE_MULTIPLIER + color.rgb *= multiplier; +#endif + + gl_FragColor = color; +} diff --git a/drivers/gles2/shaders/cube_to_dp.glsl b/drivers/gles2/shaders/cube_to_dp.glsl new file mode 100644 index 00000000000..1612ec3d5a6 --- /dev/null +++ b/drivers/gles2/shaders/cube_to_dp.glsl @@ -0,0 +1,100 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision mediump float; +precision mediump int; +#endif + +attribute highp vec4 vertex_attrib; // attrib:0 +/* clang-format on */ +attribute vec2 uv_in; // attrib:4 + +varying vec2 uv_interp; + +void main() { + uv_interp = uv_in; + gl_Position = vertex_attrib; +} + +/* clang-format off */ +[fragment] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +uniform highp samplerCube source_cube; //texunit:0 +/* clang-format on */ +varying vec2 uv_interp; + +uniform bool z_flip; +uniform highp float z_far; +uniform highp float z_near; +uniform highp float bias; + +void main() { + highp vec3 normal = vec3(uv_interp * 2.0 - 1.0, 0.0); + /* + if (z_flip) { + normal.z = 0.5 - 0.5 * ((normal.x * normal.x) + (normal.y * normal.y)); + } else { + normal.z = -0.5 + 0.5 * ((normal.x * normal.x) + (normal.y * normal.y)); + } + */ + + //normal.z = sqrt(1.0 - dot(normal.xy, normal.xy)); + //normal.xy *= 1.0 + normal.z; + + normal.z = 0.5 - 0.5 * ((normal.x * normal.x) + (normal.y * normal.y)); + normal = normalize(normal); + /* + normal.z = 0.5; + normal = normalize(normal); + */ + + if (!z_flip) { + normal.z = -normal.z; + } + + //normal = normalize(vec3( uv_interp * 2.0 - 1.0, 1.0 )); + float depth = textureCube(source_cube, normal).r; + + // absolute values for direction cosines, bigger value equals closer to basis axis + vec3 unorm = abs(normal); + + if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) { + // x code + unorm = normal.x > 0.0 ? vec3(1.0, 0.0, 0.0) : vec3(-1.0, 0.0, 0.0); + } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) { + // y code + unorm = normal.y > 0.0 ? vec3(0.0, 1.0, 0.0) : vec3(0.0, -1.0, 0.0); + } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) { + // z code + unorm = normal.z > 0.0 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 0.0, -1.0); + } else { + // oh-no we messed up code + // has to be + unorm = vec3(1.0, 0.0, 0.0); + } + + float depth_fix = 1.0 / dot(normal, unorm); + + depth = 2.0 * depth - 1.0; + float linear_depth = 2.0 * z_near * z_far / (z_far + z_near - depth * (z_far - z_near)); + gl_FragDepth = (linear_depth * depth_fix + bias) / z_far; +} diff --git a/drivers/gles2/shaders/cubemap_filter.glsl b/drivers/gles2/shaders/cubemap_filter.glsl new file mode 100644 index 00000000000..f5c91cc7072 --- /dev/null +++ b/drivers/gles2/shaders/cubemap_filter.glsl @@ -0,0 +1,231 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute highp vec2 vertex; // attrib:0 +/* clang-format on */ +attribute highp vec2 uv; // attrib:4 + +varying highp vec2 uv_interp; + +void main() { + uv_interp = uv; + gl_Position = vec4(vertex, 0, 1); +} + +/* clang-format off */ +[fragment] + +// texture2DLodEXT and textureCubeLodEXT are fragment shader specific. +// Do not copy these defines in the vertex section. +#ifndef USE_GLES_OVER_GL +#ifdef GL_EXT_shader_texture_lod +#extension GL_EXT_shader_texture_lod : enable +#define texture2DLod(img, coord, lod) texture2DLodEXT(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCubeLodEXT(img, coord, lod) +#endif +#endif // !USE_GLES_OVER_GL + +#ifdef GL_ARB_shader_texture_lod +#extension GL_ARB_shader_texture_lod : enable +#endif + +#if !defined(GL_EXT_shader_texture_lod) && !defined(GL_ARB_shader_texture_lod) +#define texture2DLod(img, coord, lod) texture2D(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCube(img, coord, lod) +#endif + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif + +#endif + +#ifdef USE_SOURCE_PANORAMA +uniform sampler2D source_panorama; //texunit:0 +#else +uniform samplerCube source_cube; //texunit:0 +#endif +/* clang-format on */ + +uniform int face_id; +uniform float roughness; +varying highp vec2 uv_interp; + +uniform sampler2D radical_inverse_vdc_cache; // texunit:1 + +#define M_PI 3.14159265359 + +#ifdef LOW_QUALITY + +#define SAMPLE_COUNT 64 + +#else + +#define SAMPLE_COUNT 512 + +#endif + +#ifdef USE_SOURCE_PANORAMA + +vec4 texturePanorama(sampler2D pano, vec3 normal) { + vec2 st = vec2( + atan(normal.x, normal.z), + acos(normal.y)); + + if (st.x < 0.0) + st.x += M_PI * 2.0; + + st /= vec2(M_PI * 2.0, M_PI); + + return texture2DLod(pano, st, 0.0); +} + +#endif + +vec3 texelCoordToVec(vec2 uv, int faceID) { + mat3 faceUvVectors[6]; + + // -x + faceUvVectors[0][0] = vec3(0.0, 0.0, 1.0); // u -> +z + faceUvVectors[0][1] = vec3(0.0, -1.0, 0.0); // v -> -y + faceUvVectors[0][2] = vec3(-1.0, 0.0, 0.0); // -x face + + // +x + faceUvVectors[1][0] = vec3(0.0, 0.0, -1.0); // u -> -z + faceUvVectors[1][1] = vec3(0.0, -1.0, 0.0); // v -> -y + faceUvVectors[1][2] = vec3(1.0, 0.0, 0.0); // +x face + + // -y + faceUvVectors[2][0] = vec3(1.0, 0.0, 0.0); // u -> +x + faceUvVectors[2][1] = vec3(0.0, 0.0, -1.0); // v -> -z + faceUvVectors[2][2] = vec3(0.0, -1.0, 0.0); // -y face + + // +y + faceUvVectors[3][0] = vec3(1.0, 0.0, 0.0); // u -> +x + faceUvVectors[3][1] = vec3(0.0, 0.0, 1.0); // v -> +z + faceUvVectors[3][2] = vec3(0.0, 1.0, 0.0); // +y face + + // -z + faceUvVectors[4][0] = vec3(-1.0, 0.0, 0.0); // u -> -x + faceUvVectors[4][1] = vec3(0.0, -1.0, 0.0); // v -> -y + faceUvVectors[4][2] = vec3(0.0, 0.0, -1.0); // -z face + + // +z + faceUvVectors[5][0] = vec3(1.0, 0.0, 0.0); // u -> +x + faceUvVectors[5][1] = vec3(0.0, -1.0, 0.0); // v -> -y + faceUvVectors[5][2] = vec3(0.0, 0.0, 1.0); // +z face + + // out = u * s_faceUv[0] + v * s_faceUv[1] + s_faceUv[2]. + vec3 result; + for (int i = 0; i < 6; i++) { + if (i == faceID) { + result = (faceUvVectors[i][0] * uv.x) + (faceUvVectors[i][1] * uv.y) + faceUvVectors[i][2]; + break; + } + } + return normalize(result); +} + +vec3 ImportanceSampleGGX(vec2 Xi, float Roughness, vec3 N) { + float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph] + + // Compute distribution direction + float Phi = 2.0 * M_PI * Xi.x; + float CosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y)); + float SinTheta = sqrt(1.0 - CosTheta * CosTheta); + + // Convert to spherical direction + vec3 H; + H.x = SinTheta * cos(Phi); + H.y = SinTheta * sin(Phi); + H.z = CosTheta; + + vec3 UpVector = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 TangentX = normalize(cross(UpVector, N)); + vec3 TangentY = cross(N, TangentX); + + // Tangent to world space + return TangentX * H.x + TangentY * H.y + N * H.z; +} + +float radical_inverse_VdC(int i) { + return texture2D(radical_inverse_vdc_cache, vec2(float(i) / 512.0, 0.0)).x; +} + +vec2 Hammersley(int i, int N) { + return vec2(float(i) / float(N), radical_inverse_VdC(i)); +} + +uniform bool z_flip; + +void main() { + vec3 color = vec3(0.0); + + vec2 uv = (uv_interp * 2.0) - 1.0; + vec3 N = texelCoordToVec(uv, face_id); + +#ifdef USE_DIRECT_WRITE + +#ifdef USE_SOURCE_PANORAMA + + gl_FragColor = vec4(texturePanorama(source_panorama, N).rgb, 1.0); +#else + + gl_FragColor = vec4(textureCube(source_cube, N).rgb, 1.0); +#endif //USE_SOURCE_PANORAMA + +#else + + vec4 sum = vec4(0.0); + + for (int sample_num = 0; sample_num < SAMPLE_COUNT; sample_num++) { + vec2 xi = Hammersley(sample_num, SAMPLE_COUNT); + + vec3 H = ImportanceSampleGGX(xi, roughness, N); + vec3 V = N; + vec3 L = (2.0 * dot(V, H) * H - V); + + float NdotL = clamp(dot(N, L), 0.0, 1.0); + + if (NdotL > 0.0) { + +#ifdef USE_SOURCE_PANORAMA + vec3 val = texturePanorama(source_panorama, L).rgb; +#else + vec3 val = textureCubeLod(source_cube, L, 0.0).rgb; +#endif + //mix using Linear, to approximate high end back-end + val = mix(pow((val + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), val * (1.0 / 12.92), vec3(lessThan(val, vec3(0.04045)))); + + sum.rgb += val * NdotL; + + sum.a += NdotL; + } + } + + sum /= sum.a; + + vec3 a = vec3(0.055); + sum.rgb = mix((vec3(1.0) + a) * pow(sum.rgb, vec3(1.0 / 2.4)) - a, 12.92 * sum.rgb, vec3(lessThan(sum.rgb, vec3(0.0031308)))); + + gl_FragColor = vec4(sum.rgb, 1.0); +#endif +} diff --git a/drivers/gles2/shaders/effect_blur.glsl b/drivers/gles2/shaders/effect_blur.glsl new file mode 100644 index 00000000000..7b607dd76a0 --- /dev/null +++ b/drivers/gles2/shaders/effect_blur.glsl @@ -0,0 +1,308 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute vec2 vertex_attrib; // attrib:0 +/* clang-format on */ +attribute vec2 uv_in; // attrib:4 + +varying vec2 uv_interp; + +#ifdef USE_BLUR_SECTION + +uniform vec4 blur_section; + +#endif + +void main() { + uv_interp = uv_in; + gl_Position = vec4(vertex_attrib, 0.0, 1.0); +#ifdef USE_BLUR_SECTION + + uv_interp = blur_section.xy + uv_interp * blur_section.zw; + gl_Position.xy = (blur_section.xy + (gl_Position.xy * 0.5 + 0.5) * blur_section.zw) * 2.0 - 1.0; +#endif +} + +/* clang-format off */ +[fragment] + +// texture2DLodEXT and textureCubeLodEXT are fragment shader specific. +// Do not copy these defines in the vertex section. +#ifndef USE_GLES_OVER_GL +#ifdef GL_EXT_shader_texture_lod +#extension GL_EXT_shader_texture_lod : enable +#define texture2DLod(img, coord, lod) texture2DLodEXT(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCubeLodEXT(img, coord, lod) +#endif +#endif // !USE_GLES_OVER_GL + +#ifdef GL_ARB_shader_texture_lod +#extension GL_ARB_shader_texture_lod : enable +#endif + +#if !defined(GL_EXT_shader_texture_lod) && !defined(GL_ARB_shader_texture_lod) +#define texture2DLod(img, coord, lod) texture2D(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCube(img, coord, lod) +#endif + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +varying vec2 uv_interp; +/* clang-format on */ +uniform sampler2D source_color; //texunit:0 + +uniform float lod; +uniform vec2 pixel_size; + +#if defined(GLOW_GAUSSIAN_HORIZONTAL) || defined(GLOW_GAUSSIAN_VERTICAL) + +uniform float glow_strength; + +#endif + +#if defined(DOF_FAR_BLUR) || defined(DOF_NEAR_BLUR) + +#ifdef USE_GLES_OVER_GL +#ifdef DOF_QUALITY_LOW +const int dof_kernel_size = 5; +const int dof_kernel_from = 2; +const float dof_kernel[5] = float[](0.153388, 0.221461, 0.250301, 0.221461, 0.153388); +#endif + +#ifdef DOF_QUALITY_MEDIUM +const int dof_kernel_size = 11; +const int dof_kernel_from = 5; +const float dof_kernel[11] = float[](0.055037, 0.072806, 0.090506, 0.105726, 0.116061, 0.119726, 0.116061, 0.105726, 0.090506, 0.072806, 0.055037); + +#endif + +#ifdef DOF_QUALITY_HIGH +const int dof_kernel_size = 21; +const int dof_kernel_from = 10; +const float dof_kernel[21] = float[](0.028174, 0.032676, 0.037311, 0.041944, 0.046421, 0.050582, 0.054261, 0.057307, 0.059587, 0.060998, 0.061476, 0.060998, 0.059587, 0.057307, 0.054261, 0.050582, 0.046421, 0.041944, 0.037311, 0.032676, 0.028174); +#endif +#endif + +uniform sampler2D dof_source_depth; //texunit:1 +uniform float dof_begin; +uniform float dof_end; +uniform vec2 dof_dir; +uniform float dof_radius; + +#endif + +#ifdef GLOW_FIRST_PASS + +uniform highp float luminance_cap; + +uniform float glow_bloom; +uniform float glow_hdr_threshold; +uniform float glow_hdr_scale; + +#endif + +uniform float camera_z_far; +uniform float camera_z_near; + +void main() { +#ifdef GLOW_GAUSSIAN_HORIZONTAL + vec2 pix_size = pixel_size; + pix_size *= 0.5; //reading from larger buffer, so use more samples + vec4 color = texture2DLod(source_color, uv_interp + vec2(0.0, 0.0) * pix_size, lod) * 0.174938; + color += texture2DLod(source_color, uv_interp + vec2(1.0, 0.0) * pix_size, lod) * 0.165569; + color += texture2DLod(source_color, uv_interp + vec2(2.0, 0.0) * pix_size, lod) * 0.140367; + color += texture2DLod(source_color, uv_interp + vec2(3.0, 0.0) * pix_size, lod) * 0.106595; + color += texture2DLod(source_color, uv_interp + vec2(-1.0, 0.0) * pix_size, lod) * 0.165569; + color += texture2DLod(source_color, uv_interp + vec2(-2.0, 0.0) * pix_size, lod) * 0.140367; + color += texture2DLod(source_color, uv_interp + vec2(-3.0, 0.0) * pix_size, lod) * 0.106595; + color *= glow_strength; + gl_FragColor = color; +#endif + +#ifdef GLOW_GAUSSIAN_VERTICAL + vec4 color = texture2DLod(source_color, uv_interp + vec2(0.0, 0.0) * pixel_size, lod) * 0.288713; + color += texture2DLod(source_color, uv_interp + vec2(0.0, 1.0) * pixel_size, lod) * 0.233062; + color += texture2DLod(source_color, uv_interp + vec2(0.0, 2.0) * pixel_size, lod) * 0.122581; + color += texture2DLod(source_color, uv_interp + vec2(0.0, -1.0) * pixel_size, lod) * 0.233062; + color += texture2DLod(source_color, uv_interp + vec2(0.0, -2.0) * pixel_size, lod) * 0.122581; + color *= glow_strength; + gl_FragColor = color; +#endif + +#ifndef USE_GLES_OVER_GL +#if defined(DOF_FAR_BLUR) || defined(DOF_NEAR_BLUR) + +#ifdef DOF_QUALITY_LOW + const int dof_kernel_size = 5; + const int dof_kernel_from = 2; + float dof_kernel[5]; + dof_kernel[0] = 0.153388; + dof_kernel[1] = 0.221461; + dof_kernel[2] = 0.250301; + dof_kernel[3] = 0.221461; + dof_kernel[4] = 0.153388; +#endif + +#ifdef DOF_QUALITY_MEDIUM + const int dof_kernel_size = 11; + const int dof_kernel_from = 5; + float dof_kernel[11]; + dof_kernel[0] = 0.055037; + dof_kernel[1] = 0.072806; + dof_kernel[2] = 0.090506; + dof_kernel[3] = 0.105726; + dof_kernel[4] = 0.116061; + dof_kernel[5] = 0.119726; + dof_kernel[6] = 0.116061; + dof_kernel[7] = 0.105726; + dof_kernel[8] = 0.090506; + dof_kernel[9] = 0.072806; + dof_kernel[10] = 0.055037; +#endif + +#ifdef DOF_QUALITY_HIGH + const int dof_kernel_size = 21; + const int dof_kernel_from = 10; + float dof_kernel[21]; + dof_kernel[0] = 0.028174; + dof_kernel[1] = 0.032676; + dof_kernel[2] = 0.037311; + dof_kernel[3] = 0.041944; + dof_kernel[4] = 0.046421; + dof_kernel[5] = 0.050582; + dof_kernel[6] = 0.054261; + dof_kernel[7] = 0.057307; + dof_kernel[8] = 0.059587; + dof_kernel[9] = 0.060998; + dof_kernel[10] = 0.061476; + dof_kernel[11] = 0.060998; + dof_kernel[12] = 0.059587; + dof_kernel[13] = 0.057307; + dof_kernel[14] = 0.054261; + dof_kernel[15] = 0.050582; + dof_kernel[16] = 0.046421; + dof_kernel[17] = 0.041944; + dof_kernel[18] = 0.037311; + dof_kernel[19] = 0.032676; + dof_kernel[20] = 0.028174; +#endif +#endif +#endif //!USE_GLES_OVER_GL + +#ifdef DOF_FAR_BLUR + + vec4 color_accum = vec4(0.0); + + float depth = texture2DLod(dof_source_depth, uv_interp, 0.0).r; + depth = depth * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + depth = ((depth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - depth * (camera_z_far - camera_z_near)); +#endif + + float amount = smoothstep(dof_begin, dof_end, depth); + float k_accum = 0.0; + + for (int i = 0; i < dof_kernel_size; i++) { + int int_ofs = i - dof_kernel_from; + vec2 tap_uv = uv_interp + dof_dir * float(int_ofs) * amount * dof_radius; + + float tap_k = dof_kernel[i]; + + float tap_depth = texture2D(dof_source_depth, tap_uv, 0.0).r; + tap_depth = tap_depth * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + tap_depth = ((tap_depth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + tap_depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - tap_depth * (camera_z_far - camera_z_near)); +#endif + float tap_amount = int_ofs == 0 ? 1.0 : smoothstep(dof_begin, dof_end, tap_depth); + tap_amount *= tap_amount * tap_amount; //prevent undesired glow effect + + vec4 tap_color = texture2DLod(source_color, tap_uv, 0.0) * tap_k; + + k_accum += tap_k * tap_amount; + color_accum += tap_color * tap_amount; + } + + if (k_accum > 0.0) { + color_accum /= k_accum; + } + + gl_FragColor = color_accum; ///k_accum; + +#endif + +#ifdef DOF_NEAR_BLUR + + vec4 color_accum = vec4(0.0); + + float max_accum = 0.0; + + for (int i = 0; i < dof_kernel_size; i++) { + int int_ofs = i - dof_kernel_from; + vec2 tap_uv = uv_interp + dof_dir * float(int_ofs) * dof_radius; + float ofs_influence = max(0.0, 1.0 - abs(float(int_ofs)) / float(dof_kernel_from)); + + float tap_k = dof_kernel[i]; + + vec4 tap_color = texture2DLod(source_color, tap_uv, 0.0); + + float tap_depth = texture2D(dof_source_depth, tap_uv, 0.0).r; + tap_depth = tap_depth * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + tap_depth = ((tap_depth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + tap_depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - tap_depth * (camera_z_far - camera_z_near)); +#endif + float tap_amount = 1.0 - smoothstep(dof_end, dof_begin, tap_depth); + tap_amount *= tap_amount * tap_amount; //prevent undesired glow effect + +#ifdef DOF_NEAR_FIRST_TAP + + tap_color.a = 1.0 - smoothstep(dof_end, dof_begin, tap_depth); + +#endif + + max_accum = max(max_accum, tap_amount * ofs_influence); + + color_accum += tap_color * tap_k; + } + + color_accum.a = max(color_accum.a, sqrt(max_accum)); + + gl_FragColor = color_accum; + +#endif + +#ifdef GLOW_FIRST_PASS + + float luminance = max(gl_FragColor.r, max(gl_FragColor.g, gl_FragColor.b)); + float feedback = max(smoothstep(glow_hdr_threshold, glow_hdr_threshold + glow_hdr_scale, luminance), glow_bloom); + + gl_FragColor = min(gl_FragColor * feedback, vec4(luminance_cap)); + +#endif +} diff --git a/drivers/gles2/shaders/exposure.glsl b/drivers/gles2/shaders/exposure.glsl new file mode 100644 index 00000000000..c20812bfa3b --- /dev/null +++ b/drivers/gles2/shaders/exposure.glsl @@ -0,0 +1,86 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ + +void main() { + gl_Position = vertex_attrib; +} + +/* clang-format off */ +[fragment] + +uniform highp sampler2D source_exposure; //texunit:0 +/* clang-format on */ + +#ifdef EXPOSURE_BEGIN + +uniform highp ivec2 source_render_size; +uniform highp ivec2 target_size; + +#endif + +#ifdef EXPOSURE_END + +uniform highp sampler2D prev_exposure; //texunit:1 +uniform highp float exposure_adjust; +uniform highp float min_luminance; +uniform highp float max_luminance; + +#endif + +layout(location = 0) out highp float exposure; + +void main() { +#ifdef EXPOSURE_BEGIN + + ivec2 src_pos = ivec2(gl_FragCoord.xy) * source_render_size / target_size; + +#if 1 + //more precise and expensive, but less jittery + ivec2 next_pos = ivec2(gl_FragCoord.xy + ivec2(1)) * source_render_size / target_size; + next_pos = max(next_pos, src_pos + ivec2(1)); //so it at least reads one pixel + highp vec3 source_color = vec3(0.0); + for (int i = src_pos.x; i < next_pos.x; i++) { + for (int j = src_pos.y; j < next_pos.y; j++) { + source_color += texelFetch(source_exposure, ivec2(i, j), 0).rgb; + } + } + + source_color /= float((next_pos.x - src_pos.x) * (next_pos.y - src_pos.y)); +#else + highp vec3 source_color = texelFetch(source_exposure, src_pos, 0).rgb; + +#endif + + exposure = max(source_color.r, max(source_color.g, source_color.b)); + +#else + + ivec2 coord = ivec2(gl_FragCoord.xy); + exposure = texelFetch(source_exposure, coord * 3 + ivec2(0, 0), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(1, 0), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(2, 0), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(0, 1), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(1, 1), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(2, 1), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(0, 2), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(1, 2), 0).r; + exposure += texelFetch(source_exposure, coord * 3 + ivec2(2, 2), 0).r; + exposure *= (1.0 / 9.0); + +#ifdef EXPOSURE_END + +#ifdef EXPOSURE_FORCE_SET + //will stay as is +#else + highp float prev_lum = texelFetch(prev_exposure, ivec2(0, 0), 0).r; //1 pixel previous exposure + exposure = clamp(prev_lum + (exposure - prev_lum) * exposure_adjust, min_luminance, max_luminance); + +#endif //EXPOSURE_FORCE_SET + +#endif //EXPOSURE_END + +#endif //EXPOSURE_BEGIN +} diff --git a/drivers/gles2/shaders/lens_distorted.glsl b/drivers/gles2/shaders/lens_distorted.glsl new file mode 100644 index 00000000000..d568006cccf --- /dev/null +++ b/drivers/gles2/shaders/lens_distorted.glsl @@ -0,0 +1,84 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute highp vec2 vertex; // attrib:0 +/* clang-format on */ + +uniform vec2 offset; +uniform vec2 scale; + +varying vec2 uv_interp; + +void main() { + uv_interp = vertex.xy * 2.0 - 1.0; + + vec2 v = vertex.xy * scale + offset; + gl_Position = vec4(v, 0.0, 1.0); +} + +/* clang-format off */ +[fragment] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +uniform sampler2D source; //texunit:0 +/* clang-format on */ + +uniform vec2 eye_center; +uniform float k1; +uniform float k2; +uniform float upscale; +uniform float aspect_ratio; + +varying vec2 uv_interp; + +void main() { + vec2 coords = uv_interp; + vec2 offset = coords - eye_center; + + // take aspect ratio into account + offset.y /= aspect_ratio; + + // distort + vec2 offset_sq = offset * offset; + float radius_sq = offset_sq.x + offset_sq.y; + float radius_s4 = radius_sq * radius_sq; + float distortion_scale = 1.0 + (k1 * radius_sq) + (k2 * radius_s4); + offset *= distortion_scale; + + // reapply aspect ratio + offset.y *= aspect_ratio; + + // add our eye center back in + coords = offset + eye_center; + coords /= upscale; + + // and check our color + if (coords.x < -1.0 || coords.y < -1.0 || coords.x > 1.0 || coords.y > 1.0) { + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } else { + coords = (coords + vec2(1.0)) / vec2(2.0); + gl_FragColor = texture2D(source, coords); + } +} diff --git a/drivers/gles2/shaders/particles.glsl b/drivers/gles2/shaders/particles.glsl new file mode 100644 index 00000000000..b7fcb94ed28 --- /dev/null +++ b/drivers/gles2/shaders/particles.glsl @@ -0,0 +1,258 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 color; +/* clang-format on */ +layout(location = 1) in highp vec4 velocity_active; +layout(location = 2) in highp vec4 custom; +layout(location = 3) in highp vec4 xform_1; +layout(location = 4) in highp vec4 xform_2; +layout(location = 5) in highp vec4 xform_3; + +struct Attractor { + vec3 pos; + vec3 dir; + float radius; + float eat_radius; + float strength; + float attenuation; +}; + +#define MAX_ATTRACTORS 64 + +uniform bool emitting; +uniform float system_phase; +uniform float prev_system_phase; +uniform int total_particles; +uniform float explosiveness; +uniform float randomness; +uniform float time; +uniform float delta; + +uniform int attractor_count; +uniform Attractor attractors[MAX_ATTRACTORS]; +uniform bool clear; +uniform uint cycle; +uniform float lifetime; +uniform mat4 emission_transform; +uniform uint random_seed; + +out highp vec4 out_color; //tfb: +out highp vec4 out_velocity_active; //tfb: +out highp vec4 out_custom; //tfb: +out highp vec4 out_xform_1; //tfb: +out highp vec4 out_xform_2; //tfb: +out highp vec4 out_xform_3; //tfb: + +#if defined(USE_MATERIAL) + +/* clang-format off */ +layout(std140) uniform UniformData { //ubo:0 + +MATERIAL_UNIFORMS +}; +/* clang-format on */ + +#endif + +/* clang-format off */ + +VERTEX_SHADER_GLOBALS + +/* clang-format on */ + +uint hash(uint x) { + x = ((x >> uint(16)) ^ x) * uint(0x45d9f3b); + x = ((x >> uint(16)) ^ x) * uint(0x45d9f3b); + x = (x >> uint(16)) ^ x; + return x; +} + +void main() { +#ifdef PARTICLES_COPY + + out_color = color; + out_velocity_active = velocity_active; + out_custom = custom; + out_xform_1 = xform_1; + out_xform_2 = xform_2; + out_xform_3 = xform_3; + +#else + + bool apply_forces = true; + bool apply_velocity = true; + float local_delta = delta; + + float mass = 1.0; + + float restart_phase = float(gl_VertexID) / float(total_particles); + + if (randomness > 0.0) { + uint seed = cycle; + if (restart_phase >= system_phase) { + seed -= uint(1); + } + seed *= uint(total_particles); + seed += uint(gl_VertexID); + float random = float(hash(seed) % uint(65536)) / 65536.0; + restart_phase += randomness * random * 1.0 / float(total_particles); + } + + restart_phase *= (1.0 - explosiveness); + bool restart = false; + bool shader_active = velocity_active.a > 0.5; + + if (system_phase > prev_system_phase) { + // restart_phase >= prev_system_phase is used so particles emit in the first frame they are processed + + if (restart_phase >= prev_system_phase && restart_phase < system_phase) { + restart = true; +#ifdef USE_FRACTIONAL_DELTA + local_delta = (system_phase - restart_phase) * lifetime; +#endif + } + + } else { + if (restart_phase >= prev_system_phase) { + restart = true; +#ifdef USE_FRACTIONAL_DELTA + local_delta = (1.0 - restart_phase + system_phase) * lifetime; +#endif + } else if (restart_phase < system_phase) { + restart = true; +#ifdef USE_FRACTIONAL_DELTA + local_delta = (system_phase - restart_phase) * lifetime; +#endif + } + } + + uint current_cycle = cycle; + + if (system_phase < restart_phase) { + current_cycle -= uint(1); + } + + uint particle_number = current_cycle * uint(total_particles) + uint(gl_VertexID); + int index = int(gl_VertexID); + + if (restart) { + shader_active = emitting; + } + + mat4 xform; + +#if defined(ENABLE_KEEP_DATA) + if (clear) { +#else + if (clear || restart) { +#endif + out_color = vec4(1.0); + out_velocity_active = vec4(0.0); + out_custom = vec4(0.0); + if (!restart) + shader_active = false; + + xform = mat4( + vec4(1.0, 0.0, 0.0, 0.0), + vec4(0.0, 1.0, 0.0, 0.0), + vec4(0.0, 0.0, 1.0, 0.0), + vec4(0.0, 0.0, 0.0, 1.0)); + } else { + out_color = color; + out_velocity_active = velocity_active; + out_custom = custom; + xform = transpose(mat4(xform_1, xform_2, xform_3, vec4(vec3(0.0), 1.0))); + } + + if (shader_active) { + //execute shader + + { + /* clang-format off */ + +VERTEX_SHADER_CODE + + /* clang-format on */ + } + +#if !defined(DISABLE_FORCE) + + if (false) { + vec3 force = vec3(0.0); + for (int i = 0; i < attractor_count; i++) { + vec3 rel_vec = xform[3].xyz - attractors[i].pos; + float dist = length(rel_vec); + if (attractors[i].radius < dist) + continue; + if (attractors[i].eat_radius > 0.0 && attractors[i].eat_radius > dist) { + out_velocity_active.a = 0.0; + } + + rel_vec = normalize(rel_vec); + + float attenuation = pow(dist / attractors[i].radius, attractors[i].attenuation); + + if (attractors[i].dir == vec3(0.0)) { + //towards center + force += attractors[i].strength * rel_vec * attenuation * mass; + } else { + force += attractors[i].strength * attractors[i].dir * attenuation * mass; + } + } + + out_velocity_active.xyz += force * local_delta; + } +#endif + +#if !defined(DISABLE_VELOCITY) + + if (true) { + xform[3].xyz += out_velocity_active.xyz * local_delta; + } +#endif + } else { + xform = mat4(0.0); + } + + xform = transpose(xform); + + out_velocity_active.a = mix(0.0, 1.0, shader_active); + + out_xform_1 = xform[0]; + out_xform_2 = xform[1]; + out_xform_3 = xform[2]; + +#endif //PARTICLES_COPY +} + +/* clang-format off */ +[fragment] + +//any code here is never executed, stuff is filled just so it works + +#if defined(USE_MATERIAL) + +layout(std140) uniform UniformData { + +MATERIAL_UNIFORMS +}; + +#endif + +FRAGMENT_SHADER_GLOBALS + +void main() { + { + +LIGHT_SHADER_CODE + + } + + { + +FRAGMENT_SHADER_CODE + + } +} +/* clang-format on */ diff --git a/drivers/gles2/shaders/resolve.glsl b/drivers/gles2/shaders/resolve.glsl new file mode 100644 index 00000000000..071cb37a99d --- /dev/null +++ b/drivers/gles2/shaders/resolve.glsl @@ -0,0 +1,42 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ +layout(location = 4) in vec2 uv_in; + +out vec2 uv_interp; + +void main() { + uv_interp = uv_in; + gl_Position = vertex_attrib; +} + +/* clang-format off */ +[fragment] + +#if !defined(GLES_OVER_GL) +precision mediump float; +#endif + +in vec2 uv_interp; +/* clang-format on */ +uniform sampler2D source_specular; //texunit:0 +uniform sampler2D source_ssr; //texunit:1 + +uniform vec2 pixel_size; + +in vec2 uv2_interp; + +layout(location = 0) out vec4 frag_color; + +void main() { + vec4 specular = texture(source_specular, uv_interp); + +#ifdef USE_SSR + vec4 ssr = textureLod(source_ssr, uv_interp, 0.0); + specular.rgb = mix(specular.rgb, ssr.rgb * specular.a, ssr.a); +#endif + + frag_color = vec4(specular.rgb, 1.0); +} diff --git a/drivers/gles2/shaders/scene.glsl b/drivers/gles2/shaders/scene.glsl new file mode 100644 index 00000000000..ba3a81a5328 --- /dev/null +++ b/drivers/gles2/shaders/scene.glsl @@ -0,0 +1,2176 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +/* clang-format on */ +#include "stdlib.glsl" +/* clang-format off */ + +#define SHADER_IS_SRGB true + +#define M_PI 3.14159265359 + +// +// attributes +// + +attribute highp vec4 vertex_attrib; // attrib:0 +/* clang-format on */ +attribute vec3 normal_attrib; // attrib:1 + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) +attribute vec4 tangent_attrib; // attrib:2 +#endif + +#if defined(ENABLE_COLOR_INTERP) +attribute vec4 color_attrib; // attrib:3 +#endif + +#if defined(ENABLE_UV_INTERP) +attribute vec2 uv_attrib; // attrib:4 +#endif + +#if defined(ENABLE_UV2_INTERP) || defined(USE_LIGHTMAP) +attribute vec2 uv2_attrib; // attrib:5 +#endif + +#ifdef USE_SKELETON + +#ifdef USE_SKELETON_SOFTWARE + +attribute highp vec4 bone_transform_row_0; // attrib:13 +attribute highp vec4 bone_transform_row_1; // attrib:14 +attribute highp vec4 bone_transform_row_2; // attrib:15 + +#else + +attribute vec4 bone_ids; // attrib:6 +attribute highp vec4 bone_weights; // attrib:7 + +uniform highp sampler2D bone_transforms; // texunit:-1 +uniform ivec2 skeleton_texture_size; + +#endif + +#endif + +#ifdef USE_INSTANCING + +attribute highp vec4 instance_xform_row_0; // attrib:8 +attribute highp vec4 instance_xform_row_1; // attrib:9 +attribute highp vec4 instance_xform_row_2; // attrib:10 + +attribute highp vec4 instance_color; // attrib:11 +attribute highp vec4 instance_custom_data; // attrib:12 + +#endif + +// +// uniforms +// + +uniform highp mat4 camera_matrix; +uniform highp mat4 camera_inverse_matrix; +uniform highp mat4 projection_matrix; +uniform highp mat4 projection_inverse_matrix; + +uniform highp mat4 world_transform; + +uniform highp float time; + +uniform highp vec2 viewport_size; + +#ifdef RENDER_DEPTH +uniform float light_bias; +uniform float light_normal_bias; +#endif + +// +// varyings +// + +#if defined(RENDER_DEPTH) && defined(USE_RGBA_SHADOWS) +varying highp vec4 position_interp; +#endif + +varying highp vec3 vertex_interp; +varying vec3 normal_interp; + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) +varying vec3 tangent_interp; +varying vec3 binormal_interp; +#endif + +#if defined(ENABLE_COLOR_INTERP) +varying vec4 color_interp; +#endif + +#if defined(ENABLE_UV_INTERP) +varying vec2 uv_interp; +#endif + +#if defined(ENABLE_UV2_INTERP) || defined(USE_LIGHTMAP) +varying vec2 uv2_interp; +#endif + +/* clang-format off */ + +VERTEX_SHADER_GLOBALS + +/* clang-format on */ + +#ifdef RENDER_DEPTH_DUAL_PARABOLOID + +varying highp float dp_clip; +uniform highp float shadow_dual_paraboloid_render_zfar; +uniform highp float shadow_dual_paraboloid_render_side; + +#endif + +#if defined(USE_SHADOW) && defined(USE_LIGHTING) + +uniform highp mat4 light_shadow_matrix; +varying highp vec4 shadow_coord; + +#if defined(LIGHT_USE_PSSM2) || defined(LIGHT_USE_PSSM4) +uniform highp mat4 light_shadow_matrix2; +varying highp vec4 shadow_coord2; +#endif + +#if defined(LIGHT_USE_PSSM4) + +uniform highp mat4 light_shadow_matrix3; +uniform highp mat4 light_shadow_matrix4; +varying highp vec4 shadow_coord3; +varying highp vec4 shadow_coord4; + +#endif + +#endif + +#if defined(USE_VERTEX_LIGHTING) && defined(USE_LIGHTING) + +varying highp vec3 diffuse_interp; +varying highp vec3 specular_interp; + +// general for all lights +uniform highp vec4 light_color; +uniform highp vec4 shadow_color; +uniform highp float light_specular; + +// directional +uniform highp vec3 light_direction; + +// omni +uniform highp vec3 light_position; + +uniform highp float light_range; +uniform highp float light_attenuation; + +// spot +uniform highp float light_spot_attenuation; +uniform highp float light_spot_range; +uniform highp float light_spot_angle; + +void light_compute( + vec3 N, + vec3 L, + vec3 V, + vec3 light_color, + vec3 attenuation, + float roughness) { +//this makes lights behave closer to linear, but then addition of lights looks bad +//better left disabled + +//#define SRGB_APPROX(m_var) m_var = pow(m_var,0.4545454545); +/* +#define SRGB_APPROX(m_var) {\ + float S1 = sqrt(m_var);\ + float S2 = sqrt(S1);\ + float S3 = sqrt(S2);\ + m_var = 0.662002687 * S1 + 0.684122060 * S2 - 0.323583601 * S3 - 0.0225411470 * m_var;\ + } +*/ +#define SRGB_APPROX(m_var) + + float NdotL = dot(N, L); + float cNdotL = max(NdotL, 0.0); // clamped NdotL + float NdotV = dot(N, V); + float cNdotV = max(NdotV, 0.0); + +#if defined(DIFFUSE_OREN_NAYAR) + vec3 diffuse_brdf_NL; +#else + float diffuse_brdf_NL; // BRDF times N.L for calculating diffuse radiance +#endif + +#if defined(DIFFUSE_LAMBERT_WRAP) + // energy conserving lambert wrap shader + diffuse_brdf_NL = max(0.0, (NdotL + roughness) / ((1.0 + roughness) * (1.0 + roughness))); + +#elif defined(DIFFUSE_OREN_NAYAR) + + { + // see http://mimosa-pudica.net/improved-oren-nayar.html + float LdotV = dot(L, V); + + float s = LdotV - NdotL * NdotV; + float t = mix(1.0, max(NdotL, NdotV), step(0.0, s)); + + float sigma2 = roughness * roughness; // TODO: this needs checking + vec3 A = 1.0 + sigma2 * (-0.5 / (sigma2 + 0.33) + 0.17 * diffuse_color / (sigma2 + 0.13)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + diffuse_brdf_NL = cNdotL * (A + vec3(B) * s / t) * (1.0 / M_PI); + } +#else + // lambert by default for everything else + diffuse_brdf_NL = cNdotL * (1.0 / M_PI); +#endif + + SRGB_APPROX(diffuse_brdf_NL) + + diffuse_interp += light_color * diffuse_brdf_NL * attenuation; + + if (roughness > 0.0) { + // D + float specular_brdf_NL = 0.0; + +#if !defined(SPECULAR_DISABLED) + //normalized blinn always unless disabled + vec3 H = normalize(V + L); + float cNdotH = max(dot(N, H), 0.0); + float shininess = exp2(15.0 * (1.0 - roughness) + 1.0) * 0.25; + float blinn = pow(cNdotH, shininess) * cNdotL; + blinn *= (shininess + 8.0) * (1.0 / (8.0 * M_PI)); + specular_brdf_NL = blinn; +#endif + + SRGB_APPROX(specular_brdf_NL) + specular_interp += specular_brdf_NL * light_color * attenuation * (1.0 / M_PI); + } +} + +#endif + +#ifdef USE_VERTEX_LIGHTING + +#ifdef USE_REFLECTION_PROBE1 + +uniform highp mat4 refprobe1_local_matrix; +varying mediump vec4 refprobe1_reflection_normal_blend; +uniform highp vec3 refprobe1_box_extents; + +#ifndef USE_LIGHTMAP +varying mediump vec3 refprobe1_ambient_normal; +#endif + +#endif //reflection probe1 + +#ifdef USE_REFLECTION_PROBE2 + +uniform highp mat4 refprobe2_local_matrix; +varying mediump vec4 refprobe2_reflection_normal_blend; +uniform highp vec3 refprobe2_box_extents; + +#ifndef USE_LIGHTMAP +varying mediump vec3 refprobe2_ambient_normal; +#endif + +#endif //reflection probe2 + +#endif //vertex lighting for refprobes + +#if defined(FOG_DEPTH_ENABLED) || defined(FOG_HEIGHT_ENABLED) + +varying vec4 fog_interp; + +uniform mediump vec4 fog_color_base; +#ifdef LIGHT_MODE_DIRECTIONAL +uniform mediump vec4 fog_sun_color_amount; +#endif + +uniform bool fog_transmit_enabled; +uniform mediump float fog_transmit_curve; + +#ifdef FOG_DEPTH_ENABLED +uniform highp float fog_depth_begin; +uniform mediump float fog_depth_curve; +uniform mediump float fog_max_distance; +#endif + +#ifdef FOG_HEIGHT_ENABLED +uniform highp float fog_height_min; +uniform highp float fog_height_max; +uniform mediump float fog_height_curve; +#endif + +#endif //fog + +void main() { + highp vec4 vertex = vertex_attrib; + + mat4 world_matrix = world_transform; + +#ifdef USE_INSTANCING + { + highp mat4 m = mat4( + instance_xform_row_0, + instance_xform_row_1, + instance_xform_row_2, + vec4(0.0, 0.0, 0.0, 1.0)); + world_matrix = world_matrix * transpose(m); + } + +#endif + + vec3 normal = normal_attrib; + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + vec3 tangent = tangent_attrib.xyz; + float binormalf = tangent_attrib.a; + vec3 binormal = normalize(cross(normal, tangent) * binormalf); +#endif + +#if defined(ENABLE_COLOR_INTERP) + color_interp = color_attrib; +#ifdef USE_INSTANCING + color_interp *= instance_color; +#endif +#endif + +#if defined(ENABLE_UV_INTERP) + uv_interp = uv_attrib; +#endif + +#if defined(ENABLE_UV2_INTERP) || defined(USE_LIGHTMAP) + uv2_interp = uv2_attrib; +#endif + +#if defined(OVERRIDE_POSITION) + highp vec4 position; +#endif + +#if !defined(SKIP_TRANSFORM_USED) && defined(VERTEX_WORLD_COORDS_USED) + vertex = world_matrix * vertex; + normal = normalize((world_matrix * vec4(normal, 0.0)).xyz); +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + + tangent = normalize((world_matrix * vec4(tangent, 0.0)).xyz); + binormal = normalize((world_matrix * vec4(binormal, 0.0)).xyz); +#endif +#endif + +#ifdef USE_SKELETON + + highp mat4 bone_transform = mat4(0.0); + +#ifdef USE_SKELETON_SOFTWARE + // passing the transform as attributes + + bone_transform[0] = vec4(bone_transform_row_0.x, bone_transform_row_1.x, bone_transform_row_2.x, 0.0); + bone_transform[1] = vec4(bone_transform_row_0.y, bone_transform_row_1.y, bone_transform_row_2.y, 0.0); + bone_transform[2] = vec4(bone_transform_row_0.z, bone_transform_row_1.z, bone_transform_row_2.z, 0.0); + bone_transform[3] = vec4(bone_transform_row_0.w, bone_transform_row_1.w, bone_transform_row_2.w, 1.0); + +#else + // look up transform from the "pose texture" + { + for (int i = 0; i < 4; i++) { + ivec2 tex_ofs = ivec2(int(bone_ids[i]) * 3, 0); + + highp mat4 b = mat4( + texel2DFetch(bone_transforms, skeleton_texture_size, tex_ofs + ivec2(0, 0)), + texel2DFetch(bone_transforms, skeleton_texture_size, tex_ofs + ivec2(1, 0)), + texel2DFetch(bone_transforms, skeleton_texture_size, tex_ofs + ivec2(2, 0)), + vec4(0.0, 0.0, 0.0, 1.0)); + + bone_transform += transpose(b) * bone_weights[i]; + } + } + +#endif + + world_matrix = world_matrix * bone_transform; + +#endif + +#ifdef USE_INSTANCING + vec4 instance_custom = instance_custom_data; +#else + vec4 instance_custom = vec4(0.0); + +#endif + + mat4 local_projection_matrix = projection_matrix; + + mat4 modelview = camera_inverse_matrix * world_matrix; + float roughness = 1.0; + +#define projection_matrix local_projection_matrix +#define world_transform world_matrix + + float point_size = 1.0; + + { + /* clang-format off */ + +VERTEX_SHADER_CODE + + /* clang-format on */ + } + + gl_PointSize = point_size; + vec4 outvec = vertex; + + // use local coordinates +#if !defined(SKIP_TRANSFORM_USED) && !defined(VERTEX_WORLD_COORDS_USED) + vertex = modelview * vertex; + normal = normalize((modelview * vec4(normal, 0.0)).xyz); + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + tangent = normalize((modelview * vec4(tangent, 0.0)).xyz); + binormal = normalize((modelview * vec4(binormal, 0.0)).xyz); +#endif +#endif + +#if !defined(SKIP_TRANSFORM_USED) && defined(VERTEX_WORLD_COORDS_USED) + vertex = camera_inverse_matrix * vertex; + normal = normalize((camera_inverse_matrix * vec4(normal, 0.0)).xyz); +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + tangent = normalize((camera_inverse_matrix * vec4(tangent, 0.0)).xyz); + binormal = normalize((camera_inverse_matrix * vec4(binormal, 0.0)).xyz); +#endif +#endif + + vertex_interp = vertex.xyz; + normal_interp = normal; + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + tangent_interp = tangent; + binormal_interp = binormal; +#endif + +#ifdef RENDER_DEPTH + +#ifdef RENDER_DEPTH_DUAL_PARABOLOID + + vertex_interp.z *= shadow_dual_paraboloid_render_side; + normal_interp.z *= shadow_dual_paraboloid_render_side; + + dp_clip = vertex_interp.z; //this attempts to avoid noise caused by objects sent to the other parabolloid side due to bias + + //for dual paraboloid shadow mapping, this is the fastest but least correct way, as it curves straight edges + + highp vec3 vtx = vertex_interp + normalize(vertex_interp) * light_bias; + highp float distance = length(vtx); + vtx = normalize(vtx); + vtx.xy /= 1.0 - vtx.z; + vtx.z = (distance / shadow_dual_paraboloid_render_zfar); + vtx.z = vtx.z * 2.0 - 1.0; + + vertex_interp = vtx; + +#else + float z_ofs = light_bias; + z_ofs += (1.0 - abs(normal_interp.z)) * light_normal_bias; + + vertex_interp.z -= z_ofs; +#endif //dual parabolloid + +#endif //depth + +//vertex lighting +#if defined(USE_VERTEX_LIGHTING) && defined(USE_LIGHTING) + //vertex shaded version of lighting (more limited) + vec3 L; + vec3 light_att; + +#ifdef LIGHT_MODE_OMNI + vec3 light_vec = light_position - vertex_interp; + float light_length = length(light_vec); + + float normalized_distance = light_length / light_range; + + if (normalized_distance < 1.0) { + float omni_attenuation = pow(1.0 - normalized_distance, light_attenuation); + + vec3 attenuation = vec3(omni_attenuation); + light_att = vec3(omni_attenuation); + } else { + light_att = vec3(0.0); + } + + L = normalize(light_vec); + +#endif + +#ifdef LIGHT_MODE_SPOT + + vec3 light_rel_vec = light_position - vertex_interp; + float light_length = length(light_rel_vec); + float normalized_distance = light_length / light_range; + + if (normalized_distance < 1.0) { + float spot_attenuation = pow(1.0 - normalized_distance, light_attenuation); + vec3 spot_dir = light_direction; + + float spot_cutoff = light_spot_angle; + + float angle = dot(-normalize(light_rel_vec), spot_dir); + + if (angle > spot_cutoff) { + float scos = max(angle, spot_cutoff); + float spot_rim = max(0.0001, (1.0 - scos) / (1.0 - spot_cutoff)); + + spot_attenuation *= 1.0 - pow(spot_rim, light_spot_attenuation); + + light_att = vec3(spot_attenuation); + } else { + light_att = vec3(0.0); + } + } else { + light_att = vec3(0.0); + } + + L = normalize(light_rel_vec); + +#endif + +#ifdef LIGHT_MODE_DIRECTIONAL + vec3 light_vec = -light_direction; + light_att = vec3(1.0); //no base attenuation + L = normalize(light_vec); +#endif + + diffuse_interp = vec3(0.0); + specular_interp = vec3(0.0); + light_compute(normal_interp, L, -normalize(vertex_interp), light_color.rgb, light_att, roughness); + +#endif + +//shadows (for both vertex and fragment) +#if defined(USE_SHADOW) && defined(USE_LIGHTING) + + vec4 vi4 = vec4(vertex_interp, 1.0); + shadow_coord = light_shadow_matrix * vi4; + +#if defined(LIGHT_USE_PSSM2) || defined(LIGHT_USE_PSSM4) + shadow_coord2 = light_shadow_matrix2 * vi4; +#endif + +#if defined(LIGHT_USE_PSSM4) + shadow_coord3 = light_shadow_matrix3 * vi4; + shadow_coord4 = light_shadow_matrix4 * vi4; + +#endif + +#endif //use shadow and use lighting + +#ifdef USE_VERTEX_LIGHTING + +#ifdef USE_REFLECTION_PROBE1 + { + vec3 ref_normal = normalize(reflect(vertex_interp, normal_interp)); + vec3 local_pos = (refprobe1_local_matrix * vec4(vertex_interp, 1.0)).xyz; + vec3 inner_pos = abs(local_pos / refprobe1_box_extents); + float blend = max(inner_pos.x, max(inner_pos.y, inner_pos.z)); + + { + vec3 local_ref_vec = (refprobe1_local_matrix * vec4(ref_normal, 0.0)).xyz; + refprobe1_reflection_normal_blend.xyz = local_ref_vec; + refprobe1_reflection_normal_blend.a = blend; + } +#ifndef USE_LIGHTMAP + + refprobe1_ambient_normal = (refprobe1_local_matrix * vec4(normal_interp, 0.0)).xyz; +#endif + } + +#endif //USE_REFLECTION_PROBE1 + +#ifdef USE_REFLECTION_PROBE2 + { + vec3 ref_normal = normalize(reflect(vertex_interp, normal_interp)); + vec3 local_pos = (refprobe2_local_matrix * vec4(vertex_interp, 1.0)).xyz; + vec3 inner_pos = abs(local_pos / refprobe2_box_extents); + float blend = max(inner_pos.x, max(inner_pos.y, inner_pos.z)); + + { + vec3 local_ref_vec = (refprobe2_local_matrix * vec4(ref_normal, 0.0)).xyz; + refprobe2_reflection_normal_blend.xyz = local_ref_vec; + refprobe2_reflection_normal_blend.a = blend; + } +#ifndef USE_LIGHTMAP + + refprobe2_ambient_normal = (refprobe2_local_matrix * vec4(normal_interp, 0.0)).xyz; +#endif + } + +#endif //USE_REFLECTION_PROBE2 + +#if defined(FOG_DEPTH_ENABLED) || defined(FOG_HEIGHT_ENABLED) + + float fog_amount = 0.0; + +#ifdef LIGHT_MODE_DIRECTIONAL + + vec3 fog_color = mix(fog_color_base.rgb, fog_sun_color_amount.rgb, fog_sun_color_amount.a * pow(max(dot(normalize(vertex_interp), light_direction), 0.0), 8.0)); +#else + vec3 fog_color = fog_color_base.rgb; +#endif + +#ifdef FOG_DEPTH_ENABLED + + { + float fog_z = smoothstep(fog_depth_begin, fog_max_distance, length(vertex)); + + fog_amount = pow(fog_z, fog_depth_curve) * fog_color_base.a; + } +#endif + +#ifdef FOG_HEIGHT_ENABLED + { + float y = (camera_matrix * vec4(vertex_interp, 1.0)).y; + fog_amount = max(fog_amount, pow(smoothstep(fog_height_min, fog_height_max, y), fog_height_curve)); + } +#endif + fog_interp = vec4(fog_color, fog_amount); + +#endif //fog + +#endif //use vertex lighting + +#if defined(OVERRIDE_POSITION) + gl_Position = position; +#else + gl_Position = projection_matrix * vec4(vertex_interp, 1.0); +#endif + +#if defined(RENDER_DEPTH) && defined(USE_RGBA_SHADOWS) + position_interp = gl_Position; +#endif +} + +/* clang-format off */ +[fragment] + +// texture2DLodEXT and textureCubeLodEXT are fragment shader specific. +// Do not copy these defines in the vertex section. +#ifndef USE_GLES_OVER_GL +#ifdef GL_EXT_shader_texture_lod +#extension GL_EXT_shader_texture_lod : enable +#define texture2DLod(img, coord, lod) texture2DLodEXT(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCubeLodEXT(img, coord, lod) +#endif +#endif // !USE_GLES_OVER_GL + +#ifdef GL_ARB_shader_texture_lod +#extension GL_ARB_shader_texture_lod : enable +#endif + +#if !defined(GL_EXT_shader_texture_lod) && !defined(GL_ARB_shader_texture_lod) +#define texture2DLod(img, coord, lod) texture2D(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCube(img, coord, lod) +#endif + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +#include "stdlib.glsl" + +#define M_PI 3.14159265359 +#define SHADER_IS_SRGB true + +// +// uniforms +// + +uniform highp mat4 camera_matrix; +/* clang-format on */ +uniform highp mat4 camera_inverse_matrix; +uniform highp mat4 projection_matrix; +uniform highp mat4 projection_inverse_matrix; + +uniform highp mat4 world_transform; + +uniform highp float time; + +uniform highp vec2 viewport_size; + +#if defined(SCREEN_UV_USED) +uniform vec2 screen_pixel_size; +#endif + +#if defined(SCREEN_TEXTURE_USED) +uniform highp sampler2D screen_texture; //texunit:-4 +#endif +#if defined(DEPTH_TEXTURE_USED) +uniform highp sampler2D depth_texture; //texunit:-4 +#endif + +#ifdef USE_REFLECTION_PROBE1 + +#ifdef USE_VERTEX_LIGHTING + +varying mediump vec4 refprobe1_reflection_normal_blend; +#ifndef USE_LIGHTMAP +varying mediump vec3 refprobe1_ambient_normal; +#endif + +#else + +uniform bool refprobe1_use_box_project; +uniform highp vec3 refprobe1_box_extents; +uniform vec3 refprobe1_box_offset; +uniform highp mat4 refprobe1_local_matrix; + +#endif //use vertex lighting + +uniform bool refprobe1_exterior; + +uniform highp samplerCube reflection_probe1; //texunit:-5 + +uniform float refprobe1_intensity; +uniform vec4 refprobe1_ambient; + +#endif //USE_REFLECTION_PROBE1 + +#ifdef USE_REFLECTION_PROBE2 + +#ifdef USE_VERTEX_LIGHTING + +varying mediump vec4 refprobe2_reflection_normal_blend; +#ifndef USE_LIGHTMAP +varying mediump vec3 refprobe2_ambient_normal; +#endif + +#else + +uniform bool refprobe2_use_box_project; +uniform highp vec3 refprobe2_box_extents; +uniform vec3 refprobe2_box_offset; +uniform highp mat4 refprobe2_local_matrix; + +#endif //use vertex lighting + +uniform bool refprobe2_exterior; + +uniform highp samplerCube reflection_probe2; //texunit:-6 + +uniform float refprobe2_intensity; +uniform vec4 refprobe2_ambient; + +#endif //USE_REFLECTION_PROBE2 + +#define RADIANCE_MAX_LOD 6.0 + +#if defined(USE_REFLECTION_PROBE1) || defined(USE_REFLECTION_PROBE2) + +void reflection_process(samplerCube reflection_map, +#ifdef USE_VERTEX_LIGHTING + vec3 ref_normal, +#ifndef USE_LIGHTMAP + vec3 amb_normal, +#endif + float ref_blend, + +#else //no vertex lighting + vec3 normal, vec3 vertex, + mat4 local_matrix, + bool use_box_project, vec3 box_extents, vec3 box_offset, +#endif //vertex lighting + bool exterior, float intensity, vec4 ref_ambient, float roughness, vec3 ambient, vec3 skybox, inout highp vec4 reflection_accum, inout highp vec4 ambient_accum) { + vec4 reflection; + +#ifdef USE_VERTEX_LIGHTING + + reflection.rgb = textureCubeLod(reflection_map, ref_normal, roughness * RADIANCE_MAX_LOD).rgb; + + float blend = ref_blend; //crappier blend formula for vertex + blend *= blend; + blend = max(0.0, 1.0 - blend); + +#else //fragment lighting + + vec3 local_pos = (local_matrix * vec4(vertex, 1.0)).xyz; + + if (any(greaterThan(abs(local_pos), box_extents))) { //out of the reflection box + return; + } + + vec3 inner_pos = abs(local_pos / box_extents); + float blend = max(inner_pos.x, max(inner_pos.y, inner_pos.z)); + blend = mix(length(inner_pos), blend, blend); + blend *= blend; + blend = max(0.0, 1.0 - blend); + + //reflect and make local + vec3 ref_normal = normalize(reflect(vertex, normal)); + ref_normal = (local_matrix * vec4(ref_normal, 0.0)).xyz; + + if (use_box_project) { //box project + + vec3 nrdir = normalize(ref_normal); + vec3 rbmax = (box_extents - local_pos) / nrdir; + vec3 rbmin = (-box_extents - local_pos) / nrdir; + + vec3 rbminmax = mix(rbmin, rbmax, vec3(greaterThan(nrdir, vec3(0.0, 0.0, 0.0)))); + + float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z); + vec3 posonbox = local_pos + nrdir * fa; + ref_normal = posonbox - box_offset.xyz; + } + + reflection.rgb = textureCubeLod(reflection_map, ref_normal, roughness * RADIANCE_MAX_LOD).rgb; +#endif + + if (exterior) { + reflection.rgb = mix(skybox, reflection.rgb, blend); + } + reflection.rgb *= intensity; + reflection.a = blend; + reflection.rgb *= blend; + + reflection_accum += reflection; + +#ifndef USE_LIGHTMAP + + vec4 ambient_out; +#ifndef USE_VERTEX_LIGHTING + + vec3 amb_normal = (local_matrix * vec4(normal, 0.0)).xyz; +#endif + + ambient_out.rgb = textureCubeLod(reflection_map, amb_normal, RADIANCE_MAX_LOD).rgb; + ambient_out.rgb = mix(ref_ambient.rgb, ambient_out.rgb, ref_ambient.a); + if (exterior) { + ambient_out.rgb = mix(ambient, ambient_out.rgb, blend); + } + + ambient_out.a = blend; + ambient_out.rgb *= blend; + ambient_accum += ambient_out; + +#endif +} + +#endif //use refprobe 1 or 2 + +#ifdef USE_LIGHTMAP +uniform mediump sampler2D lightmap; //texunit:-4 +uniform mediump float lightmap_energy; +#endif + +#ifdef USE_LIGHTMAP_CAPTURE +uniform mediump vec4[12] lightmap_captures; +uniform bool lightmap_capture_sky; + +#endif + +#ifdef USE_RADIANCE_MAP + +uniform samplerCube radiance_map; // texunit:-2 + +uniform mat4 radiance_inverse_xform; + +#endif + +uniform vec4 bg_color; +uniform float bg_energy; + +uniform float ambient_sky_contribution; +uniform vec4 ambient_color; +uniform float ambient_energy; + +#ifdef USE_LIGHTING + +uniform highp vec4 shadow_color; + +#ifdef USE_VERTEX_LIGHTING + +//get from vertex +varying highp vec3 diffuse_interp; +varying highp vec3 specular_interp; + +uniform highp vec3 light_direction; //may be used by fog, so leave here + +#else +//done in fragment +// general for all lights +uniform highp vec4 light_color; + +uniform highp float light_specular; + +// directional +uniform highp vec3 light_direction; +// omni +uniform highp vec3 light_position; + +uniform highp float light_attenuation; + +// spot +uniform highp float light_spot_attenuation; +uniform highp float light_spot_range; +uniform highp float light_spot_angle; +#endif + +//this is needed outside above if because dual paraboloid wants it +uniform highp float light_range; + +#ifdef USE_SHADOW + +uniform highp vec2 shadow_pixel_size; + +#if defined(LIGHT_MODE_OMNI) || defined(LIGHT_MODE_SPOT) +uniform highp sampler2D light_shadow_atlas; //texunit:-3 +#endif + +#ifdef LIGHT_MODE_DIRECTIONAL +uniform highp sampler2D light_directional_shadow; // texunit:-3 +uniform highp vec4 light_split_offsets; +#endif + +varying highp vec4 shadow_coord; + +#if defined(LIGHT_USE_PSSM2) || defined(LIGHT_USE_PSSM4) +varying highp vec4 shadow_coord2; +#endif + +#if defined(LIGHT_USE_PSSM4) + +varying highp vec4 shadow_coord3; +varying highp vec4 shadow_coord4; + +#endif + +uniform vec4 light_clamp; + +#endif // light shadow + +// directional shadow + +#endif + +// +// varyings +// + +#if defined(RENDER_DEPTH) && defined(USE_RGBA_SHADOWS) +varying highp vec4 position_interp; +#endif + +varying highp vec3 vertex_interp; +varying vec3 normal_interp; + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) +varying vec3 tangent_interp; +varying vec3 binormal_interp; +#endif + +#if defined(ENABLE_COLOR_INTERP) +varying vec4 color_interp; +#endif + +#if defined(ENABLE_UV_INTERP) +varying vec2 uv_interp; +#endif + +#if defined(ENABLE_UV2_INTERP) || defined(USE_LIGHTMAP) +varying vec2 uv2_interp; +#endif + +varying vec3 view_interp; + +vec3 F0(float metallic, float specular, vec3 albedo) { + float dielectric = 0.16 * specular * specular; + // use albedo * metallic as colored specular reflectance at 0 angle for metallic materials; + // see https://google.github.io/filament/Filament.md.html + return mix(vec3(dielectric), albedo, vec3(metallic)); +} + +/* clang-format off */ + +FRAGMENT_SHADER_GLOBALS + +/* clang-format on */ + +#ifdef RENDER_DEPTH_DUAL_PARABOLOID + +varying highp float dp_clip; + +#endif + +#ifdef USE_LIGHTING + +// This returns the G_GGX function divided by 2 cos_theta_m, where in practice cos_theta_m is either N.L or N.V. +// We're dividing this factor off because the overall term we'll end up looks like +// (see, for example, the first unnumbered equation in B. Burley, "Physically Based Shading at Disney", SIGGRAPH 2012): +// +// F(L.V) D(N.H) G(N.L) G(N.V) / (4 N.L N.V) +// +// We're basically regouping this as +// +// F(L.V) D(N.H) [G(N.L)/(2 N.L)] [G(N.V) / (2 N.V)] +// +// and thus, this function implements the [G(N.m)/(2 N.m)] part with m = L or V. +// +// The contents of the D and G (G1) functions (GGX) are taken from +// E. Heitz, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs", J. Comp. Graph. Tech. 3 (2) (2014). +// Eqns 71-72 and 85-86 (see also Eqns 43 and 80). + +/* +float G_GGX_2cos(float cos_theta_m, float alpha) { + // Schlick's approximation + // C. Schlick, "An Inexpensive BRDF Model for Physically-based Rendering", Computer Graphics Forum. 13 (3): 233 (1994) + // Eq. (19), although see Heitz (2014) the about the problems with his derivation. + // It nevertheless approximates GGX well with k = alpha/2. + float k = 0.5 * alpha; + return 0.5 / (cos_theta_m * (1.0 - k) + k); + + // float cos2 = cos_theta_m * cos_theta_m; + // float sin2 = (1.0 - cos2); + // return 1.0 / (cos_theta_m + sqrt(cos2 + alpha * alpha * sin2)); +} +*/ + +// This approximates G_GGX_2cos(cos_theta_l, alpha) * G_GGX_2cos(cos_theta_v, alpha) +// See Filament docs, Specular G section. +float V_GGX(float cos_theta_l, float cos_theta_v, float alpha) { + return 0.5 / mix(2.0 * cos_theta_l * cos_theta_v, cos_theta_l + cos_theta_v, alpha); +} + +float D_GGX(float cos_theta_m, float alpha) { + float alpha2 = alpha * alpha; + float d = 1.0 + (alpha2 - 1.0) * cos_theta_m * cos_theta_m; + return alpha2 / (M_PI * d * d); +} + +/* +float G_GGX_anisotropic_2cos(float cos_theta_m, float alpha_x, float alpha_y, float cos_phi, float sin_phi) { + float cos2 = cos_theta_m * cos_theta_m; + float sin2 = (1.0 - cos2); + float s_x = alpha_x * cos_phi; + float s_y = alpha_y * sin_phi; + return 1.0 / max(cos_theta_m + sqrt(cos2 + (s_x * s_x + s_y * s_y) * sin2), 0.001); +} +*/ + +// This approximates G_GGX_anisotropic_2cos(cos_theta_l, ...) * G_GGX_anisotropic_2cos(cos_theta_v, ...) +// See Filament docs, Anisotropic specular BRDF section. +float V_GGX_anisotropic(float alpha_x, float alpha_y, float TdotV, float TdotL, float BdotV, float BdotL, float NdotV, float NdotL) { + float Lambda_V = NdotL * length(vec3(alpha_x * TdotV, alpha_y * BdotV, NdotV)); + float Lambda_L = NdotV * length(vec3(alpha_x * TdotL, alpha_y * BdotL, NdotL)); + return 0.5 / (Lambda_V + Lambda_L); +} + +float D_GGX_anisotropic(float cos_theta_m, float alpha_x, float alpha_y, float cos_phi, float sin_phi, float NdotH) { + float alpha2 = alpha_x * alpha_y; + highp vec3 v = vec3(alpha_y * cos_phi, alpha_x * sin_phi, alpha2 * NdotH); + highp float v2 = dot(v, v); + float w2 = alpha2 / v2; + float D = alpha2 * w2 * w2 * (1.0 / M_PI); + return D; + + /* float cos2 = cos_theta_m * cos_theta_m; + float sin2 = (1.0 - cos2); + float r_x = cos_phi / alpha_x; + float r_y = sin_phi / alpha_y; + float d = cos2 + sin2 * (r_x * r_x + r_y * r_y); + return 1.0 / max(M_PI * alpha_x * alpha_y * d * d, 0.001); */ +} + +float SchlickFresnel(float u) { + float m = 1.0 - u; + float m2 = m * m; + return m2 * m2 * m; // pow(m,5) +} + +float GTR1(float NdotH, float a) { + if (a >= 1.0) + return 1.0 / M_PI; + float a2 = a * a; + float t = 1.0 + (a2 - 1.0) * NdotH * NdotH; + return (a2 - 1.0) / (M_PI * log(a2) * t); +} + +void light_compute( + vec3 N, + vec3 L, + vec3 V, + vec3 B, + vec3 T, + vec3 light_color, + vec3 attenuation, + vec3 diffuse_color, + vec3 transmission, + float specular_blob_intensity, + float roughness, + float metallic, + float specular, + float rim, + float rim_tint, + float clearcoat, + float clearcoat_gloss, + float anisotropy, + inout vec3 diffuse_light, + inout vec3 specular_light, + inout float alpha) { +//this makes lights behave closer to linear, but then addition of lights looks bad +//better left disabled + +//#define SRGB_APPROX(m_var) m_var = pow(m_var,0.4545454545); +/* +#define SRGB_APPROX(m_var) {\ + float S1 = sqrt(m_var);\ + float S2 = sqrt(S1);\ + float S3 = sqrt(S2);\ + m_var = 0.662002687 * S1 + 0.684122060 * S2 - 0.323583601 * S3 - 0.0225411470 * m_var;\ + } +*/ +#define SRGB_APPROX(m_var) + +#if defined(USE_LIGHT_SHADER_CODE) + // light is written by the light shader + + vec3 normal = N; + vec3 albedo = diffuse_color; + vec3 light = L; + vec3 view = V; + + /* clang-format off */ + +LIGHT_SHADER_CODE + + /* clang-format on */ + +#else + float NdotL = dot(N, L); + float cNdotL = max(NdotL, 0.0); // clamped NdotL + float NdotV = dot(N, V); + float cNdotV = max(abs(NdotV), 1e-6); + +#if defined(DIFFUSE_BURLEY) || defined(SPECULAR_BLINN) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_USE_CLEARCOAT) + vec3 H = normalize(V + L); +#endif + +#if defined(SPECULAR_BLINN) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_USE_CLEARCOAT) + float cNdotH = max(dot(N, H), 0.0); +#endif + +#if defined(DIFFUSE_BURLEY) || defined(SPECULAR_SCHLICK_GGX) || defined(LIGHT_USE_CLEARCOAT) + float cLdotH = max(dot(L, H), 0.0); +#endif + + if (metallic < 1.0) { +#if defined(DIFFUSE_OREN_NAYAR) + vec3 diffuse_brdf_NL; +#else + float diffuse_brdf_NL; // BRDF times N.L for calculating diffuse radiance +#endif + +#if defined(DIFFUSE_LAMBERT_WRAP) + // energy conserving lambert wrap shader + diffuse_brdf_NL = max(0.0, (NdotL + roughness) / ((1.0 + roughness) * (1.0 + roughness))); + +#elif defined(DIFFUSE_OREN_NAYAR) + + { + // see http://mimosa-pudica.net/improved-oren-nayar.html + float LdotV = dot(L, V); + + float s = LdotV - NdotL * NdotV; + float t = mix(1.0, max(NdotL, NdotV), step(0.0, s)); + + float sigma2 = roughness * roughness; // TODO: this needs checking + vec3 A = 1.0 + sigma2 * (-0.5 / (sigma2 + 0.33) + 0.17 * diffuse_color / (sigma2 + 0.13)); + float B = 0.45 * sigma2 / (sigma2 + 0.09); + + diffuse_brdf_NL = cNdotL * (A + vec3(B) * s / t) * (1.0 / M_PI); + } + +#elif defined(DIFFUSE_TOON) + + diffuse_brdf_NL = smoothstep(-roughness, max(roughness, 0.01), NdotL); + +#elif defined(DIFFUSE_BURLEY) + + { + float FD90_minus_1 = 2.0 * cLdotH * cLdotH * roughness - 0.5; + float FdV = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotV); + float FdL = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotL); + diffuse_brdf_NL = (1.0 / M_PI) * FdV * FdL * cNdotL; + /* + float energyBias = mix(roughness, 0.0, 0.5); + float energyFactor = mix(roughness, 1.0, 1.0 / 1.51); + float fd90 = energyBias + 2.0 * VoH * VoH * roughness; + float f0 = 1.0; + float lightScatter = f0 + (fd90 - f0) * pow(1.0 - cNdotL, 5.0); + float viewScatter = f0 + (fd90 - f0) * pow(1.0 - cNdotV, 5.0); + + diffuse_brdf_NL = lightScatter * viewScatter * energyFactor; + */ + } +#else + // lambert + diffuse_brdf_NL = cNdotL * (1.0 / M_PI); +#endif + + SRGB_APPROX(diffuse_brdf_NL) + + diffuse_light += light_color * diffuse_color * diffuse_brdf_NL * attenuation; + +#if defined(TRANSMISSION_USED) + diffuse_light += light_color * diffuse_color * (vec3(1.0 / M_PI) - diffuse_brdf_NL) * transmission * attenuation; +#endif + +#if defined(LIGHT_USE_RIM) + float rim_light = pow(max(0.0, 1.0 - cNdotV), max(0.0, (1.0 - roughness) * 16.0)); + diffuse_light += rim_light * rim * mix(vec3(1.0), diffuse_color, rim_tint) * light_color; +#endif + } + + if (roughness > 0.0) { + +#if defined(SPECULAR_SCHLICK_GGX) + vec3 specular_brdf_NL = vec3(0.0); +#else + float specular_brdf_NL = 0.0; +#endif + +#if defined(SPECULAR_BLINN) + + //normalized blinn + float shininess = exp2(15.0 * (1.0 - roughness) + 1.0) * 0.25; + float blinn = pow(cNdotH, shininess) * cNdotL; + blinn *= (shininess + 8.0) * (1.0 / (8.0 * M_PI)); + specular_brdf_NL = blinn; + +#elif defined(SPECULAR_PHONG) + + vec3 R = normalize(-reflect(L, N)); + float cRdotV = max(0.0, dot(R, V)); + float shininess = exp2(15.0 * (1.0 - roughness) + 1.0) * 0.25; + float phong = pow(cRdotV, shininess); + phong *= (shininess + 8.0) * (1.0 / (8.0 * M_PI)); + specular_brdf_NL = (phong) / max(4.0 * cNdotV * cNdotL, 0.75); + +#elif defined(SPECULAR_TOON) + + vec3 R = normalize(-reflect(L, N)); + float RdotV = dot(R, V); + float mid = 1.0 - roughness; + mid *= mid; + specular_brdf_NL = smoothstep(mid - roughness * 0.5, mid + roughness * 0.5, RdotV) * mid; + +#elif defined(SPECULAR_DISABLED) + // none.. +#elif defined(SPECULAR_SCHLICK_GGX) + // shlick+ggx as default + +#if defined(LIGHT_USE_ANISOTROPY) + float alpha_ggx = roughness * roughness; + float aspect = sqrt(1.0 - anisotropy * 0.9); + float ax = alpha_ggx / aspect; + float ay = alpha_ggx * aspect; + float XdotH = dot(T, H); + float YdotH = dot(B, H); + float D = D_GGX_anisotropic(cNdotH, ax, ay, XdotH, YdotH, cNdotH); + //float G = G_GGX_anisotropic_2cos(cNdotL, ax, ay, XdotH, YdotH) * G_GGX_anisotropic_2cos(cNdotV, ax, ay, XdotH, YdotH); + float G = V_GGX_anisotropic(ax, ay, dot(T, V), dot(T, L), dot(B, V), dot(B, L), cNdotV, cNdotL); + +#else + float alpha_ggx = roughness * roughness; + float D = D_GGX(cNdotH, alpha_ggx); + //float G = G_GGX_2cos(cNdotL, alpha_ggx) * G_GGX_2cos(cNdotV, alpha_ggx); + float G = V_GGX(cNdotL, cNdotV, alpha_ggx); +#endif + // F + vec3 f0 = F0(metallic, specular, diffuse_color); + float cLdotH5 = SchlickFresnel(cLdotH); + vec3 F = mix(vec3(cLdotH5), vec3(1.0), f0); + + specular_brdf_NL = cNdotL * D * F * G; + +#endif + + SRGB_APPROX(specular_brdf_NL) + specular_light += specular_brdf_NL * light_color * specular_blob_intensity * attenuation; + +#if defined(LIGHT_USE_CLEARCOAT) + +#if !defined(SPECULAR_SCHLICK_GGX) + float cLdotH5 = SchlickFresnel(cLdotH); +#endif + float Dr = GTR1(cNdotH, mix(.1, .001, clearcoat_gloss)); + float Fr = mix(.04, 1.0, cLdotH5); + //float Gr = G_GGX_2cos(cNdotL, .25) * G_GGX_2cos(cNdotV, .25); + float Gr = V_GGX(cNdotL, cNdotV, 0.25); + + float clearcoat_specular_brdf_NL = 0.25 * clearcoat * Gr * Fr * Dr * cNdotL; + + specular_light += clearcoat_specular_brdf_NL * light_color * specular_blob_intensity * attenuation; +#endif + } + +#ifdef USE_SHADOW_TO_OPACITY + alpha = min(alpha, clamp(1.0 - length(attenuation), 0.0, 1.0)); +#endif + +#endif //defined(USE_LIGHT_SHADER_CODE) +} + +#endif +// shadows + +#ifdef USE_SHADOW + +#ifdef USE_RGBA_SHADOWS + +#define SHADOW_DEPTH(m_val) dot(m_val, vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0)) + +#else + +#define SHADOW_DEPTH(m_val) (m_val).r + +#endif + +#define SAMPLE_SHADOW_TEXEL(p_shadow, p_pos, p_depth) step(p_depth, SHADOW_DEPTH(texture2D(p_shadow, p_pos))) +#define SAMPLE_SHADOW_TEXEL_PROJ(p_shadow, p_pos) step(p_pos.z, SHADOW_DEPTH(texture2DProj(p_shadow, p_pos))) + +float sample_shadow(highp sampler2D shadow, highp vec4 spos) { +#ifdef SHADOW_MODE_PCF_13 + + spos.xyz /= spos.w; + vec2 pos = spos.xy; + float depth = spos.z; + + float avg = SAMPLE_SHADOW_TEXEL(shadow, pos, depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(shadow_pixel_size.x, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(-shadow_pixel_size.x, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, -shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(shadow_pixel_size.x, shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(-shadow_pixel_size.x, shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(shadow_pixel_size.x, -shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(-shadow_pixel_size.x, -shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(shadow_pixel_size.x * 2.0, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(-shadow_pixel_size.x * 2.0, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, shadow_pixel_size.y * 2.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, -shadow_pixel_size.y * 2.0), depth); + return avg * (1.0 / 13.0); +#endif + +#ifdef SHADOW_MODE_PCF_5 + + spos.xyz /= spos.w; + vec2 pos = spos.xy; + float depth = spos.z; + + float avg = SAMPLE_SHADOW_TEXEL(shadow, pos, depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(shadow_pixel_size.x, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(-shadow_pixel_size.x, 0.0), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, shadow_pixel_size.y), depth); + avg += SAMPLE_SHADOW_TEXEL(shadow, pos + vec2(0.0, -shadow_pixel_size.y), depth); + return avg * (1.0 / 5.0); + +#endif + +#if !defined(SHADOW_MODE_PCF_5) || !defined(SHADOW_MODE_PCF_13) + + return SAMPLE_SHADOW_TEXEL_PROJ(shadow, spos); +#endif +} + +#endif + +#if defined(FOG_DEPTH_ENABLED) || defined(FOG_HEIGHT_ENABLED) + +#if defined(USE_VERTEX_LIGHTING) + +varying vec4 fog_interp; + +#else +uniform mediump vec4 fog_color_base; +#ifdef LIGHT_MODE_DIRECTIONAL +uniform mediump vec4 fog_sun_color_amount; +#endif + +uniform bool fog_transmit_enabled; +uniform mediump float fog_transmit_curve; + +#ifdef FOG_DEPTH_ENABLED +uniform highp float fog_depth_begin; +uniform mediump float fog_depth_curve; +uniform mediump float fog_max_distance; +#endif + +#ifdef FOG_HEIGHT_ENABLED +uniform highp float fog_height_min; +uniform highp float fog_height_max; +uniform mediump float fog_height_curve; +#endif + +#endif //vertex lit +#endif //fog + +void main() { +#ifdef RENDER_DEPTH_DUAL_PARABOLOID + + if (dp_clip > 0.0) + discard; +#endif + highp vec3 vertex = vertex_interp; + vec3 view = -normalize(vertex_interp); + vec3 albedo = vec3(1.0); + vec3 transmission = vec3(0.0); + float metallic = 0.0; + float specular = 0.5; + vec3 emission = vec3(0.0); + float roughness = 1.0; + float rim = 0.0; + float rim_tint = 0.0; + float clearcoat = 0.0; + float clearcoat_gloss = 0.0; + float anisotropy = 0.0; + vec2 anisotropy_flow = vec2(1.0, 0.0); + float sss_strength = 0.0; //unused + // gl_FragDepth is not available in GLES2, so writing to DEPTH is not converted to gl_FragDepth by Godot compiler resulting in a + // compile error because DEPTH is not a variable. + float m_DEPTH = 0.0; + + float alpha = 1.0; + float side = 1.0; + + float specular_blob_intensity = 1.0; +#if defined(SPECULAR_TOON) + specular_blob_intensity *= specular * 2.0; +#endif + +#if defined(ENABLE_AO) + float ao = 1.0; + float ao_light_affect = 0.0; +#endif + +#if defined(ENABLE_TANGENT_INTERP) || defined(ENABLE_NORMALMAP) + vec3 binormal = normalize(binormal_interp) * side; + vec3 tangent = normalize(tangent_interp) * side; +#else + vec3 binormal = vec3(0.0); + vec3 tangent = vec3(0.0); +#endif + vec3 normal = normalize(normal_interp) * side; + +#if defined(ENABLE_NORMALMAP) + vec3 normalmap = vec3(0.5); +#endif + float normaldepth = 1.0; + +#if defined(ALPHA_SCISSOR_USED) + float alpha_scissor = 0.5; +#endif + +#if defined(SCREEN_UV_USED) + vec2 screen_uv = gl_FragCoord.xy * screen_pixel_size; +#endif + + { + /* clang-format off */ + +FRAGMENT_SHADER_CODE + + /* clang-format on */ + } + +#if defined(ENABLE_NORMALMAP) + normalmap.xy = normalmap.xy * 2.0 - 1.0; + normalmap.z = sqrt(max(0.0, 1.0 - dot(normalmap.xy, normalmap.xy))); + + normal = normalize(mix(normal_interp, tangent * normalmap.x + binormal * normalmap.y + normal * normalmap.z, normaldepth)) * side; + //normal = normalmap; +#endif + + normal = normalize(normal); + + vec3 N = normal; + + vec3 specular_light = vec3(0.0, 0.0, 0.0); + vec3 diffuse_light = vec3(0.0, 0.0, 0.0); + vec3 ambient_light = vec3(0.0, 0.0, 0.0); + + vec3 eye_position = view; + +#if !defined(USE_SHADOW_TO_OPACITY) + +#if defined(ALPHA_SCISSOR_USED) + if (alpha < alpha_scissor) { + discard; + } +#endif // ALPHA_SCISSOR_USED + +#ifdef USE_DEPTH_PREPASS + if (alpha < 0.1) { + discard; + } +#endif // USE_DEPTH_PREPASS + +#endif // !USE_SHADOW_TO_OPACITY + +#ifdef BASE_PASS + + // IBL precalculations + float ndotv = clamp(dot(normal, eye_position), 0.0, 1.0); + vec3 f0 = F0(metallic, specular, albedo); + vec3 F = f0 + (max(vec3(1.0 - roughness), f0) - f0) * pow(1.0 - ndotv, 5.0); + +#ifdef AMBIENT_LIGHT_DISABLED + ambient_light = vec3(0.0, 0.0, 0.0); +#else + +#ifdef USE_RADIANCE_MAP + + vec3 ref_vec = reflect(-eye_position, N); + ref_vec = normalize((radiance_inverse_xform * vec4(ref_vec, 0.0)).xyz); + + ref_vec.z *= -1.0; + + specular_light = textureCubeLod(radiance_map, ref_vec, roughness * RADIANCE_MAX_LOD).xyz * bg_energy; +#ifndef USE_LIGHTMAP + { + vec3 ambient_dir = normalize((radiance_inverse_xform * vec4(normal, 0.0)).xyz); + vec3 env_ambient = textureCubeLod(radiance_map, ambient_dir, 4.0).xyz * bg_energy; + env_ambient *= 1.0 - F; + + ambient_light = mix(ambient_color.rgb, env_ambient, ambient_sky_contribution); + } +#endif + +#else + + ambient_light = ambient_color.rgb; + specular_light = bg_color.rgb * bg_energy; + +#endif +#endif // AMBIENT_LIGHT_DISABLED + ambient_light *= ambient_energy; + +#if defined(USE_REFLECTION_PROBE1) || defined(USE_REFLECTION_PROBE2) + + vec4 ambient_accum = vec4(0.0); + vec4 reflection_accum = vec4(0.0); + +#ifdef USE_REFLECTION_PROBE1 + + reflection_process(reflection_probe1, +#ifdef USE_VERTEX_LIGHTING + refprobe1_reflection_normal_blend.rgb, +#ifndef USE_LIGHTMAP + refprobe1_ambient_normal, +#endif + refprobe1_reflection_normal_blend.a, +#else + normal_interp, vertex_interp, refprobe1_local_matrix, + refprobe1_use_box_project, refprobe1_box_extents, refprobe1_box_offset, +#endif + refprobe1_exterior, refprobe1_intensity, refprobe1_ambient, roughness, + ambient_light, specular_light, reflection_accum, ambient_accum); + +#endif // USE_REFLECTION_PROBE1 + +#ifdef USE_REFLECTION_PROBE2 + + reflection_process(reflection_probe2, +#ifdef USE_VERTEX_LIGHTING + refprobe2_reflection_normal_blend.rgb, +#ifndef USE_LIGHTMAP + refprobe2_ambient_normal, +#endif + refprobe2_reflection_normal_blend.a, +#else + normal_interp, vertex_interp, refprobe2_local_matrix, + refprobe2_use_box_project, refprobe2_box_extents, refprobe2_box_offset, +#endif + refprobe2_exterior, refprobe2_intensity, refprobe2_ambient, roughness, + ambient_light, specular_light, reflection_accum, ambient_accum); + +#endif // USE_REFLECTION_PROBE2 + + if (reflection_accum.a > 0.0) { + specular_light = reflection_accum.rgb / reflection_accum.a; + } + +#ifndef USE_LIGHTMAP + if (ambient_accum.a > 0.0) { + ambient_light = ambient_accum.rgb / ambient_accum.a; + } +#endif + +#endif // defined(USE_REFLECTION_PROBE1) || defined(USE_REFLECTION_PROBE2) + + // environment BRDF approximation + { +#if defined(DIFFUSE_TOON) + //simplify for toon, as + specular_light *= specular * metallic * albedo * 2.0; +#else + + // scales the specular reflections, needs to be be computed before lighting happens, + // but after environment and reflection probes are added + //TODO: this curve is not really designed for gammaspace, should be adjusted + const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04); + vec4 r = roughness * c0 + c1; + float a004 = min(r.x * r.x, exp2(-9.28 * ndotv)) * r.x + r.y; + vec2 env = vec2(-1.04, 1.04) * a004 + r.zw; + specular_light *= env.x * F + env.y; + +#endif + } + +#ifdef USE_LIGHTMAP + //ambient light will come entirely from lightmap is lightmap is used + ambient_light = texture2D(lightmap, uv2_interp).rgb * lightmap_energy; +#endif + +#ifdef USE_LIGHTMAP_CAPTURE + { + vec3 cone_dirs[12]; + cone_dirs[0] = vec3(0.0, 0.0, 1.0); + cone_dirs[1] = vec3(0.866025, 0.0, 0.5); + cone_dirs[2] = vec3(0.267617, 0.823639, 0.5); + cone_dirs[3] = vec3(-0.700629, 0.509037, 0.5); + cone_dirs[4] = vec3(-0.700629, -0.509037, 0.5); + cone_dirs[5] = vec3(0.267617, -0.823639, 0.5); + cone_dirs[6] = vec3(0.0, 0.0, -1.0); + cone_dirs[7] = vec3(0.866025, 0.0, -0.5); + cone_dirs[8] = vec3(0.267617, 0.823639, -0.5); + cone_dirs[9] = vec3(-0.700629, 0.509037, -0.5); + cone_dirs[10] = vec3(-0.700629, -0.509037, -0.5); + cone_dirs[11] = vec3(0.267617, -0.823639, -0.5); + + vec3 local_normal = normalize(camera_matrix * vec4(normal, 0.0)).xyz; + vec4 captured = vec4(0.0); + float sum = 0.0; + for (int i = 0; i < 12; i++) { + float amount = max(0.0, dot(local_normal, cone_dirs[i])); //not correct, but creates a nice wrap around effect + captured += lightmap_captures[i] * amount; + sum += amount; + } + + captured /= sum; + + if (lightmap_capture_sky) { + ambient_light = mix(ambient_light, captured.rgb, captured.a); + } else { + ambient_light = captured.rgb; + } + } +#endif + +#endif //BASE PASS + +// +// Lighting +// +#ifdef USE_LIGHTING + +#ifndef USE_VERTEX_LIGHTING + vec3 L; +#endif + vec3 light_att = vec3(1.0); + +#ifdef LIGHT_MODE_OMNI + +#ifndef USE_VERTEX_LIGHTING + vec3 light_vec = light_position - vertex; + float light_length = length(light_vec); + + float normalized_distance = light_length / light_range; + if (normalized_distance < 1.0) { + float omni_attenuation = pow(1.0 - normalized_distance, light_attenuation); + + light_att = vec3(omni_attenuation); + } else { + light_att = vec3(0.0); + } + L = normalize(light_vec); + +#endif + +#if !defined(SHADOWS_DISABLED) + +#ifdef USE_SHADOW + { + highp vec4 splane = shadow_coord; + float shadow_len = length(splane.xyz); + + splane.xyz = normalize(splane.xyz); + + vec4 clamp_rect = light_clamp; + + if (splane.z >= 0.0) { + splane.z += 1.0; + + clamp_rect.y += clamp_rect.w; + } else { + splane.z = 1.0 - splane.z; + } + + splane.xy /= splane.z; + splane.xy = splane.xy * 0.5 + 0.5; + splane.z = shadow_len / light_range; + + splane.xy = clamp_rect.xy + splane.xy * clamp_rect.zw; + splane.w = 1.0; + + float shadow = sample_shadow(light_shadow_atlas, splane); + + light_att *= mix(shadow_color.rgb, vec3(1.0), shadow); + } +#endif + +#endif //SHADOWS_DISABLED + +#endif //type omni + +#ifdef LIGHT_MODE_DIRECTIONAL + +#ifndef USE_VERTEX_LIGHTING + vec3 light_vec = -light_direction; + L = normalize(light_vec); +#endif + float depth_z = -vertex.z; + +#if !defined(SHADOWS_DISABLED) + +#ifdef USE_SHADOW + +#ifdef USE_VERTEX_LIGHTING + //compute shadows in a mobile friendly way + +#ifdef LIGHT_USE_PSSM4 + //take advantage of prefetch + float shadow1 = sample_shadow(light_directional_shadow, shadow_coord); + float shadow2 = sample_shadow(light_directional_shadow, shadow_coord2); + float shadow3 = sample_shadow(light_directional_shadow, shadow_coord3); + float shadow4 = sample_shadow(light_directional_shadow, shadow_coord4); + + if (depth_z < light_split_offsets.w) { + float pssm_fade = 0.0; + float shadow_att = 1.0; +#ifdef LIGHT_USE_PSSM_BLEND + float shadow_att2 = 1.0; + float pssm_blend = 0.0; + bool use_blend = true; +#endif + if (depth_z < light_split_offsets.y) { + if (depth_z < light_split_offsets.x) { + shadow_att = shadow1; + +#ifdef LIGHT_USE_PSSM_BLEND + shadow_att2 = shadow2; + + pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); +#endif + } else { + shadow_att = shadow2; + +#ifdef LIGHT_USE_PSSM_BLEND + shadow_att2 = shadow3; + + pssm_blend = smoothstep(light_split_offsets.x, light_split_offsets.y, depth_z); +#endif + } + } else { + if (depth_z < light_split_offsets.z) { + shadow_att = shadow3; + +#if defined(LIGHT_USE_PSSM_BLEND) + shadow_att2 = shadow4; + pssm_blend = smoothstep(light_split_offsets.y, light_split_offsets.z, depth_z); +#endif + + } else { + shadow_att = shadow4; + pssm_fade = smoothstep(light_split_offsets.z, light_split_offsets.w, depth_z); + +#if defined(LIGHT_USE_PSSM_BLEND) + use_blend = false; +#endif + } + } +#if defined(LIGHT_USE_PSSM_BLEND) + if (use_blend) { + shadow_att = mix(shadow_att, shadow_att2, pssm_blend); + } +#endif + light_att *= mix(shadow_color.rgb, vec3(1.0), shadow_att); + } + +#endif //LIGHT_USE_PSSM4 + +#ifdef LIGHT_USE_PSSM2 + + //take advantage of prefetch + float shadow1 = sample_shadow(light_directional_shadow, shadow_coord); + float shadow2 = sample_shadow(light_directional_shadow, shadow_coord2); + + if (depth_z < light_split_offsets.y) { + float shadow_att = 1.0; + float pssm_fade = 0.0; + +#ifdef LIGHT_USE_PSSM_BLEND + float shadow_att2 = 1.0; + float pssm_blend = 0.0; + bool use_blend = true; +#endif + if (depth_z < light_split_offsets.x) { + float pssm_fade = 0.0; + shadow_att = shadow1; + +#ifdef LIGHT_USE_PSSM_BLEND + shadow_att2 = shadow2; + pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); +#endif + } else { + shadow_att = shadow2; + pssm_fade = smoothstep(light_split_offsets.x, light_split_offsets.y, depth_z); +#ifdef LIGHT_USE_PSSM_BLEND + use_blend = false; +#endif + } +#ifdef LIGHT_USE_PSSM_BLEND + if (use_blend) { + shadow_att = mix(shadow_att, shadow_att2, pssm_blend); + } +#endif + light_att *= mix(shadow_color.rgb, vec3(1.0), shadow_att); + } + +#endif //LIGHT_USE_PSSM2 + +#if !defined(LIGHT_USE_PSSM4) && !defined(LIGHT_USE_PSSM2) + + light_att *= mix(shadow_color.rgb, vec3(1.0), sample_shadow(light_directional_shadow, shadow_coord)); +#endif //orthogonal + +#else //fragment version of pssm + + { +#ifdef LIGHT_USE_PSSM4 + if (depth_z < light_split_offsets.w) { +#elif defined(LIGHT_USE_PSSM2) + if (depth_z < light_split_offsets.y) { +#else + if (depth_z < light_split_offsets.x) { +#endif //pssm2 + + highp vec4 pssm_coord; + float pssm_fade = 0.0; + +#ifdef LIGHT_USE_PSSM_BLEND + float pssm_blend; + highp vec4 pssm_coord2; + bool use_blend = true; +#endif + +#ifdef LIGHT_USE_PSSM4 + + if (depth_z < light_split_offsets.y) { + if (depth_z < light_split_offsets.x) { + pssm_coord = shadow_coord; + +#ifdef LIGHT_USE_PSSM_BLEND + pssm_coord2 = shadow_coord2; + + pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); +#endif + } else { + pssm_coord = shadow_coord2; + +#ifdef LIGHT_USE_PSSM_BLEND + pssm_coord2 = shadow_coord3; + + pssm_blend = smoothstep(light_split_offsets.x, light_split_offsets.y, depth_z); +#endif + } + } else { + if (depth_z < light_split_offsets.z) { + pssm_coord = shadow_coord3; + +#if defined(LIGHT_USE_PSSM_BLEND) + pssm_coord2 = shadow_coord4; + pssm_blend = smoothstep(light_split_offsets.y, light_split_offsets.z, depth_z); +#endif + + } else { + pssm_coord = shadow_coord4; + pssm_fade = smoothstep(light_split_offsets.z, light_split_offsets.w, depth_z); + +#if defined(LIGHT_USE_PSSM_BLEND) + use_blend = false; +#endif + } + } + +#endif // LIGHT_USE_PSSM4 + +#ifdef LIGHT_USE_PSSM2 + if (depth_z < light_split_offsets.x) { + pssm_coord = shadow_coord; + +#ifdef LIGHT_USE_PSSM_BLEND + pssm_coord2 = shadow_coord2; + pssm_blend = smoothstep(0.0, light_split_offsets.x, depth_z); +#endif + } else { + pssm_coord = shadow_coord2; + pssm_fade = smoothstep(light_split_offsets.x, light_split_offsets.y, depth_z); +#ifdef LIGHT_USE_PSSM_BLEND + use_blend = false; +#endif + } + +#endif // LIGHT_USE_PSSM2 + +#if !defined(LIGHT_USE_PSSM4) && !defined(LIGHT_USE_PSSM2) + { + pssm_coord = shadow_coord; + } +#endif + + float shadow = sample_shadow(light_directional_shadow, pssm_coord); + +#ifdef LIGHT_USE_PSSM_BLEND + if (use_blend) { + shadow = mix(shadow, sample_shadow(light_directional_shadow, pssm_coord2), pssm_blend); + } +#endif + + light_att *= mix(shadow_color.rgb, vec3(1.0), shadow); + } + } +#endif //use vertex lighting + +#endif //use shadow + +#endif // SHADOWS_DISABLED + +#endif + +#ifdef LIGHT_MODE_SPOT + + light_att = vec3(1.0); + +#ifndef USE_VERTEX_LIGHTING + + vec3 light_rel_vec = light_position - vertex; + float light_length = length(light_rel_vec); + float normalized_distance = light_length / light_range; + + if (normalized_distance < 1.0) { + float spot_attenuation = pow(1.0 - normalized_distance, light_attenuation); + vec3 spot_dir = light_direction; + + float spot_cutoff = light_spot_angle; + float angle = dot(-normalize(light_rel_vec), spot_dir); + + if (angle > spot_cutoff) { + float scos = max(angle, spot_cutoff); + float spot_rim = max(0.0001, (1.0 - scos) / (1.0 - spot_cutoff)); + spot_attenuation *= 1.0 - pow(spot_rim, light_spot_attenuation); + + light_att = vec3(spot_attenuation); + } else { + light_att = vec3(0.0); + } + } else { + light_att = vec3(0.0); + } + + L = normalize(light_rel_vec); + +#endif + +#if !defined(SHADOWS_DISABLED) + +#ifdef USE_SHADOW + { + highp vec4 splane = shadow_coord; + + float shadow = sample_shadow(light_shadow_atlas, splane); + light_att *= mix(shadow_color.rgb, vec3(1.0), shadow); + } +#endif + +#endif // SHADOWS_DISABLED + +#endif // LIGHT_MODE_SPOT + +#ifdef USE_VERTEX_LIGHTING + //vertex lighting + + specular_light += specular_interp * specular_blob_intensity * light_att; + diffuse_light += diffuse_interp * albedo * light_att; + +#else + //fragment lighting + light_compute( + normal, + L, + eye_position, + binormal, + tangent, + light_color.xyz, + light_att, + albedo, + transmission, + specular_blob_intensity * light_specular, + roughness, + metallic, + specular, + rim, + rim_tint, + clearcoat, + clearcoat_gloss, + anisotropy, + diffuse_light, + specular_light, + alpha); + +#endif //vertex lighting + +#endif //USE_LIGHTING + //compute and merge + +#ifdef USE_SHADOW_TO_OPACITY + + alpha = min(alpha, clamp(length(ambient_light), 0.0, 1.0)); + +#if defined(ALPHA_SCISSOR_USED) + if (alpha < alpha_scissor) { + discard; + } +#endif // ALPHA_SCISSOR_USED + +#ifdef USE_DEPTH_PREPASS + if (alpha < 0.1) { + discard; + } +#endif // USE_DEPTH_PREPASS + +#endif // !USE_SHADOW_TO_OPACITY + +#ifndef RENDER_DEPTH + +#ifdef SHADELESS + + gl_FragColor = vec4(albedo, alpha); +#else + + ambient_light *= albedo; + +#if defined(ENABLE_AO) + ambient_light *= ao; + ao_light_affect = mix(1.0, ao, ao_light_affect); + specular_light *= ao_light_affect; + diffuse_light *= ao_light_affect; +#endif + + diffuse_light *= 1.0 - metallic; + ambient_light *= 1.0 - metallic; + + gl_FragColor = vec4(ambient_light + diffuse_light + specular_light, alpha); + + //add emission if in base pass +#ifdef BASE_PASS + gl_FragColor.rgb += emission; +#endif + // gl_FragColor = vec4(normal, 1.0); + +//apply fog +#if defined(FOG_DEPTH_ENABLED) || defined(FOG_HEIGHT_ENABLED) + +#if defined(USE_VERTEX_LIGHTING) + +#if defined(BASE_PASS) + gl_FragColor.rgb = mix(gl_FragColor.rgb, fog_interp.rgb, fog_interp.a); +#else + gl_FragColor.rgb *= (1.0 - fog_interp.a); +#endif // BASE_PASS + +#else //pixel based fog + float fog_amount = 0.0; + +#ifdef LIGHT_MODE_DIRECTIONAL + + vec3 fog_color = mix(fog_color_base.rgb, fog_sun_color_amount.rgb, fog_sun_color_amount.a * pow(max(dot(eye_position, light_direction), 0.0), 8.0)); +#else + vec3 fog_color = fog_color_base.rgb; +#endif + +#ifdef FOG_DEPTH_ENABLED + + { + float fog_z = smoothstep(fog_depth_begin, fog_max_distance, length(vertex)); + + fog_amount = pow(fog_z, fog_depth_curve) * fog_color_base.a; + + if (fog_transmit_enabled) { + vec3 total_light = gl_FragColor.rgb; + float transmit = pow(fog_z, fog_transmit_curve); + fog_color = mix(max(total_light, fog_color), fog_color, transmit); + } + } +#endif + +#ifdef FOG_HEIGHT_ENABLED + { + float y = (camera_matrix * vec4(vertex, 1.0)).y; + fog_amount = max(fog_amount, pow(smoothstep(fog_height_min, fog_height_max, y), fog_height_curve)); + } +#endif + +#if defined(BASE_PASS) + gl_FragColor.rgb = mix(gl_FragColor.rgb, fog_color, fog_amount); +#else + gl_FragColor.rgb *= (1.0 - fog_amount); +#endif // BASE_PASS + +#endif //use vertex lit + +#endif // defined(FOG_DEPTH_ENABLED) || defined(FOG_HEIGHT_ENABLED) + +#endif //unshaded + +#else // not RENDER_DEPTH +//depth render +#ifdef USE_RGBA_SHADOWS + + highp float depth = ((position_interp.z / position_interp.w) + 1.0) * 0.5 + 0.0; // bias + highp vec4 comp = fract(depth * vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0)); + comp -= comp.xxyz * vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0); + gl_FragColor = comp; + +#endif +#endif +} diff --git a/drivers/gles2/shaders/screen_space_reflection.glsl b/drivers/gles2/shaders/screen_space_reflection.glsl new file mode 100644 index 00000000000..6b5b7c885ca --- /dev/null +++ b/drivers/gles2/shaders/screen_space_reflection.glsl @@ -0,0 +1,284 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ +layout(location = 4) in vec2 uv_in; + +out vec2 uv_interp; +out vec2 pos_interp; + +void main() { + uv_interp = uv_in; + gl_Position = vertex_attrib; + pos_interp.xy = gl_Position.xy; +} + +/* clang-format off */ +[fragment] + +in vec2 uv_interp; +/* clang-format on */ +in vec2 pos_interp; + +uniform sampler2D source_diffuse; //texunit:0 +uniform sampler2D source_normal_roughness; //texunit:1 +uniform sampler2D source_depth; //texunit:2 + +uniform float camera_z_near; +uniform float camera_z_far; + +uniform vec2 viewport_size; +uniform vec2 pixel_size; + +uniform float filter_mipmap_levels; + +uniform mat4 inverse_projection; +uniform mat4 projection; + +uniform int num_steps; +uniform float depth_tolerance; +uniform float distance_fade; +uniform float curve_fade_in; + +layout(location = 0) out vec4 frag_color; + +vec2 view_to_screen(vec3 view_pos, out float w) { + vec4 projected = projection * vec4(view_pos, 1.0); + projected.xyz /= projected.w; + projected.xy = projected.xy * 0.5 + 0.5; + w = projected.w; + return projected.xy; +} + +#define M_PI 3.14159265359 + +void main() { + vec4 diffuse = texture(source_diffuse, uv_interp); + vec4 normal_roughness = texture(source_normal_roughness, uv_interp); + + vec3 normal; + + normal = normal_roughness.xyz * 2.0 - 1.0; + + float roughness = normal_roughness.w; + + float depth_tex = texture(source_depth, uv_interp).r; + + vec4 world_pos = inverse_projection * vec4(uv_interp * 2.0 - 1.0, depth_tex * 2.0 - 1.0, 1.0); + vec3 vertex = world_pos.xyz / world_pos.w; + + vec3 view_dir = normalize(vertex); + vec3 ray_dir = normalize(reflect(view_dir, normal)); + + if (dot(ray_dir, normal) < 0.001) { + frag_color = vec4(0.0); + return; + } + //ray_dir = normalize(view_dir - normal * dot(normal,view_dir) * 2.0); + + //ray_dir = normalize(vec3(1,1,-1)); + + //////////////// + + //make ray length and clip it against the near plane (don't want to trace beyond visible) + float ray_len = (vertex.z + ray_dir.z * camera_z_far) > -camera_z_near ? (-camera_z_near - vertex.z) / ray_dir.z : camera_z_far; + vec3 ray_end = vertex + ray_dir * ray_len; + + float w_begin; + vec2 vp_line_begin = view_to_screen(vertex, w_begin); + float w_end; + vec2 vp_line_end = view_to_screen(ray_end, w_end); + vec2 vp_line_dir = vp_line_end - vp_line_begin; + + //we need to interpolate w along the ray, to generate perspective correct reflections + + w_begin = 1.0 / w_begin; + w_end = 1.0 / w_end; + + float z_begin = vertex.z * w_begin; + float z_end = ray_end.z * w_end; + + vec2 line_begin = vp_line_begin / pixel_size; + vec2 line_dir = vp_line_dir / pixel_size; + float z_dir = z_end - z_begin; + float w_dir = w_end - w_begin; + + // clip the line to the viewport edges + + float scale_max_x = min(1.0, 0.99 * (1.0 - vp_line_begin.x) / max(1e-5, vp_line_dir.x)); + float scale_max_y = min(1.0, 0.99 * (1.0 - vp_line_begin.y) / max(1e-5, vp_line_dir.y)); + float scale_min_x = min(1.0, 0.99 * vp_line_begin.x / max(1e-5, -vp_line_dir.x)); + float scale_min_y = min(1.0, 0.99 * vp_line_begin.y / max(1e-5, -vp_line_dir.y)); + float line_clip = min(scale_max_x, scale_max_y) * min(scale_min_x, scale_min_y); + line_dir *= line_clip; + z_dir *= line_clip; + w_dir *= line_clip; + + //clip z and w advance to line advance + vec2 line_advance = normalize(line_dir); //down to pixel + float step_size = length(line_advance) / length(line_dir); + float z_advance = z_dir * step_size; // adapt z advance to line advance + float w_advance = w_dir * step_size; // adapt w advance to line advance + + //make line advance faster if direction is closer to pixel edges (this avoids sampling the same pixel twice) + float advance_angle_adj = 1.0 / max(abs(line_advance.x), abs(line_advance.y)); + line_advance *= advance_angle_adj; // adapt z advance to line advance + z_advance *= advance_angle_adj; + w_advance *= advance_angle_adj; + + vec2 pos = line_begin; + float z = z_begin; + float w = w_begin; + float z_from = z / w; + float z_to = z_from; + float depth; + vec2 prev_pos = pos; + + bool found = false; + + float steps_taken = 0.0; + + for (int i = 0; i < num_steps; i++) { + pos += line_advance; + z += z_advance; + w += w_advance; + + //convert to linear depth + + depth = texture(source_depth, pos * pixel_size).r * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + depth = ((depth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - depth * (camera_z_far - camera_z_near)); +#endif + depth = -depth; + + z_from = z_to; + z_to = z / w; + + if (depth > z_to) { + //if depth was surpassed + if (depth <= max(z_to, z_from) + depth_tolerance) { + //check the depth tolerance + found = true; + } + break; + } + + steps_taken += 1.0; + prev_pos = pos; + } + + if (found) { + float margin_blend = 1.0; + + vec2 margin = vec2((viewport_size.x + viewport_size.y) * 0.5 * 0.05); //make a uniform margin + if (any(bvec4(lessThan(pos, -margin), greaterThan(pos, viewport_size + margin)))) { + //clip outside screen + margin + frag_color = vec4(0.0); + return; + } + + { + //blend fading out towards external margin + vec2 margin_grad = mix(pos - viewport_size, -pos, lessThan(pos, vec2(0.0))); + margin_blend = 1.0 - smoothstep(0.0, margin.x, max(margin_grad.x, margin_grad.y)); + //margin_blend=1.0; + } + + vec2 final_pos; + float grad; + grad = steps_taken / float(num_steps); + float initial_fade = curve_fade_in == 0.0 ? 1.0 : pow(clamp(grad, 0.0, 1.0), curve_fade_in); + float fade = pow(clamp(1.0 - grad, 0.0, 1.0), distance_fade) * initial_fade; + final_pos = pos; + +#ifdef REFLECT_ROUGHNESS + + vec4 final_color; + //if roughness is enabled, do screen space cone tracing + if (roughness > 0.001) { + /////////////////////////////////////////////////////////////////////////////////////// + //use a blurred version (in consecutive mipmaps) of the screen to simulate roughness + + float gloss = 1.0 - roughness; + float cone_angle = roughness * M_PI * 0.5; + vec2 cone_dir = final_pos - line_begin; + float cone_len = length(cone_dir); + cone_dir = normalize(cone_dir); //will be used normalized from now on + float max_mipmap = filter_mipmap_levels - 1.0; + float gloss_mult = gloss; + + float rem_alpha = 1.0; + final_color = vec4(0.0); + + for (int i = 0; i < 7; i++) { + float op_len = 2.0 * tan(cone_angle) * cone_len; //opposite side of iso triangle + float radius; + { + //fit to sphere inside cone (sphere ends at end of cone), something like this: + // ___ + // \O/ + // V + // + // as it avoids bleeding from beyond the reflection as much as possible. As a plus + // it also makes the rough reflection more elongated. + float a = op_len; + float h = cone_len; + float a2 = a * a; + float fh2 = 4.0f * h * h; + radius = (a * (sqrt(a2 + fh2) - a)) / (4.0f * h); + } + + //find the place where screen must be sampled + vec2 sample_pos = (line_begin + cone_dir * (cone_len - radius)) * pixel_size; + //radius is in pixels, so it's natural that log2(radius) maps to the right mipmap for the amount of pixels + float mipmap = clamp(log2(radius), 0.0, max_mipmap); + + //mipmap = max(mipmap-1.0,0.0); + //do sampling + + vec4 sample_color; + { + sample_color = textureLod(source_diffuse, sample_pos, mipmap); + } + + //multiply by gloss + sample_color.rgb *= gloss_mult; + sample_color.a = gloss_mult; + + rem_alpha -= sample_color.a; + if (rem_alpha < 0.0) { + sample_color.rgb *= (1.0 - abs(rem_alpha)); + } + + final_color += sample_color; + + if (final_color.a >= 0.95) { + // This code of accumulating gloss and aborting on near one + // makes sense when you think of cone tracing. + // Think of it as if roughness was 0, then we could abort on the first + // iteration. For lesser roughness values, we need more iterations, but + // each needs to have less influence given the sphere is smaller + break; + } + + cone_len -= radius * 2.0; //go to next (smaller) circle. + + gloss_mult *= gloss; + } + } else { + final_color = textureLod(source_diffuse, final_pos * pixel_size, 0.0); + } + + frag_color = vec4(final_color.rgb, fade * margin_blend); + +#else + frag_color = vec4(textureLod(source_diffuse, final_pos * pixel_size, 0.0).rgb, fade * margin_blend); +#endif + + } else { + frag_color = vec4(0.0, 0.0, 0.0, 0.0); + } +} diff --git a/drivers/gles2/shaders/ssao.glsl b/drivers/gles2/shaders/ssao.glsl new file mode 100644 index 00000000000..0fd29e8dcce --- /dev/null +++ b/drivers/gles2/shaders/ssao.glsl @@ -0,0 +1,283 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ + +void main() { + gl_Position = vertex_attrib; + gl_Position.z = 1.0; +} + +/* clang-format off */ +[fragment] + +#define TWO_PI 6.283185307179586476925286766559 + +#ifdef SSAO_QUALITY_HIGH + +#define NUM_SAMPLES (80) + +#endif + +#ifdef SSAO_QUALITY_LOW + +#define NUM_SAMPLES (15) + +#endif + +#if !defined(SSAO_QUALITY_LOW) && !defined(SSAO_QUALITY_HIGH) + +#define NUM_SAMPLES (40) + +#endif + +// If using depth mip levels, the log of the maximum pixel offset before we need to switch to a lower +// miplevel to maintain reasonable spatial locality in the cache +// If this number is too small (< 3), too many taps will land in the same pixel, and we'll get bad variance that manifests as flashing. +// If it is too high (> 5), we'll get bad performance because we're not using the MIP levels effectively +#define LOG_MAX_OFFSET (3) + +// This must be less than or equal to the MAX_MIP_LEVEL defined in SSAO.cpp +#define MAX_MIP_LEVEL (4) + +// This is the number of turns around the circle that the spiral pattern makes. This should be prime to prevent +// taps from lining up. This particular choice was tuned for NUM_SAMPLES == 9 + +const int ROTATIONS[] = int[]( + 1, 1, 2, 3, 2, 5, 2, 3, 2, + 3, 3, 5, 5, 3, 4, 7, 5, 5, 7, + 9, 8, 5, 5, 7, 7, 7, 8, 5, 8, + 11, 12, 7, 10, 13, 8, 11, 8, 7, 14, + 11, 11, 13, 12, 13, 19, 17, 13, 11, 18, + 19, 11, 11, 14, 17, 21, 15, 16, 17, 18, + 13, 17, 11, 17, 19, 18, 25, 18, 19, 19, + 29, 21, 19, 27, 31, 29, 21, 18, 17, 29, + 31, 31, 23, 18, 25, 26, 25, 23, 19, 34, + 19, 27, 21, 25, 39, 29, 17, 21, 27); +/* clang-format on */ + +//#define NUM_SPIRAL_TURNS (7) +const int NUM_SPIRAL_TURNS = ROTATIONS[NUM_SAMPLES - 1]; + +uniform sampler2D source_depth; //texunit:0 +uniform highp usampler2D source_depth_mipmaps; //texunit:1 +uniform sampler2D source_normal; //texunit:2 + +uniform ivec2 screen_size; +uniform float camera_z_far; +uniform float camera_z_near; + +uniform float intensity_div_r6; +uniform float radius; + +#ifdef ENABLE_RADIUS2 +uniform float intensity_div_r62; +uniform float radius2; +#endif + +uniform float bias; +uniform float proj_scale; + +layout(location = 0) out float visibility; + +uniform vec4 proj_info; + +vec3 reconstructCSPosition(vec2 S, float z) { +#ifdef USE_ORTHOGONAL_PROJECTION + return vec3((S.xy * proj_info.xy + proj_info.zw), z); +#else + return vec3((S.xy * proj_info.xy + proj_info.zw) * z, z); + +#endif +} + +vec3 getPosition(ivec2 ssP) { + vec3 P; + P.z = texelFetch(source_depth, ssP, 0).r; + + P.z = P.z * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + P.z = ((P.z + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + P.z = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - P.z * (camera_z_far - camera_z_near)); +#endif + P.z = -P.z; + + // Offset to pixel center + P = reconstructCSPosition(vec2(ssP) + vec2(0.5), P.z); + return P; +} + +/** Reconstructs screen-space unit normal from screen-space position */ +vec3 reconstructCSFaceNormal(vec3 C) { + return normalize(cross(dFdy(C), dFdx(C))); +} + +/** Returns a unit vector and a screen-space radius for the tap on a unit disk (the caller should scale by the actual disk radius) */ +vec2 tapLocation(int sampleNumber, float spinAngle, out float ssR) { + // Radius relative to ssR + float alpha = (float(sampleNumber) + 0.5) * (1.0 / float(NUM_SAMPLES)); + float angle = alpha * (float(NUM_SPIRAL_TURNS) * 6.28) + spinAngle; + + ssR = alpha; + return vec2(cos(angle), sin(angle)); +} + +/** Read the camera-space position of the point at screen-space pixel ssP + unitOffset * ssR. Assumes length(unitOffset) == 1 */ +vec3 getOffsetPosition(ivec2 ssC, vec2 unitOffset, float ssR) { + // Derivation: + // mipLevel = floor(log(ssR / MAX_OFFSET)); + int mipLevel = clamp(int(floor(log2(ssR))) - LOG_MAX_OFFSET, 0, MAX_MIP_LEVEL); + + ivec2 ssP = ivec2(ssR * unitOffset) + ssC; + + vec3 P; + + // We need to divide by 2^mipLevel to read the appropriately scaled coordinate from a MIP-map. + // Manually clamp to the texture size because texelFetch bypasses the texture unit + ivec2 mipP = clamp(ssP >> mipLevel, ivec2(0), (screen_size >> mipLevel) - ivec2(1)); + + if (mipLevel < 1) { + //read from depth buffer + P.z = texelFetch(source_depth, mipP, 0).r; + P.z = P.z * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + P.z = ((P.z + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + P.z = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - P.z * (camera_z_far - camera_z_near)); + +#endif + P.z = -P.z; + + } else { + //read from mipmaps + uint d = texelFetch(source_depth_mipmaps, mipP, mipLevel - 1).r; + P.z = -(float(d) / 65535.0) * camera_z_far; + } + + // Offset to pixel center + P = reconstructCSPosition(vec2(ssP) + vec2(0.5), P.z); + + return P; +} + +/** Compute the occlusion due to sample with index \a i about the pixel at \a ssC that corresponds + to camera-space point \a C with unit normal \a n_C, using maximum screen-space sampling radius \a ssDiskRadius + + Note that units of H() in the HPG12 paper are meters, not + unitless. The whole falloff/sampling function is therefore + unitless. In this implementation, we factor out (9 / radius). + + Four versions of the falloff function are implemented below +*/ +float sampleAO(in ivec2 ssC, in vec3 C, in vec3 n_C, in float ssDiskRadius, in float p_radius, in int tapIndex, in float randomPatternRotationAngle) { + // Offset on the unit disk, spun for this pixel + float ssR; + vec2 unitOffset = tapLocation(tapIndex, randomPatternRotationAngle, ssR); + ssR *= ssDiskRadius; + + // The occluding point in camera space + vec3 Q = getOffsetPosition(ssC, unitOffset, ssR); + + vec3 v = Q - C; + + float vv = dot(v, v); + float vn = dot(v, n_C); + + const float epsilon = 0.01; + float radius2 = p_radius * p_radius; + + // A: From the HPG12 paper + // Note large epsilon to avoid overdarkening within cracks + //return float(vv < radius2) * max((vn - bias) / (epsilon + vv), 0.0) * radius2 * 0.6; + + // B: Smoother transition to zero (lowers contrast, smoothing out corners). [Recommended] + float f = max(radius2 - vv, 0.0); + return f * f * f * max((vn - bias) / (epsilon + vv), 0.0); + + // C: Medium contrast (which looks better at high radii), no division. Note that the + // contribution still falls off with radius^2, but we've adjusted the rate in a way that is + // more computationally efficient and happens to be aesthetically pleasing. + // return 4.0 * max(1.0 - vv * invRadius2, 0.0) * max(vn - bias, 0.0); + + // D: Low contrast, no division operation + // return 2.0 * float(vv < radius * radius) * max(vn - bias, 0.0); +} + +void main() { + // Pixel being shaded + ivec2 ssC = ivec2(gl_FragCoord.xy); + + // World space point being shaded + vec3 C = getPosition(ssC); + + /* + if (C.z <= -camera_z_far*0.999) { + // We're on the skybox + visibility=1.0; + return; + } + */ + + //visibility=-C.z/camera_z_far; + //return; +#if 0 + vec3 n_C = texelFetch(source_normal,ssC,0).rgb * 2.0 - 1.0; +#else + vec3 n_C = reconstructCSFaceNormal(C); + n_C = -n_C; +#endif + + // Hash function used in the HPG12 AlchemyAO paper + float randomPatternRotationAngle = mod(float((3 * ssC.x ^ ssC.y + ssC.x * ssC.y) * 10), TWO_PI); + + // Reconstruct normals from positions. These will lead to 1-pixel black lines + // at depth discontinuities, however the blur will wipe those out so they are not visible + // in the final image. + + // Choose the screen-space sample radius + // proportional to the projected area of the sphere +#ifdef USE_ORTHOGONAL_PROJECTION + float ssDiskRadius = -proj_scale * radius; +#else + float ssDiskRadius = -proj_scale * radius / C.z; +#endif + float sum = 0.0; + for (int i = 0; i < NUM_SAMPLES; ++i) { + sum += sampleAO(ssC, C, n_C, ssDiskRadius, radius, i, randomPatternRotationAngle); + } + + float A = max(0.0, 1.0 - sum * intensity_div_r6 * (5.0 / float(NUM_SAMPLES))); + +#ifdef ENABLE_RADIUS2 + + //go again for radius2 + randomPatternRotationAngle = mod(float((5 * ssC.x ^ ssC.y + ssC.x * ssC.y) * 11), TWO_PI); + + // Reconstruct normals from positions. These will lead to 1-pixel black lines + // at depth discontinuities, however the blur will wipe those out so they are not visible + // in the final image. + + // Choose the screen-space sample radius + // proportional to the projected area of the sphere + ssDiskRadius = -proj_scale * radius2 / C.z; + + sum = 0.0; + for (int i = 0; i < NUM_SAMPLES; ++i) { + sum += sampleAO(ssC, C, n_C, ssDiskRadius, radius2, i, randomPatternRotationAngle); + } + + A = min(A, max(0.0, 1.0 - sum * intensity_div_r62 * (5.0 / float(NUM_SAMPLES)))); +#endif + // Bilateral box-filter over a quad for free, respecting depth edges + // (the difference that this makes is subtle) + if (abs(dFdx(C.z)) < 0.02) { + A -= dFdx(A) * (float(ssC.x & 1) - 0.5); + } + if (abs(dFdy(C.z)) < 0.02) { + A -= dFdy(A) * (float(ssC.y & 1) - 0.5); + } + + visibility = A; +} diff --git a/drivers/gles2/shaders/ssao_blur.glsl b/drivers/gles2/shaders/ssao_blur.glsl new file mode 100644 index 00000000000..f065cd74ebf --- /dev/null +++ b/drivers/gles2/shaders/ssao_blur.glsl @@ -0,0 +1,116 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ + +void main() { + gl_Position = vertex_attrib; + gl_Position.z = 1.0; +} + +/* clang-format off */ +[fragment] + +uniform sampler2D source_ssao; //texunit:0 +/* clang-format on */ +uniform sampler2D source_depth; //texunit:1 +uniform sampler2D source_normal; //texunit:3 + +layout(location = 0) out float visibility; + +////////////////////////////////////////////////////////////////////////////////////////////// +// Tunable Parameters: + +/** Increase to make depth edges crisper. Decrease to reduce flicker. */ +uniform float edge_sharpness; + +/** Step in 2-pixel intervals since we already blurred against neighbors in the + first AO pass. This constant can be increased while R decreases to improve + performance at the expense of some dithering artifacts. + + Morgan found that a scale of 3 left a 1-pixel checkerboard grid that was + unobjectionable after shading was applied but eliminated most temporal incoherence + from using small numbers of sample taps. + */ + +uniform int filter_scale; + +/** Filter radius in pixels. This will be multiplied by SCALE. */ +#define R (4) + +////////////////////////////////////////////////////////////////////////////////////////////// + +// Gaussian coefficients +const float gaussian[R + 1] = + //float[](0.356642, 0.239400, 0.072410, 0.009869); + //float[](0.398943, 0.241971, 0.053991, 0.004432, 0.000134); // stddev = 1.0 + float[](0.153170, 0.144893, 0.122649, 0.092902, 0.062970); // stddev = 2.0 +//float[](0.111220, 0.107798, 0.098151, 0.083953, 0.067458, 0.050920, 0.036108); // stddev = 3.0 + +/** (1, 0) or (0, 1)*/ +uniform ivec2 axis; + +uniform float camera_z_far; +uniform float camera_z_near; + +uniform ivec2 screen_size; + +void main() { + ivec2 ssC = ivec2(gl_FragCoord.xy); + + float depth = texelFetch(source_depth, ssC, 0).r; + //vec3 normal = texelFetch(source_normal,ssC,0).rgb * 2.0 - 1.0; + + depth = depth * 2.0 - 1.0; + depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - depth * (camera_z_far - camera_z_near)); + + float depth_divide = 1.0 / camera_z_far; + + //depth *= depth_divide; + + /* + if (depth > camera_z_far * 0.999) { + discard; //skybox + } + */ + + float sum = texelFetch(source_ssao, ssC, 0).r; + + // Base weight for depth falloff. Increase this for more blurriness, + // decrease it for better edge discrimination + float BASE = gaussian[0]; + float totalWeight = BASE; + sum *= totalWeight; + + ivec2 clamp_limit = screen_size - ivec2(1); + + for (int r = -R; r <= R; ++r) { + // We already handled the zero case above. This loop should be unrolled and the static branch optimized out, + // so the IF statement has no runtime cost + if (r != 0) { + ivec2 ppos = ssC + axis * (r * filter_scale); + float value = texelFetch(source_ssao, clamp(ppos, ivec2(0), clamp_limit), 0).r; + ivec2 rpos = clamp(ppos, ivec2(0), clamp_limit); + float temp_depth = texelFetch(source_depth, rpos, 0).r; + //vec3 temp_normal = texelFetch(source_normal, rpos, 0).rgb * 2.0 - 1.0; + + temp_depth = temp_depth * 2.0 - 1.0; + temp_depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - temp_depth * (camera_z_far - camera_z_near)); + // temp_depth *= depth_divide; + + // spatial domain: offset gaussian tap + float weight = 0.3 + gaussian[abs(r)]; + //weight *= max(0.0,dot(temp_normal,normal)); + + // range domain (the "bilateral" weight). As depth difference increases, decrease weight. + weight *= max(0.0, 1.0 - edge_sharpness * abs(temp_depth - depth)); + + sum += value * weight; + totalWeight += weight; + } + } + + const float epsilon = 0.0001; + visibility = sum / (totalWeight + epsilon); +} diff --git a/drivers/gles2/shaders/ssao_minify.glsl b/drivers/gles2/shaders/ssao_minify.glsl new file mode 100644 index 00000000000..f654e00a4fa --- /dev/null +++ b/drivers/gles2/shaders/ssao_minify.glsl @@ -0,0 +1,54 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ + +void main() { + gl_Position = vertex_attrib; +} + +/* clang-format off */ +[fragment] + +#ifdef MINIFY_START + +#define SDEPTH_TYPE highp sampler2D +uniform float camera_z_far; +uniform float camera_z_near; +/* clang-format on */ + +#else + +#define SDEPTH_TYPE mediump usampler2D + +#endif + +uniform SDEPTH_TYPE source_depth; //texunit:0 + +uniform ivec2 from_size; +uniform int source_mipmap; + +layout(location = 0) out mediump uint depth; + +void main() { + ivec2 ssP = ivec2(gl_FragCoord.xy); + + // Rotated grid subsampling to avoid XY directional bias or Z precision bias while downsampling. + // On DX9, the bit-and can be implemented with floating-point modulo + +#ifdef MINIFY_START + float fdepth = texelFetch(source_depth, clamp(ssP * 2 + ivec2(ssP.y & 1, ssP.x & 1), ivec2(0), from_size - ivec2(1)), source_mipmap).r; + fdepth = fdepth * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + fdepth = ((fdepth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + fdepth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - fdepth * (camera_z_far - camera_z_near)); +#endif + fdepth /= camera_z_far; + depth = uint(clamp(fdepth * 65535.0, 0.0, 65535.0)); + +#else + depth = texelFetch(source_depth, clamp(ssP * 2 + ivec2(ssP.y & 1, ssP.x & 1), ivec2(0), from_size - ivec2(1)), source_mipmap).r; +#endif +} diff --git a/drivers/gles2/shaders/stdlib.glsl b/drivers/gles2/shaders/stdlib.glsl new file mode 100644 index 00000000000..9c744187430 --- /dev/null +++ b/drivers/gles2/shaders/stdlib.glsl @@ -0,0 +1,420 @@ + +vec2 select2(vec2 a, vec2 b, bvec2 c) { + vec2 ret; + + ret.x = c.x ? b.x : a.x; + ret.y = c.y ? b.y : a.y; + + return ret; +} + +vec3 select3(vec3 a, vec3 b, bvec3 c) { + vec3 ret; + + ret.x = c.x ? b.x : a.x; + ret.y = c.y ? b.y : a.y; + ret.z = c.z ? b.z : a.z; + + return ret; +} + +vec4 select4(vec4 a, vec4 b, bvec4 c) { + vec4 ret; + + ret.x = c.x ? b.x : a.x; + ret.y = c.y ? b.y : a.y; + ret.z = c.z ? b.z : a.z; + ret.w = c.w ? b.w : a.w; + + return ret; +} + +highp vec4 texel2DFetch(highp sampler2D tex, ivec2 size, ivec2 coord) { + float x_coord = float(2 * coord.x + 1) / float(size.x * 2); + float y_coord = float(2 * coord.y + 1) / float(size.y * 2); + + return texture2DLod(tex, vec2(x_coord, y_coord), 0.0); +} + +#if defined(SINH_USED) + +highp float sinh(highp float x) { + return 0.5 * (exp(x) - exp(-x)); +} + +highp vec2 sinh(highp vec2 x) { + return 0.5 * vec2(exp(x.x) - exp(-x.x), exp(x.y) - exp(-x.y)); +} + +highp vec3 sinh(highp vec3 x) { + return 0.5 * vec3(exp(x.x) - exp(-x.x), exp(x.y) - exp(-x.y), exp(x.z) - exp(-x.z)); +} + +highp vec4 sinh(highp vec4 x) { + return 0.5 * vec4(exp(x.x) - exp(-x.x), exp(x.y) - exp(-x.y), exp(x.z) - exp(-x.z), exp(x.w) - exp(-x.w)); +} + +#endif + +#if defined(COSH_USED) + +highp float cosh(highp float x) { + return 0.5 * (exp(x) + exp(-x)); +} + +highp vec2 cosh(highp vec2 x) { + return 0.5 * vec2(exp(x.x) + exp(-x.x), exp(x.y) + exp(-x.y)); +} + +highp vec3 cosh(highp vec3 x) { + return 0.5 * vec3(exp(x.x) + exp(-x.x), exp(x.y) + exp(-x.y), exp(x.z) + exp(-x.z)); +} + +highp vec4 cosh(highp vec4 x) { + return 0.5 * vec4(exp(x.x) + exp(-x.x), exp(x.y) + exp(-x.y), exp(x.z) + exp(-x.z), exp(x.w) + exp(-x.w)); +} + +#endif + +#if defined(TANH_USED) + +highp float tanh(highp float x) { + highp float exp2x = exp(2.0 * x); + return (exp2x - 1.0) / (exp2x + 1.0); +} + +highp vec2 tanh(highp vec2 x) { + highp float exp2x = exp(2.0 * x.x); + highp float exp2y = exp(2.0 * x.y); + return vec2((exp2x - 1.0) / (exp2x + 1.0), (exp2y - 1.0) / (exp2y + 1.0)); +} + +highp vec3 tanh(highp vec3 x) { + highp float exp2x = exp(2.0 * x.x); + highp float exp2y = exp(2.0 * x.y); + highp float exp2z = exp(2.0 * x.z); + return vec3((exp2x - 1.0) / (exp2x + 1.0), (exp2y - 1.0) / (exp2y + 1.0), (exp2z - 1.0) / (exp2z + 1.0)); +} + +highp vec4 tanh(highp vec4 x) { + highp float exp2x = exp(2.0 * x.x); + highp float exp2y = exp(2.0 * x.y); + highp float exp2z = exp(2.0 * x.z); + highp float exp2w = exp(2.0 * x.w); + return vec4((exp2x - 1.0) / (exp2x + 1.0), (exp2y - 1.0) / (exp2y + 1.0), (exp2z - 1.0) / (exp2z + 1.0), (exp2w - 1.0) / (exp2w + 1.0)); +} + +#endif + +#if defined(ASINH_USED) + +highp float asinh(highp float x) { + return sign(x) * log(abs(x) + sqrt(1.0 + x * x)); +} + +highp vec2 asinh(highp vec2 x) { + return vec2(sign(x.x) * log(abs(x.x) + sqrt(1.0 + x.x * x.x)), sign(x.y) * log(abs(x.y) + sqrt(1.0 + x.y * x.y))); +} + +highp vec3 asinh(highp vec3 x) { + return vec3(sign(x.x) * log(abs(x.x) + sqrt(1.0 + x.x * x.x)), sign(x.y) * log(abs(x.y) + sqrt(1.0 + x.y * x.y)), sign(x.z) * log(abs(x.z) + sqrt(1.0 + x.z * x.z))); +} + +highp vec4 asinh(highp vec4 x) { + return vec4(sign(x.x) * log(abs(x.x) + sqrt(1.0 + x.x * x.x)), sign(x.y) * log(abs(x.y) + sqrt(1.0 + x.y * x.y)), sign(x.z) * log(abs(x.z) + sqrt(1.0 + x.z * x.z)), sign(x.w) * log(abs(x.w) + sqrt(1.0 + x.w * x.w))); +} + +#endif + +#if defined(ACOSH_USED) + +highp float acosh(highp float x) { + return log(x + sqrt(x * x - 1.0)); +} + +highp vec2 acosh(highp vec2 x) { + return vec2(log(x.x + sqrt(x.x * x.x - 1.0)), log(x.y + sqrt(x.y * x.y - 1.0))); +} + +highp vec3 acosh(highp vec3 x) { + return vec3(log(x.x + sqrt(x.x * x.x - 1.0)), log(x.y + sqrt(x.y * x.y - 1.0)), log(x.z + sqrt(x.z * x.z - 1.0))); +} + +highp vec4 acosh(highp vec4 x) { + return vec4(log(x.x + sqrt(x.x * x.x - 1.0)), log(x.y + sqrt(x.y * x.y - 1.0)), log(x.z + sqrt(x.z * x.z - 1.0)), log(x.w + sqrt(x.w * x.w - 1.0))); +} + +#endif + +#if defined(ATANH_USED) + +highp float atanh(highp float x) { + return 0.5 * log((1.0 + x) / (1.0 - x)); +} + +highp vec2 atanh(highp vec2 x) { + return 0.5 * vec2(log((1.0 + x.x) / (1.0 - x.x)), log((1.0 + x.y) / (1.0 - x.y))); +} + +highp vec3 atanh(highp vec3 x) { + return 0.5 * vec3(log((1.0 + x.x) / (1.0 - x.x)), log((1.0 + x.y) / (1.0 - x.y)), log((1.0 + x.z) / (1.0 - x.z))); +} + +highp vec4 atanh(highp vec4 x) { + return 0.5 * vec4(log((1.0 + x.x) / (1.0 - x.x)), log((1.0 + x.y) / (1.0 - x.y)), log((1.0 + x.z) / (1.0 - x.z)), log((1.0 + x.w) / (1.0 - x.w))); +} + +#endif + +#if defined(ROUND_USED) + +highp float round(highp float x) { + return floor(x + 0.5); +} + +highp vec2 round(highp vec2 x) { + return floor(x + vec2(0.5)); +} + +highp vec3 round(highp vec3 x) { + return floor(x + vec3(0.5)); +} + +highp vec4 round(highp vec4 x) { + return floor(x + vec4(0.5)); +} + +#endif + +#if defined(ROUND_EVEN_USED) + +highp float roundEven(highp float x) { + highp float t = x + 0.5; + highp float f = floor(t); + highp float r; + if (t == f) { + if (x > 0) + r = f - mod(f, 2); + else + r = f + mod(f, 2); + } else + r = f; + return r; +} + +highp vec2 roundEven(highp vec2 x) { + return vec2(roundEven(x.x), roundEven(x.y)); +} + +highp vec3 roundEven(highp vec3 x) { + return vec3(roundEven(x.x), roundEven(x.y), roundEven(x.z)); +} + +highp vec4 roundEven(highp vec4 x) { + return vec4(roundEven(x.x), roundEven(x.y), roundEven(x.z), roundEven(x.w)); +} + +#endif + +#if defined(IS_INF_USED) + +bool isinf(highp float x) { + return (2 * x == x) && (x != 0); +} + +bvec2 isinf(highp vec2 x) { + return bvec2((2 * x.x == x.x) && (x.x != 0), (2 * x.y == x.y) && (x.y != 0)); +} + +bvec3 isinf(highp vec3 x) { + return bvec3((2 * x.x == x.x) && (x.x != 0), (2 * x.y == x.y) && (x.y != 0), (2 * x.z == x.z) && (x.z != 0)); +} + +bvec4 isinf(highp vec4 x) { + return bvec4((2 * x.x == x.x) && (x.x != 0), (2 * x.y == x.y) && (x.y != 0), (2 * x.z == x.z) && (x.z != 0), (2 * x.w == x.w) && (x.w != 0)); +} + +#endif + +#if defined(IS_NAN_USED) + +bool isnan(highp float x) { + return x != x; +} + +bvec2 isnan(highp vec2 x) { + return bvec2(x.x != x.x, x.y != x.y); +} + +bvec3 isnan(highp vec3 x) { + return bvec3(x.x != x.x, x.y != x.y, x.z != x.z); +} + +bvec4 isnan(highp vec4 x) { + return bvec4(x.x != x.x, x.y != x.y, x.z != x.z, x.w != x.w); +} + +#endif + +#if defined(TRUNC_USED) + +highp float trunc(highp float x) { + return x < 0 ? -floor(-x) : floor(x); +} + +highp vec2 trunc(highp vec2 x) { + return vec2(x.x < 0 ? -floor(-x.x) : floor(x.x), x.y < 0 ? -floor(-x.y) : floor(x.y)); +} + +highp vec3 trunc(highp vec3 x) { + return vec3(x.x < 0 ? -floor(-x.x) : floor(x.x), x.y < 0 ? -floor(-x.y) : floor(x.y), x.z < 0 ? -floor(-x.z) : floor(x.z)); +} + +highp vec4 trunc(highp vec4 x) { + return vec4(x.x < 0 ? -floor(-x.x) : floor(x.x), x.y < 0 ? -floor(-x.y) : floor(x.y), x.z < 0 ? -floor(-x.z) : floor(x.z), x.w < 0 ? -floor(-x.w) : floor(x.w)); +} + +#endif + +#if defined(DETERMINANT_USED) + +highp float determinant(highp mat2 m) { + return m[0].x * m[1].y - m[1].x * m[0].y; +} + +highp float determinant(highp mat3 m) { + return m[0].x * (m[1].y * m[2].z - m[2].y * m[1].z) - m[1].x * (m[0].y * m[2].z - m[2].y * m[0].z) + m[2].x * (m[0].y * m[1].z - m[1].y * m[0].z); +} + +highp float determinant(highp mat4 m) { + highp float s00 = m[2].z * m[3].w - m[3].z * m[2].w; + highp float s01 = m[2].y * m[3].w - m[3].y * m[2].w; + highp float s02 = m[2].y * m[3].z - m[3].y * m[2].z; + highp float s03 = m[2].x * m[3].w - m[3].x * m[2].w; + highp float s04 = m[2].x * m[3].z - m[3].x * m[2].z; + highp float s05 = m[2].x * m[3].y - m[3].x * m[2].y; + highp vec4 c = vec4((m[1].y * s00 - m[1].z * s01 + m[1].w * s02), -(m[1].x * s00 - m[1].z * s03 + m[1].w * s04), (m[1].x * s01 - m[1].y * s03 + m[1].w * s05), -(m[1].x * s02 - m[1].y * s04 + m[1].z * s05)); + return m[0].x * c.x + m[0].y * c.y + m[0].z * c.z + m[0].w * c.w; +} + +#endif + +#if defined(INVERSE_USED) + +highp mat2 inverse(highp mat2 m) { + highp float d = 1.0 / (m[0].x * m[1].y - m[1].x * m[0].y); + return mat2( + vec2(m[1].y * d, -m[0].y * d), + vec2(-m[1].x * d, m[0].x * d)); +} + +highp mat3 inverse(highp mat3 m) { + highp float d = 1.0 / (m[0].x * (m[1].y * m[2].z - m[2].y * m[1].z) - m[1].x * (m[0].y * m[2].z - m[2].y * m[0].z) + m[2].x * (m[0].y * m[1].z - m[1].y * m[0].z)); + return mat3( + vec3((m[1].y * m[2].z - m[2].y * m[1].z), -(m[1].x * m[2].z - m[2].x * m[1].z), (m[1].x * m[2].y - m[2].x * m[1].y)) * d, + vec3(-(m[0].y * m[2].z - m[2].y * m[0].z), (m[0].x * m[2].z - m[2].x * m[0].z), -(m[0].x * m[2].y - m[2].x * m[0].y)) * d, + vec3((m[0].y * m[1].z - m[1].y * m[0].z), -(m[0].x * m[1].z - m[1].x * m[0].z), (m[0].x * m[1].y - m[1].x * m[0].y)) * d); +} + +highp mat4 inverse(highp mat4 m) { + highp float c00 = m[2].z * m[3].w - m[3].z * m[2].w; + highp float c02 = m[1].z * m[3].w - m[3].z * m[1].w; + highp float c03 = m[1].z * m[2].w - m[2].z * m[1].w; + + highp float c04 = m[2].y * m[3].w - m[3].y * m[2].w; + highp float c06 = m[1].y * m[3].w - m[3].y * m[1].w; + highp float c07 = m[1].y * m[2].w - m[2].y * m[1].w; + + highp float c08 = m[2].y * m[3].z - m[3].y * m[2].z; + highp float c10 = m[1].y * m[3].z - m[3].y * m[1].z; + highp float c11 = m[1].y * m[2].z - m[2].y * m[1].z; + + highp float c12 = m[2].x * m[3].w - m[3].x * m[2].w; + highp float c14 = m[1].x * m[3].w - m[3].x * m[1].w; + highp float c15 = m[1].x * m[2].w - m[2].x * m[1].w; + + highp float c16 = m[2].x * m[3].z - m[3].x * m[2].z; + highp float c18 = m[1].x * m[3].z - m[3].x * m[1].z; + highp float c19 = m[1].x * m[2].z - m[2].x * m[1].z; + + highp float c20 = m[2].x * m[3].y - m[3].x * m[2].y; + highp float c22 = m[1].x * m[3].y - m[3].x * m[1].y; + highp float c23 = m[1].x * m[2].y - m[2].x * m[1].y; + + vec4 f0 = vec4(c00, c00, c02, c03); + vec4 f1 = vec4(c04, c04, c06, c07); + vec4 f2 = vec4(c08, c08, c10, c11); + vec4 f3 = vec4(c12, c12, c14, c15); + vec4 f4 = vec4(c16, c16, c18, c19); + vec4 f5 = vec4(c20, c20, c22, c23); + + vec4 v0 = vec4(m[1].x, m[0].x, m[0].x, m[0].x); + vec4 v1 = vec4(m[1].y, m[0].y, m[0].y, m[0].y); + vec4 v2 = vec4(m[1].z, m[0].z, m[0].z, m[0].z); + vec4 v3 = vec4(m[1].w, m[0].w, m[0].w, m[0].w); + + vec4 inv0 = vec4(v1 * f0 - v2 * f1 + v3 * f2); + vec4 inv1 = vec4(v0 * f0 - v2 * f3 + v3 * f4); + vec4 inv2 = vec4(v0 * f1 - v1 * f3 + v3 * f5); + vec4 inv3 = vec4(v0 * f2 - v1 * f4 + v2 * f5); + + vec4 sa = vec4(+1, -1, +1, -1); + vec4 sb = vec4(-1, +1, -1, +1); + + mat4 inv = mat4(inv0 * sa, inv1 * sb, inv2 * sa, inv3 * sb); + + vec4 r0 = vec4(inv[0].x, inv[1].x, inv[2].x, inv[3].x); + vec4 d0 = vec4(m[0] * r0); + + highp float d1 = (d0.x + d0.y) + (d0.z + d0.w); + highp float d = 1.0 / d1; + + return inv * d; +} + +#endif + +#ifndef USE_GLES_OVER_GL + +#if defined(TRANSPOSE_USED) + +highp mat2 transpose(highp mat2 m) { + return mat2( + vec2(m[0].x, m[1].x), + vec2(m[0].y, m[1].y)); +} + +highp mat3 transpose(highp mat3 m) { + return mat3( + vec3(m[0].x, m[1].x, m[2].x), + vec3(m[0].y, m[1].y, m[2].y), + vec3(m[0].z, m[1].z, m[2].z)); +} + +#endif + +highp mat4 transpose(highp mat4 m) { + return mat4( + vec4(m[0].x, m[1].x, m[2].x, m[3].x), + vec4(m[0].y, m[1].y, m[2].y, m[3].y), + vec4(m[0].z, m[1].z, m[2].z, m[3].z), + vec4(m[0].w, m[1].w, m[2].w, m[3].w)); +} + +#if defined(OUTER_PRODUCT_USED) + +highp mat2 outerProduct(highp vec2 c, highp vec2 r) { + return mat2(c * r.x, c * r.y); +} + +highp mat3 outerProduct(highp vec3 c, highp vec3 r) { + return mat3(c * r.x, c * r.y, c * r.z); +} + +highp mat4 outerProduct(highp vec4 c, highp vec4 r) { + return mat4(c * r.x, c * r.y, c * r.z, c * r.w); +} + +#endif + +#endif diff --git a/drivers/gles2/shaders/subsurf_scattering.glsl b/drivers/gles2/shaders/subsurf_scattering.glsl new file mode 100644 index 00000000000..d0c34cf1b00 --- /dev/null +++ b/drivers/gles2/shaders/subsurf_scattering.glsl @@ -0,0 +1,171 @@ +/* clang-format off */ +[vertex] + +layout(location = 0) in highp vec4 vertex_attrib; +/* clang-format on */ +layout(location = 4) in vec2 uv_in; + +out vec2 uv_interp; + +void main() { + uv_interp = uv_in; + gl_Position = vertex_attrib; +} + +/* clang-format off */ +[fragment] + +//#define QUALIFIER uniform // some guy on the interweb says it may be faster with this +#define QUALIFIER const + +#ifdef USE_25_SAMPLES +const int kernel_size = 25; +/* clang-format on */ +QUALIFIER vec2 kernel[25] = vec2[]( + vec2(0.530605, 0.0), + vec2(0.000973794, -3.0), + vec2(0.00333804, -2.52083), + vec2(0.00500364, -2.08333), + vec2(0.00700976, -1.6875), + vec2(0.0094389, -1.33333), + vec2(0.0128496, -1.02083), + vec2(0.017924, -0.75), + vec2(0.0263642, -0.520833), + vec2(0.0410172, -0.333333), + vec2(0.0493588, -0.1875), + vec2(0.0402784, -0.0833333), + vec2(0.0211412, -0.0208333), + vec2(0.0211412, 0.0208333), + vec2(0.0402784, 0.0833333), + vec2(0.0493588, 0.1875), + vec2(0.0410172, 0.333333), + vec2(0.0263642, 0.520833), + vec2(0.017924, 0.75), + vec2(0.0128496, 1.02083), + vec2(0.0094389, 1.33333), + vec2(0.00700976, 1.6875), + vec2(0.00500364, 2.08333), + vec2(0.00333804, 2.52083), + vec2(0.000973794, 3.0)); +#endif //USE_25_SAMPLES + +#ifdef USE_17_SAMPLES +const int kernel_size = 17; +QUALIFIER vec2 kernel[17] = vec2[]( + vec2(0.536343, 0.0), + vec2(0.00317394, -2.0), + vec2(0.0100386, -1.53125), + vec2(0.0144609, -1.125), + vec2(0.0216301, -0.78125), + vec2(0.0347317, -0.5), + vec2(0.0571056, -0.28125), + vec2(0.0582416, -0.125), + vec2(0.0324462, -0.03125), + vec2(0.0324462, 0.03125), + vec2(0.0582416, 0.125), + vec2(0.0571056, 0.28125), + vec2(0.0347317, 0.5), + vec2(0.0216301, 0.78125), + vec2(0.0144609, 1.125), + vec2(0.0100386, 1.53125), + vec2(0.00317394, 2.0)); +#endif //USE_17_SAMPLES + +#ifdef USE_11_SAMPLES +const int kernel_size = 11; +QUALIFIER vec2 kernel[11] = vec2[]( + vec2(0.560479, 0.0), + vec2(0.00471691, -2.0), + vec2(0.0192831, -1.28), + vec2(0.03639, -0.72), + vec2(0.0821904, -0.32), + vec2(0.0771802, -0.08), + vec2(0.0771802, 0.08), + vec2(0.0821904, 0.32), + vec2(0.03639, 0.72), + vec2(0.0192831, 1.28), + vec2(0.00471691, 2.0)); +#endif //USE_11_SAMPLES + +uniform float max_radius; +uniform float camera_z_far; +uniform float camera_z_near; +uniform float unit_size; +uniform vec2 dir; +in vec2 uv_interp; + +uniform sampler2D source_diffuse; //texunit:0 +uniform sampler2D source_sss; //texunit:1 +uniform sampler2D source_depth; //texunit:2 + +layout(location = 0) out vec4 frag_color; + +void main() { + float strength = texture(source_sss, uv_interp).r; + strength *= strength; //stored as sqrt + + // Fetch color of current pixel: + vec4 base_color = texture(source_diffuse, uv_interp); + + if (strength > 0.0) { + // Fetch linear depth of current pixel: + float depth = texture(source_depth, uv_interp).r * 2.0 - 1.0; +#ifdef USE_ORTHOGONAL_PROJECTION + depth = ((depth + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; + float scale = unit_size; //remember depth is negative by default in OpenGL +#else + depth = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - depth * (camera_z_far - camera_z_near)); + float scale = unit_size / depth; //remember depth is negative by default in OpenGL +#endif + + // Calculate the final step to fetch the surrounding pixels: + vec2 step = max_radius * scale * dir; + step *= strength; // Modulate it using the alpha channel. + step *= 1.0 / 3.0; // Divide by 3 as the kernels range from -3 to 3. + + // Accumulate the center sample: + vec3 color_accum = base_color.rgb; + color_accum *= kernel[0].x; +#ifdef ENABLE_STRENGTH_WEIGHTING + float color_weight = kernel[0].x; +#endif + + // Accumulate the other samples: + for (int i = 1; i < kernel_size; i++) { + // Fetch color and depth for current sample: + vec2 offset = uv_interp + kernel[i].y * step; + vec3 color = texture(source_diffuse, offset).rgb; + +#ifdef ENABLE_FOLLOW_SURFACE + // If the difference in depth is huge, we lerp color back to "colorM": + float depth_cmp = texture(source_depth, offset).r * 2.0 - 1.0; + +#ifdef USE_ORTHOGONAL_PROJECTION + depth_cmp = ((depth_cmp + (camera_z_far + camera_z_near) / (camera_z_far - camera_z_near)) * (camera_z_far - camera_z_near)) / 2.0; +#else + depth_cmp = 2.0 * camera_z_near * camera_z_far / (camera_z_far + camera_z_near - depth_cmp * (camera_z_far - camera_z_near)); +#endif + + float s = clamp(300.0f * scale * max_radius * abs(depth - depth_cmp), 0.0, 1.0); + color = mix(color, base_color.rgb, s); +#endif + + // Accumulate: + color *= kernel[i].x; + +#ifdef ENABLE_STRENGTH_WEIGHTING + float color_s = texture(source_sss, offset).r; + color_weight += color_s * kernel[i].x; + color *= color_s; +#endif + color_accum += color; + } + +#ifdef ENABLE_STRENGTH_WEIGHTING + color_accum /= color_weight; +#endif + frag_color = vec4(color_accum, base_color.a); //keep alpha (used for SSAO) + } else { + frag_color = base_color; + } +} diff --git a/drivers/gles2/shaders/tonemap.glsl b/drivers/gles2/shaders/tonemap.glsl new file mode 100644 index 00000000000..0117bdb3d30 --- /dev/null +++ b/drivers/gles2/shaders/tonemap.glsl @@ -0,0 +1,343 @@ +/* clang-format off */ +[vertex] + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +precision highp float; +precision highp int; +#endif + +attribute vec2 vertex_attrib; // attrib:0 +/* clang-format on */ +attribute vec2 uv_in; // attrib:4 + +varying vec2 uv_interp; + +void main() { + gl_Position = vec4(vertex_attrib, 0.0, 1.0); + + uv_interp = uv_in; +} + +/* clang-format off */ +[fragment] + +// texture2DLodEXT and textureCubeLodEXT are fragment shader specific. +// Do not copy these defines in the vertex section. +#ifndef USE_GLES_OVER_GL +#ifdef GL_EXT_shader_texture_lod +#extension GL_EXT_shader_texture_lod : enable +#define texture2DLod(img, coord, lod) texture2DLodEXT(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCubeLodEXT(img, coord, lod) +#endif +#endif // !USE_GLES_OVER_GL + +#ifdef GL_ARB_shader_texture_lod +#extension GL_ARB_shader_texture_lod : enable +#endif + +#if !defined(GL_EXT_shader_texture_lod) && !defined(GL_ARB_shader_texture_lod) +#define texture2DLod(img, coord, lod) texture2D(img, coord, lod) +#define textureCubeLod(img, coord, lod) textureCube(img, coord, lod) +#endif + +// Allows the use of bitshift operators for bicubic upscale +#ifdef GL_EXT_gpu_shader4 +#extension GL_EXT_gpu_shader4 : enable +#endif + +#ifdef USE_GLES_OVER_GL +#define lowp +#define mediump +#define highp +#else +#if defined(USE_HIGHP_PRECISION) +precision highp float; +precision highp int; +#else +precision mediump float; +precision mediump int; +#endif +#endif + +#include "stdlib.glsl" + +varying vec2 uv_interp; +/* clang-format on */ + +uniform highp sampler2D source; //texunit:0 + +#if defined(USE_GLOW_LEVEL1) || defined(USE_GLOW_LEVEL2) || defined(USE_GLOW_LEVEL3) || defined(USE_GLOW_LEVEL4) || defined(USE_GLOW_LEVEL5) || defined(USE_GLOW_LEVEL6) || defined(USE_GLOW_LEVEL7) +#define USING_GLOW // only use glow when at least one glow level is selected + +#ifdef USE_MULTI_TEXTURE_GLOW +uniform highp sampler2D source_glow1; //texunit:2 +uniform highp sampler2D source_glow2; //texunit:3 +uniform highp sampler2D source_glow3; //texunit:4 +uniform highp sampler2D source_glow4; //texunit:5 +uniform highp sampler2D source_glow5; //texunit:6 +uniform highp sampler2D source_glow6; //texunit:7 +#ifdef USE_GLOW_LEVEL7 +uniform highp sampler2D source_glow7; //texunit:8 +#endif +#else +uniform highp sampler2D source_glow; //texunit:2 +#endif +uniform highp float glow_intensity; +#endif + +#ifdef USE_BCS +uniform vec3 bcs; +#endif + +#ifdef USE_FXAA +uniform vec2 pixel_size; +#endif + +#ifdef USE_COLOR_CORRECTION +uniform sampler2D color_correction; //texunit:1 +#endif + +#ifdef GL_EXT_gpu_shader4 +#ifdef USE_GLOW_FILTER_BICUBIC +// w0, w1, w2, and w3 are the four cubic B-spline basis functions +float w0(float a) { + return (1.0 / 6.0) * (a * (a * (-a + 3.0) - 3.0) + 1.0); +} + +float w1(float a) { + return (1.0 / 6.0) * (a * a * (3.0 * a - 6.0) + 4.0); +} + +float w2(float a) { + return (1.0 / 6.0) * (a * (a * (-3.0 * a + 3.0) + 3.0) + 1.0); +} + +float w3(float a) { + return (1.0 / 6.0) * (a * a * a); +} + +// g0 and g1 are the two amplitude functions +float g0(float a) { + return w0(a) + w1(a); +} + +float g1(float a) { + return w2(a) + w3(a); +} + +// h0 and h1 are the two offset functions +float h0(float a) { + return -1.0 + w1(a) / (w0(a) + w1(a)); +} + +float h1(float a) { + return 1.0 + w3(a) / (w2(a) + w3(a)); +} + +uniform ivec2 glow_texture_size; + +vec4 texture2D_bicubic(sampler2D tex, vec2 uv, int p_lod) { + float lod = float(p_lod); + vec2 tex_size = vec2(glow_texture_size >> p_lod); + vec2 texel_size = vec2(1.0) / tex_size; + + uv = uv * tex_size + vec2(0.5); + + vec2 iuv = floor(uv); + vec2 fuv = fract(uv); + + float g0x = g0(fuv.x); + float g1x = g1(fuv.x); + float h0x = h0(fuv.x); + float h1x = h1(fuv.x); + float h0y = h0(fuv.y); + float h1y = h1(fuv.y); + + vec2 p0 = (vec2(iuv.x + h0x, iuv.y + h0y) - vec2(0.5)) * texel_size; + vec2 p1 = (vec2(iuv.x + h1x, iuv.y + h0y) - vec2(0.5)) * texel_size; + vec2 p2 = (vec2(iuv.x + h0x, iuv.y + h1y) - vec2(0.5)) * texel_size; + vec2 p3 = (vec2(iuv.x + h1x, iuv.y + h1y) - vec2(0.5)) * texel_size; + + return (g0(fuv.y) * (g0x * texture2DLod(tex, p0, lod) + g1x * texture2DLod(tex, p1, lod))) + + (g1(fuv.y) * (g0x * texture2DLod(tex, p2, lod) + g1x * texture2DLod(tex, p3, lod))); +} + +#define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2D_bicubic(m_tex, m_uv, m_lod) +#else //!USE_GLOW_FILTER_BICUBIC +#define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2DLod(m_tex, m_uv, float(m_lod)) +#endif //USE_GLOW_FILTER_BICUBIC + +#else //!GL_EXT_gpu_shader4 +#define GLOW_TEXTURE_SAMPLE(m_tex, m_uv, m_lod) texture2DLod(m_tex, m_uv, float(m_lod)) +#endif //GL_EXT_gpu_shader4 + +vec3 apply_glow(vec3 color, vec3 glow) { // apply glow using the selected blending mode +#ifdef USE_GLOW_REPLACE + color = glow; +#endif + +#ifdef USE_GLOW_SCREEN + color = max((color + glow) - (color * glow), vec3(0.0)); +#endif + +#ifdef USE_GLOW_SOFTLIGHT + glow = glow * vec3(0.5) + vec3(0.5); + + color.r = (glow.r <= 0.5) ? (color.r - (1.0 - 2.0 * glow.r) * color.r * (1.0 - color.r)) : (((glow.r > 0.5) && (color.r <= 0.25)) ? (color.r + (2.0 * glow.r - 1.0) * (4.0 * color.r * (4.0 * color.r + 1.0) * (color.r - 1.0) + 7.0 * color.r)) : (color.r + (2.0 * glow.r - 1.0) * (sqrt(color.r) - color.r))); + color.g = (glow.g <= 0.5) ? (color.g - (1.0 - 2.0 * glow.g) * color.g * (1.0 - color.g)) : (((glow.g > 0.5) && (color.g <= 0.25)) ? (color.g + (2.0 * glow.g - 1.0) * (4.0 * color.g * (4.0 * color.g + 1.0) * (color.g - 1.0) + 7.0 * color.g)) : (color.g + (2.0 * glow.g - 1.0) * (sqrt(color.g) - color.g))); + color.b = (glow.b <= 0.5) ? (color.b - (1.0 - 2.0 * glow.b) * color.b * (1.0 - color.b)) : (((glow.b > 0.5) && (color.b <= 0.25)) ? (color.b + (2.0 * glow.b - 1.0) * (4.0 * color.b * (4.0 * color.b + 1.0) * (color.b - 1.0) + 7.0 * color.b)) : (color.b + (2.0 * glow.b - 1.0) * (sqrt(color.b) - color.b))); +#endif + +#if !defined(USE_GLOW_SCREEN) && !defined(USE_GLOW_SOFTLIGHT) && !defined(USE_GLOW_REPLACE) // no other selected -> additive + color += glow; +#endif + + return color; +} + +vec3 apply_bcs(vec3 color, vec3 bcs) { + color = mix(vec3(0.0), color, bcs.x); + color = mix(vec3(0.5), color, bcs.y); + color = mix(vec3(dot(vec3(1.0), color) * 0.33333), color, bcs.z); + + return color; +} + +vec3 apply_color_correction(vec3 color, sampler2D correction_tex) { + color.r = texture2D(correction_tex, vec2(color.r, 0.0)).r; + color.g = texture2D(correction_tex, vec2(color.g, 0.0)).g; + color.b = texture2D(correction_tex, vec2(color.b, 0.0)).b; + + return color; +} + +vec3 apply_fxaa(vec3 color, vec2 uv_interp, vec2 pixel_size) { + const float FXAA_REDUCE_MIN = (1.0 / 128.0); + const float FXAA_REDUCE_MUL = (1.0 / 8.0); + const float FXAA_SPAN_MAX = 8.0; + + vec3 rgbNW = texture2DLod(source, uv_interp + vec2(-1.0, -1.0) * pixel_size, 0.0).xyz; + vec3 rgbNE = texture2DLod(source, uv_interp + vec2(1.0, -1.0) * pixel_size, 0.0).xyz; + vec3 rgbSW = texture2DLod(source, uv_interp + vec2(-1.0, 1.0) * pixel_size, 0.0).xyz; + vec3 rgbSE = texture2DLod(source, uv_interp + vec2(1.0, 1.0) * pixel_size, 0.0).xyz; + vec3 rgbM = color; + vec3 luma = vec3(0.299, 0.587, 0.114); + float lumaNW = dot(rgbNW, luma); + float lumaNE = dot(rgbNE, luma); + float lumaSW = dot(rgbSW, luma); + float lumaSE = dot(rgbSE, luma); + float lumaM = dot(rgbM, luma); + float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))); + float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE))); + + vec2 dir; + dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE)); + dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE)); + + float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * + (0.25 * FXAA_REDUCE_MUL), + FXAA_REDUCE_MIN); + + float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce); + dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX), + max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), + dir * rcpDirMin)) * + pixel_size; + + vec3 rgbA = 0.5 * (texture2DLod(source, uv_interp + dir * (1.0 / 3.0 - 0.5), 0.0).xyz + texture2DLod(source, uv_interp + dir * (2.0 / 3.0 - 0.5), 0.0).xyz); + vec3 rgbB = rgbA * 0.5 + 0.25 * (texture2DLod(source, uv_interp + dir * -0.5, 0.0).xyz + + texture2DLod(source, uv_interp + dir * 0.5, 0.0).xyz); + + float lumaB = dot(rgbB, luma); + if ((lumaB < lumaMin) || (lumaB > lumaMax)) { + return rgbA; + } else { + return rgbB; + } +} + +void main() { + vec3 color = texture2DLod(source, uv_interp, 0.0).rgb; + +#ifdef USE_FXAA + color = apply_fxaa(color, uv_interp, pixel_size); +#endif + + // Glow + +#ifdef USING_GLOW + vec3 glow = vec3(0.0); +#ifdef USE_MULTI_TEXTURE_GLOW +#ifdef USE_GLOW_LEVEL1 + glow += GLOW_TEXTURE_SAMPLE(source_glow1, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL2 + glow += GLOW_TEXTURE_SAMPLE(source_glow2, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL3 + glow += GLOW_TEXTURE_SAMPLE(source_glow3, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL4 + glow += GLOW_TEXTURE_SAMPLE(source_glow4, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL5 + glow += GLOW_TEXTURE_SAMPLE(source_glow5, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL6 + glow += GLOW_TEXTURE_SAMPLE(source_glow6, uv_interp, 0).rgb; +#ifdef USE_GLOW_LEVEL7 + glow += GLOW_TEXTURE_SAMPLE(source_glow7, uv_interp, 0).rgb; +#endif +#endif +#endif +#endif +#endif +#endif +#endif + +#else + +#ifdef USE_GLOW_LEVEL1 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 1).rgb; +#endif + +#ifdef USE_GLOW_LEVEL2 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 2).rgb; +#endif + +#ifdef USE_GLOW_LEVEL3 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 3).rgb; +#endif + +#ifdef USE_GLOW_LEVEL4 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 4).rgb; +#endif + +#ifdef USE_GLOW_LEVEL5 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 5).rgb; +#endif + +#ifdef USE_GLOW_LEVEL6 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 6).rgb; +#endif + +#ifdef USE_GLOW_LEVEL7 + glow += GLOW_TEXTURE_SAMPLE(source_glow, uv_interp, 7).rgb; +#endif +#endif //USE_MULTI_TEXTURE_GLOW + + glow *= glow_intensity; + color = apply_glow(color, glow); +#endif + + // Additional effects + +#ifdef USE_BCS + color = apply_bcs(color, bcs); +#endif + +#ifdef USE_COLOR_CORRECTION + color = apply_color_correction(color, color_correction); +#endif + + gl_FragColor = vec4(color, 1.0); +} diff --git a/drivers/gles2/texture_loader_gles2.cpp b/drivers/gles2/texture_loader_gles2.cpp new file mode 100644 index 00000000000..3878b40c19a --- /dev/null +++ b/drivers/gles2/texture_loader_gles2.cpp @@ -0,0 +1,112 @@ +/*************************************************************************/ +/* texture_loader_gles2.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "texture_loader_gles2.h" +#ifdef GLES2_BACKEND_ENABLED + +#include "core/io/file_access.h" +#include "core/string/print_string.h" + +#include + +RES ResourceFormatGLES2Texture::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) { + unsigned int width = 8; + unsigned int height = 8; + + //We just use some format + Image::Format fmt = Image::FORMAT_RGB8; + int rowsize = 3 * width; + + Vector dstbuff; + + dstbuff.resize(rowsize * height); + + uint8_t **row_p = memnew_arr(uint8_t *, height); + + for (unsigned int i = 0; i < height; i++) { + row_p[i] = 0; //No colors any more, I want them to turn black + } + + memdelete_arr(row_p); + + Ref img = memnew(Image(width, height, 0, fmt, dstbuff)); + + Ref texture = memnew(ImageTexture); + texture->create_from_image(img); + + if (r_error) + *r_error = OK; + + return texture; +} + +void ResourceFormatGLES2Texture::get_recognized_extensions(List *p_extensions) const { + p_extensions->push_back("bmp"); + p_extensions->push_back("dds"); + p_extensions->push_back("exr"); + p_extensions->push_back("jpeg"); + p_extensions->push_back("jpg"); + p_extensions->push_back("hdr"); + p_extensions->push_back("pkm"); + p_extensions->push_back("png"); + p_extensions->push_back("pvr"); + p_extensions->push_back("svg"); + p_extensions->push_back("svgz"); + p_extensions->push_back("tga"); + p_extensions->push_back("webp"); +} + +bool ResourceFormatGLES2Texture::handles_type(const String &p_type) const { + return ClassDB::is_parent_class(p_type, "Texture2D"); +} + +String ResourceFormatGLES2Texture::get_resource_type(const String &p_path) const { + String extension = p_path.get_extension().to_lower(); + if ( + extension == "bmp" || + extension == "dds" || + extension == "exr" || + extension == "jpeg" || + extension == "jpg" || + extension == "hdr" || + extension == "pkm" || + extension == "png" || + extension == "pvr" || + extension == "svg" || + extension == "svgz" || + extension == "tga" || + extension == "webp") { + return "ImageTexture"; + } + + return ""; +} + +#endif diff --git a/platform/linuxbsd/context_gl_x11.h b/drivers/gles2/texture_loader_gles2.h similarity index 69% rename from platform/linuxbsd/context_gl_x11.h rename to drivers/gles2/texture_loader_gles2.h index d089886f4de..4e6e3c4ce2f 100644 --- a/platform/linuxbsd/context_gl_x11.h +++ b/drivers/gles2/texture_loader_gles2.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* context_gl_x11.h */ +/* texture_loader_gles2.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,53 +28,22 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef CONTEXT_GL_X11_H -#define CONTEXT_GL_X11_H +#pragma once -#ifdef X11_ENABLED +#include "drivers/gles_common/rasterizer_platforms.h" +#ifdef GLES2_BACKEND_ENABLED -#if defined(OPENGL_ENABLED) +#include "core/io/resource_loader.h" +#include "scene/resources/texture.h" -#include "core/os/os.h" -#include -#include - -struct ContextGL_X11_Private; - -class ContextGL_X11 { +class ResourceFormatGLES2Texture : public ResourceFormatLoader { public: - enum ContextType { - GLES_2_0_COMPATIBLE, - }; + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, bool p_no_cache = false); + virtual void get_recognized_extensions(List *p_extensions) const; + virtual bool handles_type(const String &p_type) const; + virtual String get_resource_type(const String &p_path) const; -private: - ContextGL_X11_Private *p; - OS::VideoMode default_video_mode; - ::Display *x11_display; - ::Window &x11_window; - bool double_buffer; - bool direct_render; - int glx_minor, glx_major; - bool use_vsync; - ContextType context_type; - -public: - void release_current(); - void make_current(); - void swap_buffers(); - int get_window_width(); - int get_window_height(); - - Error initialize(); - - void set_use_vsync(bool p_use); - bool is_using_vsync() const; - - ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, ContextType p_context_type); - ~ContextGL_X11(); + virtual ~ResourceFormatGLES2Texture() {} }; #endif - -#endif -#endif diff --git a/drivers/gles_common/SCsub b/drivers/gles_common/SCsub new file mode 100644 index 00000000000..91e1140b750 --- /dev/null +++ b/drivers/gles_common/SCsub @@ -0,0 +1,5 @@ +#!/usr/bin/env python + +Import("env") + +env.add_source_files(env.drivers_sources, "*.cpp") diff --git a/drivers/gles_common/batch_diagnose.inc b/drivers/gles_common/batch_diagnose.inc new file mode 100644 index 00000000000..88a8792edb0 --- /dev/null +++ b/drivers/gles_common/batch_diagnose.inc @@ -0,0 +1,192 @@ +void _debug_write_garbage() { + // extremely slow, writes garbage over arrays to detect using + // uninitialized in graphical output. Do not enable in normal use!! +#ifdef RASTERIZER_EXTRA_CHECKS + int num_verts = MIN(bdata.vertices.max_size(), 32); + for (int n = 0; n < num_verts; n++) { + bdata.vertices[n].pos.set(Math::random(-200.0f, 200.0f), Math::random(-200.0f, 200.0f)); + bdata.vertices[n].uv.set(Math::random(0.0f, 1.0f), Math::random(0.0f, 1.0f)); + } + + int num_colors = MIN(bdata.vertex_colors.max_size(), 32); + for (int n = 0; n < num_colors; n++) { + bdata.vertex_colors[n].set(Math::randf(), Math::randf(), Math::randf(), 1.0f); + } + + int num_modulates = MIN(bdata.vertex_modulates.max_size(), 32); + for (int n = 0; n < num_modulates; n++) { + bdata.vertex_modulates[n].set(Math::randf(), Math::randf(), Math::randf(), 1.0f); + } + + int num_light_angles = MIN(bdata.light_angles.max_size(), 32); + for (int n = 0; n < num_light_angles; n++) { + bdata.light_angles[n] = Math::random(-3.0f, +3.0f); + } + + int num_transforms = MIN(bdata.vertex_transforms.max_size(), 32); + for (int n = 0; n < num_transforms; n++) { + bdata.vertex_transforms[n].translate.set(Math::random(-200.0f, 200.0f), Math::random(-200.0f, 200.0f)); + bdata.vertex_transforms[n].basis[0].set(Math::random(-2.0f, 2.0f), Math::random(-2.0f, 2.0f)); + bdata.vertex_transforms[n].basis[1].set(Math::random(-2.0f, 2.0f), Math::random(-2.0f, 2.0f)); + } + + int num_unit_verts = MIN(bdata.unit_vertices.max_size(), 32); + for (int n = 0; n < num_unit_verts; n++) { + uint8_t *data = bdata.unit_vertices.get_unit(n); + for (int b = 0; b > bdata.unit_vertices.get_unit_size_bytes(); b++) { + data[b] = Math::random(0, 255); + } + } + +#endif +} + +String get_command_type_string(const RendererCanvasRender::Item::Command &p_command) const { + String sz = ""; + + switch (p_command.type) { + default: + break; +#ifdef GODOT_3 + case RendererCanvasRender::Item::Command::GD_TYPE_LINE: { + sz = "l"; + } break; + case RendererCanvasRender::Item::Command::GD_TYPE_POLYLINE: { + sz = "PL"; + } break; + case RendererCanvasRender::Item::Command::GD_TYPE_CIRCLE: { + sz = "c"; + } break; +#endif + case RendererCanvasRender::Item::Command::TYPE_RECT: { + sz = "r"; + } break; + case RendererCanvasRender::Item::Command::TYPE_NINEPATCH: { + sz = "n"; + } break; + case RendererCanvasRender::Item::Command::TYPE_PRIMITIVE: { + sz = "PR"; + } break; + case RendererCanvasRender::Item::Command::TYPE_POLYGON: { + sz = "p"; + } break; + case RendererCanvasRender::Item::Command::TYPE_MESH: { + sz = "m"; + } break; + case RendererCanvasRender::Item::Command::TYPE_MULTIMESH: { + sz = "MM"; + } break; + case RendererCanvasRender::Item::Command::TYPE_PARTICLES: { + sz = "PA"; + } break; + case RendererCanvasRender::Item::Command::TYPE_TRANSFORM: { + sz = "t"; + + // add a bit more info in debug build + const RendererCanvasRender::Item::CommandTransform *transform = static_cast(&p_command); + const Transform2D &mat = transform->xform; + + sz += " "; + sz += String(Variant(mat.elements[2])); + sz += " "; + } break; + case RendererCanvasRender::Item::Command::TYPE_CLIP_IGNORE: { + sz = "CI"; + } break; + } // switch + + return sz; +} + +void diagnose_batches(RendererCanvasRender::Item::Command *const *p_commands) { + int num_batches = bdata.batches.size(); + + BatchColor curr_color; + curr_color.set(Color(-1, -1, -1, -1)); + bool first_color_change = true; + + for (int batch_num = 0; batch_num < num_batches; batch_num++) { + const Batch &batch = bdata.batches[batch_num]; + bdata.frame_string += "\t\t\tbatch "; + + switch (batch.type) { + case RasterizerStorageCommon::BT_POLY: { + bdata.frame_string += "P "; + bdata.frame_string += itos(batch.first_command) + "-"; + bdata.frame_string += itos(batch.num_commands); + + bdata.frame_string += " " + batch.color.to_string(); + + if (batch.num_commands > 1) { + bdata.frame_string += " MULTI"; + } + if (curr_color != batch.color) { + curr_color = batch.color; + if (!first_color_change) { + bdata.frame_string += " color"; + } else { + first_color_change = false; + } + } + bdata.frame_string += "\n"; + } break; + case RasterizerStorageCommon::BT_LINE: + case RasterizerStorageCommon::BT_LINE_AA: { + bdata.frame_string += "L "; + bdata.frame_string += itos(batch.first_command) + "-"; + bdata.frame_string += itos(batch.num_commands); + + bdata.frame_string += " " + batch.color.to_string(); + + if (batch.num_commands > 1) { + bdata.frame_string += " MULTI"; + } + if (curr_color != batch.color) { + curr_color = batch.color; + if (!first_color_change) { + bdata.frame_string += " color"; + } else { + first_color_change = false; + } + } + bdata.frame_string += "\n"; + } break; + case RasterizerStorageCommon::BT_RECT: { + bdata.frame_string += "R "; + bdata.frame_string += itos(batch.first_command) + "-"; + bdata.frame_string += itos(batch.num_commands); + + int tex_id = (int)bdata.batch_textures[batch.batch_texture_id].RID_texture.get_id(); + bdata.frame_string += " [" + itos(batch.batch_texture_id) + " - " + itos(tex_id) + "]"; + + bdata.frame_string += " " + batch.color.to_string(); + + if (batch.num_commands > 1) { + bdata.frame_string += " MULTI"; + } + if (curr_color != batch.color) { + curr_color = batch.color; + if (!first_color_change) { + bdata.frame_string += " color"; + } else { + first_color_change = false; + } + } + bdata.frame_string += "\n"; + } break; + default: { + bdata.frame_string += "D "; + bdata.frame_string += itos(batch.first_command) + "-"; + bdata.frame_string += itos(batch.num_commands) + " "; + + int num_show = MIN(batch.num_commands, 16); + for (int n = 0; n < num_show; n++) { + const RendererCanvasRender::Item::Command &comm = *p_commands[batch.first_command + n]; + bdata.frame_string += get_command_type_string(comm) + " "; + } + + bdata.frame_string += "\n"; + } break; + } + } +} diff --git a/drivers/gles_common/rasterizer_array.h b/drivers/gles_common/rasterizer_array.h new file mode 100644 index 00000000000..d1b616162fc --- /dev/null +++ b/drivers/gles_common/rasterizer_array.h @@ -0,0 +1,426 @@ +/*************************************************************************/ +/* rasterizer_array.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZER_ARRAY_H +#define RASTERIZER_ARRAY_H + +/** + * Fast single-threaded growable array for POD types. + * For use in render drivers, not for general use. + * TO BE REPLACED by local_vector. +*/ +#include "rasterizer_version.h" + +#include "core/os/memory.h" +#include + +#ifdef GODOT_4 +#include "core/templates/local_vector.h" +#include "core/templates/vector.h" +#else +#include "core/vector.h" +#endif + +// very simple non-growable array, that keeps track of the size of a 'unit' +// which can be cast to whatever vertex format FVF required, and is initially +// created with enough memory to hold the biggest FVF. +// This allows multiple FVFs to use the same array. +class RasterizerUnitArrayGLES2 { +public: + RasterizerUnitArrayGLES2() { + _list = nullptr; + free(); + } + ~RasterizerUnitArrayGLES2() { free(); } + + uint8_t *get_unit(unsigned int ui) { return &_list[ui * _unit_size_bytes]; } + const uint8_t *get_unit(unsigned int ui) const { return &_list[ui * _unit_size_bytes]; } + + int size() const { return _size; } + int max_size() const { return _max_size; } + + void free() { + if (_list) { + memdelete_arr(_list); + _list = 0; + } + _size = 0; + _max_size = 0; + _max_size_bytes = 0; + _unit_size_bytes = 0; + } + + void create(int p_max_size_units, int p_max_unit_size_bytes) { + free(); + + _max_unit_size_bytes = p_max_unit_size_bytes; + _max_size = p_max_size_units; + _max_size_bytes = p_max_size_units * p_max_unit_size_bytes; + + if (_max_size_bytes) { + _list = memnew_arr(uint8_t, _max_size_bytes); + } + } + + void prepare(int p_unit_size_bytes) { + _unit_size_bytes = p_unit_size_bytes; + _size = 0; + } + + // several items at a time + uint8_t *request(int p_num_items = 1) { + int old_size = _size; + _size += p_num_items; + + if (_size <= _max_size) { + return get_unit(old_size); + } + + // revert + _size = old_size; + return nullptr; + } + +private: + uint8_t *_list; + int _size; // in units + int _max_size; // in units + int _max_size_bytes; + int _unit_size_bytes; + int _max_unit_size_bytes; +}; + +template +class RasterizerArray { +public: + RasterizerArray() { + _list = 0; + _size = 0; + _max_size = 0; + } + ~RasterizerArray() { free(); } + + T &operator[](unsigned int ui) { return _list[ui]; } + const T &operator[](unsigned int ui) const { return _list[ui]; } + + void free() { + if (_list) { + memdelete_arr(_list); + _list = 0; + } + _size = 0; + _max_size = 0; + } + + void create(int p_size) { + free(); + if (p_size) { + _list = memnew_arr(T, p_size); + } + _size = 0; + _max_size = p_size; + } + + void reset() { _size = 0; } + + T *request_with_grow() { + T *p = request(); + if (!p) { + grow(); + return request_with_grow(); + } + return p; + } + + // none of that inefficient pass by value stuff here, thanks + T *request() { + if (_size < _max_size) { + return &_list[_size++]; + } + return 0; + } + + // several items at a time + T *request(int p_num_items) { + int old_size = _size; + _size += p_num_items; + + if (_size <= _max_size) { + return &_list[old_size]; + } + + // revert + _size = old_size; + return 0; + } + + int size() const { return _size; } + int max_size() const { return _max_size; } + const T *get_data() const { return _list; } + + bool copy_from(const RasterizerArray &o) { + // no resizing done here, it should be done manually + if (o.size() > _max_size) + return false; + + // pod types only please! + memcpy(_list, o.get_data(), o.size() * sizeof(T)); + _size = o.size(); + return true; + } + + // if you want this to be cheap, call reset before grow, + // to ensure there is no data to copy + void grow() { + unsigned int new_max_size = _max_size * 2; + if (!new_max_size) + new_max_size = 1; + + T *new_list = memnew_arr(T, new_max_size); + + // copy .. pod types only + if (_list) { + memcpy(new_list, _list, _size * sizeof(T)); + } + + unsigned int new_size = size(); + free(); + _list = new_list; + _size = new_size; + _max_size = new_max_size; + } + +private: + T *_list; + int _size; + int _max_size; +}; + +template +class RasterizerArray_non_pod { +public: + RasterizerArray_non_pod() { + _size = 0; + } + + const T &operator[](unsigned int ui) const { return _list[ui]; } + + void create(int p_size) { + _list.resize(p_size); + _size = 0; + } + void reset() { _size = 0; } + + void push_back(const T &val) { + while (true) { + if (_size < max_size()) { + _list.set(_size, val); + _size++; + return; + } + + grow(); + } + } + + int size() const { return _size; } + int max_size() const { return _list.size(); } + +private: + void grow() { + unsigned int new_max_size = _list.size() * 2; + if (!new_max_size) + new_max_size = 1; + _list.resize(new_max_size); + } + + Vector _list; + int _size; +}; + +// very simple non-growable array, that keeps track of the size of a 'unit' +// which can be cast to whatever vertex format FVF required, and is initially +// created with enough memory to hold the biggest FVF. +// This allows multiple FVFs to use the same array. +class RasterizerUnitArray { +public: + RasterizerUnitArray() { + _list = nullptr; + free(); + } + ~RasterizerUnitArray() { free(); } + + uint8_t *get_unit(unsigned int ui) { return &_list[ui * _unit_size_bytes]; } + const uint8_t *get_unit(unsigned int ui) const { return &_list[ui * _unit_size_bytes]; } + + int size() const { return _size; } + int max_size() const { return _max_size; } + int get_unit_size_bytes() const { return _unit_size_bytes; } + + void free() { + if (_list) { + memdelete_arr(_list); + _list = 0; + } + _size = 0; + _max_size = 0; + _max_size_bytes = 0; + _unit_size_bytes = 0; + } + + void create(int p_max_size_units, int p_max_unit_size_bytes) { + free(); + + _max_unit_size_bytes = p_max_unit_size_bytes; + _max_size = p_max_size_units; + _max_size_bytes = p_max_size_units * p_max_unit_size_bytes; + + if (_max_size_bytes) { + _list = memnew_arr(uint8_t, _max_size_bytes); + } + } + + void prepare(int p_unit_size_bytes) { + _unit_size_bytes = p_unit_size_bytes; + _size = 0; + } + + // several items at a time + uint8_t *request(int p_num_items = 1) { + int old_size = _size; + _size += p_num_items; + + if (_size <= _max_size) { + return get_unit(old_size); + } + + // revert + _size = old_size; + return nullptr; + } + +private: + uint8_t *_list; + int _size; // in units + int _max_size; // in units + int _max_size_bytes; + int _unit_size_bytes; + int _max_unit_size_bytes; +}; + +template +class RasterizerPooledList { + LocalVector list; + LocalVector freelist; + + // not all list members are necessarily used + int _used_size; + +public: + RasterizerPooledList() { + _used_size = 0; + } + + int estimate_memory_use() const { + return (list.size() * sizeof(T)) + (freelist.size() * sizeof(uint32_t)); + } + + const T &operator[](uint32_t p_index) const { + return list[p_index]; + } + T &operator[](uint32_t p_index) { + return list[p_index]; + } + + int size() const { return _used_size; } + + // returns the list id of the allocated item + uint32_t alloc() { + uint32_t id = 0; + _used_size++; + + if (freelist.size()) { + // pop from freelist + int new_size = freelist.size() - 1; + id = freelist[new_size]; + freelist.resize(new_size); + return id; + // return &list[r_id]; + } + + id = list.size(); + list.resize(id + 1); + return id; + // return &list[r_id]; + } + void free(const uint32_t &p_id) { + // should not be on free list already + CRASH_COND(p_id >= list.size()); + freelist.push_back(p_id); + _used_size--; + } +}; + +template +class RasterizerPooledIndirectList { +public: + const T &operator[](uint32_t p_index) const { + return *_list[p_index]; + } + T &operator[](uint32_t p_index) { + return *_list[p_index]; + } + + uint32_t alloc() { + uint32_t id = _list.alloc(); + _list[id] = memnew(T); + return id; + } + void free(const uint32_t &p_id) { + CRASH_COND(!_list[p_id]); + memdelete_notnull(_list[p_id]); + _list[p_id] = nullptr; + _list.free(p_id); + } + + ~RasterizerPooledIndirectList() { + // autodelete + for (int n = 0; n < _list.size(); n++) { + if (_list[n]) { + memdelete_notnull(_list[n]); + } + } + } + +private: + RasterizerPooledList _list; +}; + +#endif // RASTERIZER_ARRAY_H diff --git a/drivers/gles_common/rasterizer_asserts.h b/drivers/gles_common/rasterizer_asserts.h new file mode 100644 index 00000000000..dbc45035b2d --- /dev/null +++ b/drivers/gles_common/rasterizer_asserts.h @@ -0,0 +1,67 @@ +/*************************************************************************/ +/* rasterizer_asserts.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZER_ASSERTS_H +#define RASTERIZER_ASSERTS_H + +// For flow control checking, we want an easy way to apply asserts that occur in debug development builds only. +// This is enforced by outputting a warning which will fail CI checks if the define is set in a PR. +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) +// only uncomment this define for error checking in development, not in the main repository +// as these checks will slow things down in debug builds. +//#define RASTERIZER_EXTRA_CHECKS +#endif + +#ifdef RASTERIZER_EXTRA_CHECKS +#ifndef _MSC_VER +#warning do not define RASTERIZER_EXTRA_CHECKS in main repository builds +#endif +#define RAST_DEV_DEBUG_ASSERT(a) CRASH_COND(!(a)) +#else +#define RAST_DEV_DEBUG_ASSERT(a) +#endif + +// Also very useful, an assert check that only occurs in debug tools builds +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) +#define RAST_DEBUG_ASSERT(a) CRASH_COND(!(a)) +#else +#define RAST_DEBUG_ASSERT(a) +#endif + +// Thin wrapper around ERR_FAIL_COND to allow us to make it debug only +#ifdef DEBUG_ENABLED +#define RAST_FAIL_COND(m_cond) ERR_FAIL_COND(m_cond) +#else +#define RAST_FAIL_COND(m_cond) \ + if (m_cond) { \ + } +#endif + +#endif // RASTERIZER_ASSERTS_H diff --git a/drivers/gles_common/rasterizer_canvas_batcher.h b/drivers/gles_common/rasterizer_canvas_batcher.h new file mode 100644 index 00000000000..1836fd68d25 --- /dev/null +++ b/drivers/gles_common/rasterizer_canvas_batcher.h @@ -0,0 +1,3129 @@ +/*************************************************************************/ +/* rasterizer_canvas_batcher.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZER_CANVAS_BATCHER_H +#define RASTERIZER_CANVAS_BATCHER_H + +#include "core/os/os.h" +#include "core/templates/local_vector.h" +#include "rasterizer_array.h" +#include "rasterizer_asserts.h" +#include "rasterizer_storage_common.h" +#include "rasterizer_version.h" + +#ifdef GODOT_4 +#include "core/config/project_settings.h" +#include "servers/rendering/renderer_compositor.h" +#else +#include "core/project_settings.h" +#include "servers/visual/rasterizer.h" +#endif + +// We are using the curiously recurring template pattern +// https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern +// For static polymorphism. + +// This makes it super easy to access +// data / call funcs in the derived rasterizers from the base without writing and +// maintaining a boatload of virtual functions. +// In addition it assures that vtable will not be used and the function calls can be optimized, +// because it gives compile time static polymorphism. + +// These macros makes it simpler and less verbose to define (and redefine) the inline functions +// template preamble +#define T_PREAMBLE template +// class preamble +#define C_PREAMBLE RasterizerCanvasBatcher +// generic preamble +#define PREAMBLE(RET_T) \ + T_PREAMBLE \ + RET_T C_PREAMBLE + +template +class RasterizerCanvasBatcher { +public: + // used to determine whether we use hardware transform (none) + // software transform all verts, or software transform just a translate + // (no rotate or scale) + enum TransformMode { + TM_NONE, + TM_ALL, + TM_TRANSLATE, + }; + + // pod versions of vector and color and RID, need to be 32 bit for vertex format + struct BatchVector2 { + float x, y; + void set(float xx, float yy) { + x = xx; + y = yy; + } + void set(const Vector2 &p_o) { + x = p_o.x; + y = p_o.y; + } + void to(Vector2 &r_o) const { + r_o.x = x; + r_o.y = y; + } + }; + + struct BatchColor { + float r, g, b, a; + void set_white() { + r = 1.0f; + g = 1.0f; + b = 1.0f; + a = 1.0f; + } + void set(const Color &p_c) { + r = p_c.r; + g = p_c.g; + b = p_c.b; + a = p_c.a; + } + void set(float rr, float gg, float bb, float aa) { + r = rr; + g = gg; + b = bb; + a = aa; + } + bool operator==(const BatchColor &p_c) const { + return (r == p_c.r) && (g == p_c.g) && (b == p_c.b) && (a == p_c.a); + } + bool operator!=(const BatchColor &p_c) const { return (*this == p_c) == false; } + bool equals(const Color &p_c) const { + return (r == p_c.r) && (g == p_c.g) && (b == p_c.b) && (a == p_c.a); + } + const float *get_data() const { return &r; } + String to_string() const { + String sz = "{"; + const float *data = get_data(); + for (int c = 0; c < 4; c++) { + float f = data[c]; + int val = ((f * 255.0f) + 0.5f); + sz += String(Variant(val)) + " "; + } + sz += "}"; + return sz; + } + }; + + // simplest FVF - local or baked position + struct BatchVertex { + // must be 32 bit pod + BatchVector2 pos; + BatchVector2 uv; + }; + + // simple FVF but also incorporating baked color + struct BatchVertexColored : public BatchVertex { + // must be 32 bit pod + BatchColor col; + }; + + // if we are using normal mapping, we need light angles to be sent + struct BatchVertexLightAngled : public BatchVertexColored { + // must be pod + float light_angle; + }; + + // CUSTOM SHADER vertex formats. These are larger but will probably + // be needed with custom shaders in order to have the data accessible in the shader. + + // if we are using COLOR in vertex shader but not position (VERTEX) + struct BatchVertexModulated : public BatchVertexLightAngled { + BatchColor modulate; + }; + + struct BatchTransform { + BatchVector2 translate; + BatchVector2 basis[2]; + }; + + // last resort, specially for custom shader, we put everything possible into a huge FVF + // not very efficient, but better than no batching at all. + struct BatchVertexLarge : public BatchVertexModulated { + // must be pod + BatchTransform transform; + }; + + // Batch should be as small as possible, and ideally nicely aligned (is 32 bytes at the moment) + struct Batch { + RasterizerStorageCommon::BatchType type; // should be 16 bit + uint16_t batch_texture_id; + + // also item reference number + uint32_t first_command; + + // in the case of DEFAULT, this is num commands. + // with rects, is number of command and rects. + // with lines, is number of lines + uint32_t num_commands; + + // first vertex of this batch in the vertex lists + uint32_t first_vert; + + BatchColor color; + }; + + struct BatchTex { + enum TileMode : uint32_t { + TILE_OFF, + TILE_NORMAL, + TILE_FORCE_REPEAT, + }; + RID RID_texture; + RID RID_normal; + TileMode tile_mode; + BatchVector2 tex_pixel_size; + uint32_t flags; + }; + + // items in a list to be sorted prior to joining + struct BSortItem { + // have a function to keep as pod, rather than operator + void assign(const BSortItem &o) { + item = o.item; + z_index = o.z_index; + } + RendererCanvasRender::Item *item; + int z_index; + }; + + // batch item may represent 1 or more items + struct BItemJoined { + uint32_t first_item_ref; + uint32_t num_item_refs; + + Rect2 bounding_rect; + + // note the z_index may only be correct for the first of the joined item references + // this has implications for light culling with z ranged lights. + int16_t z_index; + + // these are defined in RasterizerStorageCommon::BatchFlags + uint16_t flags; + + // we are always splitting items with lots of commands, + // and items with unhandled primitives (default) + bool use_hardware_transform() const { return num_item_refs == 1; } + }; + + struct BItemRef { + RendererCanvasRender::Item *item; + Color final_modulate; + }; + + struct BLightRegion { + void reset() { + light_bitfield = 0; + shadow_bitfield = 0; + too_many_lights = false; + } + uint64_t light_bitfield; + uint64_t shadow_bitfield; + bool too_many_lights; // we can only do light region optimization if there are 64 or less lights + }; + + struct BatchData { + BatchData() { + reset_flush(); + reset_joined_item(); + + gl_vertex_buffer = 0; + gl_index_buffer = 0; + max_quads = 0; + vertex_buffer_size_units = 0; + vertex_buffer_size_bytes = 0; + index_buffer_size_units = 0; + index_buffer_size_bytes = 0; + + use_colored_vertices = false; + + settings_use_batching = false; + settings_max_join_item_commands = 0; + settings_colored_vertex_format_threshold = 0.0f; + settings_batch_buffer_num_verts = 0; + scissor_threshold_area = 0.0f; + joined_item_batch_flags = 0; + diagnose_frame = false; + next_diagnose_tick = 10000; + diagnose_frame_number = 9999999999; // some high number + join_across_z_indices = true; + settings_item_reordering_lookahead = 0; + + settings_use_batching_original_choice = false; + settings_flash_batching = false; + settings_diagnose_frame = false; + settings_scissor_lights = false; + settings_scissor_threshold = -1.0f; + settings_use_single_rect_fallback = false; + settings_use_software_skinning = true; + settings_ninepatch_mode = 0; // default + settings_light_max_join_items = 16; + + settings_uv_contract = false; + settings_uv_contract_amount = 0.0f; + + buffer_mode_batch_upload_send_null = true; + buffer_mode_batch_upload_flag_stream = false; + + stats_items_sorted = 0; + stats_light_items_joined = 0; + } + + // called for each joined item + void reset_joined_item() { + // noop but left in as a stub + } + + // called after each flush + void reset_flush() { + batches.reset(); + batch_textures.reset(); + + vertices.reset(); + light_angles.reset(); + vertex_colors.reset(); + vertex_modulates.reset(); + vertex_transforms.reset(); + + total_quads = 0; + total_verts = 0; + total_color_changes = 0; + + use_light_angles = false; + use_modulate = false; + use_large_verts = false; + fvf = RasterizerStorageCommon::FVF_REGULAR; + } + + unsigned int gl_vertex_buffer; + unsigned int gl_index_buffer; + + uint32_t max_quads; + uint32_t vertex_buffer_size_units; + uint32_t vertex_buffer_size_bytes; + uint32_t index_buffer_size_units; + uint32_t index_buffer_size_bytes; + + // small vertex FVF type - pos and UV. + // This will always be written to initially, but can be translated + // to larger FVFs if necessary. + RasterizerArray vertices; + + // extra data which can be stored during prefilling, for later translation to larger FVFs + RasterizerArray light_angles; + RasterizerArray vertex_colors; // these aren't usually used, but are for polys + RasterizerArray vertex_modulates; + RasterizerArray vertex_transforms; + + // instead of having a different buffer for each vertex FVF type + // we have a special array big enough for the biggest FVF + // which can have a changeable unit size, and reuse it. + RasterizerUnitArray unit_vertices; + + RasterizerArray batches; + RasterizerArray batches_temp; // used for translating to colored vertex batches + RasterizerArray_non_pod batch_textures; // the only reason this is non-POD is because of RIDs + + // SHOULD THESE BE IN FILLSTATE? + // flexible vertex format. + // all verts have pos and UV. + // some have color, some light angles etc. + RasterizerStorageCommon::FVF fvf; + bool use_colored_vertices; + bool use_light_angles; + bool use_modulate; + bool use_large_verts; + + // if the shader is using MODULATE, we prevent baking color so the final_modulate can + // be read in the shader. + // if the shader is reading VERTEX, we prevent baking vertex positions with extra matrices etc + // to prevent the read position being incorrect. + // These flags are defined in RasterizerStorageCommon::BatchFlags + uint32_t joined_item_batch_flags; + + RasterizerArray items_joined; + RasterizerArray item_refs; + + // items are sorted prior to joining + RasterizerArray sort_items; + + // new for Godot 4 .. the client outputs a linked list so we need to convert this + // to a linear array + LocalVector command_shortlist; + + // counts + int total_quads; + int total_verts; + + // we keep a record of how many color changes caused new batches + // if the colors are causing an excessive number of batches, we switch + // to alternate batching method and add color to the vertex format. + int total_color_changes; + + // measured in pixels, recalculated each frame + float scissor_threshold_area; + + // diagnose this frame, every nTh frame when settings_diagnose_frame is on + bool diagnose_frame; + String frame_string; + uint32_t next_diagnose_tick; + uint64_t diagnose_frame_number; + + // whether to join items across z_indices - this can interfere with z ranged lights, + // so has to be disabled in some circumstances + bool join_across_z_indices; + + // global settings + bool settings_use_batching; // the current use_batching (affected by flash) + bool settings_use_batching_original_choice; // the choice entered in project settings + bool settings_flash_batching; // for regression testing, flash between non-batched and batched renderer + bool settings_diagnose_frame; // print out batches to help optimize / regression test + int settings_max_join_item_commands; + float settings_colored_vertex_format_threshold; + int settings_batch_buffer_num_verts; + bool settings_scissor_lights; + float settings_scissor_threshold; // 0.0 to 1.0 + int settings_item_reordering_lookahead; + bool settings_use_single_rect_fallback; + bool settings_use_software_skinning; + int settings_light_max_join_items; + int settings_ninepatch_mode; + + // buffer orphaning modes + bool buffer_mode_batch_upload_send_null; + bool buffer_mode_batch_upload_flag_stream; + + // uv contraction + bool settings_uv_contract; + float settings_uv_contract_amount; + + // only done on diagnose frame + void reset_stats() { + stats_items_sorted = 0; + stats_light_items_joined = 0; + } + + // frame stats (just for monitoring and debugging) + int stats_items_sorted; + int stats_light_items_joined; + } bdata; + + struct FillState { + void reset_flush() { + // don't reset members that need to be preserved after flushing + // half way through a list of commands + curr_batch = 0; + batch_tex_id = -1; + texpixel_size = Vector2(1, 1); + contract_uvs = false; + + sequence_batch_type_flags = 0; + } + + void reset_joined_item(bool p_use_hardware_transform) { + reset_flush(); + use_hardware_transform = p_use_hardware_transform; + extra_matrix_sent = false; + } + + // for batching multiple types, we don't allow mixing RECTs / LINEs etc. + // using flags allows quicker rejection of sequences with different batch types + uint32_t sequence_batch_type_flags; + + Batch *curr_batch; + int batch_tex_id; + bool use_hardware_transform; + bool contract_uvs; + Vector2 texpixel_size; + Color final_modulate; + TransformMode transform_mode; + TransformMode orig_transform_mode; + + // support for extra matrices + bool extra_matrix_sent; // whether sent on this item (in which case sofware transform can't be used untl end of item) + int transform_extra_command_number_p1; // plus one to allow fast checking against zero + Transform2D transform_combined; // final * extra + }; + + // used during try_join + struct RenderItemState { + RenderItemState() { reset(); } + void reset() { + current_clip = nullptr; + shader_cache = nullptr; + rebind_shader = true; + prev_use_skeleton = false; + last_blend_mode = -1; + canvas_last_material = RID(); + item_group_z = 0; + item_group_light = nullptr; + final_modulate = Color(-1.0, -1.0, -1.0, -1.0); // just something unlikely + + joined_item_batch_type_flags_curr = 0; + joined_item_batch_type_flags_prev = 0; + + joined_item = nullptr; + } + + RendererCanvasRender::Item *current_clip; + typename T_STORAGE::Shader *shader_cache; + bool rebind_shader; + bool prev_use_skeleton; + bool prev_distance_field; + int last_blend_mode; + RID canvas_last_material; + Color final_modulate; + + // used for joining items only + BItemJoined *joined_item; + bool join_batch_break; + BLightRegion light_region; + + // we need some logic to prevent joining items that have vastly different batch types + // these are defined in RasterizerStorageCommon::BatchTypeFlags + uint32_t joined_item_batch_type_flags_curr; + uint32_t joined_item_batch_type_flags_prev; + + // 'item group' is data over a single call to canvas_render_items + int item_group_z; + Color item_group_modulate; + RendererCanvasRender::Light *item_group_light; + Transform2D item_group_base_transform; + } _render_item_state; + + bool use_nvidia_rect_workaround; + + ////////////////////////////////////////////////////////////////////////////// + // End of structs used by the batcher. Beginning of funcs. +private: + // curiously recurring template pattern - allows access to functions in the DERIVED class + // this is kind of like using virtual functions but more efficient as they are resolved at compile time + T_STORAGE *get_storage() { return static_cast(this)->storage; } + const T_STORAGE *get_storage() const { return static_cast(this)->storage; } + T *get_this() { return static_cast(this); } + const T *get_this() const { return static_cast(this); } + +protected: + // main functions called from the rasterizer canvas + void batch_constructor(); + void batch_initialize(); + + void batch_canvas_begin(); + void batch_canvas_end(); + void batch_canvas_render_items_begin(const Color &p_modulate, RendererCanvasRender::Light *p_light, const Transform2D &p_base_transform); + void batch_canvas_render_items_end(); + void batch_canvas_render_items(RendererCanvasRender::Item *p_item_list, int p_z, const Color &p_modulate, RendererCanvasRender::Light *p_light, const Transform2D &p_base_transform); + + // recording and sorting items from the initial pass + void record_items(RendererCanvasRender::Item *p_item_list, int p_z); + void join_sorted_items(); + void sort_items(); + bool _sort_items_match(const BSortItem &p_a, const BSortItem &p_b) const; + bool sort_items_from(int p_start); + + // joining logic + bool _disallow_item_join_if_batch_types_too_different(RenderItemState &r_ris, uint32_t btf_allowed); + bool _detect_item_batch_break(RenderItemState &r_ris, RendererCanvasRender::Item *p_ci, bool &r_batch_break); + + // drives the loop filling batches and flushing + void render_joined_item_commands(const BItemJoined &p_bij, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material, bool p_lit); + +private: + // flush once full or end of joined item + void flush_render_batches(RendererCanvasRender::Item *p_first_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material, uint32_t p_sequence_batch_type_flags); + + // a single joined item can contain multiple itemrefs, and thus create lots of batches +#ifdef GODOT_3 + bool prefill_joined_item(FillState &r_fill_state, int &r_command_start, RendererCanvasRender::Item *p_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material); +#else + // command start given a separate name to make easier to tell apart godot 3 and 4 + bool prefill_joined_item(FillState &r_fill_state, RendererCanvasRender::Item::Command **r_first_command, RendererCanvasRender::Item *p_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material); +#endif + + // prefilling different types of batch + + // default batch is an 'unhandled' legacy type batch that will be drawn with the legacy path, + // all other batches are accelerated. + void _prefill_default_batch(FillState &r_fill_state, int p_command_num, const RendererCanvasRender::Item &p_item); + + // accelerated batches +#ifdef GODOT_3 + bool _prefill_line(RendererCanvasRender::Item::GD_COMMAND_LINE *p_line, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate); + template + bool _prefill_ninepatch(RendererCanvasRender::Item::CommandNinePatch *p_np, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate); + template + bool _prefill_polygon(RendererCanvasRender::Item::CommandPolygon *p_poly, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate); + template +#endif + bool _prefill_rect(RendererCanvasRender::Item::CommandRect *rect, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item::Command *const *commands, RendererCanvasRender::Item *p_item, bool multiply_final_modulate); + + // dealing with textures + int _batch_find_or_create_tex(const RID &p_texture, const RID &p_normal, bool p_tile, int p_previous_match); + +protected: + // legacy support for non batched mode + void _legacy_canvas_item_render_commands(RendererCanvasRender::Item *p_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material); + + // light scissoring + bool _light_scissor_begin(const Rect2 &p_item_rect, const Transform2D &p_light_xform, const Rect2 &p_light_rect) const; + bool _light_find_intersection(const Rect2 &p_item_rect, const Transform2D &p_light_xform, const Rect2 &p_light_rect, Rect2 &r_cliprect) const; + void _calculate_scissor_threshold_area(); + +private: + // translating vertex formats prior to rendering + void _translate_batches_to_vertex_colored_FVF(); + template + void _translate_batches_to_larger_FVF(uint32_t p_sequence_batch_type_flags); + +protected: + // accessory funcs + void _software_transform_vertex(BatchVector2 &r_v, const Transform2D &p_tr) const; + void _software_transform_vertex(Vector2 &r_v, const Transform2D &p_tr) const; + TransformMode _find_transform_mode(const Transform2D &p_tr) const { + // decided whether to do translate only for software transform + if ((p_tr.elements[0].x == 1.0f) && + (p_tr.elements[0].y == 0.0f) && + (p_tr.elements[1].x == 0.0f) && + (p_tr.elements[1].y == 1.0f)) { + return TM_TRANSLATE; + } + + return TM_ALL; + } + +#ifdef GODOT_3 + bool _software_skin_poly(RendererCanvasRender::Item::CommandPolygon *p_poly, RendererCanvasRender::Item *p_item, BatchVertex *bvs, BatchColor *vertex_colors, const FillState &p_fill_state, const BatchColor *p_precalced_colors); +#endif + + typename T_STORAGE::Texture *_get_canvas_texture(const RID &p_texture) const { + if (p_texture.is_valid()) { + typename T_STORAGE::Texture *texture = get_storage()->texture_owner.getornull(p_texture); + + if (texture) { + return texture->get_ptr(); + } + } + + return 0; + } + +public: + Batch *_batch_request_new(bool p_blank = true) { + Batch *batch = bdata.batches.request(); + if (!batch) { + // grow the batches + bdata.batches.grow(); + + // and the temporary batches (used for color verts) + bdata.batches_temp.reset(); + bdata.batches_temp.grow(); + + // this should always succeed after growing + batch = bdata.batches.request(); + RAST_DEBUG_ASSERT(batch); + } + + if (p_blank) + memset(batch, 0, sizeof(Batch)); + + return batch; + } + + BatchVertex *_batch_vertex_request_new() { + return bdata.vertices.request(); + } + +protected: +#ifdef GODOT_4 + int godot4_commands_count(RendererCanvasRender::Item::Command *p_comm) const { + int count = 0; + while (p_comm) { + count++; + p_comm = p_comm->next; + } + return count; + } + + unsigned int godot4_commands_to_vector(RendererCanvasRender::Item::Command *p_comm, LocalVector &p_list) { + p_list.clear(); + while (p_comm) { + p_list.push_back(p_comm); + p_comm = p_comm->next; + } + return p_list.size(); + } +#endif + + // no need to compile these in in release, they are unneeded outside the editor and only add to executable size +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) +#include "batch_diagnose.inc" +#endif +}; + +PREAMBLE(void)::batch_canvas_begin() { + // diagnose_frame? + bdata.frame_string = ""; // just in case, always set this as we don't want a string leak in release... +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + if (bdata.settings_diagnose_frame) { + bdata.diagnose_frame = false; + + uint32_t tick = OS::get_singleton()->get_ticks_msec(); + uint64_t frame = Engine::get_singleton()->get_frames_drawn(); + + if (tick >= bdata.next_diagnose_tick) { + bdata.next_diagnose_tick = tick + 10000; + + // the plus one is prevent starting diagnosis half way through frame + bdata.diagnose_frame_number = frame + 1; + } + + if (frame == bdata.diagnose_frame_number) { + bdata.diagnose_frame = true; + bdata.reset_stats(); + } + + if (bdata.diagnose_frame) { + bdata.frame_string = "canvas_begin FRAME " + itos(frame) + "\n"; + } + } +#endif +} + +PREAMBLE(void)::batch_canvas_end() { +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + if (bdata.diagnose_frame) { + bdata.frame_string += "canvas_end\n"; + if (bdata.stats_items_sorted) { + bdata.frame_string += "\titems reordered: " + itos(bdata.stats_items_sorted) + "\n"; + } + if (bdata.stats_light_items_joined) { + bdata.frame_string += "\tlight items joined: " + itos(bdata.stats_light_items_joined) + "\n"; + } + + print_line(bdata.frame_string); + } +#endif +} + +PREAMBLE(void)::batch_canvas_render_items_begin(const Color &p_modulate, RendererCanvasRender::Light *p_light, const Transform2D &p_base_transform) { + // if we are debugging, flash each frame between batching renderer and old version to compare for regressions + if (bdata.settings_flash_batching) { + if ((Engine::get_singleton()->get_frames_drawn() % 2) == 0) + bdata.settings_use_batching = true; + else + bdata.settings_use_batching = false; + } + + if (!bdata.settings_use_batching) { + return; + } + + // this only needs to be done when screen size changes, but this should be + // infrequent enough + _calculate_scissor_threshold_area(); + + // set up render item state for all the z_indexes (this is common to all z_indexes) + _render_item_state.reset(); + _render_item_state.item_group_modulate = p_modulate; + _render_item_state.item_group_light = p_light; + _render_item_state.item_group_base_transform = p_base_transform; + _render_item_state.light_region.reset(); + + // batch break must be preserved over the different z indices, + // to prevent joining to an item on a previous index if not allowed + _render_item_state.join_batch_break = false; + + // whether to join across z indices depends on whether there are z ranged lights. + // joined z_index items can be wrongly classified with z ranged lights. + bdata.join_across_z_indices = true; + + int light_count = 0; + while (p_light) { + light_count++; + + if ((p_light->z_min != GD_VS::CANVAS_ITEM_Z_MIN) || (p_light->z_max != GD_VS::CANVAS_ITEM_Z_MAX)) { + // prevent joining across z indices. This would have caused visual regressions + bdata.join_across_z_indices = false; + } + + p_light = p_light->next_ptr; + } + + // can't use the light region bitfield if there are too many lights + // hopefully most games won't blow this limit.. + // if they do they will work but it won't batch join items just in case + if (light_count > 64) { + _render_item_state.light_region.too_many_lights = true; + } +} + +PREAMBLE(void)::batch_canvas_render_items_end() { + if (!bdata.settings_use_batching) { + return; + } + + join_sorted_items(); + +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + if (bdata.diagnose_frame) { + bdata.frame_string += "items\n"; + } +#endif + + // batching render is deferred until after going through all the z_indices, joining all the items + get_this()->canvas_render_items_implementation(0, 0, _render_item_state.item_group_modulate, + _render_item_state.item_group_light, + _render_item_state.item_group_base_transform); + + bdata.items_joined.reset(); + bdata.item_refs.reset(); + bdata.sort_items.reset(); +} + +PREAMBLE(void)::batch_canvas_render_items(RendererCanvasRender::Item *p_item_list, int p_z, const Color &p_modulate, RendererCanvasRender::Light *p_light, const Transform2D &p_base_transform) { + // stage 1 : join similar items, so that their state changes are not repeated, + // and commands from joined items can be batched together + if (bdata.settings_use_batching) { + record_items(p_item_list, p_z); + return; + } + + // only legacy renders at this stage, batched renderer doesn't render until canvas_render_items_end() + get_this()->canvas_render_items_implementation(p_item_list, p_z, p_modulate, p_light, p_base_transform); +} + +// Default batches will not occur in software transform only items +// EXCEPT IN THE CASE OF SINGLE RECTS (and this may well not occur, check the logic in prefill_join_item TYPE_RECT) +// but can occur where transform commands have been sent during hardware batch +PREAMBLE(void)::_prefill_default_batch(FillState &r_fill_state, int p_command_num, const RendererCanvasRender::Item &p_item) { + if (r_fill_state.curr_batch->type == RasterizerStorageCommon::BT_DEFAULT) { + // don't need to flush an extra transform command? + if (!r_fill_state.transform_extra_command_number_p1) { + // another default command, just add to the existing batch + r_fill_state.curr_batch->num_commands++; + } else { +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + if (r_fill_state.transform_extra_command_number_p1 != p_command_num) { + WARN_PRINT_ONCE("_prefill_default_batch : transform_extra_command_number_p1 != p_command_num"); + } +#endif + // if the first member of the batch is a transform we have to be careful + if (!r_fill_state.curr_batch->num_commands) { + // there can be leading useless extra transforms (sometimes happens with debug collision polys) + // we need to rejig the first_command for the first useful transform + r_fill_state.curr_batch->first_command += r_fill_state.transform_extra_command_number_p1 - 1; + } + + // we do have a pending extra transform command to flush + // either the extra transform is in the prior command, or not, in which case we need 2 batches + r_fill_state.curr_batch->num_commands += 2; + + r_fill_state.transform_extra_command_number_p1 = 0; // mark as sent + r_fill_state.extra_matrix_sent = true; + + // the original mode should always be hardware transform .. + // test this assumption + //CRASH_COND(r_fill_state.orig_transform_mode != TM_NONE); + r_fill_state.transform_mode = r_fill_state.orig_transform_mode; + + // do we need to restore anything else? + } + } else { + // end of previous different type batch, so start new default batch + + // first consider whether there is a dirty extra matrix to send + if (r_fill_state.transform_extra_command_number_p1) { + // get which command the extra is in, and blank all the records as it no longer is stored CPU side + int extra_command = r_fill_state.transform_extra_command_number_p1 - 1; // plus 1 based + r_fill_state.transform_extra_command_number_p1 = 0; + r_fill_state.extra_matrix_sent = true; + + // send the extra to the GPU in a batch + r_fill_state.curr_batch = _batch_request_new(); + r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_DEFAULT; + r_fill_state.curr_batch->first_command = extra_command; + r_fill_state.curr_batch->num_commands = 1; + + // revert to the original transform mode + // e.g. go back to NONE if we were in hardware transform mode + r_fill_state.transform_mode = r_fill_state.orig_transform_mode; + + // reset the original transform if we are going back to software mode, + // because the extra is now done on the GPU... + // (any subsequent extras are sent directly to the GPU, no deferring) + if (r_fill_state.orig_transform_mode != TM_NONE) { + r_fill_state.transform_combined = p_item.final_transform; + } + + // can possibly combine batch with the next one in some cases + // this is more efficient than having an extra batch especially for the extra + if ((extra_command + 1) == p_command_num) { + r_fill_state.curr_batch->num_commands = 2; + return; + } + } + + // start default batch + r_fill_state.curr_batch = _batch_request_new(); + r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_DEFAULT; + r_fill_state.curr_batch->first_command = p_command_num; + r_fill_state.curr_batch->num_commands = 1; + } +} + +PREAMBLE(int)::_batch_find_or_create_tex(const RID &p_texture, const RID &p_normal, bool p_tile, int p_previous_match) { + // optimization .. in 99% cases the last matched value will be the same, so no need to traverse the list + if (p_previous_match > 0) // if it is zero, it will get hit first in the linear search anyway + { + const BatchTex &batch_texture = bdata.batch_textures[p_previous_match]; + + // note for future reference, if RID implementation changes, this could become more expensive + if ((batch_texture.RID_texture == p_texture) && (batch_texture.RID_normal == p_normal)) { + // tiling mode must also match + bool tiles = batch_texture.tile_mode != BatchTex::TILE_OFF; + + if (tiles == p_tile) + // match! + return p_previous_match; + } + } + + // not the previous match .. we will do a linear search ... slower, but should happen + // not very often except with non-batchable runs, which are going to be slow anyway + // n.b. could possibly be replaced later by a fast hash table + for (int n = 0; n < bdata.batch_textures.size(); n++) { + const BatchTex &batch_texture = bdata.batch_textures[n]; + if ((batch_texture.RID_texture == p_texture) && (batch_texture.RID_normal == p_normal)) { + // tiling mode must also match + bool tiles = batch_texture.tile_mode != BatchTex::TILE_OFF; + + if (tiles == p_tile) + // match! + return n; + } + } + + // pushing back from local variable .. not ideal but has to use a Vector because non pod + // due to RIDs + BatchTex new_batch_tex; + new_batch_tex.RID_texture = p_texture; + new_batch_tex.RID_normal = p_normal; + + // get the texture + typename T_STORAGE::Texture *texture = _get_canvas_texture(p_texture); + + if (texture) { + // special case, there can be textures with no width or height + int w = texture->width; + int h = texture->height; + + if (!w || !h) { + w = 1; + h = 1; + } + + new_batch_tex.tex_pixel_size.x = 1.0 / w; + new_batch_tex.tex_pixel_size.y = 1.0 / h; + new_batch_tex.flags = texture->flags; + } else { + // maybe doesn't need doing... + new_batch_tex.tex_pixel_size.x = 1.0f; + new_batch_tex.tex_pixel_size.y = 1.0f; + new_batch_tex.flags = 0; + } + + if (p_tile) { + if (texture) { + // default + new_batch_tex.tile_mode = BatchTex::TILE_NORMAL; + + // no hardware support for non power of 2 tiling + if (!get_storage()->config.support_npot_repeat_mipmap) { + if (next_power_of_2(texture->alloc_width) != (unsigned int)texture->alloc_width && next_power_of_2(texture->alloc_height) != (unsigned int)texture->alloc_height) { + new_batch_tex.tile_mode = BatchTex::TILE_FORCE_REPEAT; + } + } + } else { + // this should not happen? + new_batch_tex.tile_mode = BatchTex::TILE_OFF; + } + } else { + new_batch_tex.tile_mode = BatchTex::TILE_OFF; + } + + // push back + bdata.batch_textures.push_back(new_batch_tex); + + return bdata.batch_textures.size() - 1; +} + +PREAMBLE(void)::batch_constructor() { + bdata.settings_use_batching = false; + +#ifdef GLES_OVER_GL + use_nvidia_rect_workaround = GLOBAL_GET("rendering/quality/2d/use_nvidia_rect_flicker_workaround"); +#else + // Not needed (a priori) on GLES devices + use_nvidia_rect_workaround = false; +#endif +} + +PREAMBLE(void)::batch_initialize() { +#define BATCHING_LOAD_PROJECT_SETTINGS + +#ifdef BATCHING_LOAD_PROJECT_SETTINGS + bdata.settings_use_batching = GLOBAL_GET("rendering/batching/options/use_batching"); + bdata.settings_max_join_item_commands = GLOBAL_GET("rendering/batching/parameters/max_join_item_commands"); + bdata.settings_colored_vertex_format_threshold = GLOBAL_GET("rendering/batching/parameters/colored_vertex_format_threshold"); + bdata.settings_item_reordering_lookahead = GLOBAL_GET("rendering/batching/parameters/item_reordering_lookahead"); + bdata.settings_light_max_join_items = GLOBAL_GET("rendering/batching/lights/max_join_items"); + bdata.settings_use_single_rect_fallback = GLOBAL_GET("rendering/batching/options/single_rect_fallback"); + bdata.settings_use_software_skinning = GLOBAL_GET("rendering/quality/2d/use_software_skinning"); + bdata.settings_ninepatch_mode = GLOBAL_GET("rendering/quality/2d/ninepatch_mode"); + + // alternatively only enable uv contract if pixel snap in use, + // but with this enable bool, it should not be necessary + bdata.settings_uv_contract = GLOBAL_GET("rendering/batching/precision/uv_contract"); + bdata.settings_uv_contract_amount = (float)GLOBAL_GET("rendering/batching/precision/uv_contract_amount") / 1000000.0f; + + // we can use the threshold to determine whether to turn scissoring off or on + bdata.settings_scissor_threshold = GLOBAL_GET("rendering/batching/lights/scissor_area_threshold"); +#endif + + if (bdata.settings_scissor_threshold > 0.999f) { + bdata.settings_scissor_lights = false; + } else { + bdata.settings_scissor_lights = true; + + // apply power of 4 relationship for the area, as most of the important changes + // will be happening at low values of scissor threshold + bdata.settings_scissor_threshold *= bdata.settings_scissor_threshold; + bdata.settings_scissor_threshold *= bdata.settings_scissor_threshold; + } + + // The sweet spot on my desktop for cache is actually smaller than the max, and this + // is the default. This saves memory too so we will use it for now, needs testing to see whether this varies according + // to device / platform. +#ifdef BATCHING_LOAD_PROJECT_SETTINGS + bdata.settings_batch_buffer_num_verts = GLOBAL_GET("rendering/batching/parameters/batch_buffer_size"); + + // override the use_batching setting in the editor + // (note that if the editor can't start, you can't change the use_batching project setting!) + if (Engine::get_singleton()->is_editor_hint()) { + bool use_in_editor = GLOBAL_GET("rendering/batching/options/use_batching_in_editor"); + bdata.settings_use_batching = use_in_editor; + + // fix some settings in the editor, as the performance not worth the risk + bdata.settings_use_single_rect_fallback = false; + } +#endif + + // if we are using batching, we will purposefully disable the nvidia workaround. + // This is because the only reason to use the single rect fallback is the approx 2x speed + // of the uniform drawing technique. If we used nvidia workaround, speed would be + // approx equal to the batcher drawing technique (indexed primitive + VB). + if (bdata.settings_use_batching) { + use_nvidia_rect_workaround = false; + } + + // For debugging, if flash is set in project settings, it will flash on alternate frames + // between the non-batched renderer and the batched renderer, + // in order to find regressions. + // This should not be used except during development. + // make a note of the original choice in case we are flashing on and off the batching + bdata.settings_use_batching_original_choice = bdata.settings_use_batching; + +#ifdef BATCHING_LOAD_PROJECT_SETTINGS + bdata.settings_flash_batching = GLOBAL_GET("rendering/batching/debug/flash_batching"); +#endif + if (!bdata.settings_use_batching) { + // no flash when batching turned off + bdata.settings_flash_batching = false; + } + + // frame diagnosis. print out the batches every nth frame + bdata.settings_diagnose_frame = false; + if (!Engine::get_singleton()->is_editor_hint() && bdata.settings_use_batching) { +#ifdef BATCHING_LOAD_PROJECT_SETTINGS + bdata.settings_diagnose_frame = GLOBAL_GET("rendering/batching/debug/diagnose_frame"); +#endif + } + + // the maximum num quads in a batch is limited by GLES2. We can have only 16 bit indices, + // which means we can address a vertex buffer of max size 65535. 4 vertices are needed per quad. + + // Note this determines the memory use by the vertex buffer vector. max quads (65536/4)-1 + // but can be reduced to save memory if really required (will result in more batches though) + const int max_possible_quads = (65536 / 4) - 1; + const int min_possible_quads = 8; // some reasonable small value + + // value from project settings + int max_quads = bdata.settings_batch_buffer_num_verts / 4; + + // sanity checks + max_quads = CLAMP(max_quads, min_possible_quads, max_possible_quads); + bdata.settings_max_join_item_commands = CLAMP(bdata.settings_max_join_item_commands, 0, 65535); + bdata.settings_colored_vertex_format_threshold = CLAMP(bdata.settings_colored_vertex_format_threshold, 0.0f, 1.0f); + bdata.settings_scissor_threshold = CLAMP(bdata.settings_scissor_threshold, 0.0f, 1.0f); + bdata.settings_light_max_join_items = CLAMP(bdata.settings_light_max_join_items, 0, 65535); + bdata.settings_item_reordering_lookahead = CLAMP(bdata.settings_item_reordering_lookahead, 0, 65535); + + // allow user to override the api usage techniques using project settings + // bdata.buffer_mode_batch_upload_send_null = GLOBAL_GET("rendering/options/api_usage_batching/send_null"); + // bdata.buffer_mode_batch_upload_flag_stream = GLOBAL_GET("rendering/options/api_usage_batching/flag_stream"); + + // for debug purposes, output a string with the batching options + String batching_options_string = "OpenGL ES Batching: "; + if (bdata.settings_use_batching) { + batching_options_string += "ON"; + + if (OS::get_singleton()->is_stdout_verbose()) { + batching_options_string += "\n\tOPTIONS\n"; + batching_options_string += "\tmax_join_item_commands " + itos(bdata.settings_max_join_item_commands) + "\n"; + batching_options_string += "\tcolored_vertex_format_threshold " + String(Variant(bdata.settings_colored_vertex_format_threshold)) + "\n"; + batching_options_string += "\tbatch_buffer_size " + itos(bdata.settings_batch_buffer_num_verts) + "\n"; + batching_options_string += "\tlight_scissor_area_threshold " + String(Variant(bdata.settings_scissor_threshold)) + "\n"; + + batching_options_string += "\titem_reordering_lookahead " + itos(bdata.settings_item_reordering_lookahead) + "\n"; + batching_options_string += "\tlight_max_join_items " + itos(bdata.settings_light_max_join_items) + "\n"; + batching_options_string += "\tsingle_rect_fallback " + String(Variant(bdata.settings_use_single_rect_fallback)) + "\n"; + + batching_options_string += "\tdebug_flash " + String(Variant(bdata.settings_flash_batching)) + "\n"; + batching_options_string += "\tdiagnose_frame " + String(Variant(bdata.settings_diagnose_frame)); + } + + print_line(batching_options_string); + } + + // special case, for colored vertex format threshold. + // as the comparison is >=, we want to be able to totally turn on or off + // conversion to colored vertex format at the extremes, so we will force + // 1.0 to be just above 1.0 + if (bdata.settings_colored_vertex_format_threshold > 0.995f) { + bdata.settings_colored_vertex_format_threshold = 1.01f; + } + + // save memory when batching off + if (!bdata.settings_use_batching) { + max_quads = 0; + } + + uint32_t sizeof_batch_vert = sizeof(BatchVertex); + + bdata.max_quads = max_quads; + + // 4 verts per quad + bdata.vertex_buffer_size_units = max_quads * 4; + + // the index buffer can be longer than 65535, only the indices need to be within this range + bdata.index_buffer_size_units = max_quads * 6; + + const int max_verts = bdata.vertex_buffer_size_units; + + // this comes out at approx 64K for non-colored vertex buffer, and 128K for colored vertex buffer + bdata.vertex_buffer_size_bytes = max_verts * sizeof_batch_vert; + bdata.index_buffer_size_bytes = bdata.index_buffer_size_units * 2; // 16 bit inds + + // create equal number of normal and (max) unit sized verts (as the normal may need to be translated to a larger FVF) + bdata.vertices.create(max_verts); // 512k + bdata.unit_vertices.create(max_verts, sizeof(BatchVertexLarge)); + + // extra data per vert needed for larger FVFs + bdata.light_angles.create(max_verts); + bdata.vertex_colors.create(max_verts); + bdata.vertex_modulates.create(max_verts); + bdata.vertex_transforms.create(max_verts); + + // num batches will be auto increased dynamically if required + bdata.batches.create(1024); + bdata.batches_temp.create(bdata.batches.max_size()); + + // batch textures can also be increased dynamically + bdata.batch_textures.create(32); +} + +PREAMBLE(bool)::_light_scissor_begin(const Rect2 &p_item_rect, const Transform2D &p_light_xform, const Rect2 &p_light_rect) const { + float area_item = p_item_rect.size.x * p_item_rect.size.y; // double check these are always positive + + // quick reject .. the area of pixels saved can never be more than the area of the item + if (area_item < bdata.scissor_threshold_area) { + return false; + } + + Rect2 cliprect; + if (!_light_find_intersection(p_item_rect, p_light_xform, p_light_rect, cliprect)) { + // should not really occur .. but just in case + cliprect = Rect2(0, 0, 0, 0); + } else { + // some conditions not to scissor + // determine the area (fill rate) that will be saved + float area_cliprect = cliprect.size.x * cliprect.size.y; + float area_saved = area_item - area_cliprect; + + // if area saved is too small, don't scissor + if (area_saved < bdata.scissor_threshold_area) { + return false; + } + } + + int rh = get_storage()->frame.current_rt->height; + + int y = rh - (cliprect.position.y + cliprect.size.y); +#ifdef GODOT_3 + if (get_storage()->frame.current_rt->flags[RendererStorage::RENDER_TARGET_VFLIP]) + y = cliprect.position.y; +#endif + get_this()->gl_enable_scissor(cliprect.position.x, y, cliprect.size.width, cliprect.size.height); + + return true; +} + +PREAMBLE(bool)::_light_find_intersection(const Rect2 &p_item_rect, const Transform2D &p_light_xform, const Rect2 &p_light_rect, Rect2 &r_cliprect) const { + // transform light to world space (note this is done in the earlier intersection test, so could + // be made more efficient) + Vector2 pts[4] = { + p_light_xform.xform(p_light_rect.position), + p_light_xform.xform(Vector2(p_light_rect.position.x + p_light_rect.size.x, p_light_rect.position.y)), + p_light_xform.xform(Vector2(p_light_rect.position.x, p_light_rect.position.y + p_light_rect.size.y)), + p_light_xform.xform(Vector2(p_light_rect.position.x + p_light_rect.size.x, p_light_rect.position.y + p_light_rect.size.y)), + }; + + // calculate the light bound rect in world space + Rect2 lrect(pts[0].x, pts[0].y, 0, 0); + for (int n = 1; n < 4; n++) { + lrect.expand_to(pts[n]); + } + + // intersection between the 2 rects + // they should probably always intersect, because of earlier check, but just in case... + if (!p_item_rect.intersects(lrect)) + return false; + + // note this does almost the same as Rect2.clip but slightly more efficient for our use case + r_cliprect.position.x = MAX(p_item_rect.position.x, lrect.position.x); + r_cliprect.position.y = MAX(p_item_rect.position.y, lrect.position.y); + + Point2 item_rect_end = p_item_rect.position + p_item_rect.size; + Point2 lrect_end = lrect.position + lrect.size; + + r_cliprect.size.x = MIN(item_rect_end.x, lrect_end.x) - r_cliprect.position.x; + r_cliprect.size.y = MIN(item_rect_end.y, lrect_end.y) - r_cliprect.position.y; + + return true; +} + +PREAMBLE(void)::_calculate_scissor_threshold_area() { + if (!bdata.settings_scissor_lights) { + return; + } + + // scissor area threshold is 0.0 to 1.0 in the settings for ease of use. + // we need to translate to an absolute area to determine quickly whether + // to scissor. + if (bdata.settings_scissor_threshold < 0.0001f) { + bdata.scissor_threshold_area = -1.0f; // will always pass + } else { + // in pixels + int w = get_storage()->frame.current_rt->width; + int h = get_storage()->frame.current_rt->height; + + int screen_area = w * h; + + bdata.scissor_threshold_area = bdata.settings_scissor_threshold * screen_area; + } +} + +#ifdef GODOT_3 +PREAMBLE(bool)::_prefill_line(RendererCanvasRender::Item::GD_COMMAND_LINE *p_line, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate) { + bool change_batch = false; + + // we have separate batch types for non and anti aliased lines. + // You can't batch the different types together. + RasterizerStorageCommon::BatchType line_batch_type = RasterizerStorageCommon::BT_LINE; + uint32_t line_batch_flags = RasterizerStorageCommon::BTF_LINE; +#ifdef GLES_OVER_GL + if (p_line->antialiased) { + line_batch_type = RasterizerStorageCommon::BT_LINE_AA; + line_batch_flags = RasterizerStorageCommon::BTF_LINE_AA; + } +#endif + + // conditions for creating a new batch + if (r_fill_state.curr_batch->type != line_batch_type) { + if (r_fill_state.sequence_batch_type_flags & (~line_batch_flags)) { + // don't allow joining to a different sequence type + r_command_start = command_num; + return true; + } + r_fill_state.sequence_batch_type_flags |= line_batch_flags; + + change_batch = true; + } + + // get the baked line color + Color col = p_line->color; + + if (multiply_final_modulate) + col *= r_fill_state.final_modulate; + + BatchColor bcol; + bcol.set(col); + + // if the color has changed we need a new batch + // (only single color line batches supported so far) + if (r_fill_state.curr_batch->color != bcol) + change_batch = true; + + // not sure if needed + r_fill_state.batch_tex_id = -1; + + // try to create vertices BEFORE creating a batch, + // because if the vertex buffer is full, we need to finish this + // function, draw what we have so far, and then start a new set of batches + + // request multiple vertices at a time, this is more efficient + BatchVertex *bvs = bdata.vertices.request(2); + if (!bvs) { + // run out of space in the vertex buffer .. finish this function and draw what we have so far + // return where we got to + r_command_start = command_num; + return true; + } + + if (change_batch) { + // open new batch (this should never fail, it dynamically grows) + r_fill_state.curr_batch = _batch_request_new(false); + + r_fill_state.curr_batch->type = line_batch_type; + r_fill_state.curr_batch->color = bcol; + r_fill_state.curr_batch->batch_texture_id = -1; + r_fill_state.curr_batch->first_command = command_num; + r_fill_state.curr_batch->num_commands = 1; + //r_fill_state.curr_batch->first_quad = bdata.total_quads; + r_fill_state.curr_batch->first_vert = bdata.total_verts; + } else { + // we could alternatively do the count when closing a batch .. perhaps more efficient + r_fill_state.curr_batch->num_commands++; + } + + // fill the geometry + Vector2 from = p_line->from; + Vector2 to = p_line->to; + + if (r_fill_state.transform_mode != TM_NONE) { + _software_transform_vertex(from, r_fill_state.transform_combined); + _software_transform_vertex(to, r_fill_state.transform_combined); + } + + bvs[0].pos.set(from); + bvs[0].uv.set(0, 0); // may not be necessary + bvs[1].pos.set(to); + bvs[1].uv.set(0, 0); + + bdata.total_verts += 2; + + return false; +} +#endif // godot 3 + +//unsigned int _ninepatch_apply_tiling_modes(RendererCanvasRender::Item::CommandNinePatch *p_np, Rect2 &r_source) { +// unsigned int rect_flags = 0; + +// switch (p_np->axis_x) { +// default: +// break; +// case VisualServer::NINE_PATCH_TILE: { +// r_source.size.x = p_np->rect.size.x; +// rect_flags = RendererCanvasRender::CANVAS_RECT_TILE; +// } break; +// case VisualServer::NINE_PATCH_TILE_FIT: { +// // prevent divide by zero (may never happen) +// if (r_source.size.x) { +// int units = p_np->rect.size.x / r_source.size.x; +// if (!units) +// units++; +// r_source.size.x = r_source.size.x * units; +// rect_flags = RendererCanvasRender::CANVAS_RECT_TILE; +// } +// } break; +// } + +// switch (p_np->axis_y) { +// default: +// break; +// case VisualServer::NINE_PATCH_TILE: { +// r_source.size.y = p_np->rect.size.y; +// rect_flags = RendererCanvasRender::CANVAS_RECT_TILE; +// } break; +// case VisualServer::NINE_PATCH_TILE_FIT: { +// // prevent divide by zero (may never happen) +// if (r_source.size.y) { +// int units = p_np->rect.size.y / r_source.size.y; +// if (!units) +// units++; +// r_source.size.y = r_source.size.y * units; +// rect_flags = RendererCanvasRender::CANVAS_RECT_TILE; +// } +// } break; +// } + +// return rect_flags; +//} + +#ifdef GODOT_3 + +T_PREAMBLE +template +bool C_PREAMBLE::_prefill_ninepatch(RendererCanvasRender::Item::CommandNinePatch *p_np, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate) { + typename T_STORAGE::Texture *tex = get_storage()->texture_owner.getornull(p_np->texture); + + if (!tex) { + // FIXME: Handle textureless ninepatch gracefully + WARN_PRINT("NinePatch without texture not supported yet in GLES2 backend, skipping."); + return false; + } + if (tex->width == 0 || tex->height == 0) { + WARN_PRINT("Cannot set empty texture to NinePatch."); + return false; + } + + // first check there are enough verts for this to complete successfully + if (bdata.vertices.size() + (4 * 9) > bdata.vertices.max_size()) { + // return where we got to + r_command_start = command_num; + return true; + } + + // create a temporary rect so we can reuse the rect routine + RendererCanvasRender::Item::CommandRect trect; + + trect.texture = p_np->texture; +#ifdef GODOT_3 + trect.normal_map = p_np->normal_map; +#endif + trect.modulate = p_np->color; + trect.flags = RendererCanvasRender::CANVAS_RECT_REGION; + + //Size2 texpixel_size(1.0f / tex->width, 1.0f / tex->height); + + Rect2 source = p_np->source; + if (source.size.x == 0 && source.size.y == 0) { + source.size.x = tex->width; + source.size.y = tex->height; + } + + float screen_scale = 1.0f; + + // optional crazy ninepatch scaling mode + if ((bdata.settings_ninepatch_mode == 1) && (source.size.x != 0) && (source.size.y != 0)) { + screen_scale = MIN(p_np->rect.size.x / source.size.x, p_np->rect.size.y / source.size.y); + screen_scale = MIN(1.0, screen_scale); + } + + // deal with nine patch texture wrapping modes + // this is switched off because it may not be possible with batching + // trect.flags |= _ninepatch_apply_tiling_modes(p_np, source); + + // translate to rects + Rect2 &rt = trect.rect; + Rect2 &src = trect.source; + + float tex_margin_left = p_np->margin[MARGIN_LEFT]; + float tex_margin_right = p_np->margin[MARGIN_RIGHT]; + float tex_margin_top = p_np->margin[MARGIN_TOP]; + float tex_margin_bottom = p_np->margin[MARGIN_BOTTOM]; + + float x[4]; + x[0] = p_np->rect.position.x; + x[1] = x[0] + (p_np->margin[MARGIN_LEFT] * screen_scale); + x[3] = x[0] + (p_np->rect.size.x); + x[2] = x[3] - (p_np->margin[MARGIN_RIGHT] * screen_scale); + + float y[4]; + y[0] = p_np->rect.position.y; + y[1] = y[0] + (p_np->margin[MARGIN_TOP] * screen_scale); + y[3] = y[0] + (p_np->rect.size.y); + y[2] = y[3] - (p_np->margin[MARGIN_BOTTOM] * screen_scale); + + float u[4]; + u[0] = source.position.x; + u[1] = u[0] + tex_margin_left; + u[3] = u[0] + source.size.x; + u[2] = u[3] - tex_margin_right; + + float v[4]; + v[0] = source.position.y; + v[1] = v[0] + tex_margin_top; + v[3] = v[0] + source.size.y; + v[2] = v[3] - tex_margin_bottom; + + // temporarily override to prevent single rect fallback + bool single_rect_fallback = bdata.settings_use_single_rect_fallback; + bdata.settings_use_single_rect_fallback = false; + + // each line of the ninepatch + for (int line = 0; line < 3; line++) { + rt.position = Vector2(x[0], y[line]); + rt.size = Vector2(x[1] - x[0], y[line + 1] - y[line]); + src.position = Vector2(u[0], v[line]); + src.size = Vector2(u[1] - u[0], v[line + 1] - v[line]); + _prefill_rect(&trect, r_fill_state, r_command_start, command_num, command_count, nullptr, p_item, multiply_final_modulate); + + if ((line == 1) && (!p_np->draw_center)) + ; + else { + rt.position.x = x[1]; + rt.size.x = x[2] - x[1]; + src.position.x = u[1]; + src.size.x = u[2] - u[1]; + _prefill_rect(&trect, r_fill_state, r_command_start, command_num, command_count, nullptr, p_item, multiply_final_modulate); + } + + rt.position.x = x[2]; + rt.size.x = x[3] - x[2]; + src.position.x = u[2]; + src.size.x = u[3] - u[2]; + _prefill_rect(&trect, r_fill_state, r_command_start, command_num, command_count, nullptr, p_item, multiply_final_modulate); + } + + // restore single rect fallback + bdata.settings_use_single_rect_fallback = single_rect_fallback; + return false; +} + +T_PREAMBLE +template +bool C_PREAMBLE::_prefill_polygon(RendererCanvasRender::Item::CommandPolygon *p_poly, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item *p_item, bool multiply_final_modulate) { + bool change_batch = false; + + // conditions for creating a new batch + if (r_fill_state.curr_batch->type != RasterizerStorageCommon::BT_POLY) { + // don't allow joining to a different sequence type + if (r_fill_state.sequence_batch_type_flags & (~RasterizerStorageCommon::BTF_POLY)) { + // don't allow joining to a different sequence type + r_command_start = command_num; + return true; + } + r_fill_state.sequence_batch_type_flags |= RasterizerStorageCommon::BTF_POLY; + + change_batch = true; + } + + int num_inds = p_poly->indices.size(); + + // nothing to draw? + if (!num_inds) + return false; + + // we aren't using indices, so will transform verts more than once .. less efficient. + // could be done with a temporary vertex buffer + BatchVertex *bvs = bdata.vertices.request(num_inds); + if (!bvs) { + // run out of space in the vertex buffer .. finish this function and draw what we have so far + // return where we got to + r_command_start = command_num; + return true; + } + + BatchColor *vertex_colors = bdata.vertex_colors.request(num_inds); + RAST_DEBUG_ASSERT(vertex_colors); + + // are we using large FVF? + //////////////////////////////////// + const bool use_large_verts = bdata.use_large_verts; + const bool use_modulate = bdata.use_modulate; + + BatchColor *vertex_modulates = nullptr; + if (use_modulate) { + vertex_modulates = bdata.vertex_modulates.request(num_inds); + RAST_DEBUG_ASSERT(vertex_modulates); + // precalc the vertex modulate (will be shared by all verts) + // we store the modulate as an attribute in the fvf rather than a uniform + vertex_modulates[0].set(r_fill_state.final_modulate); + } + + BatchTransform *pBT = nullptr; + if (use_large_verts) { + pBT = bdata.vertex_transforms.request(num_inds); + RAST_DEBUG_ASSERT(pBT); + // precalc the batch transform (will be shared by all verts) + // we store the transform as an attribute in the fvf rather than a uniform + const Transform2D &tr = r_fill_state.transform_combined; + + pBT[0].translate.set(tr.elements[2]); + // could do swizzling in shader? + pBT[0].basis[0].set(tr.elements[0][0], tr.elements[1][0]); + pBT[0].basis[1].set(tr.elements[0][1], tr.elements[1][1]); + } + //////////////////////////////////// + + // the modulate is always baked + Color modulate; + if (!use_large_verts && !use_modulate && multiply_final_modulate) + modulate = r_fill_state.final_modulate; + else + modulate = Color(1, 1, 1, 1); + + int old_batch_tex_id = r_fill_state.batch_tex_id; + r_fill_state.batch_tex_id = _batch_find_or_create_tex(p_poly->texture, p_poly->normal_map, false, old_batch_tex_id); + + // conditions for creating a new batch + if (old_batch_tex_id != r_fill_state.batch_tex_id) { + change_batch = true; + } + + // N.B. polygons don't have color thus don't need a batch change with color + // This code is left as reference in case of problems. + // if (!r_fill_state.curr_batch->color.equals(modulate)) { + // change_batch = true; + // bdata.total_color_changes++; + // } + + if (change_batch) { + // put the tex pixel size in a local (less verbose and can be a register) + const BatchTex &batchtex = bdata.batch_textures[r_fill_state.batch_tex_id]; + batchtex.tex_pixel_size.to(r_fill_state.texpixel_size); + + if (bdata.settings_uv_contract) { + r_fill_state.contract_uvs = (batchtex.flags & GD_VS::TEXTURE_FLAG_FILTER) == 0; + } + + // open new batch (this should never fail, it dynamically grows) + r_fill_state.curr_batch = _batch_request_new(false); + + r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_POLY; + + // modulate unused except for debugging? + r_fill_state.curr_batch->color.set(modulate); + r_fill_state.curr_batch->batch_texture_id = r_fill_state.batch_tex_id; + r_fill_state.curr_batch->first_command = command_num; + r_fill_state.curr_batch->num_commands = num_inds; + // r_fill_state.curr_batch->num_elements = num_inds; + r_fill_state.curr_batch->first_vert = bdata.total_verts; + } else { + // we could alternatively do the count when closing a batch .. perhaps more efficient + r_fill_state.curr_batch->num_commands += num_inds; + } + + // PRECALCULATE THE COLORS (as there may be less colors than there are indices + // in either hardware or software paths) + BatchColor vcol; + int num_verts = p_poly->points.size(); + + // in special cases, only 1 color is specified by convention, so we want to preset this + // to use in all verts. + if (p_poly->colors.size()) + vcol.set(p_poly->colors[0] * modulate); + else + // color is undefined, use modulate color straight + vcol.set(modulate); + + BatchColor *precalced_colors = (BatchColor *)alloca(num_verts * sizeof(BatchColor)); + + // two stage, super efficient setup of precalculated colors + int num_colors_specified = p_poly->colors.size(); + + for (int n = 0; n < num_colors_specified; n++) { + vcol.set(p_poly->colors[n] * modulate); + precalced_colors[n] = vcol; + } + for (int n = num_colors_specified; n < num_verts; n++) { + precalced_colors[n] = vcol; + } + + if (!_software_skin_poly(p_poly, p_item, bvs, vertex_colors, r_fill_state, precalced_colors)) { + for (int n = 0; n < num_inds; n++) { + int ind = p_poly->indices[n]; + + RAST_DEV_DEBUG_ASSERT(ind < p_poly->points.size()); + + // this could be moved outside the loop + if (r_fill_state.transform_mode != TM_NONE) { + Vector2 pos = p_poly->points[ind]; + _software_transform_vertex(pos, r_fill_state.transform_combined); + bvs[n].pos.set(pos.x, pos.y); + } else { + const Point2 &pos = p_poly->points[ind]; + bvs[n].pos.set(pos.x, pos.y); + } + + if (ind < p_poly->uvs.size()) { + const Point2 &uv = p_poly->uvs[ind]; + bvs[n].uv.set(uv.x, uv.y); + } else { + bvs[n].uv.set(0.0f, 0.0f); + } + + vertex_colors[n] = precalced_colors[ind]; + + if (use_modulate) { + vertex_modulates[n] = vertex_modulates[0]; + } + + if (use_large_verts) { + // reuse precalced transform (same for each vertex within polygon) + pBT[n] = pBT[0]; + } + } + } // if not software skinning + else { + // software skinning extra passes + if (use_modulate) { + for (int n = 0; n < num_inds; n++) { + vertex_modulates[n] = vertex_modulates[0]; + } + } + // not sure if this will produce garbage if software skinning is changing vertex pos + // in the shader, but is included for completeness + if (use_large_verts) { + for (int n = 0; n < num_inds; n++) { + pBT[n] = pBT[0]; + } + } + } + + // increment total vert count + bdata.total_verts += num_inds; + + return false; +} + +PREAMBLE(bool)::_software_skin_poly(RendererCanvasRender::Item::CommandPolygon *p_poly, RendererCanvasRender::Item *p_item, BatchVertex *bvs, BatchColor *vertex_colors, const FillState &p_fill_state, const BatchColor *p_precalced_colors) { + // alternatively could check get_this()->state.using_skeleton + if (p_item->skeleton == RID()) + return false; + + int num_inds = p_poly->indices.size(); + int num_verts = p_poly->points.size(); + + RID skeleton = p_item->skeleton; + int bone_count = RendererStorage::base_singleton->skeleton_get_bone_count(skeleton); + + // we want a temporary buffer of positions to transform + Vector2 *pTemps = (Vector2 *)alloca(num_verts * sizeof(Vector2)); + memset((void *)pTemps, 0, num_verts * sizeof(Vector2)); + + // these are used in the shader but don't appear to be needed for software transform + // const Transform2D &skel_trans = get_this()->state.skeleton_transform; + // const Transform2D &skel_trans_inv = get_this()->state.skeleton_transform_inverse; + + // get the bone transforms. + // this is not ideal because we don't know in advance which bones are needed + // for any particular poly, but depends how cheap the skeleton_bone_get_transform_2d call is + Transform2D *bone_transforms = (Transform2D *)alloca(bone_count * sizeof(Transform2D)); + for (int b = 0; b < bone_count; b++) { + bone_transforms[b] = RendererStorage::base_singleton->skeleton_bone_get_transform_2d(skeleton, b); + } + + if (num_verts && (p_poly->bones.size() == num_verts * 4) && (p_poly->weights.size() == p_poly->bones.size())) { + const Transform2D &item_transform = p_item->xform; + Transform2D item_transform_inv = item_transform.affine_inverse(); + + for (int n = 0; n < num_verts; n++) { + const Vector2 &src_pos = p_poly->points[n]; + Vector2 &dst_pos = pTemps[n]; + + // there can be an offset on the polygon at rigging time, this has to be accounted for + // note it may be possible that this could be concatenated with the bone transforms to save extra transforms - not sure yet + Vector2 src_pos_back_transformed = item_transform.xform(src_pos); + + float total_weight = 0.0f; + + for (int k = 0; k < 4; k++) { + int bone_id = p_poly->bones[n * 4 + k]; + float weight = p_poly->weights[n * 4 + k]; + if (weight == 0.0f) + continue; + + total_weight += weight; + + RAST_DEBUG_ASSERT(bone_id < bone_count); + const Transform2D &bone_tr = bone_transforms[bone_id]; + + Vector2 pos = bone_tr.xform(src_pos_back_transformed); + + dst_pos += pos * weight; + } + + // this is some unexplained weirdness with verts with no weights, + // but it seemed to work for the example project ... watch for regressions + if (total_weight < 0.01f) + dst_pos = src_pos; + else { + dst_pos /= total_weight; + + // retransform back from the poly offset space + dst_pos = item_transform_inv.xform(dst_pos); + } + } + + // software transform with combined matrix? + if (p_fill_state.transform_mode != TM_NONE) { + for (int n = 0; n < num_verts; n++) { + Vector2 &dst_pos = pTemps[n]; + _software_transform_vertex(dst_pos, p_fill_state.transform_combined); + } + } + + } // if bone format matches + else { + // not supported + } + + // output to the batch verts + for (int n = 0; n < num_inds; n++) { + int ind = p_poly->indices[n]; + + RAST_DEV_DEBUG_ASSERT(ind < num_verts); + const Point2 &pos = pTemps[ind]; + bvs[n].pos.set(pos.x, pos.y); + + if (ind < p_poly->uvs.size()) { + const Point2 &uv = p_poly->uvs[ind]; + bvs[n].uv.set(uv.x, uv.y); + } else { + bvs[n].uv.set(0.0f, 0.0f); + } + + vertex_colors[n] = p_precalced_colors[ind]; + } + + return true; +} + +T_PREAMBLE +template +bool C_PREAMBLE::_prefill_rect(RendererCanvasRender::Item::CommandRect *rect, FillState &r_fill_state, int &r_command_start, int command_num, int command_count, RendererCanvasRender::Item::Command *const *commands, RendererCanvasRender::Item *p_item, bool multiply_final_modulate) { + bool change_batch = false; + + // conditions for creating a new batch + if (r_fill_state.curr_batch->type != RasterizerStorageCommon::BT_RECT) { + // don't allow joining to a different sequence type + if (r_fill_state.sequence_batch_type_flags & (~RasterizerStorageCommon::BTF_RECT)) { + // don't allow joining to a different sequence type + r_command_start = command_num; + return true; + } + r_fill_state.sequence_batch_type_flags |= RasterizerStorageCommon::BTF_RECT; + + change_batch = true; + + // check for special case if there is only a single or small number of rects, + // in which case we will use the legacy default rect renderer + // because it is faster for single rects + + // we only want to do this if not a joined item with more than 1 item, + // because joined items with more than 1, the command * will be incorrect + // NOTE - this is assuming that use_hardware_transform means that it is a non-joined item!! + // If that assumption is incorrect this will go horribly wrong. + if (bdata.settings_use_single_rect_fallback && r_fill_state.use_hardware_transform) { + bool is_single_rect = false; + int command_num_next = command_num + 1; + if (command_num_next < command_count) { + RendererCanvasRender::Item::Command *command_next = commands[command_num_next]; + if ((command_next->type != RendererCanvasRender::Item::Command::TYPE_RECT) && (command_next->type != RendererCanvasRender::Item::Command::TYPE_TRANSFORM)) { + is_single_rect = true; + } + } else { + is_single_rect = true; + } + // if it is a rect on its own, do exactly the same as the default routine + if (is_single_rect) { + _prefill_default_batch(r_fill_state, command_num, *p_item); + return false; + } + } // if use hardware transform + } + + // try to create vertices BEFORE creating a batch, + // because if the vertex buffer is full, we need to finish this + // function, draw what we have so far, and then start a new set of batches + + // request FOUR vertices at a time, this is more efficient + BatchVertex *bvs = bdata.vertices.request(4); + if (!bvs) { + // run out of space in the vertex buffer .. finish this function and draw what we have so far + // return where we got to + r_command_start = command_num; + return true; + } + + // are we using large FVF? + const bool use_large_verts = bdata.use_large_verts; + const bool use_modulate = bdata.use_modulate; + + Color col = rect->modulate; + + if (!use_large_verts) { + if (multiply_final_modulate) { + col *= r_fill_state.final_modulate; + } + } + + // instead of doing all the texture preparation for EVERY rect, + // we build a list of texture combinations and do this once off. + // This means we have a potentially rather slow step to identify which texture combo + // using the RIDs. + int old_batch_tex_id = r_fill_state.batch_tex_id; + +#ifdef GODOT_4 + r_fill_state.batch_tex_id = _batch_find_or_create_tex(rect->texture, RID(), rect->flags & RendererCanvasRender::CANVAS_RECT_TILE, old_batch_tex_id); +#else + r_fill_state.batch_tex_id = _batch_find_or_create_tex(rect->texture, rect->normal_map, rect->flags & RendererCanvasRender::CANVAS_RECT_TILE, old_batch_tex_id); +#endif + + //r_fill_state.use_light_angles = send_light_angles; + if (SEND_LIGHT_ANGLES) { + bdata.use_light_angles = true; + } + + // conditions for creating a new batch + if (old_batch_tex_id != r_fill_state.batch_tex_id) { + change_batch = true; + } + + // we need to treat color change separately because we need to count these + // to decide whether to switch on the fly to colored vertices. + if (!r_fill_state.curr_batch->color.equals(col)) { + change_batch = true; + bdata.total_color_changes++; + } + + if (change_batch) { + // put the tex pixel size in a local (less verbose and can be a register) + const BatchTex &batchtex = bdata.batch_textures[r_fill_state.batch_tex_id]; + batchtex.tex_pixel_size.to(r_fill_state.texpixel_size); + + if (bdata.settings_uv_contract) { + r_fill_state.contract_uvs = (batchtex.flags & GD_VS::TEXTURE_FLAG_FILTER) == 0; + } + + // need to preserve texpixel_size between items + //r_fill_state.texpixel_size = r_fill_state.texpixel_size; + + // open new batch (this should never fail, it dynamically grows) + r_fill_state.curr_batch = _batch_request_new(false); + + r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_RECT; + r_fill_state.curr_batch->color.set(col); + r_fill_state.curr_batch->batch_texture_id = r_fill_state.batch_tex_id; + r_fill_state.curr_batch->first_command = command_num; + r_fill_state.curr_batch->num_commands = 1; + //r_fill_state.curr_batch->first_quad = bdata.total_quads; + r_fill_state.curr_batch->first_vert = bdata.total_verts; + } else { + // we could alternatively do the count when closing a batch .. perhaps more efficient + r_fill_state.curr_batch->num_commands++; + } + + // fill the quad geometry + Vector2 mins = rect->rect.position; + + if (r_fill_state.transform_mode == TM_TRANSLATE) { + if (!use_large_verts) { + _software_transform_vertex(mins, r_fill_state.transform_combined); + } + } + + Vector2 maxs = mins + rect->rect.size; + + // just aliases + BatchVertex *bA = &bvs[0]; + BatchVertex *bB = &bvs[1]; + BatchVertex *bC = &bvs[2]; + BatchVertex *bD = &bvs[3]; + + bA->pos.x = mins.x; + bA->pos.y = mins.y; + + bB->pos.x = maxs.x; + bB->pos.y = mins.y; + + bC->pos.x = maxs.x; + bC->pos.y = maxs.y; + + bD->pos.x = mins.x; + bD->pos.y = maxs.y; + + // possibility of applying flips here for normal mapping .. but they don't seem to be used + if (rect->rect.size.x < 0) { + SWAP(bA->pos, bB->pos); + SWAP(bC->pos, bD->pos); + } + if (rect->rect.size.y < 0) { + SWAP(bA->pos, bD->pos); + SWAP(bB->pos, bC->pos); + } + + if (r_fill_state.transform_mode == TM_ALL) { + if (!use_large_verts) { + _software_transform_vertex(bA->pos, r_fill_state.transform_combined); + _software_transform_vertex(bB->pos, r_fill_state.transform_combined); + _software_transform_vertex(bC->pos, r_fill_state.transform_combined); + _software_transform_vertex(bD->pos, r_fill_state.transform_combined); + } + } + + // uvs + Vector2 src_min; + Vector2 src_max; + if (rect->flags & RendererCanvasRender::CANVAS_RECT_REGION) { + src_min = rect->source.position; + src_max = src_min + rect->source.size; + + src_min *= r_fill_state.texpixel_size; + src_max *= r_fill_state.texpixel_size; + + const float uv_epsilon = bdata.settings_uv_contract_amount; + + // nudge offset for the maximum to prevent precision error on GPU reading into line outside the source rect + // this is very difficult to get right. + if (r_fill_state.contract_uvs) { + src_min.x += uv_epsilon; + src_min.y += uv_epsilon; + src_max.x -= uv_epsilon; + src_max.y -= uv_epsilon; + } + } else { + src_min = Vector2(0, 0); + src_max = Vector2(1, 1); + } + + // 10% faster calculating the max first + Vector2 uvs[4] = { + src_min, + Vector2(src_max.x, src_min.y), + src_max, + Vector2(src_min.x, src_max.y), + }; + + // for encoding in light angle + // flips should be optimized out when not being used for light angle. + bool flip_h = false; + bool flip_v = false; + + if (rect->flags & RendererCanvasRender::CANVAS_RECT_TRANSPOSE) { + SWAP(uvs[1], uvs[3]); + } + + if (rect->flags & RendererCanvasRender::CANVAS_RECT_FLIP_H) { + SWAP(uvs[0], uvs[1]); + SWAP(uvs[2], uvs[3]); + flip_h = !flip_h; + flip_v = !flip_v; + } + if (rect->flags & RendererCanvasRender::CANVAS_RECT_FLIP_V) { + SWAP(uvs[0], uvs[3]); + SWAP(uvs[1], uvs[2]); + flip_v = !flip_v; + } + + bA->uv.set(uvs[0]); + bB->uv.set(uvs[1]); + bC->uv.set(uvs[2]); + bD->uv.set(uvs[3]); + + // modulate + if (use_modulate) { + // store the final modulate separately from the rect modulate + BatchColor *pBC = bdata.vertex_modulates.request(4); + RAST_DEBUG_ASSERT(pBC); + pBC[0].set(r_fill_state.final_modulate); + pBC[1] = pBC[0]; + pBC[2] = pBC[0]; + pBC[3] = pBC[0]; + } + + if (use_large_verts) { + // store the transform separately + BatchTransform *pBT = bdata.vertex_transforms.request(4); + RAST_DEBUG_ASSERT(pBT); + + const Transform2D &tr = r_fill_state.transform_combined; + + pBT[0].translate.set(tr.elements[2]); + // could do swizzling in shader? + pBT[0].basis[0].set(tr.elements[0][0], tr.elements[1][0]); + pBT[0].basis[1].set(tr.elements[0][1], tr.elements[1][1]); + + pBT[1] = pBT[0]; + pBT[2] = pBT[0]; + pBT[3] = pBT[0]; + } + + if (SEND_LIGHT_ANGLES) { + // we can either keep the light angles in sync with the verts when writing, + // or sync them up during translation. We are syncing in translation. + // N.B. There may be batches that don't require light_angles between batches that do. + float *angles = bdata.light_angles.request(4); + RAST_DEBUG_ASSERT(angles); + + float angle = 0.0f; + const float TWO_PI = Math_PI * 2; + + if (r_fill_state.transform_mode != TM_NONE) { + const Transform2D &tr = r_fill_state.transform_combined; + + // apply to an x axis + // the x axis and y axis can be taken directly from the transform (no need to xform identity vectors) + Vector2 x_axis(tr.elements[0][0], tr.elements[1][0]); + + // have to do a y axis to check for scaling flips + // this is hassle and extra slowness. We could only allow flips via the flags. + Vector2 y_axis(tr.elements[0][1], tr.elements[1][1]); + + // has the x / y axis flipped due to scaling? + float cross = x_axis.cross(y_axis); + if (cross < 0.0f) { + flip_v = !flip_v; + } + + // passing an angle is smaller than a vector, it can be reconstructed in the shader + angle = x_axis.angle(); + + // we don't want negative angles, as negative is used to encode flips. + // This moves range from -PI to PI to 0 to TWO_PI + if (angle < 0.0f) + angle += TWO_PI; + + } // if transform needed + + // if horizontal flip, angle is shifted by 180 degrees + if (flip_h) { + angle += Math_PI; + + // mod to get back to 0 to TWO_PI range + angle = fmodf(angle, TWO_PI); + } + + // add 1 (to take care of zero floating point error with sign) + angle += 1.0f; + + // flip if necessary to indicate a vertical flip in the shader + if (flip_v) + angle *= -1.0f; + + // light angle must be sent for each vert, instead as a single uniform in the uniform draw method + // this has the benefit of enabling batching with light angles. + for (int n = 0; n < 4; n++) { + angles[n] = angle; + } + } + + // increment quad count + bdata.total_quads++; + bdata.total_verts += 4; + + return false; +} + +// This function may be called MULTIPLE TIMES for each item, so needs to record how far it has got +PREAMBLE(bool)::prefill_joined_item(FillState &r_fill_state, int &r_command_start, RendererCanvasRender::Item *p_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material) { + // we will prefill batches and vertices ready for sending in one go to the vertex buffer + int command_count = p_item->commands.size(); + RendererCanvasRender::Item::Command *const *commands = p_item->commands.ptr(); + + // checking the color for not being white makes it 92/90 times faster in the case where it is white + bool multiply_final_modulate = false; + if (!r_fill_state.use_hardware_transform && (r_fill_state.final_modulate != Color(1, 1, 1, 1))) { + multiply_final_modulate = true; + } + + // start batch is a dummy batch (tex id -1) .. could be made more efficient + if (!r_fill_state.curr_batch) { + // OLD METHOD, but left dangling zero length default batches + // r_fill_state.curr_batch = _batch_request_new(); + // r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_DEFAULT; + // r_fill_state.curr_batch->first_command = r_command_start; + // should tex_id be set to -1? check this + + // allocate dummy batch on the stack, it should always get replaced + // note that the rest of the structure is uninitialized, this should not matter + // if the type is checked before anything else. + r_fill_state.curr_batch = (Batch *)alloca(sizeof(Batch)); + r_fill_state.curr_batch->type = RasterizerStorageCommon::BT_DUMMY; + + // this is assumed to be the case + //CRASH_COND (r_fill_state.transform_extra_command_number_p1); + } + + // we need to return which command we got up to, so + // store this outside the loop + int command_num; + + // do as many commands as possible until the vertex buffer will be full up + for (command_num = r_command_start; command_num < command_count; command_num++) { + RendererCanvasRender::Item::Command *command = commands[command_num]; + + switch (command->type) { + default: { + _prefill_default_batch(r_fill_state, command_num, *p_item); + } break; + case RendererCanvasRender::Item::Command::TYPE_TRANSFORM: { + // if the extra matrix has been sent already, + // break this extra matrix software path (as we don't want to unset it on the GPU etc) + if (r_fill_state.extra_matrix_sent) { + _prefill_default_batch(r_fill_state, command_num, *p_item); + + // keep track of the combined matrix on the CPU in parallel, in case we use large vertex format + RendererCanvasRender::Item::CommandTransform *transform = static_cast(command); + const Transform2D &extra_matrix = transform->xform; + r_fill_state.transform_combined = p_item->final_transform * extra_matrix; + } else { + // Extra matrix fast path. + // Instead of sending the command immediately, we store the modified transform (in combined) + // for software transform, and only flush this transform command if we NEED to (i.e. we want to + // render some default commands) + RendererCanvasRender::Item::CommandTransform *transform = static_cast(command); + const Transform2D &extra_matrix = transform->xform; + + if (r_fill_state.use_hardware_transform) { + // if we are using hardware transform mode, we have already sent the final transform, + // so we only want to software transform the extra matrix + r_fill_state.transform_combined = extra_matrix; + } else { + r_fill_state.transform_combined = p_item->final_transform * extra_matrix; + } + // after a transform command, always use some form of software transform (either the combined final + extra, or just the extra) + // until we flush this dirty extra matrix because we need to render default commands. + r_fill_state.transform_mode = _find_transform_mode(r_fill_state.transform_combined); + + // make a note of which command the dirty extra matrix is store in, so we can send it later + // if necessary + r_fill_state.transform_extra_command_number_p1 = command_num + 1; // plus 1 so we can test against zero + } + } break; + case RendererCanvasRender::Item::Command::TYPE_RECT: { + RendererCanvasRender::Item::CommandRect *rect = static_cast(command); + + // unoptimized - could this be done once per batch / batch texture? + bool send_light_angles = rect->normal_map != RID(); + + bool buffer_full = false; + + // the template params must be explicit for compilation, + // this forces building the multiple versions of the function. + if (send_light_angles) { + buffer_full = _prefill_rect(rect, r_fill_state, r_command_start, command_num, command_count, commands, p_item, multiply_final_modulate); + } else { + buffer_full = _prefill_rect(rect, r_fill_state, r_command_start, command_num, command_count, commands, p_item, multiply_final_modulate); + } + + if (buffer_full) + return true; + + } break; + case RendererCanvasRender::Item::Command::TYPE_NINEPATCH: { + RendererCanvasRender::Item::CommandNinePatch *np = static_cast(command); + + if ((np->axis_x != VisualServer::NINE_PATCH_STRETCH) || (np->axis_y != VisualServer::NINE_PATCH_STRETCH)) { + // not accelerated + _prefill_default_batch(r_fill_state, command_num, *p_item); + continue; + } + + // unoptimized - could this be done once per batch / batch texture? + bool send_light_angles = np->normal_map != RID(); + + bool buffer_full = false; + + if (send_light_angles) + buffer_full = _prefill_ninepatch(np, r_fill_state, r_command_start, command_num, command_count, p_item, multiply_final_modulate); + else + buffer_full = _prefill_ninepatch(np, r_fill_state, r_command_start, command_num, command_count, p_item, multiply_final_modulate); + + if (buffer_full) + return true; + + } break; + + case RendererCanvasRender::Item::Command::TYPE_LINE: { + RendererCanvasRender::Item::CommandLine *line = static_cast(command); + + if (line->width <= 1) { + bool buffer_full = _prefill_line(line, r_fill_state, r_command_start, command_num, command_count, p_item, multiply_final_modulate); + + if (buffer_full) + return true; + } else { + // not accelerated + _prefill_default_batch(r_fill_state, command_num, *p_item); + } + } break; + + case RendererCanvasRender::Item::Command::TYPE_POLYGON: { + RendererCanvasRender::Item::CommandPolygon *polygon = static_cast(command); +#ifdef GLES_OVER_GL + // anti aliasing not accelerated .. it is problematic because it requires a 2nd line drawn around the outside of each + // poly, which would require either a second list of indices or a second list of vertices for this step + if (polygon->antialiased) { + // not accelerated + _prefill_default_batch(r_fill_state, command_num, *p_item); + } else { +#endif + // not using software skinning? + if (!bdata.settings_use_software_skinning && get_this()->state.using_skeleton) { + // not accelerated + _prefill_default_batch(r_fill_state, command_num, *p_item); + } else { + // unoptimized - could this be done once per batch / batch texture? + bool send_light_angles = polygon->normal_map != RID(); + + bool buffer_full = false; + + if (send_light_angles) { + // NYI + _prefill_default_batch(r_fill_state, command_num, *p_item); + //buffer_full = prefill_polygon(polygon, r_fill_state, r_command_start, command_num, command_count, p_item, multiply_final_modulate); + } else + buffer_full = _prefill_polygon(polygon, r_fill_state, r_command_start, command_num, command_count, p_item, multiply_final_modulate); + + if (buffer_full) + return true; + } // if not using hardware skinning path +#ifdef GLES_OVER_GL + } // if not anti-aliased poly +#endif + + } break; + } + } + + // VERY IMPORTANT to return where we got to, because this func may be called multiple + // times per item. + // Don't miss out on this step by calling return earlier in the function without setting r_command_start. + r_command_start = command_num; + + return false; +} + +PREAMBLE(void)::flush_render_batches(RendererCanvasRender::Item *p_first_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material, uint32_t p_sequence_batch_type_flags) { + // some heuristic to decide whether to use colored verts. + // feel free to tweak this. + // this could use hysteresis, to prevent jumping between methods + // .. however probably not necessary + bdata.use_colored_vertices = false; + + RasterizerStorageCommon::FVF backup_fvf = bdata.fvf; + + // the batch type in this flush can override the fvf from the joined item. + // The joined item uses the material to determine fvf, assuming a rect... + // however with custom drawing, lines or polys may be drawn. + // lines contain no color (this is stored in the batch), and polys contain vertex and color only. + if (p_sequence_batch_type_flags & (RasterizerStorageCommon::BTF_LINE | RasterizerStorageCommon::BTF_LINE_AA)) { + // do nothing, use the default regular FVF + bdata.fvf = RasterizerStorageCommon::FVF_REGULAR; + } else { + // switch from regular to colored? + if (bdata.fvf == RasterizerStorageCommon::FVF_REGULAR) { + // only check whether to convert if there are quads (prevent divide by zero) + // and we haven't decided to prevent color baking (due to e.g. MODULATE + // being used in a shader) + if (bdata.total_quads && !(bdata.joined_item_batch_flags & RasterizerStorageCommon::PREVENT_COLOR_BAKING)) { + // minus 1 to prevent single primitives (ratio 1.0) always being converted to colored.. + // in that case it is slightly cheaper to just have the color as part of the batch + float ratio = (float)(bdata.total_color_changes - 1) / (float)bdata.total_quads; + + // use bigger than or equal so that 0.0 threshold can force always using colored verts + if (ratio >= bdata.settings_colored_vertex_format_threshold) { + bdata.use_colored_vertices = true; + bdata.fvf = RasterizerStorageCommon::FVF_COLOR; + } + } + + // if we used vertex colors + if (bdata.vertex_colors.size()) { + bdata.use_colored_vertices = true; + bdata.fvf = RasterizerStorageCommon::FVF_COLOR; + } + + // needs light angles? + if (bdata.use_light_angles) { + bdata.fvf = RasterizerStorageCommon::FVF_LIGHT_ANGLE; + } + } + + backup_fvf = bdata.fvf; + } // if everything else except lines + + // translate if required to larger FVFs + switch (bdata.fvf) { + case RasterizerStorageCommon::FVF_UNBATCHED: // should not happen + break; + case RasterizerStorageCommon::FVF_REGULAR: // no change + break; + case RasterizerStorageCommon::FVF_COLOR: { + // special case, where vertex colors are used (polys) + if (!bdata.vertex_colors.size()) + _translate_batches_to_larger_FVF(p_sequence_batch_type_flags); + else + // normal, reduce number of batches by baking batch colors + _translate_batches_to_vertex_colored_FVF(); + } break; + case RasterizerStorageCommon::FVF_LIGHT_ANGLE: + _translate_batches_to_larger_FVF(p_sequence_batch_type_flags); + break; + case RasterizerStorageCommon::FVF_MODULATED: + _translate_batches_to_larger_FVF(p_sequence_batch_type_flags); + break; + case RasterizerStorageCommon::FVF_LARGE: + _translate_batches_to_larger_FVF(p_sequence_batch_type_flags); + break; + } + + // send buffers to opengl + get_this()->_batch_upload_buffers(); + + RendererCanvasRender::Item::Command *const *commands = p_first_item->commands.ptr(); + +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + if (bdata.diagnose_frame) { + diagnose_batches(commands); + } +#endif + + get_this()->render_batches(commands, p_current_clip, r_reclip, p_material); + + // if we overrode the fvf for lines, set it back to the joined item fvf + bdata.fvf = backup_fvf; + + // overwrite source buffers with garbage if error checking +#ifdef RASTERIZER_EXTRA_CHECKS + _debug_write_garbage(); +#endif +} + +#endif // godot 3 + +PREAMBLE(void)::render_joined_item_commands(const BItemJoined &p_bij, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material, bool p_lit) { + RendererCanvasRender::Item *item = 0; + RendererCanvasRender::Item *first_item = bdata.item_refs[p_bij.first_item_ref].item; + + // fill_state and bdata have once off setup per joined item, and a smaller reset on flush + FillState fill_state; + fill_state.reset_joined_item(p_bij.use_hardware_transform()); + + bdata.reset_joined_item(); + + // should this joined item be using large FVF? + if (p_bij.flags & RasterizerStorageCommon::USE_MODULATE_FVF) { + bdata.use_modulate = true; + bdata.fvf = RasterizerStorageCommon::FVF_MODULATED; + } + if (p_bij.flags & RasterizerStorageCommon::USE_LARGE_FVF) { + bdata.use_modulate = true; + bdata.use_large_verts = true; + bdata.fvf = RasterizerStorageCommon::FVF_LARGE; + } + + // in the special case of custom shaders that read from VERTEX (i.e. vertex position) + // we want to disable software transform of extra matrix + if (bdata.joined_item_batch_flags & RasterizerStorageCommon::PREVENT_VERTEX_BAKING) { + fill_state.extra_matrix_sent = true; + } + + for (unsigned int i = 0; i < p_bij.num_item_refs; i++) { + const BItemRef &ref = bdata.item_refs[p_bij.first_item_ref + i]; + item = ref.item; + + if (!p_lit) { + // if not lit we use the complex calculated final modulate + fill_state.final_modulate = ref.final_modulate; + } else { + // if lit we ignore canvas modulate and just use the item modulate + fill_state.final_modulate = item->final_modulate; + } + +#ifdef GODOT_3 + int command_count = item->commands.size(); + int command_start = 0; +#endif + + // ONCE OFF fill state setup, that will be retained over multiple calls to + // prefill_joined_item() + fill_state.transform_combined = item->final_transform; + + // decide the initial transform mode, and make a backup + // in orig_transform_mode in case we need to switch back + if (!fill_state.use_hardware_transform) { + fill_state.transform_mode = _find_transform_mode(fill_state.transform_combined); + } else { + fill_state.transform_mode = TM_NONE; + } + fill_state.orig_transform_mode = fill_state.transform_mode; + + // keep track of when we added an extra matrix + // so we can defer sending until we see a default command + fill_state.transform_extra_command_number_p1 = 0; + +#ifdef GODOT_4 + RendererCanvasRender::Item::Command *current_command = item->commands; + while (current_command) { +#else + while (command_start < command_count) { +#endif + // fill as many batches as possible (until all done, or the vertex buffer is full) +#ifdef GODOT_4 + bool bFull = get_this()->prefill_joined_item(fill_state, current_command, item, p_current_clip, r_reclip, p_material); +#else + bool bFull = get_this()->prefill_joined_item(fill_state, command_start, item, p_current_clip, r_reclip, p_material); +#endif + + if (bFull) { + // always pass first item (commands for default are always first item) + flush_render_batches(first_item, p_current_clip, r_reclip, p_material, fill_state.sequence_batch_type_flags); + + // zero all the batch data ready for a new run + bdata.reset_flush(); + + // don't zero all the fill state, some may need to be preserved + fill_state.reset_flush(); + } + } + } + + // flush if any left + flush_render_batches(first_item, p_current_clip, r_reclip, p_material, fill_state.sequence_batch_type_flags); + + // zero all the batch data ready for a new run + bdata.reset_flush(); +} + +PREAMBLE(void)::_legacy_canvas_item_render_commands(RendererCanvasRender::Item *p_item, RendererCanvasRender::Item *p_current_clip, bool &r_reclip, typename T_STORAGE::Material *p_material) { +#ifdef GODOT_3 + int command_count = p_item->commands.size(); + RendererCanvasRender::Item::Command *const *commands = p_item->commands.ptr(); +#else + // reuse the same list each time to prevent needless dynamic allocations + unsigned int command_count = godot4_commands_to_vector(p_item->commands, bdata.command_shortlist); + RendererCanvasRender::Item::Command *const *commands = nullptr; + if (command_count) + commands = &bdata.command_shortlist[0]; +#endif + + // legacy .. just create one massive batch and render everything as before + bdata.batches.reset(); + Batch *batch = _batch_request_new(); + batch->type = RasterizerStorageCommon::BT_DEFAULT; + batch->num_commands = command_count; + + get_this()->render_batches(commands, p_current_clip, r_reclip, p_material); + bdata.reset_flush(); +} + +PREAMBLE(void)::record_items(RendererCanvasRender::Item *p_item_list, int p_z) { + while (p_item_list) { + BSortItem *s = bdata.sort_items.request_with_grow(); + + s->item = p_item_list; + s->z_index = p_z; + + p_item_list = p_item_list->next; + } +} + +PREAMBLE(void)::join_sorted_items() { + /* + sort_items(); + + int z = GD_VS::CANVAS_ITEM_Z_MIN; + _render_item_state.item_group_z = z; + + for (int s = 0; s < bdata.sort_items.size(); s++) { + const BSortItem &si = bdata.sort_items[s]; + RendererCanvasRender::Item *ci = si.item; + + // change z? + if (si.z_index != z) { + z = si.z_index; + + // may not be required + _render_item_state.item_group_z = z; + + // if z ranged lights are present, sometimes we have to disable joining over z_indices. + // we do this here. + // Note this restriction may be able to be relaxed with light bitfields, investigate! + if (!bdata.join_across_z_indices) { + _render_item_state.join_batch_break = true; + } + } + + bool join; + + if (_render_item_state.join_batch_break) { + // always start a new batch for this item + join = false; + + // could be another batch break (i.e. prevent NEXT item from joining this) + // so we still need to run try_join_item + // even though we know join is false. + // also we need to run try_join_item for every item because it keeps the state up to date, + // if we didn't run it the state would be out of date. + get_this()->try_join_item(ci, _render_item_state, _render_item_state.join_batch_break); + } else { + join = get_this()->try_join_item(ci, _render_item_state, _render_item_state.join_batch_break); + } + + // assume the first item will always return no join + if (!join) { + _render_item_state.joined_item = bdata.items_joined.request_with_grow(); + _render_item_state.joined_item->first_item_ref = bdata.item_refs.size(); + _render_item_state.joined_item->num_item_refs = 1; + _render_item_state.joined_item->bounding_rect = ci->global_rect_cache; + _render_item_state.joined_item->z_index = z; + _render_item_state.joined_item->flags = bdata.joined_item_batch_flags; + + // we need some logic to prevent joining items that have vastly different batch types + _render_item_state.joined_item_batch_type_flags_prev = _render_item_state.joined_item_batch_type_flags_curr; + + // add the reference + BItemRef *r = bdata.item_refs.request_with_grow(); + r->item = ci; + // we are storing final_modulate in advance per item reference + // for baking into vertex colors. + // this may not be ideal... as we are increasing the size of item reference, + // but it is stupidly complex to calculate later, which would probably be slower. + r->final_modulate = _render_item_state.final_modulate; + } else { + RAST_DEBUG_ASSERT(_render_item_state.joined_item != 0); + _render_item_state.joined_item->num_item_refs += 1; + _render_item_state.joined_item->bounding_rect = _render_item_state.joined_item->bounding_rect.merge(ci->global_rect_cache); + + BItemRef *r = bdata.item_refs.request_with_grow(); + r->item = ci; + r->final_modulate = _render_item_state.final_modulate; + } + + } // for s through sort items +*/ +} + +#ifdef GODOT_3 +PREAMBLE(void)::sort_items() { + // turned off? + if (!bdata.settings_item_reordering_lookahead) { + return; + } + + for (int s = 0; s < bdata.sort_items.size() - 2; s++) { + if (sort_items_from(s)) { +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + bdata.stats_items_sorted++; +#endif + } + } +} + +PREAMBLE(bool)::_sort_items_match(const BSortItem &p_a, const BSortItem &p_b) const { + const RendererCanvasRender::Item *a = p_a.item; + const RendererCanvasRender::Item *b = p_b.item; + + if (b->commands.size() != 1) + return false; + + // tested outside function + // if (a->commands.size() != 1) + // return false; + + const RendererCanvasRender::Item::Command &cb = *b->commands[0]; + if (cb.type != RendererCanvasRender::Item::Command::TYPE_RECT) + return false; + + const RendererCanvasRender::Item::Command &ca = *a->commands[0]; + // tested outside function + // if (ca.type != Item::Command::TYPE_RECT) + // return false; + + const RendererCanvasRender::Item::CommandRect *rect_a = static_cast(&ca); + const RendererCanvasRender::Item::CommandRect *rect_b = static_cast(&cb); + + if (rect_a->texture != rect_b->texture) + return false; + + /* ALTERNATIVE APPROACH NOT LIMITED TO RECTS +const RendererCanvasRender::Item::Command &ca = *a->commands[0]; +const RendererCanvasRender::Item::Command &cb = *b->commands[0]; + +if (ca.type != cb.type) + return false; + +// do textures match? +switch (ca.type) +{ +default: + break; +case RendererCanvasRender::Item::Command::TYPE_RECT: + { + const RendererCanvasRender::Item::CommandRect *comm_a = static_cast(&ca); + const RendererCanvasRender::Item::CommandRect *comm_b = static_cast(&cb); + if (comm_a->texture != comm_b->texture) + return false; + } + break; +case RendererCanvasRender::Item::Command::TYPE_POLYGON: + { + const RendererCanvasRender::Item::CommandPolygon *comm_a = static_cast(&ca); + const RendererCanvasRender::Item::CommandPolygon *comm_b = static_cast(&cb); + if (comm_a->texture != comm_b->texture) + return false; + } + break; +} +*/ + + return true; +} + +PREAMBLE(bool)::sort_items_from(int p_start) { +#if defined(TOOLS_ENABLED) && defined(DEBUG_ENABLED) + ERR_FAIL_COND_V((p_start + 1) >= bdata.sort_items.size(), false) +#endif + + const BSortItem &start = bdata.sort_items[p_start]; + int start_z = start.z_index; + + // check start is the right type for sorting + if (start.item->commands.size() != 1) { + return false; + } + const RendererCanvasRender::Item::Command &command_start = *start.item->commands[0]; + if (command_start.type != RendererCanvasRender::Item::Command::TYPE_RECT) { + return false; + } + + BSortItem &second = bdata.sort_items[p_start + 1]; + if (second.z_index != start_z) { + // no sorting across z indices (for now) + return false; + } + + // if the neighbours are already a good match + if (_sort_items_match(start, second)) // order is crucial, start first + { + return false; + } + + // local cached aabb + Rect2 second_AABB = second.item->global_rect_cache; + + // if the start and 2nd items overlap, can do no more + if (start.item->global_rect_cache.intersects(second_AABB)) { + return false; + } + + // which neighbour to test + int test_last = 2 + bdata.settings_item_reordering_lookahead; + for (int test = 2; test < test_last; test++) { + int test_sort_item_id = p_start + test; + + // if we've got to the end of the list, can't sort any more, give up + if (test_sort_item_id >= bdata.sort_items.size()) { + return false; + } + + BSortItem *test_sort_item = &bdata.sort_items[test_sort_item_id]; + + // across z indices? + if (test_sort_item->z_index != start_z) { + return false; + } + + RendererCanvasRender::Item *test_item = test_sort_item->item; + + // if the test item overlaps the second item, we can't swap, AT ALL + // because swapping an item OVER this one would cause artefacts + if (second_AABB.intersects(test_item->global_rect_cache)) { + return false; + } + + // do they match? + if (!_sort_items_match(start, *test_sort_item)) // order is crucial, start first + { + continue; + } + + // we can only swap if there are no AABB overlaps with sandwiched neighbours + bool ok = true; + + // start from 2, no need to check 1 as the second has already been checked against this item + // in the intersection test above + for (int sn = 2; sn < test; sn++) { + BSortItem *sandwich_neighbour = &bdata.sort_items[p_start + sn]; + if (test_item->global_rect_cache.intersects(sandwich_neighbour->item->global_rect_cache)) { + ok = false; + break; + } + } + if (!ok) { + continue; + } + + // it is ok to exchange them! + BSortItem temp; + temp.assign(second); + second.assign(*test_sort_item); + test_sort_item->assign(temp); + + return true; + } // for test + + return false; +} +#endif // godot 3 + +PREAMBLE(void)::_software_transform_vertex(BatchVector2 &r_v, const Transform2D &p_tr) const { + Vector2 vc(r_v.x, r_v.y); + vc = p_tr.xform(vc); + r_v.set(vc); +} + +PREAMBLE(void)::_software_transform_vertex(Vector2 &r_v, const Transform2D &p_tr) const { + r_v = p_tr.xform(r_v); +} + +PREAMBLE(void)::_translate_batches_to_vertex_colored_FVF() { + // zeros the size and sets up how big each unit is + bdata.unit_vertices.prepare(sizeof(BatchVertexColored)); + + const BatchColor *source_vertex_colors = &bdata.vertex_colors[0]; + RAST_DEBUG_ASSERT(bdata.vertex_colors.size() == bdata.vertices.size()); + + int num_verts = bdata.vertices.size(); + + for (int n = 0; n < num_verts; n++) { + const BatchVertex &bv = bdata.vertices[n]; + + BatchVertexColored *cv = (BatchVertexColored *)bdata.unit_vertices.request(); + + cv->pos = bv.pos; + cv->uv = bv.uv; + cv->col = *source_vertex_colors++; + } +} + +// Translation always involved adding color to the FVF, which enables +// joining of batches that have different colors. +// There is a trade off. Non colored verts are smaller so work faster, but +// there comes a point where it is better to just use colored verts to avoid lots of +// batches. +// In addition this can optionally add light angles to the FVF, necessary for normal mapping. +T_PREAMBLE +template +void C_PREAMBLE::_translate_batches_to_larger_FVF(uint32_t p_sequence_batch_type_flags) { + bool include_poly_color = false; + + // we ONLY want to include the color verts in translation when using polys, + // as rects do not write vertex colors, only colors per batch. + if (p_sequence_batch_type_flags & RasterizerStorageCommon::BTF_POLY) { + include_poly_color = INCLUDE_LIGHT_ANGLES | INCLUDE_MODULATE | INCLUDE_LARGE; + } + + // zeros the size and sets up how big each unit is + bdata.unit_vertices.prepare(sizeof(BATCH_VERTEX_TYPE)); + bdata.batches_temp.reset(); + + // As the vertices_colored and batches_temp are 'mirrors' of the non-colored version, + // the sizes should be equal, and allocations should never fail. Hence the use of debug + // asserts to check program flow, these should not occur at runtime unless the allocation + // code has been altered. + RAST_DEBUG_ASSERT(bdata.unit_vertices.max_size() == bdata.vertices.max_size()); + RAST_DEBUG_ASSERT(bdata.batches_temp.max_size() == bdata.batches.max_size()); + + Color curr_col(-1.0f, -1.0f, -1.0f, -1.0f); + + Batch *dest_batch = nullptr; + + const BatchColor *source_vertex_colors = &bdata.vertex_colors[0]; + const float *source_light_angles = &bdata.light_angles[0]; + const BatchColor *source_vertex_modulates = &bdata.vertex_modulates[0]; + const BatchTransform *source_vertex_transforms = &bdata.vertex_transforms[0]; + + // translate the batches into vertex colored batches + for (int n = 0; n < bdata.batches.size(); n++) { + const Batch &source_batch = bdata.batches[n]; + + // does source batch use light angles? + const BatchTex &btex = bdata.batch_textures[source_batch.batch_texture_id]; + bool source_batch_uses_light_angles = btex.RID_normal != RID(); + + bool needs_new_batch = true; + + if (dest_batch) { + if (dest_batch->type == source_batch.type) { + if (source_batch.type == RasterizerStorageCommon::BT_RECT) { + if (dest_batch->batch_texture_id == source_batch.batch_texture_id) { + // add to previous batch + dest_batch->num_commands += source_batch.num_commands; + needs_new_batch = false; + + // create the colored verts (only if not default) + //int first_vert = source_batch.first_quad * 4; + //int end_vert = 4 * (source_batch.first_quad + source_batch.num_commands); + int first_vert = source_batch.first_vert; + int end_vert = first_vert + (4 * source_batch.num_commands); + + for (int v = first_vert; v < end_vert; v++) { + RAST_DEV_DEBUG_ASSERT(bdata.vertices.size()); + const BatchVertex &bv = bdata.vertices[v]; + BATCH_VERTEX_TYPE *cv = (BATCH_VERTEX_TYPE *)bdata.unit_vertices.request(); + RAST_DEBUG_ASSERT(cv); + cv->pos = bv.pos; + cv->uv = bv.uv; + cv->col = source_batch.color; + + if (INCLUDE_LIGHT_ANGLES) { + RAST_DEV_DEBUG_ASSERT(bdata.light_angles.size()); + // this is required to allow compilation with non light angle vertex. + // it should be compiled out. + BatchVertexLightAngled *lv = (BatchVertexLightAngled *)cv; + if (source_batch_uses_light_angles) + lv->light_angle = *source_light_angles++; + else + lv->light_angle = 0.0f; // dummy, unused in vertex shader (could possibly be left uninitialized, but probably bad idea) + } // if including light angles + + if (INCLUDE_MODULATE) { + RAST_DEV_DEBUG_ASSERT(bdata.vertex_modulates.size()); + BatchVertexModulated *mv = (BatchVertexModulated *)cv; + mv->modulate = *source_vertex_modulates++; + } // including modulate + + if (INCLUDE_LARGE) { + RAST_DEV_DEBUG_ASSERT(bdata.vertex_transforms.size()); + BatchVertexLarge *lv = (BatchVertexLarge *)cv; + lv->transform = *source_vertex_transforms++; + } // if including large + } + } // textures match + } else { + // default + // we can still join, but only under special circumstances + // does this ever happen? not sure at this stage, but left for future expansion + uint32_t source_last_command = source_batch.first_command + source_batch.num_commands; + if (source_last_command == dest_batch->first_command) { + dest_batch->num_commands += source_batch.num_commands; + needs_new_batch = false; + } // if the commands line up exactly + } + } // if both batches are the same type + + } // if dest batch is valid + + if (needs_new_batch) { + dest_batch = bdata.batches_temp.request(); + RAST_DEBUG_ASSERT(dest_batch); + + *dest_batch = source_batch; + + // create the colored verts (only if not default) + if (source_batch.type != RasterizerStorageCommon::BT_DEFAULT) { + // int first_vert = source_batch.first_quad * 4; + // int end_vert = 4 * (source_batch.first_quad + source_batch.num_commands); + int first_vert = source_batch.first_vert; + int end_vert = first_vert + (4 * source_batch.num_commands); + + for (int v = first_vert; v < end_vert; v++) { + RAST_DEV_DEBUG_ASSERT(bdata.vertices.size()); + const BatchVertex &bv = bdata.vertices[v]; + BATCH_VERTEX_TYPE *cv = (BATCH_VERTEX_TYPE *)bdata.unit_vertices.request(); + RAST_DEBUG_ASSERT(cv); + cv->pos = bv.pos; + cv->uv = bv.uv; + + // polys are special, they can have per vertex colors + if (!include_poly_color) { + cv->col = source_batch.color; + } else { + RAST_DEV_DEBUG_ASSERT(bdata.vertex_colors.size()); + cv->col = *source_vertex_colors++; + } + + if (INCLUDE_LIGHT_ANGLES) { + RAST_DEV_DEBUG_ASSERT(bdata.light_angles.size()); + // this is required to allow compilation with non light angle vertex. + // it should be compiled out. + BatchVertexLightAngled *lv = (BatchVertexLightAngled *)cv; + if (source_batch_uses_light_angles) + lv->light_angle = *source_light_angles++; + else + lv->light_angle = 0.0f; // dummy, unused in vertex shader (could possibly be left uninitialized, but probably bad idea) + } // if using light angles + + if (INCLUDE_MODULATE) { + RAST_DEV_DEBUG_ASSERT(bdata.vertex_modulates.size()); + BatchVertexModulated *mv = (BatchVertexModulated *)cv; + mv->modulate = *source_vertex_modulates++; + } // including modulate + + if (INCLUDE_LARGE) { + RAST_DEV_DEBUG_ASSERT(bdata.vertex_transforms.size()); + BatchVertexLarge *lv = (BatchVertexLarge *)cv; + lv->transform = *source_vertex_transforms++; + } // if including large + } + } + } + } + + // copy the temporary batches to the master batch list (this could be avoided but it makes the code cleaner) + bdata.batches.copy_from(bdata.batches_temp); +} + +PREAMBLE(bool)::_disallow_item_join_if_batch_types_too_different(RenderItemState &r_ris, uint32_t btf_allowed) { + r_ris.joined_item_batch_type_flags_curr |= btf_allowed; + + bool disallow = false; + + if (r_ris.joined_item_batch_type_flags_prev & (~btf_allowed)) + disallow = true; + + return disallow; +} + +#ifdef GODOT_3 +PREAMBLE(bool)::_detect_item_batch_break(RenderItemState &r_ris, RendererCanvasRender::Item *p_ci, bool &r_batch_break) { + int command_count = p_ci->commands.size(); + + // Any item that contains commands that are default + // (i.e. not handled by software transform and the batching renderer) should not be joined. + + // ALSO batched types that differ in what the vertex format is needed to be should not be + // joined. + + // In order to work this out, it does a lookahead through the commands, + // which could potentially be very expensive. As such it makes sense to put a limit on this + // to some small number, which will catch nearly all cases which need joining, + // but not be overly expensive in the case of items with large numbers of commands. + + // It is hard to know what this number should be, empirically, + // and this has not been fully investigated. It works to join single sprite items when set to 1 or above. + // Note that there is a cost to increasing this because it has to look in advance through + // the commands. + // On the other hand joining items where possible will usually be better up to a certain + // number where the cost of software transform is higher than separate drawcalls with hardware + // transform. + + // if there are more than this number of commands in the item, we + // don't allow joining (separate state changes, and hardware transform) + // This is set to quite a conservative (low) number until investigated properly. + // const int MAX_JOIN_ITEM_COMMANDS = 16; + + r_ris.joined_item_batch_type_flags_curr = 0; + + if (command_count > bdata.settings_max_join_item_commands) { + return true; + } else { + RendererCanvasRender::Item::Command *const *commands = p_ci->commands.ptr(); + + // run through the commands looking for one that could prevent joining + for (int command_num = 0; command_num < command_count; command_num++) { + RendererCanvasRender::Item::Command *command = commands[command_num]; + RAST_DEBUG_ASSERT(command); + + switch (command->type) { + default: { + //r_batch_break = true; + return true; + } break; + case RendererCanvasRender::Item::Command::TYPE_LINE: { + // special case, only batches certain lines + RendererCanvasRender::Item::CommandLine *line = static_cast(command); + + if (line->width > 1) { + //r_batch_break = true; + return true; + } + + if (_disallow_item_join_if_batch_types_too_different(r_ris, RasterizerStorageCommon::BTF_LINE | RasterizerStorageCommon::BTF_LINE_AA)) { + return true; + } + } break; + case RendererCanvasRender::Item::Command::TYPE_POLYGON: { + // only allow polygons to join if they aren't skeleton + RendererCanvasRender::Item::CommandPolygon *poly = static_cast(command); + +#ifdef GLES_OVER_GL + // anti aliasing not accelerated + if (poly->antialiased) + return true; +#endif + + // light angles not yet implemented, treat as default + if (poly->normal_map != RID()) + return true; + + if (!get_this()->bdata.settings_use_software_skinning && poly->bones.size()) + return true; + + if (_disallow_item_join_if_batch_types_too_different(r_ris, RasterizerStorageCommon::BTF_POLY)) { + //r_batch_break = true; + return true; + } + } break; + case RendererCanvasRender::Item::Command::TYPE_RECT: { + if (_disallow_item_join_if_batch_types_too_different(r_ris, RasterizerStorageCommon::BTF_RECT)) + return true; + } break; + case RendererCanvasRender::Item::Command::TYPE_NINEPATCH: { + // do not handle tiled ninepatches, these can't be batched and need to use legacy method + RendererCanvasRender::Item::CommandNinePatch *np = static_cast(command); + if ((np->axis_x != VisualServer::NINE_PATCH_STRETCH) || (np->axis_y != VisualServer::NINE_PATCH_STRETCH)) + return true; + + if (_disallow_item_join_if_batch_types_too_different(r_ris, RasterizerStorageCommon::BTF_RECT)) + return true; + } break; + case RendererCanvasRender::Item::Command::TYPE_TRANSFORM: { + // compatible with all types + } break; + } // switch + + } // for through commands + + } // else + + // special case, back buffer copy, so don't join + if (p_ci->copy_back_buffer) { + return true; + } + + return false; +} +#endif + +#undef PREAMBLE +#undef T_PREAMBLE +#undef C_PREAMBLE + +#endif // RASTERIZER_CANVAS_BATCHER_H diff --git a/drivers/gles_common/rasterizer_common_stubs.h b/drivers/gles_common/rasterizer_common_stubs.h new file mode 100644 index 00000000000..8f1e0364977 --- /dev/null +++ b/drivers/gles_common/rasterizer_common_stubs.h @@ -0,0 +1,1096 @@ +/*************************************************************************/ +/* rasterizer_common_stubs.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#include "core/math/camera_matrix.h" +#include "core/templates/rid_owner.h" +#include "core/templates/self_list.h" +#include "scene/resources/mesh.h" +#include "servers/rendering/rasterizer_dummy.h" +#include "servers/rendering/renderer_compositor.h" +#include "servers/rendering_server.h" + +//class StubsScene : public RendererSceneRender { +class StubsScene : public RasterizerSceneDummy { + // StubsScene() {} + // ~StubsScene() {} +}; + +//class StubsStorage : public RendererStorage { +class StubsStorage : public RasterizerStorageDummy { + // StubsStorage() {} + // ~StubsStorage() {} +}; + +//class StubsCanvas : public RendererCanvasRender { +class StubsCanvas : public RasterizerCanvasDummy { + // StubsCanvas() {} + // ~StubsCanvas() {} +}; + +//class RasterizerDummy : public RendererCompositor { +//private: +// uint64_t frame = 1; +// float delta = 0; + +//protected: +// RasterizerCanvasDummy canvas; +// RasterizerStorageDummy storage; +// RasterizerSceneDummy scene; + +//public: +// RendererStorage *get_storage() override { return &storage; } +// RendererCanvasRender *get_canvas() override { return &canvas; } +// RendererSceneRender *get_scene() override { return &scene; } + +// void set_boot_image(const Ref &p_image, const Color &p_color, bool p_scale, bool p_use_filter = true) override {} + +// void initialize() override {} +// void begin_frame(double frame_step) override { +// frame++; +// delta = frame_step; +// } + +// void prepare_for_blitting_render_targets() override {} +// void blit_render_targets_to_screen(int p_screen, const BlitToScreen *p_render_targets, int p_amount) override {} + +// void end_frame(bool p_swap_buffers) override { +// if (p_swap_buffers) { +// DisplayServer::get_singleton()->swap_buffers(); +// } +// } + +// void finalize() override {} + +// static RendererCompositor *_create_current() { +// return memnew(RasterizerDummy); +// } + +// static void make_current() { +// _create_func = _create_current; +// } + +// bool is_low_end() const override { return true; } +// uint64_t get_frame_number() const override { return frame; } +// float get_frame_delta_time() const override { return delta; } + +// RasterizerDummy() {} +// ~RasterizerDummy() {} +//}; + +/* +class StubsStorage : public RendererStorage { + +public: + // TEXTURE API + struct DummyTexture { + int width = 0; + int height = 0; + uint32_t flags = 0; + Image::Format format = Image::Format::FORMAT_MAX; + Ref image; + String path; + }; + + struct DummySurface { + uint32_t format = 0; + RS::PrimitiveType primitive = RS::PrimitiveType::PRIMITIVE_MAX; + Vector array; + int vertex_count = 0; + Vector index_array; + int index_count = 0; + AABB aabb; + Vector> blend_shapes; + Vector bone_aabbs; + }; + + struct DummyMesh { + Vector surfaces; + int blend_shape_count = 0; + RS::BlendShapeMode blend_shape_mode = RS::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED; + }; + + mutable RID_PtrOwner texture_owner; + mutable RID_PtrOwner mesh_owner; + + RID texture_2d_create(const Ref &p_image) override { return RID(); } + RID texture_2d_layered_create(const Vector> &p_layers, RS::TextureLayeredType p_layered_type) override { return RID(); } + RID texture_3d_create(Image::Format, int p_width, int p_height, int p_depth, bool p_mipmaps, const Vector> &p_data) override { return RID(); } + RID texture_proxy_create(RID p_base) override { return RID(); } + + void texture_2d_update_immediate(RID p_texture, const Ref &p_image, int p_layer = 0) override {} + void texture_2d_update(RID p_texture, const Ref &p_image, int p_layer = 0) override {} + void texture_3d_update(RID p_texture, const Vector> &p_data) override {} + void texture_proxy_update(RID p_proxy, RID p_base) override {} + + RID texture_2d_placeholder_create() override { return RID(); } + RID texture_2d_layered_placeholder_create(RenderingServer::TextureLayeredType p_layered_type) override { return RID(); } + RID texture_3d_placeholder_create() override { return RID(); } + + Ref texture_2d_get(RID p_texture) const override { return Ref(); } + Ref texture_2d_layer_get(RID p_texture, int p_layer) const override { return Ref(); } + Vector> texture_3d_get(RID p_texture) const override { return Vector>(); } + + void texture_replace(RID p_texture, RID p_by_texture) override {} + void texture_set_size_override(RID p_texture, int p_width, int p_height) override {} +// FIXME: Disabled during Vulkan refactoring, should be ported. +#if 0 + void texture_bind(RID p_texture, uint32_t p_texture_no) = 0; +#endif + + void texture_set_path(RID p_texture, const String &p_path) override {} + String texture_get_path(RID p_texture) const override { return String(); } + + void texture_set_detect_3d_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata) override {} + void texture_set_detect_normal_callback(RID p_texture, RS::TextureDetectCallback p_callback, void *p_userdata) override {} + void texture_set_detect_roughness_callback(RID p_texture, RS::TextureDetectRoughnessCallback p_callback, void *p_userdata) override {} + + void texture_debug_usage(List *r_info) override {} + void texture_set_force_redraw_if_visible(RID p_texture, bool p_enable) override {} + Size2 texture_size_with_proxy(RID p_proxy) override { return Size2(); } + + void texture_add_to_decal_atlas(RID p_texture, bool p_panorama_to_dp = false) override {} + void texture_remove_from_decal_atlas(RID p_texture, bool p_panorama_to_dp = false) override {} + + // CANVAS TEXTURE API + + RID canvas_texture_create() override { return RID(); } + void canvas_texture_set_channel(RID p_canvas_texture, RS::CanvasTextureChannel p_channel, RID p_texture) override {} + void canvas_texture_set_shading_parameters(RID p_canvas_texture, const Color &p_base_color, float p_shininess) override {} + + void canvas_texture_set_texture_filter(RID p_item, RS::CanvasItemTextureFilter p_filter) override {} + void canvas_texture_set_texture_repeat(RID p_item, RS::CanvasItemTextureRepeat p_repeat) override {} + +#if 0 + RID texture_create() override { + DummyTexture *texture = memnew(DummyTexture); + ERR_FAIL_COND_V(!texture, RID()); + return texture_owner.make_rid(texture); + } + + void texture_allocate(RID p_texture, int p_width, int p_height, int p_depth_3d, Image::Format p_format, RenderingServer::TextureType p_type = RS::TEXTURE_TYPE_2D, uint32_t p_flags = RS::TEXTURE_FLAGS_DEFAULT) override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!t); + t->width = p_width; + t->height = p_height; + t->flags = p_flags; + t->format = p_format; + t->image = Ref(memnew(Image)); + t->image->create(p_width, p_height, false, p_format); + } + void texture_set_data(RID p_texture, const Ref &p_image, int p_level) override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!t); + t->width = p_image->get_width(); + t->height = p_image->get_height(); + t->format = p_image->get_format(); + t->image->create(t->width, t->height, false, t->format, p_image->get_data()); + } + + void texture_set_data_partial(RID p_texture, const Ref &p_image, int src_x, int src_y, int src_w, int src_h, int dst_x, int dst_y, int p_dst_mip, int p_level) override { + DummyTexture *t = texture_owner.getornull(p_texture); + + ERR_FAIL_COND(!t); + ERR_FAIL_COND_MSG(p_image.is_null(), "It's not a reference to a valid Image object."); + ERR_FAIL_COND(t->format != p_image->get_format()); + ERR_FAIL_COND(src_w <= 0 || src_h <= 0); + ERR_FAIL_COND(src_x < 0 || src_y < 0 || src_x + src_w > p_image->get_width() || src_y + src_h > p_image->get_height()); + ERR_FAIL_COND(dst_x < 0 || dst_y < 0 || dst_x + src_w > t->width || dst_y + src_h > t->height); + + t->image->blit_rect(p_image, Rect2(src_x, src_y, src_w, src_h), Vector2(dst_x, dst_y)); + } + + Ref texture_get_data(RID p_texture, int p_level) const override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!t, Ref()); + return t->image; + } + void texture_set_flags(RID p_texture, uint32_t p_flags) override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!t); + t->flags = p_flags; + } + uint32_t texture_get_flags(RID p_texture) const override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!t, 0); + return t->flags; + } + Image::Format texture_get_format(RID p_texture) const override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!t, Image::FORMAT_RGB8); + return t->format; + } + + RenderingServer::TextureType texture_get_type(RID p_texture) const override { return RS::TEXTURE_TYPE_2D; } + uint32_t texture_get_texid(RID p_texture) const override { return 0; } + uint32_t texture_get_width(RID p_texture) const override { return 0; } + uint32_t texture_get_height(RID p_texture) const override { return 0; } + uint32_t texture_get_depth(RID p_texture) const override { return 0; } + void texture_set_size_override(RID p_texture, int p_width, int p_height, int p_depth_3d) override {} + void texture_bind(RID p_texture, uint32_t p_texture_no) override {} + + void texture_set_path(RID p_texture, const String &p_path) override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND(!t); + t->path = p_path; + } + String texture_get_path(RID p_texture) const override { + DummyTexture *t = texture_owner.getornull(p_texture); + ERR_FAIL_COND_V(!t, String()); + return t->path; + } + + void texture_set_shrink_all_x2_on_set_data(bool p_enable) override {} + + void texture_debug_usage(List *r_info) override {} + + RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const override { return RID(); } + + void texture_set_detect_3d_callback(RID p_texture, RenderingServer::TextureDetectCallback p_callback, void *p_userdata) override {} + void texture_set_detect_srgb_callback(RID p_texture, RenderingServer::TextureDetectCallback p_callback, void *p_userdata) override {} + void texture_set_detect_normal_callback(RID p_texture, RenderingServer::TextureDetectCallback p_callback, void *p_userdata) override {} + + void textures_keep_original(bool p_enable) override {} + + void texture_set_proxy(RID p_proxy, RID p_base) override {} + Size2 texture_size_with_proxy(RID p_texture) const override { return Size2(); } + void texture_set_force_redraw_if_visible(RID p_texture, bool p_enable) override {} +#endif + + // SHADER API + + RID shader_create() override { return RID(); } + + void shader_set_code(RID p_shader, const String &p_code) override {} + String shader_get_code(RID p_shader) const override { return ""; } + void shader_get_param_list(RID p_shader, List *p_param_list) const override {} + + void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) override {} + RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const override { return RID(); } + Variant shader_get_param_default(RID p_material, const StringName &p_param) const override { return Variant(); } + + // COMMON MATERIAL API + + RID material_create() override { return RID(); } + + void material_set_render_priority(RID p_material, int priority) override {} + void material_set_shader(RID p_shader_material, RID p_shader) override {} + + void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) override {} + Variant material_get_param(RID p_material, const StringName &p_param) const override { return Variant(); } + + void material_set_next_pass(RID p_material, RID p_next_material) override {} + + bool material_is_animated(RID p_material) override { return false; } + bool material_casts_shadows(RID p_material) override { return false; } + void material_get_instance_shader_parameters(RID p_material, List *r_parameters) override {} + void material_update_dependency(RID p_material, DependencyTracker *p_instance) override {} + + // MESH API + + RID mesh_create() override { + return RID(); + // DummyMesh *mesh = memnew(DummyMesh); + // ERR_FAIL_COND_V(!mesh, RID()); + // mesh->blend_shape_count = 0; + // mesh->blend_shape_mode = RS::BLEND_SHAPE_MODE_NORMALIZED; + // return mesh_owner.make_rid(mesh); + } + + void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override {} + + void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override {} + +#if 0 + void mesh_add_surface(RID p_mesh, uint32_t p_format, RS::PrimitiveType p_primitive, const Vector &p_array, int p_vertex_count, const Vector &p_index_array, int p_index_count, const AABB &p_aabb, const Vector > &p_blend_shapes = Vector >(), const Vector &p_bone_aabbs = Vector()) override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND(!m); + + m->surfaces.push_back(DummySurface()); + DummySurface *s = &m->surfaces.write[m->surfaces.size() - 1]; + s->format = p_format; + s->primitive = p_primitive; + s->array = p_array; + s->vertex_count = p_vertex_count; + s->index_array = p_index_array; + s->index_count = p_index_count; + s->aabb = p_aabb; + s->blend_shapes = p_blend_shapes; + s->bone_aabbs = p_bone_aabbs; + } + + void mesh_set_blend_shape_count(RID p_mesh, int p_amount) override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND(!m); + m->blend_shape_count = p_amount; + } +#endif + + int mesh_get_blend_shape_count(RID p_mesh) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, 0); + return m->blend_shape_count; + } + + void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override { + // DummyMesh *m = mesh_owner.getornull(p_mesh); + // ERR_FAIL_COND(!m); + // m->blend_shape_mode = p_mode; + } + RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, RS::BLEND_SHAPE_MODE_NORMALIZED); + return m->blend_shape_mode; + } + + void mesh_surface_update_region(RID p_mesh, int p_surface, int p_offset, const Vector &p_data) override {} + + void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override {} + RID mesh_surface_get_material(RID p_mesh, int p_surface) const override { return RID(); } + +#if 0 + int mesh_surface_get_array_len(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, 0); + + return m->surfaces[p_surface].vertex_count; + } + int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, 0); + + return m->surfaces[p_surface].index_count; + } + + Vector mesh_surface_get_array(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, Vector()); + + return m->surfaces[p_surface].array; + } + Vector mesh_surface_get_index_array(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, Vector()); + + return m->surfaces[p_surface].index_array; + } + + uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, 0); + + return m->surfaces[p_surface].format; + } + RS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, RS::PRIMITIVE_POINTS); + + return m->surfaces[p_surface].primitive; + } + + AABB mesh_surface_get_aabb(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, AABB()); + + return m->surfaces[p_surface].aabb; + } + Vector > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, Vector >()); + + return m->surfaces[p_surface].blend_shapes; + } + Vector mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, Vector()); + + return m->surfaces[p_surface].bone_aabbs; + } + + void mesh_remove_surface(RID p_mesh, int p_index) override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND(!m); + ERR_FAIL_COND(p_index >= m->surfaces.size()); + + m->surfaces.remove(p_index); + } +#endif + + RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override { return RS::SurfaceData(); } + int mesh_get_surface_count(RID p_mesh) const override { + DummyMesh *m = mesh_owner.getornull(p_mesh); + ERR_FAIL_COND_V(!m, 0); + return m->surfaces.size(); + } + + void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override {} + AABB mesh_get_custom_aabb(RID p_mesh) const override { return AABB(); } + + AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override { return AABB(); } + void mesh_clear(RID p_mesh) override {} + + bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override { return false; } + + // MESH INSTANCE + + RID mesh_instance_create(RID p_base) override { return RID(); } + void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override {} + void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override {} + void mesh_instance_check_for_update(RID p_mesh_instance) override {} + void update_mesh_instances() override {} + + // MULTIMESH API + + RID multimesh_create() override { return RID(); } + + void multimesh_allocate(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override {} + int multimesh_get_instance_count(RID p_multimesh) const override { return 0; } + + void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override {} + void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) override {} + void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override {} + void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override {} + void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override {} + + RID multimesh_get_mesh(RID p_multimesh) const override { return RID(); } + AABB multimesh_get_aabb(RID p_multimesh) const override { return AABB(); } + + Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const override { return Transform(); } + Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override { return Transform2D(); } + Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override { return Color(); } + Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override { return Color(); } + void multimesh_set_buffer(RID p_multimesh, const Vector &p_buffer) override {} + Vector multimesh_get_buffer(RID p_multimesh) const override { return Vector(); } + + void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override {} + int multimesh_get_visible_instances(RID p_multimesh) const override { return 0; } + + // IMMEDIATE API + + RID immediate_create() override { return RID(); } + void immediate_begin(RID p_immediate, RS::PrimitiveType p_rimitive, RID p_texture = RID()) override {} + void immediate_vertex(RID p_immediate, const Vector3 &p_vertex) override {} + void immediate_normal(RID p_immediate, const Vector3 &p_normal) override {} + void immediate_tangent(RID p_immediate, const Plane &p_tangent) override {} + void immediate_color(RID p_immediate, const Color &p_color) override {} + void immediate_uv(RID p_immediate, const Vector2 &tex_uv) override {} + void immediate_uv2(RID p_immediate, const Vector2 &tex_uv) override {} + void immediate_end(RID p_immediate) override {} + void immediate_clear(RID p_immediate) override {} + void immediate_set_material(RID p_immediate, RID p_material) override {} + RID immediate_get_material(RID p_immediate) const override { return RID(); } + AABB immediate_get_aabb(RID p_immediate) const override { return AABB(); } + + // SKELETON API + + RID skeleton_create() override { return RID(); } + void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override {} + void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override {} + int skeleton_get_bone_count(RID p_skeleton) const override { return 0; } + void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) override {} + Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override { return Transform(); } + void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override {} + Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override { return Transform2D(); } + + // Light API + + RID light_create(RS::LightType p_type) override { return RID(); } + + void light_set_color(RID p_light, const Color &p_color) override {} + void light_set_param(RID p_light, RS::LightParam p_param, float p_value) override {} + void light_set_shadow(RID p_light, bool p_enabled) override {} + void light_set_shadow_color(RID p_light, const Color &p_color) override {} + void light_set_projector(RID p_light, RID p_texture) override {} + void light_set_negative(RID p_light, bool p_enable) override {} + void light_set_cull_mask(RID p_light, uint32_t p_mask) override {} + void light_set_reverse_cull_face_mode(RID p_light, bool p_enabled) override {} + void light_set_bake_mode(RID p_light, RS::LightBakeMode p_bake_mode) override {} + void light_set_max_sdfgi_cascade(RID p_light, uint32_t p_cascade) override {} + + void light_omni_set_shadow_mode(RID p_light, RS::LightOmniShadowMode p_mode) override {} + + void light_directional_set_shadow_mode(RID p_light, RS::LightDirectionalShadowMode p_mode) override {} + void light_directional_set_blend_splits(RID p_light, bool p_enable) override {} + bool light_directional_get_blend_splits(RID p_light) const override { return false; } + void light_directional_set_shadow_depth_range_mode(RID p_light, RS::LightDirectionalShadowDepthRangeMode p_range_mode) override {} + void light_directional_set_sky_only(RID p_light, bool p_sky_only) override {} + bool light_directional_is_sky_only(RID p_light) const override { return false; } + RS::LightDirectionalShadowDepthRangeMode light_directional_get_shadow_depth_range_mode(RID p_light) const override { return RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE; } + + RS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light) override { return RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL; } + RS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light) override { return RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID; } + + bool light_has_shadow(RID p_light) const override { return false; } + + RS::LightType light_get_type(RID p_light) const override { return RS::LIGHT_OMNI; } + AABB light_get_aabb(RID p_light) const override { return AABB(); } + float light_get_param(RID p_light, RS::LightParam p_param) override { return 0.0; } + Color light_get_color(RID p_light) override { return Color(); } + RS::LightBakeMode light_get_bake_mode(RID p_light) override { return RS::LIGHT_BAKE_DISABLED; } + uint32_t light_get_max_sdfgi_cascade(RID p_light) override { return 0; } + uint64_t light_get_version(RID p_light) const override { return 0; } + + // PROBE API + + RID reflection_probe_create() override { return RID(); } + + void reflection_probe_set_update_mode(RID p_probe, RS::ReflectionProbeUpdateMode p_mode) override {} + void reflection_probe_set_intensity(RID p_probe, float p_intensity) override {} + void reflection_probe_set_ambient_mode(RID p_probe, RS::ReflectionProbeAmbientMode p_mode) override {} + void reflection_probe_set_ambient_color(RID p_probe, const Color &p_color) override {} + void reflection_probe_set_ambient_energy(RID p_probe, float p_energy) override {} + void reflection_probe_set_max_distance(RID p_probe, float p_distance) override {} + void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) override {} + void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) override {} + void reflection_probe_set_as_interior(RID p_probe, bool p_enable) override {} + void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) override {} + void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) override {} + void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) override {} + void reflection_probe_set_resolution(RID p_probe, int p_resolution) override {} + void reflection_probe_set_lod_threshold(RID p_probe, float p_ratio) override {} + float reflection_probe_get_lod_threshold(RID p_probe) const override { return 0.0f; } + + AABB reflection_probe_get_aabb(RID p_probe) const override { return AABB(); } + RS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const override { return RenderingServer::REFLECTION_PROBE_UPDATE_ONCE; } + uint32_t reflection_probe_get_cull_mask(RID p_probe) const override { return 0; } + Vector3 reflection_probe_get_extents(RID p_probe) const override { return Vector3(); } + Vector3 reflection_probe_get_origin_offset(RID p_probe) const override { return Vector3(); } + float reflection_probe_get_origin_max_distance(RID p_probe) const override { return 0.0; } + bool reflection_probe_renders_shadows(RID p_probe) const override { return false; } + + void base_update_dependency(RID p_base, DependencyTracker *p_instance) override {} + void skeleton_update_dependency(RID p_base, DependencyTracker *p_instance) override {} + + // DECAL API + + RID decal_create() override { return RID(); } + void decal_set_extents(RID p_decal, const Vector3 &p_extents) override {} + void decal_set_texture(RID p_decal, RS::DecalTexture p_type, RID p_texture) override {} + void decal_set_emission_energy(RID p_decal, float p_energy) override {} + void decal_set_albedo_mix(RID p_decal, float p_mix) override {} + void decal_set_modulate(RID p_decal, const Color &p_modulate) override {} + void decal_set_cull_mask(RID p_decal, uint32_t p_layers) override {} + void decal_set_distance_fade(RID p_decal, bool p_enabled, float p_begin, float p_length) override {} + void decal_set_fade(RID p_decal, float p_above, float p_below) override {} + void decal_set_normal_fade(RID p_decal, float p_fade) override {} + + AABB decal_get_aabb(RID p_decal) const override { return AABB(); } + + // GI PROBE API + + RID gi_probe_create() override { return RID(); } + + void gi_probe_allocate(RID p_gi_probe, const Transform &p_to_cell_xform, const AABB &p_aabb, const Vector3i &p_octree_size, const Vector &p_octree_cells, const Vector &p_data_cells, const Vector &p_distance_field, const Vector &p_level_counts) override {} + + AABB gi_probe_get_bounds(RID p_gi_probe) const override { return AABB(); } + Vector3i gi_probe_get_octree_size(RID p_gi_probe) const override { return Vector3i(); } + Vector gi_probe_get_octree_cells(RID p_gi_probe) const override { return Vector(); } + Vector gi_probe_get_data_cells(RID p_gi_probe) const override { return Vector(); } + Vector gi_probe_get_distance_field(RID p_gi_probe) const override { return Vector(); } + + Vector gi_probe_get_level_counts(RID p_gi_probe) const override { return Vector(); } + Transform gi_probe_get_to_cell_xform(RID p_gi_probe) const override { return Transform(); } + + void gi_probe_set_dynamic_range(RID p_gi_probe, float p_range) override {} + float gi_probe_get_dynamic_range(RID p_gi_probe) const override { return 0; } + + void gi_probe_set_propagation(RID p_gi_probe, float p_range) override {} + float gi_probe_get_propagation(RID p_gi_probe) const override { return 0; } + + void gi_probe_set_energy(RID p_gi_probe, float p_range) override {} + float gi_probe_get_energy(RID p_gi_probe) const override { return 0.0; } + + void gi_probe_set_ao(RID p_gi_probe, float p_ao) override {} + float gi_probe_get_ao(RID p_gi_probe) const override { return 0; } + + void gi_probe_set_ao_size(RID p_gi_probe, float p_strength) override {} + float gi_probe_get_ao_size(RID p_gi_probe) const override { return 0; } + + void gi_probe_set_bias(RID p_gi_probe, float p_range) override {} + float gi_probe_get_bias(RID p_gi_probe) const override { return 0.0; } + + void gi_probe_set_normal_bias(RID p_gi_probe, float p_range) override {} + float gi_probe_get_normal_bias(RID p_gi_probe) const override { return 0.0; } + + void gi_probe_set_interior(RID p_gi_probe, bool p_enable) override {} + bool gi_probe_is_interior(RID p_gi_probe) const override { return false; } + + void gi_probe_set_use_two_bounces(RID p_gi_probe, bool p_enable) override {} + bool gi_probe_is_using_two_bounces(RID p_gi_probe) const override { return false; } + + void gi_probe_set_anisotropy_strength(RID p_gi_probe, float p_strength) override {} + float gi_probe_get_anisotropy_strength(RID p_gi_probe) const override { return 0; } + + uint32_t gi_probe_get_version(RID p_gi_probe) override { return 0; } + + // LIGHTMAP CAPTURE +#if 0 + struct Instantiable { + SelfList::List instance_list; + + _FORCE_INLINE_ void instance_change_notify(bool p_aabb = true, bool p_materials = true) override { + SelfList *instances = instance_list.first(); + while (instances) override { + //instances->self()->base_changed(p_aabb, p_materials); + instances = instances->next(); + } + } + + _FORCE_INLINE_ void instance_remove_deps() override { + SelfList *instances = instance_list.first(); + while (instances) override { + SelfList *next = instances->next(); + //instances->self()->base_removed(); + instances = next; + } + } + + Instantiable() override {} + ~Instantiable() override { + } + }; + + struct LightmapCapture : public Instantiable { + Vector octree; + AABB bounds; + Transform cell_xform; + int cell_subdiv; + float energy; + LightmapCapture() override { + energy = 1.0; + cell_subdiv = 1; + } + }; + + mutable RID_PtrOwner lightmap_capture_data_owner; + void lightmap_capture_set_bounds(RID p_capture, const AABB &p_bounds) override {} + AABB lightmap_capture_get_bounds(RID p_capture) const override { return AABB(); } + void lightmap_capture_set_octree(RID p_capture, const Vector &p_octree) override {} + RID lightmap_capture_create() override { + LightmapCapture *capture = memnew(LightmapCapture); + return lightmap_capture_data_owner.make_rid(capture); + } + Vector lightmap_capture_get_octree(RID p_capture) const override { + const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture); + ERR_FAIL_COND_V(!capture, Vector()); + return Vector(); + } + void lightmap_capture_set_octree_cell_transform(RID p_capture, const Transform &p_xform) override {} + Transform lightmap_capture_get_octree_cell_transform(RID p_capture) const override { return Transform(); } + void lightmap_capture_set_octree_cell_subdiv(RID p_capture, int p_subdiv) override {} + int lightmap_capture_get_octree_cell_subdiv(RID p_capture) const override { return 0; } + void lightmap_capture_set_energy(RID p_capture, float p_energy) override {} + float lightmap_capture_get_energy(RID p_capture) const override { return 0.0; } + const Vector *lightmap_capture_get_octree_ptr(RID p_capture) const override { + const LightmapCapture *capture = lightmap_capture_data_owner.getornull(p_capture); + ERR_FAIL_COND_V(!capture, nullptr); + return &capture->octree; + } +#endif + + RID lightmap_create() override { return RID(); } + + void lightmap_set_textures(RID p_lightmap, RID p_light, bool p_uses_spherical_haromics) override {} + void lightmap_set_probe_bounds(RID p_lightmap, const AABB &p_bounds) override {} + void lightmap_set_probe_interior(RID p_lightmap, bool p_interior) override {} + void lightmap_set_probe_capture_data(RID p_lightmap, const PackedVector3Array &p_points, const PackedColorArray &p_point_sh, const PackedInt32Array &p_tetrahedra, const PackedInt32Array &p_bsp_tree) override {} + PackedVector3Array lightmap_get_probe_capture_points(RID p_lightmap) const override { return PackedVector3Array(); } + PackedColorArray lightmap_get_probe_capture_sh(RID p_lightmap) const override { return PackedColorArray(); } + PackedInt32Array lightmap_get_probe_capture_tetrahedra(RID p_lightmap) const override { return PackedInt32Array(); } + PackedInt32Array lightmap_get_probe_capture_bsp_tree(RID p_lightmap) const override { return PackedInt32Array(); } + AABB lightmap_get_aabb(RID p_lightmap) const override { return AABB(); } + void lightmap_tap_sh_light(RID p_lightmap, const Vector3 &p_point, Color *r_sh) override {} + bool lightmap_is_interior(RID p_lightmap) const override { return false; } + void lightmap_set_probe_capture_update_speed(float p_speed) override {} + float lightmap_get_probe_capture_update_speed() const override { return 0; } + + // PARTICLES + + RID particles_create() override { return RID(); } + + void particles_emit(RID p_particles, const Transform &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) override {} + void particles_set_emitting(RID p_particles, bool p_emitting) override {} + void particles_set_amount(RID p_particles, int p_amount) override {} + void particles_set_lifetime(RID p_particles, float p_lifetime) override {} + void particles_set_one_shot(RID p_particles, bool p_one_shot) override {} + void particles_set_pre_process_time(RID p_particles, float p_time) override {} + void particles_set_explosiveness_ratio(RID p_particles, float p_ratio) override {} + void particles_set_randomness_ratio(RID p_particles, float p_ratio) override {} + void particles_set_custom_aabb(RID p_particles, const AABB &p_aabb) override {} + void particles_set_speed_scale(RID p_particles, float p_scale) override {} + void particles_set_use_local_coordinates(RID p_particles, bool p_enable) override {} + void particles_set_process_material(RID p_particles, RID p_material) override {} + void particles_set_fixed_fps(RID p_particles, int p_fps) override {} + void particles_set_fractional_delta(RID p_particles, bool p_enable) override {} + void particles_set_subemitter(RID p_particles, RID p_subemitter_particles) override {} + void particles_set_view_axis(RID p_particles, const Vector3 &p_axis) override {} + void particles_set_collision_base_size(RID p_particles, float p_size) override {} + void particles_restart(RID p_particles) override {} + + void particles_set_draw_order(RID p_particles, RS::ParticlesDrawOrder p_order) override {} + + void particles_set_draw_passes(RID p_particles, int p_count) override {} + void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) override {} + + void particles_request_process(RID p_particles) override {} + AABB particles_get_current_aabb(RID p_particles) override { return AABB(); } + AABB particles_get_aabb(RID p_particles) const override { return AABB(); } + + void particles_set_emission_transform(RID p_particles, const Transform &p_transform) override {} + + bool particles_get_emitting(RID p_particles) override { return false; } + int particles_get_draw_passes(RID p_particles) const override { return 0; } + RID particles_get_draw_pass_mesh(RID p_particles, int p_pass) const override { return RID(); } + + void particles_add_collision(RID p_particles, RID p_particles_collision_instance) override {} + void particles_remove_collision(RID p_particles, RID p_particles_collision_instance) override {} + + void update_particles() override {} + + // PARTICLES COLLISION + + RID particles_collision_create() override { return RID(); } + void particles_collision_set_collision_type(RID p_particles_collision, RS::ParticlesCollisionType p_type) override {} + void particles_collision_set_cull_mask(RID p_particles_collision, uint32_t p_cull_mask) override {} + void particles_collision_set_sphere_radius(RID p_particles_collision, float p_radius) override {} + void particles_collision_set_box_extents(RID p_particles_collision, const Vector3 &p_extents) override {} + void particles_collision_set_attractor_strength(RID p_particles_collision, float p_strength) override {} + void particles_collision_set_attractor_directionality(RID p_particles_collision, float p_directionality) override {} + void particles_collision_set_attractor_attenuation(RID p_particles_collision, float p_curve) override {} + void particles_collision_set_field_texture(RID p_particles_collision, RID p_texture) override {} + void particles_collision_height_field_update(RID p_particles_collision) override {} + void particles_collision_set_height_field_resolution(RID p_particles_collision, RS::ParticlesCollisionHeightfieldResolution p_resolution) override {} + AABB particles_collision_get_aabb(RID p_particles_collision) const override { return AABB(); } + bool particles_collision_is_heightfield(RID p_particles_collision) const override { return false; } + RID particles_collision_get_heightfield_framebuffer(RID p_particles_collision) const override { return RID(); } + + //used from 2D and 3D + RID particles_collision_instance_create(RID p_collision) override { return RID(); } + void particles_collision_instance_set_transform(RID p_collision_instance, const Transform &p_transform) override {} + void particles_collision_instance_set_active(RID p_collision_instance, bool p_active) override {} + + // GLOBAL VARIABLES + + void global_variable_add(const StringName &p_name, RS::GlobalVariableType p_type, const Variant &p_value) override {} + void global_variable_remove(const StringName &p_name) override {} + Vector global_variable_get_list() const override { return Vector(); } + + void global_variable_set(const StringName &p_name, const Variant &p_value) override {} + void global_variable_set_override(const StringName &p_name, const Variant &p_value) override {} + Variant global_variable_get(const StringName &p_name) const override { return Variant(); } + RS::GlobalVariableType global_variable_get_type(const StringName &p_name) const override { return RS::GLOBAL_VAR_TYPE_MAX; } + + void global_variables_load_settings(bool p_load_textures = true) override {} + void global_variables_clear() override {} + + int32_t global_variables_instance_allocate(RID p_instance) override { return 0; } + void global_variables_instance_free(RID p_instance) override {} + void global_variables_instance_update(RID p_instance, int p_index, const Variant &p_value) override {} + + bool particles_is_inactive(RID p_particles) const override { return false; } + + // RENDER TARGET + + RID render_target_create() override { return RID(); } + void render_target_set_position(RID p_render_target, int p_x, int p_y) override {} + void render_target_set_size(RID p_render_target, int p_width, int p_height) override {} + RID render_target_get_texture(RID p_render_target) override { return RID(); } + void render_target_set_external_texture(RID p_render_target, unsigned int p_texture_id) override {} + void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) override {} + bool render_target_was_used(RID p_render_target) override { return false; } + void render_target_set_as_unused(RID p_render_target) override {} + + void render_target_request_clear(RID p_render_target, const Color &p_clear_color) override {} + bool render_target_is_clear_requested(RID p_render_target) override { return false; } + Color render_target_get_clear_request_color(RID p_render_target) override { return Color(); } + void render_target_disable_clear_request(RID p_render_target) override {} + void render_target_do_clear_request(RID p_render_target) override {} + + void render_target_set_sdf_size_and_scale(RID p_render_target, RS::ViewportSDFOversize p_size, RS::ViewportSDFScale p_scale) override {} + Rect2i render_target_get_sdf_rect(RID p_render_target) const override { return Rect2i(); } + + RS::InstanceType get_base_type(RID p_rid) const override { + if (mesh_owner.owns(p_rid)) { + return RS::INSTANCE_MESH; + } + + return RS::INSTANCE_NONE; + } + + bool free(RID p_rid) override { + if (texture_owner.owns(p_rid)) { + // delete the texture + DummyTexture *texture = texture_owner.getornull(p_rid); + texture_owner.free(p_rid); + memdelete(texture); + } + + if (mesh_owner.owns(p_rid)) { + // delete the mesh + DummyMesh *mesh = mesh_owner.getornull(p_rid); + mesh_owner.free(p_rid); + memdelete(mesh); + } + return true; + } + + bool has_os_feature(const String &p_feature) const override { return false; } + + void update_dirty_resources() override {} + + void set_debug_generate_wireframes(bool p_generate) override {} + + void render_info_begin_capture() override {} + void render_info_end_capture() override {} + int get_captured_render_info(RS::RenderInfo p_info) override { return 0; } + + int get_render_info(RS::RenderInfo p_info) override { return 0; } + String get_video_adapter_name() const override { return String(); } + String get_video_adapter_vendor() const override { return String(); } + + static RendererStorage *base_singleton; + + void capture_timestamps_begin() override {} + void capture_timestamp(const String &p_name) override {} + uint32_t get_captured_timestamps_count() const override { return 0; } + uint64_t get_captured_timestamps_frame() const override { return 0; } + uint64_t get_captured_timestamp_gpu_time(uint32_t p_index) const override { return 0; } + uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const override { return 0; } + String get_captured_timestamp_name(uint32_t p_index) const override { return String(); } + StubsStorage() {} + ~StubsStorage() {} +}; +*/ + +/* SCENE +public: +GeometryInstance *geometry_instance_create(RID p_base) override { return nullptr; } +void geometry_instance_set_skeleton(GeometryInstance *p_geometry_instance, RID p_skeleton) override {} +void geometry_instance_set_material_override(GeometryInstance *p_geometry_instance, RID p_override) override {} +void geometry_instance_set_surface_materials(GeometryInstance *p_geometry_instance, const Vector &p_material) override {} +void geometry_instance_set_mesh_instance(GeometryInstance *p_geometry_instance, RID p_mesh_instance) override {} +void geometry_instance_set_transform(GeometryInstance *p_geometry_instance, const Transform &p_transform, const AABB &p_aabb, const AABB &p_transformed_aabbb) override {} +void geometry_instance_set_layer_mask(GeometryInstance *p_geometry_instance, uint32_t p_layer_mask) override {} +void geometry_instance_set_lod_bias(GeometryInstance *p_geometry_instance, float p_lod_bias) override {} +void geometry_instance_set_use_baked_light(GeometryInstance *p_geometry_instance, bool p_enable) override {} +void geometry_instance_set_use_dynamic_gi(GeometryInstance *p_geometry_instance, bool p_enable) override {} +void geometry_instance_set_use_lightmap(GeometryInstance *p_geometry_instance, RID p_lightmap_instance, const Rect2 &p_lightmap_uv_scale, int p_lightmap_slice_index) override {} +void geometry_instance_set_lightmap_capture(GeometryInstance *p_geometry_instance, const Color *p_sh9) override {} +void geometry_instance_set_instance_shader_parameters_offset(GeometryInstance *p_geometry_instance, int32_t p_offset) override {} +void geometry_instance_set_cast_double_sided_shadows(GeometryInstance *p_geometry_instance, bool p_enable) override {} + +uint32_t geometry_instance_get_pair_mask() override { return 0; } +void geometry_instance_pair_light_instances(GeometryInstance *p_geometry_instance, const RID *p_light_instances, uint32_t p_light_instance_count) override {} +void geometry_instance_pair_reflection_probe_instances(GeometryInstance *p_geometry_instance, const RID *p_reflection_probe_instances, uint32_t p_reflection_probe_instance_count) override {} +void geometry_instance_pair_decal_instances(GeometryInstance *p_geometry_instance, const RID *p_decal_instances, uint32_t p_decal_instance_count) override {} +void geometry_instance_pair_gi_probe_instances(GeometryInstance *p_geometry_instance, const RID *p_gi_probe_instances, uint32_t p_gi_probe_instance_count) override {} + +void geometry_instance_free(GeometryInstance *p_geometry_instance) override {} + +// SHADOW ATLAS API + +RID shadow_atlas_create() override { return RID(); } +void shadow_atlas_set_size(RID p_atlas, int p_size) override {} +void shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) override {} +bool shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) override { return false; } + +void directional_shadow_atlas_set_size(int p_size) override {} +int get_directional_light_shadow_size(RID p_light_intance) override { return 0; } +void set_directional_shadow_count(int p_count) override {} + +// SDFGI UPDATE + +void sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) override {} +int sdfgi_get_pending_region_count(RID p_render_buffers) const override { return 0; } +AABB sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const override { return AABB(); } +uint32_t sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const override { return 0; } +void sdfgi_update_probes(RID p_render_buffers, RID p_environment, const Vector &p_directional_lights, const RID *p_positional_light_instances, uint32_t p_positional_light_count) override {} + +// SKY API + +RID sky_create() override { return RID(); } +void sky_set_radiance_size(RID p_sky, int p_radiance_size) override {} +void sky_set_mode(RID p_sky, RS::SkyMode p_samples) override {} +void sky_set_material(RID p_sky, RID p_material) override {} +Ref sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) override { return Ref(); } + +// ENVIRONMENT API + +RID environment_create() override { return RID(); } + +void environment_set_background(RID p_env, RS::EnvironmentBG p_bg) override {} +void environment_set_sky(RID p_env, RID p_sky) override {} +void environment_set_sky_custom_fov(RID p_env, float p_scale) override {} +void environment_set_sky_orientation(RID p_env, const Basis &p_orientation) override {} +void environment_set_bg_color(RID p_env, const Color &p_color) override {} +void environment_set_bg_energy(RID p_env, float p_energy) override {} +void environment_set_canvas_max_layer(RID p_env, int p_max_layer) override {} +void environment_set_ambient_light(RID p_env, const Color &p_color, RS::EnvironmentAmbientSource p_ambient = RS::ENV_AMBIENT_SOURCE_BG, float p_energy = 1.0, float p_sky_contribution = 0.0, RS::EnvironmentReflectionSource p_reflection_source = RS::ENV_REFLECTION_SOURCE_BG, const Color &p_ao_color = Color()) override {} + +void environment_set_glow(RID p_env, bool p_enable, Vector p_levels, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap) override {} +void environment_glow_set_use_bicubic_upscale(bool p_enable) override {} +void environment_glow_set_use_high_quality(bool p_enable) override {} + +void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance) override {} +void environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) override {} +void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_power, float p_detail, float p_horizon, float p_sharpness, float p_light_affect, float p_ao_channel_affect) override {} +void environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size, float p_adaptive_target, int p_blur_passes, float p_fadeout_from, float p_fadeout_to) override {} + +void environment_set_sdfgi(RID p_env, bool p_enable, RS::EnvironmentSDFGICascades p_cascades, float p_min_cell_size, RS::EnvironmentSDFGIYScale p_y_scale, bool p_use_occlusion, bool p_use_multibounce, bool p_read_sky, float p_energy, float p_normal_bias, float p_probe_bias) override {} + +void environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) override {} +void environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) override {} + +void environment_set_tonemap(RID p_env, RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) override {} + +void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, bool p_use_1d_color_correction, RID p_color_correction) override {} + +void environment_set_fog(RID p_env, bool p_enable, const Color &p_light_color, float p_light_energy, float p_sun_scatter, float p_density, float p_height, float p_height_density, float p_aerial_perspective) override {} +void environment_set_volumetric_fog(RID p_env, bool p_enable, float p_density, const Color &p_light, float p_light_energy, float p_length, float p_detail_spread, float p_gi_inject, RS::EnvVolumetricFogShadowFilter p_shadow_filter) override {} +void environment_set_volumetric_fog_volume_size(int p_size, int p_depth) override {} +void environment_set_volumetric_fog_filter_active(bool p_enable) override {} +void environment_set_volumetric_fog_directional_shadow_shrink_size(int p_shrink_size) override {} +void environment_set_volumetric_fog_positional_shadow_shrink_size(int p_shrink_size) override {} + +Ref environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) override { return Ref(); } + +bool is_environment(RID p_env) const override { return false; } +RS::EnvironmentBG environment_get_background(RID p_env) const override { return RS::ENV_BG_KEEP; } +int environment_get_canvas_max_layer(RID p_env) const override { return 0; } + +RID camera_effects_create() override { return RID(); } + +void camera_effects_set_dof_blur_quality(RS::DOFBlurQuality p_quality, bool p_use_jitter) override {} +void camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape p_shape) override {} + +void camera_effects_set_dof_blur(RID p_camera_effects, bool p_far_enable, float p_far_distance, float p_far_transition, bool p_near_enable, float p_near_distance, float p_near_transition, float p_amount) override {} +void camera_effects_set_custom_exposure(RID p_camera_effects, bool p_enable, float p_exposure) override {} + +void shadows_quality_set(RS::ShadowQuality p_quality) override {} +void directional_shadow_quality_set(RS::ShadowQuality p_quality) override {} + +RID light_instance_create(RID p_light) override { return RID(); } +void light_instance_set_transform(RID p_light_instance, const Transform &p_transform) override {} +void light_instance_set_aabb(RID p_light_instance, const AABB &p_aabb) override {} +void light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_shadow_texel_size, float p_bias_scale = 1.0, float p_range_begin = 0, const Vector2 &p_uv_scale = Vector2()) override {} +void light_instance_mark_visible(RID p_light_instance) override {} + +RID reflection_atlas_create() override { return RID(); } +void reflection_atlas_set_size(RID p_ref_atlas, int p_reflection_size, int p_reflection_count) override {} +int reflection_atlas_get_size(RID p_ref_atlas) const override { return 0; } + +RID reflection_probe_instance_create(RID p_probe) override { return RID(); } +void reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) override {} +void reflection_probe_release_atlas_index(RID p_instance) override {} +bool reflection_probe_instance_needs_redraw(RID p_instance) override { return false; } +bool reflection_probe_instance_has_reflection(RID p_instance) override { return false; } +bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) override { return false; } +bool reflection_probe_instance_postprocess_step(RID p_instance) override { return true; } + +RID decal_instance_create(RID p_decal) override { return RID(); } +void decal_instance_set_transform(RID p_decal, const Transform &p_transform) override {} + +RID lightmap_instance_create(RID p_lightmap) override { return RID(); } +void lightmap_instance_set_transform(RID p_lightmap, const Transform &p_transform) override {} + +RID gi_probe_instance_create(RID p_gi_probe) override { return RID(); } +void gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) override {} +bool gi_probe_needs_update(RID p_probe) const override { return false; } +void gi_probe_update(RID p_probe, bool p_update_light_instances, const Vector &p_light_instances, const PagedArray &p_dynamic_objects) override {} + +void gi_probe_set_quality(RS::GIProbeQuality) override {} + +void render_scene(RID p_render_buffers, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray &p_instances, const PagedArray &p_lights, const PagedArray &p_reflection_probes, const PagedArray &p_gi_probes, const PagedArray &p_decals, const PagedArray &p_lightmaps, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_lod_threshold) override {} + +void render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, const PagedArray &p_instances, const Plane &p_camera_plane = Plane(), float p_lod_distance_multiplier = 0, float p_screen_lod_threshold = 0.0) override {} + +void render_material(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, const PagedArray &p_instances, RID p_framebuffer, const Rect2i &p_region) override {} + +void render_sdfgi(RID p_render_buffers, int p_region, const PagedArray &p_instances) override {} + +void render_sdfgi_static_lights(RID p_render_buffers, uint32_t p_cascade_count, const uint32_t *p_cascade_indices, const PagedArray *p_positional_lights) override {} + +void render_particle_collider_heightfield(RID p_collider, const Transform &p_transform, const PagedArray &p_instances) override {} + +void set_scene_pass(uint64_t p_pass) override {} +void set_time(double p_time, double p_step) override {} +void set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) override {} + +RID render_buffers_create() override { return RID(); } +void render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_width, int p_height, RS::ViewportMSAA p_msaa, RS::ViewportScreenSpaceAA p_screen_space_aa, bool p_use_debanding) override {} + +void screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_curve) override {} +bool screen_space_roughness_limiter_is_active() const override { return false; } + +void sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) override {} +void sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) override {} + +TypedArray bake_render_uv2(RID p_base, const Vector &p_material_overrides, const Size2i &p_image_size) override { return TypedArray(); } + +bool free(RID p_rid) override { return true; } +void update() override {} +void sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) override {} + +bool is_low_end() const override { return true; } +*/ + +/* +class StubsCanvas : public RendererCanvasRender { +public: + PolygonID request_polygon(const Vector &p_indices, const Vector &p_points, const Vector &p_colors, const Vector &p_uvs = Vector(), const Vector &p_bones = Vector(), const Vector &p_weights = Vector()) override { return 0; } + void free_polygon(PolygonID p_polygon) override {} + + void canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_list, const Transform2D &p_canvas_transform, RS::CanvasItemTextureFilter p_default_filter, RS::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used) override {} + void canvas_debug_viewport_shadows(Light *p_lights_with_shadow) override {} + + RID light_create() override { return RID(); } + void light_set_texture(RID p_rid, RID p_texture) override {} + void light_set_use_shadow(RID p_rid, bool p_enable) override {} + void light_update_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders) override {} + void light_update_directional_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_cull_distance, const Rect2 &p_clip_rect, LightOccluderInstance *p_occluders) override {} + + void render_sdf(RID p_render_target, LightOccluderInstance *p_occluders) override {} + RID occluder_polygon_create() override { return RID(); } + void occluder_polygon_set_shape(RID p_occluder, const Vector &p_points, bool p_closed) override {} + void occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) override {} + void set_shadow_texture_size(int p_size) override {} + + void draw_window_margins(int *p_margins, RID *p_margin_textures) override {} + + bool free(RID p_rid) override { return true; } + void update() override {} + + StubsCanvas() {} + ~StubsCanvas() {} +}; + + +*/ diff --git a/drivers/gles_common/rasterizer_platforms.h b/drivers/gles_common/rasterizer_platforms.h new file mode 100644 index 00000000000..f1b950b71aa --- /dev/null +++ b/drivers/gles_common/rasterizer_platforms.h @@ -0,0 +1,73 @@ +/*************************************************************************/ +/* rasterizer_platforms.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +///////////////////////////////////////////////////// +// override for intellisense .. ONLY FOR DEVELOPMENT +//#ifndef X11_ENABLED +//#define X11_ENABLED +//#endif +//#define GLES2_BACKEND_ENABLED +///////////////////////////////////////////////////// + +#if defined(OPENGL_ENABLED) || defined(GLES_ENABLED) + +// platform specific defines to compile in / out GLES support +// these can later be made from Scons +#ifdef X11_ENABLED +#define GLES_X11_ENABLED +#endif + +#ifdef WINDOWS_ENABLED +//#define GLES_WINDOWS_ENABLED +#endif + +#ifdef IPHONE_ENABLED +//#define GLES_IPHONE_ENABLED +#endif + +#ifdef OSX_ENABLED +//#define GLES_OSX_ENABLED +#endif + +#ifdef ANDROID_ENABLED +//#define GLES_ANDROID_ENABLED +#endif + +#if defined(GLES_X11_ENABLED) || defined(GLES_WINDOW_ENABLED) || defined(GLES_IPHONE_ENABLED) || defined(GLES_OSX_ENABLED) || defined(GLES_ANDROID_ENABLED) +#define GLES2_BACKEND_ENABLED +#endif + +#if defined(GLES_X11_ENABLED) || defined(GLES_WINDOW_ENABLED) || defined(GLES_IPHONE_ENABLED) || defined(GLES_OSX_ENABLED) || defined(GLES_ANDROID_ENABLED) +#define GLES3_BACKEND_ENABLED +#endif + +#endif // defined(OPENGL_ENABLED) || defined(GLES_ENABLED) diff --git a/drivers/gles_common/rasterizer_storage_common.h b/drivers/gles_common/rasterizer_storage_common.h new file mode 100644 index 00000000000..ed64b8c50a3 --- /dev/null +++ b/drivers/gles_common/rasterizer_storage_common.h @@ -0,0 +1,77 @@ +/*************************************************************************/ +/* rasterizer_storage_common.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef RASTERIZER_STORAGE_COMMON_H +#define RASTERIZER_STORAGE_COMMON_H + +class RasterizerStorageCommon { +public: + enum FVF { + FVF_UNBATCHED, + FVF_REGULAR, + FVF_COLOR, + FVF_LIGHT_ANGLE, + FVF_MODULATED, + FVF_LARGE, + }; + + // these flags are specifically for batching + // some of the logic is thus in rasterizer_storage.cpp + // we could alternatively set bitflags for each 'uses' and test on the fly + enum BatchFlags { + PREVENT_COLOR_BAKING = 1 << 0, + PREVENT_VERTEX_BAKING = 1 << 1, + + // custom vertex shaders using BUILTINS that vary per item + PREVENT_ITEM_JOINING = 1 << 2, + + USE_MODULATE_FVF = 1 << 3, + USE_LARGE_FVF = 1 << 4, + }; + + enum BatchType : uint16_t { + BT_DEFAULT = 0, + BT_RECT = 1, + BT_LINE = 2, + BT_LINE_AA = 3, + BT_POLY = 4, + BT_DUMMY = 5, // dummy batch is just used to keep the batch creation loop simple + }; + + enum BatchTypeFlags { + BTF_DEFAULT = 1 << BT_DEFAULT, + BTF_RECT = 1 << BT_RECT, + BTF_LINE = 1 << BT_LINE, + BTF_LINE_AA = 1 << BT_LINE_AA, + BTF_POLY = 1 << BT_POLY, + }; +}; + +#endif // RASTERIZER_STORAGE_COMMON_H diff --git a/platform/windows/context_gl_windows.h b/drivers/gles_common/rasterizer_version.h similarity index 68% rename from platform/windows/context_gl_windows.h rename to drivers/gles_common/rasterizer_version.h index feff1d825b4..25e76f09078 100644 --- a/platform/windows/context_gl_windows.h +++ b/drivers/gles_common/rasterizer_version.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* context_gl_windows.h */ +/* rasterizer_version.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,50 +28,57 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#if defined(OPENGL_ENABLED) || defined(GLES_ENABLED) +#pragma once -// Author: Juan Linietsky , (C) 2008 +//#define GLES_OVER_GL -#ifndef CONTEXT_GL_WIN_H -#define CONTEXT_GL_WIN_H +//#define GODOT_3 +#define GODOT_4 -#include "core/error/error_list.h" -#include "core/os/os.h" +#ifdef GODOT_4 +// visual server becomes rendering server +#define GD_VS RS -#define WIN32_LEAN_AND_MEAN -#include +#define GD_RD RenderingDevice -typedef bool(APIENTRY *PFNWGLSWAPINTERVALEXTPROC)(int interval); -typedef int(APIENTRY *PFNWGLGETSWAPINTERVALEXTPROC)(void); +//#define GD_COMMAND_LINE CommandPrimitive +#else -class ContextGL_Windows { - HDC hDC; - HGLRC hRC; - unsigned int pixel_format; - HWND hWnd; - bool opengl_3_context; - bool use_vsync; +//class ContextGL_Windows { +// HDC hDC; +// HGLRC hRC; +// unsigned int pixel_format; +// HWND hWnd; +// bool opengl_3_context; +// bool use_vsync; +#define GD_VS VS - PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; - PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT; +// no rendering device in 3.2? +#define GD_RD VS -public: - void release_current(); +//public: +// void release_current(); - void make_current(); +// void make_current(); - int get_window_width(); - int get_window_height(); - void swap_buffers(); +// int get_window_width(); +// int get_window_height(); +// void swap_buffers(); - Error initialize(); +// Error initialize(); - void set_use_vsync(bool p_use); - bool is_using_vsync() const; +// void set_use_vsync(bool p_use); +// bool is_using_vsync() const; - ContextGL_Windows(HWND hwnd, bool p_opengl_3_context); - ~ContextGL_Windows(); -}; +// ContextGL_Windows(HWND hwnd, bool p_opengl_3_context); +// ~ContextGL_Windows(); +//}; -#endif +//#endif +//#define GD_COMMAND_LINE CommandLine + +#define GD_TYPE_LINE TYPE_LINE +#define GD_TYPE_POLYLINE TYPE_POLYLINE +#define GD_TYPE_POLYGON TYPE_POLYGON +#define GD_TYPE_CIRCLE TYPE_CIRCLE #endif diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp index 2010ee01db5..4909ac7a3fb 100644 --- a/editor/editor_export.cpp +++ b/editor/editor_export.cpp @@ -1491,6 +1491,9 @@ void EditorExport::add_export_preset(const Ref &p_preset, in } String EditorExportPlatform::test_etc2() const { +// String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); +// bool etc_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc"); +// bool etc2_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc2"); String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); bool etc_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc"); bool etc2_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc2"); @@ -1508,6 +1511,9 @@ String EditorExportPlatform::test_etc2_or_pvrtc() const { String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); bool etc2_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc2"); bool pvrtc_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_pvrtc"); +// String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); +// bool etc2_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_etc2"); +// bool pvrtc_supported = ProjectSettings::get_singleton()->get("rendering/textures/vram_compression/import_pvrtc"); if (driver == "GLES2" && !pvrtc_supported) { return TTR("Target platform requires 'PVRTC' texture compression for GLES2. Enable 'Import Pvrtc' in Project Settings."); diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 288b6752eed..9e84718fb7b 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -589,6 +589,11 @@ void EditorNode::_notification(int p_what) { settings_changed = false; emit_signal(SNAME("project_settings_changed")); } + + ResourceImporterTexture::get_singleton()->update_imports(); + + // if using a main thread only renderer, we need to update the resource previews + EditorResourcePreview::get_singleton()->update(); } break; case NOTIFICATION_ENTER_TREE: { @@ -2903,8 +2908,13 @@ void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) { OS::get_singleton()->shell_open("https://godotengine.org/donate"); } break; - case SET_VIDEO_DRIVER_SAVE_AND_RESTART: { - ProjectSettings::get_singleton()->set("rendering/driver/driver_name", video_driver_request); + // case SET_VIDEO_DRIVER_SAVE_AND_RESTART: { + // ProjectSettings::get_singleton()->set("rendering/driver/driver_name", video_driver_request); + // save_all_scenes(); + // restart_editor(); + // } break; + case SET_RENDERING_DRIVER_SAVE_AND_RESTART: { + ProjectSettings::get_singleton()->set("rendering/driver/driver_name", rendering_driver_request); ProjectSettings::get_singleton()->save(); save_all_scenes(); @@ -5585,17 +5595,21 @@ void EditorNode::_bottom_panel_raise_toggled(bool p_pressed) { top_split->set_visible(!p_pressed); } -void EditorNode::_update_video_driver_color() { +void EditorNode::_update_rendering_driver_color() { // TODO: Probably should de-hardcode this and add to editor settings. - if (video_driver->get_text() == "GLES2") { - video_driver->add_theme_color_override("font_color", Color::hex(0x5586a4ff)); - } else if (video_driver->get_text() == "Vulkan") { - video_driver->add_theme_color_override("font_color", theme_base->get_theme_color(SNAME("vulkan_color"), SNAME("Editor"))); + // if (video_driver->get_text() == "GLES2") { + // video_driver->add_theme_color_override("font_color", Color::hex(0x5586a4ff)); + // } else if (video_driver->get_text() == "Vulkan") { + // video_driver->add_theme_color_override("font_color", theme_base->get_theme_color(SNAME("vulkan_color"), SNAME("Editor"))); + if (rendering_driver->get_text() == "GLES2") { + rendering_driver->add_theme_color_override("font_color", Color::hex(0x5586a4ff)); + } else if (rendering_driver->get_text() == "Vulkan") { + rendering_driver->add_theme_color_override("font_color", theme_base->get_theme_color("vulkan_color", "Editor")); } } -void EditorNode::_video_driver_selected(int p_which) { - String driver = video_driver->get_item_metadata(p_which); +void EditorNode::_rendering_driver_selected(int p_which) { + String driver = rendering_driver->get_item_metadata(p_which); String current = ""; // OS::get_singleton()->get_video_driver_name(OS::get_singleton()->get_current_video_driver()); @@ -5603,10 +5617,10 @@ void EditorNode::_video_driver_selected(int p_which) { return; } - video_driver_request = driver; + rendering_driver_request = driver; video_restart_dialog->popup_centered(); - video_driver->select(video_driver_current); - _update_video_driver_color(); + rendering_driver->select(rendering_driver_current); + _update_rendering_driver_color(); } void EditorNode::_resource_saved(RES p_resource, const String &p_path) { @@ -6611,39 +6625,90 @@ EditorNode::EditorNode() { menu_hb->add_child(right_menu_hb); // Toggle for video driver - video_driver = memnew(OptionButton); - video_driver->set_focus_mode(Control::FOCUS_NONE); - video_driver->connect("item_selected", callable_mp(this, &EditorNode::_video_driver_selected)); - video_driver->add_theme_font_override("font", gui_base->get_theme_font(SNAME("bold"), SNAME("EditorFonts"))); - video_driver->add_theme_font_size_override("font_size", gui_base->get_theme_font_size(SNAME("bold_size"), SNAME("EditorFonts"))); - // TODO: Show again when OpenGL is ported. - video_driver->set_visible(false); - right_menu_hb->add_child(video_driver); + // video_driver = memnew(OptionButton); + // video_driver->set_focus_mode(Control::FOCUS_NONE); + // video_driver->connect("item_selected", callable_mp(this, &EditorNode::_video_driver_selected)); + // video_driver->add_theme_font_override("font", gui_base->get_theme_font(SNAME("bold"), SNAME("EditorFonts"))); + // video_driver->add_theme_font_size_override("font_size", gui_base->get_theme_font_size(SNAME("bold_size"), SNAME("EditorFonts"))); + // // TODO: Show again when OpenGL is ported. + // video_driver->set_visible(false); + // right_menu_hb->add_child(video_driver); -#ifndef _MSC_VER -#warning needs to be reimplemented -#endif -#if 0 - String video_drivers = ProjectSettings::get_singleton()->get_custom_property_info()["rendering/driver/driver_name"].hint_string; - String current_video_driver = OS::get_singleton()->get_video_driver_name(OS::get_singleton()->get_current_video_driver()); - video_driver_current = 0; - for (int i = 0; i < video_drivers.get_slice_count(","); i++) { - String driver = video_drivers.get_slice(",", i); - video_driver->add_item(driver); - video_driver->set_item_metadata(i, driver); + //#ifndef _MSC_VER + //#warning needs to be reimplemented + //#endif + //#if 0 + // String video_drivers = ProjectSettings::get_singleton()->get_custom_property_info()["rendering/driver/driver_name"].hint_string; + // String current_video_driver = OS::get_singleton()->get_video_driver_name(OS::get_singleton()->get_current_video_driver()); + // video_driver_current = 0; + // for (int i = 0; i < video_drivers.get_slice_count(","); i++) { + // String driver = video_drivers.get_slice(",", i); + // video_driver->add_item(driver); + // video_driver->set_item_metadata(i, driver); + rendering_driver = memnew(OptionButton); + rendering_driver->set_flat(true); + rendering_driver->set_focus_mode(Control::FOCUS_NONE); + rendering_driver->connect("item_selected", callable_mp(this, &EditorNode::_rendering_driver_selected)); + rendering_driver->add_theme_font_override("font", gui_base->get_theme_font("bold", "EditorFonts")); + rendering_driver->add_theme_font_size_override("font_size", gui_base->get_theme_font_size("bold_size", "EditorFonts")); - if (current_video_driver == driver) { - video_driver->select(i); - video_driver_current = i; + // TODO re-enable when GLES2 is ported + // video_driver->set_disabled(true); + right_menu_hb->add_child(rendering_driver); + + // only display the render drivers that are available for this display driver + int display_driver_idx = OS::get_singleton()->get_display_driver_id(); + Vector render_drivers = DisplayServer::get_create_function_rendering_drivers(display_driver_idx); + String current_rendering_driver = OS::get_singleton()->get_current_rendering_driver_name(); + + // as we are doing string comparisons, keep in standard case to prevent problems with capitals + // 'vulkan' in particular uses lower case v in the code, and upper case in the UI . + current_rendering_driver = current_rendering_driver.to_lower(); + + for (int i = 0; i < render_drivers.size(); i++) { + String driver = render_drivers[i]; + + // add the driver to the user interface + rendering_driver->add_item(driver); + rendering_driver->set_item_metadata(i, driver); + + // lower case for standard comparison + driver = driver.to_lower(); + + if (current_rendering_driver == driver) { + rendering_driver->select(i); + rendering_driver_current = i; } } +#if 0 + // commented out old version, gets the driver list from the project settings + // just in case we decide to revert to this method + String rendering_drivers = ProjectSettings::get_singleton()->get_custom_property_info()["rendering/driver/driver_name"].hint_string; + String current_rendering_driver = OS::get_singleton()->get_current_rendering_driver_name(); + current_rendering_driver = current_rendering_driver.to_lower(); + print_line("current_rendering_driver " + current_rendering_driver); - _update_video_driver_color(); + rendering_driver_current = 0; + for (int i = 0; i < rendering_drivers.get_slice_count(","); i++) { + String driver = rendering_drivers.get_slice(",", i); + rendering_driver->add_item(driver); + rendering_driver->set_item_metadata(i, driver); + + driver = driver.to_lower(); + print_line("\tdriver " + driver); + + if (current_rendering_driver == driver) { + rendering_driver->select(i); + rendering_driver_current = i; + } + } #endif + _update_rendering_driver_color(); + video_restart_dialog = memnew(ConfirmationDialog); video_restart_dialog->set_text(TTR("Changing the video driver requires restarting the editor.")); video_restart_dialog->get_ok_button()->set_text(TTR("Save & Restart")); - video_restart_dialog->connect("confirmed", callable_mp(this, &EditorNode::_menu_option), varray(SET_VIDEO_DRIVER_SAVE_AND_RESTART)); + video_restart_dialog->connect("confirmed", callable_mp(this, &EditorNode::_menu_option), varray(SET_RENDERING_DRIVER_SAVE_AND_RESTART)); gui_base->add_child(video_restart_dialog); progress_hb = memnew(BackgroundProgress); diff --git a/editor/editor_node.h b/editor/editor_node.h index 03e5146d989..98aa4b697cc 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -206,7 +206,7 @@ private: HELP_ABOUT, HELP_SUPPORT_GODOT_DEVELOPMENT, - SET_VIDEO_DRIVER_SAVE_AND_RESTART, + SET_RENDERING_DRIVER_SAVE_AND_RESTART, GLOBAL_NEW_WINDOW, GLOBAL_SCENE, @@ -222,14 +222,14 @@ private: Control *theme_base; Control *gui_base; VBoxContainer *main_vbox; - OptionButton *video_driver; + OptionButton *rendering_driver; ConfirmationDialog *video_restart_dialog; - int video_driver_current; - String video_driver_request; - void _video_driver_selected(int); - void _update_video_driver_color(); + int rendering_driver_current; + String rendering_driver_request; + void _rendering_driver_selected(int); + void _update_rendering_driver_color(); // Split containers diff --git a/editor/editor_resource_preview.cpp b/editor/editor_resource_preview.cpp index 8783fe4fc0c..e9c0b402682 100644 --- a/editor/editor_resource_preview.cpp +++ b/editor/editor_resource_preview.cpp @@ -210,126 +210,130 @@ void EditorResourcePreview::_generate_preview(Ref &r_texture, Ref< } } +void EditorResourcePreview::_iterate() { + preview_mutex.lock(); + + if (queue.size()) { + QueueItem item = queue.front()->get(); + queue.pop_front(); + + if (cache.has(item.path)) { + //already has it because someone loaded it, just let it know it's ready + String path = item.path; + if (item.resource.is_valid()) { + path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below) + } + + _preview_ready(path, cache[item.path].preview, cache[item.path].small_preview, item.id, item.function, item.userdata); + + preview_mutex.unlock(); + } else { + preview_mutex.unlock(); + + Ref texture; + Ref small_texture; + + int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size"); + thumbnail_size *= EDSCALE; + + if (item.resource.is_valid()) { + _generate_preview(texture, small_texture, item, String()); + + //adding hash to the end of path (should be ID::) because of 5 argument limit to call_deferred + _preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, small_texture, item.id, item.function, item.userdata); + + } else { + String temp_path = EditorPaths::get_singleton()->get_cache_dir(); + String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text(); + cache_base = temp_path.plus_file("resthumb-" + cache_base); + + //does not have it, try to load a cached thumbnail + + String file = cache_base + ".txt"; + FileAccess *f = FileAccess::open(file, FileAccess::READ); + if (!f) { + // No cache found, generate + _generate_preview(texture, small_texture, item, cache_base); + } else { + uint64_t modtime = FileAccess::get_modified_time(item.path); + int tsize = f->get_line().to_int(); + bool has_small_texture = f->get_line().to_int(); + uint64_t last_modtime = f->get_line().to_int(); + + bool cache_valid = true; + + if (tsize != thumbnail_size) { + cache_valid = false; + memdelete(f); + } else if (last_modtime != modtime) { + String last_md5 = f->get_line(); + String md5 = FileAccess::get_md5(item.path); + memdelete(f); + + if (last_md5 != md5) { + cache_valid = false; + + } else { + //update modified time + + f = FileAccess::open(file, FileAccess::WRITE); + if (!f) { + // Not returning as this would leave the thread hanging and would require + // some proper cleanup/disabling of resource preview generation. + ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions."); + } else { + f->store_line(itos(thumbnail_size)); + f->store_line(itos(has_small_texture)); + f->store_line(itos(modtime)); + f->store_line(md5); + memdelete(f); + } + } + } else { + memdelete(f); + } + + if (cache_valid) { + Ref img; + img.instantiate(); + Ref small_img; + small_img.instantiate(); + + if (img->load(cache_base + ".png") != OK) { + cache_valid = false; + } else { + texture.instantiate(); + texture->create_from_image(img); + + if (has_small_texture) { + if (small_img->load(cache_base + "_small.png") != OK) { + cache_valid = false; + } else { + small_texture.instantiate(); + small_texture->create_from_image(small_img); + } + } + } + } + + if (!cache_valid) { + _generate_preview(texture, small_texture, item, cache_base); + } + } + _preview_ready(item.path, texture, small_texture, item.id, item.function, item.userdata); + } + } + + } else { + preview_mutex.unlock(); + } +} + void EditorResourcePreview::_thread() { exited.clear(); while (!exit.is_set()) { preview_sem.wait(); - preview_mutex.lock(); - - if (queue.size()) { - QueueItem item = queue.front()->get(); - queue.pop_front(); - - if (cache.has(item.path)) { - //already has it because someone loaded it, just let it know it's ready - String path = item.path; - if (item.resource.is_valid()) { - path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below) - } - - _preview_ready(path, cache[item.path].preview, cache[item.path].small_preview, item.id, item.function, item.userdata); - - preview_mutex.unlock(); - } else { - preview_mutex.unlock(); - - Ref texture; - Ref small_texture; - - int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size"); - thumbnail_size *= EDSCALE; - - if (item.resource.is_valid()) { - _generate_preview(texture, small_texture, item, String()); - - //adding hash to the end of path (should be ID::) because of 5 argument limit to call_deferred - _preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, small_texture, item.id, item.function, item.userdata); - - } else { - String temp_path = EditorPaths::get_singleton()->get_cache_dir(); - String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text(); - cache_base = temp_path.plus_file("resthumb-" + cache_base); - - //does not have it, try to load a cached thumbnail - - String file = cache_base + ".txt"; - FileAccess *f = FileAccess::open(file, FileAccess::READ); - if (!f) { - // No cache found, generate - _generate_preview(texture, small_texture, item, cache_base); - } else { - uint64_t modtime = FileAccess::get_modified_time(item.path); - int tsize = f->get_line().to_int(); - bool has_small_texture = f->get_line().to_int(); - uint64_t last_modtime = f->get_line().to_int(); - - bool cache_valid = true; - - if (tsize != thumbnail_size) { - cache_valid = false; - memdelete(f); - } else if (last_modtime != modtime) { - String last_md5 = f->get_line(); - String md5 = FileAccess::get_md5(item.path); - memdelete(f); - - if (last_md5 != md5) { - cache_valid = false; - - } else { - //update modified time - - f = FileAccess::open(file, FileAccess::WRITE); - if (!f) { - // Not returning as this would leave the thread hanging and would require - // some proper cleanup/disabling of resource preview generation. - ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions."); - } else { - f->store_line(itos(thumbnail_size)); - f->store_line(itos(has_small_texture)); - f->store_line(itos(modtime)); - f->store_line(md5); - memdelete(f); - } - } - } else { - memdelete(f); - } - - if (cache_valid) { - Ref img; - img.instantiate(); - Ref small_img; - small_img.instantiate(); - - if (img->load(cache_base + ".png") != OK) { - cache_valid = false; - } else { - texture.instantiate(); - texture->create_from_image(img); - - if (has_small_texture) { - if (small_img->load(cache_base + "_small.png") != OK) { - cache_valid = false; - } else { - small_texture.instantiate(); - small_texture->create_from_image(small_img); - } - } - } - } - - if (!cache_valid) { - _generate_preview(texture, small_texture, item, cache_base); - } - } - _preview_ready(item.path, texture, small_texture, item.id, item.function, item.userdata); - } - } - - } else { - preview_mutex.unlock(); - } + _iterate(); } exited.set(); } @@ -429,8 +433,12 @@ void EditorResourcePreview::check_for_invalidation(const String &p_path) { } void EditorResourcePreview::start() { - ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started."); - thread.start(_thread_func, this); + if (OS::get_singleton()->get_render_main_thread_mode() == OS::RENDER_ANY_THREAD) { + ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started."); + thread.start(_thread_func, this); + } else { + _mainthread_only = true; + } } void EditorResourcePreview::stop() { @@ -453,3 +461,18 @@ EditorResourcePreview::EditorResourcePreview() { EditorResourcePreview::~EditorResourcePreview() { stop(); } + +void EditorResourcePreview::update() { + if (!_mainthread_only) { + return; + } + + if (!exit.is_set()) { + // no need to even lock the mutex if the size is zero + // there is no problem if queue.size() is wrong, even if + // there was a race condition. + if (queue.size()) { + _iterate(); + } + } +} diff --git a/editor/editor_resource_preview.h b/editor/editor_resource_preview.h index ea16c8fde05..9d1f269661a 100644 --- a/editor/editor_resource_preview.h +++ b/editor/editor_resource_preview.h @@ -81,6 +81,11 @@ class EditorResourcePreview : public Node { SafeFlag exit; SafeFlag exited; + // when running from GLES, we want to run the previews + // in the main thread using an update, rather than create + // a separate thread + bool _mainthread_only = false; + struct Item { Ref preview; Ref small_preview; @@ -98,6 +103,7 @@ class EditorResourcePreview : public Node { static void _thread_func(void *ud); void _thread(); + void _iterate(); Vector> preview_generators; @@ -119,6 +125,9 @@ public: void start(); void stop(); + // for single threaded mode + void update(); + EditorResourcePreview(); ~EditorResourcePreview(); }; diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index e8fd3070c29..2adcbe69d6d 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -475,6 +475,13 @@ private: } ProjectSettings::CustomMap initial_settings; initial_settings["rendering/vulkan/rendering/back_end"] = rasterizer_button_group->get_pressed_button()->get_meta(SNAME("driver_name")); + if (rasterizer_button_group->get_pressed_button()->get_meta("driver_name") == "Vulkan") { + initial_settings["rendering/driver/driver_name"] = "Vulkan"; + } else { + initial_settings["rendering/driver/driver_name"] = "GLES2"; + initial_settings["rendering/textures/vram_compression/import_etc2"] = false; + initial_settings["rendering/textures/vram_compression/import_etc"] = true; + } initial_settings["application/config/name"] = project_name->get_text().strip_edges(); initial_settings["application/config/icon"] = "res://icon.png"; initial_settings["rendering/environment/defaults/default_environment"] = "res://default_env.tres"; diff --git a/gles_builders.py b/gles_builders.py new file mode 100644 index 00000000000..c88e21bdeed --- /dev/null +++ b/gles_builders.py @@ -0,0 +1,602 @@ +"""Functions used to generate source files during build time + +All such functions are invoked in a subprocess on Windows to prevent build flakiness. + +""" +from platform_methods import subprocess_main + + +class LegacyGLHeaderStruct: + def __init__(self): + self.vertex_lines = [] + self.fragment_lines = [] + self.uniforms = [] + self.attributes = [] + self.feedbacks = [] + self.fbos = [] + self.conditionals = [] + self.enums = {} + self.texunits = [] + self.texunit_names = [] + self.ubos = [] + self.ubo_names = [] + + self.vertex_included_files = [] + self.fragment_included_files = [] + + self.reading = "" + self.line_offset = 0 + self.vertex_offset = 0 + self.fragment_offset = 0 + + +def include_file_in_legacygl_header(filename, header_data, depth): + fs = open(filename, "r") + line = fs.readline() + + while line: + + if line.find("[vertex]") != -1: + header_data.reading = "vertex" + line = fs.readline() + header_data.line_offset += 1 + header_data.vertex_offset = header_data.line_offset + continue + + if line.find("[fragment]") != -1: + header_data.reading = "fragment" + line = fs.readline() + header_data.line_offset += 1 + header_data.fragment_offset = header_data.line_offset + continue + + while line.find("#include ") != -1: + includeline = line.replace("#include ", "").strip()[1:-1] + + import os.path + + included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline) + if not included_file in header_data.vertex_included_files and header_data.reading == "vertex": + header_data.vertex_included_files += [included_file] + if include_file_in_legacygl_header(included_file, header_data, depth + 1) is None: + print("Error in file '" + filename + "': #include " + includeline + "could not be found!") + elif not included_file in header_data.fragment_included_files and header_data.reading == "fragment": + header_data.fragment_included_files += [included_file] + if include_file_in_legacygl_header(included_file, header_data, depth + 1) is None: + print("Error in file '" + filename + "': #include " + includeline + "could not be found!") + + line = fs.readline() + + if line.find("#ifdef ") != -1: + if line.find("#ifdef ") != -1: + ifdefline = line.replace("#ifdef ", "").strip() + + if line.find("_EN_") != -1: + enumbase = ifdefline[: ifdefline.find("_EN_")] + ifdefline = ifdefline.replace("_EN_", "_") + line = line.replace("_EN_", "_") + if enumbase not in header_data.enums: + header_data.enums[enumbase] = [] + if ifdefline not in header_data.enums[enumbase]: + header_data.enums[enumbase].append(ifdefline) + + elif not ifdefline in header_data.conditionals: + header_data.conditionals += [ifdefline] + + if line.find("uniform") != -1 and line.lower().find("texunit:") != -1: + # texture unit + texunitstr = line[line.find(":") + 1 :].strip() + if texunitstr == "auto": + texunit = "-1" + else: + texunit = str(int(texunitstr)) + uline = line[: line.lower().find("//")] + uline = uline.replace("uniform", "") + uline = uline.replace("highp", "") + uline = uline.replace(";", "") + lines = uline.split(",") + for x in lines: + + x = x.strip() + x = x[x.rfind(" ") + 1 :] + if x.find("[") != -1: + # unfiorm array + x = x[: x.find("[")] + + if not x in header_data.texunit_names: + header_data.texunits += [(x, texunit)] + header_data.texunit_names += [x] + + elif line.find("uniform") != -1 and line.lower().find("ubo:") != -1: + # uniform buffer object + ubostr = line[line.find(":") + 1 :].strip() + ubo = str(int(ubostr)) + uline = line[: line.lower().find("//")] + uline = uline[uline.find("uniform") + len("uniform") :] + uline = uline.replace("highp", "") + uline = uline.replace(";", "") + uline = uline.replace("{", "").strip() + lines = uline.split(",") + for x in lines: + + x = x.strip() + x = x[x.rfind(" ") + 1 :] + if x.find("[") != -1: + # unfiorm array + x = x[: x.find("[")] + + if not x in header_data.ubo_names: + header_data.ubos += [(x, ubo)] + header_data.ubo_names += [x] + + elif line.find("uniform") != -1 and line.find("{") == -1 and line.find(";") != -1: + uline = line.replace("uniform", "") + uline = uline.replace(";", "") + lines = uline.split(",") + for x in lines: + + x = x.strip() + x = x[x.rfind(" ") + 1 :] + if x.find("[") != -1: + # unfiorm array + x = x[: x.find("[")] + + if not x in header_data.uniforms: + header_data.uniforms += [x] + + if line.strip().find("attribute ") == 0 and line.find("attrib:") != -1: + uline = line.replace("in ", "") + uline = uline.replace("attribute ", "") + uline = uline.replace("highp ", "") + uline = uline.replace(";", "") + uline = uline[uline.find(" ") :].strip() + + if uline.find("//") != -1: + name, bind = uline.split("//") + if bind.find("attrib:") != -1: + name = name.strip() + bind = bind.replace("attrib:", "").strip() + header_data.attributes += [(name, bind)] + + if line.strip().find("out ") == 0 and line.find("tfb:") != -1: + uline = line.replace("out ", "") + uline = uline.replace("highp ", "") + uline = uline.replace(";", "") + uline = uline[uline.find(" ") :].strip() + + if uline.find("//") != -1: + name, bind = uline.split("//") + if bind.find("tfb:") != -1: + name = name.strip() + bind = bind.replace("tfb:", "").strip() + header_data.feedbacks += [(name, bind)] + + line = line.replace("\r", "") + line = line.replace("\n", "") + + if header_data.reading == "vertex": + header_data.vertex_lines += [line] + if header_data.reading == "fragment": + header_data.fragment_lines += [line] + + line = fs.readline() + header_data.line_offset += 1 + + fs.close() + + return header_data + + +def build_legacygl_header(filename, include, class_suffix, output_attribs, gles2=False): + header_data = LegacyGLHeaderStruct() + include_file_in_legacygl_header(filename, header_data, 0) + + out_file = filename + ".gen.h" + fd = open(out_file, "w") + + enum_constants = [] + + fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n") + + out_file_base = out_file + out_file_base = out_file_base[out_file_base.rfind("/") + 1 :] + out_file_base = out_file_base[out_file_base.rfind("\\") + 1 :] + out_file_ifdef = out_file_base.replace(".", "_").upper() + fd.write("#ifndef " + out_file_ifdef + class_suffix + "_120\n") + fd.write("#define " + out_file_ifdef + class_suffix + "_120\n") + + out_file_class = ( + out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "Shader" + class_suffix + ) + fd.write("\n\n") + fd.write('#include "' + include + '"\n\n\n') + fd.write("class " + out_file_class + " : public Shader" + class_suffix + " {\n\n") + fd.write('\t virtual String get_shader_name() const { return "' + out_file_class + '"; }\n') + + fd.write("public:\n\n") + + if header_data.conditionals: + fd.write("\tenum Conditionals {\n") + for x in header_data.conditionals: + fd.write("\t\t" + x.upper() + ",\n") + fd.write("\t};\n\n") + + if header_data.uniforms: + fd.write("\tenum Uniforms {\n") + for x in header_data.uniforms: + fd.write("\t\t" + x.upper() + ",\n") + fd.write("\t};\n\n") + + fd.write("\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\n\n") + if header_data.conditionals: + fd.write( + "\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n" + ) + fd.write("\t#ifdef DEBUG_ENABLED\n ") + fd.write( + "\t#define _FU if (get_uniform(p_uniform)<0) return; if (!is_version_valid()) return; ERR_FAIL_COND( get_active()!=this ); \n\n " + ) + fd.write("\t#else\n ") + fd.write("\t#define _FU if (get_uniform(p_uniform)<0) return; \n\n ") + fd.write("\t#endif\n") + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU GLfloat col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; glUniform4fv(get_uniform(p_uniform),1,col); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU GLfloat vec2[2]={p_vec2.x,p_vec2.y}; glUniform2fv(get_uniform(p_uniform),1,vec2); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Size2i& p_vec2) { _FU GLint vec2[2]={p_vec2.x,p_vec2.y}; glUniform2iv(get_uniform(p_uniform),1,vec2); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU GLfloat vec3[3]={p_vec3.x,p_vec3.y,p_vec3.z}; glUniform3fv(get_uniform(p_uniform),1,vec3); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU glUniform2f(get_uniform(p_uniform),p_a,p_b); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU glUniform3f(get_uniform(p_uniform),p_a,p_b,p_c); }\n\n" + ) + fd.write( + "\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU glUniform4f(get_uniform(p_uniform),p_a,p_b,p_c,p_d); }\n\n" + ) + + fd.write( + """\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU + + const Transform &tr = p_transform; + + GLfloat matrix[16]={ /* build a 16x16 matrix */ + tr.basis.elements[0][0], + tr.basis.elements[1][0], + tr.basis.elements[2][0], + 0, + tr.basis.elements[0][1], + tr.basis.elements[1][1], + tr.basis.elements[2][1], + 0, + tr.basis.elements[0][2], + tr.basis.elements[1][2], + tr.basis.elements[2][2], + 0, + tr.origin.x, + tr.origin.y, + tr.origin.z, + 1 + }; + + + glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix); + + + } + + """ + ) + + fd.write( + """_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform2D& p_transform) { _FU + + const Transform2D &tr = p_transform; + + GLfloat matrix[16]={ /* build a 16x16 matrix */ + tr.elements[0][0], + tr.elements[0][1], + 0, + 0, + tr.elements[1][0], + tr.elements[1][1], + 0, + 0, + 0, + 0, + 1, + 0, + tr.elements[2][0], + tr.elements[2][1], + 0, + 1 + }; + + + glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix); + + + } + + """ + ) + + fd.write( + """_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU + + GLfloat matrix[16]; + + for (int i=0;i<4;i++) { + for (int j=0;j<4;j++) { + matrix[i*4+j]=p_matrix.matrix[i][j]; + } + } + + glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix); +}""" + ) + + fd.write("\n\n#undef _FU\n\n\n") + + fd.write("\tvirtual void init() {\n\n") + + enum_value_count = 0 + + if header_data.enums: + + fd.write("\t\t//Written using math, given nonstandarity of 64 bits integer constants..\n") + fd.write("\t\tstatic const Enum _enums[]={\n") + + bitofs = len(header_data.conditionals) + enum_vals = [] + + for xv in header_data.enums: + x = header_data.enums[xv] + bits = 1 + amt = len(x) + while 2 ** bits < amt: + bits += 1 + strs = "{" + for i in range(amt): + strs += '"#define ' + x[i] + '\\n",' + + c = {} + c["set_mask"] = "uint64_t(" + str(i) + ")<<" + str(bitofs) + c["clear_mask"] = ( + "((uint64_t(1)<<40)-1) ^ (((uint64_t(1)<<" + str(bits) + ") - 1)<<" + str(bitofs) + ")" + ) + enum_vals.append(c) + enum_constants.append(x[i]) + + strs += "NULL}" + + fd.write( + "\t\t\t{(uint64_t(1<<" + str(bits) + ")-1)<<" + str(bitofs) + "," + str(bitofs) + "," + strs + "},\n" + ) + bitofs += bits + + fd.write("\t\t};\n\n") + + fd.write("\t\tstatic const EnumValue _enum_values[]={\n") + + enum_value_count = len(enum_vals) + for x in enum_vals: + fd.write("\t\t\t{" + x["set_mask"] + "," + x["clear_mask"] + "},\n") + + fd.write("\t\t};\n\n") + + conditionals_found = [] + if header_data.conditionals: + + fd.write("\t\tstatic const char* _conditional_strings[]={\n") + if header_data.conditionals: + for x in header_data.conditionals: + fd.write('\t\t\t"#define ' + x + '\\n",\n') + conditionals_found.append(x) + fd.write("\t\t};\n\n") + else: + fd.write("\t\tstatic const char **_conditional_strings=NULL;\n") + + if header_data.uniforms: + + fd.write("\t\tstatic const char* _uniform_strings[]={\n") + if header_data.uniforms: + for x in header_data.uniforms: + fd.write('\t\t\t"' + x + '",\n') + fd.write("\t\t};\n\n") + else: + fd.write("\t\tstatic const char **_uniform_strings=NULL;\n") + + if output_attribs: + if header_data.attributes: + + fd.write("\t\tstatic AttributePair _attribute_pairs[]={\n") + for x in header_data.attributes: + fd.write('\t\t\t{"' + x[0] + '",' + x[1] + "},\n") + fd.write("\t\t};\n\n") + else: + fd.write("\t\tstatic AttributePair *_attribute_pairs=NULL;\n") + + feedback_count = 0 + + if not gles2 and len(header_data.feedbacks): + + fd.write("\t\tstatic const Feedback _feedbacks[]={\n") + for x in header_data.feedbacks: + name = x[0] + cond = x[1] + if cond in conditionals_found: + fd.write('\t\t\t{"' + name + '",' + str(conditionals_found.index(cond)) + "},\n") + else: + fd.write('\t\t\t{"' + name + '",-1},\n') + + feedback_count += 1 + + fd.write("\t\t};\n\n") + else: + if gles2: + pass + else: + fd.write("\t\tstatic const Feedback* _feedbacks=NULL;\n") + + if header_data.texunits: + fd.write("\t\tstatic TexUnitPair _texunit_pairs[]={\n") + for x in header_data.texunits: + fd.write('\t\t\t{"' + x[0] + '",' + x[1] + "},\n") + fd.write("\t\t};\n\n") + else: + fd.write("\t\tstatic TexUnitPair *_texunit_pairs=NULL;\n") + + if not gles2 and header_data.ubos: + fd.write("\t\tstatic UBOPair _ubo_pairs[]={\n") + for x in header_data.ubos: + fd.write('\t\t\t{"' + x[0] + '",' + x[1] + "},\n") + fd.write("\t\t};\n\n") + else: + if gles2: + pass + else: + fd.write("\t\tstatic UBOPair *_ubo_pairs=NULL;\n") + + fd.write("\t\tstatic const char _vertex_code[]={\n") + for x in header_data.vertex_lines: + for c in x: + fd.write(str(ord(c)) + ",") + + fd.write(str(ord("\n")) + ",") + fd.write("\t\t0};\n\n") + + fd.write("\t\tstatic const int _vertex_code_start=" + str(header_data.vertex_offset) + ";\n") + + fd.write("\t\tstatic const char _fragment_code[]={\n") + for x in header_data.fragment_lines: + for c in x: + fd.write(str(ord(c)) + ",") + + fd.write(str(ord("\n")) + ",") + fd.write("\t\t0};\n\n") + + fd.write("\t\tstatic const int _fragment_code_start=" + str(header_data.fragment_offset) + ";\n") + + if output_attribs: + if gles2: + fd.write( + "\t\tsetup(_conditional_strings," + + str(len(header_data.conditionals)) + + ",_uniform_strings," + + str(len(header_data.uniforms)) + + ",_attribute_pairs," + + str(len(header_data.attributes)) + + ", _texunit_pairs," + + str(len(header_data.texunits)) + + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n" + ) + else: + fd.write( + "\t\tsetup(_conditional_strings," + + str(len(header_data.conditionals)) + + ",_uniform_strings," + + str(len(header_data.uniforms)) + + ",_attribute_pairs," + + str(len(header_data.attributes)) + + ", _texunit_pairs," + + str(len(header_data.texunits)) + + ",_ubo_pairs," + + str(len(header_data.ubos)) + + ",_feedbacks," + + str(feedback_count) + + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n" + ) + else: + if gles2: + fd.write( + "\t\tsetup(_conditional_strings," + + str(len(header_data.conditionals)) + + ",_uniform_strings," + + str(len(header_data.uniforms)) + + ",_texunit_pairs," + + str(len(header_data.texunits)) + + ",_enums," + + str(len(header_data.enums)) + + ",_enum_values," + + str(enum_value_count) + + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n" + ) + else: + fd.write( + "\t\tsetup(_conditional_strings," + + str(len(header_data.conditionals)) + + ",_uniform_strings," + + str(len(header_data.uniforms)) + + ",_texunit_pairs," + + str(len(header_data.texunits)) + + ",_enums," + + str(len(header_data.enums)) + + ",_enum_values," + + str(enum_value_count) + + ",_ubo_pairs," + + str(len(header_data.ubos)) + + ",_feedbacks," + + str(feedback_count) + + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n" + ) + + fd.write("\t}\n\n") + + if enum_constants: + + fd.write("\tenum EnumConditionals {\n") + for x in enum_constants: + fd.write("\t\t" + x.upper() + ",\n") + fd.write("\t};\n\n") + fd.write("\tvoid set_enum_conditional(EnumConditionals p_cond) { _set_enum_conditional(p_cond); }\n") + + fd.write("};\n\n") + fd.write("#endif\n\n") + fd.close() + + +def build_gles3_headers(target, source, env): + for x in source: + build_legacygl_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3", output_attribs=True) + + +def build_gles2_headers(target, source, env): + for x in source: + build_legacygl_header( + str(x), include="drivers/gles2/shader_gles2.h", class_suffix="GLES2", output_attribs=True, gles2=True + ) + + +if __name__ == "__main__": + subprocess_main(globals()) diff --git a/main/main.cpp b/main/main.cpp index edd67971ea0..24ede50fd44 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -128,7 +128,7 @@ static bool _start_success = false; String tablet_driver = ""; String text_driver = ""; - +String rendering_driver = ""; static int text_driver_idx = -1; static int display_driver_idx = -1; static int audio_driver_idx = -1; @@ -734,7 +734,49 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph N = I->next()->next(); } else { - OS::get_singleton()->print("Missing video driver argument, aborting.\n"); + OS::get_singleton()->print("Missing display driver argument, aborting.\n"); + goto error; + } + } else if (I->get() == "--rendering-driver") { + if (I->next()) { + rendering_driver = I->next()->get(); + + // as the rendering drivers available may depend on the display driver selected, + // we can't do an exhaustive check here, but we can look through all the options in + // all the display drivers for a match + + bool found = false; + for (int i = 0; i < DisplayServer::get_create_function_count(); i++) { + Vector r_drivers = DisplayServer::get_create_function_rendering_drivers(i); + + for (int d = 0; d < r_drivers.size(); d++) { + if (rendering_driver == r_drivers[d]) { + found = true; + break; + } + } + } + + if (!found) { + OS::get_singleton()->print("Unknown rendering driver '%s', aborting.\nValid options are ", + rendering_driver.utf8().get_data()); + + for (int i = 0; i < DisplayServer::get_create_function_count(); i++) { + Vector r_drivers = DisplayServer::get_create_function_rendering_drivers(i); + + for (int d = 0; d < r_drivers.size(); d++) { + OS::get_singleton()->print("'%s', ", r_drivers[d].utf8().get_data()); + } + } + + OS::get_singleton()->print(".\n"); + + goto error; + } + + N = I->next()->next(); + } else { + OS::get_singleton()->print("Missing rendering driver argument, aborting.\n"); goto error; } } else if (I->get() == "-f" || I->get() == "--fullscreen") { // force fullscreen @@ -1231,14 +1273,30 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph OS::get_singleton()->set_cmdline(execpath, main_args); register_core_extensions(); //before display - + // possibly be worth changing the default from vulkan to something lower spec, + // for the project manager, depending on how smooth the fallback is. GLOBAL_DEF("rendering/driver/driver_name", "Vulkan"); + + // this list is hard coded, which makes it more difficult to add new backends. + // can potentially be changed to more of a plugin system at a later date. ProjectSettings::get_singleton()->set_custom_property_info("rendering/driver/driver_name", PropertyInfo(Variant::STRING, "rendering/driver/driver_name", - PROPERTY_HINT_ENUM, "Vulkan")); - if (display_driver == "") { - display_driver = GLOBAL_GET("rendering/driver/driver_name"); + PROPERTY_HINT_ENUM, "Vulkan,GLES2,GLES3")); + + // if not set on the command line + if (rendering_driver == "") { + rendering_driver = GLOBAL_GET("rendering/driver/driver_name"); + } + + // note this is the desired rendering driver, it doesn't mean we will get it. + // TODO - make sure this is updated in the case of fallbacks, so that the user interface + // shows the correct driver string. + OS::get_singleton()->set_current_rendering_driver_name(rendering_driver); + + // always convert to lower case vulkan for consistency in the code + if (rendering_driver == "Vulkan") { + rendering_driver = "vulkan"; } GLOBAL_DEF_BASIC("display/window/size/width", 1024); @@ -1338,8 +1396,13 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph /* Determine audio and video drivers */ + // Display driver, e.g. X11, Wayland. + // print_line("requested display driver : " + display_driver); for (int i = 0; i < DisplayServer::get_create_function_count(); i++) { - if (display_driver == DisplayServer::get_create_function_name(i)) { + String name = DisplayServer::get_create_function_name(i); + // print_line("\t" + itos(i) + " : " + name); + + if (display_driver == name) { display_driver_idx = i; break; } @@ -1349,6 +1412,10 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph display_driver_idx = 0; } + // Store this in a globally accessible place, so we can retrieve the rendering drivers + // list from the display driver for the editor UI. + OS::get_singleton()->set_display_driver_id(display_driver_idx); + GLOBAL_DEF_RST_NOVAL("audio/driver/driver", AudioDriverManager::get_driver(0)->get_name()); if (audio_driver == "") { // Specified in project.godot. audio_driver = GLOBAL_GET("audio/driver/driver"); @@ -1505,8 +1572,11 @@ Error Main::setup2(Thread::ID p_main_tid_override) { /* Initialize Display Server */ { - String rendering_driver; // temp broken + String display_driver = DisplayServer::get_create_function_name(display_driver_idx); + // rendering_driver now held in static global String in main and initialized in setup() + print_line("creating display driver : " + display_driver); + print_line("creating rendering driver : " + rendering_driver); Error err; display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_size, err); if (err != OK || display_server == nullptr) { @@ -1565,6 +1635,7 @@ Error Main::setup2(Thread::ID p_main_tid_override) { rendering_server = memnew(RenderingServerDefault(OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD)); rendering_server->init(); + //rendering_server->call_set_use_vsync(OS::get_singleton()->_use_vsync); rendering_server->set_render_loop_enabled(!disable_render_loop); if (profile_gpu || (!editor && bool(GLOBAL_GET("debug/settings/stdout/print_gpu_profile")))) { diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp index 8df61831c2e..e01ad004a0b 100644 --- a/platform/android/export/export.cpp +++ b/platform/android/export/export.cpp @@ -31,6 +31,2833 @@ #include "export.h" #include "export_plugin.h" +//#include "core/config/project_settings.h" +//#include "core/io/image_loader.h" +//#include "core/io/marshalls.h" +//#include "core/io/zip_io.h" +//#include "core/os/dir_access.h" +//#include "core/os/file_access.h" +//#include "core/os/os.h" +//#include "core/version.h" +//#include "drivers/png/png_driver_common.h" +//#include "editor/editor_export.h" +//#include "editor/editor_log.h" +//#include "editor/editor_node.h" +//#include "editor/editor_settings.h" +//#include "main/splash.gen.h" +//#include "platform/android/export/gradle_export_util.h" +//#include "platform/android/logo.gen.h" +//#include "platform/android/plugin/godot_plugin_config.h" +//#include "platform/android/run_icon.gen.h" + +//#include + +//static const char *android_perms[] = { +// "ACCESS_CHECKIN_PROPERTIES", +// "ACCESS_COARSE_LOCATION", +// "ACCESS_FINE_LOCATION", +// "ACCESS_LOCATION_EXTRA_COMMANDS", +// "ACCESS_MOCK_LOCATION", +// "ACCESS_NETWORK_STATE", +// "ACCESS_SURFACE_FLINGER", +// "ACCESS_WIFI_STATE", +// "ACCOUNT_MANAGER", +// "ADD_VOICEMAIL", +// "AUTHENTICATE_ACCOUNTS", +// "BATTERY_STATS", +// "BIND_ACCESSIBILITY_SERVICE", +// "BIND_APPWIDGET", +// "BIND_DEVICE_ADMIN", +// "BIND_INPUT_METHOD", +// "BIND_NFC_SERVICE", +// "BIND_NOTIFICATION_LISTENER_SERVICE", +// "BIND_PRINT_SERVICE", +// "BIND_REMOTEVIEWS", +// "BIND_TEXT_SERVICE", +// "BIND_VPN_SERVICE", +// "BIND_WALLPAPER", +// "BLUETOOTH", +// "BLUETOOTH_ADMIN", +// "BLUETOOTH_PRIVILEGED", +// "BRICK", +// "BROADCAST_PACKAGE_REMOVED", +// "BROADCAST_SMS", +// "BROADCAST_STICKY", +// "BROADCAST_WAP_PUSH", +// "CALL_PHONE", +// "CALL_PRIVILEGED", +// "CAMERA", +// "CAPTURE_AUDIO_OUTPUT", +// "CAPTURE_SECURE_VIDEO_OUTPUT", +// "CAPTURE_VIDEO_OUTPUT", +// "CHANGE_COMPONENT_ENABLED_STATE", +// "CHANGE_CONFIGURATION", +// "CHANGE_NETWORK_STATE", +// "CHANGE_WIFI_MULTICAST_STATE", +// "CHANGE_WIFI_STATE", +// "CLEAR_APP_CACHE", +// "CLEAR_APP_USER_DATA", +// "CONTROL_LOCATION_UPDATES", +// "DELETE_CACHE_FILES", +// "DELETE_PACKAGES", +// "DEVICE_POWER", +// "DIAGNOSTIC", +// "DISABLE_KEYGUARD", +// "DUMP", +// "EXPAND_STATUS_BAR", +// "FACTORY_TEST", +// "FLASHLIGHT", +// "FORCE_BACK", +// "GET_ACCOUNTS", +// "GET_PACKAGE_SIZE", +// "GET_TASKS", +// "GET_TOP_ACTIVITY_INFO", +// "GLOBAL_SEARCH", +// "HARDWARE_TEST", +// "INJECT_EVENTS", +// "INSTALL_LOCATION_PROVIDER", +// "INSTALL_PACKAGES", +// "INSTALL_SHORTCUT", +// "INTERNAL_SYSTEM_WINDOW", +// "INTERNET", +// "KILL_BACKGROUND_PROCESSES", +// "LOCATION_HARDWARE", +// "MANAGE_ACCOUNTS", +// "MANAGE_APP_TOKENS", +// "MANAGE_DOCUMENTS", +// "MASTER_CLEAR", +// "MEDIA_CONTENT_CONTROL", +// "MODIFY_AUDIO_SETTINGS", +// "MODIFY_PHONE_STATE", +// "MOUNT_FORMAT_FILESYSTEMS", +// "MOUNT_UNMOUNT_FILESYSTEMS", +// "NFC", +// "PERSISTENT_ACTIVITY", +// "PROCESS_OUTGOING_CALLS", +// "READ_CALENDAR", +// "READ_CALL_LOG", +// "READ_CONTACTS", +// "READ_EXTERNAL_STORAGE", +// "READ_FRAME_BUFFER", +// "READ_HISTORY_BOOKMARKS", +// "READ_INPUT_STATE", +// "READ_LOGS", +// "READ_PHONE_STATE", +// "READ_PROFILE", +// "READ_SMS", +// "READ_SOCIAL_STREAM", +// "READ_SYNC_SETTINGS", +// "READ_SYNC_STATS", +// "READ_USER_DICTIONARY", +// "REBOOT", +// "RECEIVE_BOOT_COMPLETED", +// "RECEIVE_MMS", +// "RECEIVE_SMS", +// "RECEIVE_WAP_PUSH", +// "RECORD_AUDIO", +// "REORDER_TASKS", +// "RESTART_PACKAGES", +// "SEND_RESPOND_VIA_MESSAGE", +// "SEND_SMS", +// "SET_ACTIVITY_WATCHER", +// "SET_ALARM", +// "SET_ALWAYS_FINISH", +// "SET_ANIMATION_SCALE", +// "SET_DEBUG_APP", +// "SET_ORIENTATION", +// "SET_POINTER_SPEED", +// "SET_PREFERRED_APPLICATIONS", +// "SET_PROCESS_LIMIT", +// "SET_TIME", +// "SET_TIME_ZONE", +// "SET_WALLPAPER", +// "SET_WALLPAPER_HINTS", +// "SIGNAL_PERSISTENT_PROCESSES", +// "STATUS_BAR", +// "SUBSCRIBED_FEEDS_READ", +// "SUBSCRIBED_FEEDS_WRITE", +// "SYSTEM_ALERT_WINDOW", +// "TRANSMIT_IR", +// "UNINSTALL_SHORTCUT", +// "UPDATE_DEVICE_STATS", +// "USE_CREDENTIALS", +// "USE_SIP", +// "VIBRATE", +// "WAKE_LOCK", +// "WRITE_APN_SETTINGS", +// "WRITE_CALENDAR", +// "WRITE_CALL_LOG", +// "WRITE_CONTACTS", +// "WRITE_EXTERNAL_STORAGE", +// "WRITE_GSERVICES", +// "WRITE_HISTORY_BOOKMARKS", +// "WRITE_PROFILE", +// "WRITE_SECURE_SETTINGS", +// "WRITE_SETTINGS", +// "WRITE_SMS", +// "WRITE_SOCIAL_STREAM", +// "WRITE_SYNC_SETTINGS", +// "WRITE_USER_DICTIONARY", +// nullptr +//}; + +//static const char *SPLASH_IMAGE_EXPORT_PATH = "res/drawable/splash.png"; +//static const char *SPLASH_BG_COLOR_PATH = "res/drawable/splash_bg_color.png"; + +//struct LauncherIcon { +// const char *export_path; +// int dimensions = 0; +//}; + +//static const int icon_densities_count = 6; +//static const char *launcher_icon_option = "launcher_icons/main_192x192"; +//static const char *launcher_adaptive_icon_foreground_option = "launcher_icons/adaptive_foreground_432x432"; +//static const char *launcher_adaptive_icon_background_option = "launcher_icons/adaptive_background_432x432"; + +//static const LauncherIcon launcher_icons[icon_densities_count] = { +// { "res/mipmap-xxxhdpi-v4/icon.png", 192 }, +// { "res/mipmap-xxhdpi-v4/icon.png", 144 }, +// { "res/mipmap-xhdpi-v4/icon.png", 96 }, +// { "res/mipmap-hdpi-v4/icon.png", 72 }, +// { "res/mipmap-mdpi-v4/icon.png", 48 }, +// { "res/mipmap/icon.png", 192 } +//}; + +//static const LauncherIcon launcher_adaptive_icon_foregrounds[icon_densities_count] = { +// { "res/mipmap-xxxhdpi-v4/icon_foreground.png", 432 }, +// { "res/mipmap-xxhdpi-v4/icon_foreground.png", 324 }, +// { "res/mipmap-xhdpi-v4/icon_foreground.png", 216 }, +// { "res/mipmap-hdpi-v4/icon_foreground.png", 162 }, +// { "res/mipmap-mdpi-v4/icon_foreground.png", 108 }, +// { "res/mipmap/icon_foreground.png", 432 } +//}; + +//static const LauncherIcon launcher_adaptive_icon_backgrounds[icon_densities_count] = { +// { "res/mipmap-xxxhdpi-v4/icon_background.png", 432 }, +// { "res/mipmap-xxhdpi-v4/icon_background.png", 324 }, +// { "res/mipmap-xhdpi-v4/icon_background.png", 216 }, +// { "res/mipmap-hdpi-v4/icon_background.png", 162 }, +// { "res/mipmap-mdpi-v4/icon_background.png", 108 }, +// { "res/mipmap/icon_background.png", 432 } +//}; + +//static const int EXPORT_FORMAT_APK = 0; +//static const int EXPORT_FORMAT_AAB = 1; + +//class EditorExportPlatformAndroid : public EditorExportPlatform { +// GDCLASS(EditorExportPlatformAndroid, EditorExportPlatform); + +// Ref logo; +// Ref run_icon; + +// struct Device { +// String id; +// String name; +// String description; +// int api_level = 0; +// }; + +// struct APKExportData { +// zipFile apk; +// EditorProgress *ep = nullptr; +// }; + +// Vector plugins; +// String last_plugin_names; +// uint64_t last_custom_build_time = 0; +// volatile bool plugins_changed; +// Mutex plugins_lock; +// Vector devices; +// volatile bool devices_changed; +// Mutex device_lock; +// Thread *check_for_changes_thread; +// volatile bool quit_request; + +// static void _check_for_changes_poll_thread(void *ud) { +// EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud; + +// while (!ea->quit_request) { +// // Check for plugins updates +// { +// // Nothing to do if we already know the plugins have changed. +// if (!ea->plugins_changed) { +// Vector loaded_plugins = get_plugins(); + +// MutexLock lock(ea->plugins_lock); + +// if (ea->plugins.size() != loaded_plugins.size()) { +// ea->plugins_changed = true; +// } else { +// for (int i = 0; i < ea->plugins.size(); i++) { +// if (ea->plugins[i].name != loaded_plugins[i].name) { +// ea->plugins_changed = true; +// break; +// } +// } +// } + +// if (ea->plugins_changed) { +// ea->plugins = loaded_plugins; +// } +// } +// } + +// // Check for devices updates +// String adb = get_adb_path(); +// if (FileAccess::exists(adb)) { +// String devices; +// List args; +// args.push_back("devices"); +// int ec; +// OS::get_singleton()->execute(adb, args, true, nullptr, &devices, &ec); + +// Vector ds = devices.split("\n"); +// Vector ldevices; +// for (int i = 1; i < ds.size(); i++) { +// String d = ds[i]; +// int dpos = d.find("device"); +// if (dpos == -1) { +// continue; +// } +// d = d.substr(0, dpos).strip_edges(); +// ldevices.push_back(d); +// } + +// MutexLock lock(ea->device_lock); + +// bool different = false; + +// if (ea->devices.size() != ldevices.size()) { +// different = true; +// } else { +// for (int i = 0; i < ea->devices.size(); i++) { +// if (ea->devices[i].id != ldevices[i]) { +// different = true; +// break; +// } +// } +// } + +// if (different) { +// Vector ndevices; + +// for (int i = 0; i < ldevices.size(); i++) { +// Device d; +// d.id = ldevices[i]; +// for (int j = 0; j < ea->devices.size(); j++) { +// if (ea->devices[j].id == ldevices[i]) { +// d.description = ea->devices[j].description; +// d.name = ea->devices[j].name; +// d.api_level = ea->devices[j].api_level; +// } +// } + +// if (d.description == "") { +// //in the oven, request! +// args.clear(); +// args.push_back("-s"); +// args.push_back(d.id); +// args.push_back("shell"); +// args.push_back("getprop"); +// int ec2; +// String dp; + +// OS::get_singleton()->execute(adb, args, true, nullptr, &dp, &ec2); + +// Vector props = dp.split("\n"); +// String vendor; +// String device; +// d.description = "Device ID: " + d.id + "\n"; +// d.api_level = 0; +// for (int j = 0; j < props.size(); j++) { +// // got information by `shell cat /system/build.prop` before and its format is "property=value" +// // it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above +// // its format is "[property]: [value]" so changed it as like build.prop +// String p = props[j]; +// p = p.replace("]: ", "="); +// p = p.replace("[", ""); +// p = p.replace("]", ""); + +// if (p.begins_with("ro.product.model=")) { +// device = p.get_slice("=", 1).strip_edges(); +// } else if (p.begins_with("ro.product.brand=")) { +// vendor = p.get_slice("=", 1).strip_edges().capitalize(); +// } else if (p.begins_with("ro.build.display.id=")) { +// d.description += "Build: " + p.get_slice("=", 1).strip_edges() + "\n"; +// } else if (p.begins_with("ro.build.version.release=")) { +// d.description += "Release: " + p.get_slice("=", 1).strip_edges() + "\n"; +// } else if (p.begins_with("ro.build.version.sdk=")) { +// d.api_level = p.get_slice("=", 1).to_int(); +// } else if (p.begins_with("ro.product.cpu.abi=")) { +// d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n"; +// } else if (p.begins_with("ro.product.manufacturer=")) { +// d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n"; +// } else if (p.begins_with("ro.board.platform=")) { +// d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n"; +// } else if (p.begins_with("ro.opengles.version=")) { +// uint32_t opengl = p.get_slice("=", 1).to_int(); +// d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n"; +// } +// } + +// d.name = vendor + " " + device; +// if (device == String()) { +// continue; +// } +// } + +// ndevices.push_back(d); +// } + +// ea->devices = ndevices; +// ea->devices_changed = true; +// } +// } + +// uint64_t sleep = 200; +// uint64_t wait = 3000000; +// uint64_t time = OS::get_singleton()->get_ticks_usec(); +// while (OS::get_singleton()->get_ticks_usec() - time < wait) { +// OS::get_singleton()->delay_usec(1000 * sleep); +// if (ea->quit_request) { +// break; +// } +// } +// } + +// if (EditorSettings::get_singleton()->get("export/android/shutdown_adb_on_exit")) { +// String adb = get_adb_path(); +// if (!FileAccess::exists(adb)) { +// return; //adb not configured +// } + +// List args; +// args.push_back("kill-server"); +// OS::get_singleton()->execute(adb, args, true); +// }; +// } + +// String get_project_name(const String &p_name) const { +// String aname; +// if (p_name != "") { +// aname = p_name; +// } else { +// aname = ProjectSettings::get_singleton()->get("application/config/name"); +// } + +// if (aname == "") { +// aname = VERSION_NAME; +// } + +// return aname; +// } + +// String get_package_name(const String &p_package) const { +// String pname = p_package; +// String basename = ProjectSettings::get_singleton()->get("application/config/name"); +// basename = basename.to_lower(); + +// String name; +// bool first = true; +// for (int i = 0; i < basename.length(); i++) { +// char32_t c = basename[i]; +// if (c >= '0' && c <= '9' && first) { +// continue; +// } +// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { +// name += String::chr(c); +// first = false; +// } +// } +// if (name == "") { +// name = "noname"; +// } + +// pname = pname.replace("$genname", name); + +// return pname; +// } + +// bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const { +// String pname = p_package; + +// if (pname.length() == 0) { +// if (r_error) { +// *r_error = TTR("Package name is missing."); +// } +// return false; +// } + +// int segments = 0; +// bool first = true; +// for (int i = 0; i < pname.length(); i++) { +// char32_t c = pname[i]; +// if (first && c == '.') { +// if (r_error) { +// *r_error = TTR("Package segments must be of non-zero length."); +// } +// return false; +// } +// if (c == '.') { +// segments++; +// first = true; +// continue; +// } +// if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) { +// if (r_error) { +// *r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c)); +// } +// return false; +// } +// if (first && (c >= '0' && c <= '9')) { +// if (r_error) { +// *r_error = TTR("A digit cannot be the first character in a package segment."); +// } +// return false; +// } +// if (first && c == '_') { +// if (r_error) { +// *r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c)); +// } +// return false; +// } +// first = false; +// } + +// if (segments == 0) { +// if (r_error) { +// *r_error = TTR("The package must have at least one '.' separator."); +// } +// return false; +// } + +// if (first) { +// if (r_error) { +// *r_error = TTR("Package segments must be of non-zero length."); +// } +// return false; +// } + +// return true; +// } + +// static bool _should_compress_asset(const String &p_path, const Vector &p_data) { +// /* +// * By not compressing files with little or not benefit in doing so, +// * a performance gain is expected attime. Moreover, if the APK is +// * zip-aligned, assets stored as they are can be efficiently read by +// * Android by memory-mapping them. +// */ + +// // -- Unconditional uncompress to mimic AAPT plus some other + +// static const char *unconditional_compress_ext[] = { +// // From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp +// // These formats are already compressed, or don't compress well: +// ".jpg", ".jpeg", ".png", ".gif", +// ".wav", ".mp2", ".mp3", ".ogg", ".aac", +// ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", +// ".rtttl", ".imy", ".xmf", ".mp4", ".m4a", +// ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", +// ".amr", ".awb", ".wma", ".wmv", +// // Godot-specific: +// ".webp", // Same reasoning as .png +// ".cfb", // Don't let small config files slow-down startup +// ".scn", // Binary scenes are usually already compressed +// ".stex", // Streamable textures are usually already compressed +// // Trailer for easier processing +// nullptr +// }; + +// for (const char **ext = unconditional_compress_ext; *ext; ++ext) { +// if (p_path.to_lower().ends_with(String(*ext))) { +// return false; +// } +// } + +// // -- Compressed resource? + +// if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') { +// // Already compressed +// return false; +// } + +// // --- TODO: Decide on texture resources according to their image compression setting + +// return true; +// } + +// static zip_fileinfo get_zip_fileinfo() { +// OS::Time time = OS::get_singleton()->get_time(); +// OS::Date date = OS::get_singleton()->get_date(); + +// zip_fileinfo zipfi; +// zipfi.tmz_date.tm_hour = time.hour; +// zipfi.tmz_date.tm_mday = date.day; +// zipfi.tmz_date.tm_min = time.min; +// zipfi.tmz_date.tm_mon = date.month - 1; // tm_mon is zero indexed +// zipfi.tmz_date.tm_sec = time.sec; +// zipfi.tmz_date.tm_year = date.year; +// zipfi.dosDate = 0; +// zipfi.external_fa = 0; +// zipfi.internal_fa = 0; + +// return zipfi; +// } + +// static Vector get_abis() { +// Vector abis; +// abis.push_back("armeabi-v7a"); +// abis.push_back("arm64-v8a"); +// abis.push_back("x86"); +// abis.push_back("x86_64"); +// return abis; +// } + +// /// List the gdap files in the directory specified by the p_path parameter. +// static Vector list_gdap_files(const String &p_path) { +// Vector dir_files; +// DirAccessRef da = DirAccess::open(p_path); +// if (da) { +// da->list_dir_begin(); +// while (true) { +// String file = da->get_next(); +// if (file == "") { +// break; +// } + +// if (da->current_is_dir() || da->current_is_hidden()) { +// continue; +// } + +// if (file.ends_with(PLUGIN_CONFIG_EXT)) { +// dir_files.push_back(file); +// } +// } +// da->list_dir_end(); +// } + +// return dir_files; +// } + +// static Vector get_plugins() { +// Vector loaded_plugins; + +// String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/plugins"); + +// // Add the prebuilt plugins +// loaded_plugins.append_array(get_prebuilt_plugins(plugins_dir)); + +// if (DirAccess::exists(plugins_dir)) { +// Vector plugins_filenames = list_gdap_files(plugins_dir); + +// if (!plugins_filenames.is_empty()) { +// Ref config_file = memnew(ConfigFile); +// for (int i = 0; i < plugins_filenames.size(); i++) { +// PluginConfig config = load_plugin_config(config_file, plugins_dir.plus_file(plugins_filenames[i])); +// if (config.valid_config) { +// loaded_plugins.push_back(config); +// } else { +// print_error("Invalid plugin config file " + plugins_filenames[i]); +// } +// } +// } +// } + +// return loaded_plugins; +// } + +// static Vector get_enabled_plugins(const Ref &p_presets) { +// Vector enabled_plugins; +// Vector all_plugins = get_plugins(); +// for (int i = 0; i < all_plugins.size(); i++) { +// PluginConfig plugin = all_plugins[i]; +// bool enabled = p_presets->get("plugins/" + plugin.name); +// if (enabled) { +// enabled_plugins.push_back(plugin); +// } +// } + +// return enabled_plugins; +// } + +// static Error store_in_apk(APKExportData *ed, const String &p_path, const Vector &p_data, int compression_method = Z_DEFLATED) { +// zip_fileinfo zipfi = get_zip_fileinfo(); +// zipOpenNewFileInZip(ed->apk, +// p_path.utf8().get_data(), +// &zipfi, +// nullptr, +// 0, +// nullptr, +// 0, +// nullptr, +// compression_method, +// Z_DEFAULT_COMPRESSION); + +// zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size()); +// zipCloseFileInZip(ed->apk); + +// return OK; +// } + +// static Error save_apk_so(void *p_userdata, const SharedObject &p_so) { +// if (!p_so.path.get_file().begins_with("lib")) { +// String err = "Android .so file names must start with \"lib\", but got: " + p_so.path; +// ERR_PRINT(err); +// return FAILED; +// } +// APKExportData *ed = (APKExportData *)p_userdata; +// Vector abis = get_abis(); +// bool exported = false; +// for (int i = 0; i < p_so.tags.size(); ++i) { +// // shared objects can be fat (compatible with multiple ABIs) +// int abi_index = abis.find(p_so.tags[i]); +// if (abi_index != -1) { +// exported = true; +// String abi = abis[abi_index]; +// String dst_path = String("lib").plus_file(abi).plus_file(p_so.path.get_file()); +// Vector array = FileAccess::get_file_as_array(p_so.path); +// Error store_err = store_in_apk(ed, dst_path, array); +// ERR_FAIL_COND_V_MSG(store_err, store_err, "Cannot store in apk file '" + dst_path + "'."); +// } +// } +// if (!exported) { +// String abis_string = String(" ").join(abis); +// String err = "Cannot determine ABI for library \"" + p_so.path + "\". One of the supported ABIs must be used as a tag: " + abis_string; +// ERR_PRINT(err); +// return FAILED; +// } +// return OK; +// } + +// static Error save_apk_file(void *p_userdata, const String &p_path, const Vector &p_data, int p_file, int p_total, const Vector &p_enc_in_filters, const Vector &p_enc_ex_filters, const Vector &p_key) { +// APKExportData *ed = (APKExportData *)p_userdata; +// String dst_path = p_path.replace_first("res://", "assets/"); + +// store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0); +// return OK; +// } + +// static Error ignore_apk_file(void *p_userdata, const String &p_path, const Vector &p_data, int p_file, int p_total, const Vector &p_enc_in_filters, const Vector &p_enc_ex_filters, const Vector &p_key) { +// return OK; +// } + +// void _get_permissions(const Ref &p_preset, bool p_give_internet, Vector &r_permissions) { +// const char **aperms = android_perms; +// while (*aperms) { +// bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower()); +// if (enabled) { +// r_permissions.push_back("android.permission." + String(*aperms)); +// } +// aperms++; +// } +// PackedStringArray user_perms = p_preset->get("permissions/custom_permissions"); +// for (int i = 0; i < user_perms.size(); i++) { +// String user_perm = user_perms[i].strip_edges(); +// if (!user_perm.is_empty()) { +// r_permissions.push_back(user_perm); +// } +// } +// if (p_give_internet) { +// if (r_permissions.find("android.permission.INTERNET") == -1) { +// r_permissions.push_back("android.permission.INTERNET"); +// } +// } + +// int xr_mode_index = p_preset->get("xr_features/xr_mode"); +// if (xr_mode_index == 1 /* XRMode.OVR */) { +// int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required +// if (hand_tracking_index > 0) { +// if (r_permissions.find("com.oculus.permission.HAND_TRACKING") == -1) { +// r_permissions.push_back("com.oculus.permission.HAND_TRACKING"); +// } +// } +// } +// } + +// void _write_tmp_manifest(const Ref &p_preset, bool p_give_internet, bool p_debug) { +// String manifest_text = +// "\n" +// "\n"; + +// manifest_text += _get_screen_sizes_tag(p_preset); +// manifest_text += _get_gles_tag(); + +// Vector perms; +// _get_permissions(p_preset, p_give_internet, perms); +// for (int i = 0; i < perms.size(); i++) { +// manifest_text += vformat(" \n", perms.get(i)); +// } + +// manifest_text += _get_xr_features_tag(p_preset); +// manifest_text += _get_instrumentation_tag(p_preset); +// String plugins_names = get_plugins_names(get_enabled_plugins(p_preset)); +// manifest_text += _get_application_tag(p_preset, plugins_names); +// manifest_text += "\n"; +// String manifest_path = vformat("res://android/build/src/%s/AndroidManifest.xml", (p_debug ? "debug" : "release")); +// store_string_at_path(manifest_path, manifest_text); +// } + +// void _fix_manifest(const Ref &p_preset, Vector &p_manifest, bool p_give_internet) { +// // Leaving the unused types commented because looking these constants up +// // again later would be annoying +// // const int CHUNK_AXML_FILE = 0x00080003; +// // const int CHUNK_RESOURCEIDS = 0x00080180; +// const int CHUNK_STRINGS = 0x001C0001; +// // const int CHUNK_XML_END_NAMESPACE = 0x00100101; +// const int CHUNK_XML_END_TAG = 0x00100103; +// // const int CHUNK_XML_START_NAMESPACE = 0x00100100; +// const int CHUNK_XML_START_TAG = 0x00100102; +// // const int CHUNK_XML_TEXT = 0x00100104; +// const int UTF8_FLAG = 0x00000100; + +// Vector string_table; + +// uint32_t ofs = 8; + +// uint32_t string_count = 0; +// //uint32_t styles_count = 0; +// uint32_t string_flags = 0; +// uint32_t string_data_offset = 0; + +// //uint32_t styles_offset = 0; +// uint32_t string_table_begins = 0; +// uint32_t string_table_ends = 0; +// Vector stable_extra; + +// String version_name = p_preset->get("version/name"); +// int version_code = p_preset->get("version/code"); +// String package_name = p_preset->get("package/unique_name"); + +// const int screen_orientation = _get_android_orientation_value(_get_screen_orientation()); + +// bool screen_support_small = p_preset->get("screen/support_small"); +// bool screen_support_normal = p_preset->get("screen/support_normal"); +// bool screen_support_large = p_preset->get("screen/support_large"); +// bool screen_support_xlarge = p_preset->get("screen/support_xlarge"); + +// int xr_mode_index = p_preset->get("xr_features/xr_mode"); +// bool focus_awareness = p_preset->get("xr_features/focus_awareness"); + +// String plugins_names = get_plugins_names(get_enabled_plugins(p_preset)); + +// Vector perms; +// // Write permissions into the perms variable. +// _get_permissions(p_preset, p_give_internet, perms); + +// while (ofs < (uint32_t)p_manifest.size()) { +// uint32_t chunk = decode_uint32(&p_manifest[ofs]); +// uint32_t size = decode_uint32(&p_manifest[ofs + 4]); + +// switch (chunk) { +// case CHUNK_STRINGS: { +// int iofs = ofs + 8; + +// string_count = decode_uint32(&p_manifest[iofs]); +// //styles_count = decode_uint32(&p_manifest[iofs + 4]); +// string_flags = decode_uint32(&p_manifest[iofs + 8]); +// string_data_offset = decode_uint32(&p_manifest[iofs + 12]); +// //styles_offset = decode_uint32(&p_manifest[iofs + 16]); +// /* +// printf("string count: %i\n",string_count); +// printf("flags: %i\n",string_flags); +// printf("sdata ofs: %i\n",string_data_offset); +// printf("styles ofs: %i\n",styles_offset); +// */ +// uint32_t st_offset = iofs + 20; +// string_table.resize(string_count); +// uint32_t string_end = 0; + +// string_table_begins = st_offset; + +// for (uint32_t i = 0; i < string_count; i++) { +// uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]); +// string_at += st_offset + string_count * 4; + +// ERR_FAIL_COND_MSG(string_flags & UTF8_FLAG, "Unimplemented, can't read UTF-8 string table."); + +// if (string_flags & UTF8_FLAG) { +// } else { +// uint32_t len = decode_uint16(&p_manifest[string_at]); +// Vector ucstring; +// ucstring.resize(len + 1); +// for (uint32_t j = 0; j < len; j++) { +// uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]); +// ucstring.write[j] = c; +// } +// string_end = MAX(string_at + 2 + 2 * len, string_end); +// ucstring.write[len] = 0; +// string_table.write[i] = ucstring.ptr(); +// } +// } + +// for (uint32_t i = string_end; i < (ofs + size); i++) { +// stable_extra.push_back(p_manifest[i]); +// } + +// string_table_ends = ofs + size; + +// } break; +// case CHUNK_XML_START_TAG: { +// int iofs = ofs + 8; +// uint32_t name = decode_uint32(&p_manifest[iofs + 12]); + +// String tname = string_table[name]; +// uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]); +// iofs += 28; +// bool is_focus_aware_metadata = false; + +// for (uint32_t i = 0; i < attrcount; i++) { +// uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]); +// uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]); +// uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]); +// uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]); + +// const String value = (attr_value != 0xFFFFFFFF) ? string_table[attr_value] : "Res #" + itos(attr_resid); +// String attrname = string_table[attr_name]; +// const String nspace = (attr_nspace != 0xFFFFFFFF) ? string_table[attr_nspace] : ""; + +// //replace project information +// if (tname == "manifest" && attrname == "package") { +// string_table.write[attr_value] = get_package_name(package_name); +// } + +// if (tname == "manifest" && attrname == "versionCode") { +// encode_uint32(version_code, &p_manifest.write[iofs + 16]); +// } + +// if (tname == "manifest" && attrname == "versionName") { +// if (attr_value == 0xFFFFFFFF) { +// WARN_PRINT("Version name in a resource, should be plain text"); +// } else { +// string_table.write[attr_value] = version_name; +// } +// } + +// if (tname == "instrumentation" && attrname == "targetPackage") { +// string_table.write[attr_value] = get_package_name(package_name); +// } + +// if (tname == "activity" && attrname == "screenOrientation") { +// encode_uint32(screen_orientation, &p_manifest.write[iofs + 16]); +// } + +// if (tname == "supports-screens") { +// if (attrname == "smallScreens") { +// encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); + +// } else if (attrname == "normalScreens") { +// encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); + +// } else if (attrname == "largeScreens") { +// encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); + +// } else if (attrname == "xlargeScreens") { +// encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); +// } +// } + +// // FIXME: `attr_value != 0xFFFFFFFF` below added as a stopgap measure for GH-32553, +// // but the issue should be debugged further and properly addressed. +// if (tname == "meta-data" && attrname == "name" && value == "xr_mode_metadata_name") { +// // Update the meta-data 'android:name' attribute based on the selected XR mode. +// if (xr_mode_index == 1 /* XRMode.OVR */) { +// string_table.write[attr_value] = "com.samsung.android.vr.application.mode"; +// } +// } + +// if (tname == "meta-data" && attrname == "value" && value == "xr_mode_metadata_value") { +// // Update the meta-data 'android:value' attribute based on the selected XR mode. +// if (xr_mode_index == 1 /* XRMode.OVR */) { +// string_table.write[attr_value] = "vr_only"; +// } +// } + +// if (tname == "meta-data" && attrname == "value" && is_focus_aware_metadata) { +// // Update the focus awareness meta-data value +// encode_uint32(xr_mode_index == /* XRMode.OVR */ 1 && focus_awareness ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]); +// } + +// if (tname == "meta-data" && attrname == "value" && value == "plugins_value" && !plugins_names.is_empty()) { +// // Update the meta-data 'android:value' attribute with the list of enabled plugins. +// string_table.write[attr_value] = plugins_names; +// } + +// is_focus_aware_metadata = tname == "meta-data" && attrname == "name" && value == "com.oculus.vr.focusaware"; +// iofs += 20; +// } + +// } break; +// case CHUNK_XML_END_TAG: { +// int iofs = ofs + 8; +// uint32_t name = decode_uint32(&p_manifest[iofs + 12]); +// String tname = string_table[name]; + +// if (tname == "uses-feature") { +// Vector feature_names; +// Vector feature_required_list; +// Vector feature_versions; + +// if (xr_mode_index == 1 /* XRMode.OVR */) { +// // Check for degrees of freedom +// int dof_index = p_preset->get("xr_features/degrees_of_freedom"); // 0: none, 1: 3dof and 6dof, 2: 6dof + +// if (dof_index > 0) { +// feature_names.push_back("android.hardware.vr.headtracking"); +// feature_required_list.push_back(dof_index == 2); +// feature_versions.push_back(1); +// } + +// // Check for hand tracking +// int hand_tracking_index = p_preset->get("xr_features/hand_tracking"); // 0: none, 1: optional, 2: required +// if (hand_tracking_index > 0) { +// feature_names.push_back("oculus.software.handtracking"); +// feature_required_list.push_back(hand_tracking_index == 2); +// feature_versions.push_back(-1); // no version attribute should be added. +// } +// } + +// if (feature_names.size() > 0) { +// ofs += 24; // skip over end tag + +// // save manifest ending so we can restore it +// Vector manifest_end; +// uint32_t manifest_cur_size = p_manifest.size(); + +// manifest_end.resize(p_manifest.size() - ofs); +// memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size()); + +// int32_t attr_name_string = string_table.find("name"); +// ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute."); + +// int32_t ns_android_string = string_table.find("http://schemas.android.com/apk/res/android"); +// if (ns_android_string == -1) { +// string_table.push_back("http://schemas.android.com/apk/res/android"); +// ns_android_string = string_table.size() - 1; +// } + +// int32_t attr_uses_feature_string = string_table.find("uses-feature"); +// if (attr_uses_feature_string == -1) { +// string_table.push_back("uses-feature"); +// attr_uses_feature_string = string_table.size() - 1; +// } + +// int32_t attr_required_string = string_table.find("required"); +// if (attr_required_string == -1) { +// string_table.push_back("required"); +// attr_required_string = string_table.size() - 1; +// } + +// for (int i = 0; i < feature_names.size(); i++) { +// String feature_name = feature_names[i]; +// bool feature_required = feature_required_list[i]; +// int feature_version = feature_versions[i]; +// bool has_version_attribute = feature_version != -1; + +// print_line("Adding feature " + feature_name); + +// int32_t feature_string = string_table.find(feature_name); +// if (feature_string == -1) { +// string_table.push_back(feature_name); +// feature_string = string_table.size() - 1; +// } + +// String required_value_string = feature_required ? "true" : "false"; +// int32_t required_value = string_table.find(required_value_string); +// if (required_value == -1) { +// string_table.push_back(required_value_string); +// required_value = string_table.size() - 1; +// } + +// int32_t attr_version_string = -1; +// int32_t version_value = -1; +// int tag_size; +// int attr_count; +// if (has_version_attribute) { +// attr_version_string = string_table.find("version"); +// if (attr_version_string == -1) { +// string_table.push_back("version"); +// attr_version_string = string_table.size() - 1; +// } + +// version_value = string_table.find(itos(feature_version)); +// if (version_value == -1) { +// string_table.push_back(itos(feature_version)); +// version_value = string_table.size() - 1; +// } + +// tag_size = 96; // node and three attrs + end node +// attr_count = 3; +// } else { +// tag_size = 76; // node and two attrs + end node +// attr_count = 2; +// } +// manifest_cur_size += tag_size + 24; +// p_manifest.resize(manifest_cur_size); + +// // start tag +// encode_uint16(0x102, &p_manifest.write[ofs]); // type +// encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize +// encode_uint32(tag_size, &p_manifest.write[ofs + 4]); // size +// encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno +// encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment +// encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns +// encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name +// encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start +// encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size +// encode_uint16(attr_count, &p_manifest.write[ofs + 28]); // num_attrs +// encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index +// encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index +// encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index + +// // android:name attribute +// encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns +// encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name' +// encode_uint32(feature_string, &p_manifest.write[ofs + 44]); // raw_value +// encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size +// p_manifest.write[ofs + 50] = 0; // typedvalue_always0 +// p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string) +// encode_uint32(feature_string, &p_manifest.write[ofs + 52]); // typedvalue reference + +// // android:required attribute +// encode_uint32(ns_android_string, &p_manifest.write[ofs + 56]); // ns +// encode_uint32(attr_required_string, &p_manifest.write[ofs + 60]); // 'name' +// encode_uint32(required_value, &p_manifest.write[ofs + 64]); // raw_value +// encode_uint16(8, &p_manifest.write[ofs + 68]); // typedvalue_size +// p_manifest.write[ofs + 70] = 0; // typedvalue_always0 +// p_manifest.write[ofs + 71] = 0x03; // typedvalue_type (string) +// encode_uint32(required_value, &p_manifest.write[ofs + 72]); // typedvalue reference + +// ofs += 76; + +// if (has_version_attribute) { +// // android:version attribute +// encode_uint32(ns_android_string, &p_manifest.write[ofs]); // ns +// encode_uint32(attr_version_string, &p_manifest.write[ofs + 4]); // 'name' +// encode_uint32(version_value, &p_manifest.write[ofs + 8]); // raw_value +// encode_uint16(8, &p_manifest.write[ofs + 12]); // typedvalue_size +// p_manifest.write[ofs + 14] = 0; // typedvalue_always0 +// p_manifest.write[ofs + 15] = 0x03; // typedvalue_type (string) +// encode_uint32(version_value, &p_manifest.write[ofs + 16]); // typedvalue reference + +// ofs += 20; +// } + +// // end tag +// encode_uint16(0x103, &p_manifest.write[ofs]); // type +// encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize +// encode_uint32(24, &p_manifest.write[ofs + 4]); // size +// encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno +// encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment +// encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns +// encode_uint32(attr_uses_feature_string, &p_manifest.write[ofs + 20]); // name + +// ofs += 24; +// } +// memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size()); +// ofs -= 24; // go back over back end +// } +// } +// if (tname == "manifest") { +// // save manifest ending so we can restore it +// Vector manifest_end; +// uint32_t manifest_cur_size = p_manifest.size(); + +// manifest_end.resize(p_manifest.size() - ofs); +// memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size()); + +// int32_t attr_name_string = string_table.find("name"); +// ERR_FAIL_COND_MSG(attr_name_string == -1, "Template does not have 'name' attribute."); + +// int32_t ns_android_string = string_table.find("android"); +// ERR_FAIL_COND_MSG(ns_android_string == -1, "Template does not have 'android' namespace."); + +// int32_t attr_uses_permission_string = string_table.find("uses-permission"); +// if (attr_uses_permission_string == -1) { +// string_table.push_back("uses-permission"); +// attr_uses_permission_string = string_table.size() - 1; +// } + +// for (int i = 0; i < perms.size(); ++i) { +// print_line("Adding permission " + perms[i]); + +// manifest_cur_size += 56 + 24; // node + end node +// p_manifest.resize(manifest_cur_size); + +// // Add permission to the string pool +// int32_t perm_string = string_table.find(perms[i]); +// if (perm_string == -1) { +// string_table.push_back(perms[i]); +// perm_string = string_table.size() - 1; +// } + +// // start tag +// encode_uint16(0x102, &p_manifest.write[ofs]); // type +// encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize +// encode_uint32(56, &p_manifest.write[ofs + 4]); // size +// encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno +// encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment +// encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns +// encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name +// encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start +// encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size +// encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs +// encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index +// encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index +// encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index + +// // attribute +// encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns +// encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name' +// encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value +// encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size +// p_manifest.write[ofs + 50] = 0; // typedvalue_always0 +// p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string) +// encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference + +// ofs += 56; + +// // end tag +// encode_uint16(0x103, &p_manifest.write[ofs]); // type +// encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize +// encode_uint32(24, &p_manifest.write[ofs + 4]); // size +// encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno +// encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment +// encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns +// encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name + +// ofs += 24; +// } + +// // copy footer back in +// memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size()); +// } +// } break; +// } + +// ofs += size; +// } + +// //create new andriodmanifest binary + +// Vector ret; +// ret.resize(string_table_begins + string_table.size() * 4); + +// for (uint32_t i = 0; i < string_table_begins; i++) { +// ret.write[i] = p_manifest[i]; +// } + +// ofs = 0; +// for (int i = 0; i < string_table.size(); i++) { +// encode_uint32(ofs, &ret.write[string_table_begins + i * 4]); +// ofs += string_table[i].length() * 2 + 2 + 2; +// } + +// ret.resize(ret.size() + ofs); +// string_data_offset = ret.size() - ofs; +// uint8_t *chars = &ret.write[string_data_offset]; +// for (int i = 0; i < string_table.size(); i++) { +// String s = string_table[i]; +// encode_uint16(s.length(), chars); +// chars += 2; +// for (int j = 0; j < s.length(); j++) { +// encode_uint16(s[j], chars); +// chars += 2; +// } +// encode_uint16(0, chars); +// chars += 2; +// } + +// for (int i = 0; i < stable_extra.size(); i++) { +// ret.push_back(stable_extra[i]); +// } + +// //pad +// while (ret.size() % 4) { +// ret.push_back(0); +// } + +// uint32_t new_stable_end = ret.size(); + +// uint32_t extra = (p_manifest.size() - string_table_ends); +// ret.resize(new_stable_end + extra); +// for (uint32_t i = 0; i < extra; i++) { +// ret.write[new_stable_end + i] = p_manifest[string_table_ends + i]; +// } + +// while (ret.size() % 4) { +// ret.push_back(0); +// } +// encode_uint32(ret.size(), &ret.write[4]); //update new file size + +// encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size +// encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings +// encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset + +// p_manifest = ret; +// } + +// static String _parse_string(const uint8_t *p_bytes, bool p_utf8) { +// uint32_t offset = 0; +// uint32_t len = 0; + +// if (p_utf8) { +// uint8_t byte = p_bytes[offset]; +// if (byte & 0x80) { +// offset += 2; +// } else { +// offset += 1; +// } +// byte = p_bytes[offset]; +// offset++; +// if (byte & 0x80) { +// len = byte & 0x7F; +// len = (len << 8) + p_bytes[offset]; +// offset++; +// } else { +// len = byte; +// } +// } else { +// len = decode_uint16(&p_bytes[offset]); +// offset += 2; +// if (len & 0x8000) { +// len &= 0x7FFF; +// len = (len << 16) + decode_uint16(&p_bytes[offset]); +// offset += 2; +// } +// } + +// if (p_utf8) { +// Vector str8; +// str8.resize(len + 1); +// for (uint32_t i = 0; i < len; i++) { +// str8.write[i] = p_bytes[offset + i]; +// } +// str8.write[len] = 0; +// String str; +// str.parse_utf8((const char *)str8.ptr()); +// return str; +// } else { +// String str; +// for (uint32_t i = 0; i < len; i++) { +// char32_t c = decode_uint16(&p_bytes[offset + i * 2]); +// if (c == 0) { +// break; +// } +// str += String::chr(c); +// } +// return str; +// } +// } + +// void _fix_resources(const Ref &p_preset, Vector &r_manifest) { +// const int UTF8_FLAG = 0x00000100; + +// uint32_t string_block_len = decode_uint32(&r_manifest[16]); +// uint32_t string_count = decode_uint32(&r_manifest[20]); +// uint32_t string_flags = decode_uint32(&r_manifest[28]); +// const uint32_t string_table_begins = 40; + +// Vector string_table; + +// String package_name = p_preset->get("package/name"); + +// for (uint32_t i = 0; i < string_count; i++) { +// uint32_t offset = decode_uint32(&r_manifest[string_table_begins + i * 4]); +// offset += string_table_begins + string_count * 4; + +// String str = _parse_string(&r_manifest[offset], string_flags & UTF8_FLAG); + +// if (str.begins_with("godot-project-name")) { +// if (str == "godot-project-name") { +// //project name +// str = get_project_name(package_name); + +// } else { +// String lang = str.substr(str.rfind("-") + 1, str.length()).replace("-", "_"); +// String prop = "application/config/name_" + lang; +// if (ProjectSettings::get_singleton()->has_setting(prop)) { +// str = ProjectSettings::get_singleton()->get(prop); +// } else { +// str = get_project_name(package_name); +// } +// } +// } + +// string_table.push_back(str); +// } + +// //write a new string table, but use 16 bits +// Vector ret; +// ret.resize(string_table_begins + string_table.size() * 4); + +// for (uint32_t i = 0; i < string_table_begins; i++) { +// ret.write[i] = r_manifest[i]; +// } + +// int ofs = 0; +// for (int i = 0; i < string_table.size(); i++) { +// encode_uint32(ofs, &ret.write[string_table_begins + i * 4]); +// ofs += string_table[i].length() * 2 + 2 + 2; +// } + +// ret.resize(ret.size() + ofs); +// uint8_t *chars = &ret.write[ret.size() - ofs]; +// for (int i = 0; i < string_table.size(); i++) { +// String s = string_table[i]; +// encode_uint16(s.length(), chars); +// chars += 2; +// for (int j = 0; j < s.length(); j++) { +// encode_uint16(s[j], chars); +// chars += 2; +// } +// encode_uint16(0, chars); +// chars += 2; +// } + +// //pad +// while (ret.size() % 4) { +// ret.push_back(0); +// } + +// //change flags to not use utf8 +// encode_uint32(string_flags & ~0x100, &ret.write[28]); +// //change length +// encode_uint32(ret.size() - 12, &ret.write[16]); +// //append the rest... +// int rest_from = 12 + string_block_len; +// int rest_to = ret.size(); +// int rest_len = (r_manifest.size() - rest_from); +// ret.resize(ret.size() + (r_manifest.size() - rest_from)); +// for (int i = 0; i < rest_len; i++) { +// ret.write[rest_to + i] = r_manifest[rest_from + i]; +// } +// //finally update the size +// encode_uint32(ret.size(), &ret.write[4]); + +// r_manifest = ret; +// //printf("end\n"); +// } + +// void _load_image_data(const Ref &p_splash_image, Vector &p_data) { +// Vector png_buffer; +// Error err = PNGDriverCommon::image_to_png(p_splash_image, png_buffer); +// if (err == OK) { +// p_data.resize(png_buffer.size()); +// memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size()); +// } else { +// String err_str = String("Failed to convert splash image to png."); +// WARN_PRINT(err_str.utf8().get_data()); +// } +// } + +// void _process_launcher_icons(const String &p_file_name, const Ref &p_source_image, int dimension, Vector &p_data) { +// Ref working_image = p_source_image; + +// if (p_source_image->get_width() != dimension || p_source_image->get_height() != dimension) { +// working_image = p_source_image->duplicate(); +// working_image->resize(dimension, dimension, Image::Interpolation::INTERPOLATE_LANCZOS); +// } + +// Vector png_buffer; +// Error err = PNGDriverCommon::image_to_png(working_image, png_buffer); +// if (err == OK) { +// p_data.resize(png_buffer.size()); +// memcpy(p_data.ptrw(), png_buffer.ptr(), p_data.size()); +// } else { +// String err_str = String("Failed to convert resized icon (") + p_file_name + ") to png."; +// WARN_PRINT(err_str.utf8().get_data()); +// } +// } + +// void load_splash_refs(Ref &splash_image, Ref &splash_bg_color_image) { +// // TODO: Figure out how to handle remaining boot splash parameters (e.g: fullsize, filter) +// String project_splash_path = ProjectSettings::get_singleton()->get("application/boot_splash/image"); + +// if (!project_splash_path.is_empty()) { +// splash_image.instance(); +// const Error err = ImageLoader::load_image(project_splash_path, splash_image); +// if (err) { +// splash_image.unref(); +// } +// } + +// if (splash_image.is_null()) { +// // Use the default +// splash_image = Ref(memnew(Image(boot_splash_png))); +// } + +// // Setup the splash bg color +// bool bg_color_valid; +// Color bg_color = ProjectSettings::get_singleton()->get("application/boot_splash/bg_color", &bg_color_valid); +// if (!bg_color_valid) { +// bg_color = boot_splash_bg_color; +// } + +// splash_bg_color_image.instance(); +// splash_bg_color_image->create(splash_image->get_width(), splash_image->get_height(), false, splash_image->get_format()); +// splash_bg_color_image->fill(bg_color); +// } + +// void load_icon_refs(const Ref &p_preset, Ref &icon, Ref &foreground, Ref &background) { +// String project_icon_path = ProjectSettings::get_singleton()->get("application/config/icon"); + +// icon.instance(); +// foreground.instance(); +// background.instance(); + +// // Regular icon: user selection -> project icon -> default. +// String path = static_cast(p_preset->get(launcher_icon_option)).strip_edges(); +// if (path.is_empty() || ImageLoader::load_image(path, icon) != OK) { +// ImageLoader::load_image(project_icon_path, icon); +// } + +// // Adaptive foreground: user selection -> regular icon (user selection -> project icon -> default). +// path = static_cast(p_preset->get(launcher_adaptive_icon_foreground_option)).strip_edges(); +// if (path.is_empty() || ImageLoader::load_image(path, foreground) != OK) { +// foreground = icon; +// } + +// // Adaptive background: user selection -> default. +// path = static_cast(p_preset->get(launcher_adaptive_icon_background_option)).strip_edges(); +// if (!path.is_empty()) { +// ImageLoader::load_image(path, background); +// } +// } + +// void store_image(const LauncherIcon launcher_icon, const Vector &data) { +// store_image(launcher_icon.export_path, data); +// } + +// void store_image(const String &export_path, const Vector &data) { +// String img_path = export_path.insert(0, "res://android/build/"); +// store_file_at_path(img_path, data); +// } + +// void _copy_icons_to_gradle_project(const Ref &p_preset, +// const Ref &splash_image, +// const Ref &splash_bg_color_image, +// const Ref &main_image, +// const Ref &foreground, +// const Ref &background) { +// // Store the splash image +// if (splash_image.is_valid() && !splash_image->is_empty()) { +// Vector data; +// _load_image_data(splash_image, data); +// store_image(SPLASH_IMAGE_EXPORT_PATH, data); +// } + +// // Store the splash bg color image +// if (splash_bg_color_image.is_valid() && !splash_bg_color_image->is_empty()) { +// Vector data; +// _load_image_data(splash_bg_color_image, data); +// store_image(SPLASH_BG_COLOR_PATH, data); +// } + +// // Prepare images to be resized for the icons. If some image ends up being uninitialized, +// // the default image from the export template will be used. + +// for (int i = 0; i < icon_densities_count; ++i) { +// if (main_image.is_valid() && !main_image->is_empty()) { +// Vector data; +// _process_launcher_icons(launcher_icons[i].export_path, main_image, launcher_icons[i].dimensions, data); +// store_image(launcher_icons[i], data); +// } + +// if (foreground.is_valid() && !foreground->is_empty()) { +// Vector data; +// _process_launcher_icons(launcher_adaptive_icon_foregrounds[i].export_path, foreground, +// launcher_adaptive_icon_foregrounds[i].dimensions, data); +// store_image(launcher_adaptive_icon_foregrounds[i], data); +// } + +// if (background.is_valid() && !background->is_empty()) { +// Vector data; +// _process_launcher_icons(launcher_adaptive_icon_backgrounds[i].export_path, background, +// launcher_adaptive_icon_backgrounds[i].dimensions, data); +// store_image(launcher_adaptive_icon_backgrounds[i], data); +// } +// } +// } + +// static Vector get_enabled_abis(const Ref &p_preset) { +// Vector abis = get_abis(); +// Vector enabled_abis; +// for (int i = 0; i < abis.size(); ++i) { +// bool is_enabled = p_preset->get("architectures/" + abis[i]); +// if (is_enabled) { +// enabled_abis.push_back(abis[i]); +// } +// } +// return enabled_abis; +// } + +//public: +// typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector &p_data, int p_file, int p_total, const Vector &p_enc_in_filters, const Vector &p_enc_ex_filters, const Vector &p_key); + +//public: +// virtual void get_preset_features(const Ref &p_preset, List *r_features) override { +// String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); +// if (driver == "GLES2") { +// r_features->push_back("etc"); +// } +// // FIXME: Review what texture formats are used for Vulkan. +// if (driver == "Vulkan") { +// r_features->push_back("etc2"); +// } + +// Vector abis = get_enabled_abis(p_preset); +// for (int i = 0; i < abis.size(); ++i) { +// r_features->push_back(abis[i]); +// } +// } + +// virtual void get_export_options(List *r_options) override { +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_template/use_custom_build"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "custom_template/export_format", PROPERTY_HINT_ENUM, "Export APK,Export AAB"), EXPORT_FORMAT_APK)); + +// Vector plugins_configs = get_plugins(); +// for (int i = 0; i < plugins_configs.size(); i++) { +// print_verbose("Found Android plugin " + plugins_configs[i].name); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "plugins/" + plugins_configs[i].name), false)); +// } +// plugins_changed = false; + +// Vector abis = get_abis(); +// for (int i = 0; i < abis.size(); ++i) { +// String abi = abis[i]; +// bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a"); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default)); +// } + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore,*.jks"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icon_option, PROPERTY_HINT_FILE, "*.png"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_foreground_option, PROPERTY_HINT_FILE, "*.png"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_adaptive_icon_background_option, PROPERTY_HINT_FILE, "*.png"), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/opengl_debug"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/xr_mode", PROPERTY_HINT_ENUM, "Regular,Oculus Mobile VR"), 0)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/degrees_of_freedom", PROPERTY_HINT_ENUM, "None,3DOF and 6DOF,6DOF"), 0)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "xr_features/hand_tracking", PROPERTY_HINT_ENUM, "None,Optional,Required"), 0)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "xr_features/focus_awareness"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::PACKED_STRING_ARRAY, "permissions/custom_permissions"), PackedStringArray())); + +// const char **perms = android_perms; +// while (*perms) { +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false)); +// perms++; +// } +// } + +// virtual String get_name() const override { +// return "Android"; +// } + +// virtual String get_os_name() const override { +// return "Android"; +// } + +// virtual Ref get_logo() const override { +// return logo; +// } + +// virtual bool should_update_export_options() override { +// bool export_options_changed = plugins_changed; +// if (export_options_changed) { +// // don't clear unless we're reporting true, to avoid race +// plugins_changed = false; +// } +// return export_options_changed; +// } + +// virtual bool poll_export() override { +// bool dc = devices_changed; +// if (dc) { +// // don't clear unless we're reporting true, to avoid race +// devices_changed = false; +// } +// return dc; +// } + +// virtual int get_options_count() const override { +// MutexLock lock(device_lock); +// return devices.size(); +// } + +// virtual String get_options_tooltip() const override { +// return TTR("Select device from the list"); +// } + +// virtual String get_option_label(int p_index) const override { +// ERR_FAIL_INDEX_V(p_index, devices.size(), ""); +// MutexLock lock(device_lock); +// return devices[p_index].name; +// } + +// virtual String get_option_tooltip(int p_index) const override { +// ERR_FAIL_INDEX_V(p_index, devices.size(), ""); +// MutexLock lock(device_lock); +// String s = devices[p_index].description; +// if (devices.size() == 1) { +// // Tooltip will be: +// // Name +// // Description +// s = devices[p_index].name + "\n\n" + s; +// } +// return s; +// } + +// virtual Error run(const Ref &p_preset, int p_device, int p_debug_flags) override { +// ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER); + +// String can_export_error; +// bool can_export_missing_templates; +// if (!can_export(p_preset, can_export_error, can_export_missing_templates)) { +// EditorNode::add_io_error(can_export_error); +// return ERR_UNCONFIGURED; +// } + +// MutexLock lock(device_lock); + +// EditorProgress ep("run", "Running on " + devices[p_device].name, 3); + +// String adb = get_adb_path(); + +// // Export_temp APK. +// if (ep.step("Exporting APK...", 0)) { +// return ERR_SKIP; +// } + +// const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT); +// const bool use_reverse = devices[p_device].api_level >= 21; + +// if (use_reverse) { +// p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST; +// } + +// String tmp_export_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport.apk"); + +//#define CLEANUP_AND_RETURN(m_err) \ +// { \ +// DirAccess::remove_file_or_error(tmp_export_path); \ +// return m_err; \ +// } + +// // Export to temporary APK before sending to device. +// Error err = export_project_helper(p_preset, true, tmp_export_path, EXPORT_FORMAT_APK, true, p_debug_flags); + +// if (err != OK) { +// CLEANUP_AND_RETURN(err); +// } + +// List args; +// int rv; + +// bool remove_prev = p_preset->get("one_click_deploy/clear_previous_install"); +// String version_name = p_preset->get("version/name"); +// String package_name = p_preset->get("package/unique_name"); + +// if (remove_prev) { +// if (ep.step("Uninstalling...", 1)) { +// CLEANUP_AND_RETURN(ERR_SKIP); +// } + +// print_line("Uninstalling previous version: " + devices[p_device].name); + +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("uninstall"); +// args.push_back(get_package_name(package_name)); + +// err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); +// } + +// print_line("Installing to device (please wait...): " + devices[p_device].name); +// if (ep.step("Installing to device, please wait...", 2)) { +// CLEANUP_AND_RETURN(ERR_SKIP); +// } + +// args.clear(); +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("install"); +// args.push_back("-r"); +// args.push_back(tmp_export_path); + +// err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); +// if (err || rv != 0) { +// EditorNode::add_io_error("Could not install to device."); +// CLEANUP_AND_RETURN(ERR_CANT_CREATE); +// } + +// if (use_remote) { +// if (use_reverse) { +// static const char *const msg = "--- Device API >= 21; debugging over USB ---"; +// EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR); +// print_line(String(msg).to_upper()); + +// args.clear(); +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("reverse"); +// args.push_back("--remove-all"); +// OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); + +// if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) { +// int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port"); +// args.clear(); +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("reverse"); +// args.push_back("tcp:" + itos(dbg_port)); +// args.push_back("tcp:" + itos(dbg_port)); + +// OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); +// print_line("Reverse result: " + itos(rv)); +// } + +// if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) { +// int fs_port = EditorSettings::get_singleton()->get("filesystem/file_server/port"); + +// args.clear(); +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("reverse"); +// args.push_back("tcp:" + itos(fs_port)); +// args.push_back("tcp:" + itos(fs_port)); + +// err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); +// print_line("Reverse result2: " + itos(rv)); +// } +// } else { +// static const char *const msg = "--- Device API < 21; debugging over Wi-Fi ---"; +// EditorNode::get_singleton()->get_log()->add_message(msg, EditorLog::MSG_TYPE_EDITOR); +// print_line(String(msg).to_upper()); +// } +// } + +// if (ep.step("Running on device...", 3)) { +// CLEANUP_AND_RETURN(ERR_SKIP); +// } +// args.clear(); +// args.push_back("-s"); +// args.push_back(devices[p_device].id); +// args.push_back("shell"); +// args.push_back("am"); +// args.push_back("start"); +// if ((bool)EditorSettings::get_singleton()->get("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17 +// args.push_back("--user"); +// args.push_back("0"); +// } +// args.push_back("-a"); +// args.push_back("android.intent.action.MAIN"); +// args.push_back("-n"); +// args.push_back(get_package_name(package_name) + "/com.godot.game.GodotApp"); + +// err = OS::get_singleton()->execute(adb, args, true, nullptr, nullptr, &rv); +// if (err || rv != 0) { +// EditorNode::add_io_error("Could not execute on device."); +// CLEANUP_AND_RETURN(ERR_CANT_CREATE); +// } + +// CLEANUP_AND_RETURN(OK); +//#undef CLEANUP_AND_RETURN +// } + +// virtual Ref get_run_icon() const override { +// return run_icon; +// } + +// static String get_adb_path() { +// String exe_ext = ""; +// if (OS::get_singleton()->get_name() == "Windows") { +// exe_ext = ".exe"; +// } +// String sdk_path = EditorSettings::get_singleton()->get("export/android/android_sdk_path"); +// return sdk_path.plus_file("platform-tools/adb" + exe_ext); +// } + +// static String get_apksigner_path() { +// String exe_ext = ""; +// if (OS::get_singleton()->get_name() == "Windows") { +// exe_ext = ".bat"; +// } +// String apksigner_command_name = "apksigner" + exe_ext; +// String sdk_path = EditorSettings::get_singleton()->get("export/android/android_sdk_path"); +// String apksigner_path = ""; + +// Error errn; +// String build_tools_dir = sdk_path.plus_file("build-tools"); +// DirAccessRef da = DirAccess::open(build_tools_dir, &errn); +// if (errn != OK) { +// print_error("Unable to open Android 'build-tools' directory."); +// return apksigner_path; +// } + +// // There are additional versions directories we need to go through. +// da->list_dir_begin(); +// String sub_dir = da->get_next(); +// while (!sub_dir.is_empty()) { +// if (!sub_dir.begins_with(".") && da->current_is_dir()) { +// // Check if the tool is here. +// String tool_path = build_tools_dir.plus_file(sub_dir).plus_file(apksigner_command_name); +// if (FileAccess::exists(tool_path)) { +// apksigner_path = tool_path; +// break; +// } +// } +// sub_dir = da->get_next(); +// } +// da->list_dir_end(); + +// if (apksigner_path.is_empty()) { +// EditorNode::get_singleton()->show_warning(TTR("Unable to find the 'apksigner' tool.")); +// } + +// return apksigner_path; +// } + +// virtual bool can_export(const Ref &p_preset, String &r_error, bool &r_missing_templates) const override { +// String err; +// bool valid = false; + +// // Look for export templates (first official, and if defined custom templates). + +// if (!bool(p_preset->get("custom_template/use_custom_build"))) { +// String template_err; +// bool dvalid = false; +// bool rvalid = false; + +// if (p_preset->get("custom_template/debug") != "") { +// dvalid = FileAccess::exists(p_preset->get("custom_template/debug")); +// if (!dvalid) { +// template_err += TTR("Custom debug template not found.") + "\n"; +// } +// } else { +// dvalid = exists_export_template("android_debug.apk", &template_err); +// } + +// if (p_preset->get("custom_template/release") != "") { +// rvalid = FileAccess::exists(p_preset->get("custom_template/release")); +// if (!rvalid) { +// template_err += TTR("Custom release template not found.") + "\n"; +// } +// } else { +// rvalid = exists_export_template("android_release.apk", &template_err); +// } + +// valid = dvalid || rvalid; +// if (!valid) { +// err += template_err; +// } +// } else { +// valid = exists_export_template("android_source.zip", &err); + +// if (!FileAccess::exists("res://android/build/build.gradle")) { +// err += TTR("Android build template not installed in the project. Install it from the Project menu.") + "\n"; +// valid = false; +// } +// } +// r_missing_templates = !valid; + +// // Validate the rest of the configuration. + +// String dk = p_preset->get("keystore/debug"); + +// if (!FileAccess::exists(dk)) { +// dk = EditorSettings::get_singleton()->get("export/android/debug_keystore"); +// if (!FileAccess::exists(dk)) { +// valid = false; +// err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n"; +// } +// } + +// String rk = p_preset->get("keystore/release"); + +// if (!rk.is_empty() && !FileAccess::exists(rk)) { +// valid = false; +// err += TTR("Release keystore incorrectly configured in the export preset.") + "\n"; +// } + +// String sdk_path = EditorSettings::get_singleton()->get("export/android/android_sdk_path"); +// if (sdk_path == "") { +// err += TTR("A valid Android SDK path is required in Editor Settings.") + "\n"; +// valid = false; +// } else { +// Error errn; +// // Check for the platform-tools directory. +// DirAccessRef da = DirAccess::open(sdk_path.plus_file("platform-tools"), &errn); +// if (errn != OK) { +// err += TTR("Invalid Android SDK path in Editor Settings."); +// err += TTR("Missing 'platform-tools' directory!"); +// err += "\n"; +// valid = false; +// } + +// // Validate that adb is available +// String adb_path = get_adb_path(); +// if (!FileAccess::exists(adb_path)) { +// err += TTR("Unable to find Android SDK platform-tools' adb command."); +// err += TTR("Please check in the Android SDK directory specified in Editor Settings."); +// err += "\n"; +// valid = false; +// } + +// // Check for the build-tools directory. +// DirAccessRef build_tools_da = DirAccess::open(sdk_path.plus_file("build-tools"), &errn); +// if (errn != OK) { +// err += TTR("Invalid Android SDK path in Editor Settings."); +// err += TTR("Missing 'build-tools' directory!"); +// err += "\n"; +// valid = false; +// } + +// // Validate that apksigner is available +// String apksigner_path = get_apksigner_path(); +// if (!FileAccess::exists(apksigner_path)) { +// err += TTR("Unable to find Android SDK build-tools' apksigner command."); +// err += TTR("Please check in the Android SDK directory specified in Editor Settings."); +// err += "\n"; +// valid = false; +// } +// } + +// bool apk_expansion = p_preset->get("apk_expansion/enable"); + +// if (apk_expansion) { +// String apk_expansion_pkey = p_preset->get("apk_expansion/public_key"); + +// if (apk_expansion_pkey == "") { +// valid = false; + +// err += TTR("Invalid public key for APK expansion.") + "\n"; +// } +// } + +// String pn = p_preset->get("package/unique_name"); +// String pn_err; + +// if (!is_package_name_valid(get_package_name(pn), &pn_err)) { +// valid = false; +// err += TTR("Invalid package name:") + " " + pn_err + "\n"; +// } + +// String etc_error = test_etc2(); +// if (etc_error != String()) { +// valid = false; +// err += etc_error; +// } + +// // Ensure that `Use Custom Build` is enabled if a plugin is selected. +// String enabled_plugins_names = get_plugins_names(get_enabled_plugins(p_preset)); +// bool custom_build_enabled = p_preset->get("custom_template/use_custom_build"); +// if (!enabled_plugins_names.is_empty() && !custom_build_enabled) { +// valid = false; +// err += TTR("\"Use Custom Build\" must be enabled to use the plugins."); +// err += "\n"; +// } + +// // Validate the Xr features are properly populated +// int xr_mode_index = p_preset->get("xr_features/xr_mode"); +// int degrees_of_freedom = p_preset->get("xr_features/degrees_of_freedom"); +// int hand_tracking = p_preset->get("xr_features/hand_tracking"); +// bool focus_awareness = p_preset->get("xr_features/focus_awareness"); +// if (xr_mode_index != /* XRMode.OVR*/ 1) { +// if (degrees_of_freedom > 0) { +// valid = false; +// err += TTR("\"Degrees Of Freedom\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\"."); +// err += "\n"; +// } + +// if (hand_tracking > 0) { +// valid = false; +// err += TTR("\"Hand Tracking\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\"."); +// err += "\n"; +// } + +// if (focus_awareness) { +// valid = false; +// err += TTR("\"Focus Awareness\" is only valid when \"Xr Mode\" is \"Oculus Mobile VR\"."); +// err += "\n"; +// } +// } + +// if (int(p_preset->get("custom_template/export_format")) == EXPORT_FORMAT_AAB && +// !bool(p_preset->get("custom_template/use_custom_build"))) { +// valid = false; +// err += TTR("\"Export AAB\" is only valid when \"Use Custom Build\" is enabled."); +// err += "\n"; +// } + +// r_error = err; +// return valid; +// } + +// virtual List get_binary_extensions(const Ref &p_preset) const override { +// List list; +// list.push_back("apk"); +// list.push_back("aab"); +// return list; +// } + +// inline bool is_clean_build_required(Vector enabled_plugins) { +// String plugin_names = get_plugins_names(enabled_plugins); +// bool first_build = last_custom_build_time == 0; +// bool have_plugins_changed = false; + +// if (!first_build) { +// have_plugins_changed = plugin_names != last_plugin_names; +// if (!have_plugins_changed) { +// for (int i = 0; i < enabled_plugins.size(); i++) { +// if (enabled_plugins.get(i).last_updated > last_custom_build_time) { +// have_plugins_changed = true; +// break; +// } +// } +// } +// } + +// last_custom_build_time = OS::get_singleton()->get_unix_time(); +// last_plugin_names = plugin_names; + +// return have_plugins_changed || first_build; +// } + +// String get_apk_expansion_fullpath(const Ref &p_preset, const String &p_path) { +// int version_code = p_preset->get("version/code"); +// String package_name = p_preset->get("package/unique_name"); +// String apk_file_name = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb"; +// String fullpath = p_path.get_base_dir().plus_file(apk_file_name); +// return fullpath; +// } + +// Error save_apk_expansion_file(const Ref &p_preset, const String &p_path) { +// String fullpath = get_apk_expansion_fullpath(p_preset, p_path); +// Error err = save_pack(p_preset, fullpath); +// return err; +// } + +// void get_command_line_flags(const Ref &p_preset, const String &p_path, int p_flags, Vector &r_command_line_flags) { +// String cmdline = p_preset->get("command_line/extra_args"); +// Vector command_line_strings = cmdline.strip_edges().split(" "); +// for (int i = 0; i < command_line_strings.size(); i++) { +// if (command_line_strings[i].strip_edges().length() == 0) { +// command_line_strings.remove(i); +// i--; +// } +// } + +// gen_export_flags(command_line_strings, p_flags); + +// bool apk_expansion = p_preset->get("apk_expansion/enable"); +// if (apk_expansion) { +// String fullpath = get_apk_expansion_fullpath(p_preset, p_path); +// String apk_expansion_public_key = p_preset->get("apk_expansion/public_key"); + +// command_line_strings.push_back("--use_apk_expansion"); +// command_line_strings.push_back("--apk_expansion_md5"); +// command_line_strings.push_back(FileAccess::get_md5(fullpath)); +// command_line_strings.push_back("--apk_expansion_key"); +// command_line_strings.push_back(apk_expansion_public_key.strip_edges()); +// } + +// int xr_mode_index = p_preset->get("xr_features/xr_mode"); +// if (xr_mode_index == 1) { +// command_line_strings.push_back("--xr_mode_ovr"); +// } else { // XRMode.REGULAR is the default. +// command_line_strings.push_back("--xr_mode_regular"); +// } + +// bool use_32_bit_framebuffer = p_preset->get("graphics/32_bits_framebuffer"); +// if (use_32_bit_framebuffer) { +// command_line_strings.push_back("--use_depth_32"); +// } + +// bool immersive = p_preset->get("screen/immersive_mode"); +// if (immersive) { +// command_line_strings.push_back("--use_immersive"); +// } + +// bool debug_opengl = p_preset->get("graphics/opengl_debug"); +// if (debug_opengl) { +// command_line_strings.push_back("--debug_opengl"); +// } + +// if (command_line_strings.size()) { +// r_command_line_flags.resize(4); +// encode_uint32(command_line_strings.size(), &r_command_line_flags.write[0]); +// for (int i = 0; i < command_line_strings.size(); i++) { +// print_line(itos(i) + " param: " + command_line_strings[i]); +// CharString command_line_argument = command_line_strings[i].utf8(); +// int base = r_command_line_flags.size(); +// int length = command_line_argument.length(); +// if (length == 0) +// continue; +// r_command_line_flags.resize(base + 4 + length); +// encode_uint32(length, &r_command_line_flags.write[base]); +// copymem(&r_command_line_flags.write[base + 4], command_line_argument.ptr(), length); +// } +// } +// } + +// Error sign_apk(const Ref &p_preset, bool p_debug, const String &export_path, EditorProgress &ep) { +// int export_format = int(p_preset->get("custom_template/export_format")); +// String export_label = export_format == EXPORT_FORMAT_AAB ? "AAB" : "APK"; +// String release_keystore = p_preset->get("keystore/release"); +// String release_username = p_preset->get("keystore/release_user"); +// String release_password = p_preset->get("keystore/release_password"); + +// String apksigner = get_apksigner_path(); +// if (!FileAccess::exists(apksigner)) { +// EditorNode::add_io_error("'apksigner' could not be found.\nPlease check the command is available in the Android SDK build-tools directory.\nThe resulting " + export_label + " is unsigned."); +// return OK; +// } + +// String keystore; +// String password; +// String user; +// if (p_debug) { +// keystore = p_preset->get("keystore/debug"); +// password = p_preset->get("keystore/debug_password"); +// user = p_preset->get("keystore/debug_user"); + +// if (keystore.is_empty()) { +// keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore"); +// password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass"); +// user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user"); +// } + +// if (ep.step("Signing debug " + export_label + "...", 104)) { +// return ERR_SKIP; +// } + +// } else { +// keystore = release_keystore; +// password = release_password; +// user = release_username; + +// if (ep.step("Signing release " + export_label + "...", 104)) { +// return ERR_SKIP; +// } +// } + +// if (!FileAccess::exists(keystore)) { +// EditorNode::add_io_error("Could not find keystore, unable to export."); +// return ERR_FILE_CANT_OPEN; +// } + +// List args; +// args.push_back("sign"); +// args.push_back("--verbose"); +// args.push_back("--ks"); +// args.push_back(keystore); +// args.push_back("--ks-pass"); +// args.push_back("pass:" + password); +// args.push_back("--ks-key-alias"); +// args.push_back(user); +// args.push_back(export_path); +// int retval; +// OS::get_singleton()->execute(apksigner, args, true, NULL, NULL, &retval); +// if (retval) { +// EditorNode::add_io_error("'apksigner' returned with error #" + itos(retval)); +// return ERR_CANT_CREATE; +// } + +// if (ep.step("Verifying " + export_label + "...", 105)) { +// return ERR_SKIP; +// } + +// args.clear(); +// args.push_back("verify"); +// args.push_back("--verbose"); +// args.push_back(export_path); + +// OS::get_singleton()->execute(apksigner, args, true, NULL, NULL, &retval); +// if (retval) { +// EditorNode::add_io_error("'apksigner' verification of " + export_label + " failed."); +// return ERR_CANT_CREATE; +// } +// return OK; +// } + +// void _clear_assets_directory() { +// DirAccessRef da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES); +// if (da_res->dir_exists("res://android/build/assets")) { +// DirAccessRef da_assets = DirAccess::open("res://android/build/assets"); +// da_assets->erase_contents_recursive(); +// da_res->remove("res://android/build/assets"); +// } +// } + +// virtual Error export_project(const Ref &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override { +// int export_format = int(p_preset->get("custom_template/export_format")); +// bool should_sign = p_preset->get("package/signed"); +// return export_project_helper(p_preset, p_debug, p_path, export_format, should_sign, p_flags); +// } + +// Error export_project_helper(const Ref &p_preset, bool p_debug, const String &p_path, int export_format, bool should_sign, int p_flags) { +// ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags); + +// String src_apk; +// Error err; + +// EditorProgress ep("export", "Exporting for Android", 105, true); + +// bool use_custom_build = bool(p_preset->get("custom_template/use_custom_build")); +// bool p_give_internet = p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG); +// bool apk_expansion = p_preset->get("apk_expansion/enable"); +// Vector enabled_abis = get_enabled_abis(p_preset); + +// Ref splash_image; +// Ref splash_bg_color_image; +// load_splash_refs(splash_image, splash_bg_color_image); + +// Ref main_image; +// Ref foreground; +// Ref background; + +// load_icon_refs(p_preset, main_image, foreground, background); + +// Vector command_line_flags; +// // Write command line flags into the command_line_flags variable. +// get_command_line_flags(p_preset, p_path, p_flags, command_line_flags); + +// if (export_format == EXPORT_FORMAT_AAB) { +// if (!p_path.ends_with(".aab")) { +// EditorNode::get_singleton()->show_warning(TTR("Invalid filename! Android App Bundle requires the *.aab extension.")); +// return ERR_UNCONFIGURED; +// } +// if (apk_expansion) { +// EditorNode::get_singleton()->show_warning(TTR("APK Expansion not compatible with Android App Bundle.")); +// return ERR_UNCONFIGURED; +// } +// } +// if (export_format == EXPORT_FORMAT_APK && !p_path.ends_with(".apk")) { +// EditorNode::get_singleton()->show_warning( +// TTR("Invalid filename! Android APK requires the *.apk extension.")); +// return ERR_UNCONFIGURED; +// } +// if (export_format > EXPORT_FORMAT_AAB || export_format < EXPORT_FORMAT_APK) { +// EditorNode::add_io_error("Unsupported export format!\n"); +// return ERR_UNCONFIGURED; //TODO: is this the right error? +// } + +// if (use_custom_build) { +// //test that installed build version is alright +// { +// FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ); +// if (!f) { +// EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu.")); +// return ERR_UNCONFIGURED; +// } +// String version = f->get_line().strip_edges(); +// f->close(); +// if (version != VERSION_FULL_CONFIG) { +// EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n Template installed: %s\n Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG)); +// return ERR_UNCONFIGURED; +// } +// } +// String sdk_path = EDITOR_GET("export/android/android_sdk_path"); +// ERR_FAIL_COND_V_MSG(sdk_path == "", ERR_UNCONFIGURED, "Android SDK path must be configured in Editor Settings at 'export/android/android_sdk_path'."); + +// // TODO: should we use "package/name" or "application/config/name"? +// String project_name = get_project_name(p_preset->get("package/name")); +// err = _create_project_name_strings_files(p_preset, project_name); //project name localization. +// if (err != OK) { +// EditorNode::add_io_error("Unable to overwrite res://android/build/res/*.xml files with project name"); +// } +// // Copies the project icon files into the appropriate Gradle project directory. +// _copy_icons_to_gradle_project(p_preset, splash_image, splash_bg_color_image, main_image, foreground, background); +// // Write an AndroidManifest.xml file into the Gradle project directory. +// _write_tmp_manifest(p_preset, p_give_internet, p_debug); + +// //stores all the project files inside the Gradle project directory. Also includes all ABIs +// _clear_assets_directory(); +// if (!apk_expansion) { +// err = export_project_files(p_preset, rename_and_store_file_in_gradle_project, NULL, ignore_so_file); +// if (err != OK) { +// EditorNode::add_io_error("Could not export project files to gradle project\n"); +// return err; +// } +// } else { +// err = save_apk_expansion_file(p_preset, p_path); +// if (err != OK) { +// EditorNode::add_io_error("Could not write expansion package file!"); +// return err; +// } +// } +// store_file_at_path("res://android/build/assets/_cl_", command_line_flags); + +// OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required +// String build_command; + +//#ifdef WINDOWS_ENABLED +// build_command = "gradlew.bat"; +//#else +// build_command = "gradlew"; +//#endif + +// String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build"); +// build_command = build_path.plus_file(build_command); + +// String package_name = get_package_name(p_preset->get("package/unique_name")); +// String version_code = itos(p_preset->get("version/code")); +// String version_name = p_preset->get("version/name"); +// String enabled_abi_string = String("|").join(enabled_abis); +// String sign_flag = should_sign ? "true" : "false"; +// String zipalign_flag = "true"; + +// Vector enabled_plugins = get_enabled_plugins(p_preset); +// String local_plugins_binaries = get_plugins_binaries(BINARY_TYPE_LOCAL, enabled_plugins); +// String remote_plugins_binaries = get_plugins_binaries(BINARY_TYPE_REMOTE, enabled_plugins); +// String custom_maven_repos = get_plugins_custom_maven_repos(enabled_plugins); +// bool clean_build_required = is_clean_build_required(enabled_plugins); + +// List cmdline; +// if (clean_build_required) { +// cmdline.push_back("clean"); +// } + +// String build_type = p_debug ? "Debug" : "Release"; +// if (export_format == EXPORT_FORMAT_AAB) { +// String bundle_build_command = vformat("bundle%s", build_type); +// cmdline.push_back(bundle_build_command); +// } else if (export_format == EXPORT_FORMAT_APK) { +// String apk_build_command = vformat("assemble%s", build_type); +// cmdline.push_back(apk_build_command); +// } + +// cmdline.push_back("-Pexport_package_name=" + package_name); // argument to specify the package name. +// cmdline.push_back("-Pexport_version_code=" + version_code); // argument to specify the version code. +// cmdline.push_back("-Pexport_version_name=" + version_name); // argument to specify the version name. +// cmdline.push_back("-Pexport_enabled_abis=" + enabled_abi_string); // argument to specify enabled ABIs. +// cmdline.push_back("-Pplugins_local_binaries=" + local_plugins_binaries); // argument to specify the list of plugins local dependencies. +// cmdline.push_back("-Pplugins_remote_binaries=" + remote_plugins_binaries); // argument to specify the list of plugins remote dependencies. +// cmdline.push_back("-Pplugins_maven_repos=" + custom_maven_repos); // argument to specify the list of custom maven repos for the plugins dependencies. +// cmdline.push_back("-Pperform_zipalign=" + zipalign_flag); // argument to specify whether the build should be zipaligned. +// cmdline.push_back("-Pperform_signing=" + sign_flag); // argument to specify whether the build should be signed. +// if (should_sign && !p_debug) { +// // Pass the release keystore info as well +// String release_keystore = p_preset->get("keystore/release"); +// String release_username = p_preset->get("keystore/release_user"); +// String release_password = p_preset->get("keystore/release_password"); +// if (!FileAccess::exists(release_keystore)) { +// EditorNode::add_io_error("Could not find keystore, unable to export."); +// return ERR_FILE_CANT_OPEN; +// } + +// cmdline.push_back("-Prelease_keystore_file=" + release_keystore); // argument to specify the release keystore file. +// cmdline.push_back("-Prelease_keystore_alias=" + release_username); // argument to specify the release keystore alias. +// cmdline.push_back("-Prelease_keystore_password=" + release_password); // argument to specity the release keystore password. +// } +// cmdline.push_back("-p"); // argument to specify the start directory. +// cmdline.push_back(build_path); // start directory. + +// int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline); +// if (result != 0) { +// EditorNode::get_singleton()->show_warning(TTR("Building of Android project failed, check output for the error.\nAlternatively visit docs.godotengine.org for Android build documentation.")); +// return ERR_CANT_CREATE; +// } + +// List copy_args; +// String copy_command; +// if (export_format == EXPORT_FORMAT_AAB) { +// copy_command = vformat("copyAndRename%sAab", build_type); +// } else if (export_format == EXPORT_FORMAT_APK) { +// copy_command = vformat("copyAndRename%sApk", build_type); +// } + +// copy_args.push_back(copy_command); + +// copy_args.push_back("-p"); // argument to specify the start directory. +// copy_args.push_back(build_path); // start directory. + +// String export_filename = p_path.get_file(); +// String export_path = p_path.get_base_dir(); +// if (export_path.is_rel_path()) { +// export_path = OS::get_singleton()->get_resource_dir().plus_file(export_path); +// } +// export_path = ProjectSettings::get_singleton()->globalize_path(export_path).simplify_path(); + +// copy_args.push_back("-Pexport_path=file:" + export_path); +// copy_args.push_back("-Pexport_filename=" + export_filename); + +// int copy_result = EditorNode::get_singleton()->execute_and_show_output(TTR("Moving output"), build_command, copy_args); +// if (copy_result != 0) { +// EditorNode::get_singleton()->show_warning(TTR("Unable to copy and rename export file, check gradle project directory for outputs.")); +// return ERR_CANT_CREATE; +// } + +// return OK; +// } +// // This is the start of the Legacy build system +// if (p_debug) +// src_apk = p_preset->get("custom_template/debug"); +// else +// src_apk = p_preset->get("custom_template/release"); +// src_apk = src_apk.strip_edges(); +// if (src_apk == "") { +// if (p_debug) { +// src_apk = find_export_template("android_debug.apk"); +// } else { +// src_apk = find_export_template("android_release.apk"); +// } +// if (src_apk == "") { +// EditorNode::add_io_error("Package not found: " + src_apk); +// return ERR_FILE_NOT_FOUND; +// } +// } + +// if (!DirAccess::exists(p_path.get_base_dir())) { +// return ERR_FILE_BAD_PATH; +// } + +// FileAccess *src_f = nullptr; +// zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + +// if (ep.step("Creating APK...", 0)) { +// return ERR_SKIP; +// } + +// unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io); +// if (!pkg) { +// EditorNode::add_io_error("Could not find template APK to export:\n" + src_apk); +// return ERR_FILE_NOT_FOUND; +// } + +// int ret = unzGoToFirstFile(pkg); + +// zlib_filefunc_def io2 = io; +// FileAccess *dst_f = nullptr; +// io2.opaque = &dst_f; + +// String tmp_unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk"); + +//#define CLEANUP_AND_RETURN(m_err) \ +// { \ +// DirAccess::remove_file_or_error(tmp_unaligned_path); \ +// return m_err; \ +// } + +// zipFile unaligned_apk = zipOpen2(tmp_unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); + +// String cmdline = p_preset->get("command_line/extra_args"); + +// String version_name = p_preset->get("version/name"); +// String package_name = p_preset->get("package/unique_name"); + +// String apk_expansion_pkey = p_preset->get("apk_expansion/public_key"); + +// Vector invalid_abis(enabled_abis); +// while (ret == UNZ_OK) { +// //get filename +// unz_file_info info; +// char fname[16384]; +// ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + +// bool skip = false; + +// String file = fname; + +// Vector data; +// data.resize(info.uncompressed_size); + +// //read +// unzOpenCurrentFile(pkg); +// unzReadCurrentFile(pkg, data.ptrw(), data.size()); +// unzCloseCurrentFile(pkg); + +// //write +// if (file == "AndroidManifest.xml") { +// _fix_manifest(p_preset, data, p_give_internet); +// } +// if (file == "resources.arsc") { +// _fix_resources(p_preset, data); +// } + +// // Process the splash image +// if (file == SPLASH_IMAGE_EXPORT_PATH && splash_image.is_valid() && !splash_image->is_empty()) { +// _load_image_data(splash_image, data); +// } + +// // Process the splash bg color image +// if (file == SPLASH_BG_COLOR_PATH && splash_bg_color_image.is_valid() && !splash_bg_color_image->is_empty()) { +// _load_image_data(splash_bg_color_image, data); +// } + +// for (int i = 0; i < icon_densities_count; ++i) { +// if (main_image.is_valid() && !main_image->is_empty()) { +// if (file == launcher_icons[i].export_path) { +// _process_launcher_icons(file, main_image, launcher_icons[i].dimensions, data); +// } +// } +// if (foreground.is_valid() && !foreground->is_empty()) { +// if (file == launcher_adaptive_icon_foregrounds[i].export_path) { +// _process_launcher_icons(file, foreground, launcher_adaptive_icon_foregrounds[i].dimensions, data); +// } +// } +// if (background.is_valid() && !background->is_empty()) { +// if (file == launcher_adaptive_icon_backgrounds[i].export_path) { +// _process_launcher_icons(file, background, launcher_adaptive_icon_backgrounds[i].dimensions, data); +// } +// } +// } + +// if (file.ends_with(".so")) { +// bool enabled = false; +// for (int i = 0; i < enabled_abis.size(); ++i) { +// if (file.begins_with("lib/" + enabled_abis[i] + "/")) { +// invalid_abis.erase(enabled_abis[i]); +// enabled = true; +// break; +// } +// } +// if (!enabled) { +// skip = true; +// } +// } + +// if (file.begins_with("META-INF") && should_sign) { +// skip = true; +// } + +// if (!skip) { +// print_line("ADDING: " + file); + +// // Respect decision on compression made by AAPT for the export template +// const bool uncompressed = info.compression_method == 0; + +// zip_fileinfo zipfi = get_zip_fileinfo(); + +// zipOpenNewFileInZip(unaligned_apk, +// file.utf8().get_data(), +// &zipfi, +// nullptr, +// 0, +// nullptr, +// 0, +// nullptr, +// uncompressed ? 0 : Z_DEFLATED, +// Z_DEFAULT_COMPRESSION); + +// zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size()); +// zipCloseFileInZip(unaligned_apk); +// } + +// ret = unzGoToNextFile(pkg); +// } + +// if (!invalid_abis.is_empty()) { +// String unsupported_arch = String(", ").join(invalid_abis); +// EditorNode::add_io_error("Missing libraries in the export template for the selected architectures: " + unsupported_arch + ".\n" + +// "Please build a template with all required libraries, or uncheck the missing architectures in the export preset."); +// CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND); +// } + +// if (ep.step("Adding files...", 1)) { +// CLEANUP_AND_RETURN(ERR_SKIP); +// } +// err = OK; + +// if (p_flags & DEBUG_FLAG_DUMB_CLIENT) { +// APKExportData ed; +// ed.ep = &ep; +// ed.apk = unaligned_apk; +// err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so); +// } else { +// if (apk_expansion) { +// err = save_apk_expansion_file(p_preset, p_path); +// if (err != OK) { +// EditorNode::add_io_error("Could not write expansion package file!"); +// return err; +// } +// } else { +// APKExportData ed; +// ed.ep = &ep; +// ed.apk = unaligned_apk; +// err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so); +// } +// } + +// if (err != OK) { +// unzClose(pkg); +// EditorNode::add_io_error("Could not export project files"); +// CLEANUP_AND_RETURN(ERR_SKIP); +// } + +// zip_fileinfo zipfi = get_zip_fileinfo(); +// zipOpenNewFileInZip(unaligned_apk, +// "assets/_cl_", +// &zipfi, +// NULL, +// 0, +// NULL, +// 0, +// NULL, +// 0, // No compress (little size gain and potentially slower startup) +// Z_DEFAULT_COMPRESSION); +// zipWriteInFileInZip(unaligned_apk, command_line_flags.ptr(), command_line_flags.size()); +// zipCloseFileInZip(unaligned_apk); +// zipClose(unaligned_apk, nullptr); +// unzClose(pkg); + +// if (err != OK) { +// CLEANUP_AND_RETURN(err); +// } + +// // Let's zip-align (must be done before signing) + +// static const int ZIP_ALIGNMENT = 4; + +// // If we're not signing the apk, then the next step should be the last. +// const int next_step = should_sign ? 103 : 105; +// if (ep.step("Aligning APK...", next_step)) { +// CLEANUP_AND_RETURN(ERR_SKIP); +// } + +// unzFile tmp_unaligned = unzOpen2(tmp_unaligned_path.utf8().get_data(), &io); +// if (!tmp_unaligned) { +// EditorNode::add_io_error("Could not unzip temporary unaligned APK."); +// CLEANUP_AND_RETURN(ERR_FILE_NOT_FOUND); +// } + +// ret = unzGoToFirstFile(tmp_unaligned); + +// io2 = io; +// dst_f = nullptr; +// io2.opaque = &dst_f; +// zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); + +// // Take files from the unaligned APK and write them out to the aligned one +// // in raw mode, i.e. not uncompressing and recompressing, aligning them as needed, +// // following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp +// int bias = 0; +// while (ret == UNZ_OK) { +// unz_file_info info; +// memset(&info, 0, sizeof(info)); + +// char fname[16384]; +// char extra[16384]; +// ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0); + +// String file = fname; + +// Vector data; +// data.resize(info.compressed_size); + +// // read +// int method, level; +// unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read +// long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned); +// unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size()); +// unzCloseCurrentFile(tmp_unaligned); + +// // align +// int padding = 0; +// if (!info.compression_method) { +// // Uncompressed file => Align +// long new_offset = file_offset + bias; +// padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT; +// } + +// memset(extra + info.size_file_extra, 0, padding); + +// zip_fileinfo fileinfo = get_zip_fileinfo(); +// zipOpenNewFileInZip2(final_apk, +// file.utf8().get_data(), +// &fileinfo, +// extra, +// info.size_file_extra + padding, +// nullptr, +// 0, +// nullptr, +// method, +// level, +// 1); // raw write +// zipWriteInFileInZip(final_apk, data.ptr(), data.size()); +// zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc); + +// bias += padding; + +// ret = unzGoToNextFile(tmp_unaligned); +// } + +// zipClose(final_apk, nullptr); +// unzClose(tmp_unaligned); + +// if (should_sign) { +// // Signing must be done last as any additional modifications to the +// // file will invalidate the signature. +// err = sign_apk(p_preset, p_debug, p_path, ep); +// if (err != OK) { +// CLEANUP_AND_RETURN(err); +// } +// } + +// CLEANUP_AND_RETURN(OK); +// } + +// virtual void get_platform_features(List *r_features) override { +// r_features->push_back("mobile"); +// r_features->push_back("Android"); +// } + +// virtual void resolve_platform_feature_priorities(const Ref &p_preset, Set &p_features) override { +// } + +// EditorExportPlatformAndroid() { +// Ref img = memnew(Image(_android_logo)); +// logo.instance(); +// logo->create_from_image(img); + +// img = Ref(memnew(Image(_android_run_icon))); +// run_icon.instance(); +// run_icon->create_from_image(img); + +// devices_changed = true; +// plugins_changed = true; +// quit_request = false; +// check_for_changes_thread = Thread::create(_check_for_changes_poll_thread, this); +// } + +// ~EditorExportPlatformAndroid() { +// quit_request = true; +// Thread::wait_to_finish(check_for_changes_thread); +// memdelete(check_for_changes_thread); +// } +//}; void register_android_exporter() { String exe_ext; diff --git a/platform/android/export/gradle_export_util.h b/platform/android/export/gradle_export_util.h index 744022f1f9f..7c773309e86 100644 --- a/platform/android/export/gradle_export_util.h +++ b/platform/android/export/gradle_export_util.h @@ -74,6 +74,51 @@ Error rename_and_store_file_in_gradle_project(void *p_userdata, const String &p_ // Creates strings.xml files inside the gradle project for different locales. Error _create_project_name_strings_files(const Ref &p_preset, const String &project_name); +//Error _create_project_name_strings_files(const Ref &p_preset, const String &project_name) { +// // Stores the string into the default values directory. +// String processed_default_xml_string = vformat(godot_project_name_xml_string, project_name.xml_escape(true)); +// store_string_at_path("res://android/build/res/values/godot_project_name_string.xml", processed_default_xml_string); + +// // Searches the Gradle project res/ directory to find all supported locales +// DirAccessRef da = DirAccess::open("res://android/build/res"); +// if (!da) { +// return ERR_CANT_OPEN; +// } +// da->list_dir_begin(); +// while (true) { +// String file = da->get_next(); +// if (file == "") { +// break; +// } +// if (!file.begins_with("values-")) { +// // NOTE: This assumes all directories that start with "values-" are for localization. +// continue; +// } +// String locale = file.replace("values-", "").replace("-r", "_"); +// String property_name = "application/config/name_" + locale; +// String locale_directory = "res://android/build/res/" + file + "/godot_project_name_string.xml"; +// if (ProjectSettings::get_singleton()->has_setting(property_name)) { +// String locale_project_name = ProjectSettings::get_singleton()->get(property_name); +// String processed_xml_string = vformat(godot_project_name_xml_string, locale_project_name.xml_escape(true)); +// store_string_at_path(locale_directory, processed_xml_string); +// } else { +// // TODO: Once the legacy build system is deprecated we don't need to have xml files for this else branch +// store_string_at_path(locale_directory, processed_default_xml_string); +// } +// } +// da->list_dir_end(); +// return OK; +//} + +//String bool_to_string(bool v) { +// return v ? "true" : "false"; +//} + +//String _get_gles_tag() { +// bool min_gles3 = ProjectSettings::get_singleton()->get("rendering/driver/driver_name") == "GLES3" && +// !ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2"); +// return min_gles3 ? " \n" : ""; +//} String bool_to_string(bool v); diff --git a/platform/iphone/export/export.cpp b/platform/iphone/export/export.cpp index 208626ae368..6cec3658852 100644 --- a/platform/iphone/export/export.cpp +++ b/platform/iphone/export/export.cpp @@ -31,6 +31,1929 @@ #include "export.h" #include "export_plugin.h" +//#include "core/config/project_settings.h" +//#include "core/io/image_loader.h" +//#include "core/io/marshalls.h" +//#include "core/io/resource_saver.h" +//#include "core/io/zip_io.h" +//#include "core/os/file_access.h" +//#include "core/os/os.h" +//#include "core/version.h" +//#include "editor/editor_export.h" +//#include "editor/editor_node.h" +//#include "editor/editor_settings.h" +//#include "main/splash.gen.h" +//#include "platform/iphone/logo.gen.h" +//#include "platform/iphone/plugin/godot_plugin_config.h" +//#include "string.h" + +//#include + +//class EditorExportPlatformIOS : public EditorExportPlatform { +// GDCLASS(EditorExportPlatformIOS, EditorExportPlatform); + +// int version_code; + +// Ref logo; + +// // Plugins +// volatile bool plugins_changed; +// Thread *check_for_changes_thread; +// volatile bool quit_request; +// Mutex plugins_lock; +// Vector plugins; + +// typedef Error (*FileHandler)(String p_file, void *p_userdata); +// static Error _walk_dir_recursive(DirAccess *p_da, FileHandler p_handler, void *p_userdata); +// static Error _codesign(String p_file, void *p_userdata); +// void _blend_and_rotate(Ref &p_dst, Ref &p_src, bool p_rot); + +// struct IOSConfigData { +// String pkg_name; +// String binary_name; +// String plist_content; +// String architectures; +// String linker_flags; +// String cpp_code; +// String modules_buildfile; +// String modules_fileref; +// String modules_buildphase; +// String modules_buildgrp; +// Vector capabilities; +// }; +// struct ExportArchitecture { +// String name; +// bool is_default = false; + +// ExportArchitecture() {} + +// ExportArchitecture(String p_name, bool p_is_default) { +// name = p_name; +// is_default = p_is_default; +// } +// }; + +// struct IOSExportAsset { +// String exported_path; +// bool is_framework = false; // framework is anything linked to the binary, otherwise it's a resource +// bool should_embed = false; +// }; + +// String _get_additional_plist_content(); +// String _get_linker_flags(); +// String _get_cpp_code(); +// void _fix_config_file(const Ref &p_preset, Vector &pfile, const IOSConfigData &p_config, bool p_debug); +// Error _export_loading_screen_images(const Ref &p_preset, const String &p_dest_dir); +// Error _export_loading_screen_file(const Ref &p_preset, const String &p_dest_dir); +// Error _export_icons(const Ref &p_preset, const String &p_iconset_dir); + +// Vector _get_supported_architectures(); +// Vector _get_preset_architectures(const Ref &p_preset); + +// void _add_assets_to_project(const Ref &p_preset, Vector &p_project_data, const Vector &p_additional_assets); +// Error _export_additional_assets(const String &p_out_dir, const Vector &p_assets, bool p_is_framework, bool p_should_embed, Vector &r_exported_assets); +// Error _copy_asset(const String &p_out_dir, const String &p_asset, const String *p_custom_file_name, bool p_is_framework, bool p_should_embed, Vector &r_exported_assets); +// Error _export_additional_assets(const String &p_out_dir, const Vector &p_libraries, Vector &r_exported_assets); +// Error _export_ios_plugins(const Ref &p_preset, IOSConfigData &p_config_data, const String &dest_dir, Vector &r_exported_assets, bool p_debug); + +// bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const { +// String pname = p_package; + +// if (pname.length() == 0) { +// if (r_error) { +// *r_error = TTR("Identifier is missing."); +// } +// return false; +// } + +// for (int i = 0; i < pname.length(); i++) { +// char32_t c = pname[i]; +// if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.')) { +// if (r_error) { +// *r_error = vformat(TTR("The character '%s' is not allowed in Identifier."), String::chr(c)); +// } +// return false; +// } +// } + +// return true; +// } + +// static void _check_for_changes_poll_thread(void *ud) { +// EditorExportPlatformIOS *ea = (EditorExportPlatformIOS *)ud; + +// while (!ea->quit_request) { +// // Nothing to do if we already know the plugins have changed. +// if (!ea->plugins_changed) { +// MutexLock lock(ea->plugins_lock); + +// Vector loaded_plugins = get_plugins(); + +// if (ea->plugins.size() != loaded_plugins.size()) { +// ea->plugins_changed = true; +// } else { +// for (int i = 0; i < ea->plugins.size(); i++) { +// if (ea->plugins[i].name != loaded_plugins[i].name || ea->plugins[i].last_updated != loaded_plugins[i].last_updated) { +// ea->plugins_changed = true; +// break; +// } +// } +// } +// } + +// uint64_t wait = 3000000; +// uint64_t time = OS::get_singleton()->get_ticks_usec(); +// while (OS::get_singleton()->get_ticks_usec() - time < wait) { +// OS::get_singleton()->delay_usec(300000); + +// if (ea->quit_request) { +// break; +// } +// } +// } +// } + +//protected: +// virtual void get_preset_features(const Ref &p_preset, List *r_features) override; +// virtual void get_export_options(List *r_options) override; + +//public: +// virtual String get_name() const override { return "iOS"; } +// virtual String get_os_name() const override { return "iOS"; } +// virtual Ref get_logo() const override { return logo; } + +// virtual bool should_update_export_options() override { +// bool export_options_changed = plugins_changed; +// if (export_options_changed) { +// // don't clear unless we're reporting true, to avoid race +// plugins_changed = false; +// } +// return export_options_changed; +// } + +// virtual List get_binary_extensions(const Ref &p_preset) const override { +// List list; +// list.push_back("ipa"); +// return list; +// } +// virtual Error export_project(const Ref &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override; + +// virtual bool can_export(const Ref &p_preset, String &r_error, bool &r_missing_templates) const override; + +// virtual void get_platform_features(List *r_features) override { +// r_features->push_back("mobile"); +// r_features->push_back("iOS"); +// } + +// virtual void resolve_platform_feature_priorities(const Ref &p_preset, Set &p_features) override { +// } + +// EditorExportPlatformIOS(); +// ~EditorExportPlatformIOS(); + +// /// List the gdip files in the directory specified by the p_path parameter. +// static Vector list_plugin_config_files(const String &p_path, bool p_check_directories) { +// Vector dir_files; +// DirAccessRef da = DirAccess::open(p_path); +// if (da) { +// da->list_dir_begin(); +// while (true) { +// String file = da->get_next(); +// if (file.is_empty()) { +// break; +// } + +// if (file == "." || file == "..") { +// continue; +// } + +// if (da->current_is_hidden()) { +// continue; +// } + +// if (da->current_is_dir()) { +// if (p_check_directories) { +// Vector directory_files = list_plugin_config_files(p_path.plus_file(file), false); +// for (int i = 0; i < directory_files.size(); ++i) { +// dir_files.push_back(file.plus_file(directory_files[i])); +// } +// } + +// continue; +// } + +// if (file.ends_with(PLUGIN_CONFIG_EXT)) { +// dir_files.push_back(file); +// } +// } +// da->list_dir_end(); +// } + +// return dir_files; +// } + +// static Vector get_plugins() { +// Vector loaded_plugins; + +// String plugins_dir = ProjectSettings::get_singleton()->get_resource_path().plus_file("ios/plugins"); + +// if (DirAccess::exists(plugins_dir)) { +// Vector plugins_filenames = list_plugin_config_files(plugins_dir, true); + +// if (!plugins_filenames.is_empty()) { +// Ref config_file = memnew(ConfigFile); +// for (int i = 0; i < plugins_filenames.size(); i++) { +// PluginConfig config = load_plugin_config(config_file, plugins_dir.plus_file(plugins_filenames[i])); +// if (config.valid_config) { +// loaded_plugins.push_back(config); +// } else { +// print_error("Invalid plugin config file " + plugins_filenames[i]); +// } +// } +// } +// } + +// return loaded_plugins; +// } + +// static Vector get_enabled_plugins(const Ref &p_presets) { +// Vector enabled_plugins; +// Vector all_plugins = get_plugins(); +// for (int i = 0; i < all_plugins.size(); i++) { +// PluginConfig plugin = all_plugins[i]; +// bool enabled = p_presets->get("plugins/" + plugin.name); +// if (enabled) { +// enabled_plugins.push_back(plugin); +// } +// } + +// return enabled_plugins; +// } +//}; + +//void EditorExportPlatformIOS::get_preset_features(const Ref &p_preset, List *r_features) { +// String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); +// r_features->push_back("pvrtc"); +// if (driver == "Vulkan") { +// // FIXME: Review if this is correct. +// r_features->push_back("etc2"); +// } + +// Vector architectures = _get_preset_architectures(p_preset); +// for (int i = 0; i < architectures.size(); ++i) { +// r_features->push_back(architectures[i]); +// } +//} + +//Vector EditorExportPlatformIOS::_get_supported_architectures() { +// Vector archs; +// archs.push_back(ExportArchitecture("armv7", false)); // Disabled by default, not included in official templates. +// archs.push_back(ExportArchitecture("arm64", true)); +// return archs; +//} + +//struct LoadingScreenInfo { +// const char *preset_key; +// const char *export_name; +// int width = 0; +// int height = 0; +// bool rotate = false; +//}; + +//static const LoadingScreenInfo loading_screen_infos[] = { +// { "landscape_launch_screens/iphone_2436x1125", "Default-Landscape-X.png", 2436, 1125, false }, +// { "landscape_launch_screens/iphone_2208x1242", "Default-Landscape-736h@3x.png", 2208, 1242, false }, +// { "landscape_launch_screens/ipad_1024x768", "Default-Landscape.png", 1024, 768, false }, +// { "landscape_launch_screens/ipad_2048x1536", "Default-Landscape@2x.png", 2048, 1536, false }, + +// { "portrait_launch_screens/iphone_640x960", "Default-480h@2x.png", 640, 960, true }, +// { "portrait_launch_screens/iphone_640x1136", "Default-568h@2x.png", 640, 1136, true }, +// { "portrait_launch_screens/iphone_750x1334", "Default-667h@2x.png", 750, 1334, true }, +// { "portrait_launch_screens/iphone_1125x2436", "Default-Portrait-X.png", 1125, 2436, true }, +// { "portrait_launch_screens/ipad_768x1024", "Default-Portrait.png", 768, 1024, true }, +// { "portrait_launch_screens/ipad_1536x2048", "Default-Portrait@2x.png", 1536, 2048, true }, +// { "portrait_launch_screens/iphone_1242x2208", "Default-Portrait-736h@3x.png", 1242, 2208, true } +//}; + +//void EditorExportPlatformIOS::get_export_options(List *r_options) { +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + +// Vector architectures = _get_supported_architectures(); +// for (int i = 0; i < architectures.size(); ++i) { +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + architectures[i].name), architectures[i].is_default)); +// } + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/app_store_team_id"), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/provisioning_profile_uuid_debug"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_debug", PROPERTY_HINT_PLACEHOLDER_TEXT, "iPhone Developer"), "iPhone Developer")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/export_method_debug", PROPERTY_HINT_ENUM, "App Store,Development,Ad-Hoc,Enterprise"), 1)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/provisioning_profile_uuid_release"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/code_sign_identity_release", PROPERTY_HINT_PLACEHOLDER_TEXT, "iPhone Distribution"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/export_method_release", PROPERTY_HINT_ENUM, "App Store,Development,Ad-Hoc,Enterprise"), 0)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/info"), "Made with Godot Engine")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/bundle_identifier", PROPERTY_HINT_PLACEHOLDER_TEXT, "com.example.game"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/signature"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/short_version"), "1.0")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/version"), "1.0")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/copyright"), "")); + +// Vector found_plugins = get_plugins(); +// for (int i = 0; i < found_plugins.size(); i++) { +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "plugins/" + found_plugins[i].name), false)); +// } +// plugins_changed = false; +// plugins = found_plugins; + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "capabilities/access_wifi"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "capabilities/push_notifications"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data/accessible_from_files_app"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data/accessible_from_itunes_sharing"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/camera_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need to use the camera"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/microphone_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need to use the microphone"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/photolibrary_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need access to the photo library"), "")); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "orientation/portrait"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "orientation/landscape_left"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "orientation/landscape_right"), true)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "orientation/portrait_upside_down"), true)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "icons/generate_missing"), false)); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/iphone_120x120", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone/iPod Touch with retina display +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/ipad_76x76", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "required_icons/app_store_1024x1024", PROPERTY_HINT_FILE, "*.png"), "")); // App Store + +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/iphone_180x180", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPhone with retina HD display +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_152x152", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad with retina display +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/ipad_167x167", PROPERTY_HINT_FILE, "*.png"), "")); // Home screen on iPad Pro +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_40x40", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "optional_icons/spotlight_80x80", PROPERTY_HINT_FILE, "*.png"), "")); // Spotlight on devices with retina display + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "storyboard/use_launch_screen_storyboard"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "storyboard/image_scale_mode", PROPERTY_HINT_ENUM, "Same as Logo,Center,Scale To Fit,Scale To Fill,Scale"), 0)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@2x", PROPERTY_HINT_FILE, "*.png"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "storyboard/custom_image@3x", PROPERTY_HINT_FILE, "*.png"), "")); +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "storyboard/use_custom_bg_color"), false)); +// r_options->push_back(ExportOption(PropertyInfo(Variant::COLOR, "storyboard/custom_bg_color"), Color())); + +// r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "launch_screens/generate_missing"), false)); + +// for (uint64_t i = 0; i < sizeof(loading_screen_infos) / sizeof(loading_screen_infos[0]); ++i) { +// r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, loading_screen_infos[i].preset_key, PROPERTY_HINT_FILE, "*.png"), "")); +// } +//} + +//void EditorExportPlatformIOS::_fix_config_file(const Ref &p_preset, Vector &pfile, const IOSConfigData &p_config, bool p_debug) { +// static const String export_method_string[] = { +// "app-store", +// "development", +// "ad-hoc", +// "enterprise" +// }; +// static const String storyboard_image_scale_mode[] = { +// "center", +// "scaleAspectFit", +// "scaleAspectFill", +// "scaleToFill" +// }; +// String str; +// String strnew; +// str.parse_utf8((const char *)pfile.ptr(), pfile.size()); +// Vector lines = str.split("\n"); +// for (int i = 0; i < lines.size(); i++) { +// if (lines[i].find("$binary") != -1) { +// strnew += lines[i].replace("$binary", p_config.binary_name) + "\n"; +// } else if (lines[i].find("$modules_buildfile") != -1) { +// strnew += lines[i].replace("$modules_buildfile", p_config.modules_buildfile) + "\n"; +// } else if (lines[i].find("$modules_fileref") != -1) { +// strnew += lines[i].replace("$modules_fileref", p_config.modules_fileref) + "\n"; +// } else if (lines[i].find("$modules_buildphase") != -1) { +// strnew += lines[i].replace("$modules_buildphase", p_config.modules_buildphase) + "\n"; +// } else if (lines[i].find("$modules_buildgrp") != -1) { +// strnew += lines[i].replace("$modules_buildgrp", p_config.modules_buildgrp) + "\n"; +// } else if (lines[i].find("$name") != -1) { +// strnew += lines[i].replace("$name", p_config.pkg_name) + "\n"; +// } else if (lines[i].find("$info") != -1) { +// strnew += lines[i].replace("$info", p_preset->get("application/info")) + "\n"; +// } else if (lines[i].find("$bundle_identifier") != -1) { +// strnew += lines[i].replace("$bundle_identifier", p_preset->get("application/bundle_identifier")) + "\n"; +// } else if (lines[i].find("$short_version") != -1) { +// strnew += lines[i].replace("$short_version", p_preset->get("application/short_version")) + "\n"; +// } else if (lines[i].find("$version") != -1) { +// strnew += lines[i].replace("$version", p_preset->get("application/version")) + "\n"; +// } else if (lines[i].find("$signature") != -1) { +// strnew += lines[i].replace("$signature", p_preset->get("application/signature")) + "\n"; +// } else if (lines[i].find("$copyright") != -1) { +// strnew += lines[i].replace("$copyright", p_preset->get("application/copyright")) + "\n"; +// } else if (lines[i].find("$team_id") != -1) { +// strnew += lines[i].replace("$team_id", p_preset->get("application/app_store_team_id")) + "\n"; +// } else if (lines[i].find("$export_method") != -1) { +// int export_method = p_preset->get(p_debug ? "application/export_method_debug" : "application/export_method_release"); +// strnew += lines[i].replace("$export_method", export_method_string[export_method]) + "\n"; +// } else if (lines[i].find("$provisioning_profile_uuid_release") != -1) { +// strnew += lines[i].replace("$provisioning_profile_uuid_release", p_preset->get("application/provisioning_profile_uuid_release")) + "\n"; +// } else if (lines[i].find("$provisioning_profile_uuid_debug") != -1) { +// strnew += lines[i].replace("$provisioning_profile_uuid_debug", p_preset->get("application/provisioning_profile_uuid_debug")) + "\n"; +// } else if (lines[i].find("$provisioning_profile_uuid") != -1) { +// String uuid = p_debug ? p_preset->get("application/provisioning_profile_uuid_debug") : p_preset->get("application/provisioning_profile_uuid_release"); +// strnew += lines[i].replace("$provisioning_profile_uuid", uuid) + "\n"; +// } else if (lines[i].find("$code_sign_identity_debug") != -1) { +// strnew += lines[i].replace("$code_sign_identity_debug", p_preset->get("application/code_sign_identity_debug")) + "\n"; +// } else if (lines[i].find("$code_sign_identity_release") != -1) { +// strnew += lines[i].replace("$code_sign_identity_release", p_preset->get("application/code_sign_identity_release")) + "\n"; +// } else if (lines[i].find("$additional_plist_content") != -1) { +// strnew += lines[i].replace("$additional_plist_content", p_config.plist_content) + "\n"; +// } else if (lines[i].find("$godot_archs") != -1) { +// strnew += lines[i].replace("$godot_archs", p_config.architectures) + "\n"; +// } else if (lines[i].find("$linker_flags") != -1) { +// strnew += lines[i].replace("$linker_flags", p_config.linker_flags) + "\n"; +// } else if (lines[i].find("$cpp_code") != -1) { +// strnew += lines[i].replace("$cpp_code", p_config.cpp_code) + "\n"; +// } else if (lines[i].find("$docs_in_place") != -1) { +// strnew += lines[i].replace("$docs_in_place", ((bool)p_preset->get("user_data/accessible_from_files_app")) ? "" : "") + "\n"; +// } else if (lines[i].find("$docs_sharing") != -1) { +// strnew += lines[i].replace("$docs_sharing", ((bool)p_preset->get("user_data/accessible_from_itunes_sharing")) ? "" : "") + "\n"; +// } else if (lines[i].find("$entitlements_push_notifications") != -1) { +// bool is_on = p_preset->get("capabilities/push_notifications"); +// strnew += lines[i].replace("$entitlements_push_notifications", is_on ? "aps-environmentdevelopment" : "") + "\n"; +// } else if (lines[i].find("$required_device_capabilities") != -1) { +// String capabilities; + +// // I've removed armv7 as we can run on 64bit only devices +// // Note that capabilities listed here are requirements for the app to be installed. +// // They don't enable anything. +// Vector capabilities_list = p_config.capabilities; + +// if ((bool)p_preset->get("capabilities/access_wifi") && !capabilities_list.has("wifi")) { +// capabilities_list.push_back("wifi"); +// } + +// for (int idx = 0; idx < capabilities_list.size(); idx++) { +// capabilities += "" + capabilities_list[idx] + "\n"; +// } + +// strnew += lines[i].replace("$required_device_capabilities", capabilities); +// } else if (lines[i].find("$interface_orientations") != -1) { +// String orientations; + +// if ((bool)p_preset->get("orientation/portrait")) { +// orientations += "UIInterfaceOrientationPortrait\n"; +// } +// if ((bool)p_preset->get("orientation/landscape_left")) { +// orientations += "UIInterfaceOrientationLandscapeLeft\n"; +// } +// if ((bool)p_preset->get("orientation/landscape_right")) { +// orientations += "UIInterfaceOrientationLandscapeRight\n"; +// } +// if ((bool)p_preset->get("orientation/portrait_upside_down")) { +// orientations += "UIInterfaceOrientationPortraitUpsideDown\n"; +// } + +// strnew += lines[i].replace("$interface_orientations", orientations); +// } else if (lines[i].find("$camera_usage_description") != -1) { +// String description = p_preset->get("privacy/camera_usage_description"); +// strnew += lines[i].replace("$camera_usage_description", description) + "\n"; +// } else if (lines[i].find("$microphone_usage_description") != -1) { +// String description = p_preset->get("privacy/microphone_usage_description"); +// strnew += lines[i].replace("$microphone_usage_description", description) + "\n"; +// } else if (lines[i].find("$photolibrary_usage_description") != -1) { +// String description = p_preset->get("privacy/photolibrary_usage_description"); +// strnew += lines[i].replace("$photolibrary_usage_description", description) + "\n"; +// } else if (lines[i].find("$plist_launch_screen_name") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "UILaunchStoryboardName\nLaunch Screen" : ""; +// strnew += lines[i].replace("$plist_launch_screen_name", value) + "\n"; +// } else if (lines[i].find("$pbx_launch_screen_file_reference") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "90DD2D9D24B36E8000717FE1 = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = \"Launch Screen.storyboard\"; sourceTree = \"\"; };" : ""; +// strnew += lines[i].replace("$pbx_launch_screen_file_reference", value) + "\n"; +// } else if (lines[i].find("$pbx_launch_screen_copy_files") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "90DD2D9D24B36E8000717FE1 /* Launch Screen.storyboard */," : ""; +// strnew += lines[i].replace("$pbx_launch_screen_copy_files", value) + "\n"; +// } else if (lines[i].find("$pbx_launch_screen_build_phase") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "90DD2D9E24B36E8000717FE1 /* Launch Screen.storyboard in Resources */," : ""; +// strnew += lines[i].replace("$pbx_launch_screen_build_phase", value) + "\n"; +// } else if (lines[i].find("$pbx_launch_screen_build_reference") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "90DD2D9E24B36E8000717FE1 /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 90DD2D9D24B36E8000717FE1 /* Launch Screen.storyboard */; };" : ""; +// strnew += lines[i].replace("$pbx_launch_screen_build_reference", value) + "\n"; +// } else if (lines[i].find("$pbx_launch_image_usage_setting") != -1) { +// bool is_on = p_preset->get("storyboard/use_launch_screen_storyboard"); +// String value = is_on ? "" : "ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;"; +// strnew += lines[i].replace("$pbx_launch_image_usage_setting", value) + "\n"; +// } else if (lines[i].find("$launch_screen_image_mode") != -1) { +// int image_scale_mode = p_preset->get("storyboard/image_scale_mode"); +// String value; + +// switch (image_scale_mode) { +// case 0: { +// String logo_path = ProjectSettings::get_singleton()->get("application/boot_splash/image"); +// bool is_on = ProjectSettings::get_singleton()->get("application/boot_splash/fullsize"); +// // If custom logo is not specified, Godot does not scale default one, so we should do the same. +// value = (is_on && logo_path.length() > 0) ? "scaleAspectFit" : "center"; +// } break; +// default: { +// value = storyboard_image_scale_mode[image_scale_mode - 1]; +// } +// } + +// strnew += lines[i].replace("$launch_screen_image_mode", value) + "\n"; +// } else if (lines[i].find("$launch_screen_background_color") != -1) { +// bool use_custom = p_preset->get("storyboard/use_custom_bg_color"); +// Color color = use_custom ? p_preset->get("storyboard/custom_bg_color") : ProjectSettings::get_singleton()->get("application/boot_splash/bg_color"); +// const String value_format = "red=\"$red\" green=\"$green\" blue=\"$blue\" alpha=\"$alpha\""; + +// Dictionary value_dictionary; +// value_dictionary["red"] = color.r; +// value_dictionary["green"] = color.g; +// value_dictionary["blue"] = color.b; +// value_dictionary["alpha"] = color.a; +// String value = value_format.format(value_dictionary, "$_"); + +// strnew += lines[i].replace("$launch_screen_background_color", value) + "\n"; +// } else { +// strnew += lines[i] + "\n"; +// } +// } + +// // !BAS! I'm assuming the 9 in the original code was a typo. I've added -1 or else it seems to also be adding our terminating zero... +// // should apply the same fix in our OSX export. +// CharString cs = strnew.utf8(); +// pfile.resize(cs.size() - 1); +// for (int i = 0; i < cs.size() - 1; i++) { +// pfile.write[i] = cs[i]; +// } +//} + +//String EditorExportPlatformIOS::_get_additional_plist_content() { +// Vector> export_plugins = EditorExport::get_singleton()->get_export_plugins(); +// String result; +// for (int i = 0; i < export_plugins.size(); ++i) { +// result += export_plugins[i]->get_ios_plist_content(); +// } +// return result; +//} + +//String EditorExportPlatformIOS::_get_linker_flags() { +// Vector> export_plugins = EditorExport::get_singleton()->get_export_plugins(); +// String result; +// for (int i = 0; i < export_plugins.size(); ++i) { +// String flags = export_plugins[i]->get_ios_linker_flags(); +// if (flags.length() == 0) { +// continue; +// } +// if (result.length() > 0) { +// result += ' '; +// } +// result += flags; +// } +// // the flags will be enclosed in quotes, so need to escape them +// return result.replace("\"", "\\\""); +//} + +//String EditorExportPlatformIOS::_get_cpp_code() { +// Vector> export_plugins = EditorExport::get_singleton()->get_export_plugins(); +// String result; +// for (int i = 0; i < export_plugins.size(); ++i) { +// result += export_plugins[i]->get_ios_cpp_code(); +// } +// return result; +//} + +//void EditorExportPlatformIOS::_blend_and_rotate(Ref &p_dst, Ref &p_src, bool p_rot) { +// ERR_FAIL_COND(p_dst.is_null()); +// ERR_FAIL_COND(p_src.is_null()); + +// int sw = p_rot ? p_src->get_height() : p_src->get_width(); +// int sh = p_rot ? p_src->get_width() : p_src->get_height(); + +// int x_pos = (p_dst->get_width() - sw) / 2; +// int y_pos = (p_dst->get_height() - sh) / 2; + +// int xs = (x_pos >= 0) ? 0 : -x_pos; +// int ys = (y_pos >= 0) ? 0 : -y_pos; + +// if (sw + x_pos > p_dst->get_width()) { +// sw = p_dst->get_width() - x_pos; +// } +// if (sh + y_pos > p_dst->get_height()) { +// sh = p_dst->get_height() - y_pos; +// } + +// for (int y = ys; y < sh; y++) { +// for (int x = xs; x < sw; x++) { +// Color sc = p_rot ? p_src->get_pixel(p_src->get_width() - y - 1, x) : p_src->get_pixel(x, y); +// Color dc = p_dst->get_pixel(x_pos + x, y_pos + y); +// dc.r = (double)(sc.a * sc.r + dc.a * (1.0 - sc.a) * dc.r); +// dc.g = (double)(sc.a * sc.g + dc.a * (1.0 - sc.a) * dc.g); +// dc.b = (double)(sc.a * sc.b + dc.a * (1.0 - sc.a) * dc.b); +// dc.a = (double)(sc.a + dc.a * (1.0 - sc.a)); +// p_dst->set_pixel(x_pos + x, y_pos + y, dc); +// } +// } +//} + +//struct IconInfo { +// const char *preset_key; +// const char *idiom; +// const char *export_name; +// const char *actual_size_side; +// const char *scale; +// const char *unscaled_size; +// bool is_required = false; +//}; + +//static const IconInfo icon_infos[] = { +// { "required_icons/iphone_120x120", "iphone", "Icon-120.png", "120", "2x", "60x60", true }, +// { "required_icons/iphone_120x120", "iphone", "Icon-120.png", "120", "3x", "40x40", true }, + +// { "required_icons/ipad_76x76", "ipad", "Icon-76.png", "76", "1x", "76x76", true }, +// { "required_icons/app_store_1024x1024", "ios-marketing", "Icon-1024.png", "1024", "1x", "1024x1024", true }, + +// { "optional_icons/iphone_180x180", "iphone", "Icon-180.png", "180", "3x", "60x60", false }, + +// { "optional_icons/ipad_152x152", "ipad", "Icon-152.png", "152", "2x", "76x76", false }, + +// { "optional_icons/ipad_167x167", "ipad", "Icon-167.png", "167", "2x", "83.5x83.5", false }, + +// { "optional_icons/spotlight_40x40", "ipad", "Icon-40.png", "40", "1x", "40x40", false }, + +// { "optional_icons/spotlight_80x80", "iphone", "Icon-80.png", "80", "2x", "40x40", false }, +// { "optional_icons/spotlight_80x80", "ipad", "Icon-80.png", "80", "2x", "40x40", false } +//}; + +//Error EditorExportPlatformIOS::_export_icons(const Ref &p_preset, const String &p_iconset_dir) { +// String json_description = "{\"images\":["; +// String sizes; + +// DirAccess *da = DirAccess::open(p_iconset_dir); +// ERR_FAIL_COND_V_MSG(!da, ERR_CANT_OPEN, "Cannot open directory '" + p_iconset_dir + "'."); + +// for (uint64_t i = 0; i < (sizeof(icon_infos) / sizeof(icon_infos[0])); ++i) { +// IconInfo info = icon_infos[i]; +// int side_size = String(info.actual_size_side).to_int(); +// String icon_path = p_preset->get(info.preset_key); +// if (icon_path.length() == 0) { +// if ((bool)p_preset->get("icons/generate_missing")) { +// // Resize main app icon +// icon_path = ProjectSettings::get_singleton()->get("application/config/icon"); +// Ref img = memnew(Image); +// Error err = ImageLoader::load_image(icon_path, img); +// if (err != OK) { +// ERR_PRINT("Invalid icon (" + String(info.preset_key) + "): '" + icon_path + "'."); +// return ERR_UNCONFIGURED; +// } +// img->resize(side_size, side_size); +// err = img->save_png(p_iconset_dir + info.export_name); +// if (err) { +// String err_str = String("Failed to export icon(" + String(info.preset_key) + "): '" + icon_path + "'."); +// ERR_PRINT(err_str.utf8().get_data()); +// return err; +// } +// } else { +// if (info.is_required) { +// String err_str = String("Required icon (") + info.preset_key + ") is not specified in the preset."; +// ERR_PRINT(err_str); +// return ERR_UNCONFIGURED; +// } else { +// String err_str = String("Icon (") + info.preset_key + ") is not specified in the preset."; +// WARN_PRINT(err_str); +// } +// continue; +// } +// } else { +// // Load custom icon +// Ref img = memnew(Image); +// Error err = ImageLoader::load_image(icon_path, img); +// if (err != OK) { +// ERR_PRINT("Invalid icon (" + String(info.preset_key) + "): '" + icon_path + "'."); +// return ERR_UNCONFIGURED; +// } +// if (img->get_width() != side_size || img->get_height() != side_size) { +// ERR_PRINT("Invalid icon size (" + String(info.preset_key) + "): '" + icon_path + "'."); +// return ERR_UNCONFIGURED; +// } + +// err = da->copy(icon_path, p_iconset_dir + info.export_name); +// if (err) { +// memdelete(da); +// String err_str = String("Failed to export icon(" + String(info.preset_key) + "): '" + icon_path + "'."); +// ERR_PRINT(err_str.utf8().get_data()); +// return err; +// } +// } +// sizes += String(info.actual_size_side) + "\n"; +// if (i > 0) { +// json_description += ","; +// } +// json_description += String("{"); +// json_description += String("\"idiom\":") + "\"" + info.idiom + "\","; +// json_description += String("\"size\":") + "\"" + info.unscaled_size + "\","; +// json_description += String("\"scale\":") + "\"" + info.scale + "\","; +// json_description += String("\"filename\":") + "\"" + info.export_name + "\""; +// json_description += String("}"); +// } +// json_description += "]}"; +// memdelete(da); + +// FileAccess *json_file = FileAccess::open(p_iconset_dir + "Contents.json", FileAccess::WRITE); +// ERR_FAIL_COND_V(!json_file, ERR_CANT_CREATE); +// CharString json_utf8 = json_description.utf8(); +// json_file->store_buffer((const uint8_t *)json_utf8.get_data(), json_utf8.length()); +// memdelete(json_file); + +// FileAccess *sizes_file = FileAccess::open(p_iconset_dir + "sizes", FileAccess::WRITE); +// ERR_FAIL_COND_V(!sizes_file, ERR_CANT_CREATE); +// CharString sizes_utf8 = sizes.utf8(); +// sizes_file->store_buffer((const uint8_t *)sizes_utf8.get_data(), sizes_utf8.length()); +// memdelete(sizes_file); + +// return OK; +//} + +//Error EditorExportPlatformIOS::_export_loading_screen_file(const Ref &p_preset, const String &p_dest_dir) { +// const String custom_launch_image_2x = p_preset->get("storyboard/custom_image@2x"); +// const String custom_launch_image_3x = p_preset->get("storyboard/custom_image@3x"); + +// if (custom_launch_image_2x.length() > 0 && custom_launch_image_3x.length() > 0) { +// Ref image; +// String image_path = p_dest_dir.plus_file("splash@2x.png"); +// image.instance(); +// Error err = image->load(custom_launch_image_2x); + +// if (err) { +// image.unref(); +// return err; +// } + +// if (image->save_png(image_path) != OK) { +// return ERR_FILE_CANT_WRITE; +// } + +// image.unref(); +// image_path = p_dest_dir.plus_file("splash@3x.png"); +// image.instance(); +// err = image->load(custom_launch_image_3x); + +// if (err) { +// image.unref(); +// return err; +// } + +// if (image->save_png(image_path) != OK) { +// return ERR_FILE_CANT_WRITE; +// } +// } else { +// Ref splash; + +// const String splash_path = ProjectSettings::get_singleton()->get("application/boot_splash/image"); + +// if (!splash_path.is_empty()) { +// splash.instance(); +// const Error err = splash->load(splash_path); +// if (err) { +// splash.unref(); +// } +// } + +// if (splash.is_null()) { +// splash = Ref(memnew(Image(boot_splash_png))); +// } + +// // Using same image for both @2x and @3x +// // because Godot's own boot logo uses single image for all resolutions. +// // Also not using @1x image, because devices using this image variant +// // are not supported by iOS 9, which is minimal target. +// const String splash_png_path_2x = p_dest_dir.plus_file("splash@2x.png"); +// const String splash_png_path_3x = p_dest_dir.plus_file("splash@3x.png"); + +// if (splash->save_png(splash_png_path_2x) != OK) { +// return ERR_FILE_CANT_WRITE; +// } + +// if (splash->save_png(splash_png_path_3x) != OK) { +// return ERR_FILE_CANT_WRITE; +// } +// } + +// return OK; +//} + +//Error EditorExportPlatformIOS::_export_loading_screen_images(const Ref &p_preset, const String &p_dest_dir) { +// DirAccess *da = DirAccess::open(p_dest_dir); +// ERR_FAIL_COND_V_MSG(!da, ERR_CANT_OPEN, "Cannot open directory '" + p_dest_dir + "'."); + +// for (uint64_t i = 0; i < sizeof(loading_screen_infos) / sizeof(loading_screen_infos[0]); ++i) { +// LoadingScreenInfo info = loading_screen_infos[i]; +// String loading_screen_file = p_preset->get(info.preset_key); +// if (loading_screen_file.size() > 0) { +// // Load custom loading screens +// Ref img = memnew(Image); +// Error err = ImageLoader::load_image(loading_screen_file, img); +// if (err != OK) { +// ERR_PRINT("Invalid loading screen (" + String(info.preset_key) + "): '" + loading_screen_file + "'."); +// return ERR_UNCONFIGURED; +// } +// if (img->get_width() != info.width || img->get_height() != info.height) { +// ERR_PRINT("Invalid loading screen size (" + String(info.preset_key) + "): '" + loading_screen_file + "'."); +// return ERR_UNCONFIGURED; +// } +// err = da->copy(loading_screen_file, p_dest_dir + info.export_name); +// if (err) { +// memdelete(da); +// String err_str = String("Failed to export loading screen (") + info.preset_key + ") from path '" + loading_screen_file + "'."; +// ERR_PRINT(err_str.utf8().get_data()); +// return err; +// } +// } else if ((bool)p_preset->get("launch_screens/generate_missing")) { +// // Generate loading screen from the splash screen +// Color boot_bg_color = ProjectSettings::get_singleton()->get("application/boot_splash/bg_color"); +// String boot_logo_path = ProjectSettings::get_singleton()->get("application/boot_splash/image"); +// bool boot_logo_scale = ProjectSettings::get_singleton()->get("application/boot_splash/fullsize"); + +// Ref img = memnew(Image); +// img->create(info.width, info.height, false, Image::FORMAT_RGBA8); +// img->fill(boot_bg_color); + +// Ref img_bs; + +// if (boot_logo_path.length() > 0) { +// img_bs = Ref(memnew(Image)); +// ImageLoader::load_image(boot_logo_path, img_bs); +// } +// if (!img_bs.is_valid()) { +// img_bs = Ref(memnew(Image(boot_splash_png))); +// } +// if (img_bs.is_valid()) { +// float aspect_ratio = (float)img_bs->get_width() / (float)img_bs->get_height(); +// if (info.rotate) { +// if (boot_logo_scale) { +// if (info.width * aspect_ratio <= info.height) { +// img_bs->resize(info.width * aspect_ratio, info.width); +// } else { +// img_bs->resize(info.height, info.height / aspect_ratio); +// } +// } +// } else { +// if (boot_logo_scale) { +// if (info.height * aspect_ratio <= info.width) { +// img_bs->resize(info.height * aspect_ratio, info.height); +// } else { +// img_bs->resize(info.width, info.width / aspect_ratio); +// } +// } +// } +// _blend_and_rotate(img, img_bs, info.rotate); +// } +// Error err = img->save_png(p_dest_dir + info.export_name); +// if (err) { +// String err_str = String("Failed to export loading screen (") + info.preset_key + ") from splash screen."; +// WARN_PRINT(err_str.utf8().get_data()); +// } +// } else { +// String err_str = String("No loading screen (") + info.preset_key + ") specified."; +// WARN_PRINT(err_str.utf8().get_data()); +// } +// } +// memdelete(da); + +// return OK; +//} + +//Error EditorExportPlatformIOS::_walk_dir_recursive(DirAccess *p_da, FileHandler p_handler, void *p_userdata) { +// Vector dirs; +// String path; +// String current_dir = p_da->get_current_dir(); +// p_da->list_dir_begin(); +// while ((path = p_da->get_next()).length() != 0) { +// if (p_da->current_is_dir()) { +// if (path != "." && path != "..") { +// dirs.push_back(path); +// } +// } else { +// Error err = p_handler(current_dir.plus_file(path), p_userdata); +// if (err) { +// p_da->list_dir_end(); +// return err; +// } +// } +// } +// p_da->list_dir_end(); + +// for (int i = 0; i < dirs.size(); ++i) { +// String dir = dirs[i]; +// p_da->change_dir(dir); +// Error err = _walk_dir_recursive(p_da, p_handler, p_userdata); +// p_da->change_dir(".."); +// if (err) { +// return err; +// } +// } + +// return OK; +//} + +//struct CodesignData { +// const Ref &preset; +// bool debug = false; + +// CodesignData(const Ref &p_preset, bool p_debug) : +// preset(p_preset), +// debug(p_debug) { +// } +//}; + +//Error EditorExportPlatformIOS::_codesign(String p_file, void *p_userdata) { +// if (p_file.ends_with(".dylib")) { +// CodesignData *data = (CodesignData *)p_userdata; +// print_line(String("Signing ") + p_file); +// List codesign_args; +// codesign_args.push_back("-f"); +// codesign_args.push_back("-s"); +// codesign_args.push_back(data->preset->get(data->debug ? "application/code_sign_identity_debug" : "application/code_sign_identity_release")); +// codesign_args.push_back(p_file); +// return OS::get_singleton()->execute("codesign", codesign_args, true); +// } +// return OK; +//} + +//struct PbxId { +//private: +// static char _hex_char(uint8_t four_bits) { +// if (four_bits < 10) { +// return ('0' + four_bits); +// } +// return 'A' + (four_bits - 10); +// } + +// static String _hex_pad(uint32_t num) { +// Vector ret; +// ret.resize(sizeof(num) * 2); +// for (uint64_t i = 0; i < sizeof(num) * 2; ++i) { +// uint8_t four_bits = (num >> (sizeof(num) * 8 - (i + 1) * 4)) & 0xF; +// ret.write[i] = _hex_char(four_bits); +// } +// return String::utf8(ret.ptr(), ret.size()); +// } + +//public: +// uint32_t high_bits; +// uint32_t mid_bits; +// uint32_t low_bits; + +// String str() const { +// return _hex_pad(high_bits) + _hex_pad(mid_bits) + _hex_pad(low_bits); +// } + +// PbxId &operator++() { +// low_bits++; +// if (!low_bits) { +// mid_bits++; +// if (!mid_bits) { +// high_bits++; +// } +// } + +// return *this; +// } +//}; + +//struct ExportLibsData { +// Vector lib_paths; +// String dest_dir; +//}; + +//void EditorExportPlatformIOS::_add_assets_to_project(const Ref &p_preset, Vector &p_project_data, const Vector &p_additional_assets) { +// // that is just a random number, we just need Godot IDs not to clash with +// // existing IDs in the project. +// PbxId current_id = { 0x58938401, 0, 0 }; +// String pbx_files; +// String pbx_frameworks_build; +// String pbx_frameworks_refs; +// String pbx_resources_build; +// String pbx_resources_refs; +// String pbx_embeded_frameworks; + +// const String file_info_format = String("$build_id = {isa = PBXBuildFile; fileRef = $ref_id; };\n") + +// "$ref_id = {isa = PBXFileReference; lastKnownFileType = $file_type; name = \"$name\"; path = \"$file_path\"; sourceTree = \"\"; };\n"; + +// for (int i = 0; i < p_additional_assets.size(); ++i) { +// String additional_asset_info_format = file_info_format; + +// String build_id = (++current_id).str(); +// String ref_id = (++current_id).str(); +// String framework_id = ""; + +// const IOSExportAsset &asset = p_additional_assets[i]; + +// String type; +// if (asset.exported_path.ends_with(".framework")) { +// if (asset.should_embed) { +// additional_asset_info_format += "$framework_id = {isa = PBXBuildFile; fileRef = $ref_id; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };\n"; +// framework_id = (++current_id).str(); +// pbx_embeded_frameworks += framework_id + ",\n"; +// } + +// type = "wrapper.framework"; +// } else if (asset.exported_path.ends_with(".xcframework")) { +// if (asset.should_embed) { +// additional_asset_info_format += "$framework_id = {isa = PBXBuildFile; fileRef = $ref_id; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };\n"; +// framework_id = (++current_id).str(); +// pbx_embeded_frameworks += framework_id + ",\n"; +// } + +// type = "wrapper.xcframework"; +// } else if (asset.exported_path.ends_with(".dylib")) { +// type = "compiled.mach-o.dylib"; +// } else if (asset.exported_path.ends_with(".a")) { +// type = "archive.ar"; +// } else { +// type = "file"; +// } + +// String &pbx_build = asset.is_framework ? pbx_frameworks_build : pbx_resources_build; +// String &pbx_refs = asset.is_framework ? pbx_frameworks_refs : pbx_resources_refs; + +// if (pbx_build.length() > 0) { +// pbx_build += ",\n"; +// pbx_refs += ",\n"; +// } +// pbx_build += build_id; +// pbx_refs += ref_id; + +// Dictionary format_dict; +// format_dict["build_id"] = build_id; +// format_dict["ref_id"] = ref_id; +// format_dict["name"] = asset.exported_path.get_file(); +// format_dict["file_path"] = asset.exported_path; +// format_dict["file_type"] = type; +// if (framework_id.length() > 0) { +// format_dict["framework_id"] = framework_id; +// } +// pbx_files += additional_asset_info_format.format(format_dict, "$_"); +// } + +// // Note, frameworks like gamekit are always included in our project.pbxprof file +// // even if turned off in capabilities. + +// String str = String::utf8((const char *)p_project_data.ptr(), p_project_data.size()); +// str = str.replace("$additional_pbx_files", pbx_files); +// str = str.replace("$additional_pbx_frameworks_build", pbx_frameworks_build); +// str = str.replace("$additional_pbx_frameworks_refs", pbx_frameworks_refs); +// str = str.replace("$additional_pbx_resources_build", pbx_resources_build); +// str = str.replace("$additional_pbx_resources_refs", pbx_resources_refs); +// str = str.replace("$pbx_embeded_frameworks", pbx_embeded_frameworks); + +// CharString cs = str.utf8(); +// p_project_data.resize(cs.size() - 1); +// for (int i = 0; i < cs.size() - 1; i++) { +// p_project_data.write[i] = cs[i]; +// } +//} + +//Error EditorExportPlatformIOS::_copy_asset(const String &p_out_dir, const String &p_asset, const String *p_custom_file_name, bool p_is_framework, bool p_should_embed, Vector &r_exported_assets) { +// DirAccess *filesystem_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); +// ERR_FAIL_COND_V_MSG(!filesystem_da, ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_out_dir + "'."); + +// String binary_name = p_out_dir.get_file().get_basename(); + +// DirAccess *da = DirAccess::create_for_path(p_asset); +// if (!da) { +// memdelete(filesystem_da); +// ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Can't create directory: " + p_asset + "."); +// } +// bool file_exists = da->file_exists(p_asset); +// bool dir_exists = da->dir_exists(p_asset); +// if (!file_exists && !dir_exists) { +// memdelete(da); +// memdelete(filesystem_da); +// return ERR_FILE_NOT_FOUND; +// } + +// String base_dir = p_asset.get_base_dir().replace("res://", ""); +// String destination_dir; +// String destination; +// String asset_path; + +// bool create_framework = false; + +// if (p_is_framework && p_asset.ends_with(".dylib")) { +// // For iOS we need to turn .dylib into .framework +// // to be able to send application to AppStore +// asset_path = String("dylibs").plus_file(base_dir); + +// String file_name; + +// if (!p_custom_file_name) { +// file_name = p_asset.get_basename().get_file(); +// } else { +// file_name = *p_custom_file_name; +// } + +// String framework_name = file_name + ".framework"; + +// asset_path = asset_path.plus_file(framework_name); +// destination_dir = p_out_dir.plus_file(asset_path); +// destination = destination_dir.plus_file(file_name); +// create_framework = true; +// } else if (p_is_framework && (p_asset.ends_with(".framework") || p_asset.ends_with(".xcframework"))) { +// asset_path = String("dylibs").plus_file(base_dir); + +// String file_name; + +// if (!p_custom_file_name) { +// file_name = p_asset.get_file(); +// } else { +// file_name = *p_custom_file_name; +// } + +// asset_path = asset_path.plus_file(file_name); +// destination_dir = p_out_dir.plus_file(asset_path); +// destination = destination_dir; +// } else { +// asset_path = base_dir; + +// String file_name; + +// if (!p_custom_file_name) { +// file_name = p_asset.get_file(); +// } else { +// file_name = *p_custom_file_name; +// } + +// destination_dir = p_out_dir.plus_file(asset_path); +// asset_path = asset_path.plus_file(file_name); +// destination = p_out_dir.plus_file(asset_path); +// } + +// if (!filesystem_da->dir_exists(destination_dir)) { +// Error make_dir_err = filesystem_da->make_dir_recursive(destination_dir); +// if (make_dir_err) { +// memdelete(da); +// memdelete(filesystem_da); +// return make_dir_err; +// } +// } + +// Error err = dir_exists ? da->copy_dir(p_asset, destination) : da->copy(p_asset, destination); +// memdelete(da); +// if (err) { +// memdelete(filesystem_da); +// return err; +// } +// IOSExportAsset exported_asset = { binary_name.plus_file(asset_path), p_is_framework, p_should_embed }; +// r_exported_assets.push_back(exported_asset); + +// if (create_framework) { +// String file_name; + +// if (!p_custom_file_name) { +// file_name = p_asset.get_basename().get_file(); +// } else { +// file_name = *p_custom_file_name; +// } + +// String framework_name = file_name + ".framework"; + +// // Performing `install_name_tool -id @rpath/{name}.framework/{name} ./{name}` on dylib +// { +// List install_name_args; +// install_name_args.push_back("-id"); +// install_name_args.push_back(String("@rpath").plus_file(framework_name).plus_file(file_name)); +// install_name_args.push_back(destination); + +// OS::get_singleton()->execute("install_name_tool", install_name_args, true); +// } + +// // Creating Info.plist +// { +// String info_plist_format = "\n" +// "\n" +// "\n" +// "\n" +// "CFBundleShortVersionString\n" +// "1.0\n" +// "CFBundleIdentifier\n" +// "com.gdnative.framework.$name\n" +// "CFBundleName\n" +// "$name\n" +// "CFBundleExecutable\n" +// "$name\n" +// "DTPlatformName\n" +// "iphoneos\n" +// "CFBundleInfoDictionaryVersion\n" +// "6.0\n" +// "CFBundleVersion\n" +// "1\n" +// "CFBundlePackageType\n" +// "FMWK\n" +// "MinimumOSVersion\n" +// "10.0\n" +// "\n" +// ""; + +// String info_plist = info_plist_format.replace("$name", file_name); + +// FileAccess *f = FileAccess::open(destination_dir.plus_file("Info.plist"), FileAccess::WRITE); +// if (f) { +// f->store_string(info_plist); +// f->close(); +// memdelete(f); +// } +// } +// } + +// memdelete(filesystem_da); + +// return OK; +//} + +//Error EditorExportPlatformIOS::_export_additional_assets(const String &p_out_dir, const Vector &p_assets, bool p_is_framework, bool p_should_embed, Vector &r_exported_assets) { +// for (int f_idx = 0; f_idx < p_assets.size(); ++f_idx) { +// String asset = p_assets[f_idx]; +// if (!asset.begins_with("res://")) { +// // either SDK-builtin or already a part of the export template +// IOSExportAsset exported_asset = { asset, p_is_framework, p_should_embed }; +// r_exported_assets.push_back(exported_asset); +// } else { +// Error err = _copy_asset(p_out_dir, asset, nullptr, p_is_framework, p_should_embed, r_exported_assets); +// ERR_FAIL_COND_V(err, err); +// } +// } + +// return OK; +//} + +//Error EditorExportPlatformIOS::_export_additional_assets(const String &p_out_dir, const Vector &p_libraries, Vector &r_exported_assets) { +// Vector> export_plugins = EditorExport::get_singleton()->get_export_plugins(); +// for (int i = 0; i < export_plugins.size(); i++) { +// Vector linked_frameworks = export_plugins[i]->get_ios_frameworks(); +// Error err = _export_additional_assets(p_out_dir, linked_frameworks, true, false, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// Vector embedded_frameworks = export_plugins[i]->get_ios_embedded_frameworks(); +// err = _export_additional_assets(p_out_dir, embedded_frameworks, true, true, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// Vector project_static_libs = export_plugins[i]->get_ios_project_static_libs(); +// for (int j = 0; j < project_static_libs.size(); j++) { +// project_static_libs.write[j] = project_static_libs[j].get_file(); // Only the file name as it's copied to the project +// } +// err = _export_additional_assets(p_out_dir, project_static_libs, true, true, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// Vector ios_bundle_files = export_plugins[i]->get_ios_bundle_files(); +// err = _export_additional_assets(p_out_dir, ios_bundle_files, false, false, r_exported_assets); +// ERR_FAIL_COND_V(err, err); +// } + +// Vector library_paths; +// for (int i = 0; i < p_libraries.size(); ++i) { +// library_paths.push_back(p_libraries[i].path); +// } +// Error err = _export_additional_assets(p_out_dir, library_paths, true, true, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// return OK; +//} + +//Vector EditorExportPlatformIOS::_get_preset_architectures(const Ref &p_preset) { +// Vector all_archs = _get_supported_architectures(); +// Vector enabled_archs; +// for (int i = 0; i < all_archs.size(); ++i) { +// bool is_enabled = p_preset->get("architectures/" + all_archs[i].name); +// if (is_enabled) { +// enabled_archs.push_back(all_archs[i].name); +// } +// } +// return enabled_archs; +//} + +//Error EditorExportPlatformIOS::_export_ios_plugins(const Ref &p_preset, IOSConfigData &p_config_data, const String &dest_dir, Vector &r_exported_assets, bool p_debug) { +// String plugin_definition_cpp_code; +// String plugin_initialization_cpp_code; +// String plugin_deinitialization_cpp_code; + +// Vector plugin_linked_dependencies; +// Vector plugin_embedded_dependencies; +// Vector plugin_files; + +// Vector enabled_plugins = get_enabled_plugins(p_preset); + +// Vector added_linked_dependenciy_names; +// Vector added_embedded_dependenciy_names; +// HashMap plist_values; + +// Error err; + +// for (int i = 0; i < enabled_plugins.size(); i++) { +// PluginConfig plugin = enabled_plugins[i]; + +// // Export plugin binary. +// if (!plugin.supports_targets) { +// err = _copy_asset(dest_dir, plugin.binary, nullptr, true, true, r_exported_assets); +// } else { +// String plugin_binary_dir = plugin.binary.get_base_dir(); +// String plugin_name_prefix = plugin.binary.get_basename().get_file(); +// String plugin_file = plugin_name_prefix + "." + (p_debug ? "debug" : "release") + ".a"; +// String result_file_name = plugin.binary.get_file(); + +// err = _copy_asset(dest_dir, plugin_binary_dir.plus_file(plugin_file), &result_file_name, true, true, r_exported_assets); +// } + +// ERR_FAIL_COND_V(err, err); + +// // Adding dependencies. +// // Use separate container for names to check for duplicates. +// for (int j = 0; j < plugin.linked_dependencies.size(); j++) { +// String dependency = plugin.linked_dependencies[j]; +// String name = dependency.get_file(); + +// if (added_linked_dependenciy_names.has(name)) { +// continue; +// } + +// added_linked_dependenciy_names.push_back(name); +// plugin_linked_dependencies.push_back(dependency); +// } + +// for (int j = 0; j < plugin.system_dependencies.size(); j++) { +// String dependency = plugin.system_dependencies[j]; +// String name = dependency.get_file(); + +// if (added_linked_dependenciy_names.has(name)) { +// continue; +// } + +// added_linked_dependenciy_names.push_back(name); +// plugin_linked_dependencies.push_back(dependency); +// } + +// for (int j = 0; j < plugin.embedded_dependencies.size(); j++) { +// String dependency = plugin.embedded_dependencies[j]; +// String name = dependency.get_file(); + +// if (added_embedded_dependenciy_names.has(name)) { +// continue; +// } + +// added_embedded_dependenciy_names.push_back(name); +// plugin_embedded_dependencies.push_back(dependency); +// } + +// plugin_files.append_array(plugin.files_to_copy); + +// // Capabilities +// // Also checking for duplicates. +// for (int j = 0; j < plugin.capabilities.size(); j++) { +// String capability = plugin.capabilities[j]; + +// if (p_config_data.capabilities.has(capability)) { +// continue; +// } + +// p_config_data.capabilities.push_back(capability); +// } + +// // Plist +// // Using hash map container to remove duplicates +// const String *K = nullptr; + +// while ((K = plugin.plist.next(K))) { +// String key = *K; +// String value = plugin.plist[key]; + +// if (key.is_empty() || value.is_empty()) { +// continue; +// } + +// plist_values[key] = value; +// } + +// // CPP Code +// String definition_comment = "// Plugin: " + plugin.name + "\n"; +// String initialization_method = plugin.initialization_method + "();\n"; +// String deinitialization_method = plugin.deinitialization_method + "();\n"; + +// plugin_definition_cpp_code += definition_comment + +// "extern void " + initialization_method + +// "extern void " + deinitialization_method + "\n"; + +// plugin_initialization_cpp_code += "\t" + initialization_method; +// plugin_deinitialization_cpp_code += "\t" + deinitialization_method; +// } + +// // Updating `Info.plist` +// { +// const String *K = nullptr; +// while ((K = plist_values.next(K))) { +// String key = *K; +// String value = plist_values[key]; + +// if (key.is_empty() || value.is_empty()) { +// continue; +// } + +// p_config_data.plist_content += "" + key + "" + value + "\n"; +// } +// } + +// // Export files +// { +// // Export linked plugin dependency +// err = _export_additional_assets(dest_dir, plugin_linked_dependencies, true, false, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// // Export embedded plugin dependency +// err = _export_additional_assets(dest_dir, plugin_embedded_dependencies, true, true, r_exported_assets); +// ERR_FAIL_COND_V(err, err); + +// // Export plugin files +// err = _export_additional_assets(dest_dir, plugin_files, false, false, r_exported_assets); +// ERR_FAIL_COND_V(err, err); +// } + +// // Update CPP +// { +// Dictionary plugin_format; +// plugin_format["definition"] = plugin_definition_cpp_code; +// plugin_format["initialization"] = plugin_initialization_cpp_code; +// plugin_format["deinitialization"] = plugin_deinitialization_cpp_code; + +// String plugin_cpp_code = "\n// Godot Plugins\n" +// "void godot_ios_plugins_initialize();\n" +// "void godot_ios_plugins_deinitialize();\n" +// "// Exported Plugins\n\n" +// "$definition" +// "// Use Plugins\n" +// "void godot_ios_plugins_initialize() {\n" +// "$initialization" +// "}\n\n" +// "void godot_ios_plugins_deinitialize() {\n" +// "$deinitialization" +// "}\n"; + +// p_config_data.cpp_code += plugin_cpp_code.format(plugin_format, "$_"); +// } +// return OK; +//} + +//Error EditorExportPlatformIOS::export_project(const Ref &p_preset, bool p_debug, const String &p_path, int p_flags) { +// ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags); + +// String src_pkg_name; +// String dest_dir = p_path.get_base_dir() + "/"; +// String binary_name = p_path.get_file().get_basename(); + +// EditorProgress ep("export", "Exporting for iOS", 5, true); + +// String team_id = p_preset->get("application/app_store_team_id"); +// ERR_FAIL_COND_V_MSG(team_id.length() == 0, ERR_CANT_OPEN, "App Store Team ID not specified - cannot configure the project."); + +// if (p_debug) { +// src_pkg_name = p_preset->get("custom_template/debug"); +// } else { +// src_pkg_name = p_preset->get("custom_template/release"); +// } + +// if (src_pkg_name == "") { +// String err; +// src_pkg_name = find_export_template("iphone.zip", &err); +// if (src_pkg_name == "") { +// EditorNode::add_io_error(err); +// return ERR_FILE_NOT_FOUND; +// } +// } + +// if (!DirAccess::exists(dest_dir)) { +// return ERR_FILE_BAD_PATH; +// } + +// DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); +// if (da) { +// String current_dir = da->get_current_dir(); + +// // remove leftovers from last export so they don't interfere +// // in case some files are no longer needed +// if (da->change_dir(dest_dir + binary_name + ".xcodeproj") == OK) { +// da->erase_contents_recursive(); +// } +// if (da->change_dir(dest_dir + binary_name) == OK) { +// da->erase_contents_recursive(); +// } + +// da->change_dir(current_dir); + +// if (!da->dir_exists(dest_dir + binary_name)) { +// Error err = da->make_dir(dest_dir + binary_name); +// if (err) { +// memdelete(da); +// return err; +// } +// } +// memdelete(da); +// } + +// if (ep.step("Making .pck", 0)) { +// return ERR_SKIP; +// } +// String pack_path = dest_dir + binary_name + ".pck"; +// Vector libraries; +// Error err = save_pack(p_preset, pack_path, &libraries); +// if (err) { +// return err; +// } + +// if (ep.step("Extracting and configuring Xcode project", 1)) { +// return ERR_SKIP; +// } + +// String library_to_use = "libgodot.iphone." + String(p_debug ? "debug" : "release") + ".fat.a"; + +// print_line("Static library: " + library_to_use); +// String pkg_name; +// if (p_preset->get("application/name") != "") { +// pkg_name = p_preset->get("application/name"); // app_name +// } else if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "") { +// pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name")); +// } else { +// pkg_name = "Unnamed"; +// } + +// bool found_library = false; +// int total_size = 0; + +// const String project_file = "godot_ios.xcodeproj/project.pbxproj"; +// Set files_to_parse; +// files_to_parse.insert("godot_ios/godot_ios-Info.plist"); +// files_to_parse.insert(project_file); +// files_to_parse.insert("godot_ios/export_options.plist"); +// files_to_parse.insert("godot_ios/dummy.cpp"); +// files_to_parse.insert("godot_ios.xcodeproj/project.xcworkspace/contents.xcworkspacedata"); +// files_to_parse.insert("godot_ios.xcodeproj/xcshareddata/xcschemes/godot_ios.xcscheme"); +// files_to_parse.insert("godot_ios/godot_ios.entitlements"); +// files_to_parse.insert("godot_ios/Launch Screen.storyboard"); + +// IOSConfigData config_data = { +// pkg_name, +// binary_name, +// _get_additional_plist_content(), +// String(" ").join(_get_preset_architectures(p_preset)), +// _get_linker_flags(), +// _get_cpp_code(), +// "", +// "", +// "", +// "", +// Vector() +// }; + +// Vector assets; + +// DirAccess *tmp_app_path = DirAccess::create_for_path(dest_dir); +// ERR_FAIL_COND_V(!tmp_app_path, ERR_CANT_CREATE); + +// print_line("Unzipping..."); +// FileAccess *src_f = nullptr; +// zlib_filefunc_def io = zipio_create_io_from_file(&src_f); +// unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io); +// if (!src_pkg_zip) { +// EditorNode::add_io_error("Could not open export template (not a zip file?):\n" + src_pkg_name); +// return ERR_CANT_OPEN; +// } + +// err = _export_ios_plugins(p_preset, config_data, dest_dir + binary_name, assets, p_debug); +// ERR_FAIL_COND_V(err, err); + +// //export rest of the files +// int ret = unzGoToFirstFile(src_pkg_zip); +// Vector project_file_data; +// while (ret == UNZ_OK) { +//#if defined(OSX_ENABLED) || defined(X11_ENABLED) +// bool is_execute = false; +//#endif + +// //get filename +// unz_file_info info; +// char fname[16384]; +// ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, nullptr, 0, nullptr, 0); + +// String file = fname; + +// print_line("READ: " + file); +// Vector data; +// data.resize(info.uncompressed_size); + +// //read +// unzOpenCurrentFile(src_pkg_zip); +// unzReadCurrentFile(src_pkg_zip, data.ptrw(), data.size()); +// unzCloseCurrentFile(src_pkg_zip); + +// //write + +// file = file.replace_first("iphone/", ""); + +// if (files_to_parse.has(file)) { +// _fix_config_file(p_preset, data, config_data, p_debug); +// } else if (file.begins_with("libgodot.iphone")) { +// if (file != library_to_use) { +// ret = unzGoToNextFile(src_pkg_zip); +// continue; //ignore! +// } +// found_library = true; +//#if defined(OSX_ENABLED) || defined(X11_ENABLED) +// is_execute = true; +//#endif +// file = "godot_ios.a"; +// } + +// if (file == project_file) { +// project_file_data = data; +// } + +// ///@TODO need to parse logo files + +// if (data.size() > 0) { +// file = file.replace("godot_ios", binary_name); + +// print_line("ADDING: " + file + " size: " + itos(data.size())); +// total_size += data.size(); + +// /* write it into our folder structure */ +// file = dest_dir + file; + +// /* make sure this folder exists */ +// String dir_name = file.get_base_dir(); +// if (!tmp_app_path->dir_exists(dir_name)) { +// print_line("Creating " + dir_name); +// Error dir_err = tmp_app_path->make_dir_recursive(dir_name); +// if (dir_err) { +// ERR_PRINT("Can't create '" + dir_name + "'."); +// unzClose(src_pkg_zip); +// memdelete(tmp_app_path); +// return ERR_CANT_CREATE; +// } +// } + +// /* write the file */ +// FileAccess *f = FileAccess::open(file, FileAccess::WRITE); +// if (!f) { +// ERR_PRINT("Can't write '" + file + "'."); +// unzClose(src_pkg_zip); +// memdelete(tmp_app_path); +// return ERR_CANT_CREATE; +// }; +// f->store_buffer(data.ptr(), data.size()); +// f->close(); +// memdelete(f); + +//#if defined(OSX_ENABLED) || defined(X11_ENABLED) +// if (is_execute) { +// // we need execute rights on this file +// chmod(file.utf8().get_data(), 0755); +// } +//#endif +// } + +// ret = unzGoToNextFile(src_pkg_zip); +// } + +// /* we're done with our source zip */ +// unzClose(src_pkg_zip); + +// if (!found_library) { +// ERR_PRINT("Requested template library '" + library_to_use + "' not found. It might be missing from your template archive."); +// memdelete(tmp_app_path); +// return ERR_FILE_NOT_FOUND; +// } + +// // Copy project static libs to the project +// Vector> export_plugins = EditorExport::get_singleton()->get_export_plugins(); +// for (int i = 0; i < export_plugins.size(); i++) { +// Vector project_static_libs = export_plugins[i]->get_ios_project_static_libs(); +// for (int j = 0; j < project_static_libs.size(); j++) { +// const String &static_lib_path = project_static_libs[j]; +// String dest_lib_file_path = dest_dir + static_lib_path.get_file(); +// Error lib_copy_err = tmp_app_path->copy(static_lib_path, dest_lib_file_path); +// if (lib_copy_err != OK) { +// ERR_PRINT("Can't copy '" + static_lib_path + "'."); +// memdelete(tmp_app_path); +// return lib_copy_err; +// } +// } +// } + +// String iconset_dir = dest_dir + binary_name + "/Images.xcassets/AppIcon.appiconset/"; +// err = OK; +// if (!tmp_app_path->dir_exists(iconset_dir)) { +// err = tmp_app_path->make_dir_recursive(iconset_dir); +// } +// memdelete(tmp_app_path); +// if (err) { +// return err; +// } + +// err = _export_icons(p_preset, iconset_dir); +// if (err) { +// return err; +// } + +// bool use_storyboard = p_preset->get("storyboard/use_launch_screen_storyboard"); + +// String launch_image_path = dest_dir + binary_name + "/Images.xcassets/LaunchImage.launchimage/"; +// String splash_image_path = dest_dir + binary_name + "/Images.xcassets/SplashImage.imageset/"; + +// DirAccess *launch_screen_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + +// if (!launch_screen_da) { +// return ERR_CANT_CREATE; +// } + +// if (use_storyboard) { +// print_line("Using Launch Storyboard"); + +// if (launch_screen_da->change_dir(launch_image_path) == OK) { +// launch_screen_da->erase_contents_recursive(); +// launch_screen_da->remove(launch_image_path); +// } + +// err = _export_loading_screen_file(p_preset, splash_image_path); +// } else { +// print_line("Using Launch Images"); + +// const String launch_screen_path = dest_dir + binary_name + "/Launch Screen.storyboard"; + +// launch_screen_da->remove(launch_screen_path); + +// if (launch_screen_da->change_dir(splash_image_path) == OK) { +// launch_screen_da->erase_contents_recursive(); +// launch_screen_da->remove(splash_image_path); +// } + +// err = _export_loading_screen_images(p_preset, launch_image_path); +// } + +// memdelete(launch_screen_da); + +// if (err) { +// return err; +// } + +// print_line("Exporting additional assets"); +// _export_additional_assets(dest_dir + binary_name, libraries, assets); +// _add_assets_to_project(p_preset, project_file_data, assets); +// String project_file_name = dest_dir + binary_name + ".xcodeproj/project.pbxproj"; +// FileAccess *f = FileAccess::open(project_file_name, FileAccess::WRITE); +// if (!f) { +// ERR_PRINT("Can't write '" + project_file_name + "'."); +// return ERR_CANT_CREATE; +// }; +// f->store_buffer(project_file_data.ptr(), project_file_data.size()); +// f->close(); +// memdelete(f); + +//#ifdef OSX_ENABLED +// if (ep.step("Code-signing dylibs", 2)) { +// return ERR_SKIP; +// } +// DirAccess *dylibs_dir = DirAccess::open(dest_dir + binary_name + "/dylibs"); +// ERR_FAIL_COND_V(!dylibs_dir, ERR_CANT_OPEN); +// CodesignData codesign_data(p_preset, p_debug); +// err = _walk_dir_recursive(dylibs_dir, _codesign, &codesign_data); +// memdelete(dylibs_dir); +// ERR_FAIL_COND_V(err, err); + +// if (ep.step("Making .xcarchive", 3)) { +// return ERR_SKIP; +// } +// String archive_path = p_path.get_basename() + ".xcarchive"; +// List archive_args; +// archive_args.push_back("-project"); +// archive_args.push_back(dest_dir + binary_name + ".xcodeproj"); +// archive_args.push_back("-scheme"); +// archive_args.push_back(binary_name); +// archive_args.push_back("-sdk"); +// archive_args.push_back("iphoneos"); +// archive_args.push_back("-configuration"); +// archive_args.push_back(p_debug ? "Debug" : "Release"); +// archive_args.push_back("-destination"); +// archive_args.push_back("generic/platform=iOS"); +// archive_args.push_back("archive"); +// archive_args.push_back("-archivePath"); +// archive_args.push_back(archive_path); +// err = OS::get_singleton()->execute("xcodebuild", archive_args, true); +// ERR_FAIL_COND_V(err, err); + +// if (ep.step("Making .ipa", 4)) { +// return ERR_SKIP; +// } +// List export_args; +// export_args.push_back("-exportArchive"); +// export_args.push_back("-archivePath"); +// export_args.push_back(archive_path); +// export_args.push_back("-exportOptionsPlist"); +// export_args.push_back(dest_dir + binary_name + "/export_options.plist"); +// export_args.push_back("-allowProvisioningUpdates"); +// export_args.push_back("-exportPath"); +// export_args.push_back(dest_dir); +// err = OS::get_singleton()->execute("xcodebuild", export_args, true); +// ERR_FAIL_COND_V(err, err); +//#else +// print_line(".ipa can only be built on macOS. Leaving Xcode project without building the package."); +//#endif + +// return OK; +//} + +//bool EditorExportPlatformIOS::can_export(const Ref &p_preset, String &r_error, bool &r_missing_templates) const { +// String err; +// bool valid = false; + +// // Look for export templates (first official, and if defined custom templates). + +// bool dvalid = exists_export_template("iphone.zip", &err); +// bool rvalid = dvalid; // Both in the same ZIP. + +// if (p_preset->get("custom_template/debug") != "") { +// dvalid = FileAccess::exists(p_preset->get("custom_template/debug")); +// if (!dvalid) { +// err += TTR("Custom debug template not found.") + "\n"; +// } +// } +// if (p_preset->get("custom_template/release") != "") { +// rvalid = FileAccess::exists(p_preset->get("custom_template/release")); +// if (!rvalid) { +// err += TTR("Custom release template not found.") + "\n"; +// } +// } + +// valid = dvalid || rvalid; +// r_missing_templates = !valid; + +// // Validate the rest of the configuration. + +// String team_id = p_preset->get("application/app_store_team_id"); +// if (team_id.length() == 0) { +// err += TTR("App Store Team ID not specified - cannot configure the project.") + "\n"; +// valid = false; +// } + +// String identifier = p_preset->get("application/bundle_identifier"); +// String pn_err; +// if (!is_package_name_valid(identifier, &pn_err)) { +// err += TTR("Invalid Identifier:") + " " + pn_err + "\n"; +// valid = false; +// } + +// for (uint64_t i = 0; i < (sizeof(icon_infos) / sizeof(icon_infos[0])); ++i) { +// IconInfo info = icon_infos[i]; +// String icon_path = p_preset->get(info.preset_key); +// if (icon_path.length() == 0) { +// if (info.is_required) { +// err += TTR("Required icon is not specified in the preset.") + "\n"; +// valid = false; +// } +// break; +// } +// } + +// String etc_error = test_etc2_or_pvrtc(); +// if (etc_error != String()) { +// valid = false; +// err += etc_error; +// } + +// if (!err.is_empty()) { +// r_error = err; +// } + +// return valid; +//} + +//EditorExportPlatformIOS::EditorExportPlatformIOS() { +// Ref img = memnew(Image(_iphone_logo)); +// logo.instance(); +// logo->create_from_image(img); + +// plugins_changed = true; +// quit_request = false; + +// check_for_changes_thread = Thread::create(_check_for_changes_poll_thread, this); +//} + +//EditorExportPlatformIOS::~EditorExportPlatformIOS() { +// quit_request = true; +// Thread::wait_to_finish(check_for_changes_thread); +// memdelete(check_for_changes_thread); +//} void register_iphone_exporter() { Ref platform; diff --git a/platform/iphone/platform_config.h b/platform/iphone/platform_config.h index 88ad4a3f670..f8a8eb15d2c 100644 --- a/platform/iphone/platform_config.h +++ b/platform/iphone/platform_config.h @@ -30,6 +30,9 @@ #include +#define GLES2_INCLUDE_H +#define GLES3_INCLUDE_H + #define PLATFORM_REFCOUNT #define PTHREAD_RENAME_SELF diff --git a/platform/javascript/export/export.cpp b/platform/javascript/export/export.cpp index 889b0bbd027..503e58f9a8d 100644 --- a/platform/javascript/export/export.cpp +++ b/platform/javascript/export/export.cpp @@ -32,6 +32,678 @@ #include "export_plugin.h" +/* + +class EditorHTTPServer : public Reference { +private: + Ref server; + Ref connection; + uint64_t time = 0; + uint8_t req_buf[4096]; + int req_pos = 0; + + void _clear_client() { + connection = Ref(); + memset(req_buf, 0, sizeof(req_buf)); + time = 0; + req_pos = 0; + } + +public: + EditorHTTPServer() { + server.instance(); + stop(); + } + + void stop() { + server->stop(); + _clear_client(); + } + + Error listen(int p_port, IP_Address p_address) { + return server->listen(p_port, p_address); + } + + bool is_listening() const { + return server->is_listening(); + } + + void _send_response() { + Vector psa = String((char *)req_buf).split("\r\n"); + int len = psa.size(); + ERR_FAIL_COND_MSG(len < 4, "Not enough response headers, got: " + itos(len) + ", expected >= 4."); + + Vector req = psa[0].split(" ", false); + ERR_FAIL_COND_MSG(req.size() < 2, "Invalid protocol or status code."); + + // Wrong protocol + ERR_FAIL_COND_MSG(req[0] != "GET" || req[2] != "HTTP/1.1", "Invalid method or HTTP version."); + + const String cache_path = EditorSettings::get_singleton()->get_cache_dir(); + const String basereq = "/tmp_js_export"; + String filepath; + String ctype; + if (req[1] == basereq + ".html") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "text/html"; + } else if (req[1] == basereq + ".js") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/javascript"; + } else if (req[1] == basereq + ".audio.worklet.js") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/javascript"; + } else if (req[1] == basereq + ".worker.js") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/javascript"; + } else if (req[1] == basereq + ".pck") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/octet-stream"; + } else if (req[1] == basereq + ".png" || req[1] == "/favicon.png") { + // Also allow serving the generated favicon for a smoother loading experience. + if (req[1] == "/favicon.png") { + filepath = EditorSettings::get_singleton()->get_cache_dir().plus_file("favicon.png"); + } else { + filepath = basereq + ".png"; + } + ctype = "image/png"; + } else if (req[1] == basereq + ".side.wasm") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/wasm"; + } else if (req[1] == basereq + ".wasm") { + filepath = cache_path.plus_file(req[1].get_file()); + ctype = "application/wasm"; + } else if (req[1].ends_with(".wasm")) { + filepath = cache_path.plus_file(req[1].get_file()); // TODO dangerous? + ctype = "application/wasm"; + } + if (filepath.is_empty() || !FileAccess::exists(filepath)) { + String s = "HTTP/1.1 404 Not Found\r\n"; + s += "Connection: Close\r\n"; + s += "\r\n"; + CharString cs = s.utf8(); + connection->put_data((const uint8_t *)cs.get_data(), cs.size() - 1); + return; + } + FileAccess *f = FileAccess::open(filepath, FileAccess::READ); + ERR_FAIL_COND(!f); + String s = "HTTP/1.1 200 OK\r\n"; + s += "Connection: Close\r\n"; + s += "Content-Type: " + ctype + "\r\n"; + s += "Access-Control-Allow-Origin: *\r\n"; + s += "Cross-Origin-Opener-Policy: same-origin\r\n"; + s += "Cross-Origin-Embedder-Policy: require-corp\r\n"; + s += "\r\n"; + CharString cs = s.utf8(); + Error err = connection->put_data((const uint8_t *)cs.get_data(), cs.size() - 1); + if (err != OK) { + memdelete(f); + ERR_FAIL(); + } + + while (true) { + uint8_t bytes[4096]; + int read = f->get_buffer(bytes, 4096); + if (read < 1) { + break; + } + err = connection->put_data(bytes, read); + if (err != OK) { + memdelete(f); + ERR_FAIL(); + } + } + memdelete(f); + } + + void poll() { + if (!server->is_listening()) { + return; + } + if (connection.is_null()) { + if (!server->is_connection_available()) { + return; + } + connection = server->take_connection(); + time = OS::get_singleton()->get_ticks_usec(); + } + if (OS::get_singleton()->get_ticks_usec() - time > 1000000) { + _clear_client(); + return; + } + if (connection->get_status() != StreamPeerTCP::STATUS_CONNECTED) { + return; + } + + while (true) { + char *r = (char *)req_buf; + int l = req_pos - 1; + if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') { + _send_response(); + _clear_client(); + return; + } + + int read = 0; + ERR_FAIL_COND(req_pos >= 4096); + Error err = connection->get_partial_data(&req_buf[req_pos], 1, read); + if (err != OK) { + // Got an error + _clear_client(); + return; + } else if (read != 1) { + // Busy, wait next poll + return; + } + req_pos += read; + } + } +}; + +class EditorExportPlatformJavaScript : public EditorExportPlatform { + GDCLASS(EditorExportPlatformJavaScript, EditorExportPlatform); + + Ref logo; + Ref run_icon; + Ref stop_icon; + int menu_options = 0; + + Ref server; + bool server_quit = false; + Mutex server_lock; + Thread *server_thread = nullptr; + + enum ExportMode { + EXPORT_MODE_NORMAL = 0, + EXPORT_MODE_THREADS = 1, + EXPORT_MODE_GDNATIVE = 2, + }; + + String _get_template_name(ExportMode p_mode, bool p_debug) const { + String name = "webassembly"; + switch (p_mode) { + case EXPORT_MODE_THREADS: + name += "_threads"; + break; + case EXPORT_MODE_GDNATIVE: + name += "_gdnative"; + break; + default: + break; + } + if (p_debug) { + name += "_debug.zip"; + } else { + name += "_release.zip"; + } + return name; + } + + void _fix_html(Vector &p_html, const Ref &p_preset, const String &p_name, bool p_debug, int p_flags, const Vector p_shared_objects); + + static void _server_thread_poll(void *data); + +public: + virtual void get_preset_features(const Ref &p_preset, List *r_features) override; + + virtual void get_export_options(List *r_options) override; + + virtual String get_name() const override; + virtual String get_os_name() const override; + virtual Ref get_logo() const override; + + virtual bool can_export(const Ref &p_preset, String &r_error, bool &r_missing_templates) const override; + virtual List get_binary_extensions(const Ref &p_preset) const override; + virtual Error export_project(const Ref &p_preset, bool p_debug, const String &p_path, int p_flags = 0) override; + + virtual bool poll_export() override; + virtual int get_options_count() const override; + virtual String get_option_label(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run in Browser"); } + virtual String get_option_tooltip(int p_index) const override { return p_index ? TTR("Stop HTTP Server") : TTR("Run exported HTML in the system's default browser."); } + virtual Ref get_option_icon(int p_index) const override; + virtual Error run(const Ref &p_preset, int p_option, int p_debug_flags) override; + virtual Ref get_run_icon() const override; + + virtual void get_platform_features(List *r_features) override { + r_features->push_back("web"); + r_features->push_back(get_os_name()); + } + + virtual void resolve_platform_feature_priorities(const Ref &p_preset, Set &p_features) override { + } + + String get_debug_protocol() const override { return "ws://"; } + + EditorExportPlatformJavaScript(); + ~EditorExportPlatformJavaScript(); +}; + +void EditorExportPlatformJavaScript::_fix_html(Vector &p_html, const Ref &p_preset, const String &p_name, bool p_debug, int p_flags, const Vector p_shared_objects) { + String str_template = String::utf8(reinterpret_cast(p_html.ptr()), p_html.size()); + String str_export; + Vector lines = str_template.split("\n"); + Vector flags; + String flags_json; + gen_export_flags(flags, p_flags); + flags_json = JSON::print(flags); + String libs; + for (int i = 0; i < p_shared_objects.size(); i++) { + libs += "\"" + p_shared_objects[i].path.get_file() + "\","; + } + + for (int i = 0; i < lines.size(); i++) { + String current_line = lines[i]; + current_line = current_line.replace("$GODOT_BASENAME", p_name); + current_line = current_line.replace("$GODOT_PROJECT_NAME", ProjectSettings::get_singleton()->get_setting("application/config/name")); + current_line = current_line.replace("$GODOT_HEAD_INCLUDE", p_preset->get("html/head_include")); + current_line = current_line.replace("$GODOT_FULL_WINDOW", p_preset->get("html/full_window_size") ? "true" : "false"); + current_line = current_line.replace("$GODOT_GDNATIVE_LIBS", libs); + current_line = current_line.replace("$GODOT_DEBUG_ENABLED", p_debug ? "true" : "false"); + current_line = current_line.replace("$GODOT_ARGS", flags_json); + str_export += current_line + "\n"; + } + + CharString cs = str_export.utf8(); + p_html.resize(cs.length()); + for (int i = 0; i < cs.length(); i++) { + p_html.write[i] = cs[i]; + } +} + +void EditorExportPlatformJavaScript::get_preset_features(const Ref &p_preset, List *r_features) { + if (p_preset->get("vram_texture_compression/for_desktop")) { + r_features->push_back("s3tc"); + } + + if (p_preset->get("vram_texture_compression/for_mobile")) { + String driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name"); + if (driver == "GLES2") { + r_features->push_back("etc"); + } else if (driver == "Vulkan") { + // FIXME: Review if this is correct. + r_features->push_back("etc2"); + } + } + ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type"); + if (mode == EXPORT_MODE_THREADS) { + r_features->push_back("threads"); + } else if (mode == EXPORT_MODE_GDNATIVE) { + r_features->push_back("wasm32"); + } +} + +void EditorExportPlatformJavaScript::get_export_options(List *r_options) { + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE, "*.zip"), "")); + + r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "variant/export_type", PROPERTY_HINT_ENUM, "Regular,Threads,GDNative"), 0)); // Export type. + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_desktop"), true)); // S3TC + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "vram_texture_compression/for_mobile"), false)); // ETC or ETC2, depending on renderer + + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/custom_html_shell", PROPERTY_HINT_FILE, "*.html"), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "html/head_include", PROPERTY_HINT_MULTILINE_TEXT), "")); + r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "html/full_window_size"), true)); +} + +String EditorExportPlatformJavaScript::get_name() const { + return "HTML5"; +} + +String EditorExportPlatformJavaScript::get_os_name() const { + return "HTML5"; +} + +Ref EditorExportPlatformJavaScript::get_logo() const { + return logo; +} + +bool EditorExportPlatformJavaScript::can_export(const Ref &p_preset, String &r_error, bool &r_missing_templates) const { + String err; + bool valid = false; + ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type"); + + // Look for export templates (first official, and if defined custom templates). + bool dvalid = exists_export_template(_get_template_name(mode, true), &err); + bool rvalid = exists_export_template(_get_template_name(mode, false), &err); + + if (p_preset->get("custom_template/debug") != "") { + dvalid = FileAccess::exists(p_preset->get("custom_template/debug")); + if (!dvalid) { + err += TTR("Custom debug template not found.") + "\n"; + } + } + if (p_preset->get("custom_template/release") != "") { + rvalid = FileAccess::exists(p_preset->get("custom_template/release")); + if (!rvalid) { + err += TTR("Custom release template not found.") + "\n"; + } + } + + valid = dvalid || rvalid; + r_missing_templates = !valid; + + // Validate the rest of the configuration. + + if (p_preset->get("vram_texture_compression/for_mobile")) { + String etc_error = test_etc2(); + if (etc_error != String()) { + valid = false; + err += etc_error; + } + } + + if (!err.is_empty()) { + r_error = err; + } + + return valid; +} + +List EditorExportPlatformJavaScript::get_binary_extensions(const Ref &p_preset) const { + List list; + list.push_back("html"); + return list; +} + +Error EditorExportPlatformJavaScript::export_project(const Ref &p_preset, bool p_debug, const String &p_path, int p_flags) { + ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags); + + String custom_debug = p_preset->get("custom_template/debug"); + String custom_release = p_preset->get("custom_template/release"); + String custom_html = p_preset->get("html/custom_html_shell"); + + String template_path = p_debug ? custom_debug : custom_release; + + template_path = template_path.strip_edges(); + + if (template_path == String()) { + ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type"); + template_path = find_export_template(_get_template_name(mode, p_debug)); + } + + if (!DirAccess::exists(p_path.get_base_dir())) { + return ERR_FILE_BAD_PATH; + } + + if (template_path != String() && !FileAccess::exists(template_path)) { + EditorNode::get_singleton()->show_warning(TTR("Template file not found:") + "\n" + template_path); + return ERR_FILE_NOT_FOUND; + } + + Vector shared_objects; + String pck_path = p_path.get_basename() + ".pck"; + Error error = save_pack(p_preset, pck_path, &shared_objects); + if (error != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + pck_path); + return error; + } + DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + for (int i = 0; i < shared_objects.size(); i++) { + String dst = p_path.get_base_dir().plus_file(shared_objects[i].path.get_file()); + error = da->copy(shared_objects[i].path, dst); + if (error != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + shared_objects[i].path.get_file()); + memdelete(da); + return error; + } + } + memdelete(da); + + FileAccess *src_f = nullptr; + zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + unzFile pkg = unzOpen2(template_path.utf8().get_data(), &io); + + if (!pkg) { + EditorNode::get_singleton()->show_warning(TTR("Could not open template for export:") + "\n" + template_path); + return ERR_FILE_NOT_FOUND; + } + + if (unzGoToFirstFile(pkg) != UNZ_OK) { + EditorNode::get_singleton()->show_warning(TTR("Invalid export template:") + "\n" + template_path); + unzClose(pkg); + return ERR_FILE_CORRUPT; + } + + do { + //get filename + unz_file_info info; + char fname[16384]; + unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + + String file = fname; + + Vector data; + data.resize(info.uncompressed_size); + + //read + unzOpenCurrentFile(pkg); + unzReadCurrentFile(pkg, data.ptrw(), data.size()); + unzCloseCurrentFile(pkg); + + //write + + if (file == "godot.html") { + if (!custom_html.is_empty()) { + continue; + } + _fix_html(data, p_preset, p_path.get_file().get_basename(), p_debug, p_flags, shared_objects); + file = p_path.get_file(); + + } else if (file == "godot.js") { + file = p_path.get_file().get_basename() + ".js"; + + } else if (file == "godot.worker.js") { + file = p_path.get_file().get_basename() + ".worker.js"; + + } else if (file == "godot.side.wasm") { + file = p_path.get_file().get_basename() + ".side.wasm"; + + } else if (file == "godot.audio.worklet.js") { + file = p_path.get_file().get_basename() + ".audio.worklet.js"; + + } else if (file == "godot.wasm") { + file = p_path.get_file().get_basename() + ".wasm"; + } + + String dst = p_path.get_base_dir().plus_file(file); + FileAccess *f = FileAccess::open(dst, FileAccess::WRITE); + if (!f) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst); + unzClose(pkg); + return ERR_FILE_CANT_WRITE; + } + f->store_buffer(data.ptr(), data.size()); + memdelete(f); + + } while (unzGoToNextFile(pkg) == UNZ_OK); + unzClose(pkg); + + if (!custom_html.is_empty()) { + FileAccess *f = FileAccess::open(custom_html, FileAccess::READ); + if (!f) { + EditorNode::get_singleton()->show_warning(TTR("Could not read custom HTML shell:") + "\n" + custom_html); + return ERR_FILE_CANT_READ; + } + Vector buf; + buf.resize(f->get_len()); + f->get_buffer(buf.ptrw(), buf.size()); + memdelete(f); + _fix_html(buf, p_preset, p_path.get_file().get_basename(), p_debug, p_flags, shared_objects); + + f = FileAccess::open(p_path, FileAccess::WRITE); + if (!f) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path); + return ERR_FILE_CANT_WRITE; + } + f->store_buffer(buf.ptr(), buf.size()); + memdelete(f); + } + + Ref splash; + const String splash_path = String(GLOBAL_GET("application/boot_splash/image")).strip_edges(); + if (!splash_path.is_empty()) { + splash.instance(); + const Error err = splash->load(splash_path); + if (err) { + EditorNode::get_singleton()->show_warning(TTR("Could not read boot splash image file:") + "\n" + splash_path + "\n" + TTR("Using default boot splash image.")); + splash.unref(); + } + } + if (splash.is_null()) { + splash = Ref(memnew(Image(boot_splash_png))); + } + const String splash_png_path = p_path.get_base_dir().plus_file(p_path.get_file().get_basename() + ".png"); + if (splash->save_png(splash_png_path) != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + splash_png_path); + return ERR_FILE_CANT_WRITE; + } + + // Save a favicon that can be accessed without waiting for the project to finish loading. + // This way, the favicon can be displayed immediately when loading the page. + Ref favicon; + const String favicon_path = String(GLOBAL_GET("application/config/icon")).strip_edges(); + if (!favicon_path.is_empty()) { + favicon.instance(); + const Error err = favicon->load(favicon_path); + if (err) { + favicon.unref(); + } + } + + if (favicon.is_valid()) { + const String favicon_png_path = p_path.get_base_dir().plus_file("favicon.png"); + if (favicon->save_png(favicon_png_path) != OK) { + EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + favicon_png_path); + return ERR_FILE_CANT_WRITE; + } + } + + return OK; +} + +bool EditorExportPlatformJavaScript::poll_export() { + Ref preset; + + for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + Ref ep = EditorExport::get_singleton()->get_export_preset(i); + if (ep->is_runnable() && ep->get_platform() == this) { + preset = ep; + break; + } + } + + int prev = menu_options; + menu_options = preset.is_valid(); + if (server->is_listening()) { + if (menu_options == 0) { + MutexLock lock(server_lock); + server->stop(); + } else { + menu_options += 1; + } + } + return menu_options != prev; +} + +Ref EditorExportPlatformJavaScript::get_option_icon(int p_index) const { + return p_index == 1 ? stop_icon : EditorExportPlatform::get_option_icon(p_index); +} + +int EditorExportPlatformJavaScript::get_options_count() const { + return menu_options; +} + +Error EditorExportPlatformJavaScript::run(const Ref &p_preset, int p_option, int p_debug_flags) { + if (p_option == 1) { + MutexLock lock(server_lock); + server->stop(); + return OK; + } + + const String basepath = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmp_js_export"); + Error err = export_project(p_preset, true, basepath + ".html", p_debug_flags); + if (err != OK) { + // Export generates several files, clean them up on failure. + DirAccess::remove_file_or_error(basepath + ".html"); + DirAccess::remove_file_or_error(basepath + ".js"); + DirAccess::remove_file_or_error(basepath + ".worker.js"); + DirAccess::remove_file_or_error(basepath + ".audio.worklet.js"); + DirAccess::remove_file_or_error(basepath + ".pck"); + DirAccess::remove_file_or_error(basepath + ".png"); + DirAccess::remove_file_or_error(basepath + ".side.wasm"); + DirAccess::remove_file_or_error(basepath + ".wasm"); + DirAccess::remove_file_or_error(EditorSettings::get_singleton()->get_cache_dir().plus_file("favicon.png")); + return err; + } + + const uint16_t bind_port = EDITOR_GET("export/web/http_port"); + // Resolve host if needed. + const String bind_host = EDITOR_GET("export/web/http_host"); + IP_Address bind_ip; + if (bind_host.is_valid_ip_address()) { + bind_ip = bind_host; + } else { + bind_ip = IP::get_singleton()->resolve_hostname(bind_host); + } + ERR_FAIL_COND_V_MSG(!bind_ip.is_valid(), ERR_INVALID_PARAMETER, "Invalid editor setting 'export/web/http_host': '" + bind_host + "'. Try using '127.0.0.1'."); + + // Restart server. + { + MutexLock lock(server_lock); + + server->stop(); + err = server->listen(bind_port, bind_ip); + } + ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to start HTTP server."); + + OS::get_singleton()->shell_open(String("http://" + bind_host + ":" + itos(bind_port) + "/tmp_js_export.html")); + // FIXME: Find out how to clean up export files after running the successfully + // exported game. Might not be trivial. + return OK; +} + +Ref EditorExportPlatformJavaScript::get_run_icon() const { + return run_icon; +} + +void EditorExportPlatformJavaScript::_server_thread_poll(void *data) { + EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data; + while (!ej->server_quit) { + OS::get_singleton()->delay_usec(1000); + { + MutexLock lock(ej->server_lock); + ej->server->poll(); + } + } +} + +EditorExportPlatformJavaScript::EditorExportPlatformJavaScript() { + server.instance(); + server_thread = Thread::create(_server_thread_poll, this); + + Ref img = memnew(Image(_javascript_logo)); + logo.instance(); + logo->create_from_image(img); + + img = Ref(memnew(Image(_javascript_run_icon))); + run_icon.instance(); + run_icon->create_from_image(img); + + Ref theme = EditorNode::get_singleton()->get_editor_theme(); + if (theme.is_valid()) { + stop_icon = theme->get_icon("Stop", "EditorIcons"); + } else { + stop_icon.instance(); + } +} + +EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() { + server->stop(); + server_quit = true; + Thread::wait_to_finish(server_thread); + memdelete(server_thread); +} + +*/ void register_javascript_exporter() { EDITOR_DEF("export/web/http_host", "localhost"); EDITOR_DEF("export/web/http_port", 8060); diff --git a/platform/linuxbsd/SCsub b/platform/linuxbsd/SCsub index 8aebd57fd29..05393f6246d 100644 --- a/platform/linuxbsd/SCsub +++ b/platform/linuxbsd/SCsub @@ -14,12 +14,14 @@ common_linuxbsd = [ if "x11" in env and env["x11"]: common_linuxbsd += [ - "context_gl_x11.cpp", + "gl_manager_x11.cpp", "detect_prime_x11.cpp", "display_server_x11.cpp", "key_mapping_x11.cpp", ] +#"context_gl_x11.cpp", + if "vulkan" in env and env["vulkan"]: common_linuxbsd.append("vulkan_context_x11.cpp") diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py index 4b3804d049e..04da082b16c 100644 --- a/platform/linuxbsd/detect.py +++ b/platform/linuxbsd/detect.py @@ -381,8 +381,8 @@ def configure(env): # No pkgconfig file for glslang so far env.Append(LIBS=["glslang", "SPIRV"]) - # env.Append(CPPDEFINES=['OPENGL_ENABLED']) - env.Append(LIBS=["GL"]) + env.Append(CPPDEFINES=["OPENGL_ENABLED"]) + env.Append(LIBS=["GL"]) env.Append(LIBS=["pthread"]) diff --git a/platform/linuxbsd/detect_prime_x11.cpp b/platform/linuxbsd/detect_prime_x11.cpp index da1c95a593c..f074c9e9d89 100644 --- a/platform/linuxbsd/detect_prime_x11.cpp +++ b/platform/linuxbsd/detect_prime_x11.cpp @@ -31,7 +31,7 @@ #ifdef X11_ENABLED #if defined(OPENGL_ENABLED) -#include "detect_prime.h" +#include "detect_prime_x11.h" #include "core/string/print_string.h" #include "core/string/ustring.h" diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp index dd296ec3b46..18247deafb8 100644 --- a/platform/linuxbsd/display_server_x11.cpp +++ b/platform/linuxbsd/display_server_x11.cpp @@ -34,6 +34,7 @@ #include "core/config/project_settings.h" #include "core/string/print_string.h" +#include "core/string/ustring.h" #include "detect_prime_x11.h" #include "key_mapping_x11.h" #include "main/main.h" @@ -43,6 +44,10 @@ #include "servers/rendering/renderer_rd/renderer_compositor_rd.h" #endif +#if defined(GLES_X11_ENABLED) +#include "drivers/gles2/rasterizer_gles2.h" +#endif + #include #include #include @@ -884,6 +889,12 @@ void DisplayServerX11::delete_sub_window(WindowID p_id) { context_vulkan->window_destroy(p_id); } #endif +#ifdef GLES_X11_ENABLED + if (gl_manager) { + gl_manager->window_destroy(p_id); + } +#endif + XUnmapWindow(x11_display, wd.x11_window); XDestroyWindow(x11_display, wd.x11_window); if (wd.xic) { @@ -1052,6 +1063,13 @@ int DisplayServerX11::window_get_current_screen(WindowID p_window) const { return screen_index; } +void DisplayServerX11::gl_window_make_current(DisplayServer::WindowID p_window_id) { +#if defined(GLES_X11_ENABLED) + if (gl_manager) + gl_manager->window_make_current(p_window_id); +#endif +} + void DisplayServerX11::window_set_current_screen(int p_screen, WindowID p_window) { _THREAD_SAFE_METHOD_ @@ -2648,6 +2666,11 @@ void DisplayServerX11::_window_changed(XEvent *event) { context_vulkan->window_resize(window_id, wd.size.width, wd.size.height); } #endif +#if defined(GLES_X11_ENABLED) + if (gl_manager) { + gl_manager->window_resize(window_id, wd.size.width, wd.size.height); + } +#endif if (!wd.rect_changed_callback.is_null()) { Rect2i r = new_rect; @@ -3524,12 +3547,23 @@ void DisplayServerX11::process_events() { } void DisplayServerX11::release_rendering_thread() { +#if defined(GLES_X11_ENABLED) +// gl_manager->release_current(); +#endif } void DisplayServerX11::make_rendering_thread() { +#if defined(GLES_X11_ENABLED) +// gl_manager->make_current(); +#endif } void DisplayServerX11::swap_buffers() { +#if defined(GLES_X11_ENABLED) + if (gl_manager) { + gl_manager->swap_buffers(); + } +#endif } void DisplayServerX11::_update_context(WindowData &wd) { @@ -3671,17 +3705,31 @@ void DisplayServerX11::set_icon(const Ref &p_icon) { void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) { _THREAD_SAFE_METHOD_ #if defined(VULKAN_ENABLED) - context_vulkan->set_vsync_mode(p_window, p_vsync_mode); + if (context_vulkan) { + context_vulkan->set_vsync_mode(p_window, p_vsync_mode); + } +#endif + +#if defined(GLES_X11_ENABLED) + if (gl_manager) { + gl_manager->set_use_vsync(p_vsync_mode == DisplayServer::VSYNC_ENABLED); + } #endif } DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const { _THREAD_SAFE_METHOD_ #if defined(VULKAN_ENABLED) - return context_vulkan->get_vsync_mode(p_window); -#else - return DisplayServer::VSYNC_ENABLED; + if (context_vulkan) { + return context_vulkan->get_vsync_mode(p_window); + } #endif +#if defined(GLES_X11_ENABLED) + if (gl_manager) { + return gl_manager->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED; + } +#endif + return DisplayServer::VSYNC_ENABLED; } Vector DisplayServerX11::get_rendering_drivers_func() { @@ -3690,8 +3738,10 @@ Vector DisplayServerX11::get_rendering_drivers_func() { #ifdef VULKAN_ENABLED drivers.push_back("vulkan"); #endif -#ifdef OPENGL_ENABLED - drivers.push_back("opengl"); +#ifdef GLES_X11_ENABLED + // drivers.push_back("opengl"); + drivers.push_back("GLES2"); + drivers.push_back("GLES3"); #endif return drivers; @@ -3876,6 +3926,13 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, V ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan window"); } #endif +#ifdef GLES_X11_ENABLED + print_line("rendering_driver " + rendering_driver); + if (gl_manager) { + Error err = gl_manager->window_create(id, wd.x11_window, x11_display, p_rect.size.width, p_rect.size.height); + ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a GLES2 window"); + } +#endif //set_class_hint(x11_display, wd.x11_window); XFlush(x11_display); @@ -4061,10 +4118,13 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode rendering_driver = p_rendering_driver; #ifndef _MSC_VER -#warning Forcing vulkan rendering driver because OpenGL not implemented yet +//#warning Forcing vulkan rendering driver because OpenGL not implemented yet +//#warning Forcing opengl rendering driver because selecting properly is too much effort #endif - rendering_driver = "vulkan"; + // rendering_driver = "vulkan"; + //rendering_driver = "GLES2"; + bool driver_found = false; #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { context_vulkan = memnew(VulkanContextX11); @@ -4074,11 +4134,13 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode r_error = ERR_CANT_CREATE; ERR_FAIL_MSG("Could not initialize Vulkan"); } + driver_found = true; } #endif // Init context and rendering device -#if defined(OPENGL_ENABLED) - if (rendering_driver == "opengl_es") { +#if defined(GLES_X11_ENABLED) + print_line("rendering_driver " + rendering_driver); + if (rendering_driver == "GLES2") { if (getenv("DRI_PRIME") == nullptr) { int use_prime = -1; @@ -4120,28 +4182,37 @@ DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode } } - ContextGL_X11::ContextType opengl_api_type = ContextGL_X11::GLES_2_0_COMPATIBLE; + GLManager_X11::ContextType opengl_api_type = GLManager_X11::GLES_2_0_COMPATIBLE; - context_gles2 = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, opengl_api_type)); + gl_manager = memnew(GLManager_X11(p_resolution, opengl_api_type)); - if (context_gles2->initialize() != OK) { - memdelete(context_gles2); - context_gles2 = nullptr; - ERR_FAIL_V(ERR_UNAVAILABLE); + if (gl_manager->initialize() != OK) { + memdelete(gl_manager); + gl_manager = nullptr; + r_error = ERR_UNAVAILABLE; + return; } + driver_found = true; - context_gles2->set_use_vsync(current_videomode.use_vsync); + // gl_manager->set_use_vsync(current_videomode.use_vsync); - if (RasterizerGLES2::is_viable() == OK) { - RasterizerGLES2::register_config(); + if (true) { + // if (RasterizerGLES2::is_viable() == OK) { + // RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); } else { - memdelete(context_gles2); - context_gles2 = nullptr; - ERR_FAIL_V(ERR_UNAVAILABLE); + memdelete(gl_manager); + gl_manager = nullptr; + r_error = ERR_UNAVAILABLE; + return; } } #endif + if (!driver_found) { + r_error = ERR_UNAVAILABLE; + ERR_FAIL_MSG("Video driver not found"); + } + Point2i window_position( (screen_get_size(0).width - p_resolution.width) / 2, (screen_get_size(0).height - p_resolution.height) / 2); @@ -4344,6 +4415,11 @@ DisplayServerX11::~DisplayServerX11() { context_vulkan->window_destroy(E.key); } #endif +#ifdef GLES_X11_ENABLED + if (rendering_driver == "GLES2") { + gl_manager->window_destroy(E->key()); + } +#endif WindowData &wd = E.value; if (wd.xic) { @@ -4368,6 +4444,13 @@ DisplayServerX11::~DisplayServerX11() { } #endif +#ifdef GLES_X11_ENABLED + if (gl_manager) { + memdelete(gl_manager); + gl_manager = nullptr; + } +#endif + if (xrandr_handle) { dlclose(xrandr_handle); } diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h index 4575714bf2f..bbf0e64fd3d 100644 --- a/platform/linuxbsd/display_server_x11.h +++ b/platform/linuxbsd/display_server_x11.h @@ -31,6 +31,8 @@ #ifndef DISPLAY_SERVER_X11_H #define DISPLAY_SERVER_X11_H +#include "drivers/gles_common/rasterizer_platforms.h" + #ifdef X11_ENABLED #include "servers/display_server.h" @@ -46,8 +48,8 @@ #include "servers/rendering/renderer_compositor.h" #include "servers/rendering_server.h" -#if defined(OPENGL_ENABLED) -#include "context_gl_x11.h" +#if defined(GLES_X11_ENABLED) +#include "gl_manager_x11.h" #endif #if defined(VULKAN_ENABLED) @@ -99,12 +101,12 @@ class DisplayServerX11 : public DisplayServer { Atom requested; int xdnd_version; -#if defined(OPENGL_ENABLED) - ContextGL_X11 *context_gles2; +#if defined(GLES_X11_ENABLED) + GLManager_X11 *gl_manager = nullptr; #endif #if defined(VULKAN_ENABLED) - VulkanContextX11 *context_vulkan; - RenderingDeviceVulkan *rendering_device_vulkan; + VulkanContextX11 *context_vulkan = nullptr; + RenderingDeviceVulkan *rendering_device_vulkan = nullptr; #endif #if defined(DBUS_ENABLED) @@ -337,6 +339,7 @@ public: virtual void window_set_max_size(const Size2i p_size, WindowID p_window = MAIN_WINDOW_ID) override; virtual Size2i window_get_max_size(WindowID p_window = MAIN_WINDOW_ID) const override; + virtual void gl_window_make_current(DisplayServer::WindowID p_window_id); virtual void window_set_transient(WindowID p_window, WindowID p_parent) override; diff --git a/platform/linuxbsd/context_gl_x11.cpp b/platform/linuxbsd/gl_manager_x11.cpp similarity index 50% rename from platform/linuxbsd/context_gl_x11.cpp rename to platform/linuxbsd/gl_manager_x11.cpp index 1f92370ab78..e3d12dcb019 100644 --- a/platform/linuxbsd/context_gl_x11.cpp +++ b/platform/linuxbsd/gl_manager_x11.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* context_gl_x11.cpp */ +/* gl_manager_x11.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,10 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "context_gl_x11.h" +#include "gl_manager_x11.h" #ifdef X11_ENABLED -#if defined(OPENGL_ENABLED) +#if defined(GLES_X11_ENABLED) + #include #include #include @@ -45,20 +46,17 @@ typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *); -struct ContextGL_X11_Private { +struct GLManager_X11_Private { ::GLXContext glx_context; }; -void ContextGL_X11::release_current() { - glXMakeCurrent(x11_display, None, nullptr); -} - -void ContextGL_X11::make_current() { - glXMakeCurrent(x11_display, x11_window, p->glx_context); -} - -void ContextGL_X11::swap_buffers() { - glXSwapBuffers(x11_display, x11_window); +GLManager_X11::GLDisplay::~GLDisplay() { + if (context) { + //release_current(); + glXDestroyContext(x11_display, context->glx_context); + memdelete(context); + context = nullptr; + } } static bool ctxErrorOccurred = false; @@ -67,20 +65,35 @@ static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { return 0; } -static void set_class_hint(Display *p_display, Window p_window) { - XClassHint *classHint; - - /* set the name and class hints for the window manager to use */ - classHint = XAllocClassHint(); - if (classHint) { - classHint->res_name = (char *)"Godot_Engine"; - classHint->res_class = (char *)"Godot"; +int GLManager_X11::_find_or_create_display(Display *p_x11_display) { + for (unsigned int n = 0; n < _displays.size(); n++) { + const GLDisplay &d = _displays[n]; + if (d.x11_display == p_x11_display) + return n; } - XSetClassHint(p_display, p_window, classHint); - XFree(classHint); + + // create + GLDisplay d_temp; + d_temp.x11_display = p_x11_display; + _displays.push_back(d_temp); + int new_display_id = _displays.size() - 1; + + // create context + GLDisplay &d = _displays[new_display_id]; + + d.context = memnew(GLManager_X11_Private); + ; + d.context->glx_context = 0; + + //Error err = _create_context(d); + _create_context(d); + return new_display_id; } -Error ContextGL_X11::initialize() { +Error GLManager_X11::_create_context(GLDisplay &gl_display) { + // some aliases + ::Display *x11_display = gl_display.x11_display; + //const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB"); @@ -114,10 +127,9 @@ Error ContextGL_X11::initialize() { GLXFBConfig fbconfig = 0; XVisualInfo *vi = nullptr; - XSetWindowAttributes swa; - swa.event_mask = StructureNotifyMask; - swa.border_pixel = 0; - unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask; + gl_display.x_swa.event_mask = StructureNotifyMask; + gl_display.x_swa.border_pixel = 0; + gl_display.x_valuemask = CWBorderPixel | CWColormap | CWEventMask; if (OS::get_singleton()->is_layered_allowed()) { GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs_layered, &fbcount); @@ -141,12 +153,13 @@ Error ContextGL_X11::initialize() { } } XFree(fbc); + ERR_FAIL_COND_V(!fbconfig, ERR_UNCONFIGURED); - swa.background_pixmap = None; - swa.background_pixel = 0; - swa.border_pixmap = None; - valuemask |= CWBackPixel; + gl_display.x_swa.background_pixmap = None; + gl_display.x_swa.background_pixel = 0; + gl_display.x_swa.border_pixmap = None; + gl_display.x_valuemask |= CWBackPixel; } else { GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount); @@ -162,52 +175,167 @@ Error ContextGL_X11::initialize() { switch (context_type) { case GLES_2_0_COMPATIBLE: { - p->glx_context = glXCreateNewContext(x11_display, fbconfig, GLX_RGBA_TYPE, 0, true); - ERR_FAIL_COND_V(!p->glx_context, ERR_UNCONFIGURED); + gl_display.context->glx_context = glXCreateNewContext(gl_display.x11_display, fbconfig, GLX_RGBA_TYPE, 0, true); + ERR_FAIL_COND_V(!gl_display.context->glx_context, ERR_UNCONFIGURED); } break; } - swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); - x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, valuemask, &swa); - XStoreName(x11_display, x11_window, "Godot Engine"); - - ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED); - set_class_hint(x11_display, x11_window); - XMapWindow(x11_display, x11_window); + gl_display.x_swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); XSync(x11_display, False); XSetErrorHandler(oldHandler); - glXMakeCurrent(x11_display, x11_window, p->glx_context); + // make our own copy of the vi data + // for later creating windows using this display + if (vi) { + gl_display.x_vi = *vi; + } XFree(vi); return OK; } -int ContextGL_X11::get_window_width() { - XWindowAttributes xwa; - XGetWindowAttributes(x11_display, x11_window, &xwa); +Error GLManager_X11::window_create(DisplayServer::WindowID p_window_id, ::Window p_window, Display *p_display, int p_width, int p_height) { + print_line("window_create window id " + itos(p_window_id)); - return xwa.width; + // make sure vector is big enough... + // we can mirror the external vector, it is simpler + // to keep the IDs identical for fast lookup + if (p_window_id >= (int)_windows.size()) { + _windows.resize(p_window_id + 1); + } + + GLWindow &win = _windows[p_window_id]; + win.in_use = true; + win.window_id = p_window_id; + win.width = p_width; + win.height = p_height; + win.x11_window = p_window; + win.gldisplay_id = _find_or_create_display(p_display); + + // the display could be invalid .. check NYI + GLDisplay &gl_display = _displays[win.gldisplay_id]; + //const XVisualInfo &vi = gl_display.x_vi; + //XSetWindowAttributes &swa = gl_display.x_swa; + ::Display *x11_display = gl_display.x11_display; + ::Window &x11_window = win.x11_window; + + if (!glXMakeCurrent(x11_display, x11_window, gl_display.context->glx_context)) { + ERR_PRINT("glXMakeCurrent failed"); + } + + _internal_set_current_window(&win); + + return OK; } -int ContextGL_X11::get_window_height() { - XWindowAttributes xwa; - XGetWindowAttributes(x11_display, x11_window, &xwa); +void GLManager_X11::_internal_set_current_window(GLWindow *p_win) { + _current_window = p_win; - return xwa.height; + // quick access to x info + _x_windisp.x11_window = _current_window->x11_window; + const GLDisplay &disp = get_current_display(); + _x_windisp.x11_display = disp.x11_display; } -void ContextGL_X11::set_use_vsync(bool p_use) { +void GLManager_X11::window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) { + get_window(p_window_id).width = p_width; + get_window(p_window_id).height = p_height; +} + +void GLManager_X11::window_destroy(DisplayServer::WindowID p_window_id) { + GLWindow &win = get_window(p_window_id); + win.in_use = false; + + if (_current_window == &win) { + _current_window = nullptr; + _x_windisp.x11_display = nullptr; + _x_windisp.x11_window = -1; + } +} + +void GLManager_X11::release_current() { + if (!_current_window) + return; + glXMakeCurrent(_x_windisp.x11_display, None, nullptr); +} + +void GLManager_X11::window_make_current(DisplayServer::WindowID p_window_id) { + if (p_window_id == -1) + return; + + GLWindow &win = _windows[p_window_id]; + if (!win.in_use) + return; + + // noop + if (&win == _current_window) + return; + + const GLDisplay &disp = get_display(win.gldisplay_id); + + glXMakeCurrent(disp.x11_display, win.x11_window, disp.context->glx_context); + + _internal_set_current_window(&win); +} + +void GLManager_X11::make_current() { + if (!_current_window) + return; + if (!_current_window->in_use) { + WARN_PRINT("current window not in use!"); + return; + } + const GLDisplay &disp = get_current_display(); + glXMakeCurrent(_x_windisp.x11_display, _x_windisp.x11_window, disp.context->glx_context); +} + +void GLManager_X11::swap_buffers() { + // NO NEED TO CALL SWAP BUFFERS for each window... + // see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glXSwapBuffers.xml + + if (!_current_window) + return; + if (!_current_window->in_use) { + WARN_PRINT("current window not in use!"); + return; + } + + // print_line("\tswap_buffers"); + + // only for debugging without drawing anything + // glClearColor(Math::randf(), 0, 1, 1); + //glClear(GL_COLOR_BUFFER_BIT); + + //const GLDisplay &disp = get_current_display(); + glXSwapBuffers(_x_windisp.x11_display, _x_windisp.x11_window); +} + +Error GLManager_X11::initialize() { + return OK; +} + +void GLManager_X11::set_use_vsync(bool p_use) { static bool setup = false; static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = nullptr; static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = nullptr; static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = nullptr; + // force vsync in the editor for now, as a safety measure + bool is_editor = Engine::get_singleton()->is_editor_hint(); + if (is_editor) { + p_use = true; + } + + // we need an active window to get a display to set the vsync + if (!_current_window) + return; + const GLDisplay &disp = get_current_display(); + if (!setup) { setup = true; - String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); + String extensions = glXQueryExtensionsString(disp.x11_display, DefaultScreen(disp.x11_display)); if (extensions.find("GLX_EXT_swap_control") != -1) glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT"); if (extensions.find("GLX_MESA_swap_control") != -1) @@ -222,35 +350,28 @@ void ContextGL_X11::set_use_vsync(bool p_use) { glXSwapIntervalSGI(val); } else if (glXSwapIntervalEXT) { GLXDrawable drawable = glXGetCurrentDrawable(); - glXSwapIntervalEXT(x11_display, drawable, val); + glXSwapIntervalEXT(disp.x11_display, drawable, val); } else return; use_vsync = p_use; } -bool ContextGL_X11::is_using_vsync() const { +bool GLManager_X11::is_using_vsync() const { return use_vsync; } -ContextGL_X11::ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, ContextType p_context_type) : - x11_window(p_x11_window) { - default_video_mode = p_default_video_mode; - x11_display = p_x11_display; - +GLManager_X11::GLManager_X11(const Vector2i &p_size, ContextType p_context_type) { context_type = p_context_type; double_buffer = false; direct_render = false; glx_minor = glx_major = 0; - p = memnew(ContextGL_X11_Private); - p->glx_context = 0; use_vsync = false; + _current_window = nullptr; } -ContextGL_X11::~ContextGL_X11() { +GLManager_X11::~GLManager_X11() { release_current(); - glXDestroyContext(x11_display, p->glx_context); - memdelete(p); } #endif diff --git a/platform/linuxbsd/gl_manager_x11.h b/platform/linuxbsd/gl_manager_x11.h new file mode 100644 index 00000000000..67813120748 --- /dev/null +++ b/platform/linuxbsd/gl_manager_x11.h @@ -0,0 +1,127 @@ +/*************************************************************************/ +/* gl_manager_x11.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#ifdef X11_ENABLED + +#include "drivers/gles_common/rasterizer_platforms.h" + +#if defined(GLES_X11_ENABLED) + +#include "core/os/os.h" +#include "core/templates/local_vector.h" +#include "servers/display_server.h" +#include +#include + +struct GLManager_X11_Private; + +class GLManager_X11 { +public: + enum ContextType { + GLES_2_0_COMPATIBLE, + }; + +private: + // any data specific to the window + struct GLWindow { + GLWindow() { in_use = false; } + bool in_use; + + // the external ID .. should match the GL window number .. unused I think + DisplayServer::WindowID window_id; + int width; + int height; + ::Window x11_window; + int gldisplay_id; + }; + + struct GLDisplay { + GLDisplay() { context = nullptr; } + ~GLDisplay(); + GLManager_X11_Private *context; + ::Display *x11_display; + XVisualInfo x_vi; + XSetWindowAttributes x_swa; + unsigned long x_valuemask; + }; + + // just for convenience, window and display struct + struct XWinDisp { + ::Window x11_window; + ::Display *x11_display; + } _x_windisp; + + LocalVector _windows; + LocalVector _displays; + + GLWindow *_current_window; + + void _internal_set_current_window(GLWindow *p_win); + + GLWindow &get_window(unsigned int id) { return _windows[id]; } + const GLWindow &get_window(unsigned int id) const { return _windows[id]; } + + const GLDisplay &get_current_display() const { return _displays[_current_window->gldisplay_id]; } + const GLDisplay &get_display(unsigned int id) { return _displays[id]; } + + bool double_buffer; + bool direct_render; + int glx_minor, glx_major; + bool use_vsync; + ContextType context_type; + +private: + int _find_or_create_display(Display *p_x11_display); + Error _create_context(GLDisplay &gl_display); + +public: + Error window_create(DisplayServer::WindowID p_window_id, ::Window p_window, Display *p_display, int p_width, int p_height); + void window_destroy(DisplayServer::WindowID p_window_id); + void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height); + + void release_current(); + void make_current(); + void swap_buffers(); + + void window_make_current(DisplayServer::WindowID p_window_id); + + Error initialize(); + + void set_use_vsync(bool p_use); + bool is_using_vsync() const; + + GLManager_X11(const Vector2i &p_size, ContextType p_context_type); + ~GLManager_X11(); +}; + +#endif // GLES_X11_ENABLED +#endif // X11_ENABLED diff --git a/platform/linuxbsd/platform_config.h b/platform/linuxbsd/platform_config.h index 3195d089356..cdf989fee7a 100644 --- a/platform/linuxbsd/platform_config.h +++ b/platform/linuxbsd/platform_config.h @@ -43,3 +43,6 @@ #define PTHREAD_BSD_SET_NAME #endif #endif + +#define GLES3_INCLUDE_H "thirdparty/glad/glad/glad.h" +#define GLES2_INCLUDE_H "thirdparty/glad/glad/glad.h" diff --git a/platform/osx/platform_config.h b/platform/osx/platform_config.h index 2d0fd872dc2..d36a72f9a14 100644 --- a/platform/osx/platform_config.h +++ b/platform/osx/platform_config.h @@ -30,4 +30,6 @@ #include +#define GLES3_INCLUDE_H "thirdparty/glad/glad/glad.h" +#define GLES2_INCLUDE_H "thirdparty/glad/glad/glad.h" #define PTHREAD_RENAME_SELF diff --git a/platform/windows/SCsub b/platform/windows/SCsub index 47d8e146806..76234c3065e 100644 --- a/platform/windows/SCsub +++ b/platform/windows/SCsub @@ -15,7 +15,7 @@ common_win = [ "joypad_windows.cpp", "windows_terminal_logger.cpp", "vulkan_context_win.cpp", - "context_gl_windows.cpp", + "gl_manager_windows.cpp", ] res_file = "godot_res.rc" diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 6752885f377..d8a1ff4c80f 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -453,8 +453,7 @@ def configure_mingw(env): if not env["use_volk"]: env.Append(LIBS=["vulkan"]) - ## TODO !!! Re-enable when OpenGLES Rendering Device is implemented !!! - # env.Append(CPPDEFINES=['OPENGL_ENABLED']) + env.Append(CPPDEFINES=["OPENGL_ENABLED"]) env.Append(LIBS=["opengl32"]) env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)]) diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 905c4142a88..4b09edabdbd 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -38,6 +38,10 @@ #include +#if defined(GLES_WINDOWS_ENABLED) +#include "drivers/gles2/rasterizer_gles2.h" +#endif + static String format_error_message(DWORD id) { LPWSTR messageBuffer = nullptr; size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, @@ -533,6 +537,11 @@ void DisplayServerWindows::delete_sub_window(WindowID p_window) { context_vulkan->window_destroy(p_window); } #endif +#ifdef GLES_WINDOWS_ENABLED + if (rendering_driver == "GLES2") { + gl_manager->window_destroy(p_window); + } +#endif if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[p_window].wtctx) { wintab_WTClose(windows[p_window].wtctx); @@ -542,6 +551,12 @@ void DisplayServerWindows::delete_sub_window(WindowID p_window) { windows.erase(p_window); } +void DisplayServerWindows::gl_window_make_current(DisplayServer::WindowID p_window_id) { +#if defined(GLES_WINDOWS_ENABLED) + gl_manager->window_make_current(p_window_id); +#endif +} + void DisplayServerWindows::window_attach_instance_id(ObjectID p_instance, WindowID p_window) { _THREAD_SAFE_METHOD_ @@ -812,6 +827,11 @@ void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_windo context_vulkan->window_resize(p_window, w, h); } #endif +#if defined(GLES_WINDOWS_ENABLED) + if (rendering_driver == "GLES2") { + gl_manager->window_resize(p_window, w, h); + } +#endif if (wd.fullscreen) { return; @@ -1591,6 +1611,9 @@ void DisplayServerWindows::make_rendering_thread() { } void DisplayServerWindows::swap_buffers() { +#if defined(GLES_WINDOWS_ENABLED) + gl_manager->swap_buffers(); +#endif } void DisplayServerWindows::set_native_icon(const String &p_filename) { @@ -3086,6 +3109,14 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, } #endif +#ifdef GLES_WINDOWS_ENABLED + print_line("rendering_driver " + rendering_driver); + if (rendering_driver == "GLES2") { + Error err = gl_manager->window_create(id, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top); + ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a GLES2 window"); + } +#endif + RegisterTouchWindow(wd.hWnd, 0); TRACKMOUSEEVENT tme; @@ -3292,7 +3323,10 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win use_raw_input = false; } - rendering_driver = "vulkan"; + // hard coded render drivers... + // rendering_driver = "vulkan"; + // rendering_driver = "GLES2"; + print_line("rendering_driver " + rendering_driver); #if defined(VULKAN_ENABLED) if (rendering_driver == "vulkan") { @@ -3305,7 +3339,35 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win } } #endif + // Init context and rendering device +#if defined(GLES_WINDOWS_ENABLED) + if (rendering_driver == "GLES2") { + GLManager_Windows::ContextType opengl_api_type = GLManager_Windows::GLES_2_0_COMPATIBLE; + + gl_manager = memnew(GLManager_Windows(opengl_api_type)); + + if (gl_manager->initialize() != OK) { + memdelete(gl_manager); + gl_manager = nullptr; + r_error = ERR_UNAVAILABLE; + return; + } + + // gl_manager->set_use_vsync(current_videomode.use_vsync); + + if (true) { + RasterizerGLES2::make_current(); + } else { + memdelete(gl_manager); + gl_manager = nullptr; + r_error = ERR_UNAVAILABLE; + return; + } + } +#endif + + /* #if defined(OPENGL_ENABLED) if (rendering_driver_index == VIDEO_DRIVER_GLES2) { context_gles2 = memnew(ContextGL_Windows(hWnd, false)); @@ -3328,7 +3390,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win } } #endif - + */ Point2i window_position( (screen_get_size(0).width - p_resolution.width) / 2, (screen_get_size(0).height - p_resolution.height) / 2); @@ -3386,8 +3448,8 @@ Vector DisplayServerWindows::get_rendering_drivers_func() { #ifdef VULKAN_ENABLED drivers.push_back("vulkan"); #endif -#ifdef OPENGL_ENABLED - drivers.push_back("opengl"); +#ifdef GLES_WINDOWS_ENABLED + drivers.push_back("GLES2"); #endif return drivers; @@ -3417,6 +3479,10 @@ DisplayServerWindows::~DisplayServerWindows() { SetWindowLongPtr(windows[MAIN_WINDOW_ID].hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc); }; +#ifdef GLES_WINDOWS_ENABLED + // destroy windows .. NYI? +#endif + if (windows.has(MAIN_WINDOW_ID)) { #ifdef VULKAN_ENABLED if (rendering_driver == "vulkan") { @@ -3445,4 +3511,10 @@ DisplayServerWindows::~DisplayServerWindows() { if (restore_mouse_trails > 1) { SystemParametersInfoA(SPI_SETMOUSETRAILS, restore_mouse_trails, 0, 0); } +#ifdef GLES_WINDOWS_ENABLED + if (gl_manager) { + memdelete(gl_manager); + gl_manager = nullptr; + } +#endif } diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 22c4f96a909..145c1472083 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -51,15 +51,15 @@ #include "drivers/xaudio2/audio_driver_xaudio2.h" #endif -#if defined(OPENGL_ENABLED) -#include "context_gl_windows.h" -#endif - #if defined(VULKAN_ENABLED) #include "drivers/vulkan/rendering_device_vulkan.h" #include "platform/windows/vulkan_context_win.h" #endif +#if defined(GLES_WINDOWS_ENABLED) +#include "gl_manager_windows.h" +#endif + #include #include #include @@ -304,8 +304,8 @@ class DisplayServerWindows : public DisplayServer { int old_x, old_y; Point2i center; -#if defined(OPENGL_ENABLED) - ContextGL_Windows *context_gles2; +#if defined(GLES_WINDOWS_ENABLED) + GLManager_Windows *gl_manager; #endif #if defined(VULKAN_ENABLED) @@ -477,6 +477,7 @@ public: virtual void window_attach_instance_id(ObjectID p_instance, WindowID p_window = MAIN_WINDOW_ID) override; virtual ObjectID window_get_attached_instance_id(WindowID p_window = MAIN_WINDOW_ID) const override; + virtual void gl_window_make_current(DisplayServer::WindowID p_window_id); virtual void window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window = MAIN_WINDOW_ID) override; diff --git a/platform/windows/gl_manager_windows.cpp b/platform/windows/gl_manager_windows.cpp new file mode 100644 index 00000000000..b6107088a25 --- /dev/null +++ b/platform/windows/gl_manager_windows.cpp @@ -0,0 +1,353 @@ +/*************************************************************************/ +/* gl_manager_windows.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "gl_manager_windows.h" + +#ifdef WINDOWS_ENABLED +#ifdef GLES_WINDOWS_ENABLED + +#include +#include + +#include + +#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 +#define WGL_CONTEXT_FLAGS_ARB 0x2094 +#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 +#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 +#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 + +#define _WGL_CONTEXT_DEBUG_BIT_ARB 0x0001 + +#if defined(__GNUC__) +// Workaround GCC warning from -Wcast-function-type. +#define wglGetProcAddress (void *)wglGetProcAddress +#endif + +typedef HGLRC(APIENTRY *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *); + +int GLManager_Windows::_find_or_create_display(GLWindow &win) { + // find display NYI, only 1 supported so far + if (_displays.size()) + return 0; + + // for (unsigned int n = 0; n < _displays.size(); n++) { + // const GLDisplay &d = _displays[n]; + // if (d.x11_display == p_x11_display) + // return n; + // } + + // create + GLDisplay d_temp; + _displays.push_back(d_temp); + int new_display_id = _displays.size() - 1; + + // create context + GLDisplay &d = _displays[new_display_id]; + Error err = _create_context(win, d); + + if (err != OK) { + // not good + // delete the _display? + _displays.remove(new_display_id); + return -1; + } + + return new_display_id; +} + +Error GLManager_Windows::_create_context(GLWindow &win, GLDisplay &gl_display) { + static PIXELFORMATDESCRIPTOR pfd = { + sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor + 1, + PFD_DRAW_TO_WINDOW | // Format Must Support Window + PFD_SUPPORT_OPENGL | // Format Must Support OpenGL + PFD_DOUBLEBUFFER, + (BYTE)PFD_TYPE_RGBA, + (BYTE)(OS::get_singleton()->is_layered_allowed() ? 32 : 24), + (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Color Bits Ignored + (BYTE)(OS::get_singleton()->is_layered_allowed() ? 8 : 0), // Alpha Buffer + (BYTE)0, // Shift Bit Ignored + (BYTE)0, // No Accumulation Buffer + (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Accumulation Bits Ignored + (BYTE)24, // 24Bit Z-Buffer (Depth Buffer) + (BYTE)0, // No Stencil Buffer + (BYTE)0, // No Auxiliary Buffer + (BYTE)PFD_MAIN_PLANE, // Main Drawing Layer + (BYTE)0, // Reserved + 0, 0, 0 // Layer Masks Ignored + }; + + // alias + HDC hDC = win.hDC; + + int pixel_format = ChoosePixelFormat(hDC, &pfd); + if (!pixel_format) // Did Windows Find A Matching Pixel Format? + { + return ERR_CANT_CREATE; // Return FALSE + } + + BOOL ret = SetPixelFormat(hDC, pixel_format, &pfd); + if (!ret) // Are We Able To Set The Pixel Format? + { + return ERR_CANT_CREATE; // Return FALSE + } + + gl_display.hRC = wglCreateContext(hDC); + if (!gl_display.hRC) // Are We Able To Get A Rendering Context? + { + return ERR_CANT_CREATE; // Return FALSE + } + + wglMakeCurrent(hDC, gl_display.hRC); + + if (opengl_3_context) { + int attribs[] = { + WGL_CONTEXT_MAJOR_VERSION_ARB, 3, //we want a 3.3 context + WGL_CONTEXT_MINOR_VERSION_ARB, 3, + //and it shall be forward compatible so that we can only use up to date functionality + WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, + WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB /*| _WGL_CONTEXT_DEBUG_BIT_ARB*/, + 0 + }; //zero indicates the end of the array + + PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = nullptr; //pointer to the method + wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); + + if (wglCreateContextAttribsARB == nullptr) //OpenGL 3.0 is not supported + { + wglDeleteContext(gl_display.hRC); + gl_display.hRC = 0; + return ERR_CANT_CREATE; + } + + HGLRC new_hRC = wglCreateContextAttribsARB(hDC, 0, attribs); + if (!new_hRC) { + wglDeleteContext(gl_display.hRC); + gl_display.hRC = 0; + return ERR_CANT_CREATE; // Return false + } + wglMakeCurrent(hDC, nullptr); + wglDeleteContext(gl_display.hRC); + gl_display.hRC = new_hRC; + + if (!wglMakeCurrent(hDC, gl_display.hRC)) // Try To Activate The Rendering Context + { + wglDeleteContext(gl_display.hRC); + gl_display.hRC = 0; + return ERR_CANT_CREATE; // Return FALSE + } + } + + return OK; +} + +Error GLManager_Windows::window_create(DisplayServer::WindowID p_window_id, HWND p_hwnd, HINSTANCE p_hinstance, int p_width, int p_height) { + print_line("window_create window id " + itos(p_window_id)); + + HDC hdc = GetDC(p_hwnd); + if (!hdc) { + return ERR_CANT_CREATE; // Return FALSE + } + + // make sure vector is big enough... + // we can mirror the external vector, it is simpler + // to keep the IDs identical for fast lookup + if (p_window_id >= (int)_windows.size()) { + _windows.resize(p_window_id + 1); + } + + GLWindow &win = _windows[p_window_id]; + win.in_use = true; + win.window_id = p_window_id; + win.width = p_width; + win.height = p_height; + win.hwnd = p_hwnd; + win.hDC = hdc; + + win.gldisplay_id = _find_or_create_display(win); + + if (win.gldisplay_id == -1) { + // release DC? + _windows.remove(_windows.size() - 1); + return FAILED; + } + + // the display could be invalid .. check NYI + GLDisplay &gl_display = _displays[win.gldisplay_id]; + + // make current + window_make_current(_windows.size() - 1); + + return OK; +} + +void GLManager_Windows::_internal_set_current_window(GLWindow *p_win) { + _current_window = p_win; +} + +void GLManager_Windows::window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) { + get_window(p_window_id).width = p_width; + get_window(p_window_id).height = p_height; +} + +int GLManager_Windows::window_get_width(DisplayServer::WindowID p_window_id) { + return get_window(p_window_id).width; +} + +int GLManager_Windows::window_get_height(DisplayServer::WindowID p_window_id) { + return get_window(p_window_id).height; +} + +void GLManager_Windows::window_destroy(DisplayServer::WindowID p_window_id) { + GLWindow &win = get_window(p_window_id); + win.in_use = false; + + if (_current_window == &win) { + _current_window = nullptr; + } +} + +void GLManager_Windows::release_current() { + if (!_current_window) + return; + + wglMakeCurrent(_current_window->hDC, nullptr); +} + +void GLManager_Windows::window_make_current(DisplayServer::WindowID p_window_id) { + if (p_window_id == -1) + return; + + GLWindow &win = _windows[p_window_id]; + if (!win.in_use) + return; + + // noop + if (&win == _current_window) + return; + + const GLDisplay &disp = get_display(win.gldisplay_id); + wglMakeCurrent(win.hDC, disp.hRC); + + _internal_set_current_window(&win); +} + +void GLManager_Windows::make_current() { + if (!_current_window) + return; + if (!_current_window->in_use) { + WARN_PRINT("current window not in use!"); + return; + } + const GLDisplay &disp = get_current_display(); + wglMakeCurrent(_current_window->hDC, disp.hRC); +} + +void GLManager_Windows::swap_buffers() { + // NO NEED TO CALL SWAP BUFFERS for each window... + // see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glXSwapBuffers.xml + + if (!_current_window) + return; + if (!_current_window->in_use) { + WARN_PRINT("current window not in use!"); + return; + } + + // print_line("\tswap_buffers"); + + // only for debugging without drawing anything + // glClearColor(Math::randf(), 0, 1, 1); + //glClear(GL_COLOR_BUFFER_BIT); + + // const GLDisplay &disp = get_current_display(); + SwapBuffers(_current_window->hDC); +} + +Error GLManager_Windows::initialize() { + wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); + wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC)wglGetProcAddress("wglGetSwapIntervalEXT"); + //glWrapperInit(wrapper_get_proc_address); + + return OK; +} + +void GLManager_Windows::set_use_vsync(bool p_use) { + /* + static bool setup = false; + static PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalMESA = nullptr; + static PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = nullptr; + + if (!setup) { + setup = true; + String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); + if (extensions.find("GLX_EXT_swap_control") != -1) + glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT"); + if (extensions.find("GLX_MESA_swap_control") != -1) + glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA"); + if (extensions.find("GLX_SGI_swap_control") != -1) + glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalSGI"); + } + int val = p_use ? 1 : 0; + if (glXSwapIntervalMESA) { + glXSwapIntervalMESA(val); + } else if (glXSwapIntervalSGI) { + glXSwapIntervalSGI(val); + } else if (glXSwapIntervalEXT) { + GLXDrawable drawable = glXGetCurrentDrawable(); + glXSwapIntervalEXT(x11_display, drawable, val); + } else + return; + use_vsync = p_use; + */ +} + +bool GLManager_Windows::is_using_vsync() const { + return use_vsync; +} + +GLManager_Windows::GLManager_Windows(ContextType p_context_type) { + context_type = p_context_type; + + direct_render = false; + glx_minor = glx_major = 0; + use_vsync = false; + _current_window = nullptr; +} + +GLManager_Windows::~GLManager_Windows() { + release_current(); +} + +#endif // OPENGL_ENABLED +#endif // WINDOWS diff --git a/platform/windows/gl_manager_windows.h b/platform/windows/gl_manager_windows.h new file mode 100644 index 00000000000..7d0aa0d6249 --- /dev/null +++ b/platform/windows/gl_manager_windows.h @@ -0,0 +1,129 @@ +/*************************************************************************/ +/* gl_manager_windows.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#pragma once + +#ifdef WINDOWS_ENABLED + +#ifdef GLES_WINDOWS_ENABLED + +#include "core/error/error_list.h" +#include "core/os/os.h" +#include "core/templates/local_vector.h" +#include "servers/display_server.h" + +#include + +typedef bool(APIENTRY *PFNWGLSWAPINTERVALEXTPROC)(int interval); +typedef int(APIENTRY *PFNWGLGETSWAPINTERVALEXTPROC)(void); + +class GLManager_Windows { +public: + enum ContextType { + GLES_2_0_COMPATIBLE, + }; + +private: + // any data specific to the window + struct GLWindow { + GLWindow() { in_use = false; } + bool in_use; + + // the external ID .. should match the GL window number .. unused I think + DisplayServer::WindowID window_id; + int width; + int height; + + // windows specific + HDC hDC; + HWND hwnd; + + int gldisplay_id; + }; + + struct GLDisplay { + // windows specific + HGLRC hRC; + }; + + LocalVector _windows; + LocalVector _displays; + + GLWindow *_current_window; + bool opengl_3_context = false; + + PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; + PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT; + + // funcs + void _internal_set_current_window(GLWindow *p_win); + + GLWindow &get_window(unsigned int id) { return _windows[id]; } + const GLWindow &get_window(unsigned int id) const { return _windows[id]; } + + const GLDisplay &get_current_display() const { return _displays[_current_window->gldisplay_id]; } + const GLDisplay &get_display(unsigned int id) { return _displays[id]; } + + bool direct_render; + int glx_minor, glx_major; + bool use_vsync; + ContextType context_type; + +private: + int _find_or_create_display(GLWindow &win); + Error _create_context(GLWindow &win, GLDisplay &gl_display); + +public: + Error window_create(DisplayServer::WindowID p_window_id, HWND p_hwnd, HINSTANCE p_hinstance, int p_width, int p_height); + void window_destroy(DisplayServer::WindowID p_window_id); + void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height); + + // get directly from the cached GLWindow + int window_get_width(DisplayServer::WindowID p_window_id = 0); + int window_get_height(DisplayServer::WindowID p_window_id = 0); + + void release_current(); + void make_current(); + void swap_buffers(); + + void window_make_current(DisplayServer::WindowID p_window_id); + + Error initialize(); + + void set_use_vsync(bool p_use); + bool is_using_vsync() const; + + GLManager_Windows(ContextType p_context_type); + ~GLManager_Windows(); +}; + +#endif // OPENGL_ENABLED + +#endif // WINDOWS diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index b8eca956c8a..1342d95575b 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -46,10 +46,6 @@ #include "drivers/xaudio2/audio_driver_xaudio2.h" #endif -#if defined(OPENGL_ENABLED) -#include "context_gl_windows.h" -#endif - #if defined(VULKAN_ENABLED) #include "drivers/vulkan/rendering_device_vulkan.h" #include "platform/windows/vulkan_context_win.h" diff --git a/platform/windows/platform_config.h b/platform/windows/platform_config.h index 481f583f6ff..87e1743d49a 100644 --- a/platform/windows/platform_config.h +++ b/platform/windows/platform_config.h @@ -29,3 +29,6 @@ /*************************************************************************/ #include + +#define GLES3_INCLUDE_H "thirdparty/glad/glad/glad.h" +#define GLES2_INCLUDE_H "thirdparty/glad/glad/glad.h" diff --git a/servers/display_server.cpp b/servers/display_server.cpp index 3fb47e8f054..7bf5673663c 100644 --- a/servers/display_server.cpp +++ b/servers/display_server.cpp @@ -208,6 +208,10 @@ void DisplayServer::window_set_mouse_passthrough(const Vector &p_region ERR_FAIL_MSG("Mouse passthrough not supported by this display server."); } +void DisplayServer::gl_window_make_current(DisplayServer::WindowID p_window_id) { + // noop except in gles +} + void DisplayServer::window_set_ime_active(const bool p_active, WindowID p_window) { WARN_PRINT("IME not supported by this display server."); } diff --git a/servers/display_server.h b/servers/display_server.h index 2595cf2eb82..2d837dbef90 100644 --- a/servers/display_server.h +++ b/servers/display_server.h @@ -298,6 +298,9 @@ public: virtual void window_set_ime_active(const bool p_active, WindowID p_window = MAIN_WINDOW_ID); virtual void window_set_ime_position(const Point2i &p_pos, WindowID p_window = MAIN_WINDOW_ID); + // necessary for GL focus, may be able to use one of the existing functions for this, not sure yet + virtual void gl_window_make_current(DisplayServer::WindowID p_window_id); + virtual Point2i ime_get_selection() const; virtual String ime_get_text() const; diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp index 84219385073..e338e526a07 100644 --- a/servers/rendering/renderer_scene_cull.cpp +++ b/servers/rendering/renderer_scene_cull.cpp @@ -3855,6 +3855,10 @@ void RendererSceneCull::update() { } bool RendererSceneCull::free(RID p_rid) { + if (p_rid.is_null()) { + return true; + } + if (scene_render->free(p_rid)) { return true; } diff --git a/servers/rendering/renderer_viewport.cpp b/servers/rendering/renderer_viewport.cpp index 347238cdaac..f312c2501fd 100644 --- a/servers/rendering/renderer_viewport.cpp +++ b/servers/rendering/renderer_viewport.cpp @@ -129,6 +129,9 @@ void RendererViewport::_draw_viewport(Viewport *p_viewport) { timestamp_vp_map[rt_id] = p_viewport->self; } + // This is currently needed for GLES to keep the current window being rendered to up to date + DisplayServer::get_singleton()->gl_window_make_current(p_viewport->viewport_to_screen); + /* Camera should always be BEFORE any other 3D */ bool scenario_draw_canvas_bg = false; //draw canvas, or some layer of it, as BG for 3D instead of in front diff --git a/thirdparty/glad/KHR/khrplatform.h b/thirdparty/glad/KHR/khrplatform.h new file mode 100644 index 00000000000..dd22d927018 --- /dev/null +++ b/thirdparty/glad/KHR/khrplatform.h @@ -0,0 +1,290 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) +# define KHRONOS_STATIC 1 +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(KHRONOS_STATIC) + /* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +# define KHRONOS_APICALL +#elif defined(_WIN32) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/thirdparty/glad/LICENSE b/thirdparty/glad/LICENSE new file mode 100644 index 00000000000..b6e2ca25b08 --- /dev/null +++ b/thirdparty/glad/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2018 David Herberth + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/thirdparty/glad/glad.c b/thirdparty/glad/glad.c new file mode 100644 index 00000000000..dc1b8cb697e --- /dev/null +++ b/thirdparty/glad/glad.c @@ -0,0 +1,1939 @@ +/* + + OpenGL loader generated by glad 0.1.34 on Tue Nov 17 16:41:02 2020. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=3.3 + Profile: compatibility + Extensions: + GL_ARB_debug_output, + GL_ARB_framebuffer_object, + GL_EXT_framebuffer_blit, + GL_EXT_framebuffer_multisample, + GL_EXT_framebuffer_object + Loader: True + Local files: False + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object +*/ + +#include +#include +#include +#include + +static void* get_proc(const char *namez); + +#if defined(_WIN32) || defined(__CYGWIN__) +#ifndef _WINDOWS_ +#undef APIENTRY +#endif +#include +static HMODULE libGL; + +typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); +static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; + +#ifdef _MSC_VER +#ifdef __has_include + #if __has_include() + #define HAVE_WINAPIFAMILY 1 + #endif +#elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ + #define HAVE_WINAPIFAMILY 1 +#endif +#endif + +#ifdef HAVE_WINAPIFAMILY + #include + #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + #define IS_UWP 1 + #endif +#endif + +static +int open_gl(void) { +#ifndef IS_UWP + libGL = LoadLibraryW(L"opengl32.dll"); + if(libGL != NULL) { + void (* tmp)(void); + tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress"); + gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp; + return gladGetProcAddressPtr != NULL; + } +#endif + + return 0; +} + +static +void close_gl(void) { + if(libGL != NULL) { + FreeLibrary((HMODULE) libGL); + libGL = NULL; + } +} +#else +#include +static void* libGL; + +#if !defined(__APPLE__) && !defined(__HAIKU__) +typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); +static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; +#endif + +static +int open_gl(void) { +#ifdef __APPLE__ + static const char *NAMES[] = { + "../Frameworks/OpenGL.framework/OpenGL", + "/Library/Frameworks/OpenGL.framework/OpenGL", + "/System/Library/Frameworks/OpenGL.framework/OpenGL", + "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" + }; +#else + static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; +#endif + + unsigned int index = 0; + for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { + libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); + + if(libGL != NULL) { +#if defined(__APPLE__) || defined(__HAIKU__) + return 1; +#else + gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, + "glXGetProcAddressARB"); + return gladGetProcAddressPtr != NULL; +#endif + } + } + + return 0; +} + +static +void close_gl(void) { + if(libGL != NULL) { + dlclose(libGL); + libGL = NULL; + } +} +#endif + +static +void* get_proc(const char *namez) { + void* result = NULL; + if(libGL == NULL) return NULL; + +#if !defined(__APPLE__) && !defined(__HAIKU__) + if(gladGetProcAddressPtr != NULL) { + result = gladGetProcAddressPtr(namez); + } +#endif + if(result == NULL) { +#if defined(_WIN32) || defined(__CYGWIN__) + result = (void*)GetProcAddress((HMODULE) libGL, namez); +#else + result = dlsym(libGL, namez); +#endif + } + + return result; +} + +int gladLoadGL(void) { + int status = 0; + + if(open_gl()) { + status = gladLoadGLLoader(&get_proc); + close_gl(); + } + + return status; +} + +struct gladGLversionStruct GLVersion = { 0, 0 }; + +#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) +#define _GLAD_IS_SOME_NEW_VERSION 1 +#endif + +static int max_loaded_major; +static int max_loaded_minor; + +static const char *exts = NULL; +static int num_exts_i = 0; +static char **exts_i = NULL; + +static int get_exts(void) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + exts = (const char *)glGetString(GL_EXTENSIONS); +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + unsigned int index; + + num_exts_i = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); + if (num_exts_i > 0) { + exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i)); + } + + if (exts_i == NULL) { + return 0; + } + + for(index = 0; index < (unsigned)num_exts_i; index++) { + const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); + size_t len = strlen(gl_str_tmp); + + char *local_str = (char*)malloc((len+1) * sizeof(char)); + if(local_str != NULL) { + memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); + } + exts_i[index] = local_str; + } + } +#endif + return 1; +} + +static void free_exts(void) { + if (exts_i != NULL) { + int index; + for(index = 0; index < num_exts_i; index++) { + free((char *)exts_i[index]); + } + free((void *)exts_i); + exts_i = NULL; + } +} + +static int has_ext(const char *ext) { +#ifdef _GLAD_IS_SOME_NEW_VERSION + if(max_loaded_major < 3) { +#endif + const char *extensions; + const char *loc; + const char *terminator; + extensions = exts; + if(extensions == NULL || ext == NULL) { + return 0; + } + + while(1) { + loc = strstr(extensions, ext); + if(loc == NULL) { + return 0; + } + + terminator = loc + strlen(ext); + if((loc == extensions || *(loc - 1) == ' ') && + (*terminator == ' ' || *terminator == '\0')) { + return 1; + } + extensions = terminator; + } +#ifdef _GLAD_IS_SOME_NEW_VERSION + } else { + int index; + if(exts_i == NULL) return 0; + for(index = 0; index < num_exts_i; index++) { + const char *e = exts_i[index]; + + if(exts_i[index] != NULL && strcmp(e, ext) == 0) { + return 1; + } + } + } +#endif + + return 0; +} +int GLAD_GL_VERSION_1_0 = 0; +int GLAD_GL_VERSION_1_1 = 0; +int GLAD_GL_VERSION_1_2 = 0; +int GLAD_GL_VERSION_1_3 = 0; +int GLAD_GL_VERSION_1_4 = 0; +int GLAD_GL_VERSION_1_5 = 0; +int GLAD_GL_VERSION_2_0 = 0; +int GLAD_GL_VERSION_2_1 = 0; +int GLAD_GL_VERSION_3_0 = 0; +int GLAD_GL_VERSION_3_1 = 0; +int GLAD_GL_VERSION_3_2 = 0; +int GLAD_GL_VERSION_3_3 = 0; +PFNGLACCUMPROC glad_glAccum = NULL; +PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; +PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; +PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; +PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; +PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; +PFNGLBEGINPROC glad_glBegin = NULL; +PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL; +PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; +PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL; +PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; +PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; +PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL; +PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL; +PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; +PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; +PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; +PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; +PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; +PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; +PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; +PFNGLBITMAPPROC glad_glBitmap = NULL; +PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; +PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; +PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; +PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; +PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; +PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; +PFNGLBUFFERDATAPROC glad_glBufferData = NULL; +PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; +PFNGLCALLLISTPROC glad_glCallList = NULL; +PFNGLCALLLISTSPROC glad_glCallLists = NULL; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; +PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; +PFNGLCLEARPROC glad_glClear = NULL; +PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; +PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL; +PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL; +PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL; +PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL; +PFNGLCLEARCOLORPROC glad_glClearColor = NULL; +PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; +PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; +PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; +PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; +PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL; +PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; +PFNGLCOLOR3BPROC glad_glColor3b = NULL; +PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; +PFNGLCOLOR3DPROC glad_glColor3d = NULL; +PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; +PFNGLCOLOR3FPROC glad_glColor3f = NULL; +PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; +PFNGLCOLOR3IPROC glad_glColor3i = NULL; +PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; +PFNGLCOLOR3SPROC glad_glColor3s = NULL; +PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; +PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; +PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; +PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; +PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; +PFNGLCOLOR3USPROC glad_glColor3us = NULL; +PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; +PFNGLCOLOR4BPROC glad_glColor4b = NULL; +PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; +PFNGLCOLOR4DPROC glad_glColor4d = NULL; +PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; +PFNGLCOLOR4FPROC glad_glColor4f = NULL; +PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; +PFNGLCOLOR4IPROC glad_glColor4i = NULL; +PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; +PFNGLCOLOR4SPROC glad_glColor4s = NULL; +PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; +PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; +PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; +PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; +PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; +PFNGLCOLOR4USPROC glad_glColor4us = NULL; +PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; +PFNGLCOLORMASKPROC glad_glColorMask = NULL; +PFNGLCOLORMASKIPROC glad_glColorMaski = NULL; +PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; +PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL; +PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL; +PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL; +PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL; +PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; +PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; +PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; +PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; +PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; +PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL; +PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; +PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; +PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; +PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; +PFNGLCREATESHADERPROC glad_glCreateShader = NULL; +PFNGLCULLFACEPROC glad_glCullFace = NULL; +PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; +PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; +PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; +PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; +PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; +PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; +PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL; +PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; +PFNGLDELETESYNCPROC glad_glDeleteSync = NULL; +PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; +PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; +PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; +PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; +PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; +PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; +PFNGLDISABLEPROC glad_glDisable = NULL; +PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; +PFNGLDISABLEIPROC glad_glDisablei = NULL; +PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; +PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL; +PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; +PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; +PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; +PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL; +PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; +PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; +PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; +PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; +PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; +PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; +PFNGLENABLEPROC glad_glEnable = NULL; +PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; +PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; +PFNGLENABLEIPROC glad_glEnablei = NULL; +PFNGLENDPROC glad_glEnd = NULL; +PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL; +PFNGLENDLISTPROC glad_glEndList = NULL; +PFNGLENDQUERYPROC glad_glEndQuery = NULL; +PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL; +PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; +PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; +PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; +PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; +PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; +PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; +PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; +PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; +PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; +PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; +PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; +PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; +PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; +PFNGLFENCESYNCPROC glad_glFenceSync = NULL; +PFNGLFINISHPROC glad_glFinish = NULL; +PFNGLFLUSHPROC glad_glFlush = NULL; +PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL; +PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; +PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; +PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; +PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; +PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; +PFNGLFOGFPROC glad_glFogf = NULL; +PFNGLFOGFVPROC glad_glFogfv = NULL; +PFNGLFOGIPROC glad_glFogi = NULL; +PFNGLFOGIVPROC glad_glFogiv = NULL; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; +PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL; +PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; +PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; +PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; +PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; +PFNGLFRONTFACEPROC glad_glFrontFace = NULL; +PFNGLFRUSTUMPROC glad_glFrustum = NULL; +PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; +PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; +PFNGLGENLISTSPROC glad_glGenLists = NULL; +PFNGLGENQUERIESPROC glad_glGenQueries = NULL; +PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; +PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL; +PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; +PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; +PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; +PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; +PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; +PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL; +PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL; +PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL; +PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL; +PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; +PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; +PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL; +PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; +PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL; +PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; +PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; +PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; +PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; +PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; +PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; +PFNGLGETERRORPROC glad_glGetError = NULL; +PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; +PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL; +PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; +PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; +PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; +PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; +PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; +PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; +PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; +PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; +PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; +PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; +PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; +PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; +PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL; +PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; +PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; +PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; +PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; +PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; +PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; +PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL; +PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; +PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL; +PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; +PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; +PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; +PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL; +PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL; +PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL; +PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL; +PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; +PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; +PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; +PFNGLGETSTRINGPROC glad_glGetString = NULL; +PFNGLGETSTRINGIPROC glad_glGetStringi = NULL; +PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL; +PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; +PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; +PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; +PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; +PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; +PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; +PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; +PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; +PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL; +PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL; +PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; +PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL; +PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL; +PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL; +PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; +PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; +PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; +PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL; +PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL; +PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL; +PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; +PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; +PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; +PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; +PFNGLHINTPROC glad_glHint = NULL; +PFNGLINDEXMASKPROC glad_glIndexMask = NULL; +PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; +PFNGLINDEXDPROC glad_glIndexd = NULL; +PFNGLINDEXDVPROC glad_glIndexdv = NULL; +PFNGLINDEXFPROC glad_glIndexf = NULL; +PFNGLINDEXFVPROC glad_glIndexfv = NULL; +PFNGLINDEXIPROC glad_glIndexi = NULL; +PFNGLINDEXIVPROC glad_glIndexiv = NULL; +PFNGLINDEXSPROC glad_glIndexs = NULL; +PFNGLINDEXSVPROC glad_glIndexsv = NULL; +PFNGLINDEXUBPROC glad_glIndexub = NULL; +PFNGLINDEXUBVPROC glad_glIndexubv = NULL; +PFNGLINITNAMESPROC glad_glInitNames = NULL; +PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; +PFNGLISBUFFERPROC glad_glIsBuffer = NULL; +PFNGLISENABLEDPROC glad_glIsEnabled = NULL; +PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL; +PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; +PFNGLISLISTPROC glad_glIsList = NULL; +PFNGLISPROGRAMPROC glad_glIsProgram = NULL; +PFNGLISQUERYPROC glad_glIsQuery = NULL; +PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; +PFNGLISSAMPLERPROC glad_glIsSampler = NULL; +PFNGLISSHADERPROC glad_glIsShader = NULL; +PFNGLISSYNCPROC glad_glIsSync = NULL; +PFNGLISTEXTUREPROC glad_glIsTexture = NULL; +PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL; +PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; +PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; +PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; +PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; +PFNGLLIGHTFPROC glad_glLightf = NULL; +PFNGLLIGHTFVPROC glad_glLightfv = NULL; +PFNGLLIGHTIPROC glad_glLighti = NULL; +PFNGLLIGHTIVPROC glad_glLightiv = NULL; +PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; +PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; +PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; +PFNGLLISTBASEPROC glad_glListBase = NULL; +PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; +PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; +PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; +PFNGLLOADNAMEPROC glad_glLoadName = NULL; +PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; +PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; +PFNGLLOGICOPPROC glad_glLogicOp = NULL; +PFNGLMAP1DPROC glad_glMap1d = NULL; +PFNGLMAP1FPROC glad_glMap1f = NULL; +PFNGLMAP2DPROC glad_glMap2d = NULL; +PFNGLMAP2FPROC glad_glMap2f = NULL; +PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; +PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL; +PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; +PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; +PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; +PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; +PFNGLMATERIALFPROC glad_glMaterialf = NULL; +PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; +PFNGLMATERIALIPROC glad_glMateriali = NULL; +PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; +PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; +PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; +PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; +PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; +PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; +PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; +PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; +PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL; +PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; +PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; +PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; +PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; +PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; +PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; +PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; +PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; +PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; +PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; +PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; +PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; +PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; +PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; +PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; +PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; +PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; +PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; +PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; +PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; +PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; +PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; +PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; +PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; +PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; +PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; +PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; +PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; +PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; +PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; +PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; +PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; +PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL; +PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL; +PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL; +PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL; +PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL; +PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL; +PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL; +PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL; +PFNGLNEWLISTPROC glad_glNewList = NULL; +PFNGLNORMAL3BPROC glad_glNormal3b = NULL; +PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; +PFNGLNORMAL3DPROC glad_glNormal3d = NULL; +PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; +PFNGLNORMAL3FPROC glad_glNormal3f = NULL; +PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; +PFNGLNORMAL3IPROC glad_glNormal3i = NULL; +PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; +PFNGLNORMAL3SPROC glad_glNormal3s = NULL; +PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; +PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL; +PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL; +PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; +PFNGLORTHOPROC glad_glOrtho = NULL; +PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; +PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; +PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; +PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; +PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; +PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; +PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; +PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; +PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; +PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; +PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; +PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; +PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; +PFNGLPOINTSIZEPROC glad_glPointSize = NULL; +PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; +PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; +PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; +PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; +PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; +PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; +PFNGLPOPNAMEPROC glad_glPopName = NULL; +PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL; +PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; +PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL; +PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; +PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; +PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; +PFNGLPUSHNAMEPROC glad_glPushName = NULL; +PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL; +PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; +PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; +PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; +PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; +PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; +PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; +PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; +PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; +PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; +PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; +PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; +PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; +PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; +PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; +PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; +PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; +PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; +PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; +PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; +PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; +PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; +PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; +PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; +PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; +PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; +PFNGLREADPIXELSPROC glad_glReadPixels = NULL; +PFNGLRECTDPROC glad_glRectd = NULL; +PFNGLRECTDVPROC glad_glRectdv = NULL; +PFNGLRECTFPROC glad_glRectf = NULL; +PFNGLRECTFVPROC glad_glRectfv = NULL; +PFNGLRECTIPROC glad_glRecti = NULL; +PFNGLRECTIVPROC glad_glRectiv = NULL; +PFNGLRECTSPROC glad_glRects = NULL; +PFNGLRECTSVPROC glad_glRectsv = NULL; +PFNGLRENDERMODEPROC glad_glRenderMode = NULL; +PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; +PFNGLROTATEDPROC glad_glRotated = NULL; +PFNGLROTATEFPROC glad_glRotatef = NULL; +PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; +PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL; +PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL; +PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL; +PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL; +PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL; +PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL; +PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL; +PFNGLSCALEDPROC glad_glScaled = NULL; +PFNGLSCALEFPROC glad_glScalef = NULL; +PFNGLSCISSORPROC glad_glScissor = NULL; +PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; +PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; +PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; +PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; +PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; +PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; +PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; +PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; +PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; +PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; +PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; +PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; +PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; +PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; +PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; +PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; +PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL; +PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL; +PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; +PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; +PFNGLSHADEMODELPROC glad_glShadeModel = NULL; +PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; +PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; +PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; +PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; +PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; +PFNGLSTENCILOPPROC glad_glStencilOp = NULL; +PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; +PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL; +PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; +PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; +PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; +PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; +PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; +PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; +PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; +PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; +PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; +PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; +PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; +PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; +PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; +PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; +PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; +PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; +PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; +PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; +PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; +PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; +PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; +PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; +PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; +PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; +PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; +PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; +PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; +PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; +PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; +PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; +PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; +PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; +PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL; +PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL; +PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL; +PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL; +PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL; +PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL; +PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL; +PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL; +PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; +PFNGLTEXENVFPROC glad_glTexEnvf = NULL; +PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; +PFNGLTEXENVIPROC glad_glTexEnvi = NULL; +PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; +PFNGLTEXGENDPROC glad_glTexGend = NULL; +PFNGLTEXGENDVPROC glad_glTexGendv = NULL; +PFNGLTEXGENFPROC glad_glTexGenf = NULL; +PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; +PFNGLTEXGENIPROC glad_glTexGeni = NULL; +PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; +PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; +PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; +PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL; +PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; +PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL; +PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL; +PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL; +PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; +PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; +PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; +PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; +PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; +PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; +PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; +PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL; +PFNGLTRANSLATEDPROC glad_glTranslated = NULL; +PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; +PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; +PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; +PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; +PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; +PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL; +PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL; +PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; +PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; +PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; +PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; +PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL; +PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL; +PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; +PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; +PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; +PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; +PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL; +PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL; +PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; +PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; +PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; +PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; +PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL; +PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL; +PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL; +PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; +PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; +PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; +PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; +PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; +PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; +PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; +PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; +PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; +PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; +PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; +PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; +PFNGLVERTEX2DPROC glad_glVertex2d = NULL; +PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; +PFNGLVERTEX2FPROC glad_glVertex2f = NULL; +PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; +PFNGLVERTEX2IPROC glad_glVertex2i = NULL; +PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; +PFNGLVERTEX2SPROC glad_glVertex2s = NULL; +PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; +PFNGLVERTEX3DPROC glad_glVertex3d = NULL; +PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; +PFNGLVERTEX3FPROC glad_glVertex3f = NULL; +PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; +PFNGLVERTEX3IPROC glad_glVertex3i = NULL; +PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; +PFNGLVERTEX3SPROC glad_glVertex3s = NULL; +PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; +PFNGLVERTEX4DPROC glad_glVertex4d = NULL; +PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; +PFNGLVERTEX4FPROC glad_glVertex4f = NULL; +PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; +PFNGLVERTEX4IPROC glad_glVertex4i = NULL; +PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; +PFNGLVERTEX4SPROC glad_glVertex4s = NULL; +PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; +PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; +PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; +PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; +PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; +PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; +PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; +PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; +PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; +PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; +PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; +PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; +PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; +PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; +PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; +PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; +PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; +PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; +PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; +PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; +PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; +PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; +PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; +PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; +PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; +PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; +PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; +PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; +PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; +PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; +PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; +PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; +PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; +PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; +PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; +PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; +PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; +PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL; +PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL; +PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL; +PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL; +PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL; +PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL; +PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL; +PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL; +PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL; +PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL; +PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL; +PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL; +PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL; +PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL; +PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL; +PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL; +PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL; +PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL; +PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL; +PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL; +PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL; +PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL; +PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL; +PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL; +PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL; +PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL; +PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL; +PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL; +PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL; +PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL; +PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; +PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL; +PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL; +PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL; +PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL; +PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL; +PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL; +PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; +PFNGLVIEWPORTPROC glad_glViewport = NULL; +PFNGLWAITSYNCPROC glad_glWaitSync = NULL; +PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; +PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; +PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; +PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; +PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; +PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; +PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; +PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; +PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; +PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; +PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; +PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; +PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; +PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; +PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; +PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; +int GLAD_GL_ARB_debug_output = 0; +int GLAD_GL_ARB_framebuffer_object = 0; +int GLAD_GL_EXT_framebuffer_blit = 0; +int GLAD_GL_EXT_framebuffer_multisample = 0; +int GLAD_GL_EXT_framebuffer_object = 0; +PFNGLDEBUGMESSAGECONTROLARBPROC glad_glDebugMessageControlARB = NULL; +PFNGLDEBUGMESSAGEINSERTARBPROC glad_glDebugMessageInsertARB = NULL; +PFNGLDEBUGMESSAGECALLBACKARBPROC glad_glDebugMessageCallbackARB = NULL; +PFNGLGETDEBUGMESSAGELOGARBPROC glad_glGetDebugMessageLogARB = NULL; +PFNGLBLITFRAMEBUFFEREXTPROC glad_glBlitFramebufferEXT = NULL; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glad_glRenderbufferStorageMultisampleEXT = NULL; +PFNGLISRENDERBUFFEREXTPROC glad_glIsRenderbufferEXT = NULL; +PFNGLBINDRENDERBUFFEREXTPROC glad_glBindRenderbufferEXT = NULL; +PFNGLDELETERENDERBUFFERSEXTPROC glad_glDeleteRenderbuffersEXT = NULL; +PFNGLGENRENDERBUFFERSEXTPROC glad_glGenRenderbuffersEXT = NULL; +PFNGLRENDERBUFFERSTORAGEEXTPROC glad_glRenderbufferStorageEXT = NULL; +PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glad_glGetRenderbufferParameterivEXT = NULL; +PFNGLISFRAMEBUFFEREXTPROC glad_glIsFramebufferEXT = NULL; +PFNGLBINDFRAMEBUFFEREXTPROC glad_glBindFramebufferEXT = NULL; +PFNGLDELETEFRAMEBUFFERSEXTPROC glad_glDeleteFramebuffersEXT = NULL; +PFNGLGENFRAMEBUFFERSEXTPROC glad_glGenFramebuffersEXT = NULL; +PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glad_glCheckFramebufferStatusEXT = NULL; +PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glad_glFramebufferTexture1DEXT = NULL; +PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glad_glFramebufferTexture2DEXT = NULL; +PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glad_glFramebufferTexture3DEXT = NULL; +PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glad_glFramebufferRenderbufferEXT = NULL; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glad_glGetFramebufferAttachmentParameterivEXT = NULL; +PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT = NULL; +static void load_GL_VERSION_1_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_0) return; + glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); + glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); + glad_glHint = (PFNGLHINTPROC)load("glHint"); + glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); + glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); + glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); + glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); + glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); + glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); + glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); + glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); + glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); + glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); + glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); + glad_glClear = (PFNGLCLEARPROC)load("glClear"); + glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); + glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); + glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); + glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); + glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); + glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); + glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); + glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); + glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); + glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); + glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); + glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); + glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); + glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); + glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); + glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); + glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); + glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); + glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); + glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); + glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); + glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); + glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); + glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); + glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); + glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); + glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); + glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); + glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); + glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); + glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); + glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); + glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); + glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); + glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); + glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); + glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); + glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); + glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); + glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); + glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); + glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); + glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); + glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); + glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); + glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); + glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); + glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); + glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); + glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); + glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); + glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); + glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); + glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); + glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); + glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); + glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); + glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); + glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); + glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); + glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); + glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); + glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); + glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); + glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); + glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); + glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); + glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); + glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); + glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); + glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); + glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); + glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); + glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); + glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); + glad_glEnd = (PFNGLENDPROC)load("glEnd"); + glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); + glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); + glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); + glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); + glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); + glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); + glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); + glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); + glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); + glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); + glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); + glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); + glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); + glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); + glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); + glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); + glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); + glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); + glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); + glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); + glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); + glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); + glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); + glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); + glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); + glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); + glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); + glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); + glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); + glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); + glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); + glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); + glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); + glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); + glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); + glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); + glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); + glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); + glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); + glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); + glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); + glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); + glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); + glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); + glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); + glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); + glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); + glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); + glad_glRects = (PFNGLRECTSPROC)load("glRects"); + glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); + glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); + glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); + glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); + glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); + glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); + glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); + glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); + glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); + glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); + glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); + glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); + glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); + glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); + glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); + glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); + glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); + glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); + glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); + glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); + glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); + glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); + glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); + glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); + glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); + glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); + glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); + glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); + glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); + glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); + glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); + glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); + glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); + glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); + glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); + glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); + glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); + glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); + glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); + glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); + glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); + glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); + glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); + glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); + glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); + glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); + glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); + glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); + glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); + glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); + glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); + glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); + glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); + glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); + glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); + glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); + glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); + glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); + glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); + glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); + glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); + glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); + glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); + glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); + glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); + glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); + glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); + glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); + glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); + glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); + glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); + glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); + glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); + glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); + glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); + glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); + glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); + glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); + glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); + glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); + glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); + glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); + glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); + glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); + glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); + glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); + glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); + glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); + glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); + glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); + glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); + glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); + glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); + glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); + glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); + glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); + glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); + glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); + glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); + glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); + glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); + glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); + glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); + glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); + glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); + glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); + glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); + glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); + glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); + glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); + glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); + glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); + glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); + glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); + glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); + glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); + glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); + glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); + glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); + glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); + glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); + glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); + glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); + glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); + glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); + glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); + glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); + glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); + glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); + glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); + glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); + glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); + glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); + glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); + glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); + glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); + glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); + glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); + glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); + glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); + glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); + glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); + glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); + glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); + glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); + glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); + glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); + glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); + glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); + glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); + glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); + glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); + glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); + glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); + glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); + glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); + glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); + glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); + glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); + glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); + glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); + glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); + glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); + glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); + glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); +} +static void load_GL_VERSION_1_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_1) return; + glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); + glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); + glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); + glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); + glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); + glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); + glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); + glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); + glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); + glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); + glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); + glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); + glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); + glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); + glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); + glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); + glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); + glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); + glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); + glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); + glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); + glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); + glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); + glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); + glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); + glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); + glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); + glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); + glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); + glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); +} +static void load_GL_VERSION_1_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_2) return; + glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); + glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); + glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); + glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); +} +static void load_GL_VERSION_1_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_3) return; + glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); + glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); + glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); + glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); + glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); + glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); + glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); + glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); + glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); + glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); + glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); + glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); + glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); + glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); + glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); + glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); + glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); + glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); + glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); + glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); + glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); + glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); + glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); + glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); + glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); + glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); + glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); + glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); + glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); + glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); + glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); + glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); + glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); + glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); + glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); + glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); + glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); + glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); + glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); + glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); + glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); + glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); + glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); + glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); + glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); + glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); +} +static void load_GL_VERSION_1_4(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_4) return; + glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); + glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); + glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); + glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); + glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); + glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); + glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); + glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); + glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); + glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); + glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); + glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); + glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); + glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); + glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); + glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); + glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); + glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); + glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); + glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); + glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); + glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); + glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); + glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); + glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); + glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); + glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); + glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); + glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); + glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); + glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); + glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); + glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); + glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); + glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); + glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); + glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); + glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); + glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); + glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); + glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); + glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); + glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); + glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); + glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); + glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); + glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); +} +static void load_GL_VERSION_1_5(GLADloadproc load) { + if(!GLAD_GL_VERSION_1_5) return; + glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); + glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); + glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); + glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); + glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); + glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); + glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); + glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); + glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); + glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); + glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); + glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); + glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); + glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); + glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); + glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); + glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); + glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); + glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); +} +static void load_GL_VERSION_2_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_2_0) return; + glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); + glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); + glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); + glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); + glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); + glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); + glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); + glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); + glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); + glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); + glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); + glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); + glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); + glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); + glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); + glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); + glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); + glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); + glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); + glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); + glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); + glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); + glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); + glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); + glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); + glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); + glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); + glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); + glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); + glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); + glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); + glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); + glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); + glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); + glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); + glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); + glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); + glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); + glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); + glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); + glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); + glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); + glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); + glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); + glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); + glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); + glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); + glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); + glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); + glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); + glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); + glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); + glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); + glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); + glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); + glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); + glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); + glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); + glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); + glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); + glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); + glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); + glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); + glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); + glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); + glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); + glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); + glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); + glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); + glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); + glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); + glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); + glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); + glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); + glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); + glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); + glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); + glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); + glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); + glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); + glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); + glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); + glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); + glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); + glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); + glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); + glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); + glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); + glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); + glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); + glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); + glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); + glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); +} +static void load_GL_VERSION_2_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_2_1) return; + glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); + glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); + glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); + glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); + glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); + glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); +} +static void load_GL_VERSION_3_0(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_0) return; + glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); + glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); + glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); + glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); + glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); + glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); + glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); + glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); + glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); + glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); + glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); + glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); + glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); + glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); + glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); + glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); + glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); + glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); + glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); + glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); + glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); + glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); + glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); + glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); + glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); + glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); + glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); + glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); + glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); + glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); + glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); + glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); + glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); + glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); + glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); + glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); + glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); + glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); + glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); + glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); + glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); + glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); + glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); + glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); + glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); + glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); + glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); + glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); + glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); + glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); + glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); + glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); + glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); + glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); + glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); + glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); + glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); + glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); + glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); + glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); + glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); + glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); + glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); + glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); + glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); + glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); + glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); + glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); + glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); + glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); + glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); + glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); + glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); + glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); + glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); + glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); + glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); + glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); + glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); + glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); + glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); + glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); + glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); + glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); +} +static void load_GL_VERSION_3_1(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_1) return; + glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); + glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); + glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); + glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); + glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); + glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); + glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); + glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); + glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); + glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); + glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); + glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); + glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); + glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); + glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); +} +static void load_GL_VERSION_3_2(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_2) return; + glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); + glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); + glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); + glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); + glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); + glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); + glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); + glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); + glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); + glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); + glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); + glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); + glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); + glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); + glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); + glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); + glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); + glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); + glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); +} +static void load_GL_VERSION_3_3(GLADloadproc load) { + if(!GLAD_GL_VERSION_3_3) return; + glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); + glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); + glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); + glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); + glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); + glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); + glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); + glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); + glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); + glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); + glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); + glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); + glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); + glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); + glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); + glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); + glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); + glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); + glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); + glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); + glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); + glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); + glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); + glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); + glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); + glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); + glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); + glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); + glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); + glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); + glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); + glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); + glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); + glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); + glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); + glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); + glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); + glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); + glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); + glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); + glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); + glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); + glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); + glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); + glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); + glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); + glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); + glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); + glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); + glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); + glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); + glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); + glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); + glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); + glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); + glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); + glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); + glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); +} +static void load_GL_ARB_debug_output(GLADloadproc load) { + if(!GLAD_GL_ARB_debug_output) return; + glad_glDebugMessageControlARB = (PFNGLDEBUGMESSAGECONTROLARBPROC)load("glDebugMessageControlARB"); + glad_glDebugMessageInsertARB = (PFNGLDEBUGMESSAGEINSERTARBPROC)load("glDebugMessageInsertARB"); + glad_glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)load("glDebugMessageCallbackARB"); + glad_glGetDebugMessageLogARB = (PFNGLGETDEBUGMESSAGELOGARBPROC)load("glGetDebugMessageLogARB"); +} +static void load_GL_ARB_framebuffer_object(GLADloadproc load) { + if(!GLAD_GL_ARB_framebuffer_object) return; + glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); + glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); + glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); + glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); + glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); + glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); + glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); + glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); + glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); + glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); + glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); + glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); + glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); + glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); + glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); + glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); + glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); + glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); + glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); + glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); +} +static void load_GL_EXT_framebuffer_blit(GLADloadproc load) { + if(!GLAD_GL_EXT_framebuffer_blit) return; + glad_glBlitFramebufferEXT = (PFNGLBLITFRAMEBUFFEREXTPROC)load("glBlitFramebufferEXT"); +} +static void load_GL_EXT_framebuffer_multisample(GLADloadproc load) { + if(!GLAD_GL_EXT_framebuffer_multisample) return; + glad_glRenderbufferStorageMultisampleEXT = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)load("glRenderbufferStorageMultisampleEXT"); +} +static void load_GL_EXT_framebuffer_object(GLADloadproc load) { + if(!GLAD_GL_EXT_framebuffer_object) return; + glad_glIsRenderbufferEXT = (PFNGLISRENDERBUFFEREXTPROC)load("glIsRenderbufferEXT"); + glad_glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)load("glBindRenderbufferEXT"); + glad_glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)load("glDeleteRenderbuffersEXT"); + glad_glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)load("glGenRenderbuffersEXT"); + glad_glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)load("glRenderbufferStorageEXT"); + glad_glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)load("glGetRenderbufferParameterivEXT"); + glad_glIsFramebufferEXT = (PFNGLISFRAMEBUFFEREXTPROC)load("glIsFramebufferEXT"); + glad_glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)load("glBindFramebufferEXT"); + glad_glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)load("glDeleteFramebuffersEXT"); + glad_glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)load("glGenFramebuffersEXT"); + glad_glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)load("glCheckFramebufferStatusEXT"); + glad_glFramebufferTexture1DEXT = (PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)load("glFramebufferTexture1DEXT"); + glad_glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)load("glFramebufferTexture2DEXT"); + glad_glFramebufferTexture3DEXT = (PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)load("glFramebufferTexture3DEXT"); + glad_glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)load("glFramebufferRenderbufferEXT"); + glad_glGetFramebufferAttachmentParameterivEXT = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)load("glGetFramebufferAttachmentParameterivEXT"); + glad_glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)load("glGenerateMipmapEXT"); +} +static int find_extensionsGL(void) { + if (!get_exts()) return 0; + GLAD_GL_ARB_debug_output = has_ext("GL_ARB_debug_output"); + GLAD_GL_ARB_framebuffer_object = has_ext("GL_ARB_framebuffer_object"); + GLAD_GL_EXT_framebuffer_blit = has_ext("GL_EXT_framebuffer_blit"); + GLAD_GL_EXT_framebuffer_multisample = has_ext("GL_EXT_framebuffer_multisample"); + GLAD_GL_EXT_framebuffer_object = has_ext("GL_EXT_framebuffer_object"); + free_exts(); + return 1; +} + +static void find_coreGL(void) { + + /* Thank you @elmindreda + * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 + * https://github.com/glfw/glfw/blob/master/src/context.c#L36 + */ + int i, major, minor; + + const char* version; + const char* prefixes[] = { + "OpenGL ES-CM ", + "OpenGL ES-CL ", + "OpenGL ES ", + NULL + }; + + version = (const char*) glGetString(GL_VERSION); + if (!version) return; + + for (i = 0; prefixes[i]; i++) { + const size_t length = strlen(prefixes[i]); + if (strncmp(version, prefixes[i], length) == 0) { + version += length; + break; + } + } + +/* PR #18 */ +#ifdef _MSC_VER + sscanf_s(version, "%d.%d", &major, &minor); +#else + sscanf(version, "%d.%d", &major, &minor); +#endif + + GLVersion.major = major; GLVersion.minor = minor; + max_loaded_major = major; max_loaded_minor = minor; + GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; + GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; + GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; + GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; + GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; + GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; + GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; + GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; + GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; + GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; + GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; + GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; + if (GLVersion.major > 3 || (GLVersion.major >= 3 && GLVersion.minor >= 3)) { + max_loaded_major = 3; + max_loaded_minor = 3; + } +} + +int gladLoadGLLoader(GLADloadproc load) { + GLVersion.major = 0; GLVersion.minor = 0; + glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); + if(glGetString == NULL) return 0; + if(glGetString(GL_VERSION) == NULL) return 0; + find_coreGL(); + load_GL_VERSION_1_0(load); + load_GL_VERSION_1_1(load); + load_GL_VERSION_1_2(load); + load_GL_VERSION_1_3(load); + load_GL_VERSION_1_4(load); + load_GL_VERSION_1_5(load); + load_GL_VERSION_2_0(load); + load_GL_VERSION_2_1(load); + load_GL_VERSION_3_0(load); + load_GL_VERSION_3_1(load); + load_GL_VERSION_3_2(load); + load_GL_VERSION_3_3(load); + + if (!find_extensionsGL()) return 0; + load_GL_ARB_debug_output(load); + load_GL_ARB_framebuffer_object(load); + load_GL_EXT_framebuffer_blit(load); + load_GL_EXT_framebuffer_multisample(load); + load_GL_EXT_framebuffer_object(load); + return GLVersion.major != 0 || GLVersion.minor != 0; +} + diff --git a/thirdparty/glad/glad/glad.h b/thirdparty/glad/glad/glad.h new file mode 100644 index 00000000000..f211e6aa570 --- /dev/null +++ b/thirdparty/glad/glad/glad.h @@ -0,0 +1,3784 @@ +/* + + OpenGL loader generated by glad 0.1.34 on Tue Nov 17 16:41:02 2020. + + Language/Generator: C/C++ + Specification: gl + APIs: gl=3.3 + Profile: compatibility + Extensions: + GL_ARB_debug_output, + GL_ARB_framebuffer_object, + GL_EXT_framebuffer_blit, + GL_EXT_framebuffer_multisample, + GL_EXT_framebuffer_object + Loader: True + Local files: False + Omit khrplatform: False + Reproducible: False + + Commandline: + --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output,GL_ARB_framebuffer_object,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object" + Online: + https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output&extensions=GL_ARB_framebuffer_object&extensions=GL_EXT_framebuffer_blit&extensions=GL_EXT_framebuffer_multisample&extensions=GL_EXT_framebuffer_object +*/ + + +#ifndef __glad_h_ +#define __glad_h_ + +#ifdef __gl_h_ +#error OpenGL header already included, remove this include, glad already provides it +#endif +#define __gl_h_ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#define APIENTRY __stdcall +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif + +#ifndef GLAPIENTRY +#define GLAPIENTRY APIENTRY +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +struct gladGLversionStruct { + int major; + int minor; +}; + +typedef void* (* GLADloadproc)(const char *name); + +#ifndef GLAPI +# if defined(GLAD_GLAPI_EXPORT) +# if defined(_WIN32) || defined(__CYGWIN__) +# if defined(GLAD_GLAPI_EXPORT_BUILD) +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllexport)) extern +# else +# define GLAPI __declspec(dllexport) extern +# endif +# else +# if defined(__GNUC__) +# define GLAPI __attribute__ ((dllimport)) extern +# else +# define GLAPI __declspec(dllimport) extern +# endif +# endif +# elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) +# define GLAPI __attribute__ ((visibility ("default"))) extern +# else +# define GLAPI extern +# endif +# else +# define GLAPI extern +# endif +#endif + +GLAPI struct gladGLversionStruct GLVersion; + +GLAPI int gladLoadGL(void); + +GLAPI int gladLoadGLLoader(GLADloadproc); + +#include +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef khronos_int8_t GLbyte; +typedef khronos_uint8_t GLubyte; +typedef khronos_int16_t GLshort; +typedef khronos_uint16_t GLushort; +typedef int GLint; +typedef unsigned int GLuint; +typedef khronos_int32_t GLclampx; +typedef int GLsizei; +typedef khronos_float_t GLfloat; +typedef khronos_float_t GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void *GLeglClientBufferEXT; +typedef void *GLeglImageOES; +typedef char GLchar; +typedef char GLcharARB; +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef khronos_uint16_t GLhalf; +typedef khronos_uint16_t GLhalfARB; +typedef khronos_int32_t GLfixed; +typedef khronos_intptr_t GLintptr; +typedef khronos_intptr_t GLintptrARB; +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_ssize_t GLsizeiptrARB; +typedef khronos_int64_t GLint64; +typedef khronos_int64_t GLint64EXT; +typedef khronos_uint64_t GLuint64; +typedef khronos_uint64_t GLuint64EXT; +typedef struct __GLsync *GLsync; +struct _cl_context; +struct _cl_event; +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +typedef unsigned short GLhalfNV; +typedef GLintptr GLvdpauSurfaceNV; +typedef void (APIENTRY *GLVULKANPROCNV)(void); +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_QUADS 0x0007 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_NONE 0 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_LEFT 0x0406 +#define GL_RIGHT 0x0407 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_VIEWPORT 0x0BA2 +#define GL_DITHER 0x0BD0 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND 0x0BE2 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_READ_BUFFER 0x0C02 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_STEREO 0x0C33 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_CLEAR 0x1500 +#define GL_AND 0x1501 +#define GL_AND_REVERSE 0x1502 +#define GL_COPY 0x1503 +#define GL_AND_INVERTED 0x1504 +#define GL_NOOP 0x1505 +#define GL_XOR 0x1506 +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_EQUIV 0x1509 +#define GL_INVERT 0x150A +#define GL_OR_REVERSE 0x150B +#define GL_COPY_INVERTED 0x150C +#define GL_OR_INVERTED 0x150D +#define GL_NAND 0x150E +#define GL_SET 0x150F +#define GL_TEXTURE 0x1702 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_POINT 0x1B00 +#define GL_LINE 0x1B01 +#define GL_FILL 0x1B02 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_REPEAT 0x2901 +#define GL_CURRENT_BIT 0x00000001 +#define GL_POINT_BIT 0x00000002 +#define GL_LINE_BIT 0x00000004 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_FOG_BIT 0x00000080 +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_ENABLE_BIT 0x00002000 +#define GL_HINT_BIT 0x00008000 +#define GL_EVAL_BIT 0x00010000 +#define GL_LIST_BIT 0x00020000 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_QUAD_STRIP 0x0008 +#define GL_POLYGON 0x0009 +#define GL_ACCUM 0x0100 +#define GL_LOAD 0x0101 +#define GL_RETURN 0x0102 +#define GL_MULT 0x0103 +#define GL_ADD 0x0104 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_2D 0x0600 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_POINT_TOKEN 0x0701 +#define GL_LINE_TOKEN 0x0702 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 +#define GL_COEFF 0x0A00 +#define GL_ORDER 0x0A01 +#define GL_DOMAIN 0x0A02 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_POINT_SMOOTH 0x0B10 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LIST_MODE 0x0B30 +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_INDEX 0x0B33 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_EDGE_FLAG 0x0B43 +#define GL_LIGHTING 0x0B50 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_SHADE_MODEL 0x0B54 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_FOG 0x0B60 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_START 0x0B63 +#define GL_FOG_END 0x0B64 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_COLOR 0x0B66 +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_NORMALIZE 0x0BA1 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_LOGIC_OP 0x0BF1 +#define GL_AUX_BUFFERS 0x0C00 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_INDEX_MODE 0x0C30 +#define GL_RGBA_MODE 0x0C31 +#define GL_RENDER_MODE 0x0C40 +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_FOG_HINT 0x0C54 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_STENCIL 0x0D11 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_RED_SCALE 0x0D14 +#define GL_RED_BIAS 0x0D15 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 +#define GL_GREEN_SCALE 0x0D18 +#define GL_GREEN_BIAS 0x0D19 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BLUE_BIAS 0x0D1B +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_BIAS 0x0D1F +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_INDEX_BITS 0x0D51 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_AUTO_NORMAL 0x0D80 +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_TEXTURE_COMPONENTS 0x1003 +#define GL_TEXTURE_BORDER 0x1005 +#define GL_AMBIENT 0x1200 +#define GL_DIFFUSE 0x1201 +#define GL_SPECULAR 0x1202 +#define GL_POSITION 0x1203 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_2_BYTES 0x1407 +#define GL_3_BYTES 0x1408 +#define GL_4_BYTES 0x1409 +#define GL_EMISSION 0x1600 +#define GL_SHININESS 0x1601 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_COLOR_INDEXES 0x1603 +#define GL_MODELVIEW 0x1700 +#define GL_PROJECTION 0x1701 +#define GL_COLOR_INDEX 0x1900 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_BITMAP 0x1A00 +#define GL_RENDER 0x1C00 +#define GL_FEEDBACK 0x1C01 +#define GL_SELECT 0x1C02 +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 +#define GL_S 0x2000 +#define GL_T 0x2001 +#define GL_R 0x2002 +#define GL_Q 0x2003 +#define GL_MODULATE 0x2100 +#define GL_DECAL 0x2101 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_ENV 0x2300 +#define GL_EYE_LINEAR 0x2400 +#define GL_OBJECT_LINEAR 0x2401 +#define GL_SPHERE_MAP 0x2402 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_OBJECT_PLANE 0x2501 +#define GL_EYE_PLANE 0x2502 +#define GL_CLAMP 0x2900 +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_DOUBLE 0x140A +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_COLOR_ARRAY 0x8076 +#define GL_INDEX_ARRAY 0x8077 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_C3F_V3F 0x2A24 +#define GL_N3F_V3F 0x2A25 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_V4F 0x2A28 +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T4F_C4F_N3F_V4F 0x2A2D +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_RESCALE_NORMAL 0x803A +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_EQUATION 0x8009 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_COORD 0x8451 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC2_ALPHA 0x858A +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_CONTEXT_FLAGS 0x821E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RG 0x8226 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_FIXED_ONLY 0x891D +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_BGR_INTEGER 0x8D9A +#define GL_BGRA_INTEGER 0x8D9B +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_QUERY_WAIT 0x8E13 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_INDEX 0x8222 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_R16 0x822A +#define GL_RG8 0x822B +#define GL_RG16 0x822C +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_ALPHA_INTEGER 0x8D97 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFF +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_INTEGER_SAMPLES 0x9110 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_SRC1_COLOR 0x88F9 +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#define GL_INT_2_10_10_10_REV 0x8D9F +#ifndef GL_VERSION_1_0 +#define GL_VERSION_1_0 1 +GLAPI int GLAD_GL_VERSION_1_0; +typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); +GLAPI PFNGLCULLFACEPROC glad_glCullFace; +#define glCullFace glad_glCullFace +typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); +GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; +#define glFrontFace glad_glFrontFace +typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); +GLAPI PFNGLHINTPROC glad_glHint; +#define glHint glad_glHint +typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); +GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; +#define glLineWidth glad_glLineWidth +typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); +GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; +#define glPointSize glad_glPointSize +typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); +GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; +#define glPolygonMode glad_glPolygonMode +typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLSCISSORPROC glad_glScissor; +#define glScissor glad_glScissor +typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); +GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; +#define glTexParameterf glad_glTexParameterf +typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; +#define glTexParameterfv glad_glTexParameterfv +typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +#define glTexParameteri glad_glTexParameteri +typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; +#define glTexParameteriv glad_glTexParameteriv +typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; +#define glTexImage1D glad_glTexImage1D +typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +#define glTexImage2D glad_glTexImage2D +typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); +GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; +#define glDrawBuffer glad_glDrawBuffer +typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); +GLAPI PFNGLCLEARPROC glad_glClear; +#define glClear glad_glClear +typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; +#define glClearColor glad_glClearColor +typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); +GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; +#define glClearStencil glad_glClearStencil +typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); +GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; +#define glClearDepth glad_glClearDepth +typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); +GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; +#define glStencilMask glad_glStencilMask +typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +GLAPI PFNGLCOLORMASKPROC glad_glColorMask; +#define glColorMask glad_glColorMask +typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); +GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; +#define glDepthMask glad_glDepthMask +typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); +GLAPI PFNGLDISABLEPROC glad_glDisable; +#define glDisable glad_glDisable +typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); +GLAPI PFNGLENABLEPROC glad_glEnable; +#define glEnable glad_glEnable +typedef void (APIENTRYP PFNGLFINISHPROC)(void); +GLAPI PFNGLFINISHPROC glad_glFinish; +#define glFinish glad_glFinish +typedef void (APIENTRYP PFNGLFLUSHPROC)(void); +GLAPI PFNGLFLUSHPROC glad_glFlush; +#define glFlush glad_glFlush +typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); +GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; +#define glBlendFunc glad_glBlendFunc +typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); +GLAPI PFNGLLOGICOPPROC glad_glLogicOp; +#define glLogicOp glad_glLogicOp +typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; +#define glStencilFunc glad_glStencilFunc +typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); +GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; +#define glStencilOp glad_glStencilOp +typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); +GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; +#define glDepthFunc glad_glDepthFunc +typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; +#define glPixelStoref glad_glPixelStoref +typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; +#define glPixelStorei glad_glPixelStorei +typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); +GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; +#define glReadBuffer glad_glReadBuffer +typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; +#define glReadPixels glad_glReadPixels +typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); +GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; +#define glGetBooleanv glad_glGetBooleanv +typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); +GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; +#define glGetDoublev glad_glGetDoublev +typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(void); +GLAPI PFNGLGETERRORPROC glad_glGetError; +#define glGetError glad_glGetError +typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); +GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; +#define glGetFloatv glad_glGetFloatv +typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); +GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; +#define glGetIntegerv glad_glGetIntegerv +typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); +GLAPI PFNGLGETSTRINGPROC glad_glGetString; +#define glGetString glad_glGetString +typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; +#define glGetTexImage glad_glGetTexImage +typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; +#define glGetTexParameterfv glad_glGetTexParameterfv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; +#define glGetTexParameteriv glad_glGetTexParameteriv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; +#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; +#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv +typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); +GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; +#define glIsEnabled glad_glIsEnabled +typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); +GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; +#define glDepthRange glad_glDepthRange +typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLVIEWPORTPROC glad_glViewport; +#define glViewport glad_glViewport +typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); +GLAPI PFNGLNEWLISTPROC glad_glNewList; +#define glNewList glad_glNewList +typedef void (APIENTRYP PFNGLENDLISTPROC)(void); +GLAPI PFNGLENDLISTPROC glad_glEndList; +#define glEndList glad_glEndList +typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); +GLAPI PFNGLCALLLISTPROC glad_glCallList; +#define glCallList glad_glCallList +typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); +GLAPI PFNGLCALLLISTSPROC glad_glCallLists; +#define glCallLists glad_glCallLists +typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); +GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; +#define glDeleteLists glad_glDeleteLists +typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); +GLAPI PFNGLGENLISTSPROC glad_glGenLists; +#define glGenLists glad_glGenLists +typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); +GLAPI PFNGLLISTBASEPROC glad_glListBase; +#define glListBase glad_glListBase +typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); +GLAPI PFNGLBEGINPROC glad_glBegin; +#define glBegin glad_glBegin +typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); +GLAPI PFNGLBITMAPPROC glad_glBitmap; +#define glBitmap glad_glBitmap +typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +GLAPI PFNGLCOLOR3BPROC glad_glColor3b; +#define glColor3b glad_glColor3b +typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); +GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; +#define glColor3bv glad_glColor3bv +typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +GLAPI PFNGLCOLOR3DPROC glad_glColor3d; +#define glColor3d glad_glColor3d +typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); +GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; +#define glColor3dv glad_glColor3dv +typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +GLAPI PFNGLCOLOR3FPROC glad_glColor3f; +#define glColor3f glad_glColor3f +typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); +GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; +#define glColor3fv glad_glColor3fv +typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); +GLAPI PFNGLCOLOR3IPROC glad_glColor3i; +#define glColor3i glad_glColor3i +typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); +GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; +#define glColor3iv glad_glColor3iv +typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +GLAPI PFNGLCOLOR3SPROC glad_glColor3s; +#define glColor3s glad_glColor3s +typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); +GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; +#define glColor3sv glad_glColor3sv +typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; +#define glColor3ub glad_glColor3ub +typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); +GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; +#define glColor3ubv glad_glColor3ubv +typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; +#define glColor3ui glad_glColor3ui +typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); +GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; +#define glColor3uiv glad_glColor3uiv +typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +GLAPI PFNGLCOLOR3USPROC glad_glColor3us; +#define glColor3us glad_glColor3us +typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); +GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; +#define glColor3usv glad_glColor3usv +typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); +GLAPI PFNGLCOLOR4BPROC glad_glColor4b; +#define glColor4b glad_glColor4b +typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); +GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; +#define glColor4bv glad_glColor4bv +typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); +GLAPI PFNGLCOLOR4DPROC glad_glColor4d; +#define glColor4d glad_glColor4d +typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); +GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; +#define glColor4dv glad_glColor4dv +typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCOLOR4FPROC glad_glColor4f; +#define glColor4f glad_glColor4f +typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); +GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; +#define glColor4fv glad_glColor4fv +typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); +GLAPI PFNGLCOLOR4IPROC glad_glColor4i; +#define glColor4i glad_glColor4i +typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); +GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; +#define glColor4iv glad_glColor4iv +typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); +GLAPI PFNGLCOLOR4SPROC glad_glColor4s; +#define glColor4s glad_glColor4s +typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); +GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; +#define glColor4sv glad_glColor4sv +typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); +GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; +#define glColor4ub glad_glColor4ub +typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); +GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; +#define glColor4ubv glad_glColor4ubv +typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); +GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; +#define glColor4ui glad_glColor4ui +typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); +GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; +#define glColor4uiv glad_glColor4uiv +typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); +GLAPI PFNGLCOLOR4USPROC glad_glColor4us; +#define glColor4us glad_glColor4us +typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); +GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; +#define glColor4usv glad_glColor4usv +typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); +GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; +#define glEdgeFlag glad_glEdgeFlag +typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); +GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; +#define glEdgeFlagv glad_glEdgeFlagv +typedef void (APIENTRYP PFNGLENDPROC)(void); +GLAPI PFNGLENDPROC glad_glEnd; +#define glEnd glad_glEnd +typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); +GLAPI PFNGLINDEXDPROC glad_glIndexd; +#define glIndexd glad_glIndexd +typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); +GLAPI PFNGLINDEXDVPROC glad_glIndexdv; +#define glIndexdv glad_glIndexdv +typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); +GLAPI PFNGLINDEXFPROC glad_glIndexf; +#define glIndexf glad_glIndexf +typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); +GLAPI PFNGLINDEXFVPROC glad_glIndexfv; +#define glIndexfv glad_glIndexfv +typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); +GLAPI PFNGLINDEXIPROC glad_glIndexi; +#define glIndexi glad_glIndexi +typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); +GLAPI PFNGLINDEXIVPROC glad_glIndexiv; +#define glIndexiv glad_glIndexiv +typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); +GLAPI PFNGLINDEXSPROC glad_glIndexs; +#define glIndexs glad_glIndexs +typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); +GLAPI PFNGLINDEXSVPROC glad_glIndexsv; +#define glIndexsv glad_glIndexsv +typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); +GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; +#define glNormal3b glad_glNormal3b +typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); +GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; +#define glNormal3bv glad_glNormal3bv +typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); +GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; +#define glNormal3d glad_glNormal3d +typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); +GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; +#define glNormal3dv glad_glNormal3dv +typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); +GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; +#define glNormal3f glad_glNormal3f +typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); +GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; +#define glNormal3fv glad_glNormal3fv +typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); +GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; +#define glNormal3i glad_glNormal3i +typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); +GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; +#define glNormal3iv glad_glNormal3iv +typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); +GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; +#define glNormal3s glad_glNormal3s +typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); +GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; +#define glNormal3sv glad_glNormal3sv +typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; +#define glRasterPos2d glad_glRasterPos2d +typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; +#define glRasterPos2dv glad_glRasterPos2dv +typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; +#define glRasterPos2f glad_glRasterPos2f +typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; +#define glRasterPos2fv glad_glRasterPos2fv +typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); +GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; +#define glRasterPos2i glad_glRasterPos2i +typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; +#define glRasterPos2iv glad_glRasterPos2iv +typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; +#define glRasterPos2s glad_glRasterPos2s +typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; +#define glRasterPos2sv glad_glRasterPos2sv +typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; +#define glRasterPos3d glad_glRasterPos3d +typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; +#define glRasterPos3dv glad_glRasterPos3dv +typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; +#define glRasterPos3f glad_glRasterPos3f +typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; +#define glRasterPos3fv glad_glRasterPos3fv +typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; +#define glRasterPos3i glad_glRasterPos3i +typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; +#define glRasterPos3iv glad_glRasterPos3iv +typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; +#define glRasterPos3s glad_glRasterPos3s +typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; +#define glRasterPos3sv glad_glRasterPos3sv +typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; +#define glRasterPos4d glad_glRasterPos4d +typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); +GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; +#define glRasterPos4dv glad_glRasterPos4dv +typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; +#define glRasterPos4f glad_glRasterPos4f +typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); +GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; +#define glRasterPos4fv glad_glRasterPos4fv +typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; +#define glRasterPos4i glad_glRasterPos4i +typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); +GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; +#define glRasterPos4iv glad_glRasterPos4iv +typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; +#define glRasterPos4s glad_glRasterPos4s +typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); +GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; +#define glRasterPos4sv glad_glRasterPos4sv +typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); +GLAPI PFNGLRECTDPROC glad_glRectd; +#define glRectd glad_glRectd +typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); +GLAPI PFNGLRECTDVPROC glad_glRectdv; +#define glRectdv glad_glRectdv +typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); +GLAPI PFNGLRECTFPROC glad_glRectf; +#define glRectf glad_glRectf +typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); +GLAPI PFNGLRECTFVPROC glad_glRectfv; +#define glRectfv glad_glRectfv +typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); +GLAPI PFNGLRECTIPROC glad_glRecti; +#define glRecti glad_glRecti +typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); +GLAPI PFNGLRECTIVPROC glad_glRectiv; +#define glRectiv glad_glRectiv +typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); +GLAPI PFNGLRECTSPROC glad_glRects; +#define glRects glad_glRects +typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); +GLAPI PFNGLRECTSVPROC glad_glRectsv; +#define glRectsv glad_glRectsv +typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); +GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; +#define glTexCoord1d glad_glTexCoord1d +typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; +#define glTexCoord1dv glad_glTexCoord1dv +typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); +GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; +#define glTexCoord1f glad_glTexCoord1f +typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; +#define glTexCoord1fv glad_glTexCoord1fv +typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); +GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; +#define glTexCoord1i glad_glTexCoord1i +typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; +#define glTexCoord1iv glad_glTexCoord1iv +typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); +GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; +#define glTexCoord1s glad_glTexCoord1s +typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; +#define glTexCoord1sv glad_glTexCoord1sv +typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); +GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; +#define glTexCoord2d glad_glTexCoord2d +typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; +#define glTexCoord2dv glad_glTexCoord2dv +typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); +GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; +#define glTexCoord2f glad_glTexCoord2f +typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; +#define glTexCoord2fv glad_glTexCoord2fv +typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); +GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; +#define glTexCoord2i glad_glTexCoord2i +typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; +#define glTexCoord2iv glad_glTexCoord2iv +typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); +GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; +#define glTexCoord2s glad_glTexCoord2s +typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; +#define glTexCoord2sv glad_glTexCoord2sv +typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); +GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; +#define glTexCoord3d glad_glTexCoord3d +typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; +#define glTexCoord3dv glad_glTexCoord3dv +typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); +GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; +#define glTexCoord3f glad_glTexCoord3f +typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; +#define glTexCoord3fv glad_glTexCoord3fv +typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); +GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; +#define glTexCoord3i glad_glTexCoord3i +typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; +#define glTexCoord3iv glad_glTexCoord3iv +typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); +GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; +#define glTexCoord3s glad_glTexCoord3s +typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; +#define glTexCoord3sv glad_glTexCoord3sv +typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; +#define glTexCoord4d glad_glTexCoord4d +typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); +GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; +#define glTexCoord4dv glad_glTexCoord4dv +typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; +#define glTexCoord4f glad_glTexCoord4f +typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); +GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; +#define glTexCoord4fv glad_glTexCoord4fv +typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); +GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; +#define glTexCoord4i glad_glTexCoord4i +typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); +GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; +#define glTexCoord4iv glad_glTexCoord4iv +typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; +#define glTexCoord4s glad_glTexCoord4s +typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); +GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; +#define glTexCoord4sv glad_glTexCoord4sv +typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; +#define glVertex2d glad_glVertex2d +typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; +#define glVertex2dv glad_glVertex2dv +typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; +#define glVertex2f glad_glVertex2f +typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; +#define glVertex2fv glad_glVertex2fv +typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); +GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; +#define glVertex2i glad_glVertex2i +typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; +#define glVertex2iv glad_glVertex2iv +typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; +#define glVertex2s glad_glVertex2s +typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; +#define glVertex2sv glad_glVertex2sv +typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; +#define glVertex3d glad_glVertex3d +typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; +#define glVertex3dv glad_glVertex3dv +typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; +#define glVertex3f glad_glVertex3f +typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; +#define glVertex3fv glad_glVertex3fv +typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; +#define glVertex3i glad_glVertex3i +typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; +#define glVertex3iv glad_glVertex3iv +typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; +#define glVertex3s glad_glVertex3s +typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; +#define glVertex3sv glad_glVertex3sv +typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; +#define glVertex4d glad_glVertex4d +typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); +GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; +#define glVertex4dv glad_glVertex4dv +typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; +#define glVertex4f glad_glVertex4f +typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); +GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; +#define glVertex4fv glad_glVertex4fv +typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; +#define glVertex4i glad_glVertex4i +typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); +GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; +#define glVertex4iv glad_glVertex4iv +typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; +#define glVertex4s glad_glVertex4s +typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); +GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; +#define glVertex4sv glad_glVertex4sv +typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); +GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; +#define glClipPlane glad_glClipPlane +typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); +GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; +#define glColorMaterial glad_glColorMaterial +typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLFOGFPROC glad_glFogf; +#define glFogf glad_glFogf +typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLFOGFVPROC glad_glFogfv; +#define glFogfv glad_glFogfv +typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); +GLAPI PFNGLFOGIPROC glad_glFogi; +#define glFogi glad_glFogi +typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLFOGIVPROC glad_glFogiv; +#define glFogiv glad_glFogiv +typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); +GLAPI PFNGLLIGHTFPROC glad_glLightf; +#define glLightf glad_glLightf +typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); +GLAPI PFNGLLIGHTFVPROC glad_glLightfv; +#define glLightfv glad_glLightfv +typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); +GLAPI PFNGLLIGHTIPROC glad_glLighti; +#define glLighti glad_glLighti +typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); +GLAPI PFNGLLIGHTIVPROC glad_glLightiv; +#define glLightiv glad_glLightiv +typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; +#define glLightModelf glad_glLightModelf +typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; +#define glLightModelfv glad_glLightModelfv +typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); +GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; +#define glLightModeli glad_glLightModeli +typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; +#define glLightModeliv glad_glLightModeliv +typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); +GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; +#define glLineStipple glad_glLineStipple +typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); +GLAPI PFNGLMATERIALFPROC glad_glMaterialf; +#define glMaterialf glad_glMaterialf +typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); +GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; +#define glMaterialfv glad_glMaterialfv +typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); +GLAPI PFNGLMATERIALIPROC glad_glMateriali; +#define glMateriali glad_glMateriali +typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); +GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; +#define glMaterialiv glad_glMaterialiv +typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); +GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; +#define glPolygonStipple glad_glPolygonStipple +typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); +GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; +#define glShadeModel glad_glShadeModel +typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); +GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; +#define glTexEnvf glad_glTexEnvf +typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; +#define glTexEnvfv glad_glTexEnvfv +typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); +GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; +#define glTexEnvi glad_glTexEnvi +typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; +#define glTexEnviv glad_glTexEnviv +typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); +GLAPI PFNGLTEXGENDPROC glad_glTexGend; +#define glTexGend glad_glTexGend +typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); +GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; +#define glTexGendv glad_glTexGendv +typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); +GLAPI PFNGLTEXGENFPROC glad_glTexGenf; +#define glTexGenf glad_glTexGenf +typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); +GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; +#define glTexGenfv glad_glTexGenfv +typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); +GLAPI PFNGLTEXGENIPROC glad_glTexGeni; +#define glTexGeni glad_glTexGeni +typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); +GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; +#define glTexGeniv glad_glTexGeniv +typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); +GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; +#define glFeedbackBuffer glad_glFeedbackBuffer +typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); +GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; +#define glSelectBuffer glad_glSelectBuffer +typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); +GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; +#define glRenderMode glad_glRenderMode +typedef void (APIENTRYP PFNGLINITNAMESPROC)(void); +GLAPI PFNGLINITNAMESPROC glad_glInitNames; +#define glInitNames glad_glInitNames +typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); +GLAPI PFNGLLOADNAMEPROC glad_glLoadName; +#define glLoadName glad_glLoadName +typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); +GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; +#define glPassThrough glad_glPassThrough +typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void); +GLAPI PFNGLPOPNAMEPROC glad_glPopName; +#define glPopName glad_glPopName +typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); +GLAPI PFNGLPUSHNAMEPROC glad_glPushName; +#define glPushName glad_glPushName +typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; +#define glClearAccum glad_glClearAccum +typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); +GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; +#define glClearIndex glad_glClearIndex +typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); +GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; +#define glIndexMask glad_glIndexMask +typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); +GLAPI PFNGLACCUMPROC glad_glAccum; +#define glAccum glad_glAccum +typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void); +GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; +#define glPopAttrib glad_glPopAttrib +typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); +GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; +#define glPushAttrib glad_glPushAttrib +typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +GLAPI PFNGLMAP1DPROC glad_glMap1d; +#define glMap1d glad_glMap1d +typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +GLAPI PFNGLMAP1FPROC glad_glMap1f; +#define glMap1f glad_glMap1f +typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +GLAPI PFNGLMAP2DPROC glad_glMap2d; +#define glMap2d glad_glMap2d +typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +GLAPI PFNGLMAP2FPROC glad_glMap2f; +#define glMap2f glad_glMap2f +typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); +GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; +#define glMapGrid1d glad_glMapGrid1d +typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); +GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; +#define glMapGrid1f glad_glMapGrid1f +typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); +GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; +#define glMapGrid2d glad_glMapGrid2d +typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); +GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; +#define glMapGrid2f glad_glMapGrid2f +typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); +GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; +#define glEvalCoord1d glad_glEvalCoord1d +typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); +GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; +#define glEvalCoord1dv glad_glEvalCoord1dv +typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); +GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; +#define glEvalCoord1f glad_glEvalCoord1f +typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); +GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; +#define glEvalCoord1fv glad_glEvalCoord1fv +typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); +GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; +#define glEvalCoord2d glad_glEvalCoord2d +typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); +GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; +#define glEvalCoord2dv glad_glEvalCoord2dv +typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); +GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; +#define glEvalCoord2f glad_glEvalCoord2f +typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); +GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; +#define glEvalCoord2fv glad_glEvalCoord2fv +typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); +GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; +#define glEvalMesh1 glad_glEvalMesh1 +typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); +GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; +#define glEvalPoint1 glad_glEvalPoint1 +typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); +GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; +#define glEvalMesh2 glad_glEvalMesh2 +typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); +GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; +#define glEvalPoint2 glad_glEvalPoint2 +typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); +GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; +#define glAlphaFunc glad_glAlphaFunc +typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); +GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; +#define glPixelZoom glad_glPixelZoom +typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; +#define glPixelTransferf glad_glPixelTransferf +typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; +#define glPixelTransferi glad_glPixelTransferi +typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); +GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; +#define glPixelMapfv glad_glPixelMapfv +typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); +GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; +#define glPixelMapuiv glad_glPixelMapuiv +typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); +GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; +#define glPixelMapusv glad_glPixelMapusv +typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); +GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; +#define glCopyPixels glad_glCopyPixels +typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; +#define glDrawPixels glad_glDrawPixels +typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); +GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; +#define glGetClipPlane glad_glGetClipPlane +typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); +GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; +#define glGetLightfv glad_glGetLightfv +typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); +GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; +#define glGetLightiv glad_glGetLightiv +typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); +GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; +#define glGetMapdv glad_glGetMapdv +typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); +GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; +#define glGetMapfv glad_glGetMapfv +typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); +GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; +#define glGetMapiv glad_glGetMapiv +typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); +GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; +#define glGetMaterialfv glad_glGetMaterialfv +typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); +GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; +#define glGetMaterialiv glad_glGetMaterialiv +typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); +GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; +#define glGetPixelMapfv glad_glGetPixelMapfv +typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); +GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; +#define glGetPixelMapuiv glad_glGetPixelMapuiv +typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); +GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; +#define glGetPixelMapusv glad_glGetPixelMapusv +typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); +GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; +#define glGetPolygonStipple glad_glGetPolygonStipple +typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; +#define glGetTexEnvfv glad_glGetTexEnvfv +typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; +#define glGetTexEnviv glad_glGetTexEnviv +typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); +GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; +#define glGetTexGendv glad_glGetTexGendv +typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); +GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; +#define glGetTexGenfv glad_glGetTexGenfv +typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; +#define glGetTexGeniv glad_glGetTexGeniv +typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); +GLAPI PFNGLISLISTPROC glad_glIsList; +#define glIsList glad_glIsList +typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI PFNGLFRUSTUMPROC glad_glFrustum; +#define glFrustum glad_glFrustum +typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void); +GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; +#define glLoadIdentity glad_glLoadIdentity +typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; +#define glLoadMatrixf glad_glLoadMatrixf +typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; +#define glLoadMatrixd glad_glLoadMatrixd +typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); +GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; +#define glMatrixMode glad_glMatrixMode +typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; +#define glMultMatrixf glad_glMultMatrixf +typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; +#define glMultMatrixd glad_glMultMatrixd +typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI PFNGLORTHOPROC glad_glOrtho; +#define glOrtho glad_glOrtho +typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void); +GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; +#define glPopMatrix glad_glPopMatrix +typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void); +GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; +#define glPushMatrix glad_glPushMatrix +typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLROTATEDPROC glad_glRotated; +#define glRotated glad_glRotated +typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLROTATEFPROC glad_glRotatef; +#define glRotatef glad_glRotatef +typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLSCALEDPROC glad_glScaled; +#define glScaled glad_glScaled +typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLSCALEFPROC glad_glScalef; +#define glScalef glad_glScalef +typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; +#define glTranslated glad_glTranslated +typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; +#define glTranslatef glad_glTranslatef +#endif +#ifndef GL_VERSION_1_1 +#define GL_VERSION_1_1 1 +GLAPI int GLAD_GL_VERSION_1_1; +typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); +GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; +#define glDrawArrays glad_glDrawArrays +typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; +#define glDrawElements glad_glDrawElements +typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); +GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; +#define glGetPointerv glad_glGetPointerv +typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); +GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; +#define glPolygonOffset glad_glPolygonOffset +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; +#define glCopyTexImage1D glad_glCopyTexImage1D +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; +#define glCopyTexImage2D glad_glCopyTexImage2D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; +#define glCopyTexSubImage1D glad_glCopyTexSubImage1D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; +#define glCopyTexSubImage2D glad_glCopyTexSubImage2D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; +#define glTexSubImage1D glad_glTexSubImage1D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; +#define glTexSubImage2D glad_glTexSubImage2D +typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); +GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; +#define glBindTexture glad_glBindTexture +typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); +GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +#define glDeleteTextures glad_glDeleteTextures +typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); +GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; +#define glGenTextures glad_glGenTextures +typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); +GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; +#define glIsTexture glad_glIsTexture +typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); +GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; +#define glArrayElement glad_glArrayElement +typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; +#define glColorPointer glad_glColorPointer +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); +GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; +#define glDisableClientState glad_glDisableClientState +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); +GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; +#define glEdgeFlagPointer glad_glEdgeFlagPointer +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); +GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; +#define glEnableClientState glad_glEnableClientState +typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; +#define glIndexPointer glad_glIndexPointer +typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); +GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; +#define glInterleavedArrays glad_glInterleavedArrays +typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; +#define glNormalPointer glad_glNormalPointer +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; +#define glTexCoordPointer glad_glTexCoordPointer +typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; +#define glVertexPointer glad_glVertexPointer +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); +GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; +#define glAreTexturesResident glad_glAreTexturesResident +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); +GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; +#define glPrioritizeTextures glad_glPrioritizeTextures +typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); +GLAPI PFNGLINDEXUBPROC glad_glIndexub; +#define glIndexub glad_glIndexub +typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); +GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; +#define glIndexubv glad_glIndexubv +typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void); +GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; +#define glPopClientAttrib glad_glPopClientAttrib +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); +GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; +#define glPushClientAttrib glad_glPushClientAttrib +#endif +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +GLAPI int GLAD_GL_VERSION_1_2; +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; +#define glDrawRangeElements glad_glDrawRangeElements +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; +#define glTexImage3D glad_glTexImage3D +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; +#define glTexSubImage3D glad_glTexSubImage3D +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; +#define glCopyTexSubImage3D glad_glCopyTexSubImage3D +#endif +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +GLAPI int GLAD_GL_VERSION_1_3; +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); +GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +#define glActiveTexture glad_glActiveTexture +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); +GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; +#define glSampleCoverage glad_glSampleCoverage +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; +#define glCompressedTexImage3D glad_glCompressedTexImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; +#define glCompressedTexImage2D glad_glCompressedTexImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; +#define glCompressedTexImage1D glad_glCompressedTexImage1D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; +#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; +#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; +#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); +GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; +#define glGetCompressedTexImage glad_glGetCompressedTexImage +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); +GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; +#define glClientActiveTexture glad_glClientActiveTexture +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); +GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; +#define glMultiTexCoord1d glad_glMultiTexCoord1d +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; +#define glMultiTexCoord1dv glad_glMultiTexCoord1dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); +GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; +#define glMultiTexCoord1f glad_glMultiTexCoord1f +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; +#define glMultiTexCoord1fv glad_glMultiTexCoord1fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); +GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; +#define glMultiTexCoord1i glad_glMultiTexCoord1i +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; +#define glMultiTexCoord1iv glad_glMultiTexCoord1iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); +GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; +#define glMultiTexCoord1s glad_glMultiTexCoord1s +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; +#define glMultiTexCoord1sv glad_glMultiTexCoord1sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); +GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; +#define glMultiTexCoord2d glad_glMultiTexCoord2d +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; +#define glMultiTexCoord2dv glad_glMultiTexCoord2dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); +GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; +#define glMultiTexCoord2f glad_glMultiTexCoord2f +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; +#define glMultiTexCoord2fv glad_glMultiTexCoord2fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); +GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; +#define glMultiTexCoord2i glad_glMultiTexCoord2i +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; +#define glMultiTexCoord2iv glad_glMultiTexCoord2iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); +GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; +#define glMultiTexCoord2s glad_glMultiTexCoord2s +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; +#define glMultiTexCoord2sv glad_glMultiTexCoord2sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; +#define glMultiTexCoord3d glad_glMultiTexCoord3d +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; +#define glMultiTexCoord3dv glad_glMultiTexCoord3dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; +#define glMultiTexCoord3f glad_glMultiTexCoord3f +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; +#define glMultiTexCoord3fv glad_glMultiTexCoord3fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); +GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; +#define glMultiTexCoord3i glad_glMultiTexCoord3i +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; +#define glMultiTexCoord3iv glad_glMultiTexCoord3iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; +#define glMultiTexCoord3s glad_glMultiTexCoord3s +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; +#define glMultiTexCoord3sv glad_glMultiTexCoord3sv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; +#define glMultiTexCoord4d glad_glMultiTexCoord4d +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); +GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; +#define glMultiTexCoord4dv glad_glMultiTexCoord4dv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; +#define glMultiTexCoord4f glad_glMultiTexCoord4f +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); +GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; +#define glMultiTexCoord4fv glad_glMultiTexCoord4fv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; +#define glMultiTexCoord4i glad_glMultiTexCoord4i +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); +GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; +#define glMultiTexCoord4iv glad_glMultiTexCoord4iv +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; +#define glMultiTexCoord4s glad_glMultiTexCoord4s +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); +GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; +#define glMultiTexCoord4sv glad_glMultiTexCoord4sv +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; +#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; +#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); +GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; +#define glMultTransposeMatrixf glad_glMultTransposeMatrixf +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); +GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; +#define glMultTransposeMatrixd glad_glMultTransposeMatrixd +#endif +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +GLAPI int GLAD_GL_VERSION_1_4; +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; +#define glBlendFuncSeparate glad_glBlendFuncSeparate +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; +#define glMultiDrawArrays glad_glMultiDrawArrays +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; +#define glMultiDrawElements glad_glMultiDrawElements +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); +GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; +#define glPointParameterf glad_glPointParameterf +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); +GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; +#define glPointParameterfv glad_glPointParameterfv +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); +GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; +#define glPointParameteri glad_glPointParameteri +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); +GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; +#define glPointParameteriv glad_glPointParameteriv +typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); +GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; +#define glFogCoordf glad_glFogCoordf +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); +GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; +#define glFogCoordfv glad_glFogCoordfv +typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); +GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; +#define glFogCoordd glad_glFogCoordd +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); +GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; +#define glFogCoorddv glad_glFogCoorddv +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; +#define glFogCoordPointer glad_glFogCoordPointer +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; +#define glSecondaryColor3b glad_glSecondaryColor3b +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); +GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; +#define glSecondaryColor3bv glad_glSecondaryColor3bv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; +#define glSecondaryColor3d glad_glSecondaryColor3d +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); +GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; +#define glSecondaryColor3dv glad_glSecondaryColor3dv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; +#define glSecondaryColor3f glad_glSecondaryColor3f +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); +GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; +#define glSecondaryColor3fv glad_glSecondaryColor3fv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); +GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; +#define glSecondaryColor3i glad_glSecondaryColor3i +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); +GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; +#define glSecondaryColor3iv glad_glSecondaryColor3iv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; +#define glSecondaryColor3s glad_glSecondaryColor3s +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); +GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; +#define glSecondaryColor3sv glad_glSecondaryColor3sv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; +#define glSecondaryColor3ub glad_glSecondaryColor3ub +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); +GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; +#define glSecondaryColor3ubv glad_glSecondaryColor3ubv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; +#define glSecondaryColor3ui glad_glSecondaryColor3ui +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); +GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; +#define glSecondaryColor3uiv glad_glSecondaryColor3uiv +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; +#define glSecondaryColor3us glad_glSecondaryColor3us +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); +GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; +#define glSecondaryColor3usv glad_glSecondaryColor3usv +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; +#define glSecondaryColorPointer glad_glSecondaryColorPointer +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); +GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; +#define glWindowPos2d glad_glWindowPos2d +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); +GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; +#define glWindowPos2dv glad_glWindowPos2dv +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); +GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; +#define glWindowPos2f glad_glWindowPos2f +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); +GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; +#define glWindowPos2fv glad_glWindowPos2fv +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); +GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; +#define glWindowPos2i glad_glWindowPos2i +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); +GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; +#define glWindowPos2iv glad_glWindowPos2iv +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); +GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; +#define glWindowPos2s glad_glWindowPos2s +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); +GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; +#define glWindowPos2sv glad_glWindowPos2sv +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; +#define glWindowPos3d glad_glWindowPos3d +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); +GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; +#define glWindowPos3dv glad_glWindowPos3dv +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; +#define glWindowPos3f glad_glWindowPos3f +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); +GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; +#define glWindowPos3fv glad_glWindowPos3fv +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); +GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; +#define glWindowPos3i glad_glWindowPos3i +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); +GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; +#define glWindowPos3iv glad_glWindowPos3iv +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); +GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; +#define glWindowPos3s glad_glWindowPos3s +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); +GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; +#define glWindowPos3sv glad_glWindowPos3sv +typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; +#define glBlendColor glad_glBlendColor +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); +GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; +#define glBlendEquation glad_glBlendEquation +#endif +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +GLAPI int GLAD_GL_VERSION_1_5; +typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); +GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; +#define glGenQueries glad_glGenQueries +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); +GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; +#define glDeleteQueries glad_glDeleteQueries +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); +GLAPI PFNGLISQUERYPROC glad_glIsQuery; +#define glIsQuery glad_glIsQuery +typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); +GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; +#define glBeginQuery glad_glBeginQuery +typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); +GLAPI PFNGLENDQUERYPROC glad_glEndQuery; +#define glEndQuery glad_glEndQuery +typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; +#define glGetQueryiv glad_glGetQueryiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); +GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; +#define glGetQueryObjectiv glad_glGetQueryObjectiv +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); +GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; +#define glGetQueryObjectuiv glad_glGetQueryObjectuiv +typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); +GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; +#define glBindBuffer glad_glBindBuffer +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); +GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +#define glDeleteBuffers glad_glDeleteBuffers +typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); +GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; +#define glGenBuffers glad_glGenBuffers +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); +GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; +#define glIsBuffer glad_glIsBuffer +typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; +#define glBufferData glad_glBufferData +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; +#define glBufferSubData glad_glBufferSubData +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; +#define glGetBufferSubData glad_glGetBufferSubData +typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); +GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; +#define glMapBuffer glad_glMapBuffer +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); +GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; +#define glUnmapBuffer glad_glUnmapBuffer +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; +#define glGetBufferParameteriv glad_glGetBufferParameteriv +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); +GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; +#define glGetBufferPointerv glad_glGetBufferPointerv +#endif +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +GLAPI int GLAD_GL_VERSION_2_0; +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); +GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; +#define glBlendEquationSeparate glad_glBlendEquationSeparate +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); +GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; +#define glDrawBuffers glad_glDrawBuffers +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; +#define glStencilOpSeparate glad_glStencilOpSeparate +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; +#define glStencilFuncSeparate glad_glStencilFuncSeparate +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); +GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; +#define glStencilMaskSeparate glad_glStencilMaskSeparate +typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; +#define glAttachShader glad_glAttachShader +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); +GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +#define glBindAttribLocation glad_glBindAttribLocation +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); +GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; +#define glCompileShader glad_glCompileShader +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(void); +GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +#define glCreateProgram glad_glCreateProgram +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); +GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; +#define glCreateShader glad_glCreateShader +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); +GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +#define glDeleteProgram glad_glDeleteProgram +typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); +GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; +#define glDeleteShader glad_glDeleteShader +typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); +GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; +#define glDetachShader glad_glDetachShader +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +#define glDisableVertexAttribArray glad_glDisableVertexAttribArray +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +#define glEnableVertexAttribArray glad_glEnableVertexAttribArray +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; +#define glGetActiveAttrib glad_glGetActiveAttrib +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; +#define glGetActiveUniform glad_glGetActiveUniform +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; +#define glGetAttachedShaders glad_glGetAttachedShaders +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; +#define glGetAttribLocation glad_glGetAttribLocation +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); +GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +#define glGetProgramiv glad_glGetProgramiv +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +#define glGetProgramInfoLog glad_glGetProgramInfoLog +typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); +GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; +#define glGetShaderiv glad_glGetShaderiv +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +#define glGetShaderInfoLog glad_glGetShaderInfoLog +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; +#define glGetShaderSource glad_glGetShaderSource +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +#define glGetUniformLocation glad_glGetUniformLocation +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); +GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; +#define glGetUniformfv glad_glGetUniformfv +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); +GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; +#define glGetUniformiv glad_glGetUniformiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); +GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; +#define glGetVertexAttribdv glad_glGetVertexAttribdv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); +GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; +#define glGetVertexAttribfv glad_glGetVertexAttribfv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; +#define glGetVertexAttribiv glad_glGetVertexAttribiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); +GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; +#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); +GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; +#define glIsProgram glad_glIsProgram +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); +GLAPI PFNGLISSHADERPROC glad_glIsShader; +#define glIsShader glad_glIsShader +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); +GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; +#define glLinkProgram glad_glLinkProgram +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; +#define glShaderSource glad_glShaderSource +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); +GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; +#define glUseProgram glad_glUseProgram +typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; +#define glUniform1f glad_glUniform1f +typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); +GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; +#define glUniform2f glad_glUniform2f +typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; +#define glUniform3f glad_glUniform3f +typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; +#define glUniform4f glad_glUniform4f +typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; +#define glUniform1i glad_glUniform1i +typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); +GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; +#define glUniform2i glad_glUniform2i +typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); +GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; +#define glUniform3i glad_glUniform3i +typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; +#define glUniform4i glad_glUniform4i +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; +#define glUniform1fv glad_glUniform1fv +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; +#define glUniform2fv glad_glUniform2fv +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; +#define glUniform3fv glad_glUniform3fv +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); +GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; +#define glUniform4fv glad_glUniform4fv +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; +#define glUniform1iv glad_glUniform1iv +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; +#define glUniform2iv glad_glUniform2iv +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; +#define glUniform3iv glad_glUniform3iv +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); +GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; +#define glUniform4iv glad_glUniform4iv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; +#define glUniformMatrix2fv glad_glUniformMatrix2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; +#define glUniformMatrix3fv glad_glUniformMatrix3fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +#define glUniformMatrix4fv glad_glUniformMatrix4fv +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); +GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; +#define glValidateProgram glad_glValidateProgram +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); +GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; +#define glVertexAttrib1d glad_glVertexAttrib1d +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; +#define glVertexAttrib1dv glad_glVertexAttrib1dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); +GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; +#define glVertexAttrib1f glad_glVertexAttrib1f +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; +#define glVertexAttrib1fv glad_glVertexAttrib1fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); +GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; +#define glVertexAttrib1s glad_glVertexAttrib1s +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; +#define glVertexAttrib1sv glad_glVertexAttrib1sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); +GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; +#define glVertexAttrib2d glad_glVertexAttrib2d +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; +#define glVertexAttrib2dv glad_glVertexAttrib2dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); +GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; +#define glVertexAttrib2f glad_glVertexAttrib2f +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; +#define glVertexAttrib2fv glad_glVertexAttrib2fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); +GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; +#define glVertexAttrib2s glad_glVertexAttrib2s +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; +#define glVertexAttrib2sv glad_glVertexAttrib2sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; +#define glVertexAttrib3d glad_glVertexAttrib3d +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; +#define glVertexAttrib3dv glad_glVertexAttrib3dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; +#define glVertexAttrib3f glad_glVertexAttrib3f +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; +#define glVertexAttrib3fv glad_glVertexAttrib3fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; +#define glVertexAttrib3s glad_glVertexAttrib3s +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; +#define glVertexAttrib3sv glad_glVertexAttrib3sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; +#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; +#define glVertexAttrib4Niv glad_glVertexAttrib4Niv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; +#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; +#define glVertexAttrib4Nub glad_glVertexAttrib4Nub +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; +#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; +#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; +#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; +#define glVertexAttrib4bv glad_glVertexAttrib4bv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; +#define glVertexAttrib4d glad_glVertexAttrib4d +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); +GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; +#define glVertexAttrib4dv glad_glVertexAttrib4dv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; +#define glVertexAttrib4f glad_glVertexAttrib4f +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); +GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; +#define glVertexAttrib4fv glad_glVertexAttrib4fv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; +#define glVertexAttrib4iv glad_glVertexAttrib4iv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; +#define glVertexAttrib4s glad_glVertexAttrib4s +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; +#define glVertexAttrib4sv glad_glVertexAttrib4sv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; +#define glVertexAttrib4ubv glad_glVertexAttrib4ubv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; +#define glVertexAttrib4uiv glad_glVertexAttrib4uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; +#define glVertexAttrib4usv glad_glVertexAttrib4usv +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +#define glVertexAttribPointer glad_glVertexAttribPointer +#endif +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +GLAPI int GLAD_GL_VERSION_2_1; +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; +#define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; +#define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; +#define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; +#define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; +#define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; +#define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv +#endif +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +GLAPI int GLAD_GL_VERSION_3_0; +typedef void (APIENTRYP PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI PFNGLCOLORMASKIPROC glad_glColorMaski; +#define glColorMaski glad_glColorMaski +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); +GLAPI PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; +#define glGetBooleani_v glad_glGetBooleani_v +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint *data); +GLAPI PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; +#define glGetIntegeri_v glad_glGetIntegeri_v +typedef void (APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); +GLAPI PFNGLENABLEIPROC glad_glEnablei; +#define glEnablei glad_glEnablei +typedef void (APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); +GLAPI PFNGLDISABLEIPROC glad_glDisablei; +#define glDisablei glad_glDisablei +typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC)(GLenum target, GLuint index); +GLAPI PFNGLISENABLEDIPROC glad_glIsEnabledi; +#define glIsEnabledi glad_glIsEnabledi +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); +GLAPI PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; +#define glBeginTransformFeedback glad_glBeginTransformFeedback +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(void); +GLAPI PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; +#define glEndTransformFeedback glad_glEndTransformFeedback +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; +#define glBindBufferRange glad_glBindBufferRange +typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); +GLAPI PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; +#define glBindBufferBase glad_glBindBufferBase +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; +#define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; +#define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying +typedef void (APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); +GLAPI PFNGLCLAMPCOLORPROC glad_glClampColor; +#define glClampColor glad_glClampColor +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); +GLAPI PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; +#define glBeginConditionalRender glad_glBeginConditionalRender +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(void); +GLAPI PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; +#define glEndConditionalRender glad_glEndConditionalRender +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; +#define glVertexAttribIPointer glad_glVertexAttribIPointer +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint *params); +GLAPI PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; +#define glGetVertexAttribIiv glad_glGetVertexAttribIiv +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint *params); +GLAPI PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; +#define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); +GLAPI PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; +#define glVertexAttribI1i glad_glVertexAttribI1i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); +GLAPI PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; +#define glVertexAttribI2i glad_glVertexAttribI2i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); +GLAPI PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; +#define glVertexAttribI3i glad_glVertexAttribI3i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; +#define glVertexAttribI4i glad_glVertexAttribI4i +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); +GLAPI PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; +#define glVertexAttribI1ui glad_glVertexAttribI1ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); +GLAPI PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; +#define glVertexAttribI2ui glad_glVertexAttribI2ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; +#define glVertexAttribI3ui glad_glVertexAttribI3ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; +#define glVertexAttribI4ui glad_glVertexAttribI4ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; +#define glVertexAttribI1iv glad_glVertexAttribI1iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; +#define glVertexAttribI2iv glad_glVertexAttribI2iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; +#define glVertexAttribI3iv glad_glVertexAttribI3iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint *v); +GLAPI PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; +#define glVertexAttribI4iv glad_glVertexAttribI4iv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; +#define glVertexAttribI1uiv glad_glVertexAttribI1uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; +#define glVertexAttribI2uiv glad_glVertexAttribI2uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; +#define glVertexAttribI3uiv glad_glVertexAttribI3uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint *v); +GLAPI PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; +#define glVertexAttribI4uiv glad_glVertexAttribI4uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte *v); +GLAPI PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; +#define glVertexAttribI4bv glad_glVertexAttribI4bv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort *v); +GLAPI PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; +#define glVertexAttribI4sv glad_glVertexAttribI4sv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte *v); +GLAPI PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; +#define glVertexAttribI4ubv glad_glVertexAttribI4ubv +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort *v); +GLAPI PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; +#define glVertexAttribI4usv glad_glVertexAttribI4usv +typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint *params); +GLAPI PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; +#define glGetUniformuiv glad_glGetUniformuiv +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar *name); +GLAPI PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; +#define glBindFragDataLocation glad_glBindFragDataLocation +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; +#define glGetFragDataLocation glad_glGetFragDataLocation +typedef void (APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); +GLAPI PFNGLUNIFORM1UIPROC glad_glUniform1ui; +#define glUniform1ui glad_glUniform1ui +typedef void (APIENTRYP PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); +GLAPI PFNGLUNIFORM2UIPROC glad_glUniform2ui; +#define glUniform2ui glad_glUniform2ui +typedef void (APIENTRYP PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI PFNGLUNIFORM3UIPROC glad_glUniform3ui; +#define glUniform3ui glad_glUniform3ui +typedef void (APIENTRYP PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI PFNGLUNIFORM4UIPROC glad_glUniform4ui; +#define glUniform4ui glad_glUniform4ui +typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; +#define glUniform1uiv glad_glUniform1uiv +typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; +#define glUniform2uiv glad_glUniform2uiv +typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; +#define glUniform3uiv glad_glUniform3uiv +typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint *value); +GLAPI PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; +#define glUniform4uiv glad_glUniform4uiv +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint *params); +GLAPI PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; +#define glTexParameterIiv glad_glTexParameterIiv +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint *params); +GLAPI PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; +#define glTexParameterIuiv glad_glTexParameterIuiv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; +#define glGetTexParameterIiv glad_glGetTexParameterIiv +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint *params); +GLAPI PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; +#define glGetTexParameterIuiv glad_glGetTexParameterIuiv +typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; +#define glClearBufferiv glad_glClearBufferiv +typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; +#define glClearBufferuiv glad_glClearBufferuiv +typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; +#define glClearBufferfv glad_glClearBufferfv +typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; +#define glClearBufferfi glad_glClearBufferfi +typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); +GLAPI PFNGLGETSTRINGIPROC glad_glGetStringi; +#define glGetStringi glad_glGetStringi +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); +GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; +#define glIsRenderbuffer glad_glIsRenderbuffer +typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); +GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; +#define glBindRenderbuffer glad_glBindRenderbuffer +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); +GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; +#define glDeleteRenderbuffers glad_glDeleteRenderbuffers +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); +GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; +#define glGenRenderbuffers glad_glGenRenderbuffers +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; +#define glRenderbufferStorage glad_glRenderbufferStorage +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; +#define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); +GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; +#define glIsFramebuffer glad_glIsFramebuffer +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); +GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; +#define glBindFramebuffer glad_glBindFramebuffer +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); +GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; +#define glDeleteFramebuffers glad_glDeleteFramebuffers +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); +GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; +#define glGenFramebuffers glad_glGenFramebuffers +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); +GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; +#define glCheckFramebufferStatus glad_glCheckFramebufferStatus +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; +#define glFramebufferTexture1D glad_glFramebufferTexture1D +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; +#define glFramebufferTexture2D glad_glFramebufferTexture2D +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; +#define glFramebufferTexture3D glad_glFramebufferTexture3D +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; +#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; +#define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv +typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); +GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; +#define glGenerateMipmap glad_glGenerateMipmap +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; +#define glBlitFramebuffer glad_glBlitFramebuffer +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; +#define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; +#define glFramebufferTextureLayer glad_glFramebufferTextureLayer +typedef void * (APIENTRYP PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; +#define glMapBufferRange glad_glMapBufferRange +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); +GLAPI PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; +#define glFlushMappedBufferRange glad_glFlushMappedBufferRange +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); +GLAPI PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; +#define glBindVertexArray glad_glBindVertexArray +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); +GLAPI PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; +#define glDeleteVertexArrays glad_glDeleteVertexArrays +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); +GLAPI PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; +#define glGenVertexArrays glad_glGenVertexArrays +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); +GLAPI PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; +#define glIsVertexArray glad_glIsVertexArray +#endif +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +GLAPI int GLAD_GL_VERSION_3_1; +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +GLAPI PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; +#define glDrawArraysInstanced glad_glDrawArraysInstanced +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +GLAPI PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; +#define glDrawElementsInstanced glad_glDrawElementsInstanced +typedef void (APIENTRYP PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); +GLAPI PFNGLTEXBUFFERPROC glad_glTexBuffer; +#define glTexBuffer glad_glTexBuffer +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); +GLAPI PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; +#define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; +#define glCopyBufferSubData glad_glCopyBufferSubData +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +GLAPI PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; +#define glGetUniformIndices glad_glGetUniformIndices +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +GLAPI PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; +#define glGetActiveUniformsiv glad_glGetActiveUniformsiv +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +GLAPI PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; +#define glGetActiveUniformName glad_glGetActiveUniformName +typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar *uniformBlockName); +GLAPI PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; +#define glGetUniformBlockIndex glad_glGetUniformBlockIndex +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; +#define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; +#define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName +typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +GLAPI PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; +#define glUniformBlockBinding glad_glUniformBlockBinding +#endif +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +GLAPI int GLAD_GL_VERSION_3_2; +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; +#define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; +#define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; +#define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; +#define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); +GLAPI PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; +#define glProvokingVertex glad_glProvokingVertex +typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); +GLAPI PFNGLFENCESYNCPROC glad_glFenceSync; +#define glFenceSync glad_glFenceSync +typedef GLboolean (APIENTRYP PFNGLISSYNCPROC)(GLsync sync); +GLAPI PFNGLISSYNCPROC glad_glIsSync; +#define glIsSync glad_glIsSync +typedef void (APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); +GLAPI PFNGLDELETESYNCPROC glad_glDeleteSync; +#define glDeleteSync glad_glDeleteSync +typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; +#define glClientWaitSync glad_glClientWaitSync +typedef void (APIENTRYP PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI PFNGLWAITSYNCPROC glad_glWaitSync; +#define glWaitSync glad_glWaitSync +typedef void (APIENTRYP PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 *data); +GLAPI PFNGLGETINTEGER64VPROC glad_glGetInteger64v; +#define glGetInteger64v glad_glGetInteger64v +typedef void (APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +GLAPI PFNGLGETSYNCIVPROC glad_glGetSynciv; +#define glGetSynciv glad_glGetSynciv +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 *data); +GLAPI PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; +#define glGetInteger64i_v glad_glGetInteger64i_v +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 *params); +GLAPI PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; +#define glGetBufferParameteri64v glad_glGetBufferParameteri64v +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; +#define glFramebufferTexture glad_glFramebufferTexture +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; +#define glTexImage2DMultisample glad_glTexImage2DMultisample +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; +#define glTexImage3DMultisample glad_glTexImage3DMultisample +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); +GLAPI PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; +#define glGetMultisamplefv glad_glGetMultisamplefv +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); +GLAPI PFNGLSAMPLEMASKIPROC glad_glSampleMaski; +#define glSampleMaski glad_glSampleMaski +#endif +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +GLAPI int GLAD_GL_VERSION_3_3; +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)(GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GLAPI PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; +#define glBindFragDataLocationIndexed glad_glBindFragDataLocationIndexed +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC)(GLuint program, const GLchar *name); +GLAPI PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; +#define glGetFragDataIndex glad_glGetFragDataIndex +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC)(GLsizei count, GLuint *samplers); +GLAPI PFNGLGENSAMPLERSPROC glad_glGenSamplers; +#define glGenSamplers glad_glGenSamplers +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC)(GLsizei count, const GLuint *samplers); +GLAPI PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; +#define glDeleteSamplers glad_glDeleteSamplers +typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC)(GLuint sampler); +GLAPI PFNGLISSAMPLERPROC glad_glIsSampler; +#define glIsSampler glad_glIsSampler +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); +GLAPI PFNGLBINDSAMPLERPROC glad_glBindSampler; +#define glBindSampler glad_glBindSampler +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC)(GLuint sampler, GLenum pname, GLint param); +GLAPI PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; +#define glSamplerParameteri glad_glSamplerParameteri +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, const GLint *param); +GLAPI PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; +#define glSamplerParameteriv glad_glSamplerParameteriv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC)(GLuint sampler, GLenum pname, GLfloat param); +GLAPI PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; +#define glSamplerParameterf glad_glSamplerParameterf +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, const GLfloat *param); +GLAPI PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; +#define glSamplerParameterfv glad_glSamplerParameterfv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, const GLint *param); +GLAPI PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; +#define glSamplerParameterIiv glad_glSamplerParameterIiv +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, const GLuint *param); +GLAPI PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; +#define glSamplerParameterIuiv glad_glSamplerParameterIuiv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, GLint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; +#define glGetSamplerParameteriv glad_glGetSamplerParameteriv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, GLint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; +#define glGetSamplerParameterIiv glad_glGetSamplerParameterIiv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, GLfloat *params); +GLAPI PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; +#define glGetSamplerParameterfv glad_glGetSamplerParameterfv +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, GLuint *params); +GLAPI PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; +#define glGetSamplerParameterIuiv glad_glGetSamplerParameterIuiv +typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); +GLAPI PFNGLQUERYCOUNTERPROC glad_glQueryCounter; +#define glQueryCounter glad_glQueryCounter +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC)(GLuint id, GLenum pname, GLint64 *params); +GLAPI PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; +#define glGetQueryObjecti64v glad_glGetQueryObjecti64v +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC)(GLuint id, GLenum pname, GLuint64 *params); +GLAPI PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; +#define glGetQueryObjectui64v glad_glGetQueryObjectui64v +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC)(GLuint index, GLuint divisor); +GLAPI PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; +#define glVertexAttribDivisor glad_glVertexAttribDivisor +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; +#define glVertexAttribP1ui glad_glVertexAttribP1ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; +#define glVertexAttribP1uiv glad_glVertexAttribP1uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; +#define glVertexAttribP2ui glad_glVertexAttribP2ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; +#define glVertexAttribP2uiv glad_glVertexAttribP2uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; +#define glVertexAttribP3ui glad_glVertexAttribP3ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; +#define glVertexAttribP3uiv glad_glVertexAttribP3uiv +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; +#define glVertexAttribP4ui glad_glVertexAttribP4ui +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; +#define glVertexAttribP4uiv glad_glVertexAttribP4uiv +typedef void (APIENTRYP PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP2UIPROC glad_glVertexP2ui; +#define glVertexP2ui glad_glVertexP2ui +typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; +#define glVertexP2uiv glad_glVertexP2uiv +typedef void (APIENTRYP PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP3UIPROC glad_glVertexP3ui; +#define glVertexP3ui glad_glVertexP3ui +typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; +#define glVertexP3uiv glad_glVertexP3uiv +typedef void (APIENTRYP PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); +GLAPI PFNGLVERTEXP4UIPROC glad_glVertexP4ui; +#define glVertexP4ui glad_glVertexP4ui +typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC)(GLenum type, const GLuint *value); +GLAPI PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; +#define glVertexP4uiv glad_glVertexP4uiv +typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; +#define glTexCoordP1ui glad_glTexCoordP1ui +typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; +#define glTexCoordP1uiv glad_glTexCoordP1uiv +typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; +#define glTexCoordP2ui glad_glTexCoordP2ui +typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; +#define glTexCoordP2uiv glad_glTexCoordP2uiv +typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; +#define glTexCoordP3ui glad_glTexCoordP3ui +typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; +#define glTexCoordP3uiv glad_glTexCoordP3uiv +typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; +#define glTexCoordP4ui glad_glTexCoordP4ui +typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; +#define glTexCoordP4uiv glad_glTexCoordP4uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; +#define glMultiTexCoordP1ui glad_glMultiTexCoordP1ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; +#define glMultiTexCoordP1uiv glad_glMultiTexCoordP1uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; +#define glMultiTexCoordP2ui glad_glMultiTexCoordP2ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; +#define glMultiTexCoordP2uiv glad_glMultiTexCoordP2uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; +#define glMultiTexCoordP3ui glad_glMultiTexCoordP3ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; +#define glMultiTexCoordP3uiv glad_glMultiTexCoordP3uiv +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC)(GLenum texture, GLenum type, GLuint coords); +GLAPI PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; +#define glMultiTexCoordP4ui glad_glMultiTexCoordP4ui +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); +GLAPI PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; +#define glMultiTexCoordP4uiv glad_glMultiTexCoordP4uiv +typedef void (APIENTRYP PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); +GLAPI PFNGLNORMALP3UIPROC glad_glNormalP3ui; +#define glNormalP3ui glad_glNormalP3ui +typedef void (APIENTRYP PFNGLNORMALP3UIVPROC)(GLenum type, const GLuint *coords); +GLAPI PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; +#define glNormalP3uiv glad_glNormalP3uiv +typedef void (APIENTRYP PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLCOLORP3UIPROC glad_glColorP3ui; +#define glColorP3ui glad_glColorP3ui +typedef void (APIENTRYP PFNGLCOLORP3UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLCOLORP3UIVPROC glad_glColorP3uiv; +#define glColorP3uiv glad_glColorP3uiv +typedef void (APIENTRYP PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLCOLORP4UIPROC glad_glColorP4ui; +#define glColorP4ui glad_glColorP4ui +typedef void (APIENTRYP PFNGLCOLORP4UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLCOLORP4UIVPROC glad_glColorP4uiv; +#define glColorP4uiv glad_glColorP4uiv +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC)(GLenum type, GLuint color); +GLAPI PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; +#define glSecondaryColorP3ui glad_glSecondaryColorP3ui +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC)(GLenum type, const GLuint *color); +GLAPI PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; +#define glSecondaryColorP3uiv glad_glSecondaryColorP3uiv +#endif +#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 +#define GL_DEBUG_SOURCE_API_ARB 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A +#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B +#define GL_DEBUG_TYPE_ERROR_ARB 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E +#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 +#define GL_DEBUG_TYPE_OTHER_ARB 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 +#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +#ifndef GL_ARB_debug_output +#define GL_ARB_debug_output 1 +GLAPI int GLAD_GL_ARB_debug_output; +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI PFNGLDEBUGMESSAGECONTROLARBPROC glad_glDebugMessageControlARB; +#define glDebugMessageControlARB glad_glDebugMessageControlARB +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI PFNGLDEBUGMESSAGEINSERTARBPROC glad_glDebugMessageInsertARB; +#define glDebugMessageInsertARB glad_glDebugMessageInsertARB +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC)(GLDEBUGPROCARB callback, const void *userParam); +GLAPI PFNGLDEBUGMESSAGECALLBACKARBPROC glad_glDebugMessageCallbackARB; +#define glDebugMessageCallbackARB glad_glDebugMessageCallbackARB +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GLAPI PFNGLGETDEBUGMESSAGELOGARBPROC glad_glGetDebugMessageLogARB; +#define glGetDebugMessageLogARB glad_glGetDebugMessageLogARB +#endif +#ifndef GL_ARB_framebuffer_object +#define GL_ARB_framebuffer_object 1 +GLAPI int GLAD_GL_ARB_framebuffer_object; +#endif +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 +GLAPI int GLAD_GL_EXT_framebuffer_blit; +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI PFNGLBLITFRAMEBUFFEREXTPROC glad_glBlitFramebufferEXT; +#define glBlitFramebufferEXT glad_glBlitFramebufferEXT +#endif +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 +GLAPI int GLAD_GL_EXT_framebuffer_multisample; +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glad_glRenderbufferStorageMultisampleEXT; +#define glRenderbufferStorageMultisampleEXT glad_glRenderbufferStorageMultisampleEXT +#endif +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +GLAPI int GLAD_GL_EXT_framebuffer_object; +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC)(GLuint renderbuffer); +GLAPI PFNGLISRENDERBUFFEREXTPROC glad_glIsRenderbufferEXT; +#define glIsRenderbufferEXT glad_glIsRenderbufferEXT +typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC)(GLenum target, GLuint renderbuffer); +GLAPI PFNGLBINDRENDERBUFFEREXTPROC glad_glBindRenderbufferEXT; +#define glBindRenderbufferEXT glad_glBindRenderbufferEXT +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC)(GLsizei n, const GLuint *renderbuffers); +GLAPI PFNGLDELETERENDERBUFFERSEXTPROC glad_glDeleteRenderbuffersEXT; +#define glDeleteRenderbuffersEXT glad_glDeleteRenderbuffersEXT +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC)(GLsizei n, GLuint *renderbuffers); +GLAPI PFNGLGENRENDERBUFFERSEXTPROC glad_glGenRenderbuffersEXT; +#define glGenRenderbuffersEXT glad_glGenRenderbuffersEXT +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI PFNGLRENDERBUFFERSTORAGEEXTPROC glad_glRenderbufferStorageEXT; +#define glRenderbufferStorageEXT glad_glRenderbufferStorageEXT +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)(GLenum target, GLenum pname, GLint *params); +GLAPI PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glad_glGetRenderbufferParameterivEXT; +#define glGetRenderbufferParameterivEXT glad_glGetRenderbufferParameterivEXT +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC)(GLuint framebuffer); +GLAPI PFNGLISFRAMEBUFFEREXTPROC glad_glIsFramebufferEXT; +#define glIsFramebufferEXT glad_glIsFramebufferEXT +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC)(GLenum target, GLuint framebuffer); +GLAPI PFNGLBINDFRAMEBUFFEREXTPROC glad_glBindFramebufferEXT; +#define glBindFramebufferEXT glad_glBindFramebufferEXT +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC)(GLsizei n, const GLuint *framebuffers); +GLAPI PFNGLDELETEFRAMEBUFFERSEXTPROC glad_glDeleteFramebuffersEXT; +#define glDeleteFramebuffersEXT glad_glDeleteFramebuffersEXT +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC)(GLsizei n, GLuint *framebuffers); +GLAPI PFNGLGENFRAMEBUFFERSEXTPROC glad_glGenFramebuffersEXT; +#define glGenFramebuffersEXT glad_glGenFramebuffersEXT +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)(GLenum target); +GLAPI PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glad_glCheckFramebufferStatusEXT; +#define glCheckFramebufferStatusEXT glad_glCheckFramebufferStatusEXT +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glad_glFramebufferTexture1DEXT; +#define glFramebufferTexture1DEXT glad_glFramebufferTexture1DEXT +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glad_glFramebufferTexture2DEXT; +#define glFramebufferTexture2DEXT glad_glFramebufferTexture2DEXT +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glad_glFramebufferTexture3DEXT; +#define glFramebufferTexture3DEXT glad_glFramebufferTexture3DEXT +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glad_glFramebufferRenderbufferEXT; +#define glFramebufferRenderbufferEXT glad_glFramebufferRenderbufferEXT +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glad_glGetFramebufferAttachmentParameterivEXT; +#define glGetFramebufferAttachmentParameterivEXT glad_glGetFramebufferAttachmentParameterivEXT +typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC)(GLenum target); +GLAPI PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT; +#define glGenerateMipmapEXT glad_glGenerateMipmapEXT +#endif + +#ifdef __cplusplus +} +#endif + +#endif