Path: blob/master/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
20914 views
/**************************************************************************/1/* renderer_canvas_render_rd.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "renderer_canvas_render_rd.h"3132#include "core/config/project_settings.h"33#include "core/math/geometry_2d.h"34#include "core/math/math_defs.h"35#include "core/math/math_funcs.h"36#include "core/math/transform_interpolator.h"37#include "core/templates/fixed_vector.h"38#include "servers/rendering/renderer_rd/storage_rd/material_storage.h"39#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h"40#include "servers/rendering/renderer_rd/storage_rd/particles_storage.h"41#include "servers/rendering/renderer_rd/storage_rd/texture_storage.h"42#include "servers/rendering/rendering_server_default.h"4344void RendererCanvasRenderRD::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {45p_mat4[0] = p_transform.columns[0][0];46p_mat4[1] = p_transform.columns[0][1];47p_mat4[2] = 0;48p_mat4[3] = 0;49p_mat4[4] = p_transform.columns[1][0];50p_mat4[5] = p_transform.columns[1][1];51p_mat4[6] = 0;52p_mat4[7] = 0;53p_mat4[8] = 0;54p_mat4[9] = 0;55p_mat4[10] = 1;56p_mat4[11] = 0;57p_mat4[12] = p_transform.columns[2][0];58p_mat4[13] = p_transform.columns[2][1];59p_mat4[14] = 0;60p_mat4[15] = 1;61}6263void RendererCanvasRenderRD::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {64p_mat2x4[0] = p_transform.columns[0][0];65p_mat2x4[1] = p_transform.columns[1][0];66p_mat2x4[2] = 0;67p_mat2x4[3] = p_transform.columns[2][0];6869p_mat2x4[4] = p_transform.columns[0][1];70p_mat2x4[5] = p_transform.columns[1][1];71p_mat2x4[6] = 0;72p_mat2x4[7] = p_transform.columns[2][1];73}7475void RendererCanvasRenderRD::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {76p_mat2x3[0] = p_transform.columns[0][0];77p_mat2x3[1] = p_transform.columns[0][1];78p_mat2x3[2] = p_transform.columns[1][0];79p_mat2x3[3] = p_transform.columns[1][1];80p_mat2x3[4] = p_transform.columns[2][0];81p_mat2x3[5] = p_transform.columns[2][1];82}8384void RendererCanvasRenderRD::_update_transform_to_mat4(const Transform3D &p_transform, float *p_mat4) {85p_mat4[0] = p_transform.basis.rows[0][0];86p_mat4[1] = p_transform.basis.rows[1][0];87p_mat4[2] = p_transform.basis.rows[2][0];88p_mat4[3] = 0;89p_mat4[4] = p_transform.basis.rows[0][1];90p_mat4[5] = p_transform.basis.rows[1][1];91p_mat4[6] = p_transform.basis.rows[2][1];92p_mat4[7] = 0;93p_mat4[8] = p_transform.basis.rows[0][2];94p_mat4[9] = p_transform.basis.rows[1][2];95p_mat4[10] = p_transform.basis.rows[2][2];96p_mat4[11] = 0;97p_mat4[12] = p_transform.origin.x;98p_mat4[13] = p_transform.origin.y;99p_mat4[14] = p_transform.origin.z;100p_mat4[15] = 1;101}102103RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, const Vector<int> &p_bones, const Vector<float> &p_weights, int p_count) {104// Care must be taken to generate array formats105// in ways where they could be reused, so we will106// put single-occurring elements first, and repeated107// elements later. This way the generated formats are108// the same no matter the length of the arrays.109// This dramatically reduces the amount of pipeline objects110// that need to be created for these formats.111112RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();113114uint32_t vertex_count = p_points.size();115uint32_t stride = 2; //vertices always repeat116if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {117stride += 4;118}119if ((uint32_t)p_uvs.size() == vertex_count) {120stride += 2;121}122if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {123stride += 4;124}125126uint32_t buffer_size = stride * p_points.size();127128Vector<uint8_t> polygon_buffer;129polygon_buffer.resize(buffer_size * sizeof(float));130Vector<RD::VertexAttribute> descriptions;131descriptions.resize(5);132Vector<RID> buffers;133buffers.resize(5);134135{136uint8_t *r = polygon_buffer.ptrw();137float *fptr = reinterpret_cast<float *>(r);138uint32_t *uptr = reinterpret_cast<uint32_t *>(r);139uint32_t base_offset = 0;140{ //vertices141RD::VertexAttribute vd;142vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;143vd.offset = base_offset * sizeof(float);144vd.location = RS::ARRAY_VERTEX;145vd.stride = stride * sizeof(float);146147descriptions.write[0] = vd;148149const Vector2 *points_ptr = p_points.ptr();150151for (uint32_t i = 0; i < vertex_count; i++) {152fptr[base_offset + i * stride + 0] = points_ptr[i].x;153fptr[base_offset + i * stride + 1] = points_ptr[i].y;154}155156base_offset += 2;157}158159//colors160if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {161RD::VertexAttribute vd;162vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;163vd.offset = base_offset * sizeof(float);164vd.location = RS::ARRAY_COLOR;165vd.stride = stride * sizeof(float);166167descriptions.write[1] = vd;168169if (p_colors.size() == 1) {170Color color = p_colors[0];171for (uint32_t i = 0; i < vertex_count; i++) {172fptr[base_offset + i * stride + 0] = color.r;173fptr[base_offset + i * stride + 1] = color.g;174fptr[base_offset + i * stride + 2] = color.b;175fptr[base_offset + i * stride + 3] = color.a;176}177} else {178const Color *color_ptr = p_colors.ptr();179180for (uint32_t i = 0; i < vertex_count; i++) {181fptr[base_offset + i * stride + 0] = color_ptr[i].r;182fptr[base_offset + i * stride + 1] = color_ptr[i].g;183fptr[base_offset + i * stride + 2] = color_ptr[i].b;184fptr[base_offset + i * stride + 3] = color_ptr[i].a;185}186}187base_offset += 4;188} else {189RD::VertexAttribute vd;190vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;191vd.offset = 0;192vd.location = RS::ARRAY_COLOR;193vd.stride = 0;194195descriptions.write[1] = vd;196buffers.write[1] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_COLOR);197}198199//uvs200if ((uint32_t)p_uvs.size() == vertex_count) {201RD::VertexAttribute vd;202vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;203vd.offset = base_offset * sizeof(float);204vd.location = RS::ARRAY_TEX_UV;205vd.stride = stride * sizeof(float);206207descriptions.write[2] = vd;208209const Vector2 *uv_ptr = p_uvs.ptr();210211for (uint32_t i = 0; i < vertex_count; i++) {212fptr[base_offset + i * stride + 0] = uv_ptr[i].x;213fptr[base_offset + i * stride + 1] = uv_ptr[i].y;214}215base_offset += 2;216} else {217RD::VertexAttribute vd;218vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;219vd.offset = 0;220vd.location = RS::ARRAY_TEX_UV;221vd.stride = 0;222223descriptions.write[2] = vd;224buffers.write[2] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_TEX_UV);225}226227//bones228if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {229RD::VertexAttribute vd;230vd.format = RD::DATA_FORMAT_R16G16B16A16_UINT;231vd.offset = base_offset * sizeof(float);232vd.location = RS::ARRAY_BONES;233vd.stride = stride * sizeof(float);234235descriptions.write[3] = vd;236237const int *bone_ptr = p_bones.ptr();238239for (uint32_t i = 0; i < vertex_count; i++) {240uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];241242bone16w[0] = bone_ptr[i * 4 + 0];243bone16w[1] = bone_ptr[i * 4 + 1];244bone16w[2] = bone_ptr[i * 4 + 2];245bone16w[3] = bone_ptr[i * 4 + 3];246}247248base_offset += 2;249} else {250RD::VertexAttribute vd;251vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;252vd.offset = 0;253vd.location = RS::ARRAY_BONES;254vd.stride = 0;255256descriptions.write[3] = vd;257buffers.write[3] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_BONES);258}259260//weights261if ((uint32_t)p_weights.size() == vertex_count * 4) {262RD::VertexAttribute vd;263vd.format = RD::DATA_FORMAT_R16G16B16A16_UNORM;264vd.offset = base_offset * sizeof(float);265vd.location = RS::ARRAY_WEIGHTS;266vd.stride = stride * sizeof(float);267268descriptions.write[4] = vd;269270const float *weight_ptr = p_weights.ptr();271272for (uint32_t i = 0; i < vertex_count; i++) {273uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride];274275weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);276weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);277weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);278weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);279}280281base_offset += 2;282} else {283RD::VertexAttribute vd;284vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;285vd.offset = 0;286vd.location = RS::ARRAY_WEIGHTS;287vd.stride = 0;288289descriptions.write[4] = vd;290buffers.write[4] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_WEIGHTS);291}292293//check that everything is as it should be294ERR_FAIL_COND_V(base_offset != stride, 0); //bug295}296297RD::VertexFormatID vertex_id = RD::get_singleton()->vertex_format_create(descriptions);298ERR_FAIL_COND_V(vertex_id == RD::INVALID_ID, 0);299300PolygonBuffers pb;301pb.vertex_buffer = RD::get_singleton()->vertex_buffer_create(polygon_buffer.size(), polygon_buffer);302for (int i = 0; i < descriptions.size(); i++) {303if (buffers[i] == RID()) { //if put in vertex, use as vertex304buffers.write[i] = pb.vertex_buffer;305}306}307308pb.vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), vertex_id, buffers);309pb.primitive_count = vertex_count;310311if (p_indices.size()) {312//create indices, as indices were requested313Vector<uint8_t> index_buffer;314index_buffer.resize(p_count * sizeof(int32_t));315{316uint8_t *w = index_buffer.ptrw();317memcpy(w, p_indices.ptr(), sizeof(int32_t) * p_indices.size());318}319pb.index_buffer = RD::get_singleton()->index_buffer_create(p_count, RD::INDEX_BUFFER_FORMAT_UINT32, index_buffer);320pb.indices = RD::get_singleton()->index_array_create(pb.index_buffer, 0, p_count);321pb.primitive_count = p_count;322}323324pb.vertex_format_id = vertex_id;325326PolygonID id = polygon_buffers.last_id++;327328polygon_buffers.polygons[id] = pb;329330return id;331}332333void RendererCanvasRenderRD::free_polygon(PolygonID p_polygon) {334PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);335ERR_FAIL_NULL(pb_ptr);336337PolygonBuffers &pb = *pb_ptr;338339if (pb.indices.is_valid()) {340RD::get_singleton()->free_rid(pb.indices);341}342if (pb.index_buffer.is_valid()) {343RD::get_singleton()->free_rid(pb.index_buffer);344}345346RD::get_singleton()->free_rid(pb.vertex_array);347RD::get_singleton()->free_rid(pb.vertex_buffer);348349polygon_buffers.polygons.erase(p_polygon);350}351352////////////////////353354static RD::RenderPrimitive _primitive_type_to_render_primitive(RS::PrimitiveType p_primitive) {355switch (p_primitive) {356case RS::PRIMITIVE_POINTS:357return RD::RENDER_PRIMITIVE_POINTS;358case RS::PRIMITIVE_LINES:359return RD::RENDER_PRIMITIVE_LINES;360case RS::PRIMITIVE_LINE_STRIP:361return RD::RENDER_PRIMITIVE_LINESTRIPS;362case RS::PRIMITIVE_TRIANGLES:363return RD::RENDER_PRIMITIVE_TRIANGLES;364case RS::PRIMITIVE_TRIANGLE_STRIP:365return RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS;366default:367return RD::RENDER_PRIMITIVE_MAX;368}369}370371_FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {372static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };373static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 2 };374return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];375}376377RID RendererCanvasRenderRD::_create_base_uniform_set(RID p_to_render_target, bool p_backbuffer) {378RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();379RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();380381//re create canvas state382thread_local LocalVector<RD::Uniform> uniforms;383uniforms.clear();384385{386RD::Uniform u;387u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;388u.binding = 1;389u.append_id(state.canvas_state_buffer);390uniforms.push_back(u);391}392393{394RD::Uniform u;395u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;396u.binding = 2;397u.append_id(state.lights_storage_buffer);398uniforms.push_back(u);399}400401{402RD::Uniform u;403u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;404u.binding = 3;405u.append_id(RendererRD::TextureStorage::get_singleton()->decal_atlas_get_texture());406uniforms.push_back(u);407}408409{410RD::Uniform u;411u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;412u.binding = 4;413u.append_id(state.shadow_texture);414uniforms.push_back(u);415}416417{418RD::Uniform u;419u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;420u.binding = 5;421u.append_id(state.shadow_sampler);422uniforms.push_back(u);423}424425{426RD::Uniform u;427u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;428u.binding = 6;429RID screen;430if (p_backbuffer) {431screen = texture_storage->render_target_get_rd_texture(p_to_render_target);432} else {433screen = texture_storage->render_target_get_rd_backbuffer(p_to_render_target);434if (screen.is_null()) { //unallocated backbuffer435screen = RendererRD::TextureStorage::get_singleton()->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE);436}437}438u.append_id(screen);439uniforms.push_back(u);440}441442{443RD::Uniform u;444u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;445u.binding = 7;446RID sdf = texture_storage->render_target_get_sdf_texture(p_to_render_target);447u.append_id(sdf);448uniforms.push_back(u);449}450451{452RD::Uniform u;453u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;454u.binding = 9;455u.append_id(RendererRD::MaterialStorage::get_singleton()->global_shader_uniforms_get_storage_buffer());456uniforms.push_back(u);457}458459material_storage->samplers_rd_get_default().append_uniforms(uniforms, SAMPLERS_BINDING_FIRST_INDEX);460461RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, BASE_UNIFORM_SET);462if (p_backbuffer) {463texture_storage->render_target_set_backbuffer_uniform_set(p_to_render_target, uniform_set);464} else {465texture_storage->render_target_set_framebuffer_uniform_set(p_to_render_target, uniform_set);466}467468return uniform_set;469}470471RID RendererCanvasRenderRD::_get_pipeline_specialization_or_ubershader(CanvasShaderData *p_shader_data, PipelineKey &r_pipeline_key, PushConstant &r_push_constant, RID p_mesh_instance, void *p_surface, uint32_t p_surface_index, RID *r_vertex_array) {472r_pipeline_key.ubershader = 0;473474const uint32_t ubershader_iterations = 1;475while (r_pipeline_key.ubershader < ubershader_iterations) {476if (r_vertex_array != nullptr) {477RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();478uint64_t input_mask = p_shader_data->get_vertex_input_mask(r_pipeline_key.variant, r_pipeline_key.ubershader);479if (p_mesh_instance.is_valid()) {480mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(p_mesh_instance, p_surface_index, input_mask, false, false, *r_vertex_array, r_pipeline_key.vertex_format_id);481} else {482mesh_storage->mesh_surface_get_vertex_arrays_and_format(p_surface, input_mask, false, false, *r_vertex_array, r_pipeline_key.vertex_format_id);483}484}485486if (r_pipeline_key.ubershader) {487r_push_constant.shader_specialization = r_pipeline_key.shader_specialization;488r_pipeline_key.shader_specialization = {};489} else {490r_push_constant.shader_specialization = {};491}492493bool wait_for_compilation = r_pipeline_key.ubershader || ubershader_iterations == 1;494RS::PipelineSource source = RS::PIPELINE_SOURCE_CANVAS;495RID pipeline = p_shader_data->pipeline_hash_map.get_pipeline(r_pipeline_key, r_pipeline_key.hash(), wait_for_compilation, source);496if (pipeline.is_valid()) {497return pipeline;498}499500r_pipeline_key.ubershader++;501}502503// This case should never be reached unless the shader wasn't available.504return RID();505}506507void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_light_list, const Transform2D &p_canvas_transform, RenderingServer::CanvasItemTextureFilter p_default_filter, RenderingServer::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used, RenderingMethod::RenderInfo *r_render_info) {508RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();509RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();510RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();511512r_sdf_used = false;513int item_count = 0;514515//setup canvas state uniforms if needed516517Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();518519//setup directional lights if exist520521uint32_t light_count = 0;522uint32_t directional_light_count = 0;523{524Light *l = p_directional_light_list;525uint32_t index = 0;526527while (l) {528if (index == MAX_LIGHTS_PER_RENDER) {529l->render_index_cache = -1;530l = l->next_ptr;531continue;532}533534CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);535if (!clight) { //unused or invalid texture536l->render_index_cache = -1;537l = l->next_ptr;538ERR_CONTINUE(!clight);539}540541Vector2 canvas_light_dir = l->xform_cache.columns[1].normalized();542543state.light_uniforms[index].position[0] = -canvas_light_dir.x;544state.light_uniforms[index].position[1] = -canvas_light_dir.y;545546_update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);547548state.light_uniforms[index].height = l->height; //0..1 here549550for (int i = 0; i < 4; i++) {551state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));552state.light_uniforms[index].color[i] = l->color[i];553}554555state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate556557if (state.shadow_fb.is_valid()) {558state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);559state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;560state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;561} else {562state.light_uniforms[index].shadow_pixel_size = 1.0;563state.light_uniforms[index].shadow_z_far_inv = 1.0;564state.light_uniforms[index].shadow_y_ofs = 0;565}566567state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;568state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;569if (clight->shadow.enabled) {570state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;571}572573l->render_index_cache = index;574575index++;576l = l->next_ptr;577}578579light_count = index;580directional_light_count = light_count;581using_directional_lights = directional_light_count > 0;582}583584//setup lights if exist585586{587Light *l = p_light_list;588uint32_t index = light_count;589590while (l) {591if (index == MAX_LIGHTS_PER_RENDER) {592l->render_index_cache = -1;593l = l->next_ptr;594continue;595}596597CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);598if (!clight) { //unused or invalid texture599l->render_index_cache = -1;600l = l->next_ptr;601ERR_CONTINUE(!clight);602}603604Transform2D final_xform;605if (!RSG::canvas->_interpolation_data.interpolation_enabled || !l->interpolated || !l->on_interpolate_transform_list) {606final_xform = l->xform_curr;607} else {608real_t f = Engine::get_singleton()->get_physics_interpolation_fraction();609TransformInterpolator::interpolate_transform_2d(l->xform_prev, l->xform_curr, final_xform, f);610}611// Convert light position to canvas coordinates, as all computation is done in canvas coordinates to avoid precision loss.612Vector2 canvas_light_pos = p_canvas_transform.xform(final_xform.get_origin());613state.light_uniforms[index].position[0] = canvas_light_pos.x;614state.light_uniforms[index].position[1] = canvas_light_pos.y;615616_update_transform_2d_to_mat2x4(l->light_shader_xform.affine_inverse(), state.light_uniforms[index].matrix);617_update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);618619state.light_uniforms[index].height = l->height * (p_canvas_transform.columns[0].length() + p_canvas_transform.columns[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss620for (int i = 0; i < 4; i++) {621state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));622state.light_uniforms[index].color[i] = l->color[i];623}624625state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate626627if (state.shadow_fb.is_valid()) {628state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);629state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;630state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;631} else {632state.light_uniforms[index].shadow_pixel_size = 1.0;633state.light_uniforms[index].shadow_z_far_inv = 1.0;634state.light_uniforms[index].shadow_y_ofs = 0;635}636637state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;638state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;639if (clight->shadow.enabled) {640state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;641}642643if (clight->texture.is_valid()) {644Rect2 atlas_rect = RendererRD::TextureStorage::get_singleton()->decal_atlas_get_texture_rect(clight->texture);645state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;646state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;647state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;648state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;649650} else {651state.light_uniforms[index].atlas_rect[0] = 0;652state.light_uniforms[index].atlas_rect[1] = 0;653state.light_uniforms[index].atlas_rect[2] = 0;654state.light_uniforms[index].atlas_rect[3] = 0;655}656657l->render_index_cache = index;658659index++;660l = l->next_ptr;661}662663light_count = index;664}665666if (light_count > 0) {667RD::get_singleton()->buffer_update(state.lights_storage_buffer, 0, sizeof(LightUniform) * light_count, &state.light_uniforms[0]);668}669670bool use_linear_colors = texture_storage->render_target_is_using_hdr(p_to_render_target);671672{673//update canvas state uniform buffer674State::Buffer state_buffer;675676Size2i ssize = texture_storage->render_target_get_size(p_to_render_target);677678Transform3D screen_transform;679screen_transform.translate_local(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);680screen_transform.scale(Vector3(2.0f / ssize.width, 2.0f / ssize.height, 1.0f));681_update_transform_to_mat4(screen_transform, state_buffer.screen_transform);682_update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);683684Transform2D normal_transform = p_canvas_transform;685normal_transform.columns[0].normalize();686normal_transform.columns[1].normalize();687normal_transform.columns[2] = Vector2();688_update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);689690Color modulate = p_modulate;691if (use_linear_colors) {692modulate = p_modulate.srgb_to_linear();693}694state_buffer.canvas_modulate[0] = modulate.r;695state_buffer.canvas_modulate[1] = modulate.g;696state_buffer.canvas_modulate[2] = modulate.b;697state_buffer.canvas_modulate[3] = modulate.a;698699Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);700state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;701state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;702703state_buffer.time = state.time;704state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;705706state_buffer.directional_light_count = directional_light_count;707708Vector2 canvas_scale = p_canvas_transform.get_scale();709710state_buffer.sdf_to_screen[0] = render_target_size.width / canvas_scale.x;711state_buffer.sdf_to_screen[1] = render_target_size.height / canvas_scale.y;712713state_buffer.screen_to_sdf[0] = 1.0 / state_buffer.sdf_to_screen[0];714state_buffer.screen_to_sdf[1] = 1.0 / state_buffer.sdf_to_screen[1];715716Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_to_render_target);717Rect2 sdf_tex_rect(sdf_rect.position / canvas_scale, sdf_rect.size / canvas_scale);718719state_buffer.sdf_to_tex[0] = 1.0 / sdf_tex_rect.size.width;720state_buffer.sdf_to_tex[1] = 1.0 / sdf_tex_rect.size.height;721state_buffer.sdf_to_tex[2] = -sdf_tex_rect.position.x / sdf_tex_rect.size.width;722state_buffer.sdf_to_tex[3] = -sdf_tex_rect.position.y / sdf_tex_rect.size.height;723724//print_line("w: " + itos(ssize.width) + " s: " + rtos(canvas_scale));725state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);726state_buffer.shadow_pixel_size = 1.0f / (float)(state.shadow_texture_size);727728state_buffer.flags = use_linear_colors ? CANVAS_FLAGS_CONVERT_ATTRIBUTES_TO_LINEAR : 0;729730RD::get_singleton()->buffer_update(state.canvas_state_buffer, 0, sizeof(State::Buffer), &state_buffer);731}732733{ //default filter/repeat734default_filter = p_default_filter;735default_repeat = p_default_repeat;736}737738Item *ci = p_item_list;739740//fill the list until rendering is possible.741bool material_screen_texture_cached = false;742bool material_screen_texture_mipmaps_cached = false;743744Rect2 back_buffer_rect;745bool backbuffer_copy = false;746bool backbuffer_gen_mipmaps = false;747748Item *canvas_group_owner = nullptr;749bool skip_item = false;750751bool update_skeletons = false;752bool time_used = false;753754bool backbuffer_cleared = false;755756RenderTarget to_render_target;757to_render_target.render_target = p_to_render_target;758to_render_target.use_linear_colors = use_linear_colors;759760while (ci) {761if (ci->copy_back_buffer && canvas_group_owner == nullptr) {762backbuffer_copy = true;763764if (ci->copy_back_buffer->full) {765back_buffer_rect = Rect2();766} else {767back_buffer_rect = ci->copy_back_buffer->rect;768}769}770771RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;772773if (material.is_valid()) {774CanvasMaterialData *md = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::MaterialStorage::SHADER_TYPE_2D));775if (md && md->shader_data->is_valid()) {776if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {777if (!material_screen_texture_cached) {778backbuffer_copy = true;779back_buffer_rect = Rect2();780backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;781} else if (!material_screen_texture_mipmaps_cached) {782backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;783}784}785786if (md->shader_data->uses_sdf) {787r_sdf_used = true;788}789if (md->shader_data->uses_time) {790time_used = true;791}792}793}794795if (ci->skeleton.is_valid()) {796const Item::Command *c = ci->commands;797798while (c) {799if (c->type == Item::Command::TYPE_MESH) {800const Item::CommandMesh *cm = static_cast<const Item::CommandMesh *>(c);801if (cm->mesh_instance.is_valid()) {802mesh_storage->mesh_instance_check_for_update(cm->mesh_instance);803mesh_storage->mesh_instance_set_canvas_item_transform(cm->mesh_instance, canvas_transform_inverse * ci->final_transform);804update_skeletons = true;805}806}807c = c->next;808}809}810811if (ci->canvas_group_owner != nullptr) {812if (canvas_group_owner == nullptr) {813// Canvas group begins here, render until before this item814if (update_skeletons) {815mesh_storage->update_mesh_instances();816update_skeletons = false;817}818_render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info);819item_count = 0;820821if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {822Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;823texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);824if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {825ci->canvas_group_owner->use_canvas_group = false;826items[item_count++] = ci->canvas_group_owner;827}828} else if (!backbuffer_cleared) {829texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));830backbuffer_cleared = true;831}832833backbuffer_copy = false;834canvas_group_owner = ci->canvas_group_owner; //continue until owner found835}836837ci->canvas_group_owner = nullptr; //must be cleared838}839840if (canvas_group_owner == nullptr && ci->canvas_group != nullptr && ci->canvas_group->mode != RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {841skip_item = true;842}843844if (ci == canvas_group_owner) {845if (update_skeletons) {846mesh_storage->update_mesh_instances();847update_skeletons = false;848}849850_render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, true, r_render_info);851item_count = 0;852853if (ci->canvas_group->blur_mipmaps) {854texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, ci->global_rect_cache);855}856857canvas_group_owner = nullptr;858// Backbuffer is dirty now and needs to be re-cleared if another CanvasGroup needs it.859backbuffer_cleared = false;860861// Tell the renderer to paint this as a canvas group862ci->use_canvas_group = true;863} else {864ci->use_canvas_group = false;865}866867if (backbuffer_copy) {868//render anything pending, including clearing if no items869if (update_skeletons) {870mesh_storage->update_mesh_instances();871update_skeletons = false;872}873874_render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info);875item_count = 0;876877texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);878879backbuffer_copy = false;880material_screen_texture_cached = true; // After a backbuffer copy, screen texture makes no further copies.881material_screen_texture_mipmaps_cached = backbuffer_gen_mipmaps;882backbuffer_gen_mipmaps = false;883}884885if (backbuffer_gen_mipmaps) {886texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, back_buffer_rect);887888backbuffer_gen_mipmaps = false;889material_screen_texture_mipmaps_cached = true;890}891892if (skip_item) {893skip_item = false;894} else {895items[item_count++] = ci;896}897898if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {899if (update_skeletons) {900mesh_storage->update_mesh_instances();901update_skeletons = false;902}903904_render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, canvas_group_owner != nullptr, r_render_info);905//then reset906item_count = 0;907}908909ci = ci->next;910}911912if (time_used) {913RenderingServerDefault::redraw_request();914}915916texture_info_map.clear();917918// Save the previous instance data pointer in case more items are rendered in the same frame.919state.prev_instance_data = state.instance_data;920state.prev_instance_data_index = state.instance_data_index;921922state.instance_data = nullptr;923if (state.instance_data_index > 0) {924// If there was any remaining instance data, it must be flushed.925RID buf = state.instance_buffers._get(0);926RD::get_singleton()->buffer_flush(buf);927state.instance_data_index = 0;928}929}930931RID RendererCanvasRenderRD::light_create() {932CanvasLight canvas_light;933return canvas_light_owner.make_rid(canvas_light);934}935936void RendererCanvasRenderRD::light_set_texture(RID p_rid, RID p_texture) {937RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();938939CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);940ERR_FAIL_NULL(cl);941if (cl->texture == p_texture) {942return;943}944945ERR_FAIL_COND(p_texture.is_valid() && !texture_storage->owns_texture(p_texture));946947if (cl->texture.is_valid()) {948texture_storage->texture_remove_from_decal_atlas(cl->texture);949}950cl->texture = p_texture;951952if (cl->texture.is_valid()) {953texture_storage->texture_add_to_decal_atlas(cl->texture);954}955}956957void RendererCanvasRenderRD::light_set_use_shadow(RID p_rid, bool p_enable) {958CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);959ERR_FAIL_NULL(cl);960961cl->shadow.enabled = p_enable;962}963964void RendererCanvasRenderRD::_update_shadow_atlas() {965if (state.shadow_fb == RID()) {966//ah, we lack the shadow texture..967RD::get_singleton()->free_rid(state.shadow_texture); //erase placeholder968969Vector<RID> fb_textures;970971{ //texture972RD::TextureFormat tf;973tf.texture_type = RD::TEXTURE_TYPE_2D;974tf.width = state.shadow_texture_size;975tf.height = MAX_LIGHTS_PER_RENDER * 2;976tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;977tf.format = RD::DATA_FORMAT_R32_SFLOAT;978979state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());980fb_textures.push_back(state.shadow_texture);981}982{983RD::TextureFormat tf;984tf.texture_type = RD::TEXTURE_TYPE_2D;985tf.width = state.shadow_texture_size;986tf.height = MAX_LIGHTS_PER_RENDER * 2;987tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;988tf.format = RD::DATA_FORMAT_D32_SFLOAT;989tf.is_discardable = true;990//chunks to write991state.shadow_depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());992fb_textures.push_back(state.shadow_depth_texture);993}994995state.shadow_fb = RD::get_singleton()->framebuffer_create(fb_textures);996}997}998999void RendererCanvasRenderRD::_update_occluder_buffer(uint32_t p_size) {1000bool needs_update = state.shadow_occluder_buffer.is_null();10011002if (p_size > state.shadow_occluder_buffer_size) {1003needs_update = true;1004state.shadow_occluder_buffer_size = next_power_of_2(p_size);1005if (state.shadow_occluder_buffer.is_valid()) {1006RD::get_singleton()->free_rid(state.shadow_occluder_buffer);1007}1008}10091010if (needs_update) {1011state.shadow_occluder_buffer = RD::get_singleton()->storage_buffer_create(state.shadow_occluder_buffer_size);10121013Vector<RD::Uniform> uniforms;10141015{1016RD::Uniform u;1017u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1018u.binding = 0;1019u.append_id(state.shadow_occluder_buffer);1020uniforms.push_back(u);1021}1022state.shadow_ocluder_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_POSITIONAL_SHADOW), 0);1023}1024}10251026void RendererCanvasRenderRD::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, const Rect2 &p_light_rect) {1027CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);1028ERR_FAIL_COND(!cl->shadow.enabled);10291030_update_shadow_atlas();10311032cl->shadow.z_far = p_far;1033cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(MAX_LIGHTS_PER_RENDER * 2);1034Color cc = Color(p_far, p_far, p_far, 1.0);10351036// First, do a culling pass and record what occluders need to be drawn for this light.1037static thread_local LocalVector<OccluderPolygon *> occluders;1038static thread_local LocalVector<uint32_t> occluder_indices;1039occluders.clear();1040occluder_indices.clear();10411042uint32_t occluder_count = 0;10431044LightOccluderInstance *instance = p_occluders;1045while (instance) {1046OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);10471048occluder_count++;10491050if (!co || co->index_array.is_null()) {1051instance = instance->next;1052continue;1053}10541055if (!(p_light_mask & instance->light_mask) || !p_light_rect.intersects_transformed(instance->xform_cache, instance->aabb_cache)) {1056instance = instance->next;1057continue;1058}10591060occluders.push_back(co);1061occluder_indices.push_back(occluder_count - 1);10621063instance = instance->next;1064}10651066// Then, upload all the occluder transforms to a shared buffer.1067// We only do this for the first light so we can avoid uploading the same1068// Transforms over and over again.1069if (p_shadow_index == 0 && occluder_count > 0) {1070static thread_local LocalVector<float> transforms;1071transforms.clear();1072transforms.resize(occluder_count * 8);10731074instance = p_occluders;1075uint32_t index = 0;1076while (instance) {1077_update_transform_2d_to_mat2x4(instance->xform_cache, &transforms[index * 8]);1078index++;1079instance = instance->next;1080}10811082_update_occluder_buffer(occluder_count * 8 * sizeof(float));1083RD::get_singleton()->buffer_update(state.shadow_occluder_buffer, 0, transforms.size() * sizeof(float), transforms.ptr());1084}10851086Rect2i rect(0, p_shadow_index * 2, state.shadow_texture_size, 2);1087RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::DRAW_CLEAR_ALL, VectorView(&cc, 1), 1.0f, 0, rect);10881089if (state.shadow_occluder_buffer.is_valid()) {1090RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[SHADOW_RENDER_MODE_POSITIONAL_SHADOW]);1091RD::get_singleton()->draw_list_bind_uniform_set(draw_list, state.shadow_ocluder_uniform_set, 0);10921093for (int i = 0; i < 4; i++) {1094Rect2i sub_rect((state.shadow_texture_size / 4) * i, p_shadow_index * 2, (state.shadow_texture_size / 4), 2);1095RD::get_singleton()->draw_list_set_viewport(draw_list, sub_rect);10961097static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };1098static const Vector4 rotations[4] = { Vector4(0, -1, 1, 0), Vector4(-1, 0, 0, -1), Vector4(0, 1, -1, 0), Vector4(1, 0, 0, 1) };10991100PositionalShadowRenderPushConstant push_constant;1101_update_transform_2d_to_mat2x4(p_light_xform, push_constant.modelview);1102push_constant.direction[0] = directions[i].x;1103push_constant.direction[1] = directions[i].y;1104push_constant.rotation[0] = rotations[i].x;1105push_constant.rotation[1] = rotations[i].y;1106push_constant.rotation[2] = rotations[i].z;1107push_constant.rotation[3] = rotations[i].w;1108push_constant.z_far = p_far;1109push_constant.z_near = p_near;11101111for (uint32_t j = 0; j < occluders.size(); j++) {1112OccluderPolygon *co = occluders[j];11131114push_constant.pad = occluder_indices[j];1115push_constant.cull_mode = uint32_t(co->cull_mode);11161117// The slowest part about this whole function is that we have to draw the occluders one by one, 4 times.1118// We can optimize this so that all occluders draw at once if we store vertices and indices in a giant1119// SSBO and just save an index into that SSBO for each occluder.1120RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);1121RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);1122RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(PositionalShadowRenderPushConstant));11231124RD::get_singleton()->draw_list_draw(draw_list, true);1125}1126}1127}1128RD::get_singleton()->draw_list_end();1129}11301131void RendererCanvasRenderRD::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) {1132CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);1133ERR_FAIL_COND(!cl->shadow.enabled);11341135_update_shadow_atlas();11361137Vector2 light_dir = p_light_xform.columns[1].normalized();11381139Vector2 center = p_clip_rect.get_center();11401141float to_edge_distance = Math::abs(light_dir.dot(p_clip_rect.get_support(-light_dir)) - light_dir.dot(center));11421143Vector2 from_pos = center - light_dir * (to_edge_distance + p_cull_distance);1144float distance = to_edge_distance * 2.0 + p_cull_distance;1145float half_size = p_clip_rect.size.length() * 0.5; //shadow length, must keep this no matter the angle11461147cl->shadow.z_far = distance;1148cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(MAX_LIGHTS_PER_RENDER * 2);11491150Transform2D to_light_xform;11511152to_light_xform[2] = from_pos;1153to_light_xform[1] = light_dir;1154to_light_xform[0] = -light_dir.orthogonal();11551156to_light_xform.invert();11571158Vector<Color> cc;1159cc.push_back(Color(1, 1, 1, 1));11601161Rect2i rect(0, p_shadow_index * 2, state.shadow_texture_size, 2);1162RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::DRAW_CLEAR_ALL, cc, 1.0f, 0, rect);1163RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[SHADOW_RENDER_MODE_DIRECTIONAL_SHADOW]);11641165Projection projection;1166projection.set_orthogonal(-half_size, half_size, -0.5, 0.5, 0.0, distance);1167projection = projection * Projection(Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, -1)).affine_inverse());11681169ShadowRenderPushConstant push_constant;1170for (int y = 0; y < 4; y++) {1171for (int x = 0; x < 4; x++) {1172push_constant.projection[y * 4 + x] = projection.columns[y][x];1173}1174}11751176push_constant.direction[0] = 0.0;1177push_constant.direction[1] = 1.0;1178push_constant.z_far = distance;11791180LightOccluderInstance *instance = p_occluders;11811182while (instance) {1183OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);11841185if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {1186instance = instance->next;1187continue;1188}11891190_update_transform_2d_to_mat2x4(to_light_xform * instance->xform_cache, push_constant.modelview);1191push_constant.cull_mode = uint32_t(co->cull_mode);11921193RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);1194RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);1195RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));11961197RD::get_singleton()->draw_list_draw(draw_list, true);11981199instance = instance->next;1200}12011202RD::get_singleton()->draw_list_end();12031204Transform2D to_shadow;1205to_shadow.columns[0].x = 1.0 / -(half_size * 2.0);1206to_shadow.columns[2].x = 0.5;12071208cl->shadow.directional_xform = to_shadow * to_light_xform;1209}12101211void RendererCanvasRenderRD::render_sdf(RID p_render_target, LightOccluderInstance *p_occluders) {1212RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();12131214RID fb = texture_storage->render_target_get_sdf_framebuffer(p_render_target);1215Rect2i rect = texture_storage->render_target_get_sdf_rect(p_render_target);12161217Transform2D to_sdf;1218to_sdf.columns[0] *= rect.size.width;1219to_sdf.columns[1] *= rect.size.height;1220to_sdf.columns[2] = rect.position;12211222Transform2D to_clip;1223to_clip.columns[0] *= 2.0;1224to_clip.columns[1] *= 2.0;1225to_clip.columns[2] = -Vector2(1.0, 1.0);12261227to_clip = to_clip * to_sdf.affine_inverse();12281229Vector<Color> cc;1230cc.push_back(Color(0, 0, 0, 0));12311232RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(fb, RD::DRAW_CLEAR_ALL, cc);12331234Projection projection;12351236ShadowRenderPushConstant push_constant;1237for (int y = 0; y < 4; y++) {1238for (int x = 0; x < 4; x++) {1239push_constant.projection[y * 4 + x] = projection.columns[y][x];1240}1241}12421243push_constant.direction[0] = 0.0;1244push_constant.direction[1] = 0.0;1245push_constant.z_far = 0;1246push_constant.cull_mode = 0;12471248LightOccluderInstance *instance = p_occluders;12491250while (instance) {1251OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);12521253if (!co || co->sdf_index_array.is_null() || !instance->sdf_collision) {1254instance = instance->next;1255continue;1256}12571258_update_transform_2d_to_mat2x4(to_clip * instance->xform_cache, push_constant.modelview);12591260RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.sdf_render_pipelines[co->sdf_is_lines ? SHADOW_RENDER_SDF_LINES : SHADOW_RENDER_SDF_TRIANGLES]);1261RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->sdf_vertex_array);1262RD::get_singleton()->draw_list_bind_index_array(draw_list, co->sdf_index_array);1263RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));12641265RD::get_singleton()->draw_list_draw(draw_list, true);12661267instance = instance->next;1268}12691270RD::get_singleton()->draw_list_end();12711272texture_storage->render_target_sdf_process(p_render_target); //done rendering, process it1273}12741275RID RendererCanvasRenderRD::occluder_polygon_create() {1276OccluderPolygon occluder;1277occluder.line_point_count = 0;1278occluder.sdf_point_count = 0;1279occluder.sdf_index_count = 0;1280occluder.cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;1281return occluder_polygon_owner.make_rid(occluder);1282}12831284void RendererCanvasRenderRD::occluder_polygon_set_shape(RID p_occluder, const Vector<Vector2> &p_points, bool p_closed) {1285OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);1286ERR_FAIL_NULL(oc);12871288Vector<Vector2> lines;12891290if (p_points.size()) {1291int lc = p_points.size() * 2;12921293lines.resize(lc - (p_closed ? 0 : 2));1294{1295Vector2 *w = lines.ptrw();1296const Vector2 *r = p_points.ptr();12971298int max = lc / 2;1299if (!p_closed) {1300max--;1301}1302for (int i = 0; i < max; i++) {1303Vector2 a = r[i];1304Vector2 b = r[(i + 1) % (lc / 2)];1305w[i * 2 + 0] = a;1306w[i * 2 + 1] = b;1307}1308}1309}13101311if ((oc->line_point_count != lines.size() || lines.is_empty()) && oc->vertex_array.is_valid()) {1312RD::get_singleton()->free_rid(oc->vertex_array);1313RD::get_singleton()->free_rid(oc->vertex_buffer);1314RD::get_singleton()->free_rid(oc->index_array);1315RD::get_singleton()->free_rid(oc->index_buffer);13161317oc->vertex_array = RID();1318oc->vertex_buffer = RID();1319oc->index_array = RID();1320oc->index_buffer = RID();13211322oc->line_point_count = lines.size();1323}13241325if (lines.size()) {1326oc->line_point_count = lines.size();1327Vector<uint8_t> geometry;1328Vector<uint8_t> indices;1329int lc = lines.size();13301331geometry.resize(lc * 6 * sizeof(float));1332indices.resize(lc * 3 * sizeof(uint16_t));13331334{1335uint8_t *vw = geometry.ptrw();1336float *vwptr = reinterpret_cast<float *>(vw);1337uint8_t *iw = indices.ptrw();1338uint16_t *iwptr = (uint16_t *)iw;13391340const Vector2 *lr = lines.ptr();13411342const int POLY_HEIGHT = 16384;13431344for (int i = 0; i < lc / 2; i++) {1345vwptr[i * 12 + 0] = lr[i * 2 + 0].x;1346vwptr[i * 12 + 1] = lr[i * 2 + 0].y;1347vwptr[i * 12 + 2] = POLY_HEIGHT;13481349vwptr[i * 12 + 3] = lr[i * 2 + 1].x;1350vwptr[i * 12 + 4] = lr[i * 2 + 1].y;1351vwptr[i * 12 + 5] = POLY_HEIGHT;13521353vwptr[i * 12 + 6] = lr[i * 2 + 1].x;1354vwptr[i * 12 + 7] = lr[i * 2 + 1].y;1355vwptr[i * 12 + 8] = -POLY_HEIGHT;13561357vwptr[i * 12 + 9] = lr[i * 2 + 0].x;1358vwptr[i * 12 + 10] = lr[i * 2 + 0].y;1359vwptr[i * 12 + 11] = -POLY_HEIGHT;13601361iwptr[i * 6 + 0] = i * 4 + 0;1362iwptr[i * 6 + 1] = i * 4 + 1;1363iwptr[i * 6 + 2] = i * 4 + 2;13641365iwptr[i * 6 + 3] = i * 4 + 2;1366iwptr[i * 6 + 4] = i * 4 + 3;1367iwptr[i * 6 + 5] = i * 4 + 0;1368}1369}13701371//if same buffer len is being set, just use buffer_update to avoid a pipeline flush13721373if (oc->vertex_array.is_null()) {1374//create from scratch1375//vertices1376oc->vertex_buffer = RD::get_singleton()->vertex_buffer_create(lc * 6 * sizeof(float), geometry);13771378Vector<RID> buffer;1379buffer.push_back(oc->vertex_buffer);1380oc->vertex_array = RD::get_singleton()->vertex_array_create(4 * lc / 2, shadow_render.vertex_format, buffer);1381//indices13821383oc->index_buffer = RD::get_singleton()->index_buffer_create(3 * lc, RD::INDEX_BUFFER_FORMAT_UINT16, indices);1384oc->index_array = RD::get_singleton()->index_array_create(oc->index_buffer, 0, 3 * lc);13851386} else {1387//update existing1388const uint8_t *vr = geometry.ptr();1389RD::get_singleton()->buffer_update(oc->vertex_buffer, 0, geometry.size(), vr);1390const uint8_t *ir = indices.ptr();1391RD::get_singleton()->buffer_update(oc->index_buffer, 0, indices.size(), ir);1392}1393}13941395// sdf13961397Vector<int> sdf_indices;13981399if (p_points.size()) {1400if (p_closed) {1401sdf_indices = Geometry2D::triangulate_polygon(p_points);1402oc->sdf_is_lines = false;1403} else {1404int max = p_points.size();1405sdf_indices.resize(max * 2);14061407int *iw = sdf_indices.ptrw();1408for (int i = 0; i < max; i++) {1409iw[i * 2 + 0] = i;1410iw[i * 2 + 1] = (i + 1) % max;1411}1412oc->sdf_is_lines = true;1413}1414}14151416if (((oc->sdf_index_count != sdf_indices.size() && oc->sdf_point_count != p_points.size()) || p_points.is_empty()) && oc->sdf_vertex_array.is_valid()) {1417RD::get_singleton()->free_rid(oc->sdf_vertex_array);1418RD::get_singleton()->free_rid(oc->sdf_vertex_buffer);1419RD::get_singleton()->free_rid(oc->sdf_index_array);1420RD::get_singleton()->free_rid(oc->sdf_index_buffer);14211422oc->sdf_vertex_array = RID();1423oc->sdf_vertex_buffer = RID();1424oc->sdf_index_array = RID();1425oc->sdf_index_buffer = RID();14261427oc->sdf_index_count = sdf_indices.size();1428oc->sdf_point_count = p_points.size();14291430oc->sdf_is_lines = false;1431}14321433if (sdf_indices.size()) {1434if (oc->sdf_vertex_array.is_null()) {1435//create from scratch1436//vertices1437#ifdef REAL_T_IS_DOUBLE1438PackedFloat32Array float_points;1439float_points.resize(p_points.size() * 2);1440float *float_points_ptr = (float *)float_points.ptrw();1441for (int i = 0; i < p_points.size(); i++) {1442float_points_ptr[i * 2] = p_points[i].x;1443float_points_ptr[i * 2 + 1] = p_points[i].y;1444}1445oc->sdf_vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_points.size() * 2 * sizeof(float), float_points.span().reinterpret<uint8_t>());1446#else1447oc->sdf_vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_points.size() * 2 * sizeof(float), p_points.span().reinterpret<uint8_t>());1448#endif1449oc->sdf_index_buffer = RD::get_singleton()->index_buffer_create(sdf_indices.size(), RD::INDEX_BUFFER_FORMAT_UINT32, sdf_indices.span().reinterpret<uint8_t>());1450oc->sdf_index_array = RD::get_singleton()->index_array_create(oc->sdf_index_buffer, 0, sdf_indices.size());14511452Vector<RID> buffer;1453buffer.push_back(oc->sdf_vertex_buffer);1454oc->sdf_vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), shadow_render.sdf_vertex_format, buffer);1455//indices14561457} else {1458//update existing1459#ifdef REAL_T_IS_DOUBLE1460PackedFloat32Array float_points;1461float_points.resize(p_points.size() * 2);1462float *float_points_ptr = (float *)float_points.ptrw();1463for (int i = 0; i < p_points.size(); i++) {1464float_points_ptr[i * 2] = p_points[i].x;1465float_points_ptr[i * 2 + 1] = p_points[i].y;1466}1467RD::get_singleton()->buffer_update(oc->sdf_vertex_buffer, 0, sizeof(float) * 2 * p_points.size(), float_points.ptr());1468#else1469RD::get_singleton()->buffer_update(oc->sdf_vertex_buffer, 0, sizeof(float) * 2 * p_points.size(), p_points.ptr());1470#endif1471RD::get_singleton()->buffer_update(oc->sdf_index_buffer, 0, sdf_indices.size() * sizeof(int32_t), sdf_indices.ptr());1472}1473}1474}14751476void RendererCanvasRenderRD::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {1477OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);1478ERR_FAIL_NULL(oc);1479oc->cull_mode = p_mode;1480}14811482void RendererCanvasRenderRD::CanvasShaderData::_clear_vertex_input_mask_cache() {1483for (uint32_t i = 0; i < VERTEX_INPUT_MASKS_SIZE; i++) {1484vertex_input_masks[i].store(0);1485}1486}14871488void RendererCanvasRenderRD::CanvasShaderData::_create_pipeline(PipelineKey p_pipeline_key) {1489#if PRINT_PIPELINE_COMPILATION_KEYS1490print_line(1491"HASH:", p_pipeline_key.hash(),1492"VERSION:", version,1493"VARIANT:", p_pipeline_key.variant,1494"FRAMEBUFFER:", p_pipeline_key.framebuffer_format_id,1495"VERTEX:", p_pipeline_key.vertex_format_id,1496"PRIMITIVE:", p_pipeline_key.render_primitive,1497"SPEC PACKED #0:", p_pipeline_key.shader_specialization.packed_0,1498"LCD:", p_pipeline_key.lcd_blend);1499#endif15001501RendererRD::MaterialStorage::ShaderData::BlendMode blend_mode_rd = RendererRD::MaterialStorage::ShaderData::BlendMode(blend_mode);1502RD::PipelineColorBlendState blend_state;1503RD::PipelineColorBlendState::Attachment attachment;1504uint32_t dynamic_state_flags = 0;1505if (p_pipeline_key.lcd_blend) {1506attachment.enable_blend = true;1507attachment.alpha_blend_op = RD::BLEND_OP_ADD;1508attachment.color_blend_op = RD::BLEND_OP_ADD;1509attachment.src_color_blend_factor = RD::BLEND_FACTOR_CONSTANT_COLOR;1510attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_COLOR;1511attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;1512attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;1513dynamic_state_flags = RD::DYNAMIC_STATE_BLEND_CONSTANTS;1514} else {1515attachment = RendererRD::MaterialStorage::ShaderData::blend_mode_to_blend_attachment(blend_mode_rd);1516}15171518blend_state.attachments.push_back(attachment);15191520RD::PipelineMultisampleState multisample_state;1521multisample_state.sample_count = RD::get_singleton()->framebuffer_format_get_texture_samples(p_pipeline_key.framebuffer_format_id, 0);15221523// Convert the specialization from the key to pipeline specialization constants.1524Vector<RD::PipelineSpecializationConstant> specialization_constants;1525RD::PipelineSpecializationConstant sc;1526sc.constant_id = 0;1527sc.int_value = p_pipeline_key.shader_specialization.packed_0;1528sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;1529specialization_constants.push_back(sc);15301531RID shader_rid = get_shader(p_pipeline_key.variant, p_pipeline_key.ubershader);1532ERR_FAIL_COND(shader_rid.is_null());15331534RID pipeline = RD::get_singleton()->render_pipeline_create(shader_rid, p_pipeline_key.framebuffer_format_id, p_pipeline_key.vertex_format_id, p_pipeline_key.render_primitive, RD::PipelineRasterizationState(), multisample_state, RD::PipelineDepthStencilState(), blend_state, dynamic_state_flags, 0, specialization_constants);1535ERR_FAIL_COND(pipeline.is_null());15361537pipeline_hash_map.add_compiled_pipeline(p_pipeline_key.hash(), pipeline);1538}15391540void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {1541//compile15421543code = p_code;1544ubo_size = 0;1545uniforms.clear();1546uses_screen_texture = false;1547uses_screen_texture_mipmaps = false;1548uses_sdf = false;1549uses_time = false;1550_clear_vertex_input_mask_cache();15511552if (code.is_empty()) {1553return; //just invalid, but no error1554}15551556ShaderCompiler::GeneratedCode gen_code;15571558blend_mode = BLEND_MODE_MIX;15591560ShaderCompiler::IdentifierActions actions;1561actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;1562actions.entry_point_stages["fragment"] = ShaderCompiler::STAGE_FRAGMENT;1563actions.entry_point_stages["light"] = ShaderCompiler::STAGE_FRAGMENT;15641565actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_mode, BLEND_MODE_ADD);1566actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MIX);1567actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_mode, BLEND_MODE_SUB);1568actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MUL);1569actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_mode, BLEND_MODE_PREMULTIPLIED_ALPHA);1570actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_mode, BLEND_MODE_DISABLED);15711572actions.usage_flag_pointers["texture_sdf"] = &uses_sdf;1573actions.usage_flag_pointers["TIME"] = &uses_time;15741575actions.uniforms = &uniforms;15761577RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1578MutexLock lock(canvas_singleton->shader.mutex);15791580Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);1581if (err != OK) {1582if (version.is_valid()) {1583canvas_singleton->shader.canvas_shader.version_free(version);1584version = RID();1585}1586ERR_FAIL_MSG("Shader compilation failed.");1587}15881589uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;1590uses_screen_texture = gen_code.uses_screen_texture;15911592pipeline_hash_map.clear_pipelines();15931594if (version.is_null()) {1595version = canvas_singleton->shader.canvas_shader.version_create(false);1596}15971598#if 01599print_line("**compiling shader:");1600print_line("**defines:\n");1601for (int i = 0; i < gen_code.defines.size(); i++) {1602print_line(gen_code.defines[i]);1603}16041605HashMap<String, String>::Iterator el = gen_code.code.begin();1606while (el) {1607print_line("\n**code " + el->key + ":\n" + el->value);1608++el;1609}16101611print_line("\n**uniforms:\n" + gen_code.uniforms);1612print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);1613print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);1614#endif1615canvas_singleton->shader.canvas_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines);16161617ubo_size = gen_code.uniform_total_size;1618ubo_offsets = gen_code.uniform_offsets;1619texture_uniforms = gen_code.texture_uniforms;1620}16211622bool RendererCanvasRenderRD::CanvasShaderData::is_animated() const {1623return false;1624}16251626bool RendererCanvasRenderRD::CanvasShaderData::casts_shadows() const {1627return false;1628}16291630RS::ShaderNativeSourceCode RendererCanvasRenderRD::CanvasShaderData::get_native_source_code() const {1631RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1632MutexLock lock(canvas_singleton->shader.mutex);1633return canvas_singleton->shader.canvas_shader.version_get_native_source_code(version);1634}16351636Pair<ShaderRD *, RID> RendererCanvasRenderRD::CanvasShaderData::get_native_shader_and_version() const {1637RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1638return { &canvas_singleton->shader.canvas_shader, version };1639}16401641RID RendererCanvasRenderRD::CanvasShaderData::get_shader(ShaderVariant p_shader_variant, bool p_ubershader) const {1642if (version.is_valid()) {1643uint32_t variant_index = p_shader_variant + (p_ubershader ? SHADER_VARIANT_MAX : 0);1644RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1645MutexLock lock(canvas_singleton->shader.mutex);1646return canvas_singleton->shader.canvas_shader.version_get_shader(version, variant_index);1647} else {1648return RID();1649}1650}16511652uint64_t RendererCanvasRenderRD::CanvasShaderData::get_vertex_input_mask(ShaderVariant p_shader_variant, bool p_ubershader) {1653// Vertex input masks require knowledge of the shader. Since querying the shader can be expensive due to high contention and the necessary mutex, we cache the result instead.1654uint32_t input_mask_index = p_shader_variant + (p_ubershader ? SHADER_VARIANT_MAX : 0);1655uint64_t input_mask = vertex_input_masks[input_mask_index].load(std::memory_order_relaxed);1656if (input_mask == 0) {1657RID shader_rid = get_shader(p_shader_variant, p_ubershader);1658ERR_FAIL_COND_V(shader_rid.is_null(), 0);16591660input_mask = RD::get_singleton()->shader_get_vertex_input_attribute_mask(shader_rid);1661vertex_input_masks[input_mask_index].store(input_mask, std::memory_order_relaxed);1662}16631664return input_mask;1665}16661667bool RendererCanvasRenderRD::CanvasShaderData::is_valid() const {1668if (version.is_valid()) {1669RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1670MutexLock lock(canvas_singleton->shader.mutex);1671return canvas_singleton->shader.canvas_shader.version_is_valid(version);1672} else {1673return false;1674}1675}16761677RendererCanvasRenderRD::CanvasShaderData::CanvasShaderData() {1678RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1679pipeline_hash_map.set_creation_object_and_function(this, &CanvasShaderData::_create_pipeline);1680pipeline_hash_map.set_compilations(&canvas_singleton->shader.pipeline_compilations[0], &canvas_singleton->shader.mutex);1681}16821683RendererCanvasRenderRD::CanvasShaderData::~CanvasShaderData() {1684pipeline_hash_map.clear_pipelines();16851686if (version.is_valid()) {1687RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1688MutexLock lock(canvas_singleton->shader.mutex);1689canvas_singleton->shader.canvas_shader.version_free(version);1690}1691}16921693RendererRD::MaterialStorage::ShaderData *RendererCanvasRenderRD::_create_shader_func() {1694CanvasShaderData *shader_data = memnew(CanvasShaderData);1695return shader_data;1696}16971698bool RendererCanvasRenderRD::CanvasMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {1699RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);1700MutexLock lock(canvas_singleton->shader.mutex);1701RID shader_to_update = canvas_singleton->shader.canvas_shader.version_get_shader(shader_data->version, 0);1702bool uniform_set_changed = update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set, shader_to_update, MATERIAL_UNIFORM_SET, true, false);1703bool uniform_set_srgb_changed = update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set_srgb, shader_to_update, MATERIAL_UNIFORM_SET, false, false);1704return uniform_set_changed || uniform_set_srgb_changed;1705}17061707RendererCanvasRenderRD::CanvasMaterialData::~CanvasMaterialData() {1708free_parameters_uniform_set(uniform_set);1709free_parameters_uniform_set(uniform_set_srgb);1710}17111712RendererRD::MaterialStorage::MaterialData *RendererCanvasRenderRD::_create_material_func(CanvasShaderData *p_shader) {1713CanvasMaterialData *material_data = memnew(CanvasMaterialData);1714material_data->shader_data = p_shader;1715//update will happen later anyway so do nothing.1716return material_data;1717}17181719void RendererCanvasRenderRD::set_time(double p_time) {1720state.time = p_time;1721}17221723void RendererCanvasRenderRD::update() {1724}17251726RendererCanvasRenderRD::RendererCanvasRenderRD() {1727RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();1728RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();17291730{ //create default samplers17311732default_samplers.default_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;1733default_samplers.default_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;1734}17351736// preallocate slots for uniform set 31737state.batch_texture_uniforms.resize(4);17381739{ //shader variants17401741String global_defines;1742global_defines += "#define MAX_LIGHTS " + itos(MAX_LIGHTS_PER_RENDER) + "\n";1743global_defines += "\n#define SAMPLERS_BINDING_FIRST_INDEX " + itos(SAMPLERS_BINDING_FIRST_INDEX) + "\n";17441745state.light_uniforms = memnew_arr(LightUniform, MAX_LIGHTS_PER_RENDER);1746Vector<String> variants;1747const uint32_t ubershader_iterations = 1;1748for (uint32_t ubershader = 0; ubershader < ubershader_iterations; ubershader++) {1749const String base_define = ubershader ? "\n#define UBERSHADER\n" : "";1750variants.push_back(base_define + ""); // SHADER_VARIANT_QUAD1751variants.push_back(base_define + "#define USE_NINEPATCH\n"); // SHADER_VARIANT_NINEPATCH1752variants.push_back(base_define + "#define USE_PRIMITIVE\n"); // SHADER_VARIANT_PRIMITIVE1753variants.push_back(base_define + "#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); // SHADER_VARIANT_PRIMITIVE_POINTS1754variants.push_back(base_define + "#define USE_ATTRIBUTES\n"); // SHADER_VARIANT_ATTRIBUTES1755variants.push_back(base_define + "#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); // SHADER_VARIANT_ATTRIBUTES_POINTS1756}17571758shader.canvas_shader.initialize(variants, global_defines, {}, {});17591760shader.default_version_data = memnew(CanvasShaderData);1761shader.default_version_data->version = shader.canvas_shader.version_create();1762shader.default_version_data->blend_mode = RendererRD::MaterialStorage::ShaderData::BLEND_MODE_MIX;1763shader.default_version_rd_shader = shader.default_version_data->get_shader(SHADER_VARIANT_QUAD, false);1764}17651766{1767//shader compiler1768ShaderCompiler::DefaultIdentifierActions actions;17691770actions.renames["VERTEX"] = "vertex";1771actions.renames["LIGHT_VERTEX"] = "light_vertex";1772actions.renames["SHADOW_VERTEX"] = "shadow_vertex";1773actions.renames["UV"] = "uv";1774actions.renames["POINT_SIZE"] = "point_size";17751776actions.renames["MODEL_MATRIX"] = "model_matrix";1777actions.renames["CANVAS_MATRIX"] = "canvas_data.canvas_transform";1778actions.renames["SCREEN_MATRIX"] = "canvas_data.screen_transform";1779actions.renames["TIME"] = "canvas_data.time";1780actions.renames["PI"] = String::num(Math::PI);1781actions.renames["TAU"] = String::num(Math::TAU);1782actions.renames["E"] = String::num(Math::E);1783actions.renames["AT_LIGHT_PASS"] = "false";1784actions.renames["INSTANCE_CUSTOM"] = "instance_custom";17851786actions.renames["COLOR"] = "color";1787actions.renames["NORMAL"] = "normal";1788actions.renames["NORMAL_MAP"] = "normal_map";1789actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";1790actions.renames["TEXTURE"] = "color_texture";1791actions.renames["TEXTURE_PIXEL_SIZE"] = "read_draw_data_color_texture_pixel_size";1792actions.renames["NORMAL_TEXTURE"] = "normal_texture";1793actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";1794actions.renames["SPECULAR_SHININESS"] = "specular_shininess";1795actions.renames["SCREEN_UV"] = "screen_uv";1796actions.renames["REGION_RECT"] = "region_rect";1797actions.renames["SCREEN_PIXEL_SIZE"] = "canvas_data.screen_pixel_size";1798actions.renames["FRAGCOORD"] = "gl_FragCoord";1799actions.renames["POINT_COORD"] = "gl_PointCoord";1800actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";1801actions.renames["VERTEX_ID"] = "gl_VertexIndex";18021803actions.renames["CUSTOM0"] = "custom0";1804actions.renames["CUSTOM1"] = "custom1";18051806actions.renames["LIGHT_POSITION"] = "light_position";1807actions.renames["LIGHT_DIRECTION"] = "light_direction";1808actions.renames["LIGHT_IS_DIRECTIONAL"] = "is_directional";1809actions.renames["LIGHT_COLOR"] = "light_color";1810actions.renames["LIGHT_ENERGY"] = "light_energy";1811actions.renames["LIGHT"] = "light";1812actions.renames["SHADOW_MODULATE"] = "shadow_modulate";18131814actions.renames["texture_sdf"] = "texture_sdf";1815actions.renames["texture_sdf_normal"] = "texture_sdf_normal";1816actions.renames["sdf_to_screen_uv"] = "sdf_to_screen_uv";1817actions.renames["screen_uv_to_sdf"] = "screen_uv_to_sdf";18181819actions.usage_defines["COLOR"] = "#define COLOR_USED\n";1820actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";1821actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";1822actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";1823actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";1824actions.usage_defines["SPECULAR_SHININESS"] = "#define SPECULAR_SHININESS_USED\n";1825actions.usage_defines["POINT_SIZE"] = "#define USE_POINT_SIZE\n";1826actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";1827actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";18281829actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";1830actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";1831actions.render_mode_defines["light_only"] = "#define MODE_LIGHT_ONLY\n";1832actions.render_mode_defines["world_vertex_coords"] = "#define USE_WORLD_VERTEX_COORDS\n";18331834actions.custom_samplers["TEXTURE"] = "texture_sampler";1835actions.custom_samplers["NORMAL_TEXTURE"] = "texture_sampler";1836actions.custom_samplers["SPECULAR_SHININESS_TEXTURE"] = "texture_sampler";1837actions.base_texture_binding_index = 1;1838actions.texture_layout_set = MATERIAL_UNIFORM_SET;1839actions.base_uniform_string = "material.";1840actions.default_filter = ShaderLanguage::FILTER_LINEAR;1841actions.default_repeat = ShaderLanguage::REPEAT_DISABLE;1842actions.base_varying_index = 9;18431844actions.global_buffer_array_variable = "global_shader_uniforms.data";1845actions.instance_uniform_index_variable = "read_draw_data_instance_offset";18461847shader.compiler.initialize(actions);1848}18491850{ //shadow rendering1851Vector<String> versions;1852versions.push_back("\n#define MODE_SHADOW\n"); // Shadow.1853versions.push_back("\n#define MODE_SHADOW\n#define POSITIONAL_SHADOW\n"); // Positional shadow.1854versions.push_back("\n#define MODE_SDF\n"); // SDF.1855shadow_render.shader.initialize(versions);18561857{1858Vector<RD::AttachmentFormat> attachments;18591860RD::AttachmentFormat af_color;1861af_color.format = RD::DATA_FORMAT_R32_SFLOAT;1862af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;18631864attachments.push_back(af_color);18651866RD::AttachmentFormat af_depth;1867af_depth.format = RD::DATA_FORMAT_D32_SFLOAT;1868af_depth.usage_flags = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;18691870attachments.push_back(af_depth);18711872shadow_render.framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);1873}18741875{1876Vector<RD::AttachmentFormat> attachments;18771878RD::AttachmentFormat af_color;1879af_color.format = RD::DATA_FORMAT_R8_UNORM;1880af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;18811882attachments.push_back(af_color);18831884shadow_render.sdf_framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);1885}18861887//pipelines1888Vector<RD::VertexAttribute> vf;1889RD::VertexAttribute vd;1890vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT;1891vd.stride = sizeof(float) * 3;1892vd.location = 0;1893vd.offset = 0;1894vf.push_back(vd);1895shadow_render.vertex_format = RD::get_singleton()->vertex_format_create(vf);18961897vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;1898vd.stride = sizeof(float) * 2;18991900vf.write[0] = vd;1901shadow_render.sdf_vertex_format = RD::get_singleton()->vertex_format_create(vf);19021903shadow_render.shader_version = shadow_render.shader.version_create();19041905for (int i = 0; i < 2; i++) {1906RD::PipelineRasterizationState rs;1907RD::PipelineDepthStencilState ds;1908ds.enable_depth_write = true;1909ds.enable_depth_test = true;1910ds.depth_compare_operator = RD::COMPARE_OP_LESS;1911shadow_render.render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, ShadowRenderMode(i)), shadow_render.framebuffer_format, shadow_render.vertex_format, RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);1912}19131914for (int i = 0; i < 2; i++) {1915shadow_render.sdf_render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SDF), shadow_render.sdf_framebuffer_format, shadow_render.sdf_vertex_format, i == 0 ? RD::RENDER_PRIMITIVE_TRIANGLES : RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0);1916}19171918// Unload shader modules to save memory.1919RD::get_singleton()->shader_destroy_modules(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_DIRECTIONAL_SHADOW));1920RD::get_singleton()->shader_destroy_modules(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_POSITIONAL_SHADOW));1921RD::get_singleton()->shader_destroy_modules(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SDF));1922}19231924{ //bindings19251926state.canvas_state_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(State::Buffer));1927state.lights_storage_buffer = RD::get_singleton()->storage_buffer_create(sizeof(LightUniform) * MAX_LIGHTS_PER_RENDER);19281929RD::SamplerState shadow_sampler_state;1930shadow_sampler_state.mag_filter = RD::SAMPLER_FILTER_NEAREST;1931shadow_sampler_state.min_filter = RD::SAMPLER_FILTER_NEAREST;1932shadow_sampler_state.repeat_u = RD::SAMPLER_REPEAT_MODE_REPEAT; //shadow wrap around1933state.shadow_sampler = RD::get_singleton()->sampler_create(shadow_sampler_state);1934}19351936{1937//polygon buffers1938polygon_buffers.last_id = 1;1939}19401941{ // default index buffer19421943Vector<uint8_t> pv;1944pv.resize(6 * 2);1945{1946uint8_t *w = pv.ptrw();1947uint16_t *p16 = (uint16_t *)w;1948p16[0] = 0;1949p16[1] = 1;1950p16[2] = 2;1951p16[3] = 0;1952p16[4] = 2;1953p16[5] = 3;1954}1955shader.quad_index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT16, pv);1956shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);1957}19581959{1960Vector<RD::VertexAttribute> vf;1961uint32_t offset = 0;1962RD::VertexAttribute vd;1963vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;1964vd.stride = sizeof(InstanceData);1965vd.frequency = RD::VERTEX_FREQUENCY_INSTANCE;1966vd.location = 8;1967vd.binding = 0; // Explicitly assign binding 0 for instance data.1968vd.offset = offset;1969offset += sizeof(float) * 4;1970vf.push_back(vd); // attrib_A19711972vd.location = 9;1973vd.offset = offset;1974offset += sizeof(float) * 4;1975vf.push_back(vd); // attrib_B19761977vd.location = 10;1978vd.offset = offset;1979offset += sizeof(float) * 4;1980vf.push_back(vd); // attrib_C19811982vd.location = 11;1983vd.offset = offset;1984offset += sizeof(float) * 4;1985vf.push_back(vd); // attrib_D19861987vd.location = 12;1988vd.offset = offset;1989offset += sizeof(float) * 4;1990vf.push_back(vd); // attrib_E19911992uint32_t attrib_F_index = vf.size();1993vd.location = 13;1994vd.offset = offset;1995offset += sizeof(float) * 4;1996vf.push_back(vd); // attrib_F (RECT, NINEPATCH)19971998vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;1999vd.location = 14;2000vd.offset = offset;2001offset += sizeof(uint32_t) * 4;2002vf.push_back(vd); // attrib_G20032004vd.location = 15;2005vd.offset = offset;2006offset += sizeof(uint32_t) * 4;2007vf.push_back(vd); // attrib_H20082009// RECT, NINEPATCH2010shader.quad_vertex_format_id = RD::get_singleton()->vertex_format_create(vf);20112012// PRIMITIVE2013vf.write[attrib_F_index].format = RD::DATA_FORMAT_R32G32B32A32_UINT;2014shader.primitive_vertex_format_id = RD::get_singleton()->vertex_format_create(vf);2015}20162017{ //primitive2018primitive_arrays.index_array[0] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 1);2019primitive_arrays.index_array[1] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 2);2020primitive_arrays.index_array[2] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 3);2021primitive_arrays.index_array[3] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);2022}20232024{2025//default shadow texture to keep uniform set happy2026RD::TextureFormat tf;2027tf.texture_type = RD::TEXTURE_TYPE_2D;2028tf.width = 4;2029tf.height = 4;2030tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;2031tf.format = RD::DATA_FORMAT_R32_SFLOAT;20322033state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());2034}20352036{2037Vector<RD::Uniform> uniforms;20382039{2040RD::Uniform u;2041u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;2042u.binding = 0;2043u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer());2044uniforms.push_back(u);2045}20462047state.default_transforms_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);2048}20492050default_canvas_texture = texture_storage->canvas_texture_allocate();2051texture_storage->canvas_texture_initialize(default_canvas_texture);20522053RendererRD::TextureStorage::CanvasTextureInfo info = RendererRD::TextureStorage::get_singleton()->canvas_texture_get_info(default_canvas_texture, default_filter, default_repeat, false, false);2054default_texture_info.diffuse = info.diffuse;2055default_texture_info.normal = info.normal;2056default_texture_info.specular = info.specular;2057default_texture_info.sampler = info.sampler;20582059state.shadow_texture_size = GLOBAL_GET("rendering/2d/shadow_atlas/size");20602061//create functions for shader and material2062material_storage->shader_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_2D, _create_shader_funcs);2063material_storage->material_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_2D, _create_material_funcs);20642065state.time = 0;20662067{2068default_canvas_group_shader = material_storage->shader_allocate();2069material_storage->shader_initialize(default_canvas_group_shader);20702071material_storage->shader_set_code(default_canvas_group_shader, R"(2072// Default CanvasGroup shader.20732074shader_type canvas_item;2075render_mode unshaded;20762077uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;20782079void fragment() {2080vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);20812082if (c.a > 0.0001) {2083c.rgb /= c.a;2084}20852086COLOR *= c;2087}2088)");2089default_canvas_group_material = material_storage->material_allocate();2090material_storage->material_initialize(default_canvas_group_material);20912092material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);2093}20942095{2096default_clip_children_shader = material_storage->shader_allocate();2097material_storage->shader_initialize(default_clip_children_shader);20982099material_storage->shader_set_code(default_clip_children_shader, R"(2100// Default clip children shader.21012102shader_type canvas_item;2103render_mode unshaded;21042105uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;21062107void fragment() {2108vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);2109COLOR.rgb = c.rgb;2110}2111)");2112default_clip_children_material = material_storage->material_allocate();2113material_storage->material_initialize(default_clip_children_material);21142115material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);2116}21172118{2119uint32_t cache_size = uint32_t(GLOBAL_GET("rendering/2d/batching/uniform_set_cache_size"));2120rid_set_to_uniform_set.set_capacity(cache_size);2121}21222123{2124state.max_instances_per_buffer = uint32_t(GLOBAL_GET("rendering/2d/batching/item_buffer_size"));2125state.max_instance_buffer_size = state.max_instances_per_buffer * sizeof(InstanceData);2126state.canvas_instance_batches.reserve(200);2127state.instance_buffers.set_vertex_size(0, state.max_instance_buffer_size);2128}2129}21302131bool RendererCanvasRenderRD::free(RID p_rid) {2132if (canvas_light_owner.owns(p_rid)) {2133CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);2134ERR_FAIL_NULL_V(cl, false);2135light_set_use_shadow(p_rid, false);2136canvas_light_owner.free(p_rid);2137} else if (occluder_polygon_owner.owns(p_rid)) {2138occluder_polygon_set_shape(p_rid, Vector<Vector2>(), false);2139occluder_polygon_owner.free(p_rid);2140} else {2141return false;2142}21432144return true;2145}21462147void RendererCanvasRenderRD::set_shadow_texture_size(int p_size) {2148p_size = MAX(1, nearest_power_of_2_templated(p_size));2149if (p_size == state.shadow_texture_size) {2150return;2151}2152state.shadow_texture_size = p_size;2153if (state.shadow_fb.is_valid()) {2154RD::get_singleton()->free_rid(state.shadow_texture);2155RD::get_singleton()->free_rid(state.shadow_depth_texture);2156state.shadow_fb = RID();21572158{2159//create a default shadow texture to keep uniform set happy (and that it gets erased when a new one is created)2160RD::TextureFormat tf;2161tf.texture_type = RD::TEXTURE_TYPE_2D;2162tf.width = 4;2163tf.height = 4;2164tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;2165tf.format = RD::DATA_FORMAT_R32_SFLOAT;21662167state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());2168}2169}2170}21712172void RendererCanvasRenderRD::set_debug_redraw(bool p_enabled, double p_time, const Color &p_color) {2173debug_redraw = p_enabled;2174debug_redraw_time = p_time;2175debug_redraw_color = p_color;2176}21772178uint32_t RendererCanvasRenderRD::get_pipeline_compilations(RS::PipelineSource p_source) {2179RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);2180MutexLock lock(canvas_singleton->shader.mutex);2181return shader.pipeline_compilations[p_source];2182}21832184void RendererCanvasRenderRD::_render_batch_items(RenderTarget p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool &r_sdf_used, bool p_to_backbuffer, RenderingMethod::RenderInfo *r_render_info) {2185// Record batches2186{2187RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();2188Item *current_clip = nullptr;21892190// Record Batches.2191// First item always forms its own batch.2192bool batch_broken = false;2193Batch *current_batch = _new_batch(batch_broken);21942195for (int i = 0; i < p_item_count; i++) {2196Item *ci = items[i];21972198if (ci->final_clip_owner != current_batch->clip) {2199current_batch = _new_batch(batch_broken);2200current_batch->clip = ci->final_clip_owner;2201current_clip = ci->final_clip_owner;2202}22032204RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;22052206if (ci->use_canvas_group) {2207if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {2208material = default_clip_children_material;2209} else {2210if (material.is_null()) {2211if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {2212material = default_clip_children_material;2213} else {2214material = default_canvas_group_material;2215}2216}2217}2218}22192220if (material != current_batch->material) {2221current_batch = _new_batch(batch_broken);22222223CanvasMaterialData *material_data = nullptr;2224if (material.is_valid()) {2225material_data = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::MaterialStorage::SHADER_TYPE_2D));2226}22272228current_batch->material = material;2229current_batch->material_data = material_data;2230}22312232if (ci->repeat_source_item == nullptr || ci->repeat_size == Vector2()) {2233Transform2D base_transform = p_canvas_transform_inverse * ci->final_transform;2234_record_item_commands(ci, p_to_render_target, base_transform, current_clip, p_lights, batch_broken, r_sdf_used, current_batch);2235} else {2236Point2 start_pos = ci->repeat_size * -(ci->repeat_times / 2);2237Point2 offset;2238int repeat_times_x = ci->repeat_size.x ? ci->repeat_times : 0;2239int repeat_times_y = ci->repeat_size.y ? ci->repeat_times : 0;2240for (int ry = 0; ry <= repeat_times_y; ry++) {2241offset.y = start_pos.y + ry * ci->repeat_size.y;2242for (int rx = 0; rx <= repeat_times_x; rx++) {2243offset.x = start_pos.x + rx * ci->repeat_size.x;2244Transform2D base_transform = ci->final_transform;2245base_transform.columns[2] += ci->repeat_source_item->final_transform.basis_xform(offset);2246base_transform = p_canvas_transform_inverse * base_transform;2247_record_item_commands(ci, p_to_render_target, base_transform, current_clip, p_lights, batch_broken, r_sdf_used, current_batch);2248}2249}2250}2251}2252}22532254if (state.canvas_instance_batches.is_empty()) {2255// Nothing to render, just return.2256return;2257}22582259// Render batches22602261RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();22622263RID framebuffer;2264RID fb_uniform_set;2265bool clear = false;2266Color clear_color;22672268if (p_to_backbuffer) {2269framebuffer = texture_storage->render_target_get_rd_backbuffer_framebuffer(p_to_render_target.render_target);2270fb_uniform_set = texture_storage->render_target_get_backbuffer_uniform_set(p_to_render_target.render_target);2271} else {2272framebuffer = texture_storage->render_target_get_rd_framebuffer(p_to_render_target.render_target);2273texture_storage->render_target_set_msaa_needs_resolve(p_to_render_target.render_target, false); // If MSAA is enabled, our framebuffer will be resolved!22742275if (texture_storage->render_target_is_clear_requested(p_to_render_target.render_target)) {2276clear = true;2277clear_color = texture_storage->render_target_get_clear_request_color(p_to_render_target.render_target);2278if (texture_storage->render_target_is_using_hdr(p_to_render_target.render_target)) {2279clear_color = clear_color.srgb_to_linear();2280}2281texture_storage->render_target_disable_clear_request(p_to_render_target.render_target);2282}2283// TODO: Obtain from framebuffer format eventually when this is implemented.2284fb_uniform_set = texture_storage->render_target_get_framebuffer_uniform_set(p_to_render_target.render_target);2285}22862287if (fb_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(fb_uniform_set)) {2288fb_uniform_set = _create_base_uniform_set(p_to_render_target.render_target, p_to_backbuffer);2289}22902291RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);22922293RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, clear ? RD::DRAW_CLEAR_COLOR_0 : RD::DRAW_DEFAULT_ALL, clear_color, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::UI_PASS);22942295RD::get_singleton()->draw_list_bind_uniform_set(draw_list, fb_uniform_set, BASE_UNIFORM_SET);2296RD::get_singleton()->draw_list_bind_uniform_set(draw_list, state.default_transforms_uniform_set, TRANSFORMS_UNIFORM_SET);22972298Item *current_clip = nullptr;2299state.current_batch_uniform_set = RID();23002301for (uint32_t i = 0; i <= state.current_batch_index; i++) {2302Batch *current_batch = &state.canvas_instance_batches[i];2303// Skipping when there is no instances.2304if (current_batch->instance_count == 0) {2305continue;2306}23072308//setup clip2309if (current_clip != current_batch->clip) {2310current_clip = current_batch->clip;2311if (current_clip) {2312RD::get_singleton()->draw_list_enable_scissor(draw_list, current_clip->final_clip_rect);2313} else {2314RD::get_singleton()->draw_list_disable_scissor(draw_list);2315}2316}23172318CanvasShaderData *shader_data = shader.default_version_data;2319CanvasMaterialData *material_data = current_batch->material_data;2320if (material_data) {2321if (material_data->shader_data->version.is_valid() && material_data->shader_data->is_valid()) {2322shader_data = material_data->shader_data;2323// Update uniform set.2324RID uniform_set = texture_storage->render_target_is_using_hdr(p_to_render_target.render_target) ? material_data->uniform_set : material_data->uniform_set_srgb;2325if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) { // Material may not have a uniform set.2326RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set, MATERIAL_UNIFORM_SET);2327material_data->set_as_used();2328}2329}2330}23312332_render_batch(draw_list, shader_data, fb_format, p_lights, current_batch, r_render_info);2333}23342335RD::get_singleton()->draw_list_end();23362337state.current_batch_index = 0;2338state.canvas_instance_batches.clear();2339}23402341void RendererCanvasRenderRD::_record_item_commands(const Item *p_item, RenderTarget p_render_target, const Transform2D &p_base_transform, Item *&r_current_clip, Light *p_lights, bool &r_batch_broken, bool &r_sdf_used, Batch *&r_current_batch) {2342const RenderingServer::CanvasItemTextureFilter texture_filter = p_item->texture_filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? default_filter : p_item->texture_filter;2343const RenderingServer::CanvasItemTextureRepeat texture_repeat = p_item->texture_repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? default_repeat : p_item->texture_repeat;23442345Transform2D base_transform = p_base_transform;23462347InstanceData template_instance;2348memset(&template_instance, 0, sizeof(InstanceData));23492350Transform2D draw_transform; // Used by transform command2351_update_transform_2d_to_mat2x3(base_transform, template_instance.world);23522353Color base_color = p_item->final_modulate;2354bool use_linear_colors = p_render_target.use_linear_colors;2355template_instance.instance_uniforms_ofs = static_cast<uint32_t>(p_item->instance_allocated_shader_uniforms_offset);23562357bool reclip = false;23582359bool skipping = false;23602361uint16_t light_count = 0;2362uint16_t shadow_mask = 0;23632364{2365Light *light = p_lights;23662367while (light) {2368if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects(light->rect_cache)) {2369uint32_t light_index = light->render_index_cache;2370// TODO: consider making lights a per-batch property and then baking light operations in the shader for better performance.2371template_instance.lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);23722373if (p_item->light_mask & light->item_shadow_mask) {2374shadow_mask |= 1 << light_count;2375}23762377light_count++;23782379if (light_count == MAX_LIGHTS_PER_ITEM - 1) {2380break;2381}2382}2383light = light->next_ptr;2384}23852386template_instance.flags |= light_count << INSTANCE_FLAGS_LIGHT_COUNT_SHIFT;2387template_instance.flags |= shadow_mask << INSTANCE_FLAGS_SHADOW_MASKED_SHIFT;2388}23892390bool use_lighting = (light_count > 0 || using_directional_lights);23912392if (use_lighting != r_current_batch->use_lighting) {2393r_current_batch = _new_batch(r_batch_broken);2394r_current_batch->use_lighting = use_lighting;2395}23962397const Item::Command *c = p_item->commands;2398while (c) {2399if (skipping && c->type != Item::Command::TYPE_ANIMATION_SLICE) {2400c = c->next;2401continue;2402}24032404switch (c->type) {2405case Item::Command::TYPE_RECT: {2406const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);24072408// 1: If commands are different, start a new batch.2409if (r_current_batch->command_type != Item::Command::TYPE_RECT) {2410r_current_batch = _new_batch(r_batch_broken);2411r_current_batch->command_type = Item::Command::TYPE_RECT;2412r_current_batch->command = c;2413// default variant2414r_current_batch->shader_variant = SHADER_VARIANT_QUAD;2415r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;2416r_current_batch->flags = 0;2417}24182419RenderingServer::CanvasItemTextureRepeat rect_repeat = texture_repeat;2420if (bool(rect->flags & CANVAS_RECT_TILE)) {2421rect_repeat = RenderingServer::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED;2422}24232424Color modulated = rect->modulate * base_color;2425if (use_linear_colors) {2426modulated = modulated.srgb_to_linear();2427}24282429bool has_blend = bool(rect->flags & CANVAS_RECT_LCD);2430// Start a new batch if the blend mode has changed,2431// or blend mode is enabled and the modulation has changed.2432if (has_blend != r_current_batch->has_blend || (has_blend && modulated != r_current_batch->modulate)) {2433r_current_batch = _new_batch(r_batch_broken);2434r_current_batch->has_blend = has_blend;2435r_current_batch->modulate = modulated;2436r_current_batch->shader_variant = SHADER_VARIANT_QUAD;2437r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;2438}24392440bool has_msdf = bool(rect->flags & CANVAS_RECT_MSDF);2441TextureState tex_state(rect->texture, texture_filter, rect_repeat, has_msdf, use_linear_colors);2442TextureInfo *tex_info = texture_info_map.getptr(tex_state);2443if (!tex_info) {2444tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2445_prepare_batch_texture_info(rect->texture, tex_state, tex_info);2446}24472448if (has_msdf != r_current_batch->use_msdf || rect->px_range != r_current_batch->msdf_pix_range || rect->outline != r_current_batch->msdf_outline) {2449r_current_batch = _new_batch(r_batch_broken);2450r_current_batch->use_msdf = has_msdf;2451r_current_batch->msdf_pix_range = rect->px_range;2452r_current_batch->msdf_outline = rect->outline;2453}24542455bool has_lcd = bool(rect->flags & CANVAS_RECT_LCD);2456if (has_lcd != r_current_batch->use_lcd) {2457r_current_batch = _new_batch(r_batch_broken);2458r_current_batch->use_lcd = has_lcd;2459}24602461if (r_current_batch->tex_info != tex_info) {2462r_current_batch = _new_batch(r_batch_broken);2463r_current_batch->tex_info = tex_info;2464}24652466InstanceData *instance_data = new_instance_data(*r_current_batch, template_instance);2467Rect2 src_rect;2468Rect2 dst_rect;24692470if (rect->texture.is_valid()) {2471src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * tex_info->texpixel_size, rect->source.size * tex_info->texpixel_size) : Rect2(0, 0, 1, 1);2472dst_rect = Rect2(rect->rect.position, rect->rect.size);24732474if (dst_rect.size.width < 0) {2475dst_rect.position.x += dst_rect.size.width;2476dst_rect.size.width *= -1;2477}2478if (dst_rect.size.height < 0) {2479dst_rect.position.y += dst_rect.size.height;2480dst_rect.size.height *= -1;2481}24822483if (rect->flags & CANVAS_RECT_FLIP_H) {2484src_rect.size.x *= -1;2485}24862487if (rect->flags & CANVAS_RECT_FLIP_V) {2488src_rect.size.y *= -1;2489}24902491if (rect->flags & CANVAS_RECT_TRANSPOSE) {2492instance_data->flags |= INSTANCE_FLAGS_TRANSPOSE_RECT;2493}24942495if (rect->flags & CANVAS_RECT_CLIP_UV) {2496instance_data->flags |= INSTANCE_FLAGS_CLIP_RECT_UV;2497}24982499} else {2500dst_rect = Rect2(rect->rect.position, rect->rect.size);25012502if (dst_rect.size.width < 0) {2503dst_rect.position.x += dst_rect.size.width;2504dst_rect.size.width *= -1;2505}2506if (dst_rect.size.height < 0) {2507dst_rect.position.y += dst_rect.size.height;2508dst_rect.size.height *= -1;2509}25102511src_rect = Rect2(0, 0, 1, 1);2512}25132514instance_data->modulation[0] = modulated.r;2515instance_data->modulation[1] = modulated.g;2516instance_data->modulation[2] = modulated.b;2517instance_data->modulation[3] = modulated.a;25182519instance_data->src_rect[0] = src_rect.position.x;2520instance_data->src_rect[1] = src_rect.position.y;2521instance_data->src_rect[2] = src_rect.size.width;2522instance_data->src_rect[3] = src_rect.size.height;25232524instance_data->dst_rect[0] = dst_rect.position.x;2525instance_data->dst_rect[1] = dst_rect.position.y;2526instance_data->dst_rect[2] = dst_rect.size.width;2527instance_data->dst_rect[3] = dst_rect.size.height;25282529_add_to_batch(r_batch_broken, r_current_batch);2530} break;25312532case Item::Command::TYPE_NINEPATCH: {2533const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);25342535if (r_current_batch->command_type != Item::Command::TYPE_NINEPATCH) {2536r_current_batch = _new_batch(r_batch_broken);2537r_current_batch->command_type = Item::Command::TYPE_NINEPATCH;2538r_current_batch->command = c;2539r_current_batch->has_blend = false;2540r_current_batch->shader_variant = SHADER_VARIANT_NINEPATCH;2541r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;2542r_current_batch->flags = 0;2543r_current_batch->use_msdf = false;2544}25452546TextureState tex_state(np->texture, texture_filter, texture_repeat, false, use_linear_colors);2547TextureInfo *tex_info = texture_info_map.getptr(tex_state);2548if (!tex_info) {2549tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2550_prepare_batch_texture_info(np->texture, tex_state, tex_info);2551}25522553if (r_current_batch->tex_info != tex_info) {2554r_current_batch = _new_batch(r_batch_broken);2555r_current_batch->tex_info = tex_info;2556}25572558InstanceData *instance_data = new_instance_data(*r_current_batch, template_instance);25592560Rect2 src_rect;2561Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);25622563if (np->texture.is_valid() && np->source != Rect2()) {2564src_rect = Rect2(np->source.position.x * tex_info->texpixel_size.width, np->source.position.y * tex_info->texpixel_size.height, np->source.size.x * tex_info->texpixel_size.width, np->source.size.y * tex_info->texpixel_size.height);2565instance_data->ninepatch_pixel_size[0] = 1.0 / np->source.size.width;2566instance_data->ninepatch_pixel_size[1] = 1.0 / np->source.size.height;2567} else {2568src_rect = Rect2(0, 0, 1, 1);2569// Set the default ninepatch pixel size to the full texture size.2570instance_data->ninepatch_pixel_size[0] = tex_info->texpixel_size.width;2571instance_data->ninepatch_pixel_size[1] = tex_info->texpixel_size.height;2572}25732574Color modulated = np->color * base_color;2575if (use_linear_colors) {2576modulated = modulated.srgb_to_linear();2577}25782579instance_data->modulation[0] = modulated.r;2580instance_data->modulation[1] = modulated.g;2581instance_data->modulation[2] = modulated.b;2582instance_data->modulation[3] = modulated.a;25832584instance_data->src_rect[0] = src_rect.position.x;2585instance_data->src_rect[1] = src_rect.position.y;2586instance_data->src_rect[2] = src_rect.size.width;2587instance_data->src_rect[3] = src_rect.size.height;25882589instance_data->dst_rect[0] = dst_rect.position.x;2590instance_data->dst_rect[1] = dst_rect.position.y;2591instance_data->dst_rect[2] = dst_rect.size.width;2592instance_data->dst_rect[3] = dst_rect.size.height;25932594instance_data->flags |= int(np->axis_x) << INSTANCE_FLAGS_NINEPATCH_H_MODE_SHIFT;2595instance_data->flags |= int(np->axis_y) << INSTANCE_FLAGS_NINEPATCH_V_MODE_SHIFT;25962597if (np->draw_center) {2598instance_data->flags |= INSTANCE_FLAGS_NINEPACH_DRAW_CENTER;2599}26002601instance_data->ninepatch_margins[0] = np->margin[SIDE_LEFT];2602instance_data->ninepatch_margins[1] = np->margin[SIDE_TOP];2603instance_data->ninepatch_margins[2] = np->margin[SIDE_RIGHT];2604instance_data->ninepatch_margins[3] = np->margin[SIDE_BOTTOM];26052606_add_to_batch(r_batch_broken, r_current_batch);2607} break;26082609case Item::Command::TYPE_POLYGON: {2610const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);26112612// Polygon's can't be batched, so always create a new batch2613r_current_batch = _new_batch(r_batch_broken);26142615r_current_batch->command_type = Item::Command::TYPE_POLYGON;2616r_current_batch->has_blend = false;2617r_current_batch->command = c;2618r_current_batch->flags = 0;2619r_current_batch->use_msdf = false;26202621TextureState tex_state(polygon->texture, texture_filter, texture_repeat, false, use_linear_colors);2622TextureInfo *tex_info = texture_info_map.getptr(tex_state);2623if (!tex_info) {2624tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2625_prepare_batch_texture_info(polygon->texture, tex_state, tex_info);2626}26272628if (r_current_batch->tex_info != tex_info) {2629r_current_batch = _new_batch(r_batch_broken);2630r_current_batch->tex_info = tex_info;2631}26322633// pipeline variant2634{2635ERR_CONTINUE(polygon->primitive < 0 || polygon->primitive >= RS::PRIMITIVE_MAX);2636r_current_batch->shader_variant = polygon->primitive == RS::PRIMITIVE_POINTS ? SHADER_VARIANT_ATTRIBUTES_POINTS : SHADER_VARIANT_ATTRIBUTES;2637r_current_batch->render_primitive = _primitive_type_to_render_primitive(polygon->primitive);2638}26392640InstanceData *instance_data = new_instance_data(*r_current_batch, template_instance, true);26412642Color color = base_color;2643if (use_linear_colors) {2644color = color.srgb_to_linear();2645}26462647instance_data->modulation[0] = color.r;2648instance_data->modulation[1] = color.g;2649instance_data->modulation[2] = color.b;2650instance_data->modulation[3] = color.a;2651} break;26522653case Item::Command::TYPE_PRIMITIVE: {2654const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);26552656if (primitive->point_count != r_current_batch->primitive_points || r_current_batch->command_type != Item::Command::TYPE_PRIMITIVE) {2657r_current_batch = _new_batch(r_batch_broken);2658r_current_batch->command_type = Item::Command::TYPE_PRIMITIVE;2659r_current_batch->has_blend = false;2660r_current_batch->command = c;2661r_current_batch->primitive_points = primitive->point_count;2662r_current_batch->flags = 0;26632664ERR_CONTINUE(primitive->point_count == 0 || primitive->point_count > 4);26652666switch (primitive->point_count) {2667case 1:2668r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE_POINTS;2669r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_POINTS;2670break;2671case 2:2672r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE;2673r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_LINES;2674break;2675case 3:2676case 4:2677r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE;2678r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;2679break;2680default:2681// Unknown point count.2682break;2683}2684}26852686TextureState tex_state(primitive->texture, texture_filter, texture_repeat, false, use_linear_colors);2687TextureInfo *tex_info = texture_info_map.getptr(tex_state);2688if (!tex_info) {2689tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2690_prepare_batch_texture_info(primitive->texture, tex_state, tex_info);2691}26922693if (r_current_batch->tex_info != tex_info) {2694r_current_batch = _new_batch(r_batch_broken);2695r_current_batch->tex_info = tex_info;2696}26972698InstanceData *instance_data = new_instance_data(*r_current_batch, template_instance);26992700for (uint32_t j = 0; j < MIN(3u, primitive->point_count); j++) {2701instance_data->points[j * 2 + 0] = primitive->points[j].x;2702instance_data->points[j * 2 + 1] = primitive->points[j].y;2703instance_data->uvs[j * 2 + 0] = primitive->uvs[j].x;2704instance_data->uvs[j * 2 + 1] = primitive->uvs[j].y;2705Color col = primitive->colors[j] * base_color;2706if (use_linear_colors) {2707col = col.srgb_to_linear();2708}2709instance_data->colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);2710instance_data->colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);2711}27122713_add_to_batch(r_batch_broken, r_current_batch);27142715if (primitive->point_count == 4) {2716instance_data = new_instance_data(*r_current_batch, template_instance);27172718for (uint32_t j = 0; j < 3; j++) {2719int offset = j == 0 ? 0 : 1;2720// Second triangle in the quad. Uses vertices 0, 2, 3.2721instance_data->points[j * 2 + 0] = primitive->points[j + offset].x;2722instance_data->points[j * 2 + 1] = primitive->points[j + offset].y;2723instance_data->uvs[j * 2 + 0] = primitive->uvs[j + offset].x;2724instance_data->uvs[j * 2 + 1] = primitive->uvs[j + offset].y;2725Color col = primitive->colors[j + offset] * base_color;2726if (use_linear_colors) {2727col = col.srgb_to_linear();2728}2729instance_data->colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);2730instance_data->colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);2731}27322733_add_to_batch(r_batch_broken, r_current_batch);2734}2735} break;27362737case Item::Command::TYPE_MESH:2738case Item::Command::TYPE_MULTIMESH:2739case Item::Command::TYPE_PARTICLES: {2740// Mesh's can't be batched, so always create a new batch2741r_current_batch = _new_batch(r_batch_broken);2742r_current_batch->command = c;2743r_current_batch->command_type = c->type;2744r_current_batch->has_blend = false;2745r_current_batch->flags = 0;2746r_current_batch->use_msdf = false;27472748InstanceData *instance_data = nullptr;27492750Color modulate(1, 1, 1, 1);2751if (c->type == Item::Command::TYPE_MESH) {2752const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(c);2753TextureState tex_state(m->texture, texture_filter, texture_repeat, false, use_linear_colors);2754TextureInfo *tex_info = texture_info_map.getptr(tex_state);2755if (!tex_info) {2756tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2757_prepare_batch_texture_info(m->texture, tex_state, tex_info);2758}2759r_current_batch->tex_info = tex_info;2760instance_data = new_instance_data(*r_current_batch, template_instance, true);27612762r_current_batch->mesh_instance_count = 1;2763_update_transform_2d_to_mat2x3(base_transform * draw_transform * m->transform, instance_data->world);2764modulate = m->modulate;2765} else if (c->type == Item::Command::TYPE_MULTIMESH) {2766RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();27672768const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(c);2769RID multimesh = mm->multimesh;27702771if (mesh_storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) {2772break;2773}27742775r_current_batch->mesh_instance_count = mesh_storage->multimesh_get_instances_to_draw(multimesh);2776if (r_current_batch->mesh_instance_count == 0) {2777break;2778}27792780TextureState tex_state(mm->texture, texture_filter, texture_repeat, false, use_linear_colors);2781TextureInfo *tex_info = texture_info_map.getptr(tex_state);2782if (!tex_info) {2783tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2784_prepare_batch_texture_info(mm->texture, tex_state, tex_info);2785}2786r_current_batch->tex_info = tex_info;2787instance_data = new_instance_data(*r_current_batch, template_instance, true);27882789r_current_batch->flags |= 1; // multimesh, trails disabled27902791if (mesh_storage->multimesh_uses_colors(mm->multimesh)) {2792r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;2793}2794if (mesh_storage->multimesh_uses_custom_data(mm->multimesh)) {2795r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;2796}2797} else if (c->type == Item::Command::TYPE_PARTICLES) {2798RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();2799RendererRD::ParticlesStorage *particles_storage = RendererRD::ParticlesStorage::get_singleton();28002801const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(c);2802TextureState tex_state(pt->texture, texture_filter, texture_repeat, false, use_linear_colors);2803TextureInfo *tex_info = texture_info_map.getptr(tex_state);2804if (!tex_info) {2805tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2806_prepare_batch_texture_info(pt->texture, tex_state, tex_info);2807}2808r_current_batch->tex_info = tex_info;2809instance_data = new_instance_data(*r_current_batch, template_instance, true);28102811uint32_t divisor = 1;2812r_current_batch->mesh_instance_count = particles_storage->particles_get_amount(pt->particles, divisor);2813r_current_batch->flags |= (divisor & BATCH_FLAGS_INSTANCING_MASK);2814r_current_batch->mesh_instance_count /= divisor;28152816RID particles = pt->particles;28172818r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;2819r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;28202821if (particles_storage->particles_has_collision(particles) && texture_storage->render_target_is_sdf_enabled(p_render_target.render_target)) {2822// Pass collision information.2823Transform2D xform = p_item->final_transform;28242825RID sdf_texture = texture_storage->render_target_get_sdf_texture(p_render_target.render_target);28262827Rect2 to_screen;2828{2829Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_render_target.render_target);28302831to_screen.size = Vector2(1.0 / sdf_rect.size.width, 1.0 / sdf_rect.size.height);2832to_screen.position = -sdf_rect.position * to_screen.size;2833}28342835particles_storage->particles_set_canvas_sdf_collision(pt->particles, true, xform, to_screen, sdf_texture);2836} else {2837particles_storage->particles_set_canvas_sdf_collision(pt->particles, false, Transform2D(), Rect2(), RID());2838}2839r_sdf_used |= particles_storage->particles_has_collision(particles);2840}28412842Color modulated = modulate * base_color;2843if (use_linear_colors) {2844modulated = modulated.srgb_to_linear();2845}28462847instance_data->modulation[0] = modulated.r;2848instance_data->modulation[1] = modulated.g;2849instance_data->modulation[2] = modulated.b;2850instance_data->modulation[3] = modulated.a;2851} break;28522853case Item::Command::TYPE_TRANSFORM: {2854const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);2855draw_transform = transform->xform;2856_update_transform_2d_to_mat2x3(base_transform * transform->xform, template_instance.world);2857} break;28582859case Item::Command::TYPE_CLIP_IGNORE: {2860const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);2861if (r_current_clip) {2862if (ci->ignore != reclip) {2863r_current_batch = _new_batch(r_batch_broken);2864if (ci->ignore) {2865r_current_batch->clip = nullptr;2866reclip = true;2867} else {2868r_current_batch->clip = r_current_clip;2869reclip = false;2870}2871}2872}2873} break;28742875case Item::Command::TYPE_ANIMATION_SLICE: {2876const Item::CommandAnimationSlice *as = static_cast<const Item::CommandAnimationSlice *>(c);2877double current_time = RSG::rasterizer->get_total_time();2878double local_time = Math::fposmod(current_time - as->offset, as->animation_length);2879skipping = !(local_time >= as->slice_begin && local_time < as->slice_end);28802881RenderingServerDefault::redraw_request(); // animation visible means redraw request2882} break;2883}28842885c = c->next;2886r_batch_broken = false;2887}28882889#ifdef DEBUG_ENABLED2890if (debug_redraw && p_item->debug_redraw_time > 0.0) {2891Color dc = debug_redraw_color;2892dc.a *= p_item->debug_redraw_time / debug_redraw_time;28932894// 1: If commands are different, start a new batch.2895if (r_current_batch->command_type != Item::Command::TYPE_RECT) {2896r_current_batch = _new_batch(r_batch_broken);2897r_current_batch->command_type = Item::Command::TYPE_RECT;2898// it is ok to be null for a TYPE_RECT2899r_current_batch->command = nullptr;2900// default variant2901r_current_batch->shader_variant = SHADER_VARIANT_QUAD;2902r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;2903r_current_batch->flags = 0;2904}29052906// 2: If the current batch has lighting, start a new batch.2907if (r_current_batch->use_lighting) {2908r_current_batch = _new_batch(r_batch_broken);2909r_current_batch->use_lighting = false;2910}29112912// 3: If the current batch has blend, start a new batch.2913if (r_current_batch->has_blend) {2914r_current_batch = _new_batch(r_batch_broken);2915r_current_batch->has_blend = false;2916}29172918TextureState tex_state(default_canvas_texture, texture_filter, texture_repeat, false, use_linear_colors);2919TextureInfo *tex_info = texture_info_map.getptr(tex_state);2920if (!tex_info) {2921tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;2922_prepare_batch_texture_info(default_canvas_texture, tex_state, tex_info);2923}29242925if (r_current_batch->tex_info != tex_info) {2926r_current_batch = _new_batch(r_batch_broken);2927r_current_batch->tex_info = tex_info;2928}29292930_update_transform_2d_to_mat2x3(base_transform, template_instance.world);2931InstanceData *instance_data = new_instance_data(*r_current_batch, template_instance);29322933Rect2 src_rect;2934Rect2 dst_rect;29352936dst_rect = p_item->rect;2937if (dst_rect.size.width < 0) {2938dst_rect.position.x += dst_rect.size.width;2939dst_rect.size.width *= -1;2940}2941if (dst_rect.size.height < 0) {2942dst_rect.position.y += dst_rect.size.height;2943dst_rect.size.height *= -1;2944}29452946src_rect = Rect2(0, 0, 1, 1);29472948instance_data->modulation[0] = dc.r;2949instance_data->modulation[1] = dc.g;2950instance_data->modulation[2] = dc.b;2951instance_data->modulation[3] = dc.a;29522953instance_data->src_rect[0] = src_rect.position.x;2954instance_data->src_rect[1] = src_rect.position.y;2955instance_data->src_rect[2] = src_rect.size.width;2956instance_data->src_rect[3] = src_rect.size.height;29572958instance_data->dst_rect[0] = dst_rect.position.x;2959instance_data->dst_rect[1] = dst_rect.position.y;2960instance_data->dst_rect[2] = dst_rect.size.width;2961instance_data->dst_rect[3] = dst_rect.size.height;29622963_add_to_batch(r_batch_broken, r_current_batch);29642965p_item->debug_redraw_time -= RSG::rasterizer->get_frame_delta_time();29662967RenderingServerDefault::redraw_request();29682969r_batch_broken = false;2970}2971#endif29722973if (r_current_clip && reclip) {2974// will make it re-enable clipping if needed afterwards2975r_current_clip = nullptr;2976}2977}29782979void RendererCanvasRenderRD::_before_evict(RendererCanvasRenderRD::RIDSetKey &p_key, RID &p_rid) {2980RD::get_singleton()->uniform_set_set_invalidation_callback(p_rid, nullptr, nullptr);2981RD::get_singleton()->free_rid(p_rid);2982}29832984void RendererCanvasRenderRD::_uniform_set_invalidation_callback(void *p_userdata) {2985const RIDSetKey *key = static_cast<RIDSetKey *>(p_userdata);2986static_cast<RendererCanvasRenderRD *>(singleton)->rid_set_to_uniform_set.erase(*key);2987}29882989void RendererCanvasRenderRD::_canvas_texture_invalidation_callback(bool p_deleted, void *p_userdata) {2990KeyValue<RID, TightLocalVector<RID>> *kv = static_cast<KeyValue<RID, TightLocalVector<RID>> *>(p_userdata);2991RD *rd = RD::get_singleton();2992for (RID rid : kv->value) {2993// The invalidation callback will also take care of clearing rid_set_to_uniform_set cache.2994rd->free_rid(rid);2995}2996kv->value.clear();2997if (p_deleted) {2998static_cast<RendererCanvasRenderRD *>(singleton)->canvas_texture_to_uniform_set.erase(kv->key);2999}3000}30013002void RendererCanvasRenderRD::_render_batch(RD::DrawListID p_draw_list, CanvasShaderData *p_shader_data, RenderingDevice::FramebufferFormatID p_framebuffer_format, Light *p_lights, Batch const *p_batch, RenderingMethod::RenderInfo *r_render_info) {3003{3004RendererRD::TextureStorage *ts = RendererRD::TextureStorage::get_singleton();30053006RIDSetKey key(p_batch->tex_info->state);30073008const RID *uniform_set = rid_set_to_uniform_set.getptr(key);3009if (uniform_set == nullptr) {3010RD::Uniform *uniform_ptrw = state.batch_texture_uniforms.ptrw();3011uniform_ptrw[0] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 0, p_batch->tex_info->diffuse);3012uniform_ptrw[1] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 1, p_batch->tex_info->normal);3013uniform_ptrw[2] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 2, p_batch->tex_info->specular);3014uniform_ptrw[3] = RD::Uniform(RD::UNIFORM_TYPE_SAMPLER, 3, p_batch->tex_info->sampler);30153016RID rid = RD::get_singleton()->uniform_set_create(state.batch_texture_uniforms, shader.default_version_rd_shader, BATCH_UNIFORM_SET);3017ERR_FAIL_COND_MSG(rid.is_null(), "Failed to create uniform set for batch.");30183019const RIDCache::Pair *iter = rid_set_to_uniform_set.insert(key, rid);3020uniform_set = &iter->data;3021RD::get_singleton()->uniform_set_set_invalidation_callback(rid, RendererCanvasRenderRD::_uniform_set_invalidation_callback, (void *)&iter->key);30223023// If this is a CanvasTexture, it must be tracked so that any changes to the diffuse, normal,3024// or specular channels invalidate all associated uniform sets.3025if (ts->owns_canvas_texture(p_batch->tex_info->state.texture)) {3026KeyValue<RID, TightLocalVector<RID>> *kv = nullptr;3027if (HashMap<RID, TightLocalVector<RID>>::Iterator i = canvas_texture_to_uniform_set.find(p_batch->tex_info->state.texture); i == canvas_texture_to_uniform_set.end()) {3028kv = &*canvas_texture_to_uniform_set.insert(p_batch->tex_info->state.texture, { *uniform_set });3029} else {3030i->value.push_back(rid);3031kv = &*i;3032}3033ts->canvas_texture_set_invalidation_callback(p_batch->tex_info->state.texture, RendererCanvasRenderRD::_canvas_texture_invalidation_callback, kv);3034}3035}30363037if (state.current_batch_uniform_set != *uniform_set) {3038state.current_batch_uniform_set = *uniform_set;3039RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, *uniform_set, BATCH_UNIFORM_SET);3040}3041}30423043RID pipeline;3044PipelineKey pipeline_key;3045pipeline_key.framebuffer_format_id = p_framebuffer_format;3046pipeline_key.variant = p_batch->shader_variant;3047pipeline_key.render_primitive = p_batch->render_primitive;3048pipeline_key.shader_specialization.use_lighting = p_batch->use_lighting;3049pipeline_key.shader_specialization.use_msdf = p_batch->use_msdf;3050pipeline_key.shader_specialization.use_lcd = p_batch->use_lcd;3051pipeline_key.lcd_blend = p_batch->has_blend;30523053switch (p_batch->command_type) {3054case Item::Command::TYPE_RECT:3055case Item::Command::TYPE_NINEPATCH: {3056PushConstant push_constant = p_batch->push_constant();30573058pipeline_key.vertex_format_id = shader.quad_vertex_format_id;3059pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);3060RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);3061if (p_batch->has_blend) {3062RD::get_singleton()->draw_list_set_blend_constants(p_draw_list, p_batch->modulate);3063}30643065RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(push_constant));3066FixedVector<RID, 1> vb = { p_batch->instance_buffer };3067FixedVector<uint64_t, 1> vo = { uint64_t(p_batch->start) * sizeof(InstanceData) };3068RD::get_singleton()->draw_list_bind_vertex_buffers_format(p_draw_list, shader.quad_vertex_format_id, 1, vb, vo);3069RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);3070RD::get_singleton()->draw_list_draw(p_draw_list, true, p_batch->instance_count);30713072if (r_render_info) {3073r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += p_batch->instance_count;3074r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += 2 * p_batch->instance_count;3075r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;3076}3077} break;30783079case Item::Command::TYPE_POLYGON: {3080ERR_FAIL_NULL(p_batch->command);3081PushConstantAttributes push_constant = p_batch->push_constant_attributes();30823083const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(p_batch->command);30843085PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);3086ERR_FAIL_NULL(pb);30873088pipeline_key.vertex_format_id = pb->vertex_format_id;3089pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);3090RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);30913092RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(push_constant));3093RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, pb->vertex_array);3094if (pb->indices.is_valid()) {3095RD::get_singleton()->draw_list_bind_index_array(p_draw_list, pb->indices);3096}30973098RD::get_singleton()->draw_list_draw(p_draw_list, pb->indices.is_valid());3099if (r_render_info) {3100r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;3101r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(polygon->primitive, pb->primitive_count);3102r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;3103}3104} break;31053106case Item::Command::TYPE_PRIMITIVE: {3107ERR_FAIL_NULL(p_batch->command);31083109const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(p_batch->command);31103111PushConstant push_constant = p_batch->push_constant();3112pipeline_key.vertex_format_id = shader.primitive_vertex_format_id;3113pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);3114RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);31153116RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(push_constant));3117FixedVector<RID, 1> vb = { p_batch->instance_buffer };3118FixedVector<uint64_t, 1> vo = { uint64_t(p_batch->start) * sizeof(InstanceData) };3119RD::get_singleton()->draw_list_bind_vertex_buffers_format(p_draw_list, shader.primitive_vertex_format_id, 1, vb, vo);3120RD::get_singleton()->draw_list_bind_index_array(p_draw_list, primitive_arrays.index_array[MIN(3u, primitive->point_count) - 1]);3121uint32_t instance_count = p_batch->instance_count;3122RD::get_singleton()->draw_list_draw(p_draw_list, true, instance_count);31233124if (r_render_info) {3125const RenderingServer::PrimitiveType rs_primitive[5] = { RS::PRIMITIVE_POINTS, RS::PRIMITIVE_POINTS, RS::PRIMITIVE_LINES, RS::PRIMITIVE_TRIANGLES, RS::PRIMITIVE_TRIANGLES };3126r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += instance_count;3127r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(rs_primitive[p_batch->primitive_points], p_batch->primitive_points) * instance_count;3128r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;3129}3130} break;31313132case Item::Command::TYPE_MESH:3133case Item::Command::TYPE_MULTIMESH:3134case Item::Command::TYPE_PARTICLES: {3135ERR_FAIL_NULL(p_batch->command);31363137PushConstantAttributes push_constant = p_batch->push_constant_attributes();31383139RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();3140RendererRD::ParticlesStorage *particles_storage = RendererRD::ParticlesStorage::get_singleton();31413142RID mesh;3143RID mesh_instance;31443145if (p_batch->command_type == Item::Command::TYPE_MESH) {3146const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(p_batch->command);3147mesh = m->mesh;3148mesh_instance = m->mesh_instance;3149} else if (p_batch->command_type == Item::Command::TYPE_MULTIMESH) {3150const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(p_batch->command);3151RID multimesh = mm->multimesh;3152mesh = mesh_storage->multimesh_get_mesh(multimesh);31533154RID uniform_set = mesh_storage->multimesh_get_2d_uniform_set(multimesh, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);3155RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, TRANSFORMS_UNIFORM_SET);3156} else if (p_batch->command_type == Item::Command::TYPE_PARTICLES) {3157const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(p_batch->command);3158RID particles = pt->particles;3159mesh = particles_storage->particles_get_draw_pass_mesh(particles, 0);31603161ERR_BREAK(particles_storage->particles_get_mode(particles) != RS::PARTICLES_MODE_2D);3162particles_storage->particles_request_process(particles);31633164if (particles_storage->particles_is_inactive(particles)) {3165break;3166}31673168RenderingServerDefault::redraw_request(); // Active particles means redraw request.31693170int dpc = particles_storage->particles_get_draw_passes(particles);3171if (dpc == 0) {3172break; // Nothing to draw.3173}31743175RID uniform_set = particles_storage->particles_get_instance_buffer_uniform_set(pt->particles, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);3176RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, TRANSFORMS_UNIFORM_SET);3177}31783179if (mesh.is_null()) {3180break;3181}31823183uint32_t surf_count = mesh_storage->mesh_get_surface_count(mesh);31843185for (uint32_t j = 0; j < surf_count; j++) {3186void *surface = mesh_storage->mesh_get_surface(mesh, j);31873188RS::PrimitiveType primitive = mesh_storage->mesh_surface_get_primitive(surface);3189ERR_CONTINUE(primitive < 0 || primitive >= RS::PRIMITIVE_MAX);31903191RID vertex_array;3192pipeline_key.variant = primitive == RS::PRIMITIVE_POINTS ? SHADER_VARIANT_ATTRIBUTES_POINTS : SHADER_VARIANT_ATTRIBUTES;3193pipeline_key.render_primitive = _primitive_type_to_render_primitive(primitive);3194pipeline_key.vertex_format_id = RD::INVALID_FORMAT_ID;31953196pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant, mesh_instance, surface, j, &vertex_array);3197RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);31983199RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(push_constant));32003201RID index_array = mesh_storage->mesh_surface_get_index_array(surface, 0);32023203if (index_array.is_valid()) {3204RD::get_singleton()->draw_list_bind_index_array(p_draw_list, index_array);3205}32063207RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, vertex_array);3208RD::get_singleton()->draw_list_draw(p_draw_list, index_array.is_valid(), p_batch->mesh_instance_count);32093210if (r_render_info) {3211r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;3212r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(primitive, mesh_storage->mesh_surface_get_vertices_drawn_count(surface)) * p_batch->mesh_instance_count;3213r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;3214}3215}3216} break;3217case Item::Command::TYPE_TRANSFORM:3218case Item::Command::TYPE_CLIP_IGNORE:3219case Item::Command::TYPE_ANIMATION_SLICE: {3220// Can ignore these as they only impact batch creation.3221} break;3222}3223}32243225RendererCanvasRenderRD::InstanceData *RendererCanvasRenderRD::new_instance_data(Batch &p_current_batch, const InstanceData &template_instance, bool p_use_push_data) {3226InstanceData *instance_data = nullptr;32273228if (unlikely(p_use_push_data)) {3229instance_data = &p_current_batch.push_data;3230// instance_count must be > 0 to indicate the batch has been used when calling _new_batch, so we set a flag.3231p_current_batch.instance_count = PUSH_DATA_INSTANCE_COUNT;3232} else {3233// Return the intermediary instance data to prevent the caller from accidentally reading write-combined memory pages, which has huge performance implications.3234instance_data = &state.intermediary_instance_data;3235}32363237memcpy(instance_data, &template_instance, sizeof(InstanceData));3238return instance_data;3239}32403241RendererCanvasRenderRD::Batch *RendererCanvasRenderRD::_new_batch(bool &r_batch_broken) {3242if (state.canvas_instance_batches.is_empty()) {3243Batch new_batch;3244// First try to reuse previous instance buffer if possible.3245if (state.prev_instance_data && state.prev_instance_data_index < state.max_instances_per_buffer) {3246bool must_remap = state.instance_buffers.prepare_for_map(true);3247// must_remap will be false if we're preparing to map the buffer for the same frame and can reuse the existing UMA buffer.3248if (!must_remap) {3249state.instance_data = state.prev_instance_data;3250state.instance_data_index = state.prev_instance_data_index;3251}3252state.prev_instance_data = nullptr;3253state.prev_instance_data_index = 0;3254}3255// This will still be a valid point when multiple calls to _render_batch_items3256// are made in the same draw call.3257if (state.instance_data == nullptr) {3258// If there is no existing instance buffer, we must allocate a new one.3259_allocate_instance_buffer();3260} else {3261// Otherwise, just use the existing one from where it last left off.3262new_batch.start = state.instance_data_index;3263}3264new_batch.instance_buffer = state.instance_buffers._get(0);3265state.canvas_instance_batches.push_back(new_batch);3266return state.canvas_instance_batches.ptr();3267}32683269if (r_batch_broken || state.canvas_instance_batches[state.current_batch_index].instance_count == 0) {3270return &state.canvas_instance_batches[state.current_batch_index];3271}32723273r_batch_broken = true;32743275// Copy the properties of the current batch, we will manually update the things that changed.3276Batch new_batch = state.canvas_instance_batches[state.current_batch_index];3277new_batch.instance_count = 0;3278new_batch.start = state.instance_data_index;3279memset(&new_batch.push_data, 0, sizeof(new_batch.push_data));3280state.current_batch_index++;3281state.canvas_instance_batches.push_back(new_batch);3282return &state.canvas_instance_batches[state.current_batch_index];3283}32843285void RendererCanvasRenderRD::_add_to_batch(bool &r_batch_broken, Batch *&r_current_batch) {3286DEV_ASSERT(r_current_batch->command_type == Item::Command::TYPE_RECT ||3287r_current_batch->command_type == Item::Command::TYPE_NINEPATCH ||3288r_current_batch->command_type == Item::Command::TYPE_PRIMITIVE);3289r_current_batch->instance_count++;3290memcpy(&state.instance_data[state.instance_data_index], &state.intermediary_instance_data, sizeof(InstanceData));3291state.instance_data_index++;3292if (state.instance_data_index >= state.max_instances_per_buffer) {3293RD::get_singleton()->buffer_flush(r_current_batch->instance_buffer);3294state.instance_data = nullptr;3295_allocate_instance_buffer();3296state.instance_data_index = 0;3297r_batch_broken = false; // Force a new batch to be created3298r_current_batch = _new_batch(r_batch_broken);3299r_current_batch->instance_buffer = state.instance_buffers._get(0);3300}3301}33023303void RendererCanvasRenderRD::_allocate_instance_buffer() {3304state.instance_buffers.prepare_for_upload();3305state.instance_data = reinterpret_cast<InstanceData *>(state.instance_buffers.map_raw_for_upload(0));3306}33073308void RendererCanvasRenderRD::_prepare_batch_texture_info(RID p_texture, TextureState &p_state, TextureInfo *p_info) {3309if (p_texture.is_null()) {3310p_texture = default_canvas_texture;3311}33123313RendererRD::TextureStorage::CanvasTextureInfo info =3314RendererRD::TextureStorage::get_singleton()->canvas_texture_get_info(3315p_texture,3316p_state.texture_filter(),3317p_state.texture_repeat(),3318p_state.linear_colors(),3319p_state.texture_is_data());3320// something odd happened3321if (info.is_null()) {3322_prepare_batch_texture_info(default_canvas_texture, p_state, p_info);3323return;3324}33253326p_info->state = p_state;3327p_info->diffuse = info.diffuse;3328p_info->normal = info.normal;3329p_info->specular = info.specular;3330p_info->sampler = info.sampler;33313332// cache values to be copied to instance data3333if (info.specular_color.a < 0.999) {3334p_info->flags |= BATCH_FLAGS_DEFAULT_SPECULAR_MAP_USED;3335}33363337if (info.use_normal) {3338p_info->flags |= BATCH_FLAGS_DEFAULT_NORMAL_MAP_USED;3339}33403341uint8_t a = uint8_t(CLAMP(info.specular_color.a * 255.0, 0.0, 255.0));3342uint8_t b = uint8_t(CLAMP(info.specular_color.b * 255.0, 0.0, 255.0));3343uint8_t g = uint8_t(CLAMP(info.specular_color.g * 255.0, 0.0, 255.0));3344uint8_t r = uint8_t(CLAMP(info.specular_color.r * 255.0, 0.0, 255.0));3345p_info->specular_shininess = uint32_t(a) << 24 | uint32_t(b) << 16 | uint32_t(g) << 8 | uint32_t(r);33463347p_info->texpixel_size = Vector2(1.0 / float(info.size.width), 1.0 / float(info.size.height));3348}33493350RendererCanvasRenderRD::~RendererCanvasRenderRD() {3351RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();3352RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();33533354//canvas state33553356material_storage->material_free(default_canvas_group_material);3357material_storage->shader_free(default_canvas_group_shader);33583359material_storage->material_free(default_clip_children_material);3360material_storage->shader_free(default_clip_children_shader);33613362{3363if (state.canvas_state_buffer.is_valid()) {3364RD::get_singleton()->free_rid(state.canvas_state_buffer);3365}33663367memdelete_arr(state.light_uniforms);3368RD::get_singleton()->free_rid(state.lights_storage_buffer);3369}33703371//shadow rendering3372{3373shadow_render.shader.version_free(shadow_render.shader_version);3374//this will also automatically clear all pipelines3375RD::get_singleton()->free_rid(state.shadow_sampler);3376}33773378//buffers3379{3380RD::get_singleton()->free_rid(shader.quad_index_array);3381RD::get_singleton()->free_rid(shader.quad_index_buffer);3382//primitives are erase by dependency3383}33843385if (state.shadow_fb.is_valid()) {3386RD::get_singleton()->free_rid(state.shadow_depth_texture);3387}3388RD::get_singleton()->free_rid(state.shadow_texture);33893390if (state.shadow_occluder_buffer.is_valid()) {3391RD::get_singleton()->free_rid(state.shadow_occluder_buffer);3392}33933394state.instance_buffers.uninit();33953396// Disable the callback, as we're tearing everything down3397texture_storage->canvas_texture_set_invalidation_callback(default_canvas_texture, nullptr, nullptr);3398texture_storage->canvas_texture_free(default_canvas_texture);3399//pipelines don't need freeing, they are all gone after shaders are gone34003401memdelete(shader.default_version_data);3402}340334043405