Path: blob/master/servers/rendering/rendering_device.cpp
20844 views
/**************************************************************************/1/* rendering_device.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 "rendering_device.h"31#include "rendering_device.compat.inc"3233#include "rendering_device_binds.h"34#include "shader_include_db.h"3536#include "core/config/project_settings.h"37#include "core/io/dir_access.h"38#include "core/io/file_access.h"39#include "core/profiling/profiling.h"40#include "core/templates/fixed_vector.h"41#include "modules/modules_enabled.gen.h"42#include "servers/rendering/rendering_shader_container.h"4344#ifdef MODULE_GLSLANG_ENABLED45#include "modules/glslang/shader_compile.h"46#endif4748#define FORCE_SEPARATE_PRESENT_QUEUE 049#define PRINT_FRAMEBUFFER_FORMAT 05051#define ERR_RENDER_THREAD_MSG String("This function (") + String(__func__) + String(") can only be called from the render thread. ")52#define ERR_RENDER_THREAD_GUARD() ERR_FAIL_COND_MSG(render_thread_id != Thread::get_caller_id(), ERR_RENDER_THREAD_MSG);53#define ERR_RENDER_THREAD_GUARD_V(m_ret) ERR_FAIL_COND_V_MSG(render_thread_id != Thread::get_caller_id(), (m_ret), ERR_RENDER_THREAD_MSG);5455/**************************/56/**** HELPER FUNCTIONS ****/57/**************************/5859static String _get_device_vendor_name(const RenderingContextDriver::Device &p_device) {60switch (p_device.vendor) {61case RenderingContextDriver::Vendor::VENDOR_AMD:62return "AMD";63case RenderingContextDriver::Vendor::VENDOR_IMGTEC:64return "ImgTec";65case RenderingContextDriver::Vendor::VENDOR_APPLE:66return "Apple";67case RenderingContextDriver::Vendor::VENDOR_NVIDIA:68return "NVIDIA";69case RenderingContextDriver::Vendor::VENDOR_ARM:70return "ARM";71case RenderingContextDriver::Vendor::VENDOR_MICROSOFT:72return "Microsoft";73case RenderingContextDriver::Vendor::VENDOR_QUALCOMM:74return "Qualcomm";75case RenderingContextDriver::Vendor::VENDOR_INTEL:76return "Intel";77default:78return "Unknown";79}80}8182static String _get_device_type_name(const RenderingContextDriver::Device &p_device) {83switch (p_device.type) {84case RenderingContextDriver::DEVICE_TYPE_INTEGRATED_GPU:85return "Integrated";86case RenderingContextDriver::DEVICE_TYPE_DISCRETE_GPU:87return "Discrete";88case RenderingContextDriver::DEVICE_TYPE_VIRTUAL_GPU:89return "Virtual";90case RenderingContextDriver::DEVICE_TYPE_CPU:91return "CPU";92case RenderingContextDriver::DEVICE_TYPE_OTHER:93default:94return "Other";95}96}9798static uint32_t _get_device_type_score(const RenderingContextDriver::Device &p_device) {99static const bool prefer_integrated = OS::get_singleton()->get_user_prefers_integrated_gpu();100switch (p_device.type) {101case RenderingContextDriver::DEVICE_TYPE_INTEGRATED_GPU:102return prefer_integrated ? 5 : 4;103case RenderingContextDriver::DEVICE_TYPE_DISCRETE_GPU:104return prefer_integrated ? 4 : 5;105case RenderingContextDriver::DEVICE_TYPE_VIRTUAL_GPU:106return 3;107case RenderingContextDriver::DEVICE_TYPE_CPU:108return 2;109case RenderingContextDriver::DEVICE_TYPE_OTHER:110default:111return 1;112}113}114115/**************************/116/**** RENDERING DEVICE ****/117/**************************/118119// When true, the command graph will attempt to reorder the rendering commands submitted by the user based on the dependencies detected from120// the commands automatically. This should improve rendering performance in most scenarios at the cost of some extra CPU overhead.121//122// This behavior can be disabled if it's suspected that the graph is not detecting dependencies correctly and more control over the order of123// the commands is desired (e.g. debugging).124125#define RENDER_GRAPH_REORDER 1126127// Synchronization barriers are issued between the graph's levels only with the necessary amount of detail to achieve the correct result. If128// it's suspected that the graph is not doing this correctly, full barriers can be issued instead that will block all types of operations129// between the synchronization levels. This setting will have a very negative impact on performance when enabled, so it's only intended for130// debugging purposes.131132#define RENDER_GRAPH_FULL_BARRIERS 0133134// The command graph can automatically issue secondary command buffers and record them on background threads when they reach an arbitrary135// size threshold. This can be very beneficial towards reducing the time the main thread takes to record all the rendering commands. However,136// this setting is not enabled by default as it's been shown to cause some strange issues with certain IHVs that have yet to be understood.137138#define SECONDARY_COMMAND_BUFFERS_PER_FRAME 0139140RenderingDevice *RenderingDevice::singleton = nullptr;141142RenderingDevice *RenderingDevice::get_singleton() {143return singleton;144}145146/***************************/147/**** ID INFRASTRUCTURE ****/148/***************************/149150void RenderingDevice::_add_dependency(RID p_id, RID p_depends_on) {151_THREAD_SAFE_METHOD_152153HashSet<RID> *set = dependency_map.getptr(p_depends_on);154if (set == nullptr) {155set = &dependency_map.insert(p_depends_on, HashSet<RID>())->value;156}157set->insert(p_id);158159set = reverse_dependency_map.getptr(p_id);160if (set == nullptr) {161set = &reverse_dependency_map.insert(p_id, HashSet<RID>())->value;162}163set->insert(p_depends_on);164}165166void RenderingDevice::_free_dependencies(RID p_id) {167_THREAD_SAFE_METHOD_168169// Direct dependencies must be freed.170171HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);172if (E) {173while (E->value.size()) {174free_rid(*E->value.begin());175}176dependency_map.remove(E);177}178179// Reverse dependencies must be unreferenced.180E = reverse_dependency_map.find(p_id);181182if (E) {183for (const RID &F : E->value) {184HashMap<RID, HashSet<RID>>::Iterator G = dependency_map.find(F);185ERR_CONTINUE(!G);186ERR_CONTINUE(!G->value.has(p_id));187G->value.erase(p_id);188}189190reverse_dependency_map.remove(E);191}192}193194/*******************************/195/**** SHADER INFRASTRUCTURE ****/196/*******************************/197198Vector<uint8_t> RenderingDevice::shader_compile_spirv_from_source(ShaderStage p_stage, const String &p_source_code, ShaderLanguage p_language, String *r_error, bool p_allow_cache) {199switch (p_language) {200#ifdef MODULE_GLSLANG_ENABLED201case ShaderLanguage::SHADER_LANGUAGE_GLSL: {202ShaderLanguageVersion language_version = driver->get_shader_container_format().get_shader_language_version();203ShaderSpirvVersion spirv_version = driver->get_shader_container_format().get_shader_spirv_version();204return compile_glslang_shader(p_stage, ShaderIncludeDB::parse_include_files(p_source_code), language_version, spirv_version, r_error);205}206#endif207default:208ERR_FAIL_V_MSG(Vector<uint8_t>(), "Shader language is not supported.");209}210}211212RID RenderingDevice::shader_create_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {213Vector<uint8_t> bytecode = shader_compile_binary_from_spirv(p_spirv, p_shader_name);214ERR_FAIL_COND_V(bytecode.is_empty(), RID());215return shader_create_from_bytecode(bytecode);216}217218/********************************/219/**** ACCELERATION STRUCTURE ****/220/********************************/221222RID RenderingDevice::blas_create(RID p_vertex_array, RID p_index_array, BitField<AccelerationStructureGeometryBits> p_geometry_bits, uint32_t p_position_attribute_location) {223ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), RID(), "The current rendering device has neither raytracing pipeline nor ray query support.");224225VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);226ERR_FAIL_NULL_V(vertex_array, RID());227228uint32_t position_binding = p_position_attribute_location;229RDD::VertexFormatID vertex_format;230231if (vertex_array->description != INVALID_ID) {232ERR_FAIL_COND_V(!vertex_formats.has(vertex_array->description), RID());233const VertexDescriptionCache &vd_cache = vertex_formats[vertex_array->description];234vertex_format = vd_cache.driver_id;235236const VertexAttribute *position_attribute = nullptr;237for (int i = 0; i < vd_cache.vertex_formats.size(); i++) {238const VertexAttribute &attr = vd_cache.vertex_formats[i];239if (attr.location == p_position_attribute_location) {240position_attribute = &attr;241break;242}243}244ERR_FAIL_NULL_V_MSG(position_attribute, RID(), vformat("Vertex array is missing a position attribute at location %u.", p_position_attribute_location));245ERR_FAIL_COND_V_MSG(position_attribute->frequency != VERTEX_FREQUENCY_VERTEX, RID(), vformat("Position attribute at location %u must use vertex frequency.", p_position_attribute_location));246247if (position_attribute->binding != UINT32_MAX) {248position_binding = position_attribute->binding;249}250}251252ERR_FAIL_COND_V_MSG(position_binding >= (uint32_t)vertex_array->buffers.size(), RID(), vformat("Vertex array is missing a buffer for binding %u.", position_binding));253RDD::BufferID vertex_buffer = vertex_array->buffers[position_binding];254uint64_t vertex_offset = vertex_array->offsets[position_binding];255256// Indices are optional.257IndexArray *index_array = index_array_owner.get_or_null(p_index_array);258RDD::BufferID index_buffer = RDD::BufferID();259IndexBufferFormat index_format = IndexBufferFormat::INDEX_BUFFER_FORMAT_UINT32;260uint32_t index_offset_bytes = 0;261uint32_t index_count = 0;262if (index_array) {263index_buffer = index_array->driver_id;264index_format = index_array->format;265index_offset_bytes = index_array->offset * (index_array->format == INDEX_BUFFER_FORMAT_UINT16 ? sizeof(uint16_t) : sizeof(uint32_t));266index_count = index_array->indices;267}268269AccelerationStructure acceleration_structure;270acceleration_structure.type = RDD::ACCELERATION_STRUCTURE_TYPE_BLAS;271272BitField<RDD::AccelerationStructureGeometryBits> geometry_bits = 0;273if (p_geometry_bits.has_flag(ACCELERATION_STRUCTURE_GEOMETRY_OPAQUE)) {274geometry_bits.set_flag(RDD::ACCELERATION_STRUCTURE_GEOMETRY_OPAQUE);275}276if (p_geometry_bits.has_flag(ACCELERATION_STRUCTURE_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION)) {277geometry_bits.set_flag(RDD::ACCELERATION_STRUCTURE_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION);278}279280acceleration_structure.driver_id = driver->blas_create(vertex_buffer, vertex_offset, vertex_format, vertex_array->vertex_count, p_position_attribute_location, index_buffer, index_format, index_offset_bytes, index_count, geometry_bits);281ERR_FAIL_COND_V_MSG(!acceleration_structure.driver_id, RID(), "Failed to create BLAS.");282acceleration_structure.vertex_array = p_vertex_array;283acceleration_structure.index_array = p_index_array;284285acceleration_structure.draw_tracker = RDG::resource_tracker_create();286acceleration_structure.draw_tracker->acceleration_structure_driver_id = acceleration_structure.driver_id;287// Assume we are going to build this acceleration structure288acceleration_structure.draw_tracker->usage = RDG::RESOURCE_USAGE_ACCELERATION_STRUCTURE_READ_WRITE;289290for (int i = 0; i < vertex_array->draw_trackers.size(); i++) {291acceleration_structure.draw_trackers.push_back(vertex_array->draw_trackers[i]);292}293_check_transfer_worker_vertex_array(vertex_array);294295if (index_array && index_array->draw_tracker) {296acceleration_structure.draw_trackers.push_back(index_array->draw_tracker);297}298_check_transfer_worker_index_array(index_array);299300RID id = acceleration_structure_owner.make_rid(acceleration_structure);301#ifdef DEV_ENABLED302set_resource_name(id, "RID:" + itos(id.get_id()));303#endif304return id;305}306307BitField<RDD::BufferUsageBits> RenderingDevice::_creation_to_usage_bits(BitField<RD::BufferCreationBits> p_creation_bits) {308BitField<RDD::BufferUsageBits> usage = 0;309310if (p_creation_bits.has_flag(BUFFER_CREATION_AS_STORAGE_BIT)) {311usage.set_flag(RDD::BUFFER_USAGE_STORAGE_BIT);312}313314if (p_creation_bits.has_flag(BUFFER_CREATION_DEVICE_ADDRESS_BIT)) {315#ifdef DEBUG_ENABLED316ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_BUFFER_DEVICE_ADDRESS), 0,317"The GPU doesn't support buffer address flag.");318#endif319usage.set_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);320}321322if (p_creation_bits.has_flag(BUFFER_CREATION_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT)) {323#ifdef DEBUG_ENABLED324ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), 0,325"The GPU doesn't support acceleration structure build input flag.");326#endif327usage.set_flag(RDD::BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT);328}329330return usage;331}332333RID RenderingDevice::tlas_instances_buffer_create(uint32_t p_instance_count, BitField<BufferCreationBits> p_creation_bits) {334ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), RID(), "The current rendering device has neither raytracing pipeline nor ray query support.");335ERR_FAIL_COND_V(p_instance_count == 0, RID());336337uint32_t instances_buffer_size_bytes = driver->tlas_instances_buffer_get_size_bytes(p_instance_count);338339InstancesBuffer instances_buffer;340instances_buffer.instance_count = p_instance_count;341instances_buffer.buffer.size = instances_buffer_size_bytes;342instances_buffer.buffer.usage = _creation_to_usage_bits(p_creation_bits) | RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT | RDD::BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT;343instances_buffer.buffer.driver_id = driver->buffer_create(instances_buffer.buffer.size, instances_buffer.buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);344ERR_FAIL_COND_V_MSG(!instances_buffer.buffer.driver_id, RID(), "Failed to create instances buffer.");345346_THREAD_SAFE_LOCK_347buffer_memory += instances_buffer.buffer.size;348_THREAD_SAFE_UNLOCK_349350RID id = instances_buffer_owner.make_rid(instances_buffer);351#ifdef DEV_ENABLED352set_resource_name(id, "RID:" + itos(id.get_id()));353#endif354return id;355}356357void RenderingDevice::tlas_instances_buffer_fill(RID p_instances_buffer, const Vector<RID> &p_blases, VectorView<Transform3D> p_transforms) {358ERR_FAIL_COND_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), "The current rendering device has neither raytracing pipeline nor ray query support.");359360InstancesBuffer *instances_buffer = instances_buffer_owner.get_or_null(p_instances_buffer);361ERR_FAIL_NULL_MSG(instances_buffer, "Instances buffer input is not valid.");362363uint32_t blases_count = p_blases.size();364ERR_FAIL_COND_MSG(blases_count != instances_buffer->instance_count, "The number of blases is not equal to the instance count of the instances buffer.");365ERR_FAIL_COND_MSG(blases_count != p_transforms.size(), "Blases and transforms vectors must have the same size.");366367thread_local LocalVector<RDD::AccelerationStructureID> blases;368blases.resize(blases_count);369370for (uint32_t i = 0; i < blases_count; i++) {371const AccelerationStructure *blas = acceleration_structure_owner.get_or_null(p_blases[i]);372ERR_FAIL_NULL_MSG(blas, "BLAS input is not valid.");373ERR_FAIL_COND_MSG(blas->type != RDD::ACCELERATION_STRUCTURE_TYPE_BLAS, "Acceleration structure input is not a BLAS.");374blases[i] = blas->driver_id;375}376377instances_buffer->blases = p_blases;378379driver->tlas_instances_buffer_fill(instances_buffer->buffer.driver_id, blases, p_transforms);380}381382RID RenderingDevice::tlas_create(RID p_instances_buffer) {383ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), RID(), "The current rendering device has neither raytracing pipeline nor ray query support.");384385const InstancesBuffer *instances_buffer = instances_buffer_owner.get_or_null(p_instances_buffer);386ERR_FAIL_NULL_V_MSG(instances_buffer, RID(), "Instances buffer input is not valid.");387388AccelerationStructure acceleration_structure;389acceleration_structure.type = RDD::ACCELERATION_STRUCTURE_TYPE_TLAS;390acceleration_structure.driver_id = driver->tlas_create(instances_buffer->buffer.driver_id);391ERR_FAIL_COND_V_MSG(!acceleration_structure.driver_id, RID(), "Failed to create TLAS.");392acceleration_structure.instances_buffer = p_instances_buffer;393394acceleration_structure.draw_tracker = RDG::resource_tracker_create();395acceleration_structure.draw_tracker->acceleration_structure_driver_id = acceleration_structure.driver_id;396// Assume we are going to build this acceleration structure397acceleration_structure.draw_tracker->usage = RDG::RESOURCE_USAGE_ACCELERATION_STRUCTURE_READ_WRITE;398399for (Vector<RID>::ConstIterator itr = instances_buffer->blases.begin(); itr != instances_buffer->blases.end(); ++itr) {400const AccelerationStructure *blas = acceleration_structure_owner.get_or_null(*itr);401ERR_FAIL_NULL_V_MSG(blas, RID(), "BLAS input is not valid.");402if (blas->draw_tracker) {403acceleration_structure.draw_trackers.push_back(blas->draw_tracker);404}405}406407RID id = acceleration_structure_owner.make_rid(acceleration_structure);408#ifdef DEV_ENABLED409set_resource_name(id, "RID:" + itos(id.get_id()));410#endif411return id;412}413414Error RenderingDevice::acceleration_structure_build(RID p_acceleration_structure) {415ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);416417ERR_FAIL_COND_V_MSG(draw_list.active, ERR_INVALID_PARAMETER,418"Building acceleration structures is forbidden during creation of a draw list.");419ERR_FAIL_COND_V_MSG(compute_list.active, ERR_INVALID_PARAMETER,420"Building acceleration structures is forbidden during creation of a compute list.");421ERR_FAIL_COND_V_MSG(raytracing_list.active, ERR_INVALID_PARAMETER,422"Building acceleration structures is forbidden during creation of a raytracing list.");423424AccelerationStructure *accel = acceleration_structure_owner.get_or_null(p_acceleration_structure);425ERR_FAIL_NULL_V_MSG(accel, ERR_INVALID_PARAMETER, "Acceleration structure argument is not valid.");426427uint64_t scratch_size = driver->acceleration_structure_get_scratch_size_bytes(accel->driver_id);428429const Buffer *scratch_buffer = storage_buffer_owner.get_or_null(accel->scratch_buffer);430if (scratch_buffer && driver->buffer_get_allocation_size(scratch_buffer->driver_id) < scratch_size) {431scratch_buffer = nullptr;432free_rid(accel->scratch_buffer);433accel->scratch_buffer = RID();434}435if (accel->scratch_buffer == RID()) {436accel->scratch_buffer = storage_buffer_create(scratch_size, { nullptr, 0 }, RDD::BUFFER_USAGE_STORAGE_BIT | RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);437ERR_FAIL_COND_V(accel->scratch_buffer == RID(), ERR_CANT_CREATE);438}439440if (scratch_buffer == nullptr) {441scratch_buffer = storage_buffer_owner.get_or_null(accel->scratch_buffer);442ERR_FAIL_NULL_V_MSG(scratch_buffer, ERR_CANT_CREATE, "Scratch buffer is not valid.");443}444445draw_graph.add_acceleration_structure_build(accel->driver_id, scratch_buffer->driver_id, accel->draw_tracker, accel->draw_trackers);446447return OK;448}449450/***************************/451/**** BUFFER MANAGEMENT ****/452/***************************/453454RenderingDevice::Buffer *RenderingDevice::_get_buffer_from_owner(RID p_buffer) {455Buffer *buffer = nullptr;456if (vertex_buffer_owner.owns(p_buffer)) {457buffer = vertex_buffer_owner.get_or_null(p_buffer);458} else if (index_buffer_owner.owns(p_buffer)) {459buffer = index_buffer_owner.get_or_null(p_buffer);460} else if (uniform_buffer_owner.owns(p_buffer)) {461buffer = uniform_buffer_owner.get_or_null(p_buffer);462} else if (texture_buffer_owner.owns(p_buffer)) {463DEV_ASSERT(false && "FIXME: Broken.");464//buffer = texture_buffer_owner.get_or_null(p_buffer)->buffer;465} else if (storage_buffer_owner.owns(p_buffer)) {466buffer = storage_buffer_owner.get_or_null(p_buffer);467} else if (instances_buffer_owner.owns(p_buffer)) {468buffer = &instances_buffer_owner.get_or_null(p_buffer)->buffer;469}470return buffer;471}472473Error RenderingDevice::_buffer_initialize(Buffer *p_buffer, Span<uint8_t> p_data, uint32_t p_required_align) {474uint32_t transfer_worker_offset;475TransferWorker *transfer_worker = _acquire_transfer_worker(p_data.size(), p_required_align, transfer_worker_offset);476p_buffer->transfer_worker_index = transfer_worker->index;477478{479MutexLock lock(transfer_worker->operations_mutex);480p_buffer->transfer_worker_operation = ++transfer_worker->operations_counter;481}482483// Copy to the worker's staging buffer.484uint8_t *data_ptr = driver->buffer_map(transfer_worker->staging_buffer);485ERR_FAIL_NULL_V(data_ptr, ERR_CANT_CREATE);486487memcpy(data_ptr + transfer_worker_offset, p_data.ptr(), p_data.size());488driver->buffer_unmap(transfer_worker->staging_buffer);489490// Copy from the staging buffer to the real buffer.491RDD::BufferCopyRegion region;492region.src_offset = transfer_worker_offset;493region.dst_offset = 0;494region.size = p_data.size();495driver->command_copy_buffer(transfer_worker->command_buffer, transfer_worker->staging_buffer, p_buffer->driver_id, region);496497_release_transfer_worker(transfer_worker);498499return OK;500}501502Error RenderingDevice::_insert_staging_block(StagingBuffers &p_staging_buffers) {503StagingBufferBlock block;504505block.driver_id = driver->buffer_create(p_staging_buffers.block_size, p_staging_buffers.usage_bits, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);506ERR_FAIL_COND_V(!block.driver_id, ERR_CANT_CREATE);507508block.frame_used = 0;509block.fill_amount = 0;510block.data_ptr = driver->buffer_map(block.driver_id);511512if (block.data_ptr == nullptr) {513driver->buffer_free(block.driver_id);514return ERR_CANT_CREATE;515}516517p_staging_buffers.blocks.insert(p_staging_buffers.current, block);518return OK;519}520521Error RenderingDevice::_staging_buffer_allocate(StagingBuffers &p_staging_buffers, uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, StagingRequiredAction &r_required_action, bool p_can_segment) {522// Determine a block to use.523524r_alloc_size = p_amount;525r_required_action = STAGING_REQUIRED_ACTION_NONE;526527while (true) {528r_alloc_offset = 0;529530// See if we can use current block.531if (p_staging_buffers.blocks[p_staging_buffers.current].frame_used == frames_drawn) {532// We used this block this frame, let's see if there is still room.533534uint32_t write_from = p_staging_buffers.blocks[p_staging_buffers.current].fill_amount;535536{537uint32_t align_remainder = write_from % p_required_align;538if (align_remainder != 0) {539write_from += p_required_align - align_remainder;540}541}542543int32_t available_bytes = int32_t(p_staging_buffers.block_size) - int32_t(write_from);544545if ((int32_t)p_amount < available_bytes) {546// All is good, we should be ok, all will fit.547r_alloc_offset = write_from;548} else if (p_can_segment && available_bytes >= (int32_t)p_required_align) {549// Ok all won't fit but at least we can fit a chunkie.550// All is good, update what needs to be written to.551r_alloc_offset = write_from;552r_alloc_size = available_bytes - (available_bytes % p_required_align);553554} else {555// Can't fit it into this buffer.556// Will need to try next buffer.557558p_staging_buffers.current = (p_staging_buffers.current + 1) % p_staging_buffers.blocks.size();559560// Before doing anything, though, let's check that we didn't manage to fill all blocks.561// Possible in a single frame.562if (p_staging_buffers.blocks[p_staging_buffers.current].frame_used == frames_drawn) {563// Guess we did.. ok, let's see if we can insert a new block.564if ((uint64_t)p_staging_buffers.blocks.size() * p_staging_buffers.block_size < p_staging_buffers.max_size) {565// We can, so we are safe.566Error err = _insert_staging_block(p_staging_buffers);567if (err) {568return err;569}570// Claim for this frame.571p_staging_buffers.blocks.write[p_staging_buffers.current].frame_used = frames_drawn;572} else {573// Ok, worst case scenario, all the staging buffers belong to this frame574// and this frame is not even done.575// If this is the main thread, it means the user is likely loading a lot of resources at once,.576// Otherwise, the thread should just be blocked until the next frame (currently unimplemented).577r_required_action = STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL;578}579580} else {581// Not from current frame, so continue and try again.582continue;583}584}585586} else if (p_staging_buffers.blocks[p_staging_buffers.current].frame_used <= frames_drawn - frames.size()) {587// This is an old block, which was already processed, let's reuse.588p_staging_buffers.blocks.write[p_staging_buffers.current].frame_used = frames_drawn;589p_staging_buffers.blocks.write[p_staging_buffers.current].fill_amount = 0;590} else {591// This block may still be in use, let's not touch it unless we have to, so.. can we create a new one?592if ((uint64_t)p_staging_buffers.blocks.size() * p_staging_buffers.block_size < p_staging_buffers.max_size) {593// We are still allowed to create a new block, so let's do that and insert it for current pos.594Error err = _insert_staging_block(p_staging_buffers);595if (err) {596return err;597}598// Claim for this frame.599p_staging_buffers.blocks.write[p_staging_buffers.current].frame_used = frames_drawn;600} else {601// Oops, we are out of room and we can't create more.602// Let's flush older frames.603// The logic here is that if a game is loading a lot of data from the main thread, it will need to be stalled anyway.604// If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though).605r_required_action = STAGING_REQUIRED_ACTION_STALL_PREVIOUS;606}607}608609// All was good, break.610break;611}612613p_staging_buffers.used = true;614615return OK;616}617618void RenderingDevice::_staging_buffer_execute_required_action(StagingBuffers &p_staging_buffers, StagingRequiredAction p_required_action) {619switch (p_required_action) {620case STAGING_REQUIRED_ACTION_NONE: {621// Do nothing.622} break;623case STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL: {624_flush_and_stall_for_all_frames();625626// Clear the whole staging buffer.627for (int i = 0; i < p_staging_buffers.blocks.size(); i++) {628p_staging_buffers.blocks.write[i].frame_used = 0;629p_staging_buffers.blocks.write[i].fill_amount = 0;630}631632// Claim for current frame.633p_staging_buffers.blocks.write[p_staging_buffers.current].frame_used = frames_drawn;634} break;635case STAGING_REQUIRED_ACTION_STALL_PREVIOUS: {636_stall_for_previous_frames();637638for (int i = 0; i < p_staging_buffers.blocks.size(); i++) {639// Clear all blocks but the ones from this frame.640int block_idx = (i + p_staging_buffers.current) % p_staging_buffers.blocks.size();641if (p_staging_buffers.blocks[block_idx].frame_used == frames_drawn) {642break; // Ok, we reached something from this frame, abort.643}644645p_staging_buffers.blocks.write[block_idx].frame_used = 0;646p_staging_buffers.blocks.write[block_idx].fill_amount = 0;647}648649// Claim for current frame.650p_staging_buffers.blocks.write[p_staging_buffers.current].frame_used = frames_drawn;651} break;652default: {653DEV_ASSERT(false && "Unknown required action.");654} break;655}656}657658Error RenderingDevice::buffer_copy(RID p_src_buffer, RID p_dst_buffer, uint32_t p_src_offset, uint32_t p_dst_offset, uint32_t p_size) {659ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);660661ERR_FAIL_COND_V_MSG(draw_list.active, ERR_INVALID_PARAMETER,662"Copying buffers is forbidden during creation of a draw list.");663ERR_FAIL_COND_V_MSG(compute_list.active, ERR_INVALID_PARAMETER,664"Copying buffers is forbidden during creation of a compute list.");665ERR_FAIL_COND_V_MSG(raytracing_list.active, ERR_INVALID_PARAMETER,666"Copying buffers is forbidden during creation of a raytracing list.");667668Buffer *src_buffer = _get_buffer_from_owner(p_src_buffer);669if (!src_buffer) {670ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Source buffer argument is not a valid buffer of any type.");671}672673Buffer *dst_buffer = _get_buffer_from_owner(p_dst_buffer);674if (!dst_buffer) {675ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Destination buffer argument is not a valid buffer of any type.");676}677678// Validate the copy's dimensions for both buffers.679ERR_FAIL_COND_V_MSG((p_size + p_src_offset) > src_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the source buffer.");680ERR_FAIL_COND_V_MSG((p_size + p_dst_offset) > dst_buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the destination buffer.");681682_check_transfer_worker_buffer(src_buffer);683_check_transfer_worker_buffer(dst_buffer);684685// Perform the copy.686RDD::BufferCopyRegion region;687region.src_offset = p_src_offset;688region.dst_offset = p_dst_offset;689region.size = p_size;690691if (_buffer_make_mutable(dst_buffer, p_dst_buffer)) {692// The destination buffer must be mutable to be used as a copy destination.693draw_graph.add_synchronization();694}695696draw_graph.add_buffer_copy(src_buffer->driver_id, src_buffer->draw_tracker, dst_buffer->driver_id, dst_buffer->draw_tracker, region);697698return OK;699}700701Error RenderingDevice::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, bool p_skip_check) {702ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);703704copy_bytes_count += p_size;705706ERR_FAIL_COND_V_MSG(draw_list.active && !p_skip_check, ERR_INVALID_PARAMETER,707"Updating buffers is forbidden during creation of a draw list.");708ERR_FAIL_COND_V_MSG(compute_list.active && !p_skip_check, ERR_INVALID_PARAMETER,709"Updating buffers is forbidden during creation of a compute list.");710ERR_FAIL_COND_V_MSG(raytracing_list.active && !p_skip_check, ERR_INVALID_PARAMETER,711"Updating buffers is forbidden during creation of a raytracing list.");712713Buffer *buffer = _get_buffer_from_owner(p_buffer);714ERR_FAIL_NULL_V_MSG(buffer, ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");715ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER, "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");716717if (buffer->usage.has_flag(RDD::BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT)) {718uint8_t *dst_data = driver->buffer_persistent_map_advance(buffer->driver_id, frames_drawn);719720memcpy(dst_data + p_offset, p_data, p_size);721direct_copy_count++;722buffer_flush(p_buffer);723return OK;724}725726_check_transfer_worker_buffer(buffer);727728// Submitting may get chunked for various reasons, so convert this to a task.729size_t to_submit = p_size;730size_t submit_from = 0;731732thread_local LocalVector<RDG::RecordedBufferCopy> command_buffer_copies_vector;733command_buffer_copies_vector.clear();734735const uint8_t *src_data = reinterpret_cast<const uint8_t *>(p_data);736const uint32_t required_align = 32;737while (to_submit > 0) {738uint32_t block_write_offset;739uint32_t block_write_amount;740StagingRequiredAction required_action;741742Error err = _staging_buffer_allocate(upload_staging_buffers, MIN(to_submit, upload_staging_buffers.block_size), required_align, block_write_offset, block_write_amount, required_action);743if (err) {744return err;745}746747if (!command_buffer_copies_vector.is_empty() && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL) {748if (_buffer_make_mutable(buffer, p_buffer)) {749// The buffer must be mutable to be used as a copy destination.750draw_graph.add_synchronization();751}752753draw_graph.add_buffer_update(buffer->driver_id, buffer->draw_tracker, command_buffer_copies_vector);754command_buffer_copies_vector.clear();755}756757_staging_buffer_execute_required_action(upload_staging_buffers, required_action);758759// Copy to staging buffer.760memcpy(upload_staging_buffers.blocks[upload_staging_buffers.current].data_ptr + block_write_offset, src_data + submit_from, block_write_amount);761762// Insert a command to copy this.763RDD::BufferCopyRegion region;764region.src_offset = block_write_offset;765region.dst_offset = submit_from + p_offset;766region.size = block_write_amount;767768RDG::RecordedBufferCopy buffer_copy;769buffer_copy.source = upload_staging_buffers.blocks[upload_staging_buffers.current].driver_id;770buffer_copy.region = region;771command_buffer_copies_vector.push_back(buffer_copy);772773upload_staging_buffers.blocks.write[upload_staging_buffers.current].fill_amount = block_write_offset + block_write_amount;774775to_submit -= block_write_amount;776submit_from += block_write_amount;777}778779if (!command_buffer_copies_vector.is_empty()) {780if (_buffer_make_mutable(buffer, p_buffer)) {781// The buffer must be mutable to be used as a copy destination.782draw_graph.add_synchronization();783}784785draw_graph.add_buffer_update(buffer->driver_id, buffer->draw_tracker, command_buffer_copies_vector);786}787788gpu_copy_count++;789790return OK;791}792793Error RenderingDevice::driver_callback_add(RDD::DriverCallback p_callback, void *p_userdata, VectorView<CallbackResource> p_resources) {794ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);795796ERR_FAIL_COND_V_MSG(draw_list.active, ERR_INVALID_PARAMETER,797"Driver callback is forbidden during creation of a draw list.");798ERR_FAIL_COND_V_MSG(compute_list.active, ERR_INVALID_PARAMETER,799"Driver callback is forbidden during creation of a compute list.");800ERR_FAIL_COND_V_MSG(raytracing_list.active, ERR_INVALID_PARAMETER,801"Driver callback is forbidden during creation of a raytracing list.");802803thread_local LocalVector<RDG::ResourceTracker *> trackers;804thread_local LocalVector<RDG::ResourceUsage> usages;805806uint32_t resource_count = p_resources.size();807trackers.resize(resource_count);808usages.resize(resource_count);809810if (resource_count > 0) {811for (uint32_t i = 0; i < p_resources.size(); i++) {812const CallbackResource &cr = p_resources[i];813switch (cr.type) {814case CALLBACK_RESOURCE_TYPE_BUFFER: {815Buffer *buffer = _get_buffer_from_owner(cr.rid);816if (!buffer) {817ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("Argument %d is not a valid buffer of any type.", i));818}819if (_buffer_make_mutable(buffer, cr.rid)) {820draw_graph.add_synchronization();821}822trackers[i] = buffer->draw_tracker;823usages[i] = (RDG::ResourceUsage)cr.usage;824} break;825case CALLBACK_RESOURCE_TYPE_TEXTURE: {826Texture *texture = texture_owner.get_or_null(cr.rid);827if (!texture) {828ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("Argument %d is not a valid texture.", i));829}830if (_texture_make_mutable(texture, cr.rid)) {831draw_graph.add_synchronization();832}833trackers[i] = texture->draw_tracker;834usages[i] = (RDG::ResourceUsage)cr.usage;835} break;836default: {837CRASH_NOW_MSG("Invalid callback resource type.");838} break;839}840}841}842843draw_graph.add_driver_callback(p_callback, p_userdata, trackers, usages);844845return OK;846}847848String RenderingDevice::get_perf_report() const {849String perf_report_text;850perf_report_text += " gpu:" + String::num_int64(gpu_copy_count);851perf_report_text += " direct:" + String::num_int64(direct_copy_count);852perf_report_text += " bytes:" + String::num_int64(copy_bytes_count);853854perf_report_text += " lazily alloc:" + String::num_int64(driver->get_lazily_memory_used());855return perf_report_text;856}857858void RenderingDevice::update_perf_report() {859prev_gpu_copy_count = gpu_copy_count;860prev_copy_bytes_count = copy_bytes_count;861gpu_copy_count = 0;862direct_copy_count = 0;863copy_bytes_count = 0;864}865866Error RenderingDevice::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size) {867ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);868869ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,870"Size must be a multiple of four.");871ERR_FAIL_COND_V_MSG(draw_list.active, ERR_INVALID_PARAMETER,872"Updating buffers in is forbidden during creation of a draw list.");873ERR_FAIL_COND_V_MSG(compute_list.active, ERR_INVALID_PARAMETER,874"Updating buffers is forbidden during creation of a compute list.");875ERR_FAIL_COND_V_MSG(raytracing_list.active, ERR_INVALID_PARAMETER,876"Updating buffers is forbidden during creation of a raytracing list.");877878Buffer *buffer = _get_buffer_from_owner(p_buffer);879if (!buffer) {880ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");881}882883ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,884"Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");885886_check_transfer_worker_buffer(buffer);887888if (_buffer_make_mutable(buffer, p_buffer)) {889// The destination buffer must be mutable to be used as a clear destination.890draw_graph.add_synchronization();891}892893draw_graph.add_buffer_clear(buffer->driver_id, buffer->draw_tracker, p_offset, p_size);894895return OK;896}897898Vector<uint8_t> RenderingDevice::buffer_get_data(RID p_buffer, uint32_t p_offset, uint32_t p_size) {899ERR_RENDER_THREAD_GUARD_V(Vector<uint8_t>());900901Buffer *buffer = _get_buffer_from_owner(p_buffer);902if (!buffer) {903ERR_FAIL_V_MSG(Vector<uint8_t>(), "Buffer is either invalid or this type of buffer can't be retrieved.");904}905906// Size of buffer to retrieve.907if (!p_size) {908p_size = buffer->size;909} else {910ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, Vector<uint8_t>(),911"Size is larger than the buffer.");912}913914_check_transfer_worker_buffer(buffer);915916RDD::BufferID tmp_buffer = driver->buffer_create(buffer->size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);917ERR_FAIL_COND_V(!tmp_buffer, Vector<uint8_t>());918919RDD::BufferCopyRegion region;920region.src_offset = p_offset;921region.size = p_size;922923draw_graph.add_buffer_get_data(buffer->driver_id, buffer->draw_tracker, tmp_buffer, region);924925// Flush everything so memory can be safely mapped.926_flush_and_stall_for_all_frames();927928uint8_t *buffer_mem = driver->buffer_map(tmp_buffer);929ERR_FAIL_NULL_V(buffer_mem, Vector<uint8_t>());930931Vector<uint8_t> buffer_data;932{933buffer_data.resize(p_size);934uint8_t *w = buffer_data.ptrw();935memcpy(w, buffer_mem, p_size);936}937938driver->buffer_unmap(tmp_buffer);939940driver->buffer_free(tmp_buffer);941942return buffer_data;943}944945Error RenderingDevice::buffer_get_data_async(RID p_buffer, const Callable &p_callback, uint32_t p_offset, uint32_t p_size) {946ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);947948Buffer *buffer = _get_buffer_from_owner(p_buffer);949if (buffer == nullptr) {950ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer is either invalid or this type of buffer can't be retrieved.");951}952953if (p_size == 0) {954p_size = buffer->size;955}956957ERR_FAIL_COND_V_MSG(p_size + p_offset > buffer->size, ERR_INVALID_PARAMETER, "Size is larger than the buffer.");958ERR_FAIL_COND_V_MSG(!p_callback.is_valid(), ERR_INVALID_PARAMETER, "Callback must be valid.");959960_check_transfer_worker_buffer(buffer);961962BufferGetDataRequest get_data_request;963get_data_request.callback = p_callback;964get_data_request.frame_local_index = frames[frame].download_buffer_copy_regions.size();965get_data_request.size = p_size;966967const uint32_t required_align = 32;968uint32_t block_write_offset;969uint32_t block_write_amount;970StagingRequiredAction required_action;971uint32_t to_submit = p_size;972uint32_t submit_from = 0;973while (to_submit > 0) {974Error err = _staging_buffer_allocate(download_staging_buffers, MIN(to_submit, download_staging_buffers.block_size), required_align, block_write_offset, block_write_amount, required_action);975if (err) {976return err;977}978979const bool flush_frames = (get_data_request.frame_local_count > 0) && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL;980if (flush_frames) {981if (_buffer_make_mutable(buffer, p_buffer)) {982// The buffer must be mutable to be used as a copy source.983draw_graph.add_synchronization();984}985986for (uint32_t i = 0; i < get_data_request.frame_local_count; i++) {987uint32_t local_index = get_data_request.frame_local_index + i;988draw_graph.add_buffer_get_data(buffer->driver_id, buffer->draw_tracker, frames[frame].download_buffer_staging_buffers[local_index], frames[frame].download_buffer_copy_regions[local_index]);989}990}991992_staging_buffer_execute_required_action(download_staging_buffers, required_action);993994if (flush_frames) {995get_data_request.frame_local_count = 0;996get_data_request.frame_local_index = frames[frame].download_buffer_copy_regions.size();997}998999RDD::BufferCopyRegion region;1000region.src_offset = submit_from + p_offset;1001region.dst_offset = block_write_offset;1002region.size = block_write_amount;10031004frames[frame].download_buffer_staging_buffers.push_back(download_staging_buffers.blocks[download_staging_buffers.current].driver_id);1005frames[frame].download_buffer_copy_regions.push_back(region);1006get_data_request.frame_local_count++;10071008download_staging_buffers.blocks.write[download_staging_buffers.current].fill_amount = block_write_offset + block_write_amount;10091010to_submit -= block_write_amount;1011submit_from += block_write_amount;1012}10131014if (get_data_request.frame_local_count > 0) {1015if (_buffer_make_mutable(buffer, p_buffer)) {1016// The buffer must be mutable to be used as a copy source.1017draw_graph.add_synchronization();1018}10191020for (uint32_t i = 0; i < get_data_request.frame_local_count; i++) {1021uint32_t local_index = get_data_request.frame_local_index + i;1022draw_graph.add_buffer_get_data(buffer->driver_id, buffer->draw_tracker, frames[frame].download_buffer_staging_buffers[local_index], frames[frame].download_buffer_copy_regions[local_index]);1023}10241025frames[frame].download_buffer_get_data_requests.push_back(get_data_request);1026}10271028return OK;1029}10301031uint64_t RenderingDevice::buffer_get_device_address(RID p_buffer) {1032ERR_RENDER_THREAD_GUARD_V(0);10331034Buffer *buffer = _get_buffer_from_owner(p_buffer);1035ERR_FAIL_NULL_V_MSG(buffer, 0, "Buffer argument is not a valid buffer of any type.");1036ERR_FAIL_COND_V_MSG(!buffer->usage.has_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT), 0, "Buffer was not created with device address flag.");10371038return driver->buffer_get_device_address(buffer->driver_id);1039}10401041uint8_t *RenderingDevice::buffer_persistent_map_advance(RID p_buffer) {1042ERR_RENDER_THREAD_GUARD_V(0);10431044Buffer *buffer = _get_buffer_from_owner(p_buffer);1045ERR_FAIL_NULL_V_MSG(buffer, nullptr, "Buffer argument is not a valid buffer of any type.");1046direct_copy_count++;1047return driver->buffer_persistent_map_advance(buffer->driver_id, frames_drawn);1048}10491050void RenderingDevice::buffer_flush(RID p_buffer) {1051ERR_RENDER_THREAD_GUARD();10521053Buffer *buffer = _get_buffer_from_owner(p_buffer);1054ERR_FAIL_NULL_MSG(buffer, "Buffer argument is not a valid buffer of any type.");1055driver->buffer_flush(buffer->driver_id);1056}10571058RID RenderingDevice::storage_buffer_create(uint32_t p_size_bytes, Span<uint8_t> p_data, BitField<StorageBufferUsage> p_usage, BitField<BufferCreationBits> p_creation_bits) {1059ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());10601061Buffer buffer;1062buffer.size = p_size_bytes;1063buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_STORAGE_BIT);1064if (p_creation_bits.has_flag(BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT)) {1065buffer.usage.set_flag(RDD::BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT);10661067// This is a precaution: Persistent buffers are meant for frequent CPU -> GPU transfers.1068// Writing to this buffer from GPU might cause sync issues if both CPU & GPU try to write at the1069// same time. It's probably fine (since CPU always advances the pointer before writing) but let's1070// stick to the known/intended use cases and scream if we deviate from it.1071buffer.usage.clear_flag(RDD::BUFFER_USAGE_TRANSFER_TO_BIT);1072}1073if (p_usage.has_flag(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT)) {1074buffer.usage.set_flag(RDD::BUFFER_USAGE_INDIRECT_BIT);1075}1076if (p_creation_bits.has_flag(BUFFER_CREATION_DEVICE_ADDRESS_BIT)) {1077#ifdef DEBUG_ENABLED1078ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_BUFFER_DEVICE_ADDRESS), RID(),1079"The GPU doesn't support buffer address flag.");1080#endif10811082buffer.usage.set_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);1083}1084if (p_creation_bits.has_flag(BUFFER_CREATION_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT)) {1085#ifdef DEBUG_ENABLED1086ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE) && !has_feature(SUPPORTS_RAY_QUERY), RID(),1087"The GPU doesn't support acceleration structure build input flag.");1088#endif1089buffer.usage.set_flag(RDD::BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT);1090}10911092buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);1093ERR_FAIL_COND_V(!buffer.driver_id, RID());10941095// Storage buffers are assumed to be mutable.1096buffer.draw_tracker = RDG::resource_tracker_create();1097buffer.draw_tracker->buffer_driver_id = buffer.driver_id;10981099if (p_data.size()) {1100_buffer_initialize(&buffer, p_data);1101}11021103_THREAD_SAFE_LOCK_1104buffer_memory += buffer.size;1105_THREAD_SAFE_UNLOCK_11061107RID id = storage_buffer_owner.make_rid(buffer);1108#ifdef DEV_ENABLED1109set_resource_name(id, "RID:" + itos(id.get_id()));1110#endif1111return id;1112}11131114RID RenderingDevice::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, Span<uint8_t> p_data) {1115uint32_t element_size = get_format_vertex_size(p_format);1116ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");1117uint64_t size_bytes = uint64_t(element_size) * p_size_elements;11181119ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());11201121Buffer texture_buffer;1122texture_buffer.size = size_bytes;1123BitField<RDD::BufferUsageBits> usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_TEXEL_BIT);1124texture_buffer.driver_id = driver->buffer_create(size_bytes, usage, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);1125ERR_FAIL_COND_V(!texture_buffer.driver_id, RID());11261127// Texture buffers are assumed to be immutable unless they don't have initial data.1128if (p_data.is_empty()) {1129texture_buffer.draw_tracker = RDG::resource_tracker_create();1130texture_buffer.draw_tracker->buffer_driver_id = texture_buffer.driver_id;1131}11321133bool ok = driver->buffer_set_texel_format(texture_buffer.driver_id, p_format);1134if (!ok) {1135driver->buffer_free(texture_buffer.driver_id);1136ERR_FAIL_V(RID());1137}11381139if (p_data.size()) {1140_buffer_initialize(&texture_buffer, p_data);1141}11421143_THREAD_SAFE_LOCK_1144buffer_memory += size_bytes;1145_THREAD_SAFE_UNLOCK_11461147RID id = texture_buffer_owner.make_rid(texture_buffer);1148#ifdef DEV_ENABLED1149set_resource_name(id, "RID:" + itos(id.get_id()));1150#endif1151return id;1152}11531154/*****************/1155/**** TEXTURE ****/1156/*****************/11571158RID RenderingDevice::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) {1159// Some adjustments will happen.1160TextureFormat format = p_format;11611162if (format.shareable_formats.size()) {1163ERR_FAIL_COND_V_MSG(!format.shareable_formats.has(format.format), RID(),1164"If supplied a list of shareable formats, the current format must be present in the list");1165ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && !format.shareable_formats.has(p_view.format_override), RID(),1166"If supplied a list of shareable formats, the current view format override must be present in the list");1167}11681169ERR_FAIL_INDEX_V(format.texture_type, RDD::TEXTURE_TYPE_MAX, RID());11701171ERR_FAIL_COND_V_MSG(format.width < 1, RID(), "Width must be equal or greater than 1 for all textures");11721173if (format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY) {1174ERR_FAIL_COND_V_MSG(format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures");1175}11761177if (format.texture_type == TEXTURE_TYPE_3D) {1178ERR_FAIL_COND_V_MSG(format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures");1179}11801181ERR_FAIL_COND_V(format.mipmaps < 1, RID());11821183if (format.texture_type == TEXTURE_TYPE_1D_ARRAY || format.texture_type == TEXTURE_TYPE_2D_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) {1184ERR_FAIL_COND_V_MSG(format.array_layers < 1, RID(),1185"Number of layers must be equal or greater than 1 for arrays and cubemaps.");1186ERR_FAIL_COND_V_MSG((format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE) && (format.array_layers % 6) != 0, RID(),1187"Cubemap and cubemap array textures must provide a layer number that is multiple of 6");1188ERR_FAIL_COND_V_MSG(((format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || format.texture_type == TEXTURE_TYPE_CUBE)) && (format.width != format.height), RID(),1189"Cubemap and cubemap array textures must have equal width and height.");1190ERR_FAIL_COND_V_MSG(format.array_layers > driver->limit_get(LIMIT_MAX_TEXTURE_ARRAY_LAYERS), RID(), "Number of layers exceeds device maximum.");1191} else {1192format.array_layers = 1;1193}11941195ERR_FAIL_INDEX_V(format.samples, TEXTURE_SAMPLES_MAX, RID());11961197ERR_FAIL_COND_V_MSG(format.usage_bits == 0, RID(), "No usage bits specified (at least one is needed)");11981199format.height = format.texture_type != TEXTURE_TYPE_1D && format.texture_type != TEXTURE_TYPE_1D_ARRAY ? format.height : 1;1200format.depth = format.texture_type == TEXTURE_TYPE_3D ? format.depth : 1;12011202uint64_t size_max = 0;1203switch (format.texture_type) {1204case TEXTURE_TYPE_1D:1205case TEXTURE_TYPE_1D_ARRAY:1206size_max = driver->limit_get(LIMIT_MAX_TEXTURE_SIZE_1D);1207break;1208case TEXTURE_TYPE_2D:1209case TEXTURE_TYPE_2D_ARRAY:1210size_max = driver->limit_get(LIMIT_MAX_TEXTURE_SIZE_2D);1211break;1212case TEXTURE_TYPE_CUBE:1213case TEXTURE_TYPE_CUBE_ARRAY:1214size_max = driver->limit_get(LIMIT_MAX_TEXTURE_SIZE_CUBE);1215break;1216case TEXTURE_TYPE_3D:1217size_max = driver->limit_get(LIMIT_MAX_TEXTURE_SIZE_3D);1218break;1219case TEXTURE_TYPE_MAX:1220break;1221}1222ERR_FAIL_COND_V_MSG(format.width > size_max || format.height > size_max || format.depth > size_max, RID(), "Texture dimensions exceed device maximum.");12231224uint32_t required_mipmaps = get_image_required_mipmaps(format.width, format.height, format.depth);12251226ERR_FAIL_COND_V_MSG(required_mipmaps < format.mipmaps, RID(),1227"Too many mipmaps requested for texture format and dimensions (" + itos(format.mipmaps) + "), maximum allowed: (" + itos(required_mipmaps) + ").");12281229Vector<Vector<uint8_t>> data = p_data;1230bool immediate_flush = false;12311232// If this is a VRS texture, we make sure that it is created with valid initial data. This prevents a crash on Qualcomm Snapdragon XR2 Gen 11233// (used in Quest 2, Quest Pro, Pico 4, HTC Vive XR Elite and others) where the driver will read the texture before we've had time to finish updating it.1234if (data.is_empty() && (p_format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {1235immediate_flush = true;1236for (uint32_t i = 0; i < format.array_layers; i++) {1237uint32_t required_size = get_image_format_required_size(format.format, format.width, format.height, format.depth, format.mipmaps);1238Vector<uint8_t> layer;1239layer.resize(required_size);1240layer.fill(255);1241data.push_back(layer);1242}1243}12441245uint32_t forced_usage_bits = _texture_vrs_method_to_usage_bits();1246if (data.size()) {1247ERR_FAIL_COND_V_MSG(data.size() != (int)format.array_layers, RID(),1248"Default supplied data for image format is of invalid length (" + itos(data.size()) + "), should be (" + itos(format.array_layers) + ").");12491250for (uint32_t i = 0; i < format.array_layers; i++) {1251uint32_t required_size = get_image_format_required_size(format.format, format.width, format.height, format.depth, format.mipmaps);1252ERR_FAIL_COND_V_MSG((uint32_t)data[i].size() != required_size, RID(),1253"Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(data[i].size()) + ") than what is required by the format (" + itos(required_size) + ").");1254}12551256ERR_FAIL_COND_V_MSG(format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, RID(),1257"Textures created as depth attachments can't be initialized with data directly. Use RenderingDevice::texture_update() instead.");12581259if (!(format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT)) {1260forced_usage_bits |= TEXTURE_USAGE_CAN_UPDATE_BIT;1261}1262}12631264{1265// Validate that this image is supported for the intended use.1266bool cpu_readable = (format.usage_bits & RDD::TEXTURE_USAGE_CPU_READ_BIT);1267BitField<RDD::TextureUsageBits> supported_usage = driver->texture_get_usages_supported_by_format(format.format, cpu_readable);12681269String format_text = "'" + String(FORMAT_NAMES[format.format]) + "'";12701271if ((format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_SAMPLING_BIT)) {1272ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture.");1273}1274if ((format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {1275ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment.");1276}1277if ((format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {1278ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment.");1279}1280if ((format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_BIT)) {1281ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image.");1282}1283if ((format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_STORAGE_ATOMIC_BIT)) {1284ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image.");1285}1286if ((format.usage_bits & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && !supported_usage.has_flag(TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {1287ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as variable shading rate attachment.");1288}1289}12901291// Transfer and validate view info.12921293RDD::TextureView tv;1294if (p_view.format_override == DATA_FORMAT_MAX) {1295tv.format = format.format;1296} else {1297ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());1298tv.format = p_view.format_override;1299}1300ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID());1301ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID());1302ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID());1303ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID());1304tv.swizzle_r = p_view.swizzle_r;1305tv.swizzle_g = p_view.swizzle_g;1306tv.swizzle_b = p_view.swizzle_b;1307tv.swizzle_a = p_view.swizzle_a;13081309// Create.13101311Texture texture;1312format.usage_bits |= forced_usage_bits;1313texture.driver_id = driver->texture_create(format, tv);1314ERR_FAIL_COND_V(!texture.driver_id, RID());1315texture.type = format.texture_type;1316texture.format = format.format;1317texture.width = format.width;1318texture.height = format.height;1319texture.depth = format.depth;1320texture.layers = format.array_layers;1321texture.mipmaps = format.mipmaps;1322texture.base_mipmap = 0;1323texture.base_layer = 0;1324texture.is_resolve_buffer = format.is_resolve_buffer;1325texture.is_discardable = format.is_discardable;1326texture.usage_flags = format.usage_bits & ~forced_usage_bits;1327texture.samples = format.samples;1328texture.allowed_shared_formats = format.shareable_formats;1329texture.has_initial_data = !data.is_empty();13301331if (driver->api_trait_get(RDD::API_TRAIT_TEXTURE_OUTPUTS_REQUIRE_CLEARS)) {1332// Check if a clear for this texture must be performed the first time it's used if the driver requires explicit clears after initialization.1333texture.pending_clear = !texture.has_initial_data && (format.usage_bits & (TEXTURE_USAGE_STORAGE_BIT | TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT));1334}13351336if ((format.usage_bits & (TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT))) {1337texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);1338texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);1339if (format_has_stencil(format.format)) {1340texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);1341}1342} else {1343texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);1344texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);1345}13461347texture.bound = false;13481349// Textures are only assumed to be immutable if they have initial data and none of the other bits that indicate write usage are enabled.1350bool texture_mutable_by_default = texture.usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT | TEXTURE_USAGE_STORAGE_BIT | TEXTURE_USAGE_STORAGE_ATOMIC_BIT);1351if (data.is_empty() || texture_mutable_by_default) {1352_texture_make_mutable(&texture, RID());1353}13541355texture_memory += driver->texture_get_allocation_size(texture.driver_id);13561357RID id = texture_owner.make_rid(texture);1358#ifdef DEV_ENABLED1359set_resource_name(id, "RID:" + itos(id.get_id()));1360#endif13611362if (data.size()) {1363const bool use_general_in_copy_queues = driver->api_trait_get(RDD::API_TRAIT_USE_GENERAL_IN_COPY_QUEUES);1364const RDD::TextureLayout dst_layout = use_general_in_copy_queues ? RDD::TEXTURE_LAYOUT_GENERAL : RDD::TEXTURE_LAYOUT_COPY_DST_OPTIMAL;1365for (uint32_t i = 0; i < format.array_layers; i++) {1366_texture_initialize(id, i, data[i], dst_layout, immediate_flush);1367}13681369if (texture.draw_tracker != nullptr) {1370texture.draw_tracker->usage = use_general_in_copy_queues ? RDG::RESOURCE_USAGE_GENERAL : RDG::RESOURCE_USAGE_COPY_TO;1371}1372}13731374return id;1375}13761377RID RenderingDevice::texture_create_shared(const TextureView &p_view, RID p_with_texture) {1378Texture *src_texture = texture_owner.get_or_null(p_with_texture);1379ERR_FAIL_NULL_V(src_texture, RID());13801381if (src_texture->owner.is_valid()) { // Ahh this is a share. The RenderingDeviceDriver needs the actual owner.1382p_with_texture = src_texture->owner;1383src_texture = texture_owner.get_or_null(src_texture->owner);1384ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug.1385}13861387// Create view.13881389Texture texture = *src_texture;1390texture.slice_trackers = nullptr;1391texture.shared_fallback = nullptr;13921393RDD::TextureView tv;1394bool create_shared = true;1395bool raw_reintepretation = false;1396if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {1397tv.format = texture.format;1398} else {1399ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());14001401ERR_FAIL_COND_V_MSG(!texture.allowed_shared_formats.has(p_view.format_override), RID(),1402"Format override is not in the list of allowed shareable formats for original texture.");1403tv.format = p_view.format_override;1404create_shared = driver->texture_can_make_shared_with_format(texture.driver_id, p_view.format_override, raw_reintepretation);1405}1406tv.swizzle_r = p_view.swizzle_r;1407tv.swizzle_g = p_view.swizzle_g;1408tv.swizzle_b = p_view.swizzle_b;1409tv.swizzle_a = p_view.swizzle_a;14101411if (create_shared) {1412texture.driver_id = driver->texture_create_shared(texture.driver_id, tv);1413} else {1414// The regular view will use the same format as the main texture.1415RDD::TextureView regular_view = tv;1416regular_view.format = src_texture->format;1417texture.driver_id = driver->texture_create_shared(texture.driver_id, regular_view);14181419// Create the independent texture for the alias.1420RDD::TextureFormat alias_format = texture.texture_format();1421alias_format.format = tv.format;1422alias_format.usage_bits = TEXTURE_USAGE_SAMPLING_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT;14231424_texture_check_shared_fallback(src_texture);1425_texture_check_shared_fallback(&texture);14261427texture.shared_fallback->texture = driver->texture_create(alias_format, tv);1428texture.shared_fallback->raw_reinterpretation = raw_reintepretation;1429texture_memory += driver->texture_get_allocation_size(texture.shared_fallback->texture);14301431RDG::ResourceTracker *tracker = RDG::resource_tracker_create();1432tracker->texture_driver_id = texture.shared_fallback->texture;1433tracker->texture_size = Size2i(texture.width, texture.height);1434tracker->texture_subresources = texture.barrier_range();1435tracker->texture_usage = alias_format.usage_bits;1436tracker->is_discardable = texture.is_discardable;1437tracker->reference_count = 1;1438texture.shared_fallback->texture_tracker = tracker;1439texture.shared_fallback->revision = 0;14401441if (raw_reintepretation && src_texture->shared_fallback->buffer.id == 0) {1442// For shared textures of the same size, we create the buffer on the main texture if it doesn't have it already.1443_texture_create_reinterpret_buffer(src_texture);1444}1445}14461447ERR_FAIL_COND_V(!texture.driver_id, RID());14481449if (texture.draw_tracker != nullptr) {1450texture.draw_tracker->reference_count++;1451}14521453texture.owner = p_with_texture;1454RID id = texture_owner.make_rid(texture);1455#ifdef DEV_ENABLED1456set_resource_name(id, "RID:" + itos(id.get_id()));1457#endif1458_add_dependency(id, p_with_texture);14591460return id;1461}14621463RID RenderingDevice::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, BitField<RenderingDevice::TextureUsageBits> p_usage, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers, uint64_t p_mipmaps) {1464// This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).14651466Texture texture;1467texture.type = p_type;1468texture.format = p_format;1469texture.samples = p_samples;1470texture.width = p_width;1471texture.height = p_height;1472texture.depth = p_depth;1473texture.layers = p_layers;1474texture.mipmaps = p_mipmaps;1475texture.usage_flags = p_usage;1476texture.base_mipmap = 0;1477texture.base_layer = 0;1478texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);1479texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);14801481if (p_usage.has_flag(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) || p_usage.has_flag(TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT)) {1482texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);1483texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);1484/*if (format_has_stencil(p_format.format)) {1485texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);1486}*/1487} else {1488texture.read_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);1489texture.barrier_aspect_flags.set_flag(RDD::TEXTURE_ASPECT_COLOR_BIT);1490}14911492texture.driver_id = driver->texture_create_from_extension(p_image, p_type, p_format, p_layers, (texture.usage_flags & (TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT)), p_mipmaps);1493ERR_FAIL_COND_V(!texture.driver_id, RID());14941495_texture_make_mutable(&texture, RID());14961497RID id = texture_owner.make_rid(texture);1498#ifdef DEV_ENABLED1499set_resource_name(id, "RID:" + itos(id.get_id()));1500#endif15011502return id;1503}15041505RID RenderingDevice::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type, uint32_t p_layers) {1506Texture *src_texture = texture_owner.get_or_null(p_with_texture);1507ERR_FAIL_NULL_V(src_texture, RID());15081509if (src_texture->owner.is_valid()) { // // Ahh this is a share. The RenderingDeviceDriver needs the actual owner.1510p_with_texture = src_texture->owner;1511src_texture = texture_owner.get_or_null(src_texture->owner);1512ERR_FAIL_NULL_V(src_texture, RID()); // This is a bug.1513}15141515ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(),1516"Can only create a cubemap slice from a cubemap or cubemap array mipmap");15171518ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),1519"Can only create a 3D slice from a 3D texture");15201521ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),1522"Can only create an array slice from a 2D array mipmap");15231524// Create view.15251526ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());1527ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());1528ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());15291530int slice_layers = 1;1531if (p_layers != 0) {1532ERR_FAIL_COND_V_MSG(p_layers > 1 && p_slice_type != TEXTURE_SLICE_2D_ARRAY, RID(), "layer slicing only supported for 2D arrays");1533ERR_FAIL_COND_V_MSG(p_layer + p_layers > src_texture->layers, RID(), "layer slice is out of bounds");1534slice_layers = p_layers;1535} else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {1536ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");1537slice_layers = src_texture->layers;1538} else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {1539slice_layers = 6;1540}15411542Texture texture = *src_texture;1543texture.slice_trackers = nullptr;1544texture.shared_fallback = nullptr;15451546get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);1547texture.mipmaps = p_mipmaps;1548texture.layers = slice_layers;1549texture.base_mipmap = p_mipmap;1550texture.base_layer = p_layer;15511552if (p_slice_type == TEXTURE_SLICE_2D) {1553texture.type = TEXTURE_TYPE_2D;1554} else if (p_slice_type == TEXTURE_SLICE_3D) {1555texture.type = TEXTURE_TYPE_3D;1556}15571558RDD::TextureView tv;1559bool create_shared = true;1560bool raw_reintepretation = false;1561if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {1562tv.format = texture.format;1563} else {1564ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());15651566ERR_FAIL_COND_V_MSG(!texture.allowed_shared_formats.has(p_view.format_override), RID(),1567"Format override is not in the list of allowed shareable formats for original texture.");1568tv.format = p_view.format_override;1569create_shared = driver->texture_can_make_shared_with_format(texture.driver_id, p_view.format_override, raw_reintepretation);1570}15711572tv.swizzle_r = p_view.swizzle_r;1573tv.swizzle_g = p_view.swizzle_g;1574tv.swizzle_b = p_view.swizzle_b;1575tv.swizzle_a = p_view.swizzle_a;15761577if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {1578ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),1579"Specified layer is invalid for cubemap");1580ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),1581"Specified layer must be a multiple of 6.");1582}15831584if (create_shared) {1585texture.driver_id = driver->texture_create_shared_from_slice(src_texture->driver_id, tv, p_slice_type, p_layer, slice_layers, p_mipmap, p_mipmaps);1586} else {1587// The regular view will use the same format as the main texture.1588RDD::TextureView regular_view = tv;1589regular_view.format = src_texture->format;1590texture.driver_id = driver->texture_create_shared_from_slice(src_texture->driver_id, regular_view, p_slice_type, p_layer, slice_layers, p_mipmap, p_mipmaps);15911592// Create the independent texture for the slice.1593RDD::TextureSubresourceRange slice_range = texture.barrier_range();1594slice_range.base_mipmap = 0;1595slice_range.base_layer = 0;15961597RDD::TextureFormat slice_format = texture.texture_format();1598slice_format.width = MAX(texture.width >> p_mipmap, 1U);1599slice_format.height = MAX(texture.height >> p_mipmap, 1U);1600slice_format.depth = MAX(texture.depth >> p_mipmap, 1U);1601slice_format.format = tv.format;1602slice_format.usage_bits = TEXTURE_USAGE_SAMPLING_BIT | TEXTURE_USAGE_CAN_COPY_TO_BIT;16031604_texture_check_shared_fallback(src_texture);1605_texture_check_shared_fallback(&texture);16061607texture.shared_fallback->texture = driver->texture_create(slice_format, tv);1608texture.shared_fallback->raw_reinterpretation = raw_reintepretation;1609texture_memory += driver->texture_get_allocation_size(texture.shared_fallback->texture);16101611RDG::ResourceTracker *tracker = RDG::resource_tracker_create();1612tracker->texture_driver_id = texture.shared_fallback->texture;1613tracker->texture_size = Size2i(texture.width, texture.height);1614tracker->texture_subresources = slice_range;1615tracker->texture_usage = slice_format.usage_bits;1616tracker->is_discardable = slice_format.is_discardable;1617tracker->reference_count = 1;1618texture.shared_fallback->texture_tracker = tracker;1619texture.shared_fallback->revision = 0;16201621if (raw_reintepretation && src_texture->shared_fallback->buffer.id == 0) {1622// For shared texture slices, we create the buffer on the slice if the source texture has no reinterpretation buffer.1623_texture_create_reinterpret_buffer(&texture);1624}1625}16261627ERR_FAIL_COND_V(!texture.driver_id, RID());16281629const Rect2i slice_rect(p_mipmap, p_layer, p_mipmaps, slice_layers);1630texture.owner = p_with_texture;1631texture.slice_type = p_slice_type;1632texture.slice_rect = slice_rect;16331634// If parent is mutable, make slice mutable by default.1635if (src_texture->draw_tracker != nullptr) {1636texture.draw_tracker = nullptr;1637_texture_make_mutable(&texture, RID());1638}16391640RID id = texture_owner.make_rid(texture);1641#ifdef DEV_ENABLED1642set_resource_name(id, "RID:" + itos(id.get_id()));1643#endif1644_add_dependency(id, p_with_texture);16451646return id;1647}16481649static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_x, uint32_t p_src_y, uint32_t p_src_w, uint32_t p_src_h, uint32_t p_src_full_w, uint32_t p_dst_pitch, uint32_t p_unit_size) {1650uint32_t src_offset = (p_src_y * p_src_full_w + p_src_x) * p_unit_size;1651uint32_t dst_offset = 0;1652for (uint32_t y = p_src_h; y > 0; y--) {1653uint8_t const *__restrict src = p_src + src_offset;1654uint8_t *__restrict dst = p_dst + dst_offset;1655for (uint32_t x = p_src_w * p_unit_size; x > 0; x--) {1656*dst = *src;1657src++;1658dst++;1659}1660src_offset += p_src_full_w * p_unit_size;1661dst_offset += p_dst_pitch;1662}1663}16641665static _ALWAYS_INLINE_ void _copy_region_block_or_regular(const uint8_t *p_read_ptr, uint8_t *p_write_ptr, uint32_t p_x, uint32_t p_y, uint32_t p_width, uint32_t p_region_w, uint32_t p_region_h, uint32_t p_block_w, uint32_t p_block_h, uint32_t p_dst_pitch, uint32_t p_pixel_size, uint32_t p_block_size) {1666if (p_block_w != 1 || p_block_h != 1) {1667// Block format.1668uint32_t xb = p_x / p_block_w;1669uint32_t yb = p_y / p_block_h;1670uint32_t wb = p_width / p_block_w;1671uint32_t region_wb = p_region_w / p_block_w;1672uint32_t region_hb = p_region_h / p_block_h;1673_copy_region(p_read_ptr, p_write_ptr, xb, yb, region_wb, region_hb, wb, p_dst_pitch, p_block_size);1674} else {1675// Regular format.1676_copy_region(p_read_ptr, p_write_ptr, p_x, p_y, p_region_w, p_region_h, p_width, p_dst_pitch, p_pixel_size);1677}1678}16791680uint32_t RenderingDevice::_texture_layer_count(Texture *p_texture) const {1681switch (p_texture->type) {1682case TEXTURE_TYPE_CUBE:1683case TEXTURE_TYPE_CUBE_ARRAY:1684return p_texture->layers * 6;1685default:1686return p_texture->layers;1687}1688}16891690uint32_t greatest_common_denominator(uint32_t a, uint32_t b) {1691// Euclidean algorithm.1692uint32_t t;1693while (b != 0) {1694t = b;1695b = a % b;1696a = t;1697}16981699return a;1700}17011702uint32_t least_common_multiple(uint32_t a, uint32_t b) {1703if (a == 0 || b == 0) {1704return 0;1705}17061707return (a / greatest_common_denominator(a, b)) * b;1708}17091710uint32_t RenderingDevice::_texture_alignment(Texture *p_texture) const {1711uint32_t alignment = get_compressed_image_format_block_byte_size(p_texture->format);1712if (alignment == 1) {1713alignment = get_image_format_pixel_size(p_texture->format);1714}17151716return least_common_multiple(alignment, driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT));1717}17181719Error RenderingDevice::_texture_initialize(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, RDD::TextureLayout p_dst_layout, bool p_immediate_flush) {1720Texture *texture = texture_owner.get_or_null(p_texture);1721ERR_FAIL_NULL_V(texture, ERR_INVALID_PARAMETER);17221723if (texture->owner != RID()) {1724p_texture = texture->owner;1725texture = texture_owner.get_or_null(texture->owner);1726ERR_FAIL_NULL_V(texture, ERR_BUG); // This is a bug.1727}17281729uint32_t layer_count = _texture_layer_count(texture);1730ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);17311732uint32_t width, height;1733uint32_t tight_mip_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);1734uint32_t required_size = tight_mip_size;1735uint32_t required_align = _texture_alignment(texture);17361737ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,1738"Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");17391740uint32_t block_w, block_h;1741get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);17421743uint32_t pixel_size = get_image_format_pixel_size(texture->format);1744uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(texture->format);1745uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);17461747// The algorithm operates on two passes, one to figure out the total size the staging buffer will require to allocate and another one where the copy is actually performed.1748uint32_t staging_worker_offset = 0;1749uint32_t staging_local_offset = 0;1750TransferWorker *transfer_worker = nullptr;1751const uint8_t *read_ptr = p_data.ptr();1752uint8_t *write_ptr = nullptr;1753for (uint32_t pass = 0; pass < 2; pass++) {1754const bool copy_pass = (pass == 1);1755if (copy_pass) {1756transfer_worker = _acquire_transfer_worker(staging_local_offset, required_align, staging_worker_offset);1757texture->transfer_worker_index = transfer_worker->index;17581759{1760MutexLock lock(transfer_worker->operations_mutex);1761texture->transfer_worker_operation = ++transfer_worker->operations_counter;1762}17631764staging_local_offset = 0;17651766write_ptr = driver->buffer_map(transfer_worker->staging_buffer);1767ERR_FAIL_NULL_V(write_ptr, ERR_CANT_CREATE);17681769if (driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {1770// Transition the texture to the optimal layout.1771RDD::TextureBarrier tb;1772tb.texture = texture->driver_id;1773tb.dst_access = RDD::BARRIER_ACCESS_COPY_WRITE_BIT;1774tb.prev_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;1775tb.next_layout = p_dst_layout;1776tb.subresources.aspect = texture->barrier_aspect_flags;1777tb.subresources.mipmap_count = texture->mipmaps;1778tb.subresources.base_layer = p_layer;1779tb.subresources.layer_count = 1;1780driver->command_pipeline_barrier(transfer_worker->command_buffer, RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, RDD::PIPELINE_STAGE_COPY_BIT, {}, {}, tb, {});1781}1782}17831784uint32_t mipmap_offset = 0;1785uint32_t logic_width = texture->width;1786uint32_t logic_height = texture->height;1787for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {1788uint32_t depth = 0;1789uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);17901791const uint8_t *read_ptr_mipmap = read_ptr + mipmap_offset;1792tight_mip_size = image_total - mipmap_offset;17931794for (uint32_t z = 0; z < depth; z++) {1795if (required_align > 0) {1796uint32_t align_offset = staging_local_offset % required_align;1797if (align_offset != 0) {1798staging_local_offset += required_align - align_offset;1799}1800}18011802uint32_t pitch = (width * pixel_size * block_w) >> pixel_rshift;1803uint32_t pitch_step = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP);1804pitch = STEPIFY(pitch, pitch_step);1805uint32_t to_allocate = pitch * height;1806to_allocate >>= pixel_rshift;18071808if (copy_pass) {1809const uint8_t *read_ptr_mipmap_layer = read_ptr_mipmap + (tight_mip_size / depth) * z;1810uint64_t staging_buffer_offset = staging_worker_offset + staging_local_offset;1811uint8_t *write_ptr_mipmap_layer = write_ptr + staging_buffer_offset;1812_copy_region_block_or_regular(read_ptr_mipmap_layer, write_ptr_mipmap_layer, 0, 0, width, width, height, block_w, block_h, pitch, pixel_size, block_size);18131814RDD::BufferTextureCopyRegion copy_region;1815copy_region.buffer_offset = staging_buffer_offset;1816copy_region.row_pitch = pitch;1817copy_region.texture_subresource.aspect = texture->read_aspect_flags.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT) ? RDD::TEXTURE_ASPECT_DEPTH : RDD::TEXTURE_ASPECT_COLOR;1818copy_region.texture_subresource.mipmap = mm_i;1819copy_region.texture_subresource.layer = p_layer;1820copy_region.texture_offset = Vector3i(0, 0, z);1821copy_region.texture_region_size = Vector3i(logic_width, logic_height, 1);1822driver->command_copy_buffer_to_texture(transfer_worker->command_buffer, transfer_worker->staging_buffer, texture->driver_id, p_dst_layout, copy_region);1823}18241825staging_local_offset += to_allocate;1826}18271828mipmap_offset = image_total;1829logic_width = MAX(1u, logic_width >> 1);1830logic_height = MAX(1u, logic_height >> 1);1831}18321833if (copy_pass) {1834driver->buffer_unmap(transfer_worker->staging_buffer);18351836// If the texture does not have a tracker, it means it must be transitioned to the sampling state.1837if (texture->draw_tracker == nullptr && driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {1838RDD::TextureBarrier tb;1839tb.texture = texture->driver_id;1840tb.src_access = RDD::BARRIER_ACCESS_COPY_WRITE_BIT;1841tb.prev_layout = p_dst_layout;1842tb.next_layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;1843tb.subresources.aspect = texture->barrier_aspect_flags;1844tb.subresources.mipmap_count = texture->mipmaps;1845tb.subresources.base_layer = p_layer;1846tb.subresources.layer_count = 1;1847transfer_worker->texture_barriers.push_back(tb);1848}18491850if (p_immediate_flush) {1851_end_transfer_worker(transfer_worker);1852_submit_transfer_worker(transfer_worker);1853_wait_for_transfer_worker(transfer_worker);1854}18551856_release_transfer_worker(transfer_worker);1857}1858}18591860return OK;1861}18621863Error RenderingDevice::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data) {1864ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);18651866ERR_FAIL_COND_V_MSG(draw_list.active, ERR_INVALID_PARAMETER, "Updating textures is forbidden during creation of a draw list.");1867ERR_FAIL_COND_V_MSG(compute_list.active, ERR_INVALID_PARAMETER, "Updating textures is forbidden during creation of a compute list.");1868ERR_FAIL_COND_V_MSG(raytracing_list.active, ERR_INVALID_PARAMETER, "Updating textures is forbidden during creation of a raytracing list.");18691870Texture *texture = texture_owner.get_or_null(p_texture);1871ERR_FAIL_NULL_V(texture, ERR_INVALID_PARAMETER);18721873if (texture->owner != RID()) {1874p_texture = texture->owner;1875texture = texture_owner.get_or_null(texture->owner);1876ERR_FAIL_NULL_V(texture, ERR_BUG); // This is a bug.1877}18781879ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,1880"Texture can't be updated while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to update this texture.");18811882ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER, "Texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_UPDATE_BIT` to be set to be updatable.");18831884uint32_t layer_count = _texture_layer_count(texture);1885ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);18861887uint32_t width, height;1888uint32_t tight_mip_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);1889uint32_t required_size = tight_mip_size;1890uint32_t required_align = _texture_alignment(texture);18911892ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,1893"Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");18941895// Clear the texture if the driver requires it during its first use.1896_texture_check_pending_clear(p_texture, texture);18971898_check_transfer_worker_texture(texture);18991900uint32_t block_w, block_h;1901get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);19021903uint32_t pixel_size = get_image_format_pixel_size(texture->format);1904uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(texture->format);1905uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);19061907uint32_t region_size = texture_upload_region_size_px;19081909const uint8_t *read_ptr = p_data.ptr();19101911thread_local LocalVector<RDG::RecordedBufferToTextureCopy> command_buffer_to_texture_copies_vector;1912command_buffer_to_texture_copies_vector.clear();19131914// Indicate the texture will get modified for the shared texture fallback.1915_texture_update_shared_fallback(p_texture, texture, true);19161917uint32_t mipmap_offset = 0;19181919uint32_t logic_width = texture->width;1920uint32_t logic_height = texture->height;19211922for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {1923uint32_t depth = 0;1924uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);19251926const uint8_t *read_ptr_mipmap = read_ptr + mipmap_offset;1927tight_mip_size = image_total - mipmap_offset;19281929for (uint32_t z = 0; z < depth; z++) {1930const uint8_t *read_ptr_mipmap_layer = read_ptr_mipmap + (tight_mip_size / depth) * z;1931for (uint32_t y = 0; y < height; y += region_size) {1932for (uint32_t x = 0; x < width; x += region_size) {1933uint32_t region_w = MIN(region_size, width - x);1934uint32_t region_h = MIN(region_size, height - y);19351936uint32_t region_logic_w = MIN(region_size, logic_width - x);1937uint32_t region_logic_h = MIN(region_size, logic_height - y);19381939uint32_t region_pitch = (region_w * pixel_size * block_w) >> pixel_rshift;1940uint32_t pitch_step = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP);1941region_pitch = STEPIFY(region_pitch, pitch_step);1942uint32_t to_allocate = region_pitch * region_h;1943uint32_t alloc_offset = 0, alloc_size = 0;1944StagingRequiredAction required_action;1945Error err = _staging_buffer_allocate(upload_staging_buffers, to_allocate, required_align, alloc_offset, alloc_size, required_action, false);1946ERR_FAIL_COND_V(err, ERR_CANT_CREATE);19471948if (!command_buffer_to_texture_copies_vector.is_empty() && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL) {1949if (_texture_make_mutable(texture, p_texture)) {1950// The texture must be mutable to be used as a copy destination.1951draw_graph.add_synchronization();1952}19531954// If the staging buffer requires flushing everything, we submit the command early and clear the current vector.1955draw_graph.add_texture_update(texture->driver_id, texture->draw_tracker, command_buffer_to_texture_copies_vector);1956command_buffer_to_texture_copies_vector.clear();1957}19581959_staging_buffer_execute_required_action(upload_staging_buffers, required_action);19601961uint8_t *write_ptr = upload_staging_buffers.blocks[upload_staging_buffers.current].data_ptr + alloc_offset;19621963ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);1964ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);19651966_copy_region_block_or_regular(read_ptr_mipmap_layer, write_ptr, x, y, width, region_w, region_h, block_w, block_h, region_pitch, pixel_size, block_size);19671968RDD::BufferTextureCopyRegion copy_region;1969copy_region.buffer_offset = alloc_offset;1970copy_region.row_pitch = region_pitch;1971copy_region.texture_subresource.aspect = texture->read_aspect_flags.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT) ? RDD::TEXTURE_ASPECT_DEPTH : RDD::TEXTURE_ASPECT_COLOR;1972copy_region.texture_subresource.mipmap = mm_i;1973copy_region.texture_subresource.layer = p_layer;1974copy_region.texture_offset = Vector3i(x, y, z);1975copy_region.texture_region_size = Vector3i(region_logic_w, region_logic_h, 1);19761977RDG::RecordedBufferToTextureCopy buffer_to_texture_copy;1978buffer_to_texture_copy.from_buffer = upload_staging_buffers.blocks[upload_staging_buffers.current].driver_id;1979buffer_to_texture_copy.region = copy_region;1980command_buffer_to_texture_copies_vector.push_back(buffer_to_texture_copy);19811982upload_staging_buffers.blocks.write[upload_staging_buffers.current].fill_amount = alloc_offset + alloc_size;1983}1984}1985}19861987mipmap_offset = image_total;1988logic_width = MAX(1u, logic_width >> 1);1989logic_height = MAX(1u, logic_height >> 1);1990}19911992if (_texture_make_mutable(texture, p_texture)) {1993// The texture must be mutable to be used as a copy destination.1994draw_graph.add_synchronization();1995}19961997draw_graph.add_texture_update(texture->driver_id, texture->draw_tracker, command_buffer_to_texture_copies_vector);19981999return OK;2000}20012002void RenderingDevice::_texture_check_shared_fallback(Texture *p_texture) {2003if (p_texture->shared_fallback == nullptr) {2004p_texture->shared_fallback = memnew(Texture::SharedFallback);2005}2006}20072008void RenderingDevice::_texture_update_shared_fallback(RID p_texture_rid, Texture *p_texture, bool p_for_writing) {2009if (p_texture->shared_fallback == nullptr) {2010// This texture does not use any of the shared texture fallbacks.2011return;2012}20132014if (p_texture->owner.is_valid()) {2015Texture *owner_texture = texture_owner.get_or_null(p_texture->owner);2016ERR_FAIL_NULL(owner_texture);2017if (p_for_writing) {2018// Only the main texture is used for writing when using the shared fallback.2019owner_texture->shared_fallback->revision++;2020} else if (p_texture->shared_fallback->revision != owner_texture->shared_fallback->revision) {2021// Copy the contents of the main texture into the shared texture fallback slice. Update the revision.2022_texture_copy_shared(p_texture->owner, owner_texture, p_texture_rid, p_texture);2023p_texture->shared_fallback->revision = owner_texture->shared_fallback->revision;2024}2025} else if (p_for_writing) {2026// Increment the revision of the texture so shared texture fallback slices must be updated.2027p_texture->shared_fallback->revision++;2028}2029}20302031void RenderingDevice::_texture_free_shared_fallback(Texture *p_texture) {2032if (p_texture->shared_fallback != nullptr) {2033if (p_texture->shared_fallback->texture_tracker != nullptr) {2034RDG::resource_tracker_free(p_texture->shared_fallback->texture_tracker);2035}20362037if (p_texture->shared_fallback->buffer_tracker != nullptr) {2038RDG::resource_tracker_free(p_texture->shared_fallback->buffer_tracker);2039}20402041if (p_texture->shared_fallback->texture.id != 0) {2042texture_memory -= driver->texture_get_allocation_size(p_texture->shared_fallback->texture);2043driver->texture_free(p_texture->shared_fallback->texture);2044}20452046if (p_texture->shared_fallback->buffer.id != 0) {2047buffer_memory -= driver->buffer_get_allocation_size(p_texture->shared_fallback->buffer);2048driver->buffer_free(p_texture->shared_fallback->buffer);2049}20502051memdelete(p_texture->shared_fallback);2052p_texture->shared_fallback = nullptr;2053}2054}20552056void RenderingDevice::_texture_copy_shared(RID p_src_texture_rid, Texture *p_src_texture, RID p_dst_texture_rid, Texture *p_dst_texture) {2057// The only type of copying allowed is from the main texture to the slice texture, as slice textures are not allowed to be used for writing when using this fallback.2058DEV_ASSERT(p_src_texture != nullptr);2059DEV_ASSERT(p_dst_texture != nullptr);2060DEV_ASSERT(p_src_texture->owner.is_null());2061DEV_ASSERT(p_dst_texture->owner == p_src_texture_rid);20622063bool src_made_mutable = _texture_make_mutable(p_src_texture, p_src_texture_rid);2064bool dst_made_mutable = _texture_make_mutable(p_dst_texture, p_dst_texture_rid);2065if (src_made_mutable || dst_made_mutable) {2066draw_graph.add_synchronization();2067}20682069if (p_dst_texture->shared_fallback->raw_reinterpretation) {2070// If one of the textures is a main texture and they have a reinterpret buffer, we prefer using that as it's guaranteed to be big enough to hold2071// anything and it's how the shared textures that don't use slices are created.2072bool src_has_buffer = p_src_texture->shared_fallback->buffer.id != 0;2073bool dst_has_buffer = p_dst_texture->shared_fallback->buffer.id != 0;2074bool from_src = p_src_texture->owner.is_null() && src_has_buffer;2075bool from_dst = p_dst_texture->owner.is_null() && dst_has_buffer;2076if (!from_src && !from_dst) {2077// If neither texture passed the condition, we just pick whichever texture has a reinterpretation buffer.2078from_src = src_has_buffer;2079from_dst = dst_has_buffer;2080}20812082// Pick the buffer and tracker to use from the right texture.2083RDD::BufferID shared_buffer;2084RDG::ResourceTracker *shared_buffer_tracker = nullptr;2085if (from_src) {2086shared_buffer = p_src_texture->shared_fallback->buffer;2087shared_buffer_tracker = p_src_texture->shared_fallback->buffer_tracker;2088} else if (from_dst) {2089shared_buffer = p_dst_texture->shared_fallback->buffer;2090shared_buffer_tracker = p_dst_texture->shared_fallback->buffer_tracker;2091} else {2092DEV_ASSERT(false && "This path should not be reachable.");2093}20942095// Copying each mipmap from main texture to a buffer and then to the slice texture.2096thread_local LocalVector<RDD::BufferTextureCopyRegion> get_data_vector;2097thread_local LocalVector<RDG::RecordedBufferToTextureCopy> update_vector;2098get_data_vector.clear();2099update_vector.clear();21002101uint32_t buffer_size = 0;2102uint32_t transfer_alignment = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT);21032104for (uint32_t i = 0; i < p_dst_texture->layers; i++) {2105for (uint32_t j = 0; j < p_dst_texture->mipmaps; j++) {2106// FIXME: When using reinterpretation buffers, the only texture aspect supported is color. Depth or stencil contents won't get copied.2107RDD::TextureSubresource texture_subresource;2108texture_subresource.aspect = RDD::TEXTURE_ASPECT_COLOR;2109texture_subresource.layer = i;2110texture_subresource.mipmap = j;21112112RDD::TextureCopyableLayout copyable_layout;2113driver->texture_get_copyable_layout(p_dst_texture->shared_fallback->texture, texture_subresource, ©able_layout);21142115uint32_t mipmap = p_dst_texture->base_mipmap + j;21162117RDD::BufferTextureCopyRegion get_data_region;2118get_data_region.buffer_offset = STEPIFY(buffer_size, transfer_alignment);2119get_data_region.row_pitch = copyable_layout.row_pitch;2120get_data_region.texture_subresource.aspect = RDD::TEXTURE_ASPECT_COLOR;2121get_data_region.texture_subresource.layer = p_dst_texture->base_layer + i;2122get_data_region.texture_subresource.mipmap = mipmap;2123get_data_region.texture_region_size.x = MAX(1U, p_src_texture->width >> mipmap);2124get_data_region.texture_region_size.y = MAX(1U, p_src_texture->height >> mipmap);2125get_data_region.texture_region_size.z = MAX(1U, p_src_texture->depth >> mipmap);2126get_data_vector.push_back(get_data_region);21272128RDG::RecordedBufferToTextureCopy update_copy;2129update_copy.from_buffer = shared_buffer;2130update_copy.region.buffer_offset = get_data_region.buffer_offset;2131update_copy.region.row_pitch = get_data_region.row_pitch;2132update_copy.region.texture_subresource.aspect = RDD::TEXTURE_ASPECT_COLOR;2133update_copy.region.texture_subresource.layer = texture_subresource.layer;2134update_copy.region.texture_subresource.mipmap = texture_subresource.mipmap;2135update_copy.region.texture_region_size.x = get_data_region.texture_region_size.x;2136update_copy.region.texture_region_size.y = get_data_region.texture_region_size.y;2137update_copy.region.texture_region_size.z = get_data_region.texture_region_size.z;2138update_vector.push_back(update_copy);21392140buffer_size = get_data_region.buffer_offset + copyable_layout.size;2141}2142}21432144DEV_ASSERT(buffer_size <= driver->buffer_get_allocation_size(shared_buffer));21452146draw_graph.add_texture_get_data(p_src_texture->driver_id, p_src_texture->draw_tracker, shared_buffer, get_data_vector, shared_buffer_tracker);2147draw_graph.add_texture_update(p_dst_texture->shared_fallback->texture, p_dst_texture->shared_fallback->texture_tracker, update_vector, shared_buffer_tracker);2148} else {2149// Raw reinterpretation is not required. Use a regular texture copy.2150RDD::TextureCopyRegion copy_region;2151copy_region.src_subresources.aspect = p_src_texture->read_aspect_flags;2152copy_region.src_subresources.base_layer = p_dst_texture->base_layer;2153copy_region.src_subresources.layer_count = p_dst_texture->layers;2154copy_region.dst_subresources.aspect = p_dst_texture->read_aspect_flags;2155copy_region.dst_subresources.base_layer = 0;2156copy_region.dst_subresources.layer_count = copy_region.src_subresources.layer_count;21572158// Copying each mipmap from main texture to to the slice texture.2159thread_local LocalVector<RDD::TextureCopyRegion> region_vector;2160region_vector.clear();2161for (uint32_t i = 0; i < p_dst_texture->mipmaps; i++) {2162uint32_t mipmap = p_dst_texture->base_mipmap + i;2163copy_region.src_subresources.mipmap = mipmap;2164copy_region.dst_subresources.mipmap = i;2165copy_region.size.x = MAX(1U, p_src_texture->width >> mipmap);2166copy_region.size.y = MAX(1U, p_src_texture->height >> mipmap);2167copy_region.size.z = MAX(1U, p_src_texture->depth >> mipmap);2168region_vector.push_back(copy_region);2169}21702171draw_graph.add_texture_copy(p_src_texture->driver_id, p_src_texture->draw_tracker, p_dst_texture->shared_fallback->texture, p_dst_texture->shared_fallback->texture_tracker, region_vector);2172}2173}21742175void RenderingDevice::_texture_create_reinterpret_buffer(Texture *p_texture) {2176uint64_t row_pitch_step = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP);2177uint64_t transfer_alignment = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT);2178uint32_t pixel_bytes = get_image_format_pixel_size(p_texture->format);2179uint32_t row_pitch = STEPIFY(p_texture->width * pixel_bytes, row_pitch_step);2180uint64_t buffer_size = STEPIFY(pixel_bytes * row_pitch * p_texture->height * p_texture->depth, transfer_alignment);2181p_texture->shared_fallback->buffer = driver->buffer_create(buffer_size, RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);2182buffer_memory += driver->buffer_get_allocation_size(p_texture->shared_fallback->buffer);21832184RDG::ResourceTracker *tracker = RDG::resource_tracker_create();2185tracker->buffer_driver_id = p_texture->shared_fallback->buffer;2186p_texture->shared_fallback->buffer_tracker = tracker;2187}21882189uint32_t RenderingDevice::_texture_vrs_method_to_usage_bits() const {2190switch (vrs_method) {2191case VRS_METHOD_FRAGMENT_SHADING_RATE:2192return RDD::TEXTURE_USAGE_VRS_FRAGMENT_SHADING_RATE_BIT;2193case VRS_METHOD_FRAGMENT_DENSITY_MAP:2194return RDD::TEXTURE_USAGE_VRS_FRAGMENT_DENSITY_MAP_BIT;2195default:2196return 0;2197}2198}21992200void RenderingDevice::_texture_check_pending_clear(RID p_texture_rid, Texture *p_texture) {2201DEV_ASSERT(p_texture != nullptr);22022203if (!p_texture->pending_clear) {2204return;2205}22062207bool clear = true;2208p_texture->pending_clear = false;22092210if (p_texture->owner.is_valid()) {2211// Check the owner texture instead if it exists.2212p_texture_rid = p_texture->owner;2213p_texture = texture_owner.get_or_null(p_texture_rid);2214clear = p_texture->pending_clear;2215}22162217if (p_texture != nullptr && clear) {2218if (p_texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {2219_texture_clear_depth_stencil(p_texture_rid, p_texture, 0.0f, 0, 0, p_texture->mipmaps, 0, p_texture->layers);2220} else {2221_texture_clear_color(p_texture_rid, p_texture, Color(), 0, p_texture->mipmaps, 0, p_texture->layers);2222}2223p_texture->pending_clear = false;2224}2225}22262227void RenderingDevice::_texture_clear_color(RID p_texture_rid, Texture *p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers) {2228_check_transfer_worker_texture(p_texture);22292230RDD::TextureSubresourceRange range;2231range.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;2232range.base_mipmap = p_texture->base_mipmap + p_base_mipmap;2233range.mipmap_count = p_mipmaps;2234range.base_layer = p_texture->base_layer + p_base_layer;2235range.layer_count = p_layers;22362237// Indicate the texture will get modified for the shared texture fallback.2238_texture_update_shared_fallback(p_texture_rid, p_texture, true);22392240if (_texture_make_mutable(p_texture, p_texture_rid)) {2241// The texture must be mutable to be used as a clear destination.2242draw_graph.add_synchronization();2243}22442245draw_graph.add_texture_clear_color(p_texture->driver_id, p_texture->draw_tracker, p_color, range);2246}22472248void RenderingDevice::_texture_clear_depth_stencil(RID p_texture_rid, Texture *p_texture, float p_depth, uint8_t p_stencil, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers) {2249_check_transfer_worker_texture(p_texture);22502251RDD::TextureSubresourceRange range;2252if (format_has_depth(p_texture->format)) {2253range.aspect.set_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT);2254}2255if (format_has_stencil(p_texture->format)) {2256range.aspect.set_flag(RDD::TEXTURE_ASPECT_STENCIL_BIT);2257}2258range.base_mipmap = p_texture->base_mipmap + p_base_mipmap;2259range.mipmap_count = p_mipmaps;2260range.base_layer = p_texture->base_layer + p_base_layer;2261range.layer_count = p_layers;22622263// Indicate the texture will get modified for the shared texture fallback.2264_texture_update_shared_fallback(p_texture_rid, p_texture, true);22652266if (_texture_make_mutable(p_texture, p_texture_rid)) {2267// The texture must be mutable to be used as a clear destination.2268draw_graph.add_synchronization();2269}22702271draw_graph.add_texture_clear_depth_stencil(p_texture->driver_id, p_texture->draw_tracker, p_depth, p_stencil, range);2272}22732274Vector<uint8_t> RenderingDevice::texture_get_data(RID p_texture, uint32_t p_layer) {2275ERR_RENDER_THREAD_GUARD_V(Vector<uint8_t>());22762277Texture *tex = texture_owner.get_or_null(p_texture);2278ERR_FAIL_NULL_V(tex, Vector<uint8_t>());22792280ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),2281"Texture can't be retrieved while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to retrieve this texture.");2282ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),2283"Texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");22842285ERR_FAIL_COND_V(p_layer >= tex->layers, Vector<uint8_t>());22862287// Clear the texture if the driver requires it during its first use.2288_texture_check_pending_clear(p_texture, tex);22892290_check_transfer_worker_texture(tex);22912292if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) {2293return driver->texture_get_data(tex->driver_id, p_layer);2294} else {2295RDD::TextureAspect aspect = tex->read_aspect_flags.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT) ? RDD::TEXTURE_ASPECT_DEPTH : RDD::TEXTURE_ASPECT_COLOR;2296uint32_t mip_alignment = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT);2297uint32_t buffer_size = 0;22982299thread_local LocalVector<RDD::TextureCopyableLayout> mip_layouts;2300thread_local LocalVector<RDD::BufferTextureCopyRegion> copy_regions;2301mip_layouts.resize(tex->mipmaps);2302copy_regions.resize(tex->mipmaps);23032304for (uint32_t i = 0; i < tex->mipmaps; i++) {2305RDD::TextureSubresource subres;2306subres.aspect = aspect;2307subres.layer = p_layer;2308subres.mipmap = i;23092310RDD::TextureCopyableLayout &mip_layout = mip_layouts[i];2311driver->texture_get_copyable_layout(tex->driver_id, subres, &mip_layout);23122313uint32_t mip_offset = STEPIFY(buffer_size, mip_alignment);2314buffer_size = mip_offset + mip_layout.size;23152316RDD::BufferTextureCopyRegion ©_region = copy_regions[i];2317copy_region.buffer_offset = mip_offset;2318copy_region.row_pitch = mip_layout.row_pitch;2319copy_region.texture_subresource.aspect = aspect;2320copy_region.texture_subresource.mipmap = i;2321copy_region.texture_subresource.layer = p_layer;2322copy_region.texture_region_size.x = MAX(1u, tex->width >> i);2323copy_region.texture_region_size.y = MAX(1u, tex->height >> i);2324copy_region.texture_region_size.z = MAX(1u, tex->depth >> i);2325}23262327RDD::BufferID tmp_buffer = driver->buffer_create(buffer_size, RDD::BUFFER_USAGE_TRANSFER_TO_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);2328ERR_FAIL_COND_V(!tmp_buffer, Vector<uint8_t>());23292330if (_texture_make_mutable(tex, p_texture)) {2331// The texture must be mutable to be used as a copy source due to layout transitions.2332draw_graph.add_synchronization();2333}23342335draw_graph.add_texture_get_data(tex->driver_id, tex->draw_tracker, tmp_buffer, copy_regions);23362337// Flush everything so memory can be safely mapped.2338_flush_and_stall_for_all_frames();23392340const uint8_t *read_ptr = driver->buffer_map(tmp_buffer);2341ERR_FAIL_NULL_V(read_ptr, Vector<uint8_t>());23422343uint32_t block_w = 0;2344uint32_t block_h = 0;2345get_compressed_image_format_block_dimensions(tex->format, block_w, block_h);23462347Vector<uint8_t> buffer_data;2348uint32_t tight_buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps);2349buffer_data.resize(tight_buffer_size);23502351uint8_t *write_ptr = buffer_data.ptrw();23522353for (uint32_t i = 0; i < tex->mipmaps; i++) {2354uint32_t width = 0, height = 0, depth = 0;23552356uint32_t tight_mip_size = get_image_format_required_size(2357tex->format,2358MAX(1u, tex->width >> i),2359MAX(1u, tex->height >> i),2360MAX(1u, tex->depth >> i),23611,2362&width,2363&height,2364&depth);23652366uint32_t row_count = (height / block_h) * depth;2367uint32_t tight_row_pitch = tight_mip_size / row_count;23682369const uint8_t *rp = read_ptr + copy_regions[i].buffer_offset;2370uint32_t row_pitch = mip_layouts[i].row_pitch;23712372if (tight_row_pitch == row_pitch) {2373// Same row pitch, we can copy directly.2374memcpy(write_ptr, rp, tight_mip_size);2375write_ptr += tight_mip_size;2376} else {2377// Copy row-by-row to erase padding.2378for (uint32_t j = 0; j < row_count; j++) {2379memcpy(write_ptr, rp, tight_row_pitch);2380rp += row_pitch;2381write_ptr += tight_row_pitch;2382}2383}2384}23852386driver->buffer_unmap(tmp_buffer);2387driver->buffer_free(tmp_buffer);23882389return buffer_data;2390}2391}23922393Error RenderingDevice::texture_get_data_async(RID p_texture, uint32_t p_layer, const Callable &p_callback) {2394ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);23952396Texture *tex = texture_owner.get_or_null(p_texture);2397ERR_FAIL_NULL_V(tex, ERR_INVALID_PARAMETER);23982399ERR_FAIL_COND_V_MSG(tex->bound, ERR_INVALID_PARAMETER, "Texture can't be retrieved while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to retrieve this texture.");2400ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER, "Texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");2401ERR_FAIL_COND_V(p_layer >= tex->layers, ERR_INVALID_PARAMETER);24022403// Clear the texture if the driver requires it during its first use.2404_texture_check_pending_clear(p_texture, tex);24052406_check_transfer_worker_texture(tex);24072408if (_texture_make_mutable(tex, p_texture)) {2409// The texture must be mutable to be used as a copy source due to layout transitions.2410draw_graph.add_synchronization();2411}24122413TextureGetDataRequest get_data_request;2414get_data_request.callback = p_callback;2415get_data_request.frame_local_index = frames[frame].download_buffer_texture_copy_regions.size();2416get_data_request.width = tex->width;2417get_data_request.height = tex->height;2418get_data_request.depth = tex->depth;2419get_data_request.format = tex->format;2420get_data_request.mipmaps = tex->mipmaps;24212422uint32_t block_w, block_h;2423get_compressed_image_format_block_dimensions(tex->format, block_w, block_h);24242425uint32_t pixel_size = get_image_format_pixel_size(tex->format);2426uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(tex->format);24272428uint32_t w, h, d;2429uint32_t required_align = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT);2430uint32_t pitch_step = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP);2431uint32_t region_size = texture_download_region_size_px;2432uint32_t logic_w = tex->width;2433uint32_t logic_h = tex->height;2434uint32_t mipmap_offset = 0;2435uint32_t block_write_offset;2436uint32_t block_write_amount;2437StagingRequiredAction required_action;2438for (uint32_t i = 0; i < tex->mipmaps; i++) {2439uint32_t image_total = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1, &w, &h, &d);2440uint32_t tight_mip_size = image_total - mipmap_offset;2441for (uint32_t z = 0; z < d; z++) {2442for (uint32_t y = 0; y < h; y += region_size) {2443for (uint32_t x = 0; x < w; x += region_size) {2444uint32_t region_w = MIN(region_size, w - x);2445uint32_t region_h = MIN(region_size, h - y);2446ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);2447ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);24482449uint32_t region_logic_w = MIN(region_size, logic_w - x);2450uint32_t region_logic_h = MIN(region_size, logic_h - y);2451uint32_t region_pitch = (region_w * pixel_size * block_w) >> pixel_rshift;2452region_pitch = STEPIFY(region_pitch, pitch_step);24532454uint32_t to_allocate = region_pitch * region_h;2455Error err = _staging_buffer_allocate(download_staging_buffers, to_allocate, required_align, block_write_offset, block_write_amount, required_action, false);2456ERR_FAIL_COND_V(err, ERR_CANT_CREATE);24572458const bool flush_frames = (get_data_request.frame_local_count > 0) && required_action == STAGING_REQUIRED_ACTION_FLUSH_AND_STALL_ALL;2459if (flush_frames) {2460for (uint32_t j = 0; j < get_data_request.frame_local_count; j++) {2461uint32_t local_index = get_data_request.frame_local_index + j;2462draw_graph.add_texture_get_data(tex->driver_id, tex->draw_tracker, frames[frame].download_texture_staging_buffers[local_index], frames[frame].download_buffer_texture_copy_regions[local_index]);2463}2464}24652466_staging_buffer_execute_required_action(download_staging_buffers, required_action);24672468if (flush_frames) {2469get_data_request.frame_local_count = 0;2470get_data_request.frame_local_index = frames[frame].download_buffer_texture_copy_regions.size();2471}24722473RDD::BufferTextureCopyRegion copy_region;2474copy_region.buffer_offset = block_write_offset;2475copy_region.row_pitch = region_pitch;2476copy_region.texture_subresource.aspect = tex->read_aspect_flags.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT) ? RDD::TEXTURE_ASPECT_DEPTH : RDD::TEXTURE_ASPECT_COLOR;2477copy_region.texture_subresource.mipmap = i;2478copy_region.texture_subresource.layer = p_layer;2479copy_region.texture_offset = Vector3i(x, y, z);2480copy_region.texture_region_size = Vector3i(region_logic_w, region_logic_h, 1);2481frames[frame].download_texture_staging_buffers.push_back(download_staging_buffers.blocks[download_staging_buffers.current].driver_id);2482frames[frame].download_buffer_texture_copy_regions.push_back(copy_region);2483frames[frame].download_texture_mipmap_offsets.push_back(mipmap_offset + (tight_mip_size / d) * z);2484get_data_request.frame_local_count++;24852486download_staging_buffers.blocks.write[download_staging_buffers.current].fill_amount = block_write_offset + block_write_amount;2487}2488}2489}24902491mipmap_offset = image_total;2492logic_w = MAX(1u, logic_w >> 1);2493logic_h = MAX(1u, logic_h >> 1);2494}24952496if (get_data_request.frame_local_count > 0) {2497for (uint32_t i = 0; i < get_data_request.frame_local_count; i++) {2498uint32_t local_index = get_data_request.frame_local_index + i;2499draw_graph.add_texture_get_data(tex->driver_id, tex->draw_tracker, frames[frame].download_texture_staging_buffers[local_index], frames[frame].download_buffer_texture_copy_regions[local_index]);2500}25012502frames[frame].download_texture_get_data_requests.push_back(get_data_request);2503}25042505return OK;2506}25072508bool RenderingDevice::texture_is_shared(RID p_texture) {2509ERR_RENDER_THREAD_GUARD_V(false);25102511Texture *tex = texture_owner.get_or_null(p_texture);2512ERR_FAIL_NULL_V(tex, false);2513return tex->owner.is_valid();2514}25152516bool RenderingDevice::texture_is_valid(RID p_texture) {2517ERR_RENDER_THREAD_GUARD_V(false);25182519return texture_owner.owns(p_texture);2520}25212522RD::TextureFormat RenderingDevice::texture_get_format(RID p_texture) {2523ERR_RENDER_THREAD_GUARD_V(TextureFormat());25242525Texture *tex = texture_owner.get_or_null(p_texture);2526ERR_FAIL_NULL_V(tex, TextureFormat());25272528TextureFormat tf;25292530tf.format = tex->format;2531tf.width = tex->width;2532tf.height = tex->height;2533tf.depth = tex->depth;2534tf.array_layers = tex->layers;2535tf.mipmaps = tex->mipmaps;2536tf.texture_type = tex->type;2537tf.samples = tex->samples;2538tf.usage_bits = tex->usage_flags;2539tf.shareable_formats = tex->allowed_shared_formats;2540tf.is_resolve_buffer = tex->is_resolve_buffer;2541tf.is_discardable = tex->is_discardable;25422543return tf;2544}25452546Size2i RenderingDevice::texture_size(RID p_texture) {2547ERR_RENDER_THREAD_GUARD_V(Size2i());25482549Texture *tex = texture_owner.get_or_null(p_texture);2550ERR_FAIL_NULL_V(tex, Size2i());2551return Size2i(tex->width, tex->height);2552}25532554#ifndef DISABLE_DEPRECATED2555uint64_t RenderingDevice::texture_get_native_handle(RID p_texture) {2556return get_driver_resource(DRIVER_RESOURCE_TEXTURE, p_texture);2557}2558#endif25592560Error RenderingDevice::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer) {2561ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);25622563Texture *src_tex = texture_owner.get_or_null(p_from_texture);2564ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);25652566ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,2567"Source texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");2568ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,2569"Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");25702571uint32_t src_width, src_height, src_depth;2572get_image_format_required_size(src_tex->format, src_tex->width, src_tex->height, src_tex->depth, p_src_mipmap + 1, &src_width, &src_height, &src_depth);25732574ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);2575ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);2576ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);2577ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);2578ERR_FAIL_COND_V(p_src_layer >= src_tex->layers, ERR_INVALID_PARAMETER);25792580Texture *dst_tex = texture_owner.get_or_null(p_to_texture);2581ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER);25822583ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,2584"Destination texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");2585ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,2586"Destination texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be retrieved.");25872588uint32_t dst_width, dst_height, dst_depth;2589get_image_format_required_size(dst_tex->format, dst_tex->width, dst_tex->height, dst_tex->depth, p_dst_mipmap + 1, &dst_width, &dst_height, &dst_depth);25902591ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);2592ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);2593ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);2594ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);2595ERR_FAIL_COND_V(p_dst_layer >= dst_tex->layers, ERR_INVALID_PARAMETER);25962597ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER,2598"Source and destination texture must be of the same type (color or depth).");25992600// Clear the textures if the driver requires it during its first use.2601_texture_check_pending_clear(p_from_texture, src_tex);2602_texture_check_pending_clear(p_to_texture, dst_tex);26032604_check_transfer_worker_texture(src_tex);2605_check_transfer_worker_texture(dst_tex);26062607RDD::TextureCopyRegion copy_region;2608copy_region.src_subresources.aspect = src_tex->read_aspect_flags;2609copy_region.src_subresources.mipmap = p_src_mipmap;2610copy_region.src_subresources.base_layer = p_src_layer;2611copy_region.src_subresources.layer_count = 1;2612copy_region.src_offset = p_from;26132614copy_region.dst_subresources.aspect = dst_tex->read_aspect_flags;2615copy_region.dst_subresources.mipmap = p_dst_mipmap;2616copy_region.dst_subresources.base_layer = p_dst_layer;2617copy_region.dst_subresources.layer_count = 1;2618copy_region.dst_offset = p_to;26192620copy_region.size = p_size;26212622// Indicate the texture will get modified for the shared texture fallback.2623_texture_update_shared_fallback(p_to_texture, dst_tex, true);26242625// The textures must be mutable to be used in the copy operation.2626bool src_made_mutable = _texture_make_mutable(src_tex, p_from_texture);2627bool dst_made_mutable = _texture_make_mutable(dst_tex, p_to_texture);2628if (src_made_mutable || dst_made_mutable) {2629draw_graph.add_synchronization();2630}26312632draw_graph.add_texture_copy(src_tex->driver_id, src_tex->draw_tracker, dst_tex->driver_id, dst_tex->draw_tracker, copy_region);26332634return OK;2635}26362637Error RenderingDevice::texture_resolve_multisample(RID p_from_texture, RID p_to_texture) {2638ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);26392640Texture *src_tex = texture_owner.get_or_null(p_from_texture);2641ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);26422643ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,2644"Source texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");2645ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,2646"Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_FROM_BIT` to be set to be retrieved.");26472648ERR_FAIL_COND_V_MSG(src_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Source texture must be 2D (or a slice of a 3D/Cube texture)");2649ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");26502651Texture *dst_tex = texture_owner.get_or_null(p_to_texture);2652ERR_FAIL_NULL_V(dst_tex, ERR_INVALID_PARAMETER);26532654ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,2655"Destination texture can't be copied while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to copy this texture.");2656ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,2657"Destination texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be retrieved.");26582659ERR_FAIL_COND_V_MSG(dst_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Destination texture must be 2D (or a slice of a 3D/Cube texture).");2660ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");26612662ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");2663ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions.");26642665ERR_FAIL_COND_V_MSG(src_tex->read_aspect_flags != dst_tex->read_aspect_flags, ERR_INVALID_PARAMETER,2666"Source and destination texture must be of the same type (color or depth).");26672668// Indicate the texture will get modified for the shared texture fallback.2669_texture_update_shared_fallback(p_to_texture, dst_tex, true);26702671// Clear the textures if the driver requires it during its first use.2672_texture_check_pending_clear(p_from_texture, src_tex);2673_texture_check_pending_clear(p_to_texture, dst_tex);26742675_check_transfer_worker_texture(src_tex);2676_check_transfer_worker_texture(dst_tex);26772678// The textures must be mutable to be used in the resolve operation.2679bool src_made_mutable = _texture_make_mutable(src_tex, p_from_texture);2680bool dst_made_mutable = _texture_make_mutable(dst_tex, p_to_texture);2681if (src_made_mutable || dst_made_mutable) {2682draw_graph.add_synchronization();2683}26842685draw_graph.add_texture_resolve(src_tex->driver_id, src_tex->draw_tracker, dst_tex->driver_id, dst_tex->draw_tracker, src_tex->base_layer, src_tex->base_mipmap, dst_tex->base_layer, dst_tex->base_mipmap);26862687return OK;2688}26892690void RenderingDevice::texture_set_discardable(RID p_texture, bool p_discardable) {2691ERR_RENDER_THREAD_GUARD();26922693Texture *texture = texture_owner.get_or_null(p_texture);2694ERR_FAIL_NULL(texture);26952696texture->is_discardable = p_discardable;26972698if (texture->draw_tracker != nullptr) {2699texture->draw_tracker->is_discardable = p_discardable;2700}27012702if (texture->shared_fallback != nullptr && texture->shared_fallback->texture_tracker != nullptr) {2703texture->shared_fallback->texture_tracker->is_discardable = p_discardable;2704}2705}27062707bool RenderingDevice::texture_is_discardable(RID p_texture) {2708ERR_RENDER_THREAD_GUARD_V(false);27092710Texture *texture = texture_owner.get_or_null(p_texture);2711ERR_FAIL_NULL_V(texture, false);27122713return texture->is_discardable;2714}27152716Error RenderingDevice::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers) {2717ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);27182719Texture *src_tex = texture_owner.get_or_null(p_texture);2720ERR_FAIL_NULL_V(src_tex, ERR_INVALID_PARAMETER);27212722ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,2723"Source texture can't be cleared while a draw list that uses it as part of a framebuffer is being created. Ensure the draw list is finalized (and that the color/depth texture using it is not set to `RenderingDevice.FINAL_ACTION_CONTINUE`) to clear this texture.");27242725ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);2726ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);27272728ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,2729"Source texture requires the `RenderingDevice.TEXTURE_USAGE_CAN_COPY_TO_BIT` to be set to be cleared.");27302731ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);2732ERR_FAIL_COND_V(p_base_layer + p_layers > src_tex->layers, ERR_INVALID_PARAMETER);27332734// Clear the texture if the driver requires it during its first use.2735_texture_check_pending_clear(p_texture, src_tex);27362737_texture_clear_color(p_texture, src_tex, p_color, p_base_mipmap, p_mipmaps, p_base_layer, p_layers);27382739return OK;2740}27412742bool RenderingDevice::texture_is_format_supported_for_usage(DataFormat p_format, BitField<RenderingDevice::TextureUsageBits> p_usage) const {2743ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);27442745bool cpu_readable = (p_usage & RDD::TEXTURE_USAGE_CPU_READ_BIT);2746BitField<TextureUsageBits> supported = driver->texture_get_usages_supported_by_format(p_format, cpu_readable);2747bool any_unsupported = (((int64_t)supported) | ((int64_t)p_usage)) != ((int64_t)supported);2748return !any_unsupported;2749}27502751/*********************/2752/**** FRAMEBUFFER ****/2753/*********************/27542755RDD::RenderPassID RenderingDevice::_render_pass_create(RenderingDeviceDriver *p_driver, const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, uint32_t p_view_count, VRSMethod p_vrs_method, int32_t p_vrs_attachment, Size2i p_vrs_texel_size, Vector<TextureSamples> *r_samples) {2756// NOTE:2757// Before the refactor to RenderingDevice-RenderingDeviceDriver, there was commented out code to2758// specify dependencies to external subpasses. Since it had been unused for a long timel it wasn't ported2759// to the new architecture.27602761LocalVector<int32_t> attachment_last_pass;2762attachment_last_pass.resize(p_attachments.size());27632764if (p_view_count > 1) {2765const RDD::MultiviewCapabilities &capabilities = p_driver->get_multiview_capabilities();27662767// This only works with multiview!2768ERR_FAIL_COND_V_MSG(!capabilities.is_supported, RDD::RenderPassID(), "Multiview not supported");27692770// Make sure we limit this to the number of views we support.2771ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, RDD::RenderPassID(), "Hardware does not support requested number of views for Multiview render pass");2772}27732774LocalVector<RDD::Attachment> attachments;2775LocalVector<uint32_t> attachment_remap;27762777for (int i = 0; i < p_attachments.size(); i++) {2778if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) {2779attachment_remap.push_back(RDD::AttachmentReference::UNUSED);2780continue;2781}27822783ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, RDD::RenderPassID());2784ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, RDD::RenderPassID());2785ERR_FAIL_COND_V_MSG(!(p_attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT | TEXTURE_USAGE_VRS_ATTACHMENT_BIT)),2786RDD::RenderPassID(), "Texture format for index (" + itos(i) + ") requires an attachment (color, depth-stencil, input or VRS) bit set.");27872788RDD::Attachment description;2789description.format = p_attachments[i].format;2790description.samples = p_attachments[i].samples;27912792// We can setup a framebuffer where we write to our VRS texture to set it up.2793// We make the assumption here that if our texture is actually used as our VRS attachment.2794// It is used as such for each subpass. This is fairly certain seeing the restrictions on subpasses.2795bool is_vrs = (p_attachments[i].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) && i == p_vrs_attachment;2796if (is_vrs) {2797description.load_op = RDD::ATTACHMENT_LOAD_OP_LOAD;2798description.store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;2799description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;2800description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;2801description.initial_layout = _vrs_layout_from_method(p_vrs_method);2802description.final_layout = _vrs_layout_from_method(p_vrs_method);2803} else {2804if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {2805description.load_op = p_load_ops[i];2806description.store_op = p_store_ops[i];2807description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;2808description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;2809description.initial_layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;2810description.final_layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;2811} else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {2812description.load_op = p_load_ops[i];2813description.store_op = p_store_ops[i];2814description.stencil_load_op = p_load_ops[i];2815description.stencil_store_op = p_store_ops[i];2816description.initial_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2817description.final_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2818} else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT) {2819description.load_op = p_load_ops[i];2820description.store_op = p_store_ops[i];2821description.stencil_load_op = p_load_ops[i];2822description.stencil_store_op = p_store_ops[i];2823description.initial_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2824description.final_layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2825} else {2826description.load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;2827description.store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;2828description.stencil_load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;2829description.stencil_store_op = RDD::ATTACHMENT_STORE_OP_DONT_CARE;2830description.initial_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2831description.final_layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2832}2833}28342835attachment_last_pass[i] = -1;2836attachment_remap.push_back(attachments.size());2837attachments.push_back(description);2838}28392840LocalVector<RDD::Subpass> subpasses;2841subpasses.resize(p_passes.size());2842LocalVector<RDD::SubpassDependency> subpass_dependencies;28432844for (int i = 0; i < p_passes.size(); i++) {2845const FramebufferPass *pass = &p_passes[i];2846RDD::Subpass &subpass = subpasses[i];28472848TextureSamples texture_samples = TEXTURE_SAMPLES_1;2849bool is_multisample_first = true;28502851for (int j = 0; j < pass->color_attachments.size(); j++) {2852int32_t attachment = pass->color_attachments[j];2853RDD::AttachmentReference reference;2854if (attachment == ATTACHMENT_UNUSED) {2855reference.attachment = RDD::AttachmentReference::UNUSED;2856reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2857} else {2858ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ").");2859ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment.");2860ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");28612862if (is_multisample_first) {2863texture_samples = p_attachments[attachment].samples;2864is_multisample_first = false;2865} else {2866ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples.");2867}2868reference.attachment = attachment_remap[attachment];2869reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;2870attachment_last_pass[attachment] = i;2871}2872reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;2873subpass.color_references.push_back(reference);2874}28752876for (int j = 0; j < pass->input_attachments.size(); j++) {2877int32_t attachment = pass->input_attachments[j];2878RDD::AttachmentReference reference;2879if (attachment == ATTACHMENT_UNUSED) {2880reference.attachment = RDD::AttachmentReference::UNUSED;2881reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2882} else {2883ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ").");2884ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture.");2885ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");2886reference.attachment = attachment_remap[attachment];2887reference.layout = RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;2888attachment_last_pass[attachment] = i;2889}2890reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;2891subpass.input_references.push_back(reference);2892}28932894if (pass->resolve_attachments.size() > 0) {2895ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), RDD::RenderPassID(), "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ").");2896ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, RDD::RenderPassID(), "Resolve attachments specified, but color attachments are not multisample.");2897}2898for (int j = 0; j < pass->resolve_attachments.size(); j++) {2899int32_t attachment = pass->resolve_attachments[j];2900attachments[attachment].load_op = RDD::ATTACHMENT_LOAD_OP_DONT_CARE;29012902RDD::AttachmentReference reference;2903if (attachment == ATTACHMENT_UNUSED) {2904reference.attachment = RDD::AttachmentReference::UNUSED;2905reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2906} else {2907ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ").");2908ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused.");2909ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture.");2910ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");2911bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;2912ERR_FAIL_COND_V_MSG(multisample, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample.");2913reference.attachment = attachment_remap[attachment];2914reference.layout = RDD::TEXTURE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // RDD::TEXTURE_LAYOUT_SHADER_READ_ONLY_OPTIMAL2915attachment_last_pass[attachment] = i;2916}2917reference.aspect = RDD::TEXTURE_ASPECT_COLOR_BIT;2918subpass.resolve_references.push_back(reference);2919}29202921if (pass->depth_attachment != ATTACHMENT_UNUSED) {2922int32_t attachment = pass->depth_attachment;2923ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment.");2924ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment.");2925ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");2926subpass.depth_stencil_reference.attachment = attachment_remap[attachment];2927subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2928attachment_last_pass[attachment] = i;29292930if (is_multisample_first) {2931texture_samples = p_attachments[attachment].samples;2932is_multisample_first = false;2933} else {2934ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth.");2935}29362937if (pass->depth_resolve_attachment != ATTACHMENT_UNUSED) {2938attachment = pass->depth_resolve_attachment;29392940// As our fallbacks are handled outside of our pass, we should never be setting up a render pass with a depth resolve attachment when not supported.2941ERR_FAIL_COND_V_MSG(!p_driver->has_feature(SUPPORTS_FRAMEBUFFER_DEPTH_RESOLVE), RDD::RenderPassID(), "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), a depth resolve attachment was supplied when driver doesn't support this feature.");29422943ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer depth resolve format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth resolve attachment.");2944ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer depth resolve format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth resolve attachment.");2945ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer depth resolve format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");29462947subpass.depth_resolve_reference.attachment = attachment_remap[attachment];2948subpass.depth_resolve_reference.layout = RDD::TEXTURE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;2949attachment_last_pass[attachment] = i;2950}29512952} else {2953subpass.depth_stencil_reference.attachment = RDD::AttachmentReference::UNUSED;2954subpass.depth_stencil_reference.layout = RDD::TEXTURE_LAYOUT_UNDEFINED;2955}29562957if (p_vrs_method == VRS_METHOD_FRAGMENT_SHADING_RATE && p_vrs_attachment >= 0) {2958int32_t attachment = p_vrs_attachment;2959ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), VRS attachment.");2960ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT), RDD::RenderPassID(), "Invalid framebuffer VRS format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as VRS, but it's not a VRS attachment.");2961ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, RDD::RenderPassID(), "Invalid framebuffer VRS attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");29622963subpass.fragment_shading_rate_reference.attachment = attachment_remap[attachment];2964subpass.fragment_shading_rate_reference.layout = RDD::TEXTURE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL;2965subpass.fragment_shading_rate_texel_size = p_vrs_texel_size;29662967attachment_last_pass[attachment] = i;2968}29692970for (int j = 0; j < pass->preserve_attachments.size(); j++) {2971int32_t attachment = pass->preserve_attachments[j];29722973ERR_FAIL_COND_V_MSG(attachment == ATTACHMENT_UNUSED, RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused.");29742975ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), RDD::RenderPassID(), "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ").");29762977if (attachment_last_pass[attachment] != i) {2978// Preserve can still be used to keep depth or color from being discarded after use.2979attachment_last_pass[attachment] = i;2980subpasses[i].preserve_attachments.push_back(attachment);2981}2982}29832984if (r_samples) {2985r_samples->push_back(texture_samples);2986}29872988if (i > 0) {2989RDD::SubpassDependency dependency;2990dependency.src_subpass = i - 1;2991dependency.dst_subpass = i;2992dependency.src_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);2993dependency.dst_stages = (RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT);2994dependency.src_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);2995dependency.dst_access = (RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | RDD::BARRIER_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | RDD::BARRIER_ACCESS_INPUT_ATTACHMENT_READ_BIT);2996subpass_dependencies.push_back(dependency);2997}2998}29993000RDD::AttachmentReference fragment_density_map_attachment_reference;3001if (p_vrs_method == VRS_METHOD_FRAGMENT_DENSITY_MAP && p_vrs_attachment >= 0) {3002fragment_density_map_attachment_reference.attachment = p_vrs_attachment;3003fragment_density_map_attachment_reference.layout = RDD::TEXTURE_LAYOUT_FRAGMENT_DENSITY_MAP_ATTACHMENT_OPTIMAL;3004}30053006RDD::RenderPassID render_pass = p_driver->render_pass_create(attachments, subpasses, subpass_dependencies, p_view_count, fragment_density_map_attachment_reference);3007ERR_FAIL_COND_V(!render_pass, RDD::RenderPassID());30083009return render_pass;3010}30113012RDD::RenderPassID RenderingDevice::_render_pass_create_from_graph(RenderingDeviceDriver *p_driver, VectorView<RDD::AttachmentLoadOp> p_load_ops, VectorView<RDD::AttachmentStoreOp> p_store_ops, void *p_user_data) {3013DEV_ASSERT(p_driver != nullptr);3014DEV_ASSERT(p_user_data != nullptr);30153016// The graph delegates the creation of the render pass to the user according to the load and store ops that were determined as necessary after3017// resolving the dependencies between commands. This function creates a render pass for the framebuffer accordingly.3018const FramebufferFormatKey *key = (const FramebufferFormatKey *)(p_user_data);3019return _render_pass_create(p_driver, key->attachments, key->passes, p_load_ops, p_store_ops, key->view_count, key->vrs_method, key->vrs_attachment, key->vrs_texel_size);3020}30213022RDG::ResourceUsage RenderingDevice::_vrs_usage_from_method(VRSMethod p_method) {3023switch (p_method) {3024case VRS_METHOD_FRAGMENT_SHADING_RATE:3025return RDG::RESOURCE_USAGE_ATTACHMENT_FRAGMENT_SHADING_RATE_READ;3026case VRS_METHOD_FRAGMENT_DENSITY_MAP:3027return RDG::RESOURCE_USAGE_ATTACHMENT_FRAGMENT_DENSITY_MAP_READ;3028default:3029return RDG::RESOURCE_USAGE_NONE;3030}3031}30323033RDD::PipelineStageBits RenderingDevice::_vrs_stages_from_method(VRSMethod p_method) {3034switch (p_method) {3035case VRS_METHOD_FRAGMENT_SHADING_RATE:3036return RDD::PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT;3037case VRS_METHOD_FRAGMENT_DENSITY_MAP:3038return RDD::PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT;3039default:3040return RDD::PipelineStageBits(0);3041}3042}30433044RDD::TextureLayout RenderingDevice::_vrs_layout_from_method(VRSMethod p_method) {3045switch (p_method) {3046case VRS_METHOD_FRAGMENT_SHADING_RATE:3047return RDD::TEXTURE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL;3048case VRS_METHOD_FRAGMENT_DENSITY_MAP:3049return RDD::TEXTURE_LAYOUT_FRAGMENT_DENSITY_MAP_ATTACHMENT_OPTIMAL;3050default:3051return RDD::TEXTURE_LAYOUT_UNDEFINED;3052}3053}30543055void RenderingDevice::_vrs_detect_method() {3056const RDD::FragmentShadingRateCapabilities &fsr_capabilities = driver->get_fragment_shading_rate_capabilities();3057const RDD::FragmentDensityMapCapabilities &fdm_capabilities = driver->get_fragment_density_map_capabilities();3058if (fsr_capabilities.attachment_supported) {3059vrs_method = VRS_METHOD_FRAGMENT_SHADING_RATE;3060} else if (fdm_capabilities.attachment_supported) {3061vrs_method = VRS_METHOD_FRAGMENT_DENSITY_MAP;3062}30633064switch (vrs_method) {3065case VRS_METHOD_FRAGMENT_SHADING_RATE:3066vrs_format = DATA_FORMAT_R8_UINT;3067vrs_texel_size = Vector2i(16, 16).clamp(fsr_capabilities.min_texel_size, fsr_capabilities.max_texel_size);3068break;3069case VRS_METHOD_FRAGMENT_DENSITY_MAP:3070vrs_format = DATA_FORMAT_R8G8_UNORM;3071vrs_texel_size = Vector2i(32, 32).clamp(fdm_capabilities.min_texel_size, fdm_capabilities.max_texel_size);3072break;3073default:3074break;3075}3076}30773078RD::VRSMethod RenderingDevice::vrs_get_method() const {3079return vrs_method;3080}30813082RD::DataFormat RenderingDevice::vrs_get_format() const {3083return vrs_format;3084}30853086Size2i RenderingDevice::vrs_get_texel_size() const {3087return vrs_texel_size;3088}30893090RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count, int32_t p_fragment_density_map_attachment) {3091FramebufferPass pass;3092for (int i = 0; i < p_format.size(); i++) {3093if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {3094pass.depth_attachment = i;3095} else if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT) {3096pass.depth_resolve_attachment = i;3097} else {3098pass.color_attachments.push_back(i);3099}3100}31013102Vector<FramebufferPass> passes;3103passes.push_back(pass);3104return framebuffer_format_create_multipass(p_format, passes, p_view_count, p_fragment_density_map_attachment);3105}31063107RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, uint32_t p_view_count, int32_t p_vrs_attachment) {3108_THREAD_SAFE_METHOD_31093110FramebufferFormatKey key;3111key.attachments = p_attachments;3112key.passes = p_passes;3113key.view_count = p_view_count;3114key.vrs_method = vrs_method;3115key.vrs_attachment = p_vrs_attachment;3116key.vrs_texel_size = vrs_texel_size;31173118const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);3119if (E) {3120// Exists, return.3121return E->get();3122}31233124Vector<TextureSamples> samples;3125LocalVector<RDD::AttachmentLoadOp> load_ops;3126LocalVector<RDD::AttachmentStoreOp> store_ops;3127for (int64_t i = 0; i < p_attachments.size(); i++) {3128load_ops.push_back(RDD::ATTACHMENT_LOAD_OP_CLEAR);3129store_ops.push_back(RDD::ATTACHMENT_STORE_OP_STORE);3130}31313132RDD::RenderPassID render_pass = _render_pass_create(driver, p_attachments, p_passes, load_ops, store_ops, p_view_count, vrs_method, p_vrs_attachment, vrs_texel_size, &samples); // Actions don't matter for this use case.3133if (!render_pass) { // Was likely invalid.3134return INVALID_ID;3135}31363137FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));3138E = framebuffer_format_cache.insert(key, id);31393140FramebufferFormat fb_format;3141fb_format.E = E;3142fb_format.render_pass = render_pass;3143fb_format.pass_samples = samples;3144fb_format.view_count = p_view_count;3145framebuffer_formats[id] = fb_format;31463147#if PRINT_FRAMEBUFFER_FORMAT3148print_line("FRAMEBUFFER FORMAT:", id, "ATTACHMENTS:", p_attachments.size(), "PASSES:", p_passes.size());3149for (RD::AttachmentFormat attachment : p_attachments) {3150print_line("FORMAT:", attachment.format, "SAMPLES:", attachment.samples, "USAGE FLAGS:", attachment.usage_flags);3151}3152#endif31533154return id;3155}31563157RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_format_create_empty(TextureSamples p_samples) {3158_THREAD_SAFE_METHOD_31593160FramebufferFormatKey key;3161key.passes.push_back(FramebufferPass());31623163const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);3164if (E) {3165// Exists, return.3166return E->get();3167}31683169LocalVector<RDD::Subpass> subpass;3170subpass.resize(1);31713172RDD::RenderPassID render_pass = driver->render_pass_create({}, subpass, {}, 1, RDD::AttachmentReference());3173ERR_FAIL_COND_V(!render_pass, FramebufferFormatID());31743175FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));31763177E = framebuffer_format_cache.insert(key, id);31783179FramebufferFormat fb_format;3180fb_format.E = E;3181fb_format.render_pass = render_pass;3182fb_format.pass_samples.push_back(p_samples);3183framebuffer_formats[id] = fb_format;31843185#if PRINT_FRAMEBUFFER_FORMAT3186print_line("FRAMEBUFFER FORMAT:", id, "ATTACHMENTS: EMPTY");3187#endif31883189return id;3190}31913192RenderingDevice::TextureSamples RenderingDevice::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {3193_THREAD_SAFE_METHOD_31943195HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format);3196ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);3197ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1);31983199return E->value.pass_samples[p_pass];3200}32013202RID RenderingDevice::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {3203_THREAD_SAFE_METHOD_32043205Framebuffer framebuffer;3206framebuffer.format_id = framebuffer_format_create_empty(p_samples);3207ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());3208framebuffer.size = p_size;3209framebuffer.view_count = 1;32103211RDG::FramebufferCache *framebuffer_cache = RDG::framebuffer_cache_create();3212framebuffer_cache->width = p_size.width;3213framebuffer_cache->height = p_size.height;3214framebuffer.framebuffer_cache = framebuffer_cache;32153216RID id = framebuffer_owner.make_rid(framebuffer);3217#ifdef DEV_ENABLED3218set_resource_name(id, "RID:" + itos(id.get_id()));3219#endif32203221// This relies on the fact that HashMap will not change the address of an object after it's been inserted into the container.3222framebuffer_cache->render_pass_creation_user_data = (void *)(&framebuffer_formats[framebuffer.format_id].E->key());32233224return id;3225}32263227RID RenderingDevice::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {3228_THREAD_SAFE_METHOD_32293230FramebufferPass pass;32313232for (int i = 0; i < p_texture_attachments.size(); i++) {3233Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);32343235ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");32363237if (texture != nullptr) {3238_check_transfer_worker_texture(texture);3239}32403241if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {3242pass.depth_attachment = i;3243} else if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT) {3244pass.depth_resolve_attachment = i;3245} else if (texture && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {3246// Prevent the VRS attachment from being added to the color_attachments.3247} else {3248if (texture && texture->is_resolve_buffer) {3249pass.resolve_attachments.push_back(i);3250} else {3251pass.color_attachments.push_back(texture ? i : ATTACHMENT_UNUSED);3252}3253}3254}32553256Vector<FramebufferPass> passes;3257passes.push_back(pass);32583259return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);3260}32613262RID RenderingDevice::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, const Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {3263_THREAD_SAFE_METHOD_32643265Vector<AttachmentFormat> attachments;3266LocalVector<RDD::TextureID> textures;3267LocalVector<RDG::ResourceTracker *> trackers;3268int32_t vrs_attachment = -1;3269attachments.resize(p_texture_attachments.size());3270Size2i size;3271bool size_set = false;3272for (int i = 0; i < p_texture_attachments.size(); i++) {3273AttachmentFormat af;3274Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);3275if (!texture) {3276af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT;3277trackers.push_back(nullptr);3278} else {3279ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");32803281_check_transfer_worker_texture(texture);32823283if (i != 0 && texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {3284// Detect if the texture is the fragment density map and it's not the first attachment.3285vrs_attachment = i;3286}32873288if (!size_set) {3289size.width = texture->width;3290size.height = texture->height;3291size_set = true;3292} else if (texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT) {3293// If this is not the first attachment we assume this is used as the VRS attachment.3294// In this case this texture will be 1/16th the size of the color attachment.3295// So we skip the size check.3296} else {3297ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),3298"All textures in a framebuffer should be the same size.");3299}33003301af.format = texture->format;3302af.samples = texture->samples;3303af.usage_flags = texture->usage_flags;33043305_texture_make_mutable(texture, p_texture_attachments[i]);33063307textures.push_back(texture->driver_id);3308trackers.push_back(texture->draw_tracker);3309}3310attachments.write[i] = af;3311}33123313ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused.");33143315FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count, vrs_attachment);3316if (format_id == INVALID_ID) {3317return RID();3318}33193320ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),3321"The format used to check this framebuffer differs from the intended framebuffer format.");33223323Framebuffer framebuffer;3324framebuffer.format_id = format_id;3325framebuffer.texture_ids = p_texture_attachments;3326framebuffer.size = size;3327framebuffer.view_count = p_view_count;33283329RDG::FramebufferCache *framebuffer_cache = RDG::framebuffer_cache_create();3330framebuffer_cache->width = size.width;3331framebuffer_cache->height = size.height;3332framebuffer_cache->textures = textures;3333framebuffer_cache->trackers = trackers;3334framebuffer.framebuffer_cache = framebuffer_cache;33353336RID id = framebuffer_owner.make_rid(framebuffer);3337#ifdef DEV_ENABLED3338set_resource_name(id, "RID:" + itos(id.get_id()));3339#endif33403341for (int i = 0; i < p_texture_attachments.size(); i++) {3342if (p_texture_attachments[i].is_valid()) {3343_add_dependency(id, p_texture_attachments[i]);3344}3345}33463347// This relies on the fact that HashMap will not change the address of an object after it's been inserted into the container.3348framebuffer_cache->render_pass_creation_user_data = (void *)(&framebuffer_formats[framebuffer.format_id].E->key());33493350return id;3351}33523353RenderingDevice::FramebufferFormatID RenderingDevice::framebuffer_get_format(RID p_framebuffer) {3354_THREAD_SAFE_METHOD_33553356Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);3357ERR_FAIL_NULL_V(framebuffer, INVALID_ID);33583359return framebuffer->format_id;3360}33613362Size2 RenderingDevice::framebuffer_get_size(RID p_framebuffer) {3363_THREAD_SAFE_METHOD_33643365Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);3366ERR_FAIL_NULL_V(framebuffer, Size2(0, 0));33673368return framebuffer->size;3369}33703371bool RenderingDevice::framebuffer_is_valid(RID p_framebuffer) const {3372_THREAD_SAFE_METHOD_33733374return framebuffer_owner.owns(p_framebuffer);3375}33763377void RenderingDevice::framebuffer_set_invalidation_callback(RID p_framebuffer, InvalidationCallback p_callback, void *p_userdata) {3378_THREAD_SAFE_METHOD_33793380Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);3381ERR_FAIL_NULL(framebuffer);33823383framebuffer->invalidated_callback = p_callback;3384framebuffer->invalidated_callback_userdata = p_userdata;3385}33863387/*****************/3388/**** SAMPLER ****/3389/*****************/33903391RID RenderingDevice::sampler_create(const SamplerState &p_state) {3392_THREAD_SAFE_METHOD_33933394ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());3395ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());3396ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());3397ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());3398ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());33993400RDD::SamplerID sampler = driver->sampler_create(p_state);3401ERR_FAIL_COND_V(!sampler, RID());34023403RID id = sampler_owner.make_rid(sampler);3404#ifdef DEV_ENABLED3405set_resource_name(id, "RID:" + itos(id.get_id()));3406#endif3407return id;3408}34093410bool RenderingDevice::sampler_is_format_supported_for_filter(DataFormat p_format, SamplerFilter p_sampler_filter) const {3411_THREAD_SAFE_METHOD_34123413ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);34143415return driver->sampler_is_format_supported_for_filter(p_format, p_sampler_filter);3416}34173418/***********************/3419/**** VERTEX BUFFER ****/3420/***********************/34213422RID RenderingDevice::vertex_buffer_create(uint32_t p_size_bytes, Span<uint8_t> p_data, BitField<BufferCreationBits> p_creation_bits) {3423ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());34243425Buffer buffer;3426buffer.size = p_size_bytes;3427buffer.usage = RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_VERTEX_BIT;3428if (p_creation_bits.has_flag(BUFFER_CREATION_AS_STORAGE_BIT)) {3429buffer.usage.set_flag(RDD::BUFFER_USAGE_STORAGE_BIT);3430}3431if (p_creation_bits.has_flag(BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT)) {3432buffer.usage.set_flag(RDD::BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT);34333434// Persistent buffers expect frequent CPU -> GPU writes, so GPU writes should avoid the same path.3435buffer.usage.clear_flag(RDD::BUFFER_USAGE_TRANSFER_TO_BIT);3436}3437if (p_creation_bits.has_flag(BUFFER_CREATION_DEVICE_ADDRESS_BIT)) {3438buffer.usage.set_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);3439}3440if (p_creation_bits.has_flag(BUFFER_CREATION_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT)) {3441buffer.usage.set_flag(RDD::BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT);3442}3443buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);3444ERR_FAIL_COND_V(!buffer.driver_id, RID());34453446// Vertex buffers are assumed to be immutable unless they don't have initial data or they've been marked for storage explicitly.3447if (p_data.is_empty() || p_creation_bits.has_flag(BUFFER_CREATION_AS_STORAGE_BIT) || p_creation_bits.has_flag(BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT)) {3448buffer.draw_tracker = RDG::resource_tracker_create();3449buffer.draw_tracker->buffer_driver_id = buffer.driver_id;3450}34513452if (p_data.size()) {3453_buffer_initialize(&buffer, p_data);3454}34553456_THREAD_SAFE_LOCK_3457buffer_memory += buffer.size;3458_THREAD_SAFE_UNLOCK_34593460RID id = vertex_buffer_owner.make_rid(buffer);3461#ifdef DEV_ENABLED3462set_resource_name(id, "RID:" + itos(id.get_id()));3463#endif3464return id;3465}34663467// Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated.3468RenderingDevice::VertexFormatID RenderingDevice::vertex_format_create(const Vector<VertexAttribute> &p_vertex_descriptions) {3469_THREAD_SAFE_METHOD_34703471VertexDescriptionKey key;3472key.vertex_formats = p_vertex_descriptions;34733474VertexFormatID *idptr = vertex_format_cache.getptr(key);3475if (idptr) {3476return *idptr;3477}34783479VertexAttributeBindingsMap bindings;3480bool has_implicit = false;3481bool has_explicit = false;3482Vector<VertexAttribute> vertex_descriptions = p_vertex_descriptions;3483HashSet<int> used_locations;3484for (int i = 0; i < vertex_descriptions.size(); i++) {3485VertexAttribute &attr = vertex_descriptions.write[i];3486ERR_CONTINUE(attr.format >= DATA_FORMAT_MAX);3487ERR_FAIL_COND_V(used_locations.has(attr.location), INVALID_ID);34883489ERR_FAIL_COND_V_MSG(get_format_vertex_size(attr.format) == 0, INVALID_ID,3490vformat("Data format for attribute (%d), '%s', is not valid for a vertex array.", attr.location, String(FORMAT_NAMES[attr.format])));34913492if (attr.binding == UINT32_MAX) {3493attr.binding = i; // Implicitly assigned binding3494has_implicit = true;3495} else {3496has_explicit = true;3497}3498ERR_FAIL_COND_V_MSG(!(has_implicit ^ has_explicit), INVALID_ID, "Vertex attributes must use either all explicit or all implicit bindings.");34993500const VertexAttributeBinding *existing = bindings.getptr(attr.binding);3501if (!existing) {3502bindings.insert(attr.binding, VertexAttributeBinding(attr.stride, attr.frequency));3503} else {3504ERR_FAIL_COND_V_MSG(existing->stride != attr.stride, INVALID_ID,3505vformat("Vertex attributes with binding (%d) have an inconsistent stride.", attr.binding));3506ERR_FAIL_COND_V_MSG(existing->frequency != attr.frequency, INVALID_ID,3507vformat("Vertex attributes with binding (%d) have an inconsistent frequency.", attr.binding));3508}35093510used_locations.insert(attr.location);3511}35123513RDD::VertexFormatID driver_id = driver->vertex_format_create(vertex_descriptions, bindings);3514ERR_FAIL_COND_V(!driver_id, 0);35153516VertexFormatID id = (vertex_format_cache.size() | ((int64_t)ID_TYPE_VERTEX_FORMAT << ID_BASE_SHIFT));3517vertex_format_cache[key] = id;3518VertexDescriptionCache &ce = vertex_formats.insert(id, VertexDescriptionCache())->value;3519ce.vertex_formats = vertex_descriptions;3520ce.bindings = std::move(bindings);3521ce.driver_id = driver_id;3522return id;3523}35243525RID RenderingDevice::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers, const Vector<uint64_t> &p_offsets) {3526_THREAD_SAFE_METHOD_35273528ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());3529const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];35303531VertexArray vertex_array;35323533if (p_offsets.is_empty()) {3534vertex_array.offsets.resize_initialized(p_src_buffers.size());3535} else {3536ERR_FAIL_COND_V(p_offsets.size() != p_src_buffers.size(), RID());3537vertex_array.offsets = p_offsets;3538}35393540vertex_array.vertex_count = p_vertex_count;3541vertex_array.description = p_vertex_format;3542vertex_array.max_instances_allowed = 0xFFFFFFFF; // By default as many as you want.3543vertex_array.buffers.resize(p_src_buffers.size());35443545HashSet<RID> unique_buffers;3546unique_buffers.reserve(p_src_buffers.size());35473548for (const VertexAttribute &atf : vd.vertex_formats) {3549ERR_FAIL_COND_V_MSG(atf.binding >= p_src_buffers.size(), RID(), vformat("Vertex attribute location (%d) is missing a buffer for binding (%d).", atf.location, atf.binding));3550RID buf = p_src_buffers[atf.binding];3551ERR_FAIL_COND_V(!vertex_buffer_owner.owns(buf), RID());35523553Buffer *buffer = vertex_buffer_owner.get_or_null(buf);35543555// Validate with buffer.3556{3557uint32_t element_size = get_format_vertex_size(atf.format);3558ERR_FAIL_COND_V(element_size == 0, RID()); // Should never happen since this was prevalidated.35593560if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {3561// Validate size for regular drawing.3562uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;3563ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),3564vformat("Vertex attribute (%d) will read past the end of the buffer.", atf.location));35653566} else {3567// Validate size for instances drawing.3568uint64_t available = buffer->size - atf.offset;3569ERR_FAIL_COND_V_MSG(available < element_size, RID(),3570vformat("Vertex attribute (%d) uses instancing, but it's just too small.", atf.location));35713572uint32_t instances_allowed = available / atf.stride;3573vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);3574}3575}35763577vertex_array.buffers.write[atf.binding] = buffer->driver_id;35783579if (unique_buffers.has(buf)) {3580// No need to add dependencies multiple times.3581continue;3582}35833584unique_buffers.insert(buf);35853586if (buffer->draw_tracker != nullptr) {3587vertex_array.draw_trackers.push_back(buffer->draw_tracker);3588} else {3589vertex_array.untracked_buffers.insert(buf);3590}35913592if (buffer->transfer_worker_index >= 0) {3593vertex_array.transfer_worker_indices.push_back(buffer->transfer_worker_index);3594vertex_array.transfer_worker_operations.push_back(buffer->transfer_worker_operation);3595}3596}35973598RID id = vertex_array_owner.make_rid(vertex_array);3599for (const RID &buf : unique_buffers) {3600_add_dependency(id, buf);3601}36023603return id;3604}36053606RID RenderingDevice::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, Span<uint8_t> p_data, bool p_use_restart_indices, BitField<BufferCreationBits> p_creation_bits) {3607ERR_FAIL_COND_V(p_index_count == 0, RID());36083609IndexBuffer index_buffer;3610index_buffer.format = p_format;3611index_buffer.supports_restart_indices = p_use_restart_indices;3612index_buffer.index_count = p_index_count;3613uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);3614#ifdef DEBUG_ENABLED3615if (p_data.size()) {3616index_buffer.max_index = 0;3617ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),3618"Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");3619const uint8_t *r = p_data.ptr();3620if (p_format == INDEX_BUFFER_FORMAT_UINT16) {3621const uint16_t *index16 = (const uint16_t *)r;3622for (uint32_t i = 0; i < p_index_count; i++) {3623if (p_use_restart_indices && index16[i] == 0xFFFF) {3624continue; // Restart index, ignore.3625}3626index_buffer.max_index = MAX(index16[i], index_buffer.max_index);3627}3628} else {3629const uint32_t *index32 = (const uint32_t *)r;3630for (uint32_t i = 0; i < p_index_count; i++) {3631if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {3632continue; // Restart index, ignore.3633}3634index_buffer.max_index = MAX(index32[i], index_buffer.max_index);3635}3636}3637} else {3638index_buffer.max_index = 0xFFFFFFFF;3639}3640#else3641index_buffer.max_index = 0xFFFFFFFF;3642#endif3643index_buffer.size = size_bytes;3644index_buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_FROM_BIT | RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_INDEX_BIT);3645if (p_creation_bits.has_flag(BUFFER_CREATION_AS_STORAGE_BIT)) {3646index_buffer.usage.set_flag(RDD::BUFFER_USAGE_STORAGE_BIT);3647}3648if (p_creation_bits.has_flag(BUFFER_CREATION_DEVICE_ADDRESS_BIT)) {3649index_buffer.usage.set_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);3650}3651if (p_creation_bits.has_flag(BUFFER_CREATION_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT)) {3652index_buffer.usage.set_flag(RDD::BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT);3653}3654index_buffer.driver_id = driver->buffer_create(index_buffer.size, index_buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);3655ERR_FAIL_COND_V(!index_buffer.driver_id, RID());36563657// Index buffers are assumed to be immutable unless they don't have initial data.3658if (p_data.is_empty()) {3659index_buffer.draw_tracker = RDG::resource_tracker_create();3660index_buffer.draw_tracker->buffer_driver_id = index_buffer.driver_id;3661}36623663if (p_data.size()) {3664_buffer_initialize(&index_buffer, p_data);3665}36663667_THREAD_SAFE_LOCK_3668buffer_memory += index_buffer.size;3669_THREAD_SAFE_UNLOCK_36703671RID id = index_buffer_owner.make_rid(index_buffer);3672#ifdef DEV_ENABLED3673set_resource_name(id, "RID:" + itos(id.get_id()));3674#endif3675return id;3676}36773678RID RenderingDevice::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {3679_THREAD_SAFE_METHOD_36803681ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());36823683IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);36843685ERR_FAIL_COND_V(p_index_count == 0, RID());3686ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());36873688IndexArray index_array;3689index_array.max_index = index_buffer->max_index;3690index_array.driver_id = index_buffer->driver_id;3691index_array.draw_tracker = index_buffer->draw_tracker;3692index_array.offset = p_index_offset;3693index_array.indices = p_index_count;3694index_array.format = index_buffer->format;3695index_array.supports_restart_indices = index_buffer->supports_restart_indices;3696index_array.transfer_worker_index = index_buffer->transfer_worker_index;3697index_array.transfer_worker_operation = index_buffer->transfer_worker_operation;36983699RID id = index_array_owner.make_rid(index_array);3700_add_dependency(id, p_index_buffer);3701return id;3702}37033704/****************/3705/**** SHADER ****/3706/****************/37073708// Keep the values in sync with the `UniformType` enum (file rendering_device_commons.h).3709static const char *SHADER_UNIFORM_NAMES[RenderingDevice::UNIFORM_TYPE_MAX] = {3710"Sampler",3711"CombinedSampler", // UNIFORM_TYPE_SAMPLER_WITH_TEXTURE3712"Texture",3713"Image",3714"TextureBuffer",3715"SamplerTextureBuffer",3716"ImageBuffer",3717"UniformBuffer",3718"StorageBuffer",3719"InputAttachment",3720"UniformBufferDynamic",3721"StorageBufferDynamic",3722};37233724String RenderingDevice::_shader_uniform_debug(RID p_shader, int p_set) {3725String ret;3726const Shader *shader = shader_owner.get_or_null(p_shader);3727ERR_FAIL_NULL_V(shader, String());3728for (int i = 0; i < shader->uniform_sets.size(); i++) {3729if (p_set >= 0 && i != p_set) {3730continue;3731}3732for (int j = 0; j < shader->uniform_sets[i].size(); j++) {3733const ShaderUniform &ui = shader->uniform_sets[i][j];3734if (!ret.is_empty()) {3735ret += "\n";3736}3737ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + SHADER_UNIFORM_NAMES[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length);3738}3739}3740return ret;3741}37423743Vector<uint8_t> RenderingDevice::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {3744const RenderingShaderContainerFormat &container_format = driver->get_shader_container_format();3745Ref<RenderingShaderContainer> shader_container = container_format.create_container();3746ERR_FAIL_COND_V(shader_container.is_null(), Vector<uint8_t>());37473748// Compile shader binary from SPIR-V.3749bool code_compiled = shader_container->set_code_from_spirv(p_shader_name, p_spirv);3750ERR_FAIL_COND_V_MSG(!code_compiled, Vector<uint8_t>(), vformat("Failed to compile code to native for SPIR-V."));37513752return shader_container->to_bytes();3753}37543755RID RenderingDevice::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary, RID p_placeholder) {3756// Immutable samplers :3757// Expanding api when creating shader to allow passing optionally a set of immutable samplers3758// keeping existing api but extending it by sending an empty set.3759Vector<PipelineImmutableSampler> immutable_samplers;3760return shader_create_from_bytecode_with_samplers(p_shader_binary, p_placeholder, immutable_samplers);3761}37623763RID RenderingDevice::shader_create_from_bytecode_with_samplers(const Vector<uint8_t> &p_shader_binary, RID p_placeholder, const Vector<PipelineImmutableSampler> &p_immutable_samplers) {3764_THREAD_SAFE_METHOD_37653766Ref<RenderingShaderContainer> shader_container = driver->get_shader_container_format().create_container();3767ERR_FAIL_COND_V(shader_container.is_null(), RID());37683769bool parsed_container = shader_container->from_bytes(p_shader_binary);3770ERR_FAIL_COND_V_MSG(!parsed_container, RID(), "Failed to parse shader container from binary.");37713772Vector<RDD::ImmutableSampler> driver_immutable_samplers;3773for (const PipelineImmutableSampler &source_sampler : p_immutable_samplers) {3774RDD::ImmutableSampler driver_sampler;3775driver_sampler.type = source_sampler.uniform_type;3776driver_sampler.binding = source_sampler.binding;37773778for (uint32_t j = 0; j < source_sampler.get_id_count(); j++) {3779RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(source_sampler.get_id(j));3780driver_sampler.ids.push_back(*sampler_driver_id);3781}37823783driver_immutable_samplers.append(driver_sampler);3784}37853786RDD::ShaderID shader_id = driver->shader_create_from_container(shader_container, driver_immutable_samplers);3787ERR_FAIL_COND_V(!shader_id, RID());37883789// All good, let's create modules.37903791RID id;3792if (p_placeholder.is_null()) {3793id = shader_owner.make_rid();3794} else {3795id = p_placeholder;3796}37973798Shader *shader = shader_owner.get_or_null(id);3799ERR_FAIL_NULL_V(shader, RID());38003801*((ShaderReflection *)shader) = shader_container->get_shader_reflection();3802shader->name.clear();3803shader->name.append_utf8(shader_container->shader_name);3804shader->driver_id = shader_id;3805shader->layout_hash = driver->shader_get_layout_hash(shader_id);38063807for (int i = 0; i < shader->uniform_sets.size(); i++) {3808uint32_t format = 0; // No format, default.38093810if (shader->uniform_sets[i].size()) {3811// Sort and hash.38123813shader->uniform_sets.write[i].sort();38143815UniformSetFormat usformat;3816usformat.uniforms = shader->uniform_sets[i];3817RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);3818if (E) {3819format = E->get();3820} else {3821format = uniform_set_format_cache.size() + 1;3822uniform_set_format_cache.insert(usformat, format);3823}3824}38253826shader->set_formats.push_back(format);3827}38283829for (ShaderStage stage : shader->stages_vector) {3830switch (stage) {3831case SHADER_STAGE_VERTEX:3832shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT);3833break;3834case SHADER_STAGE_FRAGMENT:3835shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT);3836break;3837case SHADER_STAGE_TESSELATION_CONTROL:3838shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT);3839break;3840case SHADER_STAGE_TESSELATION_EVALUATION:3841shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT);3842break;3843case SHADER_STAGE_COMPUTE:3844shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT);3845break;3846case SHADER_STAGE_RAYGEN:3847case SHADER_STAGE_ANY_HIT:3848case SHADER_STAGE_CLOSEST_HIT:3849case SHADER_STAGE_MISS:3850case SHADER_STAGE_INTERSECTION:3851shader->stage_bits.set_flag(RDD::PIPELINE_STAGE_RAY_TRACING_SHADER_BIT);3852break;3853default:3854DEV_ASSERT(false && "Unknown shader stage.");3855break;3856}3857}38583859#ifdef DEV_ENABLED3860set_resource_name(id, "RID:" + itos(id.get_id()));3861#endif3862return id;3863}38643865void RenderingDevice::shader_destroy_modules(RID p_shader) {3866Shader *shader = shader_owner.get_or_null(p_shader);3867ERR_FAIL_NULL(shader);3868driver->shader_destroy_modules(shader->driver_id);3869}38703871RID RenderingDevice::shader_create_placeholder() {3872_THREAD_SAFE_METHOD_38733874Shader shader;3875return shader_owner.make_rid(shader);3876}38773878uint64_t RenderingDevice::shader_get_vertex_input_attribute_mask(RID p_shader) {3879_THREAD_SAFE_METHOD_38803881const Shader *shader = shader_owner.get_or_null(p_shader);3882ERR_FAIL_NULL_V(shader, 0);3883return shader->vertex_input_mask;3884}38853886/******************/3887/**** UNIFORMS ****/3888/******************/38893890RID RenderingDevice::uniform_buffer_create(uint32_t p_size_bytes, Span<uint8_t> p_data, BitField<BufferCreationBits> p_creation_bits) {3891ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());38923893Buffer buffer;3894buffer.size = p_size_bytes;3895buffer.usage = (RDD::BUFFER_USAGE_TRANSFER_TO_BIT | RDD::BUFFER_USAGE_UNIFORM_BIT);3896if (p_creation_bits.has_flag(BUFFER_CREATION_DEVICE_ADDRESS_BIT)) {3897buffer.usage.set_flag(RDD::BUFFER_USAGE_DEVICE_ADDRESS_BIT);3898}3899if (p_creation_bits.has_flag(BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT)) {3900buffer.usage.set_flag(RDD::BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT);39013902// This is a precaution: Persistent buffers are meant for frequent CPU -> GPU transfers.3903// Writing to this buffer from GPU might cause sync issues if both CPU & GPU try to write at the3904// same time. It's probably fine (since CPU always advances the pointer before writing) but let's3905// stick to the known/intended use cases and scream if we deviate from it.3906buffer.usage.clear_flag(RDD::BUFFER_USAGE_TRANSFER_TO_BIT);3907}3908buffer.driver_id = driver->buffer_create(buffer.size, buffer.usage, RDD::MEMORY_ALLOCATION_TYPE_GPU, frames_drawn);3909ERR_FAIL_COND_V(!buffer.driver_id, RID());39103911// Uniform buffers are assumed to be immutable unless they don't have initial data.3912if (p_data.is_empty()) {3913buffer.draw_tracker = RDG::resource_tracker_create();3914buffer.draw_tracker->buffer_driver_id = buffer.driver_id;3915}39163917if (p_data.size()) {3918_buffer_initialize(&buffer, p_data);3919}39203921_THREAD_SAFE_LOCK_3922buffer_memory += buffer.size;3923_THREAD_SAFE_UNLOCK_39243925RID id = uniform_buffer_owner.make_rid(buffer);3926#ifdef DEV_ENABLED3927set_resource_name(id, "RID:" + itos(id.get_id()));3928#endif3929return id;3930}39313932void RenderingDevice::_uniform_set_update_shared(UniformSet *p_uniform_set) {3933for (UniformSet::SharedTexture shared : p_uniform_set->shared_textures_to_update) {3934Texture *texture = texture_owner.get_or_null(shared.texture);3935ERR_CONTINUE(texture == nullptr);3936_texture_update_shared_fallback(shared.texture, texture, shared.writing);3937}3938}39393940void RenderingDevice::_uniform_set_update_clears(UniformSet *p_uniform_set) {3941if (p_uniform_set->pending_clear_textures.is_empty()) {3942return;3943}39443945for (RID texture_id : p_uniform_set->pending_clear_textures) {3946Texture *texture = texture_owner.get_or_null(texture_id);3947if (texture != nullptr) {3948_texture_check_pending_clear(texture_id, texture);3949}3950}39513952p_uniform_set->pending_clear_textures.clear();3953}39543955RID RenderingDevice::uniform_set_create(const VectorView<RD::Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set, bool p_linear_pool) {3956_THREAD_SAFE_METHOD_39573958ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());39593960Shader *shader = shader_owner.get_or_null(p_shader);3961ERR_FAIL_NULL_V(shader, RID());39623963ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->uniform_sets.size() || shader->uniform_sets[p_shader_set].is_empty(), RID(),3964"Desired set (" + itos(p_shader_set) + ") not used by shader.");3965// See that all sets in shader are satisfied.39663967const Vector<ShaderUniform> &set = shader->uniform_sets[p_shader_set];39683969uint32_t uniform_count = p_uniforms.size();3970const Uniform *uniforms = p_uniforms.ptr();39713972uint32_t set_uniform_count = set.size();3973const ShaderUniform *set_uniforms = set.ptr();39743975LocalVector<RDD::BoundUniform> driver_uniforms;3976driver_uniforms.resize(set_uniform_count);39773978// Used for verification to make sure a uniform set does not use a framebuffer bound texture.3979LocalVector<UniformSet::AttachableTexture> attachable_textures;3980Vector<RDG::ResourceTracker *> draw_trackers;3981Vector<RDG::ResourceUsage> draw_trackers_usage;3982HashMap<RID, RDG::ResourceUsage> untracked_usage;3983Vector<UniformSet::SharedTexture> shared_textures_to_update;3984LocalVector<RID> pending_clear_textures;39853986for (uint32_t i = 0; i < set_uniform_count; i++) {3987const ShaderUniform &set_uniform = set_uniforms[i];3988int uniform_idx = -1;3989for (int j = 0; j < (int)uniform_count; j++) {3990if (uniforms[j].binding == set_uniform.binding) {3991uniform_idx = j;3992break;3993}3994}3995ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),3996"All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + ") was not provided.");39973998const Uniform &uniform = uniforms[uniform_idx];39994000ERR_FAIL_INDEX_V(uniform.uniform_type, RD::UNIFORM_TYPE_MAX, RID());4001ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(), "Shader '" + shader->name + "' Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + SHADER_UNIFORM_NAMES[set_uniform.type] + "', supplied: '" + SHADER_UNIFORM_NAMES[uniform.uniform_type] + "'.");40024003RDD::BoundUniform &driver_uniform = driver_uniforms[i];4004driver_uniform.type = uniform.uniform_type;4005driver_uniform.binding = uniform.binding;40064007// Mark immutable samplers to be skipped when creating uniform set.4008driver_uniform.immutable_sampler = uniform.immutable_sampler;40094010switch (uniform.uniform_type) {4011case UNIFORM_TYPE_SAMPLER: {4012if (uniform.get_id_count() != (uint32_t)set_uniform.length) {4013if (set_uniform.length > 1) {4014ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler elements, so it should be provided equal number of sampler IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4015} else {4016ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ").");4017}4018}40194020for (uint32_t j = 0; j < uniform.get_id_count(); j++) {4021RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j));4022ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");40234024driver_uniform.ids.push_back(*sampler_driver_id);4025}4026} break;4027case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {4028if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {4029if (set_uniform.length > 1) {4030ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler&texture elements, so it should provided twice the amount of IDs (sampler,texture pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4031} else {4032ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");4033}4034}40354036for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {4037RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0));4038ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");40394040RID texture_id = uniform.get_id(j + 1);4041Texture *texture = texture_owner.get_or_null(texture_id);4042ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");40434044ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),4045"Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");40464047if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) {4048UniformSet::AttachableTexture attachable_texture;4049attachable_texture.bind = set_uniform.binding;4050attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1);4051attachable_textures.push_back(attachable_texture);4052}40534054if (texture->pending_clear) {4055pending_clear_textures.push_back(texture_id);4056}40574058RDD::TextureID driver_id = texture->driver_id;4059RDG::ResourceTracker *tracker = texture->draw_tracker;4060if (texture->shared_fallback != nullptr && texture->shared_fallback->texture.id != 0) {4061driver_id = texture->shared_fallback->texture;4062tracker = texture->shared_fallback->texture_tracker;4063shared_textures_to_update.push_back({ false, texture_id });4064}40654066if (tracker != nullptr) {4067draw_trackers.push_back(tracker);4068draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_SAMPLE);4069} else {4070untracked_usage[texture_id] = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;4071}40724073DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));40744075driver_uniform.ids.push_back(*sampler_driver_id);4076driver_uniform.ids.push_back(driver_id);4077_check_transfer_worker_texture(texture);4078}4079} break;4080case UNIFORM_TYPE_TEXTURE: {4081if (uniform.get_id_count() != (uint32_t)set_uniform.length) {4082if (set_uniform.length > 1) {4083ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4084} else {4085ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");4086}4087}40884089for (uint32_t j = 0; j < uniform.get_id_count(); j++) {4090RID texture_id = uniform.get_id(j);4091Texture *texture = texture_owner.get_or_null(texture_id);4092ERR_FAIL_NULL_V_MSG(texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");40934094ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),4095"Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");40964097if ((texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT))) {4098UniformSet::AttachableTexture attachable_texture;4099attachable_texture.bind = set_uniform.binding;4100attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j);4101attachable_textures.push_back(attachable_texture);4102}41034104if (texture->pending_clear) {4105pending_clear_textures.push_back(texture_id);4106}41074108RDD::TextureID driver_id = texture->driver_id;4109RDG::ResourceTracker *tracker = texture->draw_tracker;4110if (texture->shared_fallback != nullptr && texture->shared_fallback->texture.id != 0) {4111driver_id = texture->shared_fallback->texture;4112tracker = texture->shared_fallback->texture_tracker;4113shared_textures_to_update.push_back({ false, texture_id });4114}41154116if (tracker != nullptr) {4117draw_trackers.push_back(tracker);4118draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_SAMPLE);4119} else {4120untracked_usage[texture_id] = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;4121}41224123DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));41244125driver_uniform.ids.push_back(driver_id);4126_check_transfer_worker_texture(texture);4127}4128} break;4129case UNIFORM_TYPE_IMAGE: {4130if (uniform.get_id_count() != (uint32_t)set_uniform.length) {4131if (set_uniform.length > 1) {4132ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4133} else {4134ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");4135}4136}41374138for (uint32_t j = 0; j < uniform.get_id_count(); j++) {4139RID texture_id = uniform.get_id(j);4140Texture *texture = texture_owner.get_or_null(texture_id);41414142ERR_FAIL_NULL_V_MSG(texture, RID(),4143"Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");41444145ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),4146"Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");41474148if (texture->owner.is_null() && texture->shared_fallback != nullptr) {4149shared_textures_to_update.push_back({ true, texture_id });4150}41514152if (texture->pending_clear) {4153pending_clear_textures.push_back(texture_id);4154}41554156if (_texture_make_mutable(texture, texture_id)) {4157// The texture must be mutable as a layout transition will be required.4158draw_graph.add_synchronization();4159}41604161if (texture->draw_tracker != nullptr) {4162draw_trackers.push_back(texture->draw_tracker);41634164if (set_uniform.writable) {4165draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ_WRITE);4166} else {4167draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ);4168}4169}41704171DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));41724173driver_uniform.ids.push_back(texture->driver_id);4174_check_transfer_worker_texture(texture);4175}4176} break;4177case UNIFORM_TYPE_TEXTURE_BUFFER: {4178if (uniform.get_id_count() != (uint32_t)set_uniform.length) {4179if (set_uniform.length > 1) {4180ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") texture buffer elements, so it should be provided equal number of texture buffer IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4181} else {4182ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");4183}4184}41854186for (uint32_t j = 0; j < uniform.get_id_count(); j++) {4187RID buffer_id = uniform.get_id(j);4188Buffer *buffer = texture_buffer_owner.get_or_null(buffer_id);4189ERR_FAIL_NULL_V_MSG(buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");41904191if (set_uniform.writable && _buffer_make_mutable(buffer, buffer_id)) {4192// The buffer must be mutable if it's used for writing.4193draw_graph.add_synchronization();4194}41954196if (buffer->draw_tracker != nullptr) {4197draw_trackers.push_back(buffer->draw_tracker);41984199if (set_uniform.writable) {4200draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ_WRITE);4201} else {4202draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ);4203}4204} else {4205untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ;4206}42074208driver_uniform.ids.push_back(buffer->driver_id);4209_check_transfer_worker_buffer(buffer);4210}4211} break;4212case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {4213if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {4214if (set_uniform.length > 1) {4215ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler buffer elements, so it should provided twice the amount of IDs (sampler,buffer pairs) to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4216} else {4217ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");4218}4219}42204221for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {4222RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(uniform.get_id(j + 0));4223ERR_FAIL_NULL_V_MSG(sampler_driver_id, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");42244225RID buffer_id = uniform.get_id(j + 1);4226Buffer *buffer = texture_buffer_owner.get_or_null(buffer_id);4227ERR_FAIL_NULL_V_MSG(buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");42284229if (buffer->draw_tracker != nullptr) {4230draw_trackers.push_back(buffer->draw_tracker);4231draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ);4232} else {4233untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ;4234}42354236driver_uniform.ids.push_back(*sampler_driver_id);4237driver_uniform.ids.push_back(buffer->driver_id);4238_check_transfer_worker_buffer(buffer);4239}4240} break;4241case UNIFORM_TYPE_IMAGE_BUFFER: {4242// Todo.4243} break;4244case UNIFORM_TYPE_UNIFORM_BUFFER:4245case UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC: {4246ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),4247"Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");42484249RID buffer_id = uniform.get_id(0);4250Buffer *buffer = uniform_buffer_owner.get_or_null(buffer_id);4251ERR_FAIL_NULL_V_MSG(buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");42524253ERR_FAIL_COND_V_MSG(buffer->size < (uint32_t)set_uniform.length, RID(),4254"Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + ") is smaller than size of shader uniform: (" + itos(set_uniform.length) + ").");42554256if (buffer->draw_tracker != nullptr) {4257draw_trackers.push_back(buffer->draw_tracker);4258draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_UNIFORM_BUFFER_READ);4259} else {4260untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_UNIFORM_BUFFER_READ;4261}42624263driver_uniform.ids.push_back(buffer->driver_id);4264_check_transfer_worker_buffer(buffer);4265} break;4266case UNIFORM_TYPE_STORAGE_BUFFER:4267case UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {4268ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),4269"Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");42704271Buffer *buffer = nullptr;42724273RID buffer_id = uniform.get_id(0);4274if (storage_buffer_owner.owns(buffer_id)) {4275buffer = storage_buffer_owner.get_or_null(buffer_id);4276} else if (vertex_buffer_owner.owns(buffer_id)) {4277buffer = vertex_buffer_owner.get_or_null(buffer_id);42784279ERR_FAIL_COND_V_MSG(!(buffer->usage.has_flag(RDD::BUFFER_USAGE_STORAGE_BIT)), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag.");4280}4281ERR_FAIL_NULL_V_MSG(buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");42824283// If 0, then it's sized on link time.4284ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),4285"Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + ") does not match size of shader uniform: (" + itos(set_uniform.length) + ").");42864287if (set_uniform.writable && _buffer_make_mutable(buffer, buffer_id)) {4288// The buffer must be mutable if it's used for writing.4289draw_graph.add_synchronization();4290}42914292if (buffer->draw_tracker != nullptr) {4293draw_trackers.push_back(buffer->draw_tracker);42944295if (set_uniform.writable) {4296draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ_WRITE);4297} else {4298draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ);4299}4300} else {4301untracked_usage[buffer_id] = RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ;4302}43034304driver_uniform.ids.push_back(buffer->driver_id);4305_check_transfer_worker_buffer(buffer);4306} break;4307case UNIFORM_TYPE_INPUT_ATTACHMENT: {4308ERR_FAIL_COND_V_MSG(shader->pipeline_type != PIPELINE_TYPE_RASTERIZATION, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for non-render shader (this is not allowed).");43094310if (uniform.get_id_count() != (uint32_t)set_uniform.length) {4311if (set_uniform.length > 1) {4312ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.get_id_count()) + ").");4313} else {4314ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");4315}4316}43174318for (uint32_t j = 0; j < uniform.get_id_count(); j++) {4319RID texture_id = uniform.get_id(j);4320Texture *texture = texture_owner.get_or_null(texture_id);43214322ERR_FAIL_NULL_V_MSG(texture, RID(),4323"InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");43244325ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),4326"InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");43274328DEV_ASSERT(!texture->owner.is_valid() || texture_owner.get_or_null(texture->owner));43294330driver_uniform.ids.push_back(texture->driver_id);4331_check_transfer_worker_texture(texture);4332}4333} break;4334case UNIFORM_TYPE_ACCELERATION_STRUCTURE: {4335ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),4336"Acceleration structure supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");43374338RID accel_id = uniform.get_id(0);4339AccelerationStructure *accel = acceleration_structure_owner.get_or_null(accel_id);4340ERR_FAIL_NULL_V_MSG(accel, RID(), "Acceleration Structure supplied (binding: " + itos(uniform.binding) + ") is invalid.");43414342if (accel->draw_tracker != nullptr) {4343draw_trackers.push_back(accel->draw_tracker);4344// Acceleration structure is never going to be writable from raytracing shaders4345draw_trackers_usage.push_back(RDG::RESOURCE_USAGE_ACCELERATION_STRUCTURE_READ);4346}43474348driver_uniform.ids.push_back(accel->driver_id);4349} break;4350default: {4351}4352}4353}43544355RDD::UniformSetID driver_uniform_set = driver->uniform_set_create(driver_uniforms, shader->driver_id, p_shader_set, p_linear_pool ? frame : -1);4356ERR_FAIL_COND_V(!driver_uniform_set, RID());43574358UniformSet uniform_set;4359uniform_set.driver_id = driver_uniform_set;4360uniform_set.format = shader->set_formats[p_shader_set];4361uniform_set.attachable_textures = attachable_textures;4362uniform_set.draw_trackers = draw_trackers;4363uniform_set.draw_trackers_usage = draw_trackers_usage;4364uniform_set.untracked_usage = untracked_usage;4365uniform_set.shared_textures_to_update = shared_textures_to_update;4366uniform_set.pending_clear_textures = pending_clear_textures;4367uniform_set.shader_set = p_shader_set;4368uniform_set.shader_id = p_shader;43694370RID id = uniform_set_owner.make_rid(uniform_set);4371#ifdef DEV_ENABLED4372set_resource_name(id, "RID:" + itos(id.get_id()));4373#endif4374// Add dependencies.4375_add_dependency(id, p_shader);4376for (uint32_t i = 0; i < uniform_count; i++) {4377const Uniform &uniform = uniforms[i];4378int id_count = uniform.get_id_count();4379for (int j = 0; j < id_count; j++) {4380_add_dependency(id, uniform.get_id(j));4381}4382}43834384return id;4385}43864387bool RenderingDevice::uniform_set_is_valid(RID p_uniform_set) {4388_THREAD_SAFE_METHOD_43894390return uniform_set_owner.owns(p_uniform_set);4391}43924393void RenderingDevice::uniform_set_set_invalidation_callback(RID p_uniform_set, InvalidationCallback p_callback, void *p_userdata) {4394_THREAD_SAFE_METHOD_43954396UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);4397ERR_FAIL_NULL(us);4398us->invalidated_callback = p_callback;4399us->invalidated_callback_userdata = p_userdata;4400}44014402bool RenderingDevice::uniform_sets_have_linear_pools() const {4403return driver->uniform_sets_have_linear_pools();4404}44054406/*******************/4407/**** PIPELINES ****/4408/*******************/44094410RID RenderingDevice::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {4411// Needs a shader.4412Shader *shader = shader_owner.get_or_null(p_shader);4413ERR_FAIL_NULL_V(shader, RID());4414ERR_FAIL_COND_V_MSG(shader->pipeline_type != PIPELINE_TYPE_RASTERIZATION, RID(),4415"Only render shaders can be used in render pipelines");44164417// Validate pre-raster shader. One of stages must be vertex shader or mesh shader (not implemented yet).4418ERR_FAIL_COND_V_MSG(!shader->stage_bits.has_flag(RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT), RID(), "Pre-raster shader (vertex shader) is not provided for pipeline creation.");44194420FramebufferFormat fb_format;4421{4422_THREAD_SAFE_METHOD_44234424if (p_framebuffer_format == INVALID_ID) {4425// If nothing provided, use an empty one (no attachments).4426p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());4427}4428ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());4429fb_format = framebuffer_formats[p_framebuffer_format];4430}44314432// Validate shader vs. framebuffer.4433{4434ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.E->key().passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds");4435const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];4436uint32_t output_mask = 0;4437for (int i = 0; i < pass.color_attachments.size(); i++) {4438if (pass.color_attachments[i] != ATTACHMENT_UNUSED) {4439output_mask |= 1 << i;4440}4441}4442ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),4443"Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");4444}44454446RDD::VertexFormatID driver_vertex_format;4447if (p_vertex_format != INVALID_ID) {4448// Uses vertices, else it does not.4449ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());4450const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];4451driver_vertex_format = vertex_formats[p_vertex_format].driver_id;44524453// Validate with inputs.4454for (uint32_t i = 0; i < 64; i++) {4455if (!(shader->vertex_input_mask & ((uint64_t)1) << i)) {4456continue;4457}4458bool found = false;4459for (int j = 0; j < vd.vertex_formats.size(); j++) {4460if (vd.vertex_formats[j].location == i) {4461found = true;4462break;4463}4464}44654466ERR_FAIL_COND_V_MSG(!found, RID(),4467"Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");4468}44694470} else {4471ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),4472"Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");4473}44744475ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());44764477ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());44784479if (p_multisample_state.sample_mask.size()) {4480// Use sample mask.4481ERR_FAIL_COND_V((int)TEXTURE_SAMPLES_COUNT[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());4482}44834484ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());44854486ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());4487ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());4488ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());4489ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());44904491ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());4492ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());4493ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());4494ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());44954496ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());44974498const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];4499ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID());4500for (int i = 0; i < pass.color_attachments.size(); i++) {4501if (pass.color_attachments[i] != ATTACHMENT_UNUSED) {4502ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());4503ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());4504ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());45054506ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());4507ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());4508ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());4509}4510}45114512for (int i = 0; i < shader->specialization_constants.size(); i++) {4513const ShaderSpecializationConstant &sc = shader->specialization_constants[i];4514for (int j = 0; j < p_specialization_constants.size(); j++) {4515const PipelineSpecializationConstant &psc = p_specialization_constants[j];4516if (psc.constant_id == sc.constant_id) {4517ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type.");4518break;4519}4520}4521}45224523RenderPipeline pipeline;4524pipeline.driver_id = driver->render_pipeline_create(4525shader->driver_id,4526driver_vertex_format,4527p_render_primitive,4528p_rasterization_state,4529p_multisample_state,4530p_depth_stencil_state,4531p_blend_state,4532pass.color_attachments,4533p_dynamic_state_flags,4534fb_format.render_pass,4535p_for_render_pass,4536p_specialization_constants);4537ERR_FAIL_COND_V(!pipeline.driver_id, RID());45384539if (pipeline_cache_enabled) {4540update_pipeline_cache();4541}45424543pipeline.shader = p_shader;4544pipeline.shader_driver_id = shader->driver_id;4545pipeline.shader_layout_hash = shader->layout_hash;4546pipeline.set_formats = shader->set_formats;4547pipeline.push_constant_size = shader->push_constant_size;4548pipeline.stage_bits = shader->stage_bits;45494550#ifdef DEBUG_ENABLED4551pipeline.validation.dynamic_state = p_dynamic_state_flags;4552pipeline.validation.framebuffer_format = p_framebuffer_format;4553pipeline.validation.render_pass = p_for_render_pass;4554pipeline.validation.vertex_format = p_vertex_format;4555pipeline.validation.uses_restart_indices = p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX;45564557static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {45581, 2, 1, 1, 1, 3, 1, 1, 1, 1, 14559};4560pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];4561static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {45621,45632,45642,45652,45662,45673,45683,45693,45703,45713,45721,4573};4574pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];4575#endif45764577// Create ID to associate with this pipeline.4578RID id = render_pipeline_owner.make_rid(pipeline);4579{4580_THREAD_SAFE_METHOD_45814582#ifdef DEV_ENABLED4583set_resource_name(id, "RID:" + itos(id.get_id()));4584#endif4585// Now add all the dependencies.4586_add_dependency(id, p_shader);4587}45884589return id;4590}45914592bool RenderingDevice::render_pipeline_is_valid(RID p_pipeline) {4593_THREAD_SAFE_METHOD_45944595return render_pipeline_owner.owns(p_pipeline);4596}45974598RID RenderingDevice::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {4599Shader *shader;46004601{4602_THREAD_SAFE_METHOD_46034604// Needs a shader.4605shader = shader_owner.get_or_null(p_shader);4606ERR_FAIL_NULL_V(shader, RID());46074608ERR_FAIL_COND_V_MSG(shader->pipeline_type != PIPELINE_TYPE_COMPUTE, RID(),4609"Non-compute shaders can't be used in compute pipelines");4610}46114612for (int i = 0; i < shader->specialization_constants.size(); i++) {4613const ShaderSpecializationConstant &sc = shader->specialization_constants[i];4614for (int j = 0; j < p_specialization_constants.size(); j++) {4615const PipelineSpecializationConstant &psc = p_specialization_constants[j];4616if (psc.constant_id == sc.constant_id) {4617ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type.");4618break;4619}4620}4621}46224623ComputePipeline pipeline;4624pipeline.driver_id = driver->compute_pipeline_create(shader->driver_id, p_specialization_constants);4625ERR_FAIL_COND_V(!pipeline.driver_id, RID());46264627if (pipeline_cache_enabled) {4628update_pipeline_cache();4629}46304631pipeline.shader = p_shader;4632pipeline.shader_driver_id = shader->driver_id;4633pipeline.shader_layout_hash = shader->layout_hash;4634pipeline.set_formats = shader->set_formats;4635pipeline.push_constant_size = shader->push_constant_size;4636pipeline.local_group_size[0] = shader->compute_local_size[0];4637pipeline.local_group_size[1] = shader->compute_local_size[1];4638pipeline.local_group_size[2] = shader->compute_local_size[2];46394640// Create ID to associate with this pipeline.4641RID id = compute_pipeline_owner.make_rid(pipeline);4642{4643_THREAD_SAFE_METHOD_46444645#ifdef DEV_ENABLED4646set_resource_name(id, "RID:" + itos(id.get_id()));4647#endif4648// Now add all the dependencies.4649_add_dependency(id, p_shader);4650}46514652return id;4653}46544655bool RenderingDevice::compute_pipeline_is_valid(RID p_pipeline) {4656_THREAD_SAFE_METHOD_46574658return compute_pipeline_owner.owns(p_pipeline);4659}46604661RID RenderingDevice::raytracing_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {4662_THREAD_SAFE_METHOD_46634664// Needs a shader.4665Shader *shader = shader_owner.get_or_null(p_shader);4666ERR_FAIL_NULL_V(shader, RID());46674668ERR_FAIL_COND_V_MSG(shader->pipeline_type != PIPELINE_TYPE_RAYTRACING, RID(),4669"Only raytracing shaders can be used in raytracing pipelines");46704671for (int i = 0; i < shader->specialization_constants.size(); i++) {4672const ShaderSpecializationConstant &sc = shader->specialization_constants[i];4673for (int j = 0; j < p_specialization_constants.size(); j++) {4674const PipelineSpecializationConstant &psc = p_specialization_constants[j];4675if (psc.constant_id == sc.constant_id) {4676ERR_FAIL_COND_V_MSG(psc.type != sc.type, RID(), "Specialization constant provided for id (" + itos(sc.constant_id) + ") is of the wrong type.");4677break;4678}4679}4680}46814682RaytracingPipeline pipeline;4683pipeline.driver_id = driver->raytracing_pipeline_create(shader->driver_id, p_specialization_constants);4684ERR_FAIL_COND_V(!pipeline.driver_id, RID());46854686if (pipeline_cache_enabled) {4687update_pipeline_cache();4688}46894690pipeline.shader = p_shader;4691pipeline.shader_driver_id = shader->driver_id;4692pipeline.shader_layout_hash = shader->layout_hash;4693pipeline.set_formats = shader->set_formats;4694pipeline.push_constant_size = shader->push_constant_size;46954696// Create ID to associate with this pipeline.4697RID id = raytracing_pipeline_owner.make_rid(pipeline);4698#ifdef DEV_ENABLED4699set_resource_name(id, "RID:" + itos(id.get_id()));4700#endif4701// Now add all the dependencies.4702_add_dependency(id, p_shader);4703return id;4704}47054706bool RenderingDevice::raytracing_pipeline_is_valid(RID p_pipeline) {4707_THREAD_SAFE_METHOD_47084709return raytracing_pipeline_owner.owns(p_pipeline);4710}47114712/****************/4713/**** SCREEN ****/4714/****************/47154716uint32_t RenderingDevice::_get_swap_chain_desired_count() const {4717return MAX(2U, uint32_t(GLOBAL_GET_CACHED(uint32_t, "rendering/rendering_device/vsync/swapchain_image_count")));4718}47194720Error RenderingDevice::screen_create(DisplayServer::WindowID p_screen) {4721_THREAD_SAFE_METHOD_47224723RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);4724ERR_FAIL_COND_V_MSG(surface == 0, ERR_CANT_CREATE, "A surface was not created for the screen.");47254726HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);4727ERR_FAIL_COND_V_MSG(it != screen_swap_chains.end(), ERR_CANT_CREATE, "A swap chain was already created for the screen.");47284729RDD::SwapChainID swap_chain = driver->swap_chain_create(surface);4730ERR_FAIL_COND_V_MSG(swap_chain.id == 0, ERR_CANT_CREATE, "Unable to create swap chain.");47314732screen_swap_chains[p_screen] = swap_chain;47334734return OK;4735}47364737Error RenderingDevice::screen_prepare_for_drawing(DisplayServer::WindowID p_screen) {4738_THREAD_SAFE_METHOD_47394740// After submitting work, acquire the swapchain image(s).4741HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);4742ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), ERR_CANT_CREATE, "A swap chain was not created for the screen.");47434744// Erase the framebuffer corresponding to this screen from the map in case any of the operations fail.4745screen_framebuffers.erase(p_screen);47464747// If this frame has already queued this swap chain for presentation, we present it and remove it from the pending list.4748uint32_t to_present_index = 0;4749while (to_present_index < frames[frame].swap_chains_to_present.size()) {4750if (frames[frame].swap_chains_to_present[to_present_index] == it->value) {4751driver->command_queue_execute_and_present(present_queue, {}, {}, {}, {}, it->value);4752frames[frame].swap_chains_to_present.remove_at(to_present_index);4753} else {4754to_present_index++;4755}4756}47574758bool resize_required = false;4759RDD::FramebufferID framebuffer = driver->swap_chain_acquire_framebuffer(main_queue, it->value, resize_required);4760if (resize_required) {4761// Flush everything so nothing can be using the swap chain before resizing it.4762_flush_and_stall_for_all_frames();47634764Error err = driver->swap_chain_resize(main_queue, it->value, _get_swap_chain_desired_count());4765if (err != OK) {4766// Resize is allowed to fail silently because the window can be minimized.4767return err;4768}47694770framebuffer = driver->swap_chain_acquire_framebuffer(main_queue, it->value, resize_required);4771}47724773if (framebuffer.id == 0) {4774// Some drivers like NVIDIA are fast enough to invalidate the swap chain between resizing and acquisition (GH-94104).4775// This typically occurs during continuous window resizing operations, especially if done quickly.4776// Allow this to fail silently since it has no visual consequences.4777return ERR_CANT_CREATE;4778}47794780// Store the framebuffer that will be used next to draw to this screen.4781screen_framebuffers[p_screen] = framebuffer;4782frames[frame].swap_chains_to_present.push_back(it->value);47834784return OK;4785}47864787int RenderingDevice::screen_get_width(DisplayServer::WindowID p_screen) const {4788_THREAD_SAFE_METHOD_47894790RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);4791ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");4792return context->surface_get_width(surface);4793}47944795int RenderingDevice::screen_get_height(DisplayServer::WindowID p_screen) const {4796_THREAD_SAFE_METHOD_47974798RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);4799ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");4800return context->surface_get_height(surface);4801}48024803int RenderingDevice::screen_get_pre_rotation_degrees(DisplayServer::WindowID p_screen) const {4804_THREAD_SAFE_METHOD_48054806HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);4807ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), ERR_CANT_CREATE, "A swap chain was not created for the screen.");48084809return driver->swap_chain_get_pre_rotation_degrees(it->value);4810}48114812RenderingDevice::FramebufferFormatID RenderingDevice::screen_get_framebuffer_format(DisplayServer::WindowID p_screen) const {4813_THREAD_SAFE_METHOD_48144815HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);4816ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), INVALID_ID, "Screen was never prepared.");48174818DataFormat format = driver->swap_chain_get_format(it->value);4819ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);48204821AttachmentFormat attachment;4822attachment.format = format;4823attachment.samples = TEXTURE_SAMPLES_1;4824attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;4825Vector<AttachmentFormat> screen_attachment;4826screen_attachment.push_back(attachment);4827return const_cast<RenderingDevice *>(this)->framebuffer_format_create(screen_attachment);4828}48294830Error RenderingDevice::screen_free(DisplayServer::WindowID p_screen) {4831_THREAD_SAFE_METHOD_48324833HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator it = screen_swap_chains.find(p_screen);4834ERR_FAIL_COND_V_MSG(it == screen_swap_chains.end(), FAILED, "Screen was never created.");48354836// Flush everything so nothing can be using the swap chain before erasing it.4837_flush_and_stall_for_all_frames();48384839const DisplayServer::WindowID screen = it->key;4840const RDD::SwapChainID swap_chain = it->value;4841driver->swap_chain_free(swap_chain);4842screen_framebuffers.erase(screen);4843screen_swap_chains.erase(screen);48444845return OK;4846}48474848/*******************/4849/**** DRAW LIST ****/4850/*******************/48514852RenderingDevice::DrawListID RenderingDevice::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {4853ERR_RENDER_THREAD_GUARD_V(INVALID_ID);48544855ERR_FAIL_COND_V_MSG(draw_list.active, INVALID_ID, "Only one draw list can be active at the same time.");4856ERR_FAIL_COND_V_MSG(compute_list.active, INVALID_ID, "Only one draw/compute list can be active at the same time.");4857ERR_FAIL_COND_V_MSG(raytracing_list.active, INVALID_ID, "Only one draw/raytracing list can be active at the same time.");48584859RenderingContextDriver::SurfaceID surface = context->surface_get_from_window(p_screen);4860HashMap<DisplayServer::WindowID, RDD::SwapChainID>::ConstIterator sc_it = screen_swap_chains.find(p_screen);4861HashMap<DisplayServer::WindowID, RDD::FramebufferID>::ConstIterator fb_it = screen_framebuffers.find(p_screen);4862ERR_FAIL_COND_V_MSG(surface == 0, 0, "A surface was not created for the screen.");4863ERR_FAIL_COND_V_MSG(sc_it == screen_swap_chains.end(), INVALID_ID, "Screen was never prepared.");4864ERR_FAIL_COND_V_MSG(fb_it == screen_framebuffers.end(), INVALID_ID, "Framebuffer was never prepared.");48654866Rect2i viewport = Rect2i(0, 0, context->surface_get_width(surface), context->surface_get_height(surface));48674868_draw_list_start(viewport);4869#ifdef DEBUG_ENABLED4870draw_list_framebuffer_format = screen_get_framebuffer_format(p_screen);4871#endif4872draw_list_subpass_count = 1;48734874RDD::RenderPassClearValue clear_value;4875clear_value.color = p_clear_color;48764877RDD::RenderPassID render_pass = driver->swap_chain_get_render_pass(sc_it->value);4878draw_graph.add_draw_list_begin(render_pass, fb_it->value, viewport, RDG::ATTACHMENT_OPERATION_CLEAR, clear_value, RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, RDD::BreadcrumbMarker::BLIT_PASS, split_swapchain_into_its_own_cmd_buffer);48794880draw_graph.add_draw_list_set_viewport(viewport);4881draw_graph.add_draw_list_set_scissor(viewport);48824883return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;4884}48854886RenderingDevice::DrawListID RenderingDevice::_draw_list_begin_bind(RID p_framebuffer, BitField<DrawFlags> p_draw_flags, const Vector<Color> &p_clear_color_values, float p_clear_depth_value, uint32_t p_clear_stencil_value, const Rect2 &p_region, uint32_t p_breadcrumb) {4887return draw_list_begin(p_framebuffer, p_draw_flags, p_clear_color_values, p_clear_depth_value, p_clear_stencil_value, p_region, p_breadcrumb);4888}48894890RenderingDevice::DrawListID RenderingDevice::draw_list_begin(RID p_framebuffer, BitField<DrawFlags> p_draw_flags, VectorView<Color> p_clear_color_values, float p_clear_depth_value, uint32_t p_clear_stencil_value, const Rect2 &p_region, uint32_t p_breadcrumb) {4891ERR_RENDER_THREAD_GUARD_V(INVALID_ID);48924893ERR_FAIL_COND_V_MSG(draw_list.active, INVALID_ID, "Only one draw list can be active at the same time.");48944895Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);4896ERR_FAIL_NULL_V(framebuffer, INVALID_ID);48974898const FramebufferFormatKey &framebuffer_key = framebuffer_formats[framebuffer->format_id].E->key();4899Point2i viewport_offset;4900Point2i viewport_size = framebuffer->size;49014902if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { // Check custom region.4903Rect2i viewport(viewport_offset, viewport_size);4904Rect2i regioni = p_region;4905if (!((regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&4906((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&4907((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y)))) {4908ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");4909}49104911viewport_offset = regioni.position;4912viewport_size = regioni.size;4913}49144915thread_local LocalVector<RDG::AttachmentOperation> operations;4916thread_local LocalVector<RDD::RenderPassClearValue> clear_values;4917thread_local LocalVector<RDG::ResourceTracker *> resource_trackers;4918thread_local LocalVector<RDG::ResourceUsage> resource_usages;4919BitField<RDD::PipelineStageBits> stages = {};4920operations.resize(framebuffer->texture_ids.size());4921clear_values.resize(framebuffer->texture_ids.size());4922resource_trackers.clear();4923resource_usages.clear();4924stages.clear();49254926uint32_t color_index = 0;4927for (int i = 0; i < framebuffer->texture_ids.size(); i++) {4928RID texture_rid = framebuffer->texture_ids[i];4929Texture *texture = texture_owner.get_or_null(texture_rid);4930if (texture == nullptr) {4931operations[i] = RDG::ATTACHMENT_OPERATION_DEFAULT;4932clear_values[i] = RDD::RenderPassClearValue();4933continue;4934}49354936// Clear the texture if the driver requires it during its first use.4937_texture_check_pending_clear(texture_rid, texture);49384939// Indicate the texture will get modified for the shared texture fallback.4940_texture_update_shared_fallback(texture_rid, texture, true);49414942RDG::AttachmentOperation operation = RDG::ATTACHMENT_OPERATION_DEFAULT;4943RDD::RenderPassClearValue clear_value;4944if (framebuffer_key.vrs_attachment == i && (texture->usage_flags & TEXTURE_USAGE_VRS_ATTACHMENT_BIT)) {4945resource_trackers.push_back(texture->draw_tracker);4946resource_usages.push_back(_vrs_usage_from_method(framebuffer_key.vrs_method));4947stages.set_flag(_vrs_stages_from_method(framebuffer_key.vrs_method));4948} else if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {4949if (p_draw_flags.has_flag(DrawFlags(DRAW_CLEAR_COLOR_0 << color_index))) {4950ERR_FAIL_COND_V_MSG(color_index >= p_clear_color_values.size(), INVALID_ID, vformat("Color texture (%d) was specified to be cleared but no color value was provided.", color_index));4951operation = RDG::ATTACHMENT_OPERATION_CLEAR;4952clear_value.color = p_clear_color_values[color_index];4953} else if (p_draw_flags.has_flag(DrawFlags(DRAW_IGNORE_COLOR_0 << color_index))) {4954operation = RDG::ATTACHMENT_OPERATION_IGNORE;4955}49564957resource_trackers.push_back(texture->draw_tracker);4958resource_usages.push_back(RDG::RESOURCE_USAGE_ATTACHMENT_COLOR_READ_WRITE);4959stages.set_flag(RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);4960color_index++;4961} else if (texture->usage_flags & (TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT)) {4962if (p_draw_flags.has_flag(DRAW_CLEAR_DEPTH) || p_draw_flags.has_flag(DRAW_CLEAR_STENCIL)) {4963operation = RDG::ATTACHMENT_OPERATION_CLEAR;4964clear_value.depth = p_clear_depth_value;4965clear_value.stencil = p_clear_stencil_value;4966} else if (p_draw_flags.has_flag(DRAW_IGNORE_DEPTH) || p_draw_flags.has_flag(DRAW_IGNORE_STENCIL)) {4967operation = RDG::ATTACHMENT_OPERATION_IGNORE;4968}49694970resource_trackers.push_back(texture->draw_tracker);4971resource_usages.push_back(RDG::RESOURCE_USAGE_ATTACHMENT_DEPTH_STENCIL_READ_WRITE);4972stages.set_flag(RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT);4973stages.set_flag(RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT);4974}49754976operations[i] = operation;4977clear_values[i] = clear_value;4978}49794980draw_graph.add_draw_list_begin(framebuffer->framebuffer_cache, Rect2i(viewport_offset, viewport_size), operations, clear_values, stages, p_breadcrumb);4981draw_graph.add_draw_list_usages(resource_trackers, resource_usages);49824983// Mark textures as bound.4984draw_list_bound_textures.clear();49854986for (int i = 0; i < framebuffer->texture_ids.size(); i++) {4987Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);4988if (texture == nullptr) {4989continue;4990}49914992texture->bound = true;4993draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);4994}49954996_draw_list_start(Rect2i(viewport_offset, viewport_size));4997#ifdef DEBUG_ENABLED4998draw_list_framebuffer_format = framebuffer->format_id;4999#endif5000draw_list_current_subpass = 0;5001draw_list_subpass_count = framebuffer_key.passes.size();50025003Rect2i viewport_rect(viewport_offset, viewport_size);5004draw_graph.add_draw_list_set_viewport(viewport_rect);5005draw_graph.add_draw_list_set_scissor(viewport_rect);50065007return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;5008}50095010#ifndef DISABLE_DEPRECATED5011Error RenderingDevice::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {5012ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Deprecated. Split draw lists are used automatically by RenderingDevice.");5013}5014#endif50155016void RenderingDevice::draw_list_set_blend_constants(DrawListID p_list, const Color &p_color) {5017ERR_RENDER_THREAD_GUARD();50185019ERR_FAIL_COND(!draw_list.active);50205021draw_graph.add_draw_list_set_blend_constants(p_color);5022}50235024void RenderingDevice::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {5025ERR_RENDER_THREAD_GUARD();50265027ERR_FAIL_COND(!draw_list.active);50285029const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);5030ERR_FAIL_NULL(pipeline);5031#ifdef DEBUG_ENABLED5032ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);5033#endif50345035if (p_render_pipeline == draw_list.state.pipeline) {5036return; // Redundant state, return.5037}50385039draw_list.state.pipeline = p_render_pipeline;50405041draw_graph.add_draw_list_bind_pipeline(pipeline->driver_id, pipeline->stage_bits);50425043if (draw_list.state.pipeline_shader != pipeline->shader) {5044// Shader changed, so descriptor sets may become incompatible.50455046uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.5047draw_list.state.set_count = MAX(draw_list.state.set_count, pcount);5048const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.50495050uint32_t first_invalid_set = UINT32_MAX; // All valid by default.5051if (pipeline->push_constant_size != draw_list.state.pipeline_push_constant_size) {5052// All sets must be invalidated as the pipeline layout is not compatible if the push constant range is different.5053draw_list.state.pipeline_push_constant_size = pipeline->push_constant_size;5054first_invalid_set = 0;5055} else {5056switch (driver->api_trait_get(RDD::API_TRAIT_SHADER_CHANGE_INVALIDATION)) {5057case RDD::SHADER_CHANGE_INVALIDATION_ALL_BOUND_UNIFORM_SETS: {5058first_invalid_set = 0;5059} break;5060case RDD::SHADER_CHANGE_INVALIDATION_INCOMPATIBLE_SETS_PLUS_CASCADE: {5061for (uint32_t i = 0; i < pcount; i++) {5062if (draw_list.state.sets[i].pipeline_expected_format != pformats[i]) {5063first_invalid_set = i;5064break;5065}5066}5067} break;5068case RDD::SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH: {5069if (draw_list.state.pipeline_shader_layout_hash != pipeline->shader_layout_hash) {5070first_invalid_set = 0;5071}5072} break;5073}5074}50755076if (pipeline->push_constant_size) {5077#ifdef DEBUG_ENABLED5078draw_list.validation.pipeline_push_constant_supplied = false;5079#endif5080}50815082for (uint32_t i = 0; i < pcount; i++) {5083draw_list.state.sets[i].bound = draw_list.state.sets[i].bound && i < first_invalid_set;5084draw_list.state.sets[i].pipeline_expected_format = pformats[i];5085}50865087for (uint32_t i = pcount; i < draw_list.state.set_count; i++) {5088// Unbind the ones above (not used) if exist.5089draw_list.state.sets[i].bound = false;5090}50915092draw_list.state.set_count = pcount; // Update set count.50935094draw_list.state.pipeline_shader = pipeline->shader;5095draw_list.state.pipeline_shader_driver_id = pipeline->shader_driver_id;5096draw_list.state.pipeline_shader_layout_hash = pipeline->shader_layout_hash;5097}50985099#ifdef DEBUG_ENABLED5100// Update render pass pipeline info.5101draw_list.validation.pipeline_active = true;5102draw_list.validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;5103draw_list.validation.pipeline_vertex_format = pipeline->validation.vertex_format;5104draw_list.validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;5105draw_list.validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;5106draw_list.validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;5107draw_list.validation.pipeline_push_constant_size = pipeline->push_constant_size;5108#endif5109}51105111void RenderingDevice::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {5112ERR_RENDER_THREAD_GUARD();51135114#ifdef DEBUG_ENABLED5115ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS,5116"Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ").");5117#endif51185119ERR_FAIL_COND(!draw_list.active);51205121const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);5122ERR_FAIL_NULL(uniform_set);51235124if (p_index > draw_list.state.set_count) {5125draw_list.state.set_count = p_index;5126}51275128draw_list.state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer.5129draw_list.state.sets[p_index].bound = false; // Needs rebind.5130draw_list.state.sets[p_index].uniform_set_format = uniform_set->format;5131draw_list.state.sets[p_index].uniform_set = p_uniform_set;51325133#ifdef DEBUG_ENABLED5134{ // Validate that textures bound are not attached as framebuffer bindings.5135uint32_t attachable_count = uniform_set->attachable_textures.size();5136const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();5137uint32_t bound_count = draw_list_bound_textures.size();5138const RID *bound_ptr = draw_list_bound_textures.ptr();5139for (uint32_t i = 0; i < attachable_count; i++) {5140for (uint32_t j = 0; j < bound_count; j++) {5141ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],5142"Attempted to use the same texture in framebuffer attachment and a uniform (set: " + itos(p_index) + ", binding: " + itos(attachable_ptr[i].bind) + "), this is not allowed.");5143}5144}5145}5146#endif5147}51485149void RenderingDevice::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {5150ERR_RENDER_THREAD_GUARD();51515152ERR_FAIL_COND(!draw_list.active);51535154VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);5155ERR_FAIL_NULL(vertex_array);51565157if (draw_list.state.vertex_array == p_vertex_array) {5158return; // Already set.5159}51605161_check_transfer_worker_vertex_array(vertex_array);51625163draw_list.state.vertex_array = p_vertex_array;51645165#ifdef DEBUG_ENABLED5166draw_list.validation.vertex_format = vertex_array->description;5167draw_list.validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;5168#endif5169draw_list.validation.vertex_array_size = vertex_array->vertex_count;51705171draw_graph.add_draw_list_bind_vertex_buffers(vertex_array->buffers, vertex_array->offsets);51725173for (int i = 0; i < vertex_array->draw_trackers.size(); i++) {5174draw_graph.add_draw_list_usage(vertex_array->draw_trackers[i], RDG::RESOURCE_USAGE_VERTEX_BUFFER_READ);5175}5176}51775178void RenderingDevice::draw_list_bind_vertex_buffers_format(DrawListID p_list, VertexFormatID p_vertex_format, uint32_t p_vertex_count, const Span<RID> &p_vertex_buffers, const Span<uint64_t> &p_offsets) {5179ERR_RENDER_THREAD_GUARD();51805181ERR_FAIL_COND(!draw_list.active);51825183const VertexDescriptionCache *vertex_description = vertex_formats.getptr(p_vertex_format);5184ERR_FAIL_NULL_MSG(vertex_description, "Supplied vertex format does not exist.");51855186Span<uint64_t> offsets_span = p_offsets;5187FixedVector<uint64_t, 32> offsets;5188if (offsets_span.is_empty()) {5189offsets.resize_initialized(p_vertex_buffers.size());5190offsets_span = offsets;5191} else {5192ERR_FAIL_COND_MSG(offsets_span.size() != p_vertex_buffers.size(),5193"Number of vertex buffer offsets (" + itos(offsets_span.size()) + ") does not match number of vertex buffers (" + itos(p_vertex_buffers.size()) + ").");5194}51955196FixedVector<RDD::BufferID, 32> driver_buffers;5197driver_buffers.resize_initialized(p_vertex_buffers.size());51985199FixedVector<RDG::ResourceTracker *, 32> draw_trackers;52005201#if DEBUG_ENABLED5202uint32_t max_instances_allowed = 0xFFFFFFFF;5203#endif52045205for (uint32_t i = 0; i < p_vertex_buffers.size(); i++) {5206RID buffer_rid = p_vertex_buffers[i];5207if (buffer_rid.is_null()) {5208// The buffer array can be sparse.5209continue;5210}5211ERR_FAIL_COND_MSG(!vertex_buffer_owner.owns(buffer_rid), "Vertex buffer at index " + itos(i) + " is invalid.");52125213Buffer *buffer = vertex_buffer_owner.get_or_null(buffer_rid);5214ERR_FAIL_NULL(buffer);52155216_check_transfer_worker_buffer(buffer);52175218#if DEBUG_ENABLED5219uint64_t binding_offset = offsets_span[i];5220ERR_FAIL_COND_MSG(binding_offset > buffer->size, "Vertex buffer offset for attachment (" + itos(i) + ") exceeds buffer size.");52215222const VertexAttribute &attribute = vertex_description->vertex_formats[i];5223uint32_t element_size = get_format_vertex_size(attribute.format);5224ERR_FAIL_COND_MSG(element_size == 0, "Vertex attribute format for attachment (" + itos(i) + ") is invalid.");52255226uint64_t attribute_offset = binding_offset + attribute.offset;5227ERR_FAIL_COND_MSG(attribute_offset > buffer->size, "Vertex attribute offset for attachment (" + itos(i) + ") exceeds buffer size.");5228ERR_FAIL_COND_MSG(attribute_offset + element_size > buffer->size,5229"Vertex buffer (" + itos(i) + ") will read past the end of the buffer.");52305231if (attribute.frequency == VERTEX_FREQUENCY_VERTEX) {5232ERR_FAIL_COND_MSG(p_vertex_count == 0, "Vertex count must be greater than 0 when binding vertex buffers.");52335234uint64_t required_size = attribute_offset + element_size;5235if (p_vertex_count > 1) {5236required_size += uint64_t(attribute.stride) * (uint64_t(p_vertex_count) - 1);5237}52385239ERR_FAIL_COND_MSG(required_size > buffer->size,5240"Vertex buffer (" + itos(i) + ") will read past the end of the buffer.");5241} else {5242uint64_t available = buffer->size - attribute_offset;5243ERR_FAIL_COND_MSG(available < element_size,5244"Vertex buffer (" + itos(i) + ") uses instancing, but it's just too small.");52455246uint32_t instances_allowed = attribute.stride == 0 ? 0 : uint32_t(buffer->size / attribute.stride);5247max_instances_allowed = MIN(instances_allowed, max_instances_allowed);5248}5249#endif52505251driver_buffers[i] = buffer->driver_id;52525253if (buffer->draw_tracker != nullptr) {5254draw_trackers.push_back(buffer->draw_tracker);5255}5256}52575258draw_list.state.vertex_array = RID();52595260draw_graph.add_draw_list_bind_vertex_buffers(driver_buffers, offsets_span);52615262for (RDG::ResourceTracker *tracker : draw_trackers) {5263draw_graph.add_draw_list_usage(tracker, RDG::RESOURCE_USAGE_VERTEX_BUFFER_READ);5264}52655266draw_list.validation.vertex_array_size = p_vertex_count;52675268#ifdef DEBUG_ENABLED5269draw_list.validation.vertex_format = p_vertex_format;5270draw_list.validation.vertex_max_instances_allowed = max_instances_allowed;5271#endif5272}52735274void RenderingDevice::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {5275ERR_RENDER_THREAD_GUARD();52765277ERR_FAIL_COND(!draw_list.active);52785279IndexArray *index_array = index_array_owner.get_or_null(p_index_array);5280ERR_FAIL_NULL(index_array);52815282if (draw_list.state.index_array == p_index_array) {5283return; // Already set.5284}52855286_check_transfer_worker_index_array(index_array);52875288draw_list.state.index_array = p_index_array;5289#ifdef DEBUG_ENABLED5290draw_list.validation.index_array_max_index = index_array->max_index;5291#endif5292draw_list.validation.index_array_count = index_array->indices;52935294const uint64_t offset_bytes = index_array->offset * (index_array->format == INDEX_BUFFER_FORMAT_UINT16 ? sizeof(uint16_t) : sizeof(uint32_t));5295draw_graph.add_draw_list_bind_index_buffer(index_array->driver_id, index_array->format, offset_bytes);52965297if (index_array->draw_tracker != nullptr) {5298draw_graph.add_draw_list_usage(index_array->draw_tracker, RDG::RESOURCE_USAGE_INDEX_BUFFER_READ);5299}5300}53015302void RenderingDevice::draw_list_set_line_width(DrawListID p_list, float p_width) {5303ERR_RENDER_THREAD_GUARD();53045305ERR_FAIL_COND(!draw_list.active);53065307draw_graph.add_draw_list_set_line_width(p_width);5308}53095310void RenderingDevice::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {5311ERR_RENDER_THREAD_GUARD();53125313ERR_FAIL_COND(!draw_list.active);53145315#ifdef DEBUG_ENABLED5316ERR_FAIL_COND_MSG(p_data_size != draw_list.validation.pipeline_push_constant_size,5317"This render pipeline requires (" + itos(draw_list.validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");5318#endif53195320draw_graph.add_draw_list_set_push_constant(draw_list.state.pipeline_shader_driver_id, p_data, p_data_size);53215322#ifdef DEBUG_ENABLED5323draw_list.validation.pipeline_push_constant_supplied = true;5324#endif5325}53265327void RenderingDevice::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {5328ERR_RENDER_THREAD_GUARD();53295330ERR_FAIL_COND(!draw_list.active);53315332#ifdef DEBUG_ENABLED5333ERR_FAIL_COND_MSG(!draw_list.validation.pipeline_active,5334"No render pipeline was set before attempting to draw.");5335if (draw_list.validation.pipeline_vertex_format != INVALID_ID) {5336// Pipeline uses vertices, validate format.5337ERR_FAIL_COND_MSG(draw_list.validation.vertex_format == INVALID_ID,5338"No vertex array was bound, and render pipeline expects vertices.");5339// Make sure format is right.5340ERR_FAIL_COND_MSG(draw_list.validation.pipeline_vertex_format != draw_list.validation.vertex_format,5341"The vertex format used to create the pipeline does not match the vertex format bound.");5342// Make sure number of instances is valid.5343ERR_FAIL_COND_MSG(p_instances > draw_list.validation.vertex_max_instances_allowed,5344"Number of instances requested (" + itos(p_instances) + " is larger than the maximum number supported by the bound vertex array (" + itos(draw_list.validation.vertex_max_instances_allowed) + ").");5345}53465347if (draw_list.validation.pipeline_push_constant_size > 0) {5348// Using push constants, check that they were supplied.5349ERR_FAIL_COND_MSG(!draw_list.validation.pipeline_push_constant_supplied,5350"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");5351}53525353#endif53545355#ifdef DEBUG_ENABLED5356for (uint32_t i = 0; i < draw_list.state.set_count; i++) {5357if (draw_list.state.sets[i].pipeline_expected_format == 0) {5358// Nothing expected by this pipeline.5359continue;5360}53615362if (draw_list.state.sets[i].pipeline_expected_format != draw_list.state.sets[i].uniform_set_format) {5363if (draw_list.state.sets[i].uniform_set_format == 0) {5364ERR_FAIL_MSG(vformat("Uniforms were never supplied for set (%d) at the time of drawing, which are required by the pipeline.", i));5365} else if (uniform_set_owner.owns(draw_list.state.sets[i].uniform_set)) {5366UniformSet *us = uniform_set_owner.get_or_null(draw_list.state.sets[i].uniform_set);5367const String us_info = us ? vformat("(%d):\n%s\n", i, _shader_uniform_debug(us->shader_id, us->shader_set)) : vformat("(%d, which was just freed) ", i);5368ERR_FAIL_MSG(vformat("Uniforms supplied for set %sare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n%s", us_info, _shader_uniform_debug(draw_list.state.pipeline_shader)));5369} else {5370ERR_FAIL_MSG(vformat("Uniforms supplied for set (%d, which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n%s", i, _shader_uniform_debug(draw_list.state.pipeline_shader)));5371}5372}5373}5374#endif5375thread_local LocalVector<RDD::UniformSetID> valid_descriptor_ids;5376valid_descriptor_ids.clear();5377valid_descriptor_ids.resize(draw_list.state.set_count);5378uint32_t valid_set_count = 0;5379uint32_t first_set_index = 0;5380uint32_t last_set_index = 0;5381bool found_first_set = false;53825383for (uint32_t i = 0; i < draw_list.state.set_count; i++) {5384if (draw_list.state.sets[i].pipeline_expected_format == 0) {5385continue; // Nothing expected by this pipeline.5386}53875388if (!draw_list.state.sets[i].bound && !found_first_set) {5389first_set_index = i;5390found_first_set = true;5391}5392// Prepare descriptor sets if the API doesn't use pipeline barriers.5393if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {5394draw_graph.add_draw_list_uniform_set_prepare_for_use(draw_list.state.pipeline_shader_driver_id, draw_list.state.sets[i].uniform_set_driver_id, i);5395}5396}53975398// Bind descriptor sets.5399for (uint32_t i = first_set_index; i < draw_list.state.set_count; i++) {5400if (draw_list.state.sets[i].pipeline_expected_format == 0) {5401continue; // Nothing expected by this pipeline.5402}54035404if (!draw_list.state.sets[i].bound) {5405// Batch contiguous descriptor sets in a single call.5406if (descriptor_set_batching) {5407// All good, see if this requires re-binding.5408if (i - last_set_index > 1) {5409// If the descriptor sets are not contiguous, bind the previous ones and start a new batch.5410draw_graph.add_draw_list_bind_uniform_sets(draw_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);54115412first_set_index = i;5413valid_set_count = 1;5414valid_descriptor_ids[0] = draw_list.state.sets[i].uniform_set_driver_id;5415} else {5416// Otherwise, keep storing in the current batch.5417valid_descriptor_ids[valid_set_count] = draw_list.state.sets[i].uniform_set_driver_id;5418valid_set_count++;5419}54205421UniformSet *uniform_set = uniform_set_owner.get_or_null(draw_list.state.sets[i].uniform_set);5422ERR_FAIL_NULL(uniform_set);5423_uniform_set_update_shared(uniform_set);5424_uniform_set_update_clears(uniform_set);54255426draw_graph.add_draw_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);5427draw_list.state.sets[i].bound = true;54285429last_set_index = i;5430} else {5431draw_graph.add_draw_list_bind_uniform_set(draw_list.state.pipeline_shader_driver_id, draw_list.state.sets[i].uniform_set_driver_id, i);5432}5433}5434}54355436// Bind the remaining batch.5437if (descriptor_set_batching && valid_set_count > 0) {5438draw_graph.add_draw_list_bind_uniform_sets(draw_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);5439}54405441if (p_use_indices) {5442#ifdef DEBUG_ENABLED5443ERR_FAIL_COND_MSG(p_procedural_vertices > 0,5444"Procedural vertices can't be used together with indices.");54455446ERR_FAIL_COND_MSG(!draw_list.validation.index_array_count,5447"Draw command requested indices, but no index buffer was set.");54485449ERR_FAIL_COND_MSG(draw_list.validation.pipeline_uses_restart_indices != draw_list.validation.index_buffer_uses_restart_indices,5450"The usage of restart indices in index buffer does not match the render primitive in the pipeline.");5451#endif5452uint32_t to_draw = draw_list.validation.index_array_count;54535454#ifdef DEBUG_ENABLED5455ERR_FAIL_COND_MSG(to_draw < draw_list.validation.pipeline_primitive_minimum,5456"Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(draw_list.validation.pipeline_primitive_minimum) + ").");54575458ERR_FAIL_COND_MSG((to_draw % draw_list.validation.pipeline_primitive_divisor) != 0,5459"Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(draw_list.validation.pipeline_primitive_divisor) + ").");5460#endif54615462draw_graph.add_draw_list_draw_indexed(to_draw, p_instances, 0);5463} else {5464uint32_t to_draw;54655466if (p_procedural_vertices > 0) {5467to_draw = p_procedural_vertices;5468} else {5469#ifdef DEBUG_ENABLED5470ERR_FAIL_COND_MSG(draw_list.validation.pipeline_vertex_format == INVALID_ID,5471"Draw command lacks indices, but pipeline format does not use vertices.");5472#endif5473to_draw = draw_list.validation.vertex_array_size;5474}54755476#ifdef DEBUG_ENABLED5477ERR_FAIL_COND_MSG(to_draw < draw_list.validation.pipeline_primitive_minimum,5478"Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(draw_list.validation.pipeline_primitive_minimum) + ").");54795480ERR_FAIL_COND_MSG((to_draw % draw_list.validation.pipeline_primitive_divisor) != 0,5481"Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(draw_list.validation.pipeline_primitive_divisor) + ").");5482#endif54835484draw_graph.add_draw_list_draw(to_draw, p_instances);5485}54865487draw_list.state.draw_count++;5488}54895490void RenderingDevice::draw_list_draw_indirect(DrawListID p_list, bool p_use_indices, RID p_buffer, uint32_t p_offset, uint32_t p_draw_count, uint32_t p_stride) {5491ERR_RENDER_THREAD_GUARD();54925493ERR_FAIL_COND(!draw_list.active);54945495Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);5496ERR_FAIL_NULL(buffer);54975498ERR_FAIL_COND_MSG(!buffer->usage.has_flag(RDD::BUFFER_USAGE_INDIRECT_BIT), "Buffer provided was not created to do indirect dispatch.");54995500#ifdef DEBUG_ENABLED5501ERR_FAIL_COND_MSG(!draw_list.validation.pipeline_active,5502"No render pipeline was set before attempting to draw.");5503if (draw_list.validation.pipeline_vertex_format != INVALID_ID) {5504// Pipeline uses vertices, validate format.5505ERR_FAIL_COND_MSG(draw_list.validation.vertex_format == INVALID_ID,5506"No vertex array was bound, and render pipeline expects vertices.");5507// Make sure format is right.5508ERR_FAIL_COND_MSG(draw_list.validation.pipeline_vertex_format != draw_list.validation.vertex_format,5509"The vertex format used to create the pipeline does not match the vertex format bound.");5510}55115512if (draw_list.validation.pipeline_push_constant_size > 0) {5513// Using push constants, check that they were supplied.5514ERR_FAIL_COND_MSG(!draw_list.validation.pipeline_push_constant_supplied,5515"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");5516}5517#endif55185519#ifdef DEBUG_ENABLED5520for (uint32_t i = 0; i < draw_list.state.set_count; i++) {5521if (draw_list.state.sets[i].pipeline_expected_format == 0) {5522// Nothing expected by this pipeline.5523continue;5524}55255526if (draw_list.state.sets[i].pipeline_expected_format != draw_list.state.sets[i].uniform_set_format) {5527if (draw_list.state.sets[i].uniform_set_format == 0) {5528ERR_FAIL_MSG(vformat("Uniforms were never supplied for set (%d) at the time of drawing, which are required by the pipeline.", i));5529} else if (uniform_set_owner.owns(draw_list.state.sets[i].uniform_set)) {5530UniformSet *us = uniform_set_owner.get_or_null(draw_list.state.sets[i].uniform_set);5531const String us_info = us ? vformat("(%d):\n%s\n", i, _shader_uniform_debug(us->shader_id, us->shader_set)) : vformat("(%d, which was just freed) ", i);5532ERR_FAIL_MSG(vformat("Uniforms supplied for set %sare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n%s", us_info, _shader_uniform_debug(draw_list.state.pipeline_shader)));5533} else {5534ERR_FAIL_MSG(vformat("Uniforms supplied for set (%d, which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n%s", i, _shader_uniform_debug(draw_list.state.pipeline_shader)));5535}5536}5537}5538#endif55395540// Prepare descriptor sets if the API doesn't use pipeline barriers.5541if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {5542for (uint32_t i = 0; i < draw_list.state.set_count; i++) {5543if (draw_list.state.sets[i].pipeline_expected_format == 0) {5544// Nothing expected by this pipeline.5545continue;5546}55475548draw_graph.add_draw_list_uniform_set_prepare_for_use(draw_list.state.pipeline_shader_driver_id, draw_list.state.sets[i].uniform_set_driver_id, i);5549}5550}55515552// Bind descriptor sets.5553for (uint32_t i = 0; i < draw_list.state.set_count; i++) {5554if (draw_list.state.sets[i].pipeline_expected_format == 0) {5555continue; // Nothing expected by this pipeline.5556}5557if (!draw_list.state.sets[i].bound) {5558// All good, see if this requires re-binding.5559draw_graph.add_draw_list_bind_uniform_set(draw_list.state.pipeline_shader_driver_id, draw_list.state.sets[i].uniform_set_driver_id, i);55605561UniformSet *uniform_set = uniform_set_owner.get_or_null(draw_list.state.sets[i].uniform_set);5562ERR_FAIL_NULL(uniform_set);5563_uniform_set_update_shared(uniform_set);5564_uniform_set_update_clears(uniform_set);55655566draw_graph.add_draw_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);55675568draw_list.state.sets[i].bound = true;5569}5570}55715572if (p_use_indices) {5573#ifdef DEBUG_ENABLED5574ERR_FAIL_COND_MSG(!draw_list.validation.index_array_count,5575"Draw command requested indices, but no index buffer was set.");55765577ERR_FAIL_COND_MSG(draw_list.validation.pipeline_uses_restart_indices != draw_list.validation.index_buffer_uses_restart_indices,5578"The usage of restart indices in index buffer does not match the render primitive in the pipeline.");5579#endif55805581ERR_FAIL_COND_MSG(p_offset + 20 > buffer->size, "Offset provided (+20) is past the end of buffer.");55825583draw_graph.add_draw_list_draw_indexed_indirect(buffer->driver_id, p_offset, p_draw_count, p_stride);5584} else {5585ERR_FAIL_COND_MSG(p_offset + 16 > buffer->size, "Offset provided (+16) is past the end of buffer.");55865587draw_graph.add_draw_list_draw_indirect(buffer->driver_id, p_offset, p_draw_count, p_stride);5588}55895590draw_list.state.draw_count++;55915592if (buffer->draw_tracker != nullptr) {5593draw_graph.add_draw_list_usage(buffer->draw_tracker, RDG::RESOURCE_USAGE_INDIRECT_BUFFER_READ);5594}55955596_check_transfer_worker_buffer(buffer);5597}55985599void RenderingDevice::draw_list_set_viewport(DrawListID p_list, const Rect2 &p_rect) {5600ERR_FAIL_COND(!draw_list.active);56015602if (p_rect.get_area() == 0) {5603return;5604}56055606draw_list.viewport = p_rect;5607draw_graph.add_draw_list_set_viewport(p_rect);5608}56095610void RenderingDevice::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {5611ERR_RENDER_THREAD_GUARD();56125613ERR_FAIL_COND(!draw_list.active);56145615Rect2i rect = p_rect;5616rect.position += draw_list.viewport.position;56175618rect = draw_list.viewport.intersection(rect);56195620if (rect.get_area() == 0) {5621return;5622}56235624draw_graph.add_draw_list_set_scissor(rect);5625}56265627void RenderingDevice::draw_list_disable_scissor(DrawListID p_list) {5628ERR_RENDER_THREAD_GUARD();56295630ERR_FAIL_COND(!draw_list.active);56315632draw_graph.add_draw_list_set_scissor(draw_list.viewport);5633}56345635uint32_t RenderingDevice::draw_list_get_current_pass() {5636ERR_RENDER_THREAD_GUARD_V(0);56375638return draw_list_current_subpass;5639}56405641RenderingDevice::DrawListID RenderingDevice::draw_list_switch_to_next_pass() {5642ERR_RENDER_THREAD_GUARD_V(INVALID_ID);56435644ERR_FAIL_COND_V(!draw_list.active, INVALID_FORMAT_ID);5645ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);56465647draw_list_current_subpass++;56485649Rect2i viewport;5650_draw_list_end(&viewport);56515652draw_graph.add_draw_list_next_subpass(RDD::COMMAND_BUFFER_TYPE_PRIMARY);56535654_draw_list_start(viewport);56555656return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;5657}56585659#ifndef DISABLE_DEPRECATED5660Error RenderingDevice::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {5661ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Deprecated. Split draw lists are used automatically by RenderingDevice.");5662}5663#endif56645665void RenderingDevice::_draw_list_start(const Rect2i &p_viewport) {5666draw_list.viewport = p_viewport;5667draw_list.active = true;5668}56695670void RenderingDevice::_draw_list_end(Rect2i *r_last_viewport) {5671if (r_last_viewport) {5672*r_last_viewport = draw_list.viewport;5673}56745675draw_list = DrawList();5676}56775678void RenderingDevice::draw_list_end() {5679ERR_RENDER_THREAD_GUARD();56805681ERR_FAIL_COND_MSG(!draw_list.active, "Immediate draw list is already inactive.");56825683draw_graph.add_draw_list_end();56845685_draw_list_end();56865687for (uint32_t i = 0; i < draw_list_bound_textures.size(); i++) {5688Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);5689ERR_CONTINUE(!texture); // Wtf.5690if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {5691texture->bound = false;5692}5693if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {5694texture->bound = false;5695}5696if (texture->usage_flags & TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT) {5697texture->bound = false;5698}5699}57005701draw_list_bound_textures.clear();5702}57035704/***************************/5705/**** RAYTRACING LISTS ****/5706/**************************/57075708RenderingDevice::RaytracingListID RenderingDevice::raytracing_list_begin() {5709ERR_RENDER_THREAD_GUARD_V(INVALID_ID);57105711ERR_FAIL_COND_V_MSG(!has_feature(SUPPORTS_RAYTRACING_PIPELINE), INVALID_ID, "The current rendering device has no raytracing pipeline support.");57125713ERR_FAIL_COND_V_MSG(draw_list.active, INVALID_ID, "Only one draw/raytracing list can be active at the same time.");5714ERR_FAIL_COND_V_MSG(compute_list.active, INVALID_ID, "Only one compute/raytracing list can be active at the same time.");5715ERR_FAIL_COND_V_MSG(raytracing_list.active, INVALID_ID, "Only one raytracing list can be active at the same time.");57165717raytracing_list.active = true;57185719draw_graph.add_raytracing_list_begin();57205721return ID_TYPE_RAYTRACING_LIST;5722}57235724void RenderingDevice::raytracing_list_bind_raytracing_pipeline(RaytracingListID p_list, RID p_raytracing_pipeline) {5725ERR_RENDER_THREAD_GUARD();57265727ERR_FAIL_COND(p_list != ID_TYPE_RAYTRACING_LIST);5728ERR_FAIL_COND(!raytracing_list.active);57295730const RaytracingPipeline *pipeline = raytracing_pipeline_owner.get_or_null(p_raytracing_pipeline);5731ERR_FAIL_NULL(pipeline);57325733if (p_raytracing_pipeline == raytracing_list.state.pipeline) {5734return; // Redundant state, return.5735}57365737raytracing_list.state.pipeline = p_raytracing_pipeline;5738raytracing_list.state.pipeline_driver_id = pipeline->driver_id;57395740draw_graph.add_raytracing_list_bind_pipeline(pipeline->driver_id);57415742if (raytracing_list.state.pipeline_shader != pipeline->shader) {5743// Shader changed, so descriptor sets may become incompatible.57445745uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.5746raytracing_list.state.set_count = MAX(raytracing_list.state.set_count, pcount);5747const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.57485749uint32_t first_invalid_set = UINT32_MAX; // All valid by default.5750switch (driver->api_trait_get(RDD::API_TRAIT_SHADER_CHANGE_INVALIDATION)) {5751case RDD::SHADER_CHANGE_INVALIDATION_ALL_BOUND_UNIFORM_SETS: {5752first_invalid_set = 0;5753} break;5754case RDD::SHADER_CHANGE_INVALIDATION_INCOMPATIBLE_SETS_PLUS_CASCADE: {5755for (uint32_t i = 0; i < pcount; i++) {5756if (raytracing_list.state.sets[i].pipeline_expected_format != pformats[i]) {5757first_invalid_set = i;5758break;5759}5760}5761} break;5762case RDD::SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH: {5763if (raytracing_list.state.pipeline_shader_layout_hash != pipeline->shader_layout_hash) {5764first_invalid_set = 0;5765}5766} break;5767}57685769for (uint32_t i = 0; i < pcount; i++) {5770raytracing_list.state.sets[i].bound = raytracing_list.state.sets[i].bound && i < first_invalid_set;5771raytracing_list.state.sets[i].pipeline_expected_format = pformats[i];5772}57735774for (uint32_t i = pcount; i < raytracing_list.state.set_count; i++) {5775// Unbind the ones above (not used) if exist.5776raytracing_list.state.sets[i].bound = false;5777}57785779raytracing_list.state.set_count = pcount; // Update set count.57805781if (pipeline->push_constant_size) {5782#ifdef DEBUG_ENABLED5783raytracing_list.validation.pipeline_push_constant_supplied = false;5784#endif5785}57865787raytracing_list.state.pipeline_shader = pipeline->shader;5788raytracing_list.state.pipeline_shader_driver_id = pipeline->shader_driver_id;5789raytracing_list.state.pipeline_shader_layout_hash = pipeline->shader_layout_hash;5790}57915792#ifdef DEBUG_ENABLED5793// Update raytracing pass pipeline info.5794raytracing_list.validation.pipeline_active = true;5795raytracing_list.validation.pipeline_push_constant_size = pipeline->push_constant_size;5796#endif5797}57985799void RenderingDevice::raytracing_list_bind_uniform_set(RaytracingListID p_list, RID p_uniform_set, uint32_t p_index) {5800ERR_RENDER_THREAD_GUARD();58015802ERR_FAIL_COND(p_list != ID_TYPE_RAYTRACING_LIST);5803ERR_FAIL_COND(!raytracing_list.active);58045805#ifdef DEBUG_ENABLED5806ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS,5807"Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ").");5808#endif58095810UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);5811ERR_FAIL_NULL(uniform_set);58125813if (p_index > raytracing_list.state.set_count) {5814raytracing_list.state.set_count = p_index;5815}58165817raytracing_list.state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer.5818raytracing_list.state.sets[p_index].bound = false; // Needs rebind.5819raytracing_list.state.sets[p_index].uniform_set_format = uniform_set->format;5820raytracing_list.state.sets[p_index].uniform_set = p_uniform_set;5821}58225823void RenderingDevice::raytracing_list_set_push_constant(RaytracingListID p_list, const void *p_data, uint32_t p_data_size) {5824ERR_RENDER_THREAD_GUARD();58255826ERR_FAIL_COND(p_list != ID_TYPE_RAYTRACING_LIST);5827ERR_FAIL_COND(!raytracing_list.active);58285829ERR_FAIL_COND_MSG(p_data_size > MAX_PUSH_CONSTANT_SIZE, "Push constants can't be bigger than 128 bytes to maintain compatibility.");58305831#ifdef DEBUG_ENABLED5832ERR_FAIL_COND_MSG(p_data_size != raytracing_list.validation.pipeline_push_constant_size,5833"This raytracing pipeline requires (" + itos(raytracing_list.validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");5834#endif58355836draw_graph.add_raytracing_list_set_push_constant(raytracing_list.state.pipeline_shader_driver_id, p_data, p_data_size);58375838// Store it in the state in case we need to restart the raytracing list.5839memcpy(raytracing_list.state.push_constant_data, p_data, p_data_size);5840raytracing_list.state.push_constant_size = p_data_size;58415842#ifdef DEBUG_ENABLED5843raytracing_list.validation.pipeline_push_constant_supplied = true;5844#endif5845}58465847void RenderingDevice::raytracing_list_trace_rays(RaytracingListID p_list, uint32_t p_width, uint32_t p_height) {5848ERR_RENDER_THREAD_GUARD();58495850ERR_FAIL_COND(p_list != ID_TYPE_RAYTRACING_LIST);5851ERR_FAIL_COND(!raytracing_list.active);58525853#ifdef DEBUG_ENABLED5854ERR_FAIL_NULL_MSG(shader_owner.get_or_null(raytracing_list.state.pipeline_shader), "No shader was set before attempting to trace rays.");5855ERR_FAIL_NULL_MSG(raytracing_pipeline_owner.get_or_null(raytracing_list.state.pipeline), "No raytracing pipeline was set before attempting to trace rays.");5856#endif58575858#ifdef DEBUG_ENABLED58595860ERR_FAIL_COND_MSG(!raytracing_list.validation.pipeline_active, "No raytracing pipeline was set before attempting to draw.");58615862if (raytracing_list.validation.pipeline_push_constant_size > 0) {5863// Using push constants, check that they were supplied.5864ERR_FAIL_COND_MSG(!raytracing_list.validation.pipeline_push_constant_supplied,5865"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");5866}58675868#endif58695870#ifdef DEBUG_ENABLED5871for (uint32_t i = 0; i < raytracing_list.state.set_count; i++) {5872if (raytracing_list.state.sets[i].pipeline_expected_format == 0) {5873// Nothing expected by this pipeline.5874continue;5875}58765877if (raytracing_list.state.sets[i].pipeline_expected_format != raytracing_list.state.sets[i].uniform_set_format) {5878if (raytracing_list.state.sets[i].uniform_set_format == 0) {5879ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");5880} else if (uniform_set_owner.owns(raytracing_list.state.sets[i].uniform_set)) {5881UniformSet *us = uniform_set_owner.get_or_null(raytracing_list.state.sets[i].uniform_set);5882ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(raytracing_list.state.pipeline_shader));5883} else {5884ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(raytracing_list.state.pipeline_shader));5885}5886}5887}5888#endif58895890// Prepare descriptor sets if the API doesn't use pipeline barriers.5891if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {5892for (uint32_t i = 0; i < raytracing_list.state.set_count; i++) {5893if (raytracing_list.state.sets[i].pipeline_expected_format == 0) {5894// Nothing expected by this pipeline.5895continue;5896}58975898draw_graph.add_raytracing_list_uniform_set_prepare_for_use(raytracing_list.state.pipeline_shader_driver_id, raytracing_list.state.sets[i].uniform_set_driver_id, i);5899}5900}59015902// Bind descriptor sets.5903for (uint32_t i = 0; i < raytracing_list.state.set_count; i++) {5904if (raytracing_list.state.sets[i].pipeline_expected_format == 0) {5905continue; // Nothing expected by this pipeline.5906}5907if (!raytracing_list.state.sets[i].bound) {5908// All good, see if this requires re-binding.5909draw_graph.add_raytracing_list_bind_uniform_set(raytracing_list.state.pipeline_shader_driver_id, raytracing_list.state.sets[i].uniform_set_driver_id, i);59105911UniformSet *uniform_set = uniform_set_owner.get_or_null(raytracing_list.state.sets[i].uniform_set);5912_uniform_set_update_shared(uniform_set);59135914draw_graph.add_raytracing_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);59155916raytracing_list.state.sets[i].bound = true;5917}5918}59195920draw_graph.add_raytracing_list_trace_rays(p_width, p_height);5921raytracing_list.state.trace_count++;5922}59235924void RenderingDevice::raytracing_list_end() {5925ERR_RENDER_THREAD_GUARD();59265927ERR_FAIL_COND(!raytracing_list.active);59285929draw_graph.add_raytracing_list_end();59305931raytracing_list = RaytracingList();5932}59335934/***********************/5935/**** COMPUTE LISTS ****/5936/***********************/59375938RenderingDevice::ComputeListID RenderingDevice::compute_list_begin() {5939ERR_RENDER_THREAD_GUARD_V(INVALID_ID);59405941ERR_FAIL_COND_V_MSG(compute_list.active, INVALID_ID, "Only one compute list can be active at the same time.");5942ERR_FAIL_COND_V_MSG(raytracing_list.active, INVALID_ID, "Only one raytracing list can be active at the same time.");59435944compute_list.active = true;59455946draw_graph.add_compute_list_begin();59475948return ID_TYPE_COMPUTE_LIST;5949}59505951void RenderingDevice::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {5952ERR_RENDER_THREAD_GUARD();59535954ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);5955ERR_FAIL_COND(!compute_list.active);59565957const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);5958ERR_FAIL_NULL(pipeline);59595960if (p_compute_pipeline == compute_list.state.pipeline) {5961return; // Redundant state, return.5962}59635964compute_list.state.pipeline = p_compute_pipeline;59655966draw_graph.add_compute_list_bind_pipeline(pipeline->driver_id);59675968if (compute_list.state.pipeline_shader != pipeline->shader) {5969// Shader changed, so descriptor sets may become incompatible.59705971uint32_t pcount = pipeline->set_formats.size(); // Formats count in this pipeline.5972compute_list.state.set_count = MAX(compute_list.state.set_count, pcount);5973const uint32_t *pformats = pipeline->set_formats.ptr(); // Pipeline set formats.59745975uint32_t first_invalid_set = UINT32_MAX; // All valid by default.5976switch (driver->api_trait_get(RDD::API_TRAIT_SHADER_CHANGE_INVALIDATION)) {5977case RDD::SHADER_CHANGE_INVALIDATION_ALL_BOUND_UNIFORM_SETS: {5978first_invalid_set = 0;5979} break;5980case RDD::SHADER_CHANGE_INVALIDATION_INCOMPATIBLE_SETS_PLUS_CASCADE: {5981for (uint32_t i = 0; i < pcount; i++) {5982if (compute_list.state.sets[i].pipeline_expected_format != pformats[i]) {5983first_invalid_set = i;5984break;5985}5986}5987} break;5988case RDD::SHADER_CHANGE_INVALIDATION_ALL_OR_NONE_ACCORDING_TO_LAYOUT_HASH: {5989if (compute_list.state.pipeline_shader_layout_hash != pipeline->shader_layout_hash) {5990first_invalid_set = 0;5991}5992} break;5993}59945995for (uint32_t i = 0; i < pcount; i++) {5996compute_list.state.sets[i].bound = compute_list.state.sets[i].bound && i < first_invalid_set;5997compute_list.state.sets[i].pipeline_expected_format = pformats[i];5998}59996000for (uint32_t i = pcount; i < compute_list.state.set_count; i++) {6001// Unbind the ones above (not used) if exist.6002compute_list.state.sets[i].bound = false;6003}60046005compute_list.state.set_count = pcount; // Update set count.60066007if (pipeline->push_constant_size) {6008#ifdef DEBUG_ENABLED6009compute_list.validation.pipeline_push_constant_supplied = false;6010#endif6011}60126013compute_list.state.pipeline_shader = pipeline->shader;6014compute_list.state.pipeline_shader_driver_id = pipeline->shader_driver_id;6015compute_list.state.pipeline_shader_layout_hash = pipeline->shader_layout_hash;6016compute_list.state.local_group_size[0] = pipeline->local_group_size[0];6017compute_list.state.local_group_size[1] = pipeline->local_group_size[1];6018compute_list.state.local_group_size[2] = pipeline->local_group_size[2];6019}60206021#ifdef DEBUG_ENABLED6022// Update compute pass pipeline info.6023compute_list.validation.pipeline_active = true;6024compute_list.validation.pipeline_push_constant_size = pipeline->push_constant_size;6025#endif6026}60276028void RenderingDevice::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {6029ERR_RENDER_THREAD_GUARD();60306031ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);6032ERR_FAIL_COND(!compute_list.active);60336034#ifdef DEBUG_ENABLED6035ERR_FAIL_COND_MSG(p_index >= driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS) || p_index >= MAX_UNIFORM_SETS,6036"Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(driver->limit_get(LIMIT_MAX_BOUND_UNIFORM_SETS)) + ").");6037#endif60386039UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);6040ERR_FAIL_NULL(uniform_set);60416042if (p_index > compute_list.state.set_count) {6043compute_list.state.set_count = p_index;6044}60456046compute_list.state.sets[p_index].uniform_set_driver_id = uniform_set->driver_id; // Update set pointer.6047compute_list.state.sets[p_index].bound = false; // Needs rebind.6048compute_list.state.sets[p_index].uniform_set_format = uniform_set->format;6049compute_list.state.sets[p_index].uniform_set = p_uniform_set;60506051#if 06052{ // Validate that textures bound are not attached as framebuffer bindings.6053uint32_t attachable_count = uniform_set->attachable_textures.size();6054const RID *attachable_ptr = uniform_set->attachable_textures.ptr();6055uint32_t bound_count = draw_list_bound_textures.size();6056const RID *bound_ptr = draw_list_bound_textures.ptr();6057for (uint32_t i = 0; i < attachable_count; i++) {6058for (uint32_t j = 0; j < bound_count; j++) {6059ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],6060"Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");6061}6062}6063}6064#endif6065}60666067void RenderingDevice::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {6068ERR_RENDER_THREAD_GUARD();60696070ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);6071ERR_FAIL_COND(!compute_list.active);6072ERR_FAIL_COND_MSG(p_data_size > MAX_PUSH_CONSTANT_SIZE, "Push constants can't be bigger than 128 bytes to maintain compatibility.");60736074#ifdef DEBUG_ENABLED6075ERR_FAIL_COND_MSG(p_data_size != compute_list.validation.pipeline_push_constant_size,6076"This compute pipeline requires (" + itos(compute_list.validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");6077#endif60786079draw_graph.add_compute_list_set_push_constant(compute_list.state.pipeline_shader_driver_id, p_data, p_data_size);60806081// Store it in the state in case we need to restart the compute list.6082memcpy(compute_list.state.push_constant_data, p_data, p_data_size);6083compute_list.state.push_constant_size = p_data_size;60846085#ifdef DEBUG_ENABLED6086compute_list.validation.pipeline_push_constant_supplied = true;6087#endif6088}60896090void RenderingDevice::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {6091ERR_RENDER_THREAD_GUARD();60926093ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);6094ERR_FAIL_COND(!compute_list.active);60956096#ifdef DEBUG_ENABLED6097ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");6098ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");6099ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");6100ERR_FAIL_COND_MSG(p_x_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X),6101"Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X)) + ")");6102ERR_FAIL_COND_MSG(p_y_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y),6103"Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y)) + ")");6104ERR_FAIL_COND_MSG(p_z_groups > driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z),6105"Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(driver->limit_get(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z)) + ")");6106#endif61076108#ifdef DEBUG_ENABLED61096110ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_active, "No compute pipeline was set before attempting to draw.");61116112if (compute_list.validation.pipeline_push_constant_size > 0) {6113// Using push constants, check that they were supplied.6114ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_push_constant_supplied,6115"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");6116}61176118#endif61196120#ifdef DEBUG_ENABLED6121for (uint32_t i = 0; i < compute_list.state.set_count; i++) {6122if (compute_list.state.sets[i].pipeline_expected_format == 0) {6123// Nothing expected by this pipeline.6124continue;6125}61266127if (compute_list.state.sets[i].pipeline_expected_format != compute_list.state.sets[i].uniform_set_format) {6128if (compute_list.state.sets[i].uniform_set_format == 0) {6129ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");6130} else if (uniform_set_owner.owns(compute_list.state.sets[i].uniform_set)) {6131UniformSet *us = uniform_set_owner.get_or_null(compute_list.state.sets[i].uniform_set);6132ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(compute_list.state.pipeline_shader));6133} else {6134ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(compute_list.state.pipeline_shader));6135}6136}6137}6138#endif6139thread_local LocalVector<RDD::UniformSetID> valid_descriptor_ids;6140valid_descriptor_ids.clear();6141valid_descriptor_ids.resize(compute_list.state.set_count);61426143uint32_t valid_set_count = 0;6144uint32_t first_set_index = 0;6145uint32_t last_set_index = 0;6146bool found_first_set = false;61476148for (uint32_t i = 0; i < compute_list.state.set_count; i++) {6149if (compute_list.state.sets[i].pipeline_expected_format == 0) {6150// Nothing expected by this pipeline.6151continue;6152}61536154if (!compute_list.state.sets[i].bound && !found_first_set) {6155first_set_index = i;6156found_first_set = true;6157}6158// Prepare descriptor sets if the API doesn't use pipeline barriers.6159if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {6160draw_graph.add_compute_list_uniform_set_prepare_for_use(compute_list.state.pipeline_shader_driver_id, compute_list.state.sets[i].uniform_set_driver_id, i);6161}6162}61636164// Bind descriptor sets.6165for (uint32_t i = first_set_index; i < compute_list.state.set_count; i++) {6166if (compute_list.state.sets[i].pipeline_expected_format == 0) {6167continue; // Nothing expected by this pipeline.6168}61696170if (!compute_list.state.sets[i].bound) {6171// Descriptor set batching6172if (descriptor_set_batching) {6173// All good, see if this requires re-binding.6174if (i - last_set_index > 1) {6175// If the descriptor sets are not contiguous, bind the previous ones and start a new batch.6176draw_graph.add_compute_list_bind_uniform_sets(compute_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);61776178first_set_index = i;6179valid_set_count = 1;6180valid_descriptor_ids[0] = compute_list.state.sets[i].uniform_set_driver_id;6181} else {6182// Otherwise, keep storing in the current batch.6183valid_descriptor_ids[valid_set_count] = compute_list.state.sets[i].uniform_set_driver_id;6184valid_set_count++;6185}61866187last_set_index = i;6188} else {6189draw_graph.add_compute_list_bind_uniform_set(compute_list.state.pipeline_shader_driver_id, compute_list.state.sets[i].uniform_set_driver_id, i);6190}6191UniformSet *uniform_set = uniform_set_owner.get_or_null(compute_list.state.sets[i].uniform_set);6192_uniform_set_update_shared(uniform_set);6193_uniform_set_update_clears(uniform_set);61946195draw_graph.add_compute_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);6196compute_list.state.sets[i].bound = true;6197}6198}61996200// Bind the remaining batch.6201if (valid_set_count > 0) {6202draw_graph.add_compute_list_bind_uniform_sets(compute_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);6203}6204draw_graph.add_compute_list_dispatch(p_x_groups, p_y_groups, p_z_groups);6205compute_list.state.dispatch_count++;6206}62076208void RenderingDevice::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {6209ERR_RENDER_THREAD_GUARD();62106211ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);6212ERR_FAIL_COND(!compute_list.active);62136214#ifdef DEBUG_ENABLED6215ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");6216ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");6217ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");6218#endif62196220#ifdef DEBUG_ENABLED62216222ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_active, "No compute pipeline was set before attempting to draw.");62236224if (compute_list.validation.pipeline_push_constant_size > 0) {6225// Using push constants, check that they were supplied.6226ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_push_constant_supplied,6227"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");6228}62296230#endif62316232compute_list_dispatch(p_list, Math::division_round_up(p_x_threads, compute_list.state.local_group_size[0]), Math::division_round_up(p_y_threads, compute_list.state.local_group_size[1]), Math::division_round_up(p_z_threads, compute_list.state.local_group_size[2]));6233}62346235void RenderingDevice::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {6236ERR_RENDER_THREAD_GUARD();62376238ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);6239ERR_FAIL_COND(!compute_list.active);62406241Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);6242ERR_FAIL_NULL(buffer);62436244ERR_FAIL_COND_MSG(!buffer->usage.has_flag(RDD::BUFFER_USAGE_INDIRECT_BIT), "Buffer provided was not created to do indirect dispatch.");62456246ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");62476248#ifdef DEBUG_ENABLED62496250ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_active, "No compute pipeline was set before attempting to draw.");62516252if (compute_list.validation.pipeline_push_constant_size > 0) {6253// Using push constants, check that they were supplied.6254ERR_FAIL_COND_MSG(!compute_list.validation.pipeline_push_constant_supplied,6255"The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");6256}62576258#endif62596260#ifdef DEBUG_ENABLED6261for (uint32_t i = 0; i < compute_list.state.set_count; i++) {6262if (compute_list.state.sets[i].pipeline_expected_format == 0) {6263// Nothing expected by this pipeline.6264continue;6265}62666267if (compute_list.state.sets[i].pipeline_expected_format != compute_list.state.sets[i].uniform_set_format) {6268if (compute_list.state.sets[i].uniform_set_format == 0) {6269ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline.");6270} else if (uniform_set_owner.owns(compute_list.state.sets[i].uniform_set)) {6271UniformSet *us = uniform_set_owner.get_or_null(compute_list.state.sets[i].uniform_set);6272ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(compute_list.state.pipeline_shader));6273} else {6274ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(compute_list.state.pipeline_shader));6275}6276}6277}6278#endif6279thread_local LocalVector<RDD::UniformSetID> valid_descriptor_ids;6280valid_descriptor_ids.clear();6281valid_descriptor_ids.resize(compute_list.state.set_count);62826283uint32_t valid_set_count = 0;6284uint32_t first_set_index = 0;6285uint32_t last_set_index = 0;6286bool found_first_set = false;62876288for (uint32_t i = 0; i < compute_list.state.set_count; i++) {6289if (compute_list.state.sets[i].pipeline_expected_format == 0) {6290// Nothing expected by this pipeline.6291continue;6292}62936294if (!compute_list.state.sets[i].bound && !found_first_set) {6295first_set_index = i;6296found_first_set = true;6297}62986299// Prepare descriptor sets if the API doesn't use pipeline barriers.6300if (!driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {6301draw_graph.add_compute_list_uniform_set_prepare_for_use(compute_list.state.pipeline_shader_driver_id, compute_list.state.sets[i].uniform_set_driver_id, i);6302}6303}63046305// Bind descriptor sets.6306for (uint32_t i = first_set_index; i < compute_list.state.set_count; i++) {6307if (compute_list.state.sets[i].pipeline_expected_format == 0) {6308continue; // Nothing expected by this pipeline.6309}63106311if (!compute_list.state.sets[i].bound) {6312// All good, see if this requires re-binding.6313if (i - last_set_index > 1) {6314// If the descriptor sets are not contiguous, bind the previous ones and start a new batch.6315draw_graph.add_compute_list_bind_uniform_sets(compute_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);63166317first_set_index = i;6318valid_set_count = 1;6319valid_descriptor_ids[0] = compute_list.state.sets[i].uniform_set_driver_id;6320} else {6321// Otherwise, keep storing in the current batch.6322valid_descriptor_ids[valid_set_count] = compute_list.state.sets[i].uniform_set_driver_id;6323valid_set_count++;6324}63256326last_set_index = i;63276328UniformSet *uniform_set = uniform_set_owner.get_or_null(compute_list.state.sets[i].uniform_set);6329_uniform_set_update_shared(uniform_set);6330_uniform_set_update_clears(uniform_set);63316332draw_graph.add_compute_list_usages(uniform_set->draw_trackers, uniform_set->draw_trackers_usage);6333compute_list.state.sets[i].bound = true;6334}6335}63366337// Bind the remaining batch.6338if (valid_set_count > 0) {6339draw_graph.add_compute_list_bind_uniform_sets(compute_list.state.pipeline_shader_driver_id, valid_descriptor_ids, first_set_index, valid_set_count);6340}63416342draw_graph.add_compute_list_dispatch_indirect(buffer->driver_id, p_offset);6343compute_list.state.dispatch_count++;63446345if (buffer->draw_tracker != nullptr) {6346draw_graph.add_compute_list_usage(buffer->draw_tracker, RDG::RESOURCE_USAGE_INDIRECT_BUFFER_READ);6347}63486349_check_transfer_worker_buffer(buffer);6350}63516352void RenderingDevice::compute_list_add_barrier(ComputeListID p_list) {6353ERR_RENDER_THREAD_GUARD();63546355compute_list_barrier_state = compute_list.state;6356compute_list_end();6357compute_list_begin();63586359if (compute_list_barrier_state.pipeline.is_valid()) {6360compute_list_bind_compute_pipeline(p_list, compute_list_barrier_state.pipeline);6361}63626363for (uint32_t i = 0; i < compute_list_barrier_state.set_count; i++) {6364if (compute_list_barrier_state.sets[i].uniform_set.is_valid()) {6365compute_list_bind_uniform_set(p_list, compute_list_barrier_state.sets[i].uniform_set, i);6366}6367}63686369if (compute_list_barrier_state.push_constant_size > 0) {6370compute_list_set_push_constant(p_list, compute_list_barrier_state.push_constant_data, compute_list_barrier_state.push_constant_size);6371}6372}63736374void RenderingDevice::compute_list_end() {6375ERR_RENDER_THREAD_GUARD();63766377ERR_FAIL_COND(!compute_list.active);63786379draw_graph.add_compute_list_end();63806381compute_list = ComputeList();6382}63836384#ifndef DISABLE_DEPRECATED6385void RenderingDevice::barrier(BitField<BarrierMask> p_from, BitField<BarrierMask> p_to) {6386WARN_PRINT("Deprecated. Barriers are automatically inserted by RenderingDevice.");6387}63886389void RenderingDevice::full_barrier() {6390WARN_PRINT("Deprecated. Barriers are automatically inserted by RenderingDevice.");6391}6392#endif63936394/*************************/6395/**** TRANSFER WORKER ****/6396/*************************/63976398static uint32_t _get_alignment_offset(uint32_t p_offset, uint32_t p_required_align) {6399uint32_t alignment_offset = (p_required_align > 0) ? (p_offset % p_required_align) : 0;6400if (alignment_offset != 0) {6401// If a particular alignment is required, add the offset as part of the required size.6402alignment_offset = p_required_align - alignment_offset;6403}64046405return alignment_offset;6406}64076408RenderingDevice::TransferWorker *RenderingDevice::_acquire_transfer_worker(uint32_t p_transfer_size, uint32_t p_required_align, uint32_t &r_staging_offset) {6409// Find the first worker that is not currently executing anything and has enough size for the transfer.6410// If no workers are available, we make a new one. If we're not allowed to make new ones, we wait until one of them is available.6411TransferWorker *transfer_worker = nullptr;6412uint32_t available_list_index = 0;6413bool transfer_worker_busy = true;6414bool transfer_worker_full = true;6415{6416MutexLock pool_lock(transfer_worker_pool_mutex);64176418// If no workers are available and we've reached the max pool capacity, wait until one of them becomes available.6419bool transfer_worker_pool_full = transfer_worker_pool_size >= transfer_worker_pool_max_size;6420while (transfer_worker_pool_available_list.is_empty() && transfer_worker_pool_full) {6421transfer_worker_pool_condition.wait(pool_lock);6422}64236424// Look at all available workers first.6425for (uint32_t i = 0; i < transfer_worker_pool_available_list.size(); i++) {6426uint32_t worker_index = transfer_worker_pool_available_list[i];6427TransferWorker *candidate_worker = transfer_worker_pool[worker_index];6428candidate_worker->thread_mutex.lock();64296430// Figure out if the worker can fit the transfer.6431uint32_t alignment_offset = _get_alignment_offset(candidate_worker->staging_buffer_size_in_use, p_required_align);6432uint32_t required_size = candidate_worker->staging_buffer_size_in_use + p_transfer_size + alignment_offset;6433bool candidate_worker_busy = candidate_worker->submitted;6434bool candidate_worker_full = required_size > candidate_worker->staging_buffer_size_allocated;6435bool pick_candidate = false;6436if (!candidate_worker_busy && !candidate_worker_full) {6437// A worker that can fit the transfer and is not waiting for a previous execution is the best possible candidate.6438pick_candidate = true;6439} else if (!candidate_worker_busy) {6440// The worker can't fit the transfer but it's not currently doing anything.6441// We pick it as a possible candidate if the current one is busy.6442pick_candidate = transfer_worker_busy;6443} else if (!candidate_worker_full) {6444// The worker can fit the transfer but it's currently executing previous work.6445// We pick it as a possible candidate if the current one is both busy and full.6446pick_candidate = transfer_worker_busy && transfer_worker_full;6447} else if (transfer_worker == nullptr) {6448// The worker can't fit the transfer and it's currently executing work, so it's the worst candidate.6449// We only pick if no candidate has been picked yet.6450pick_candidate = true;6451}64526453if (pick_candidate) {6454if (transfer_worker != nullptr) {6455// Release the lock for the worker that was picked previously.6456transfer_worker->thread_mutex.unlock();6457}64586459// Keep the lock active for this worker.6460transfer_worker = candidate_worker;6461transfer_worker_busy = candidate_worker_busy;6462transfer_worker_full = candidate_worker_full;6463available_list_index = i;64646465if (!transfer_worker_busy && !transfer_worker_full) {6466// Best possible candidate, stop searching early.6467break;6468}6469} else {6470// Release the lock for the candidate.6471candidate_worker->thread_mutex.unlock();6472}6473}64746475if (transfer_worker != nullptr) {6476// A worker was picked, remove it from the available list.6477transfer_worker_pool_available_list.remove_at(available_list_index);6478} else {6479DEV_ASSERT(!transfer_worker_pool_full && "A transfer worker should never be created when the pool is full.");64806481// No existing worker was picked, we create a new one.6482uint32_t transfer_worker_index = transfer_worker_pool_size;6483++transfer_worker_pool_size;64846485transfer_worker = memnew(TransferWorker);6486transfer_worker->command_fence = driver->fence_create();6487transfer_worker->command_pool = driver->command_pool_create(transfer_queue_family, RDD::COMMAND_BUFFER_TYPE_PRIMARY);6488transfer_worker->command_buffer = driver->command_buffer_create(transfer_worker->command_pool);6489transfer_worker->index = transfer_worker_index;6490transfer_worker_pool[transfer_worker_index] = transfer_worker;6491transfer_worker_operation_used_by_draw[transfer_worker_index] = 0;6492transfer_worker->thread_mutex.lock();6493}6494}64956496if (transfer_worker->submitted) {6497// Wait for the worker if the command buffer was submitted but it hasn't finished processing yet.6498_wait_for_transfer_worker(transfer_worker);6499}65006501uint32_t alignment_offset = _get_alignment_offset(transfer_worker->staging_buffer_size_in_use, p_required_align);6502transfer_worker->max_transfer_size = MAX(transfer_worker->max_transfer_size, p_transfer_size);65036504uint32_t required_size = transfer_worker->staging_buffer_size_in_use + p_transfer_size + alignment_offset;6505if (required_size > transfer_worker->staging_buffer_size_allocated) {6506// If there's not enough bytes to use on the staging buffer, we submit everything pending from the worker and wait for the work to be finished.6507if (transfer_worker->recording) {6508_end_transfer_worker(transfer_worker);6509_submit_transfer_worker(transfer_worker);6510}65116512if (transfer_worker->submitted) {6513_wait_for_transfer_worker(transfer_worker);6514}65156516alignment_offset = 0;65176518// If the staging buffer can't fit the transfer, we recreate the buffer.6519const uint32_t expected_buffer_size_minimum = 16 * 1024;6520uint32_t expected_buffer_size = MAX(transfer_worker->max_transfer_size, expected_buffer_size_minimum);6521if (expected_buffer_size > transfer_worker->staging_buffer_size_allocated) {6522if (transfer_worker->staging_buffer.id != 0) {6523driver->buffer_free(transfer_worker->staging_buffer);6524}65256526uint32_t new_staging_buffer_size = next_power_of_2(expected_buffer_size);6527transfer_worker->staging_buffer_size_allocated = new_staging_buffer_size;6528transfer_worker->staging_buffer = driver->buffer_create(new_staging_buffer_size, RDD::BUFFER_USAGE_TRANSFER_FROM_BIT, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);6529}6530}65316532// Add the alignment before storing the offset that will be returned.6533transfer_worker->staging_buffer_size_in_use += alignment_offset;65346535// Store the offset to return and increment the current size.6536r_staging_offset = transfer_worker->staging_buffer_size_in_use;6537transfer_worker->staging_buffer_size_in_use += p_transfer_size;65386539if (!transfer_worker->recording) {6540// Begin the command buffer if the worker wasn't recording yet.6541driver->command_buffer_begin(transfer_worker->command_buffer);6542transfer_worker->recording = true;6543}65446545return transfer_worker;6546}65476548void RenderingDevice::_release_transfer_worker(TransferWorker *p_transfer_worker) {6549p_transfer_worker->thread_mutex.unlock();65506551transfer_worker_pool_mutex.lock();6552transfer_worker_pool_available_list.push_back(p_transfer_worker->index);6553transfer_worker_pool_mutex.unlock();6554transfer_worker_pool_condition.notify_one();6555}65566557void RenderingDevice::_end_transfer_worker(TransferWorker *p_transfer_worker) {6558driver->command_buffer_end(p_transfer_worker->command_buffer);6559p_transfer_worker->recording = false;6560}65616562void RenderingDevice::_submit_transfer_worker(TransferWorker *p_transfer_worker, VectorView<RDD::SemaphoreID> p_signal_semaphores) {6563driver->command_queue_execute_and_present(transfer_queue, {}, p_transfer_worker->command_buffer, p_signal_semaphores, p_transfer_worker->command_fence, {});65646565for (uint32_t i = 0; i < p_signal_semaphores.size(); i++) {6566// Indicate the frame should wait on these semaphores before executing the main command buffer.6567frames[frame].semaphores_to_wait_on.push_back(p_signal_semaphores[i]);6568}65696570p_transfer_worker->submitted = true;65716572{6573MutexLock lock(p_transfer_worker->operations_mutex);6574p_transfer_worker->operations_submitted = p_transfer_worker->operations_counter;6575}6576}65776578void RenderingDevice::_wait_for_transfer_worker(TransferWorker *p_transfer_worker) {6579driver->fence_wait(p_transfer_worker->command_fence);6580driver->command_pool_reset(p_transfer_worker->command_pool);6581p_transfer_worker->staging_buffer_size_in_use = 0;6582p_transfer_worker->submitted = false;65836584{6585MutexLock lock(p_transfer_worker->operations_mutex);6586p_transfer_worker->operations_processed = p_transfer_worker->operations_submitted;6587}65886589_flush_barriers_for_transfer_worker(p_transfer_worker);6590}65916592void RenderingDevice::_flush_barriers_for_transfer_worker(TransferWorker *p_transfer_worker) {6593// Caller must have already acquired the mutex for the worker.6594if (!p_transfer_worker->texture_barriers.is_empty()) {6595MutexLock transfer_worker_lock(transfer_worker_pool_texture_barriers_mutex);6596for (uint32_t i = 0; i < p_transfer_worker->texture_barriers.size(); i++) {6597transfer_worker_pool_texture_barriers.push_back(p_transfer_worker->texture_barriers[i]);6598}65996600p_transfer_worker->texture_barriers.clear();6601}6602}66036604void RenderingDevice::_check_transfer_worker_operation(uint32_t p_transfer_worker_index, uint64_t p_transfer_worker_operation) {6605TransferWorker *transfer_worker = transfer_worker_pool[p_transfer_worker_index];6606MutexLock lock(transfer_worker->operations_mutex);6607uint64_t &dst_operation = transfer_worker_operation_used_by_draw[transfer_worker->index];6608dst_operation = MAX(dst_operation, p_transfer_worker_operation);6609}66106611void RenderingDevice::_check_transfer_worker_buffer(Buffer *p_buffer) {6612if (p_buffer->transfer_worker_index >= 0) {6613_check_transfer_worker_operation(p_buffer->transfer_worker_index, p_buffer->transfer_worker_operation);6614p_buffer->transfer_worker_index = -1;6615}6616}66176618void RenderingDevice::_check_transfer_worker_texture(Texture *p_texture) {6619if (p_texture->transfer_worker_index >= 0) {6620_check_transfer_worker_operation(p_texture->transfer_worker_index, p_texture->transfer_worker_operation);6621p_texture->transfer_worker_index = -1;6622}6623}66246625void RenderingDevice::_check_transfer_worker_vertex_array(VertexArray *p_vertex_array) {6626if (!p_vertex_array->transfer_worker_indices.is_empty()) {6627for (int i = 0; i < p_vertex_array->transfer_worker_indices.size(); i++) {6628_check_transfer_worker_operation(p_vertex_array->transfer_worker_indices[i], p_vertex_array->transfer_worker_operations[i]);6629}66306631p_vertex_array->transfer_worker_indices.clear();6632p_vertex_array->transfer_worker_operations.clear();6633}6634}66356636void RenderingDevice::_check_transfer_worker_index_array(IndexArray *p_index_array) {6637if (p_index_array->transfer_worker_index >= 0) {6638_check_transfer_worker_operation(p_index_array->transfer_worker_index, p_index_array->transfer_worker_operation);6639p_index_array->transfer_worker_index = -1;6640}6641}66426643void RenderingDevice::_submit_transfer_workers(RDD::CommandBufferID p_draw_command_buffer) {6644MutexLock transfer_worker_lock(transfer_worker_pool_mutex);6645for (uint32_t i = 0; i < transfer_worker_pool_size; i++) {6646TransferWorker *worker = transfer_worker_pool[i];6647if (p_draw_command_buffer) {6648MutexLock lock(worker->operations_mutex);6649if (worker->operations_processed >= transfer_worker_operation_used_by_draw[worker->index]) {6650// The operation used by the draw has already been processed, we don't need to wait on the worker.6651continue;6652}6653}66546655{6656MutexLock lock(worker->thread_mutex);6657if (worker->recording) {6658VectorView<RDD::SemaphoreID> semaphores = p_draw_command_buffer ? frames[frame].transfer_worker_semaphores[i] : VectorView<RDD::SemaphoreID>();6659_end_transfer_worker(worker);6660_submit_transfer_worker(worker, semaphores);6661}66626663if (p_draw_command_buffer) {6664_flush_barriers_for_transfer_worker(worker);6665}6666}6667}6668}66696670void RenderingDevice::_submit_transfer_barriers(RDD::CommandBufferID p_draw_command_buffer) {6671MutexLock transfer_worker_lock(transfer_worker_pool_texture_barriers_mutex);6672if (!transfer_worker_pool_texture_barriers.is_empty()) {6673driver->command_pipeline_barrier(p_draw_command_buffer, RDD::PIPELINE_STAGE_COPY_BIT, RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, transfer_worker_pool_texture_barriers, {});6674transfer_worker_pool_texture_barriers.clear();6675}6676}66776678void RenderingDevice::_wait_for_transfer_workers() {6679MutexLock transfer_worker_lock(transfer_worker_pool_mutex);6680for (uint32_t i = 0; i < transfer_worker_pool_size; i++) {6681TransferWorker *worker = transfer_worker_pool[i];6682MutexLock lock(worker->thread_mutex);6683if (worker->submitted) {6684_wait_for_transfer_worker(worker);6685}6686}6687}66886689void RenderingDevice::_free_transfer_workers() {6690MutexLock transfer_worker_lock(transfer_worker_pool_mutex);6691for (uint32_t i = 0; i < transfer_worker_pool_size; i++) {6692TransferWorker *worker = transfer_worker_pool[i];6693driver->fence_free(worker->command_fence);6694driver->buffer_free(worker->staging_buffer);6695driver->command_pool_free(worker->command_pool);6696memdelete(worker);6697}66986699transfer_worker_pool_size = 0;6700}67016702/***********************/6703/**** COMMAND GRAPH ****/6704/***********************/67056706bool RenderingDevice::_texture_make_mutable(Texture *p_texture, RID p_texture_id) {6707if (p_texture->draw_tracker != nullptr) {6708// Texture already has a tracker.6709return false;6710} else {6711if (p_texture->owner.is_valid()) {6712// Texture has an owner.6713Texture *owner_texture = texture_owner.get_or_null(p_texture->owner);6714ERR_FAIL_NULL_V(owner_texture, false);67156716if (owner_texture->draw_tracker != nullptr) {6717// Create a tracker for this dependency in particular.6718if (p_texture->slice_type == TEXTURE_SLICE_MAX) {6719// Shared texture.6720p_texture->draw_tracker = owner_texture->draw_tracker;6721p_texture->draw_tracker->reference_count++;6722} else {6723// Slice texture.6724if (owner_texture->slice_trackers == nullptr) {6725owner_texture->slice_trackers = memnew((HashMap<Rect2i, RDG::ResourceTracker *>));6726}6727HashMap<Rect2i, RDG::ResourceTracker *>::ConstIterator draw_tracker_iterator = owner_texture->slice_trackers->find(p_texture->slice_rect);6728RDG::ResourceTracker *draw_tracker = nullptr;6729if (draw_tracker_iterator != owner_texture->slice_trackers->end()) {6730// Reuse the tracker at the matching rectangle.6731draw_tracker = draw_tracker_iterator->value;6732} else {6733// Create a new tracker and store it on the map.6734draw_tracker = RDG::resource_tracker_create();6735draw_tracker->parent = owner_texture->draw_tracker;6736draw_tracker->texture_driver_id = p_texture->driver_id;6737draw_tracker->texture_size = Size2i(p_texture->width, p_texture->height);6738draw_tracker->texture_subresources = p_texture->barrier_range();6739draw_tracker->texture_usage = p_texture->usage_flags;6740draw_tracker->texture_slice_or_dirty_rect = p_texture->slice_rect;6741(*owner_texture->slice_trackers)[p_texture->slice_rect] = draw_tracker;6742}67436744p_texture->draw_tracker = draw_tracker;6745p_texture->draw_tracker->reference_count++;6746}67476748if (p_texture_id.is_valid()) {6749_dependencies_make_mutable(p_texture_id, p_texture->draw_tracker);6750}6751} else {6752// Delegate this to the owner instead, as it'll make all its dependencies mutable.6753_texture_make_mutable(owner_texture, p_texture->owner);6754}6755} else {6756// Regular texture.6757p_texture->draw_tracker = RDG::resource_tracker_create();6758p_texture->draw_tracker->texture_driver_id = p_texture->driver_id;6759p_texture->draw_tracker->texture_size = Size2i(p_texture->width, p_texture->height);6760p_texture->draw_tracker->texture_subresources = p_texture->barrier_range();6761p_texture->draw_tracker->texture_usage = p_texture->usage_flags;6762p_texture->draw_tracker->is_discardable = p_texture->is_discardable;6763p_texture->draw_tracker->reference_count = 1;67646765if (p_texture_id.is_valid()) {6766if (p_texture->has_initial_data) {6767// If the texture was initialized with initial data but wasn't made mutable from the start, assume the texture sampling usage.6768p_texture->draw_tracker->usage = RDG::RESOURCE_USAGE_TEXTURE_SAMPLE;6769}67706771_dependencies_make_mutable(p_texture_id, p_texture->draw_tracker);6772}6773}67746775return true;6776}6777}67786779bool RenderingDevice::_buffer_make_mutable(Buffer *p_buffer, RID p_buffer_id) {6780if (p_buffer->draw_tracker != nullptr) {6781// Buffer already has a tracker.6782return false;6783} else {6784// Create a tracker for the buffer and make all its dependencies mutable.6785p_buffer->draw_tracker = RDG::resource_tracker_create();6786p_buffer->draw_tracker->buffer_driver_id = p_buffer->driver_id;6787if (p_buffer_id.is_valid()) {6788_dependencies_make_mutable(p_buffer_id, p_buffer->draw_tracker);6789}67906791return true;6792}6793}67946795bool RenderingDevice::_vertex_array_make_mutable(VertexArray *p_vertex_array, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {6796if (!p_vertex_array->untracked_buffers.has(p_resource_id)) {6797// Vertex array thinks the buffer is already tracked or does not use it.6798return false;6799} else {6800// Vertex array is aware of the buffer but it isn't being tracked.6801p_vertex_array->draw_trackers.push_back(p_resource_tracker);6802p_vertex_array->untracked_buffers.erase(p_resource_id);6803return true;6804}6805}68066807bool RenderingDevice::_index_array_make_mutable(IndexArray *p_index_array, RDG::ResourceTracker *p_resource_tracker) {6808if (p_index_array->draw_tracker != nullptr) {6809// Index array already has a tracker.6810return false;6811} else {6812// Index array should assign the tracker from the buffer.6813p_index_array->draw_tracker = p_resource_tracker;6814return true;6815}6816}68176818bool RenderingDevice::_uniform_set_make_mutable(UniformSet *p_uniform_set, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {6819HashMap<RID, RDG::ResourceUsage>::Iterator E = p_uniform_set->untracked_usage.find(p_resource_id);6820if (!E) {6821// Uniform set thinks the resource is already tracked or does not use it.6822return false;6823} else {6824// Uniform set has seen the resource but hasn't added its tracker yet.6825p_uniform_set->draw_trackers.push_back(p_resource_tracker);6826p_uniform_set->draw_trackers_usage.push_back(E->value);6827p_uniform_set->untracked_usage.remove(E);6828return true;6829}6830}68316832bool RenderingDevice::_dependency_make_mutable(RID p_id, RID p_resource_id, RDG::ResourceTracker *p_resource_tracker) {6833if (texture_owner.owns(p_id)) {6834Texture *texture = texture_owner.get_or_null(p_id);6835return _texture_make_mutable(texture, p_id);6836} else if (vertex_array_owner.owns(p_id)) {6837VertexArray *vertex_array = vertex_array_owner.get_or_null(p_id);6838return _vertex_array_make_mutable(vertex_array, p_resource_id, p_resource_tracker);6839} else if (index_array_owner.owns(p_id)) {6840IndexArray *index_array = index_array_owner.get_or_null(p_id);6841return _index_array_make_mutable(index_array, p_resource_tracker);6842} else if (uniform_set_owner.owns(p_id)) {6843UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);6844return _uniform_set_make_mutable(uniform_set, p_resource_id, p_resource_tracker);6845} else {6846DEV_ASSERT(false && "Unknown resource type to make mutable.");6847return false;6848}6849}68506851bool RenderingDevice::_dependencies_make_mutable_recursive(RID p_id, RDG::ResourceTracker *p_resource_tracker) {6852bool made_mutable = false;6853HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);6854if (E) {6855for (RID rid : E->value) {6856made_mutable = _dependency_make_mutable(rid, p_id, p_resource_tracker) || made_mutable;6857}6858}68596860return made_mutable;6861}68626863bool RenderingDevice::_dependencies_make_mutable(RID p_id, RDG::ResourceTracker *p_resource_tracker) {6864_THREAD_SAFE_METHOD_6865return _dependencies_make_mutable_recursive(p_id, p_resource_tracker);6866}68676868/**************************/6869/**** FRAME MANAGEMENT ****/6870/**************************/68716872void RenderingDevice::free_rid(RID p_rid) {6873ERR_RENDER_THREAD_GUARD();68746875_free_dependencies(p_rid); // Recursively erase dependencies first, to avoid potential API problems.6876_free_internal(p_rid);6877}68786879void RenderingDevice::_free_internal(RID p_id) {6880#ifdef DEV_ENABLED6881String resource_name;6882if (resource_names.has(p_id)) {6883resource_name = resource_names[p_id];6884resource_names.erase(p_id);6885}6886#endif68876888// Push everything so it's disposed of next time this frame index is processed (means, it's safe to do it).6889if (texture_owner.owns(p_id)) {6890Texture *texture = texture_owner.get_or_null(p_id);6891_check_transfer_worker_texture(texture);68926893RDG::ResourceTracker *draw_tracker = texture->draw_tracker;6894if (draw_tracker != nullptr) {6895draw_tracker->reference_count--;6896if (draw_tracker->reference_count == 0) {6897RDG::resource_tracker_free(draw_tracker);68986899if (texture->owner.is_valid() && (texture->slice_type != TEXTURE_SLICE_MAX)) {6900// If this was a texture slice, erase the tracker from the map.6901Texture *owner_texture = texture_owner.get_or_null(texture->owner);6902if (owner_texture != nullptr && owner_texture->slice_trackers != nullptr) {6903owner_texture->slice_trackers->erase(texture->slice_rect);69046905if (owner_texture->slice_trackers->is_empty()) {6906memdelete(owner_texture->slice_trackers);6907owner_texture->slice_trackers = nullptr;6908}6909}6910}6911}6912}69136914frames[frame].textures_to_dispose_of.push_back(*texture);6915texture_owner.free(p_id);6916} else if (framebuffer_owner.owns(p_id)) {6917Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);6918frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);69196920if (framebuffer->invalidated_callback != nullptr) {6921framebuffer->invalidated_callback(framebuffer->invalidated_callback_userdata);6922}69236924framebuffer_owner.free(p_id);6925} else if (sampler_owner.owns(p_id)) {6926RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id);6927frames[frame].samplers_to_dispose_of.push_back(sampler_driver_id);6928sampler_owner.free(p_id);6929} else if (vertex_buffer_owner.owns(p_id)) {6930Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);6931_check_transfer_worker_buffer(vertex_buffer);69326933RDG::resource_tracker_free(vertex_buffer->draw_tracker);6934frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);6935vertex_buffer_owner.free(p_id);6936} else if (vertex_array_owner.owns(p_id)) {6937vertex_array_owner.free(p_id);6938} else if (index_buffer_owner.owns(p_id)) {6939IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);6940_check_transfer_worker_buffer(index_buffer);69416942RDG::resource_tracker_free(index_buffer->draw_tracker);6943frames[frame].buffers_to_dispose_of.push_back(*index_buffer);6944index_buffer_owner.free(p_id);6945} else if (index_array_owner.owns(p_id)) {6946index_array_owner.free(p_id);6947} else if (shader_owner.owns(p_id)) {6948Shader *shader = shader_owner.get_or_null(p_id);6949if (shader->driver_id) { // Not placeholder?6950frames[frame].shaders_to_dispose_of.push_back(*shader);6951}6952shader_owner.free(p_id);6953} else if (uniform_buffer_owner.owns(p_id)) {6954Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);6955_check_transfer_worker_buffer(uniform_buffer);69566957RDG::resource_tracker_free(uniform_buffer->draw_tracker);6958frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);6959uniform_buffer_owner.free(p_id);6960} else if (texture_buffer_owner.owns(p_id)) {6961Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);6962_check_transfer_worker_buffer(texture_buffer);69636964RDG::resource_tracker_free(texture_buffer->draw_tracker);6965frames[frame].buffers_to_dispose_of.push_back(*texture_buffer);6966texture_buffer_owner.free(p_id);6967} else if (storage_buffer_owner.owns(p_id)) {6968Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);6969_check_transfer_worker_buffer(storage_buffer);69706971RDG::resource_tracker_free(storage_buffer->draw_tracker);6972frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);6973storage_buffer_owner.free(p_id);6974} else if (instances_buffer_owner.owns(p_id)) {6975InstancesBuffer *instances_buffer = instances_buffer_owner.get_or_null(p_id);6976_check_transfer_worker_buffer(&instances_buffer->buffer);69776978RDG::resource_tracker_free(instances_buffer->buffer.draw_tracker);6979frames[frame].buffers_to_dispose_of.push_back(instances_buffer->buffer);6980instances_buffer_owner.free(p_id);6981} else if (uniform_set_owner.owns(p_id)) {6982UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);6983frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);6984uniform_set_owner.free(p_id);69856986if (uniform_set->invalidated_callback != nullptr) {6987uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);6988}6989} else if (render_pipeline_owner.owns(p_id)) {6990RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);6991frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);6992render_pipeline_owner.free(p_id);6993} else if (compute_pipeline_owner.owns(p_id)) {6994ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);6995frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);6996compute_pipeline_owner.free(p_id);6997} else if (acceleration_structure_owner.owns(p_id)) {6998AccelerationStructure *acceleration_structure = acceleration_structure_owner.get_or_null(p_id);6999frames[frame].acceleration_structures_to_dispose_of.push_back(*acceleration_structure);7000acceleration_structure_owner.free(p_id);7001} else if (raytracing_pipeline_owner.owns(p_id)) {7002RaytracingPipeline *pipeline = raytracing_pipeline_owner.get_or_null(p_id);7003frames[frame].raytracing_pipelines_to_dispose_of.push_back(*pipeline);7004raytracing_pipeline_owner.free(p_id);7005} else {7006#ifdef DEV_ENABLED7007ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()) + " " + resource_name);7008#else7009ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));7010#endif7011}70127013frames_pending_resources_for_processing = uint32_t(frames.size());7014}70157016// The full list of resources that can be named is in the VkObjectType enum.7017// We just expose the resources that are owned and can be accessed easily.7018void RenderingDevice::set_resource_name(RID p_id, const String &p_name) {7019_THREAD_SAFE_METHOD_70207021if (texture_owner.owns(p_id)) {7022Texture *texture = texture_owner.get_or_null(p_id);7023driver->set_object_name(RDD::OBJECT_TYPE_TEXTURE, texture->driver_id, p_name);7024} else if (framebuffer_owner.owns(p_id)) {7025//Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);7026// Not implemented for now as the relationship between Framebuffer and RenderPass is very complex.7027} else if (sampler_owner.owns(p_id)) {7028RDD::SamplerID sampler_driver_id = *sampler_owner.get_or_null(p_id);7029driver->set_object_name(RDD::OBJECT_TYPE_SAMPLER, sampler_driver_id, p_name);7030} else if (vertex_buffer_owner.owns(p_id)) {7031Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);7032driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, vertex_buffer->driver_id, p_name);7033} else if (index_buffer_owner.owns(p_id)) {7034IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);7035driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, index_buffer->driver_id, p_name);7036} else if (shader_owner.owns(p_id)) {7037Shader *shader = shader_owner.get_or_null(p_id);7038driver->set_object_name(RDD::OBJECT_TYPE_SHADER, shader->driver_id, p_name);7039} else if (uniform_buffer_owner.owns(p_id)) {7040Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);7041driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, uniform_buffer->driver_id, p_name);7042} else if (texture_buffer_owner.owns(p_id)) {7043Buffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);7044driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, texture_buffer->driver_id, p_name);7045} else if (storage_buffer_owner.owns(p_id)) {7046Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);7047driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, storage_buffer->driver_id, p_name);7048} else if (instances_buffer_owner.owns(p_id)) {7049InstancesBuffer *instances_buffer = instances_buffer_owner.get_or_null(p_id);7050driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, instances_buffer->buffer.driver_id, p_name);7051} else if (uniform_set_owner.owns(p_id)) {7052UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);7053driver->set_object_name(RDD::OBJECT_TYPE_UNIFORM_SET, uniform_set->driver_id, p_name);7054} else if (render_pipeline_owner.owns(p_id)) {7055RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);7056driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name);7057} else if (compute_pipeline_owner.owns(p_id)) {7058ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);7059driver->set_object_name(RDD::OBJECT_TYPE_PIPELINE, pipeline->driver_id, p_name);7060} else if (acceleration_structure_owner.owns(p_id)) {7061AccelerationStructure *acceleration_structure = acceleration_structure_owner.get_or_null(p_id);7062driver->set_object_name(RDD::OBJECT_TYPE_ACCELERATION_STRUCTURE, acceleration_structure->driver_id, p_name);7063} else if (raytracing_pipeline_owner.owns(p_id)) {7064RaytracingPipeline *pipeline = raytracing_pipeline_owner.get_or_null(p_id);7065driver->set_object_name(RDD::OBJECT_TYPE_RAYTRACING_PIPELINE, pipeline->driver_id, p_name);7066} else {7067ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));7068return;7069}7070#ifdef DEV_ENABLED7071resource_names[p_id] = p_name;7072#endif7073}70747075void RenderingDevice::_draw_command_begin_label(String p_label_name, const Color &p_color) {7076draw_command_begin_label(p_label_name.utf8().span(), p_color);7077}70787079void RenderingDevice::draw_command_begin_label(const Span<char> p_label_name, const Color &p_color) {7080ERR_RENDER_THREAD_GUARD();70817082if (!context->is_debug_utils_enabled()) {7083return;7084}70857086draw_graph.begin_label(p_label_name, p_color);7087}70887089#ifndef DISABLE_DEPRECATED7090void RenderingDevice::draw_command_insert_label(String p_label_name, const Color &p_color) {7091WARN_PRINT("Deprecated. Inserting labels no longer applies due to command reordering.");7092}7093#endif70947095void RenderingDevice::draw_command_end_label() {7096ERR_RENDER_THREAD_GUARD();70977098draw_graph.end_label();7099}71007101String RenderingDevice::get_device_vendor_name() const {7102return _get_device_vendor_name(device);7103}71047105String RenderingDevice::get_device_name() const {7106return device.name;7107}71087109RenderingDevice::DeviceType RenderingDevice::get_device_type() const {7110return DeviceType(device.type);7111}71127113String RenderingDevice::get_device_api_name() const {7114return driver->get_api_name();7115}71167117bool RenderingDevice::is_composite_alpha_supported() const {7118return driver->is_composite_alpha_supported(main_queue);7119}71207121String RenderingDevice::get_device_api_version() const {7122return driver->get_api_version();7123}71247125String RenderingDevice::get_device_pipeline_cache_uuid() const {7126return driver->get_pipeline_cache_uuid();7127}71287129void RenderingDevice::swap_buffers(bool p_present) {7130ERR_RENDER_THREAD_GUARD();71317132GodotProfileZoneGroupedFirst(_profile_zone, "_end_frame");7133_end_frame();71347135GodotProfileZoneGrouped(_profile_zone, "_execute_frame");7136_execute_frame(p_present);71377138// Advance to the next frame and begin recording again.7139frame = (frame + 1) % frames.size();71407141GodotProfileZoneGrouped(_profile_zone, "_begin_frame");7142_begin_frame(true);7143}71447145void RenderingDevice::submit() {7146ERR_RENDER_THREAD_GUARD();7147ERR_FAIL_COND_MSG(is_main_instance, "Only local devices can submit and sync.");7148ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");71497150_end_frame();7151_execute_frame(false);7152local_device_processing = true;7153}71547155void RenderingDevice::sync() {7156ERR_RENDER_THREAD_GUARD();7157ERR_FAIL_COND_MSG(is_main_instance, "Only local devices can submit and sync.");7158ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");71597160_begin_frame(true);7161local_device_processing = false;7162}71637164void RenderingDevice::_free_pending_resources(int p_frame) {7165// Free in dependency usage order, so nothing weird happens.7166// Pipelines.7167while (frames[p_frame].render_pipelines_to_dispose_of.front()) {7168RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();71697170driver->pipeline_free(pipeline->driver_id);71717172frames[p_frame].render_pipelines_to_dispose_of.pop_front();7173}71747175while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {7176ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();71777178driver->pipeline_free(pipeline->driver_id);71797180frames[p_frame].compute_pipelines_to_dispose_of.pop_front();7181}71827183while (frames[p_frame].raytracing_pipelines_to_dispose_of.front()) {7184RaytracingPipeline *pipeline = &frames[p_frame].raytracing_pipelines_to_dispose_of.front()->get();71857186driver->raytracing_pipeline_free(pipeline->driver_id);71877188frames[p_frame].raytracing_pipelines_to_dispose_of.pop_front();7189}71907191// Acceleration structures.7192while (frames[p_frame].acceleration_structures_to_dispose_of.front()) {7193AccelerationStructure &acceleration_structure = frames[p_frame].acceleration_structures_to_dispose_of.front()->get();71947195if (acceleration_structure.scratch_buffer != RID()) {7196free_rid(acceleration_structure.scratch_buffer);7197}7198driver->acceleration_structure_free(acceleration_structure.driver_id);71997200frames[p_frame].acceleration_structures_to_dispose_of.pop_front();7201}72027203// Uniform sets.7204while (frames[p_frame].uniform_sets_to_dispose_of.front()) {7205UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();72067207driver->uniform_set_free(uniform_set->driver_id);72087209frames[p_frame].uniform_sets_to_dispose_of.pop_front();7210}72117212// Shaders.7213while (frames[p_frame].shaders_to_dispose_of.front()) {7214Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();72157216driver->shader_free(shader->driver_id);72177218frames[p_frame].shaders_to_dispose_of.pop_front();7219}72207221// Samplers.7222while (frames[p_frame].samplers_to_dispose_of.front()) {7223RDD::SamplerID sampler = frames[p_frame].samplers_to_dispose_of.front()->get();72247225driver->sampler_free(sampler);72267227frames[p_frame].samplers_to_dispose_of.pop_front();7228}72297230// Framebuffers.7231while (frames[p_frame].framebuffers_to_dispose_of.front()) {7232Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();7233draw_graph.framebuffer_cache_free(driver, framebuffer->framebuffer_cache);7234frames[p_frame].framebuffers_to_dispose_of.pop_front();7235}72367237// Textures.7238while (frames[p_frame].textures_to_dispose_of.front()) {7239Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();7240if (texture->bound) {7241WARN_PRINT("Deleted a texture while it was bound.");7242}72437244_texture_free_shared_fallback(texture);72457246texture_memory -= driver->texture_get_allocation_size(texture->driver_id);7247driver->texture_free(texture->driver_id);72487249frames[p_frame].textures_to_dispose_of.pop_front();7250}72517252// Buffers.7253while (frames[p_frame].buffers_to_dispose_of.front()) {7254Buffer &buffer = frames[p_frame].buffers_to_dispose_of.front()->get();7255driver->buffer_free(buffer.driver_id);7256buffer_memory -= buffer.size;72577258frames[p_frame].buffers_to_dispose_of.pop_front();7259}72607261if (frames_pending_resources_for_processing > 0u) {7262--frames_pending_resources_for_processing;7263}7264}72657266uint32_t RenderingDevice::get_frame_delay() const {7267return frames.size();7268}72697270uint64_t RenderingDevice::get_memory_usage(MemoryType p_type) const {7271switch (p_type) {7272case MEMORY_BUFFERS: {7273return buffer_memory;7274}7275case MEMORY_TEXTURES: {7276return texture_memory;7277}7278case MEMORY_TOTAL: {7279return driver->get_total_memory_used();7280}7281default: {7282DEV_ASSERT(false);7283return 0;7284}7285}7286}72877288void RenderingDevice::_begin_frame(bool p_presented) {7289GodotProfileZoneGroupedFirst(_profile_zone, "_stall_for_frame");7290// Before writing to this frame, wait for it to be finished.7291_stall_for_frame(frame);72927293if (command_pool_reset_enabled) {7294GodotProfileZoneGrouped(_profile_zone, "driver->command_pool_reset");7295bool reset = driver->command_pool_reset(frames[frame].command_pool);7296ERR_FAIL_COND(!reset);7297}72987299if (p_presented) {7300GodotProfileZoneGrouped(_profile_zone, "update_perf_report");7301update_perf_report();7302driver->linear_uniform_set_pools_reset(frame);7303}73047305// Begin recording on the frame's command buffers.7306GodotProfileZoneGrouped(_profile_zone, "driver->begin_segment");7307driver->begin_segment(frame, frames_drawn++);7308GodotProfileZoneGrouped(_profile_zone, "driver->command_buffer_begin");7309driver->command_buffer_begin(frames[frame].command_buffer);73107311// Reset the graph.7312GodotProfileZoneGrouped(_profile_zone, "draw_graph.begin");7313draw_graph.begin();73147315// Erase pending resources.7316GodotProfileZoneGrouped(_profile_zone, "_free_pending_resources");7317_free_pending_resources(frame);73187319// Advance staging buffers if used.7320if (upload_staging_buffers.used) {7321upload_staging_buffers.current = (upload_staging_buffers.current + 1) % upload_staging_buffers.blocks.size();7322upload_staging_buffers.used = false;7323}73247325if (download_staging_buffers.used) {7326download_staging_buffers.current = (download_staging_buffers.current + 1) % download_staging_buffers.blocks.size();7327download_staging_buffers.used = false;7328}73297330if (frames[frame].timestamp_count) {7331driver->timestamp_query_pool_get_results(frames[frame].timestamp_pool, frames[frame].timestamp_count, frames[frame].timestamp_result_values.ptr());7332driver->command_timestamp_query_pool_reset(frames[frame].command_buffer, frames[frame].timestamp_pool, frames[frame].timestamp_count);7333SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);7334SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);7335}73367337frames[frame].timestamp_result_count = frames[frame].timestamp_count;7338frames[frame].timestamp_count = 0;7339frames[frame].index = Engine::get_singleton()->get_frames_drawn();7340}73417342void RenderingDevice::_end_frame() {7343if (draw_list.active) {7344ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");7345}73467347if (compute_list.active) {7348ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");7349}73507351if (raytracing_list.active) {7352ERR_PRINT("Found open raytracing list at the end of the frame, this should never happen (further raytracing will likely not work).");7353}73547355// The command buffer must be copied into a stack variable as the driver workarounds can change the command buffer in use.7356RDD::CommandBufferID command_buffer = frames[frame].command_buffer;7357GodotProfileZoneGroupedFirst(_profile_zone, "_submit_transfer_workers");7358_submit_transfer_workers(command_buffer);7359GodotProfileZoneGrouped(_profile_zone, "_submit_transfer_barriers");7360_submit_transfer_barriers(command_buffer);73617362GodotProfileZoneGrouped(_profile_zone, "draw_graph.end");7363draw_graph.end(RENDER_GRAPH_REORDER, RENDER_GRAPH_FULL_BARRIERS, command_buffer, frames[frame].command_buffer_pool);7364GodotProfileZoneGrouped(_profile_zone, "driver->command_buffer_end");7365driver->command_buffer_end(command_buffer);7366GodotProfileZoneGrouped(_profile_zone, "driver->end_segment");7367driver->end_segment();7368}73697370void RenderingDevice::execute_chained_cmds(bool p_present_swap_chain, RenderingDeviceDriver::FenceID p_draw_fence,7371RenderingDeviceDriver::SemaphoreID p_dst_draw_semaphore_to_signal) {7372// Execute command buffers and use semaphores to wait on the execution of the previous one.7373// Normally there's only one command buffer, but driver workarounds can force situations where7374// there'll be more.7375uint32_t command_buffer_count = 1;7376RDG::CommandBufferPool &buffer_pool = frames[frame].command_buffer_pool;7377if (buffer_pool.buffers_used > 0) {7378command_buffer_count += buffer_pool.buffers_used;7379buffer_pool.buffers_used = 0;7380}73817382thread_local LocalVector<RDD::SwapChainID> swap_chains;7383swap_chains.clear();73847385// Instead of having just one command; we have potentially many (which had to be split due to an7386// Adreno workaround on mobile, only if the workaround is active). Thus we must execute all of them7387// and chain them together via semaphores as dependent executions.7388thread_local LocalVector<RDD::SemaphoreID> wait_semaphores;7389wait_semaphores = frames[frame].semaphores_to_wait_on;73907391for (uint32_t i = 0; i < command_buffer_count; i++) {7392RDD::CommandBufferID command_buffer;7393RDD::SemaphoreID signal_semaphore;7394RDD::FenceID signal_fence;7395if (i > 0) {7396command_buffer = buffer_pool.buffers[i - 1];7397} else {7398command_buffer = frames[frame].command_buffer;7399}74007401if (i == (command_buffer_count - 1)) {7402// This is the last command buffer, it should signal the semaphore & fence.7403signal_semaphore = p_dst_draw_semaphore_to_signal;7404signal_fence = p_draw_fence;74057406if (p_present_swap_chain) {7407// Just present the swap chains as part of the last command execution.7408swap_chains = frames[frame].swap_chains_to_present;7409}7410} else {7411signal_semaphore = buffer_pool.semaphores[i];7412// Semaphores always need to be signaled if it's not the last command buffer.7413}74147415driver->command_queue_execute_and_present(main_queue, wait_semaphores, command_buffer,7416signal_semaphore ? signal_semaphore : VectorView<RDD::SemaphoreID>(), signal_fence,7417swap_chains);74187419// Make the next command buffer wait on the semaphore signaled by this one.7420wait_semaphores.resize(1);7421wait_semaphores[0] = signal_semaphore;7422}74237424frames[frame].semaphores_to_wait_on.clear();7425}74267427void RenderingDevice::_execute_frame(bool p_present) {7428// Check whether this frame should present the swap chains and in which queue.7429const bool frame_can_present = p_present && !frames[frame].swap_chains_to_present.is_empty();7430const bool separate_present_queue = main_queue != present_queue;74317432// The semaphore is required if the frame can be presented and a separate present queue is used;7433// since the separate queue will wait for that semaphore before presenting.7434const RDD::SemaphoreID semaphore = (frame_can_present && separate_present_queue)7435? frames[frame].semaphore7436: RDD::SemaphoreID(nullptr);7437const bool present_swap_chain = frame_can_present && !separate_present_queue;74387439execute_chained_cmds(present_swap_chain, frames[frame].fence, semaphore);7440// Indicate the fence has been signaled so the next time the frame's contents need to be7441// used, the CPU needs to wait on the work to be completed.7442frames[frame].fence_signaled = true;74437444if (frame_can_present) {7445if (separate_present_queue) {7446// Issue the presentation separately if the presentation queue is different from the main queue.7447driver->command_queue_execute_and_present(present_queue, frames[frame].semaphore, {}, {}, {}, frames[frame].swap_chains_to_present);7448}74497450frames[frame].swap_chains_to_present.clear();7451}7452}74537454void RenderingDevice::_stall_for_frame(uint32_t p_frame) {7455thread_local PackedByteArray packed_byte_array;74567457if (frames[p_frame].fence_signaled) {7458GodotProfileZoneGroupedFirst(_profile_zone, "driver->fence_wait");7459driver->fence_wait(frames[p_frame].fence);7460frames[p_frame].fence_signaled = false;74617462// Flush any pending requests for asynchronous buffer downloads.7463if (!frames[p_frame].download_buffer_get_data_requests.is_empty()) {7464GodotProfileZoneGrouped(_profile_zone, "flush asynchronous buffer downloads");7465for (uint32_t i = 0; i < frames[p_frame].download_buffer_get_data_requests.size(); i++) {7466const BufferGetDataRequest &request = frames[p_frame].download_buffer_get_data_requests[i];7467packed_byte_array.resize(request.size);74687469uint32_t array_offset = 0;7470for (uint32_t j = 0; j < request.frame_local_count; j++) {7471uint32_t local_index = request.frame_local_index + j;7472const RDD::BufferCopyRegion ®ion = frames[p_frame].download_buffer_copy_regions[local_index];7473uint8_t *buffer_data = driver->buffer_map(frames[p_frame].download_buffer_staging_buffers[local_index]);7474memcpy(&packed_byte_array.write[array_offset], &buffer_data[region.dst_offset], region.size);7475driver->buffer_unmap(frames[p_frame].download_buffer_staging_buffers[local_index]);7476array_offset += region.size;7477}74787479request.callback.call(packed_byte_array);7480}74817482frames[p_frame].download_buffer_staging_buffers.clear();7483frames[p_frame].download_buffer_copy_regions.clear();7484frames[p_frame].download_buffer_get_data_requests.clear();7485}74867487// Flush any pending requests for asynchronous texture downloads.7488if (!frames[p_frame].download_texture_get_data_requests.is_empty()) {7489GodotProfileZoneGrouped(_profile_zone, "flush asynchronous texture downloads");7490for (uint32_t i = 0; i < frames[p_frame].download_texture_get_data_requests.size(); i++) {7491const TextureGetDataRequest &request = frames[p_frame].download_texture_get_data_requests[i];7492uint32_t texture_size = get_image_format_required_size(request.format, request.width, request.height, request.depth, request.mipmaps);7493packed_byte_array.resize(texture_size);74947495// Find the block size of the texture's format.7496uint32_t block_w = 0;7497uint32_t block_h = 0;7498get_compressed_image_format_block_dimensions(request.format, block_w, block_h);74997500uint32_t block_size = get_compressed_image_format_block_byte_size(request.format);7501uint32_t pixel_size = get_image_format_pixel_size(request.format);7502uint32_t region_size = texture_download_region_size_px;75037504for (uint32_t j = 0; j < request.frame_local_count; j++) {7505uint32_t local_index = request.frame_local_index + j;7506const RDD::BufferTextureCopyRegion ®ion = frames[p_frame].download_buffer_texture_copy_regions[local_index];7507uint32_t w = STEPIFY(request.width >> region.texture_subresource.mipmap, block_w);7508uint32_t h = STEPIFY(request.height >> region.texture_subresource.mipmap, block_h);7509uint32_t region_w = MIN(region_size, w - region.texture_offset.x);7510uint32_t region_h = MIN(region_size, h - region.texture_offset.y);75117512uint8_t *buffer_data = driver->buffer_map(frames[p_frame].download_texture_staging_buffers[local_index]);7513const uint8_t *read_ptr = buffer_data + region.buffer_offset;7514uint8_t *write_ptr = packed_byte_array.ptrw() + frames[p_frame].download_texture_mipmap_offsets[local_index];7515uint32_t unit_size = pixel_size;7516if (block_w != 1 || block_h != 1) {7517unit_size = block_size;7518}75197520write_ptr += ((region.texture_offset.y / block_h) * (w / block_w) + (region.texture_offset.x / block_w)) * unit_size;7521for (uint32_t y = region_h / block_h; y > 0; y--) {7522memcpy(write_ptr, read_ptr, (region_w / block_w) * unit_size);7523write_ptr += (w / block_w) * unit_size;7524read_ptr += region.row_pitch;7525}75267527driver->buffer_unmap(frames[p_frame].download_texture_staging_buffers[local_index]);7528}75297530request.callback.call(packed_byte_array);7531}75327533GodotProfileZoneGrouped(_profile_zone, "clear buffers");7534frames[p_frame].download_texture_staging_buffers.clear();7535frames[p_frame].download_buffer_texture_copy_regions.clear();7536frames[p_frame].download_texture_mipmap_offsets.clear();7537frames[p_frame].download_texture_get_data_requests.clear();7538}7539}7540}75417542void RenderingDevice::_stall_for_previous_frames() {7543for (uint32_t i = 0; i < frames.size(); i++) {7544_stall_for_frame(i);7545}7546}75477548void RenderingDevice::_flush_and_stall_for_all_frames(bool p_begin_frame) {7549_stall_for_previous_frames();7550_end_frame();7551_execute_frame(false);75527553if (p_begin_frame) {7554_begin_frame();7555} else {7556_stall_for_frame(frame);7557}7558}75597560Error RenderingDevice::initialize(RenderingContextDriver *p_context, DisplayServer::WindowID p_main_window) {7561ERR_RENDER_THREAD_GUARD_V(ERR_UNAVAILABLE);75627563Error err;7564RenderingContextDriver::SurfaceID main_surface = 0;7565is_main_instance = (singleton == this) && (p_main_window != DisplayServer::INVALID_WINDOW_ID);7566if (p_main_window != DisplayServer::INVALID_WINDOW_ID) {7567// Retrieve the surface from the main window if it was specified.7568main_surface = p_context->surface_get_from_window(p_main_window);7569ERR_FAIL_COND_V(main_surface == 0, FAILED);7570}75717572context = p_context;7573driver = context->driver_create();75747575print_verbose("Devices:");7576int32_t device_index = Engine::get_singleton()->get_gpu_index();7577const uint32_t device_count = context->device_get_count();7578const bool detect_device = (device_index < 0) || (device_index >= int32_t(device_count));7579uint32_t device_type_score = 0;7580for (uint32_t i = 0; i < device_count; i++) {7581RenderingContextDriver::Device device_option = context->device_get(i);7582String name = device_option.name;7583String vendor = _get_device_vendor_name(device_option);7584String type = _get_device_type_name(device_option);7585bool present_supported = main_surface != 0 ? context->device_supports_present(i, main_surface) : false;7586print_verbose(" #" + itos(i) + ": " + vendor + " " + name + " - " + (present_supported ? "Supported" : "Unsupported") + ", " + type);7587if (detect_device && (present_supported || main_surface == 0)) {7588// If a window was specified, present must be supported by the device to be available as an option.7589// Assign a score for each type of device and prefer the device with the higher score.7590uint32_t option_score = _get_device_type_score(device_option);7591if (option_score > device_type_score) {7592device_index = i;7593device_type_score = option_score;7594}7595}7596}75977598ERR_FAIL_COND_V_MSG((device_index < 0) || (device_index >= int32_t(device_count)), ERR_CANT_CREATE, "None of the devices supports both graphics and present queues.");75997600uint32_t frame_count = 1;7601if (main_surface != 0) {7602frame_count = MAX(2U, uint32_t(GLOBAL_GET("rendering/rendering_device/vsync/frame_queue_size")));7603}76047605frame = 0;7606max_timestamp_query_elements = GLOBAL_GET("debug/settings/profiler/max_timestamp_query_elements");76077608device = context->device_get(device_index);7609err = driver->initialize(device_index, frame_count);7610ERR_FAIL_COND_V_MSG(err != OK, FAILED, "Failed to initialize driver for device.");76117612if (is_main_instance) {7613// Only the singleton instance with a display should print this information.7614String rendering_method;7615if (OS::get_singleton()->get_current_rendering_method() == "mobile") {7616rendering_method = "Forward Mobile";7617} else {7618rendering_method = "Forward+";7619}76207621// Output our device version.7622Engine::get_singleton()->print_header(vformat("%s %s - %s - Using Device #%d: %s - %s", get_device_api_name(), get_device_api_version(), rendering_method, device_index, _get_device_vendor_name(device), device.name));7623}76247625// Pick the main queue family. It is worth noting we explicitly do not request the transfer bit, as apparently the specification defines7626// that the existence of either the graphics or compute bit implies that the queue can also do transfer operations, but it is optional7627// to indicate whether it supports them or not with the dedicated transfer bit if either is set.7628BitField<RDD::CommandQueueFamilyBits> main_queue_bits = {};7629main_queue_bits.set_flag(RDD::COMMAND_QUEUE_FAMILY_GRAPHICS_BIT);7630main_queue_bits.set_flag(RDD::COMMAND_QUEUE_FAMILY_COMPUTE_BIT);76317632#if !FORCE_SEPARATE_PRESENT_QUEUE7633// Needing to use a separate queue for presentation is an edge case that remains to be seen what hardware triggers it at all.7634main_queue_family = driver->command_queue_family_get(main_queue_bits, main_surface);7635if (!main_queue_family && (main_surface != 0))7636#endif7637{7638// If it was not possible to find a main queue that supports the surface, we attempt to get two different queues instead.7639main_queue_family = driver->command_queue_family_get(main_queue_bits);7640present_queue_family = driver->command_queue_family_get(BitField<RDD::CommandQueueFamilyBits>(), main_surface);7641ERR_FAIL_COND_V(!present_queue_family, FAILED);7642}76437644ERR_FAIL_COND_V(!main_queue_family, FAILED);76457646// Create the main queue.7647main_queue = driver->command_queue_create(main_queue_family, true);7648ERR_FAIL_COND_V(!main_queue, FAILED);76497650transfer_queue_family = driver->command_queue_family_get(RDD::COMMAND_QUEUE_FAMILY_TRANSFER_BIT);7651if (!transfer_queue_family) {7652// Use main queue family if transfer queue family is not supported.7653transfer_queue_family = main_queue_family;7654}76557656// Create the transfer queue.7657transfer_queue = driver->command_queue_create(transfer_queue_family);7658ERR_FAIL_COND_V(!transfer_queue, FAILED);76597660if (present_queue_family) {7661// Create the present queue.7662present_queue = driver->command_queue_create(present_queue_family);7663ERR_FAIL_COND_V(!present_queue, FAILED);7664} else {7665// Use main queue as the present queue.7666present_queue = main_queue;7667present_queue_family = main_queue_family;7668}76697670// Use the processor count as the max amount of transfer workers that can be created.7671transfer_worker_pool_max_size = OS::get_singleton()->get_processor_count();76727673// Pre-allocate to avoid locking a mutex when indexing into them.7674transfer_worker_pool.resize(transfer_worker_pool_max_size);7675transfer_worker_operation_used_by_draw.resize(transfer_worker_pool_max_size);76767677frames.resize(frame_count);76787679// Create data for all the frames.7680bool frame_failed = false;7681for (uint32_t i = 0; i < frames.size(); i++) {7682frames[i].index = 0;76837684// Create command pool, command buffers, semaphores and fences.7685frames[i].command_pool = driver->command_pool_create(main_queue_family, RDD::COMMAND_BUFFER_TYPE_PRIMARY);7686if (!frames[i].command_pool) {7687frame_failed = true;7688break;7689}7690frames[i].command_buffer = driver->command_buffer_create(frames[i].command_pool);7691if (!frames[i].command_buffer) {7692frame_failed = true;7693break;7694}7695frames[i].semaphore = driver->semaphore_create();7696if (!frames[i].semaphore) {7697frame_failed = true;7698break;7699}7700frames[i].fence = driver->fence_create();7701if (!frames[i].fence) {7702frame_failed = true;7703break;7704}7705frames[i].fence_signaled = false;77067707// Create query pool.7708frames[i].timestamp_pool = driver->timestamp_query_pool_create(max_timestamp_query_elements);7709frames[i].timestamp_names.resize(max_timestamp_query_elements);7710frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements);7711frames[i].timestamp_count = 0;7712frames[i].timestamp_result_names.resize(max_timestamp_query_elements);7713frames[i].timestamp_cpu_result_values.resize(max_timestamp_query_elements);7714frames[i].timestamp_result_values.resize(max_timestamp_query_elements);7715frames[i].timestamp_result_count = 0;77167717// Assign the main queue family and command pool to the command buffer pool.7718frames[i].command_buffer_pool.pool = frames[i].command_pool;77197720// Create the semaphores for the transfer workers.7721frames[i].transfer_worker_semaphores.resize(transfer_worker_pool_max_size);7722for (uint32_t j = 0; j < transfer_worker_pool_max_size; j++) {7723frames[i].transfer_worker_semaphores[j] = driver->semaphore_create();7724if (!frames[i].transfer_worker_semaphores[j]) {7725frame_failed = true;7726break;7727}7728}7729}7730if (frame_failed) {7731// Clean up created data.7732for (uint32_t i = 0; i < frames.size(); i++) {7733if (frames[i].command_pool) {7734driver->command_pool_free(frames[i].command_pool);7735}7736if (frames[i].semaphore) {7737driver->semaphore_free(frames[i].semaphore);7738}7739if (frames[i].fence) {7740driver->fence_free(frames[i].fence);7741}7742if (frames[i].timestamp_pool) {7743driver->timestamp_query_pool_free(frames[i].timestamp_pool);7744}7745for (uint32_t j = 0; j < frames[i].transfer_worker_semaphores.size(); j++) {7746if (frames[i].transfer_worker_semaphores[j]) {7747driver->semaphore_free(frames[i].transfer_worker_semaphores[j]);7748}7749}7750}7751frames.clear();7752ERR_FAIL_V_MSG(FAILED, "Failed to create frame data.");7753}77547755// Start from frame count, so everything else is immediately old.7756frames_drawn = frames.size();77577758// Initialize recording on the first frame.7759driver->begin_segment(frame, frames_drawn++);7760driver->command_buffer_begin(frames[0].command_buffer);77617762// Create draw graph and start it initialized as well.7763draw_graph.initialize(driver, device, &_render_pass_create_from_graph, frames.size(), main_queue_family, SECONDARY_COMMAND_BUFFERS_PER_FRAME);7764draw_graph.begin();77657766for (uint32_t i = 0; i < frames.size(); i++) {7767// Reset all queries in a query pool before doing any operations with them..7768driver->command_timestamp_query_pool_reset(frames[0].command_buffer, frames[i].timestamp_pool, max_timestamp_query_elements);7769}77707771// Convert block size from KB.7772upload_staging_buffers.block_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/block_size_kb");7773upload_staging_buffers.block_size = MAX(4u, upload_staging_buffers.block_size);7774upload_staging_buffers.block_size *= 1024;77757776// Convert staging buffer size from MB.7777upload_staging_buffers.max_size = GLOBAL_GET("rendering/rendering_device/staging_buffer/max_size_mb");7778upload_staging_buffers.max_size = MAX(1u, upload_staging_buffers.max_size);7779upload_staging_buffers.max_size *= 1024 * 1024;7780upload_staging_buffers.max_size = MAX(upload_staging_buffers.max_size, upload_staging_buffers.block_size * 4);77817782// Copy the sizes to the download staging buffers.7783download_staging_buffers.block_size = upload_staging_buffers.block_size;7784download_staging_buffers.max_size = upload_staging_buffers.max_size;77857786texture_upload_region_size_px = GLOBAL_GET("rendering/rendering_device/staging_buffer/texture_upload_region_size_px");7787texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);77887789texture_download_region_size_px = GLOBAL_GET("rendering/rendering_device/staging_buffer/texture_download_region_size_px");7790texture_download_region_size_px = nearest_power_of_2_templated(texture_download_region_size_px);77917792// Ensure current staging block is valid and at least one per frame exists.7793upload_staging_buffers.current = 0;7794upload_staging_buffers.used = false;7795upload_staging_buffers.usage_bits = RDD::BUFFER_USAGE_TRANSFER_FROM_BIT;77967797download_staging_buffers.current = 0;7798download_staging_buffers.used = false;7799download_staging_buffers.usage_bits = RDD::BUFFER_USAGE_TRANSFER_TO_BIT;78007801for (uint32_t i = 0; i < frames.size(); i++) {7802// Staging was never used, create the blocks.7803err = _insert_staging_block(upload_staging_buffers);7804ERR_FAIL_COND_V(err, FAILED);78057806err = _insert_staging_block(download_staging_buffers);7807ERR_FAIL_COND_V(err, FAILED);7808}78097810draw_list = DrawList();7811compute_list = ComputeList();7812raytracing_list = RaytracingList();78137814bool project_pipeline_cache_enable = GLOBAL_GET("rendering/rendering_device/pipeline_cache/enable");7815if (is_main_instance && project_pipeline_cache_enable) {7816// Only the instance that is not a local device and is also the singleton is allowed to manage a pipeline cache.7817pipeline_cache_file_path = vformat("user://vulkan/pipelines.%s.%s",7818OS::get_singleton()->get_current_rendering_method(),7819device.name.validate_filename().replace_char(' ', '_').to_lower());7820if (Engine::get_singleton()->is_editor_hint()) {7821pipeline_cache_file_path += ".editor";7822}7823pipeline_cache_file_path += ".cache";78247825Vector<uint8_t> cache_data = _load_pipeline_cache();7826pipeline_cache_enabled = driver->pipeline_cache_create(cache_data);7827if (pipeline_cache_enabled) {7828pipeline_cache_size = driver->pipeline_cache_query_size();7829print_verbose(vformat("Startup PSO cache (%.1f MiB)", pipeline_cache_size / (1024.0f * 1024.0f)));7830}7831}78327833// Find the best method available for VRS on the current hardware.7834_vrs_detect_method();78357836return OK;7837}78387839Vector<uint8_t> RenderingDevice::_load_pipeline_cache() {7840DirAccess::make_dir_recursive_absolute(pipeline_cache_file_path.get_base_dir());78417842if (FileAccess::exists(pipeline_cache_file_path)) {7843Error file_error;7844Vector<uint8_t> file_data = FileAccess::get_file_as_bytes(pipeline_cache_file_path, &file_error);7845return file_data;7846} else {7847return Vector<uint8_t>();7848}7849}78507851void RenderingDevice::update_pipeline_cache(bool p_closing) {7852_THREAD_SAFE_METHOD_78537854{7855bool still_saving = pipeline_cache_save_task != WorkerThreadPool::INVALID_TASK_ID && !WorkerThreadPool::get_singleton()->is_task_completed(pipeline_cache_save_task);7856if (still_saving) {7857if (p_closing) {7858WorkerThreadPool::get_singleton()->wait_for_task_completion(pipeline_cache_save_task);7859pipeline_cache_save_task = WorkerThreadPool::INVALID_TASK_ID;7860} else {7861// We can't save until the currently running save is done. We'll retry next time; worst case, we'll save when exiting.7862return;7863}7864}7865}78667867{7868size_t new_pipelines_cache_size = driver->pipeline_cache_query_size();7869ERR_FAIL_COND(!new_pipelines_cache_size);7870size_t difference = new_pipelines_cache_size - pipeline_cache_size;78717872bool must_save = false;78737874if (p_closing) {7875must_save = difference > 0;7876} else {7877float save_interval = GLOBAL_GET("rendering/rendering_device/pipeline_cache/save_chunk_size_mb");7878must_save = difference > 0 && difference / (1024.0f * 1024.0f) >= save_interval;7879}78807881if (must_save) {7882pipeline_cache_size = new_pipelines_cache_size;7883} else {7884return;7885}7886}78877888if (p_closing) {7889_save_pipeline_cache(this);7890} else {7891pipeline_cache_save_task = WorkerThreadPool::get_singleton()->add_native_task(&_save_pipeline_cache, this, false, "PipelineCacheSave");7892}7893}78947895void RenderingDevice::_save_pipeline_cache(void *p_data) {7896RenderingDevice *self = static_cast<RenderingDevice *>(p_data);78977898self->_thread_safe_.lock();7899Vector<uint8_t> cache_blob = self->driver->pipeline_cache_serialize();7900self->_thread_safe_.unlock();79017902if (cache_blob.is_empty()) {7903return;7904}7905print_verbose(vformat("Updated PSO cache (%.1f MiB)", cache_blob.size() / (1024.0f * 1024.0f)));79067907Ref<FileAccess> f = FileAccess::open(self->pipeline_cache_file_path, FileAccess::WRITE, nullptr);7908if (f.is_valid()) {7909f->store_buffer(cache_blob);7910}7911}79127913template <typename T>7914void RenderingDevice::_free_rids(T &p_owner, const char *p_type) {7915LocalVector<RID> owned = p_owner.get_owned_list();7916if (owned.size()) {7917if (owned.size() == 1) {7918WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));7919} else {7920WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));7921}7922for (const RID &rid : owned) {7923#ifdef DEV_ENABLED7924if (resource_names.has(rid)) {7925print_line(String(" - ") + resource_names[rid]);7926}7927#endif7928free_rid(rid);7929}7930}7931}79327933void RenderingDevice::capture_timestamp(const String &p_name) {7934ERR_RENDER_THREAD_GUARD();79357936ERR_FAIL_COND_MSG(draw_list.active && draw_list.state.draw_count > 0, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);7937ERR_FAIL_COND_MSG(compute_list.active && compute_list.state.dispatch_count > 0, "Capturing timestamps during compute list creation is not allowed. Offending timestamp was: " + p_name);7938ERR_FAIL_COND_MSG(raytracing_list.active && raytracing_list.state.trace_count > 0, "Capturing timestamps during raytracing list creation is not allowed. Offending timestamp was: " + p_name);7939ERR_FAIL_COND_MSG(frames[frame].timestamp_count >= max_timestamp_query_elements, vformat("Tried capturing more timestamps than the configured maximum (%d). You can increase this limit in the project settings under 'Debug/Settings' called 'Max Timestamp Query Elements'.", max_timestamp_query_elements));79407941draw_graph.add_capture_timestamp(frames[frame].timestamp_pool, frames[frame].timestamp_count);79427943frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;7944frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();7945frames[frame].timestamp_count++;7946}79477948uint64_t RenderingDevice::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {7949ERR_RENDER_THREAD_GUARD_V(0);79507951uint64_t driver_id = 0;7952switch (p_resource) {7953case DRIVER_RESOURCE_LOGICAL_DEVICE:7954case DRIVER_RESOURCE_PHYSICAL_DEVICE:7955case DRIVER_RESOURCE_TOPMOST_OBJECT:7956break;7957case DRIVER_RESOURCE_COMMAND_QUEUE:7958driver_id = main_queue.id;7959break;7960case DRIVER_RESOURCE_QUEUE_FAMILY:7961driver_id = main_queue_family.id;7962break;7963case DRIVER_RESOURCE_TEXTURE:7964case DRIVER_RESOURCE_TEXTURE_VIEW:7965case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {7966Texture *tex = texture_owner.get_or_null(p_rid);7967ERR_FAIL_NULL_V(tex, 0);79687969driver_id = tex->driver_id.id;7970} break;7971case DRIVER_RESOURCE_SAMPLER: {7972RDD::SamplerID *sampler_driver_id = sampler_owner.get_or_null(p_rid);7973ERR_FAIL_NULL_V(sampler_driver_id, 0);79747975driver_id = (*sampler_driver_id).id;7976} break;7977case DRIVER_RESOURCE_UNIFORM_SET: {7978UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);7979ERR_FAIL_NULL_V(uniform_set, 0);79807981driver_id = uniform_set->driver_id.id;7982} break;7983case DRIVER_RESOURCE_BUFFER: {7984Buffer *buffer = nullptr;7985if (vertex_buffer_owner.owns(p_rid)) {7986buffer = vertex_buffer_owner.get_or_null(p_rid);7987} else if (index_buffer_owner.owns(p_rid)) {7988buffer = index_buffer_owner.get_or_null(p_rid);7989} else if (uniform_buffer_owner.owns(p_rid)) {7990buffer = uniform_buffer_owner.get_or_null(p_rid);7991} else if (texture_buffer_owner.owns(p_rid)) {7992buffer = texture_buffer_owner.get_or_null(p_rid);7993} else if (storage_buffer_owner.owns(p_rid)) {7994buffer = storage_buffer_owner.get_or_null(p_rid);7995} else if (instances_buffer_owner.owns(p_rid)) {7996buffer = &instances_buffer_owner.get_or_null(p_rid)->buffer;7997}7998ERR_FAIL_NULL_V(buffer, 0);79998000driver_id = buffer->driver_id.id;8001} break;8002case DRIVER_RESOURCE_COMPUTE_PIPELINE: {8003ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);8004ERR_FAIL_NULL_V(compute_pipeline, 0);80058006driver_id = compute_pipeline->driver_id.id;8007} break;8008case DRIVER_RESOURCE_RENDER_PIPELINE: {8009RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);8010ERR_FAIL_NULL_V(render_pipeline, 0);80118012driver_id = render_pipeline->driver_id.id;8013} break;8014default: {8015ERR_FAIL_V(0);8016} break;8017}80188019return driver->get_resource_native_handle(p_resource, driver_id);8020}80218022String RenderingDevice::get_driver_and_device_memory_report() const {8023return context->get_driver_and_device_memory_report();8024}80258026String RenderingDevice::get_tracked_object_name(uint32_t p_type_index) const {8027return context->get_tracked_object_name(p_type_index);8028}80298030uint64_t RenderingDevice::get_tracked_object_type_count() const {8031return context->get_tracked_object_type_count();8032}80338034uint64_t RenderingDevice::get_driver_total_memory() const {8035return context->get_driver_total_memory();8036}80378038uint64_t RenderingDevice::get_driver_allocation_count() const {8039return context->get_driver_allocation_count();8040}80418042uint64_t RenderingDevice::get_driver_memory_by_object_type(uint32_t p_type) const {8043return context->get_driver_memory_by_object_type(p_type);8044}80458046uint64_t RenderingDevice::get_driver_allocs_by_object_type(uint32_t p_type) const {8047return context->get_driver_allocs_by_object_type(p_type);8048}80498050uint64_t RenderingDevice::get_device_total_memory() const {8051return context->get_device_total_memory();8052}80538054uint64_t RenderingDevice::get_device_allocation_count() const {8055return context->get_device_allocation_count();8056}80578058uint64_t RenderingDevice::get_device_memory_by_object_type(uint32_t type) const {8059return context->get_device_memory_by_object_type(type);8060}80618062uint64_t RenderingDevice::get_device_allocs_by_object_type(uint32_t type) const {8063return context->get_device_allocs_by_object_type(type);8064}80658066uint32_t RenderingDevice::get_captured_timestamps_count() const {8067ERR_RENDER_THREAD_GUARD_V(0);8068return frames[frame].timestamp_result_count;8069}80708071uint64_t RenderingDevice::get_captured_timestamps_frame() const {8072ERR_RENDER_THREAD_GUARD_V(0);8073return frames[frame].index;8074}80758076uint64_t RenderingDevice::get_captured_timestamp_gpu_time(uint32_t p_index) const {8077ERR_RENDER_THREAD_GUARD_V(0);8078ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);8079return driver->timestamp_query_result_to_time(frames[frame].timestamp_result_values[p_index]);8080}80818082uint64_t RenderingDevice::get_captured_timestamp_cpu_time(uint32_t p_index) const {8083ERR_RENDER_THREAD_GUARD_V(0);8084ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);8085return frames[frame].timestamp_cpu_result_values[p_index];8086}80878088String RenderingDevice::get_captured_timestamp_name(uint32_t p_index) const {8089ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());8090return frames[frame].timestamp_result_names[p_index];8091}80928093uint64_t RenderingDevice::limit_get(Limit p_limit) const {8094return driver->limit_get(p_limit);8095}80968097void RenderingDevice::finalize() {8098ERR_RENDER_THREAD_GUARD();80998100if (!frames.is_empty()) {8101// Wait for all frames to have finished rendering.8102_flush_and_stall_for_all_frames(false);8103}81048105// Wait for transfer workers to finish.8106_submit_transfer_workers();8107_wait_for_transfer_workers();81088109// Delete everything the graph has created.8110draw_graph.finalize();81118112// Free all resources.8113_free_rids(render_pipeline_owner, "Pipeline");8114_free_rids(compute_pipeline_owner, "Compute");8115_free_rids(uniform_set_owner, "UniformSet");8116_free_rids(texture_buffer_owner, "TextureBuffer");8117_free_rids(storage_buffer_owner, "StorageBuffer");8118_free_rids(instances_buffer_owner, "InstancesBuffer");8119_free_rids(uniform_buffer_owner, "UniformBuffer");8120_free_rids(shader_owner, "Shader");8121_free_rids(index_array_owner, "IndexArray");8122_free_rids(index_buffer_owner, "IndexBuffer");8123_free_rids(vertex_array_owner, "VertexArray");8124_free_rids(vertex_buffer_owner, "VertexBuffer");8125_free_rids(framebuffer_owner, "Framebuffer");8126_free_rids(sampler_owner, "Sampler");8127{8128// For textures it's a bit more difficult because they may be shared.8129LocalVector<RID> owned = texture_owner.get_owned_list();8130if (owned.size()) {8131if (owned.size() == 1) {8132WARN_PRINT("1 RID of type \"Texture\" was leaked.");8133} else {8134WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));8135}8136LocalVector<RID> owned_non_shared;8137// Free shared first.8138for (const RID &texture_rid : owned) {8139if (texture_is_shared(texture_rid)) {8140#ifdef DEV_ENABLED8141if (resource_names.has(texture_rid)) {8142print_line(String(" - ") + resource_names[texture_rid]);8143}8144#endif8145free_rid(texture_rid);8146} else {8147owned_non_shared.push_back(texture_rid);8148}8149}8150// Free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.8151for (const RID &texture_rid : owned_non_shared) {8152#ifdef DEV_ENABLED8153if (resource_names.has(texture_rid)) {8154print_line(String(" - ") + resource_names[texture_rid]);8155}8156#endif8157free_rid(texture_rid);8158}8159}8160}81618162// Erase the transfer workers after all resources have been freed.8163_free_transfer_workers();81648165// Free everything pending.8166for (uint32_t i = 0; i < frames.size(); i++) {8167int f = (frame + i) % frames.size();8168_free_pending_resources(f);8169driver->command_pool_free(frames[i].command_pool);8170driver->timestamp_query_pool_free(frames[i].timestamp_pool);8171driver->semaphore_free(frames[i].semaphore);8172driver->fence_free(frames[i].fence);81738174RDG::CommandBufferPool &buffer_pool = frames[i].command_buffer_pool;8175for (uint32_t j = 0; j < buffer_pool.buffers.size(); j++) {8176driver->semaphore_free(buffer_pool.semaphores[j]);8177}81788179for (uint32_t j = 0; j < frames[i].transfer_worker_semaphores.size(); j++) {8180driver->semaphore_free(frames[i].transfer_worker_semaphores[j]);8181}8182}81838184if (pipeline_cache_enabled) {8185update_pipeline_cache(true);8186driver->pipeline_cache_free();8187}81888189frames.clear();81908191for (int i = 0; i < upload_staging_buffers.blocks.size(); i++) {8192driver->buffer_unmap(upload_staging_buffers.blocks[i].driver_id);8193driver->buffer_free(upload_staging_buffers.blocks[i].driver_id);8194}81958196for (int i = 0; i < download_staging_buffers.blocks.size(); i++) {8197driver->buffer_unmap(download_staging_buffers.blocks[i].driver_id);8198driver->buffer_free(download_staging_buffers.blocks[i].driver_id);8199}82008201while (vertex_formats.size()) {8202HashMap<VertexFormatID, VertexDescriptionCache>::Iterator temp = vertex_formats.begin();8203driver->vertex_format_free(temp->value.driver_id);8204vertex_formats.remove(temp);8205}82068207for (KeyValue<FramebufferFormatID, FramebufferFormat> &E : framebuffer_formats) {8208driver->render_pass_free(E.value.render_pass);8209}8210framebuffer_formats.clear();82118212// Delete the swap chains created for the screens.8213for (const KeyValue<DisplayServer::WindowID, RDD::SwapChainID> &it : screen_swap_chains) {8214driver->swap_chain_free(it.value);8215}82168217screen_swap_chains.clear();82188219// Delete the command queues.8220if (present_queue) {8221if (main_queue != present_queue) {8222// Only delete the present queue if it's unique.8223driver->command_queue_free(present_queue);8224}82258226present_queue = RDD::CommandQueueID();8227}82288229if (transfer_queue) {8230if (main_queue != transfer_queue) {8231// Only delete the transfer queue if it's unique.8232driver->command_queue_free(transfer_queue);8233}82348235transfer_queue = RDD::CommandQueueID();8236}82378238if (main_queue) {8239driver->command_queue_free(main_queue);8240main_queue = RDD::CommandQueueID();8241}82428243// Delete the driver once everything else has been deleted.8244if (driver != nullptr) {8245context->driver_free(driver);8246driver = nullptr;8247}82488249// All these should be clear at this point.8250ERR_FAIL_COND(dependency_map.size());8251ERR_FAIL_COND(reverse_dependency_map.size());8252}82538254void RenderingDevice::_set_max_fps(int p_max_fps) {8255for (const KeyValue<DisplayServer::WindowID, RDD::SwapChainID> &it : screen_swap_chains) {8256driver->swap_chain_set_max_fps(it.value, p_max_fps);8257}8258}82598260RenderingDevice *RenderingDevice::create_local_device() {8261RenderingDevice *rd = memnew(RenderingDevice);8262if (rd->initialize(context) != OK) {8263memdelete(rd);8264return nullptr;8265}8266return rd;8267}82688269bool RenderingDevice::has_feature(const Features p_feature) const {8270// Some features can be deduced from the capabilities without querying the driver and looking at the capabilities.8271switch (p_feature) {8272case SUPPORTS_MULTIVIEW: {8273const RDD::MultiviewCapabilities &multiview_capabilities = driver->get_multiview_capabilities();8274return multiview_capabilities.is_supported && multiview_capabilities.max_view_count > 1;8275}8276case SUPPORTS_ATTACHMENT_VRS: {8277const RDD::FragmentShadingRateCapabilities &fsr_capabilities = driver->get_fragment_shading_rate_capabilities();8278const RDD::FragmentDensityMapCapabilities &fdm_capabilities = driver->get_fragment_density_map_capabilities();8279return fsr_capabilities.attachment_supported || fdm_capabilities.attachment_supported;8280}8281default:8282return driver->has_feature(p_feature);8283}8284}82858286void RenderingDevice::_bind_methods() {8287ClassDB::bind_method(D_METHOD("texture_create", "format", "view", "data"), &RenderingDevice::_texture_create, DEFVAL(Array()));8288ClassDB::bind_method(D_METHOD("texture_create_shared", "view", "with_texture"), &RenderingDevice::_texture_create_shared);8289ClassDB::bind_method(D_METHOD("texture_create_shared_from_slice", "view", "with_texture", "layer", "mipmap", "mipmaps", "slice_type"), &RenderingDevice::_texture_create_shared_from_slice, DEFVAL(1), DEFVAL(TEXTURE_SLICE_2D));8290ClassDB::bind_method(D_METHOD("texture_create_from_extension", "type", "format", "samples", "usage_flags", "image", "width", "height", "depth", "layers", "mipmaps"), &RenderingDevice::texture_create_from_extension, DEFVAL(1));82918292ClassDB::bind_method(D_METHOD("texture_update", "texture", "layer", "data"), &RenderingDevice::texture_update);8293ClassDB::bind_method(D_METHOD("texture_get_data", "texture", "layer"), &RenderingDevice::texture_get_data);8294ClassDB::bind_method(D_METHOD("texture_get_data_async", "texture", "layer", "callback"), &RenderingDevice::texture_get_data_async);82958296ClassDB::bind_method(D_METHOD("texture_is_format_supported_for_usage", "format", "usage_flags"), &RenderingDevice::texture_is_format_supported_for_usage);82978298ClassDB::bind_method(D_METHOD("texture_is_shared", "texture"), &RenderingDevice::texture_is_shared);8299ClassDB::bind_method(D_METHOD("texture_is_valid", "texture"), &RenderingDevice::texture_is_valid);83008301ClassDB::bind_method(D_METHOD("texture_set_discardable", "texture", "discardable"), &RenderingDevice::texture_set_discardable);8302ClassDB::bind_method(D_METHOD("texture_is_discardable", "texture"), &RenderingDevice::texture_is_discardable);83038304ClassDB::bind_method(D_METHOD("texture_copy", "from_texture", "to_texture", "from_pos", "to_pos", "size", "src_mipmap", "dst_mipmap", "src_layer", "dst_layer"), &RenderingDevice::texture_copy);8305ClassDB::bind_method(D_METHOD("texture_clear", "texture", "color", "base_mipmap", "mipmap_count", "base_layer", "layer_count"), &RenderingDevice::texture_clear);8306ClassDB::bind_method(D_METHOD("texture_resolve_multisample", "from_texture", "to_texture"), &RenderingDevice::texture_resolve_multisample);83078308ClassDB::bind_method(D_METHOD("texture_get_format", "texture"), &RenderingDevice::_texture_get_format);8309#ifndef DISABLE_DEPRECATED8310ClassDB::bind_method(D_METHOD("texture_get_native_handle", "texture"), &RenderingDevice::texture_get_native_handle);8311#endif83128313ClassDB::bind_method(D_METHOD("framebuffer_format_create", "attachments", "view_count"), &RenderingDevice::_framebuffer_format_create, DEFVAL(1));8314ClassDB::bind_method(D_METHOD("framebuffer_format_create_multipass", "attachments", "passes", "view_count"), &RenderingDevice::_framebuffer_format_create_multipass, DEFVAL(1));8315ClassDB::bind_method(D_METHOD("framebuffer_format_create_empty", "samples"), &RenderingDevice::framebuffer_format_create_empty, DEFVAL(TEXTURE_SAMPLES_1));8316ClassDB::bind_method(D_METHOD("framebuffer_format_get_texture_samples", "format", "render_pass"), &RenderingDevice::framebuffer_format_get_texture_samples, DEFVAL(0));8317ClassDB::bind_method(D_METHOD("framebuffer_create", "textures", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1));8318ClassDB::bind_method(D_METHOD("framebuffer_create_multipass", "textures", "passes", "validate_with_format", "view_count"), &RenderingDevice::_framebuffer_create_multipass, DEFVAL(INVALID_FORMAT_ID), DEFVAL(1));8319ClassDB::bind_method(D_METHOD("framebuffer_create_empty", "size", "samples", "validate_with_format"), &RenderingDevice::framebuffer_create_empty, DEFVAL(TEXTURE_SAMPLES_1), DEFVAL(INVALID_FORMAT_ID));8320ClassDB::bind_method(D_METHOD("framebuffer_get_format", "framebuffer"), &RenderingDevice::framebuffer_get_format);8321ClassDB::bind_method(D_METHOD("framebuffer_is_valid", "framebuffer"), &RenderingDevice::framebuffer_is_valid);83228323ClassDB::bind_method(D_METHOD("sampler_create", "state"), &RenderingDevice::_sampler_create);8324ClassDB::bind_method(D_METHOD("sampler_is_format_supported_for_filter", "format", "sampler_filter"), &RenderingDevice::sampler_is_format_supported_for_filter);83258326ClassDB::bind_method(D_METHOD("vertex_buffer_create", "size_bytes", "data", "creation_bits"), &RenderingDevice::_vertex_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(0));8327ClassDB::bind_method(D_METHOD("vertex_format_create", "vertex_descriptions"), &RenderingDevice::_vertex_format_create);8328ClassDB::bind_method(D_METHOD("vertex_array_create", "vertex_count", "vertex_format", "src_buffers", "offsets"), &RenderingDevice::_vertex_array_create, DEFVAL(Vector<int64_t>()));83298330ClassDB::bind_method(D_METHOD("index_buffer_create", "size_indices", "format", "data", "use_restart_indices", "creation_bits"), &RenderingDevice::_index_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(false), DEFVAL(0));8331ClassDB::bind_method(D_METHOD("index_array_create", "index_buffer", "index_offset", "index_count"), &RenderingDevice::index_array_create);83328333ClassDB::bind_method(D_METHOD("shader_compile_spirv_from_source", "shader_source", "allow_cache"), &RenderingDevice::_shader_compile_spirv_from_source, DEFVAL(true));8334ClassDB::bind_method(D_METHOD("shader_compile_binary_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_compile_binary_from_spirv, DEFVAL(""));8335ClassDB::bind_method(D_METHOD("shader_create_from_spirv", "spirv_data", "name"), &RenderingDevice::_shader_create_from_spirv, DEFVAL(""));8336ClassDB::bind_method(D_METHOD("shader_create_from_bytecode", "binary_data", "placeholder_rid"), &RenderingDevice::shader_create_from_bytecode, DEFVAL(RID()));8337ClassDB::bind_method(D_METHOD("shader_create_placeholder"), &RenderingDevice::shader_create_placeholder);83388339ClassDB::bind_method(D_METHOD("shader_get_vertex_input_attribute_mask", "shader"), &RenderingDevice::shader_get_vertex_input_attribute_mask);83408341ClassDB::bind_method(D_METHOD("uniform_buffer_create", "size_bytes", "data", "creation_bits"), &RenderingDevice::_uniform_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(0));8342ClassDB::bind_method(D_METHOD("storage_buffer_create", "size_bytes", "data", "usage", "creation_bits"), &RenderingDevice::_storage_buffer_create, DEFVAL(Vector<uint8_t>()), DEFVAL(0), DEFVAL(0));8343ClassDB::bind_method(D_METHOD("texture_buffer_create", "size_bytes", "format", "data"), &RenderingDevice::_texture_buffer_create, DEFVAL(Vector<uint8_t>()));83448345ClassDB::bind_method(D_METHOD("uniform_set_create", "uniforms", "shader", "shader_set"), &RenderingDevice::_uniform_set_create);8346ClassDB::bind_method(D_METHOD("uniform_set_is_valid", "uniform_set"), &RenderingDevice::uniform_set_is_valid);83478348ClassDB::bind_method(D_METHOD("buffer_copy", "src_buffer", "dst_buffer", "src_offset", "dst_offset", "size"), &RenderingDevice::buffer_copy);8349ClassDB::bind_method(D_METHOD("buffer_update", "buffer", "offset", "size_bytes", "data"), &RenderingDevice::_buffer_update_bind);8350ClassDB::bind_method(D_METHOD("buffer_clear", "buffer", "offset", "size_bytes"), &RenderingDevice::buffer_clear);8351ClassDB::bind_method(D_METHOD("buffer_get_data", "buffer", "offset_bytes", "size_bytes"), &RenderingDevice::buffer_get_data, DEFVAL(0), DEFVAL(0));8352ClassDB::bind_method(D_METHOD("buffer_get_data_async", "buffer", "callback", "offset_bytes", "size_bytes"), &RenderingDevice::buffer_get_data_async, DEFVAL(0), DEFVAL(0));8353ClassDB::bind_method(D_METHOD("buffer_get_device_address", "buffer"), &RenderingDevice::buffer_get_device_address);83548355ClassDB::bind_method(D_METHOD("render_pipeline_create", "shader", "framebuffer_format", "vertex_format", "primitive", "rasterization_state", "multisample_state", "stencil_state", "color_blend_state", "dynamic_state_flags", "for_render_pass", "specialization_constants"), &RenderingDevice::_render_pipeline_create, DEFVAL(0), DEFVAL(0), DEFVAL(TypedArray<RDPipelineSpecializationConstant>()));8356ClassDB::bind_method(D_METHOD("render_pipeline_is_valid", "render_pipeline"), &RenderingDevice::render_pipeline_is_valid);83578358ClassDB::bind_method(D_METHOD("compute_pipeline_create", "shader", "specialization_constants"), &RenderingDevice::_compute_pipeline_create, DEFVAL(TypedArray<RDPipelineSpecializationConstant>()));8359ClassDB::bind_method(D_METHOD("compute_pipeline_is_valid", "compute_pipeline"), &RenderingDevice::compute_pipeline_is_valid);83608361ClassDB::bind_method(D_METHOD("raytracing_pipeline_create", "shader", "specialization_constants"), &RenderingDevice::_raytracing_pipeline_create, DEFVAL(TypedArray<RDPipelineSpecializationConstant>()));8362ClassDB::bind_method(D_METHOD("raytracing_pipeline_is_valid", "raytracing_pipeline"), &RenderingDevice::raytracing_pipeline_is_valid);83638364ClassDB::bind_method(D_METHOD("blas_create", "vertex_array", "index_array", "geometry_bits", "position_attribute_location"), &RenderingDevice::blas_create, DEFVAL(0), DEFVAL(0));8365ClassDB::bind_method(D_METHOD("tlas_instances_buffer_create", "instance_count", "creation_bits"), &RenderingDevice::tlas_instances_buffer_create, DEFVAL(0));8366ClassDB::bind_method(D_METHOD("tlas_instances_buffer_fill", "instances_buffer", "blases", "transforms"), &RenderingDevice::_tlas_instances_buffer_fill);8367ClassDB::bind_method(D_METHOD("tlas_create", "instances_buffer"), &RenderingDevice::tlas_create);8368ClassDB::bind_method(D_METHOD("acceleration_structure_build", "acceleration_structure"), &RenderingDevice::acceleration_structure_build);83698370ClassDB::bind_method(D_METHOD("screen_get_width", "screen"), &RenderingDevice::screen_get_width, DEFVAL(DisplayServer::MAIN_WINDOW_ID));8371ClassDB::bind_method(D_METHOD("screen_get_height", "screen"), &RenderingDevice::screen_get_height, DEFVAL(DisplayServer::MAIN_WINDOW_ID));8372ClassDB::bind_method(D_METHOD("screen_get_framebuffer_format", "screen"), &RenderingDevice::screen_get_framebuffer_format, DEFVAL(DisplayServer::MAIN_WINDOW_ID));83738374ClassDB::bind_method(D_METHOD("draw_list_begin_for_screen", "screen", "clear_color"), &RenderingDevice::draw_list_begin_for_screen, DEFVAL(DisplayServer::MAIN_WINDOW_ID), DEFVAL(Color()));83758376ClassDB::bind_method(D_METHOD("draw_list_begin", "framebuffer", "draw_flags", "clear_color_values", "clear_depth_value", "clear_stencil_value", "region", "breadcrumb"), &RenderingDevice::_draw_list_begin_bind, DEFVAL(DRAW_DEFAULT_ALL), DEFVAL(Vector<Color>()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(0));8377#ifndef DISABLE_DEPRECATED8378ClassDB::bind_method(D_METHOD("draw_list_begin_split", "framebuffer", "splits", "initial_color_action", "final_color_action", "initial_depth_action", "final_depth_action", "clear_color_values", "clear_depth", "clear_stencil", "region", "storage_textures"), &RenderingDevice::_draw_list_begin_split, DEFVAL(Vector<Color>()), DEFVAL(1.0), DEFVAL(0), DEFVAL(Rect2()), DEFVAL(TypedArray<RID>()));8379#endif83808381ClassDB::bind_method(D_METHOD("draw_list_set_blend_constants", "draw_list", "color"), &RenderingDevice::draw_list_set_blend_constants);8382ClassDB::bind_method(D_METHOD("draw_list_bind_render_pipeline", "draw_list", "render_pipeline"), &RenderingDevice::draw_list_bind_render_pipeline);8383ClassDB::bind_method(D_METHOD("draw_list_bind_uniform_set", "draw_list", "uniform_set", "set_index"), &RenderingDevice::draw_list_bind_uniform_set);8384ClassDB::bind_method(D_METHOD("draw_list_bind_vertex_array", "draw_list", "vertex_array"), &RenderingDevice::draw_list_bind_vertex_array);8385ClassDB::bind_method(D_METHOD("draw_list_bind_vertex_buffers_format", "draw_list", "vertex_format", "vertex_count", "vertex_buffers", "offsets"), &RenderingDevice::_draw_list_bind_vertex_buffers_format, DEFVAL(Vector<int64_t>()));8386ClassDB::bind_method(D_METHOD("draw_list_bind_index_array", "draw_list", "index_array"), &RenderingDevice::draw_list_bind_index_array);8387ClassDB::bind_method(D_METHOD("draw_list_set_push_constant", "draw_list", "buffer", "size_bytes"), &RenderingDevice::_draw_list_set_push_constant);83888389ClassDB::bind_method(D_METHOD("draw_list_draw", "draw_list", "use_indices", "instances", "procedural_vertex_count"), &RenderingDevice::draw_list_draw, DEFVAL(0));8390ClassDB::bind_method(D_METHOD("draw_list_draw_indirect", "draw_list", "use_indices", "buffer", "offset", "draw_count", "stride"), &RenderingDevice::draw_list_draw_indirect, DEFVAL(0), DEFVAL(1), DEFVAL(0));83918392ClassDB::bind_method(D_METHOD("draw_list_enable_scissor", "draw_list", "rect"), &RenderingDevice::draw_list_enable_scissor, DEFVAL(Rect2()));8393ClassDB::bind_method(D_METHOD("draw_list_disable_scissor", "draw_list"), &RenderingDevice::draw_list_disable_scissor);83948395ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass"), &RenderingDevice::draw_list_switch_to_next_pass);8396#ifndef DISABLE_DEPRECATED8397ClassDB::bind_method(D_METHOD("draw_list_switch_to_next_pass_split", "splits"), &RenderingDevice::_draw_list_switch_to_next_pass_split);8398#endif83998400ClassDB::bind_method(D_METHOD("draw_list_end"), &RenderingDevice::draw_list_end);84018402ClassDB::bind_method(D_METHOD("compute_list_begin"), &RenderingDevice::compute_list_begin);8403ClassDB::bind_method(D_METHOD("compute_list_bind_compute_pipeline", "compute_list", "compute_pipeline"), &RenderingDevice::compute_list_bind_compute_pipeline);8404ClassDB::bind_method(D_METHOD("compute_list_set_push_constant", "compute_list", "buffer", "size_bytes"), &RenderingDevice::_compute_list_set_push_constant);8405ClassDB::bind_method(D_METHOD("compute_list_bind_uniform_set", "compute_list", "uniform_set", "set_index"), &RenderingDevice::compute_list_bind_uniform_set);8406ClassDB::bind_method(D_METHOD("compute_list_dispatch", "compute_list", "x_groups", "y_groups", "z_groups"), &RenderingDevice::compute_list_dispatch);8407ClassDB::bind_method(D_METHOD("compute_list_dispatch_indirect", "compute_list", "buffer", "offset"), &RenderingDevice::compute_list_dispatch_indirect);8408ClassDB::bind_method(D_METHOD("compute_list_add_barrier", "compute_list"), &RenderingDevice::compute_list_add_barrier);8409ClassDB::bind_method(D_METHOD("compute_list_end"), &RenderingDevice::compute_list_end);84108411ClassDB::bind_method(D_METHOD("raytracing_list_begin"), &RenderingDevice::raytracing_list_begin);8412ClassDB::bind_method(D_METHOD("raytracing_list_bind_raytracing_pipeline", "raytracing_list", "raytracing_pipeline"), &RenderingDevice::raytracing_list_bind_raytracing_pipeline);8413ClassDB::bind_method(D_METHOD("raytracing_list_set_push_constant", "raytracing_list", "buffer", "size_bytes"), &RenderingDevice::_raytracing_list_set_push_constant);8414ClassDB::bind_method(D_METHOD("raytracing_list_bind_uniform_set", "raytracing_list", "uniform_set", "set_index"), &RenderingDevice::raytracing_list_bind_uniform_set);8415ClassDB::bind_method(D_METHOD("raytracing_list_trace_rays", "raytracing_list", "width", "height"), &RenderingDevice::raytracing_list_trace_rays);8416ClassDB::bind_method(D_METHOD("raytracing_list_end"), &RenderingDevice::raytracing_list_end);84178418ClassDB::bind_method(D_METHOD("free_rid", "rid"), &RenderingDevice::free_rid);84198420ClassDB::bind_method(D_METHOD("capture_timestamp", "name"), &RenderingDevice::capture_timestamp);8421ClassDB::bind_method(D_METHOD("get_captured_timestamps_count"), &RenderingDevice::get_captured_timestamps_count);8422ClassDB::bind_method(D_METHOD("get_captured_timestamps_frame"), &RenderingDevice::get_captured_timestamps_frame);8423ClassDB::bind_method(D_METHOD("get_captured_timestamp_gpu_time", "index"), &RenderingDevice::get_captured_timestamp_gpu_time);8424ClassDB::bind_method(D_METHOD("get_captured_timestamp_cpu_time", "index"), &RenderingDevice::get_captured_timestamp_cpu_time);8425ClassDB::bind_method(D_METHOD("get_captured_timestamp_name", "index"), &RenderingDevice::get_captured_timestamp_name);84268427ClassDB::bind_method(D_METHOD("has_feature", "feature"), &RenderingDevice::has_feature);8428ClassDB::bind_method(D_METHOD("limit_get", "limit"), &RenderingDevice::limit_get);8429ClassDB::bind_method(D_METHOD("get_frame_delay"), &RenderingDevice::get_frame_delay);8430ClassDB::bind_method(D_METHOD("submit"), &RenderingDevice::submit);8431ClassDB::bind_method(D_METHOD("sync"), &RenderingDevice::sync);84328433#ifndef DISABLE_DEPRECATED8434ClassDB::bind_method(D_METHOD("barrier", "from", "to"), &RenderingDevice::barrier, DEFVAL(BARRIER_MASK_ALL_BARRIERS), DEFVAL(BARRIER_MASK_ALL_BARRIERS));8435ClassDB::bind_method(D_METHOD("full_barrier"), &RenderingDevice::full_barrier);8436#endif84378438ClassDB::bind_method(D_METHOD("create_local_device"), &RenderingDevice::create_local_device);84398440ClassDB::bind_method(D_METHOD("set_resource_name", "id", "name"), &RenderingDevice::set_resource_name);84418442ClassDB::bind_method(D_METHOD("draw_command_begin_label", "name", "color"), &RenderingDevice::_draw_command_begin_label);8443#ifndef DISABLE_DEPRECATED8444ClassDB::bind_method(D_METHOD("draw_command_insert_label", "name", "color"), &RenderingDevice::draw_command_insert_label);8445#endif8446ClassDB::bind_method(D_METHOD("draw_command_end_label"), &RenderingDevice::draw_command_end_label);84478448ClassDB::bind_method(D_METHOD("get_device_vendor_name"), &RenderingDevice::get_device_vendor_name);8449ClassDB::bind_method(D_METHOD("get_device_name"), &RenderingDevice::get_device_name);8450ClassDB::bind_method(D_METHOD("get_device_pipeline_cache_uuid"), &RenderingDevice::get_device_pipeline_cache_uuid);84518452ClassDB::bind_method(D_METHOD("get_memory_usage", "type"), &RenderingDevice::get_memory_usage);84538454ClassDB::bind_method(D_METHOD("get_driver_resource", "resource", "rid", "index"), &RenderingDevice::get_driver_resource);84558456ClassDB::bind_method(D_METHOD("get_perf_report"), &RenderingDevice::get_perf_report);84578458ClassDB::bind_method(D_METHOD("get_driver_and_device_memory_report"), &RenderingDevice::get_driver_and_device_memory_report);8459ClassDB::bind_method(D_METHOD("get_tracked_object_name", "type_index"), &RenderingDevice::get_tracked_object_name);8460ClassDB::bind_method(D_METHOD("get_tracked_object_type_count"), &RenderingDevice::get_tracked_object_type_count);8461ClassDB::bind_method(D_METHOD("get_driver_total_memory"), &RenderingDevice::get_driver_total_memory);8462ClassDB::bind_method(D_METHOD("get_driver_allocation_count"), &RenderingDevice::get_driver_allocation_count);8463ClassDB::bind_method(D_METHOD("get_driver_memory_by_object_type", "type"), &RenderingDevice::get_driver_memory_by_object_type);8464ClassDB::bind_method(D_METHOD("get_driver_allocs_by_object_type", "type"), &RenderingDevice::get_driver_allocs_by_object_type);8465ClassDB::bind_method(D_METHOD("get_device_total_memory"), &RenderingDevice::get_device_total_memory);8466ClassDB::bind_method(D_METHOD("get_device_allocation_count"), &RenderingDevice::get_device_allocation_count);8467ClassDB::bind_method(D_METHOD("get_device_memory_by_object_type", "type"), &RenderingDevice::get_device_memory_by_object_type);8468ClassDB::bind_method(D_METHOD("get_device_allocs_by_object_type", "type"), &RenderingDevice::get_device_allocs_by_object_type);84698470BIND_ENUM_CONSTANT(DEVICE_TYPE_OTHER);8471BIND_ENUM_CONSTANT(DEVICE_TYPE_INTEGRATED_GPU);8472BIND_ENUM_CONSTANT(DEVICE_TYPE_DISCRETE_GPU);8473BIND_ENUM_CONSTANT(DEVICE_TYPE_VIRTUAL_GPU);8474BIND_ENUM_CONSTANT(DEVICE_TYPE_CPU);8475BIND_ENUM_CONSTANT(DEVICE_TYPE_MAX);84768477BIND_ENUM_CONSTANT(DRIVER_RESOURCE_LOGICAL_DEVICE);8478BIND_ENUM_CONSTANT(DRIVER_RESOURCE_PHYSICAL_DEVICE);8479BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TOPMOST_OBJECT);8480BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMMAND_QUEUE);8481BIND_ENUM_CONSTANT(DRIVER_RESOURCE_QUEUE_FAMILY);8482BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE);8483BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_VIEW);8484BIND_ENUM_CONSTANT(DRIVER_RESOURCE_TEXTURE_DATA_FORMAT);8485BIND_ENUM_CONSTANT(DRIVER_RESOURCE_SAMPLER);8486BIND_ENUM_CONSTANT(DRIVER_RESOURCE_UNIFORM_SET);8487BIND_ENUM_CONSTANT(DRIVER_RESOURCE_BUFFER);8488BIND_ENUM_CONSTANT(DRIVER_RESOURCE_COMPUTE_PIPELINE);8489BIND_ENUM_CONSTANT(DRIVER_RESOURCE_RENDER_PIPELINE);8490#ifndef DISABLE_DEPRECATED8491BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DEVICE);8492BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE);8493BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_INSTANCE);8494BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE);8495BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX);8496BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE);8497BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_VIEW);8498BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT);8499BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_SAMPLER);8500BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET);8501BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_BUFFER);8502BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE);8503BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE);8504#endif85058506BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4_UNORM_PACK8);8507BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4B4A4_UNORM_PACK16);8508BIND_ENUM_CONSTANT(DATA_FORMAT_B4G4R4A4_UNORM_PACK16);8509BIND_ENUM_CONSTANT(DATA_FORMAT_R5G6B5_UNORM_PACK16);8510BIND_ENUM_CONSTANT(DATA_FORMAT_B5G6R5_UNORM_PACK16);8511BIND_ENUM_CONSTANT(DATA_FORMAT_R5G5B5A1_UNORM_PACK16);8512BIND_ENUM_CONSTANT(DATA_FORMAT_B5G5R5A1_UNORM_PACK16);8513BIND_ENUM_CONSTANT(DATA_FORMAT_A1R5G5B5_UNORM_PACK16);8514BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UNORM);8515BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SNORM);8516BIND_ENUM_CONSTANT(DATA_FORMAT_R8_USCALED);8517BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SSCALED);8518BIND_ENUM_CONSTANT(DATA_FORMAT_R8_UINT);8519BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SINT);8520BIND_ENUM_CONSTANT(DATA_FORMAT_R8_SRGB);8521BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UNORM);8522BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SNORM);8523BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_USCALED);8524BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SSCALED);8525BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_UINT);8526BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SINT);8527BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8_SRGB);8528BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UNORM);8529BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SNORM);8530BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_USCALED);8531BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SSCALED);8532BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_UINT);8533BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SINT);8534BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8_SRGB);8535BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UNORM);8536BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SNORM);8537BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_USCALED);8538BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SSCALED);8539BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_UINT);8540BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SINT);8541BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8_SRGB);8542BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UNORM);8543BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SNORM);8544BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_USCALED);8545BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SSCALED);8546BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_UINT);8547BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SINT);8548BIND_ENUM_CONSTANT(DATA_FORMAT_R8G8B8A8_SRGB);8549BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UNORM);8550BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SNORM);8551BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_USCALED);8552BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SSCALED);8553BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_UINT);8554BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SINT);8555BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8A8_SRGB);8556BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UNORM_PACK32);8557BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SNORM_PACK32);8558BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_USCALED_PACK32);8559BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SSCALED_PACK32);8560BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_UINT_PACK32);8561BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SINT_PACK32);8562BIND_ENUM_CONSTANT(DATA_FORMAT_A8B8G8R8_SRGB_PACK32);8563BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UNORM_PACK32);8564BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SNORM_PACK32);8565BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_USCALED_PACK32);8566BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SSCALED_PACK32);8567BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_UINT_PACK32);8568BIND_ENUM_CONSTANT(DATA_FORMAT_A2R10G10B10_SINT_PACK32);8569BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UNORM_PACK32);8570BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SNORM_PACK32);8571BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_USCALED_PACK32);8572BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SSCALED_PACK32);8573BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_UINT_PACK32);8574BIND_ENUM_CONSTANT(DATA_FORMAT_A2B10G10R10_SINT_PACK32);8575BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UNORM);8576BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SNORM);8577BIND_ENUM_CONSTANT(DATA_FORMAT_R16_USCALED);8578BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SSCALED);8579BIND_ENUM_CONSTANT(DATA_FORMAT_R16_UINT);8580BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SINT);8581BIND_ENUM_CONSTANT(DATA_FORMAT_R16_SFLOAT);8582BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UNORM);8583BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SNORM);8584BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_USCALED);8585BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SSCALED);8586BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_UINT);8587BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SINT);8588BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16_SFLOAT);8589BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UNORM);8590BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SNORM);8591BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_USCALED);8592BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SSCALED);8593BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_UINT);8594BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SINT);8595BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16_SFLOAT);8596BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UNORM);8597BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SNORM);8598BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_USCALED);8599BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SSCALED);8600BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_UINT);8601BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SINT);8602BIND_ENUM_CONSTANT(DATA_FORMAT_R16G16B16A16_SFLOAT);8603BIND_ENUM_CONSTANT(DATA_FORMAT_R32_UINT);8604BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SINT);8605BIND_ENUM_CONSTANT(DATA_FORMAT_R32_SFLOAT);8606BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_UINT);8607BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SINT);8608BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32_SFLOAT);8609BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_UINT);8610BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SINT);8611BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32_SFLOAT);8612BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_UINT);8613BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SINT);8614BIND_ENUM_CONSTANT(DATA_FORMAT_R32G32B32A32_SFLOAT);8615BIND_ENUM_CONSTANT(DATA_FORMAT_R64_UINT);8616BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SINT);8617BIND_ENUM_CONSTANT(DATA_FORMAT_R64_SFLOAT);8618BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_UINT);8619BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SINT);8620BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64_SFLOAT);8621BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_UINT);8622BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SINT);8623BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64_SFLOAT);8624BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_UINT);8625BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SINT);8626BIND_ENUM_CONSTANT(DATA_FORMAT_R64G64B64A64_SFLOAT);8627BIND_ENUM_CONSTANT(DATA_FORMAT_B10G11R11_UFLOAT_PACK32);8628BIND_ENUM_CONSTANT(DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);8629BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM);8630BIND_ENUM_CONSTANT(DATA_FORMAT_X8_D24_UNORM_PACK32);8631BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT);8632BIND_ENUM_CONSTANT(DATA_FORMAT_S8_UINT);8633BIND_ENUM_CONSTANT(DATA_FORMAT_D16_UNORM_S8_UINT);8634BIND_ENUM_CONSTANT(DATA_FORMAT_D24_UNORM_S8_UINT);8635BIND_ENUM_CONSTANT(DATA_FORMAT_D32_SFLOAT_S8_UINT);8636BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_UNORM_BLOCK);8637BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGB_SRGB_BLOCK);8638BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_UNORM_BLOCK);8639BIND_ENUM_CONSTANT(DATA_FORMAT_BC1_RGBA_SRGB_BLOCK);8640BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_UNORM_BLOCK);8641BIND_ENUM_CONSTANT(DATA_FORMAT_BC2_SRGB_BLOCK);8642BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_UNORM_BLOCK);8643BIND_ENUM_CONSTANT(DATA_FORMAT_BC3_SRGB_BLOCK);8644BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_UNORM_BLOCK);8645BIND_ENUM_CONSTANT(DATA_FORMAT_BC4_SNORM_BLOCK);8646BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_UNORM_BLOCK);8647BIND_ENUM_CONSTANT(DATA_FORMAT_BC5_SNORM_BLOCK);8648BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_UFLOAT_BLOCK);8649BIND_ENUM_CONSTANT(DATA_FORMAT_BC6H_SFLOAT_BLOCK);8650BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_UNORM_BLOCK);8651BIND_ENUM_CONSTANT(DATA_FORMAT_BC7_SRGB_BLOCK);8652BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK);8653BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK);8654BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK);8655BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK);8656BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK);8657BIND_ENUM_CONSTANT(DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK);8658BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_UNORM_BLOCK);8659BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11_SNORM_BLOCK);8660BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_UNORM_BLOCK);8661BIND_ENUM_CONSTANT(DATA_FORMAT_EAC_R11G11_SNORM_BLOCK);8662BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_UNORM_BLOCK);8663BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_SRGB_BLOCK);8664BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_UNORM_BLOCK);8665BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_SRGB_BLOCK);8666BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_UNORM_BLOCK);8667BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_SRGB_BLOCK);8668BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_UNORM_BLOCK);8669BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_SRGB_BLOCK);8670BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_UNORM_BLOCK);8671BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_SRGB_BLOCK);8672BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_UNORM_BLOCK);8673BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_SRGB_BLOCK);8674BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_UNORM_BLOCK);8675BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_SRGB_BLOCK);8676BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_UNORM_BLOCK);8677BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_SRGB_BLOCK);8678BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_UNORM_BLOCK);8679BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_SRGB_BLOCK);8680BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_UNORM_BLOCK);8681BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_SRGB_BLOCK);8682BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_UNORM_BLOCK);8683BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_SRGB_BLOCK);8684BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_UNORM_BLOCK);8685BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_SRGB_BLOCK);8686BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_UNORM_BLOCK);8687BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_SRGB_BLOCK);8688BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_UNORM_BLOCK);8689BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_SRGB_BLOCK);8690BIND_ENUM_CONSTANT(DATA_FORMAT_G8B8G8R8_422_UNORM);8691BIND_ENUM_CONSTANT(DATA_FORMAT_B8G8R8G8_422_UNORM);8692BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM);8693BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM);8694BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM);8695BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM);8696BIND_ENUM_CONSTANT(DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM);8697BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6_UNORM_PACK16);8698BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6_UNORM_2PACK16);8699BIND_ENUM_CONSTANT(DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16);8700BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16);8701BIND_ENUM_CONSTANT(DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16);8702BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16);8703BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16);8704BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16);8705BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16);8706BIND_ENUM_CONSTANT(DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16);8707BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4_UNORM_PACK16);8708BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4_UNORM_2PACK16);8709BIND_ENUM_CONSTANT(DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16);8710BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16);8711BIND_ENUM_CONSTANT(DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16);8712BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16);8713BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16);8714BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16);8715BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16);8716BIND_ENUM_CONSTANT(DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16);8717BIND_ENUM_CONSTANT(DATA_FORMAT_G16B16G16R16_422_UNORM);8718BIND_ENUM_CONSTANT(DATA_FORMAT_B16G16R16G16_422_UNORM);8719BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM);8720BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM);8721BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM);8722BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM);8723BIND_ENUM_CONSTANT(DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM);8724BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_4x4_SFLOAT_BLOCK);8725BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x4_SFLOAT_BLOCK);8726BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_5x5_SFLOAT_BLOCK);8727BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x5_SFLOAT_BLOCK);8728BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_6x6_SFLOAT_BLOCK);8729BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x5_SFLOAT_BLOCK);8730BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x6_SFLOAT_BLOCK);8731BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_8x8_SFLOAT_BLOCK);8732BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x5_SFLOAT_BLOCK);8733BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x6_SFLOAT_BLOCK);8734BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x8_SFLOAT_BLOCK);8735BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_10x10_SFLOAT_BLOCK);8736BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x10_SFLOAT_BLOCK);8737BIND_ENUM_CONSTANT(DATA_FORMAT_ASTC_12x12_SFLOAT_BLOCK);8738BIND_ENUM_CONSTANT(DATA_FORMAT_MAX);87398740#ifndef DISABLE_DEPRECATED8741BIND_BITFIELD_FLAG(BARRIER_MASK_VERTEX);8742BIND_BITFIELD_FLAG(BARRIER_MASK_FRAGMENT);8743BIND_BITFIELD_FLAG(BARRIER_MASK_COMPUTE);8744BIND_BITFIELD_FLAG(BARRIER_MASK_TRANSFER);8745BIND_BITFIELD_FLAG(BARRIER_MASK_RASTER);8746BIND_BITFIELD_FLAG(BARRIER_MASK_ALL_BARRIERS);8747BIND_BITFIELD_FLAG(BARRIER_MASK_NO_BARRIER);8748#endif87498750BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D);8751BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D);8752BIND_ENUM_CONSTANT(TEXTURE_TYPE_3D);8753BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE);8754BIND_ENUM_CONSTANT(TEXTURE_TYPE_1D_ARRAY);8755BIND_ENUM_CONSTANT(TEXTURE_TYPE_2D_ARRAY);8756BIND_ENUM_CONSTANT(TEXTURE_TYPE_CUBE_ARRAY);8757BIND_ENUM_CONSTANT(TEXTURE_TYPE_MAX);87588759BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_1);8760BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_2);8761BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_4);8762BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_8);8763BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_16);8764BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_32);8765BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_64);8766BIND_ENUM_CONSTANT(TEXTURE_SAMPLES_MAX);87678768BIND_BITFIELD_FLAG(TEXTURE_USAGE_SAMPLING_BIT);8769BIND_BITFIELD_FLAG(TEXTURE_USAGE_COLOR_ATTACHMENT_BIT);8770BIND_BITFIELD_FLAG(TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);8771BIND_BITFIELD_FLAG(TEXTURE_USAGE_DEPTH_RESOLVE_ATTACHMENT_BIT);8772BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_BIT);8773BIND_BITFIELD_FLAG(TEXTURE_USAGE_STORAGE_ATOMIC_BIT);8774BIND_BITFIELD_FLAG(TEXTURE_USAGE_CPU_READ_BIT);8775BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_UPDATE_BIT);8776BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_FROM_BIT);8777BIND_BITFIELD_FLAG(TEXTURE_USAGE_CAN_COPY_TO_BIT);8778BIND_BITFIELD_FLAG(TEXTURE_USAGE_INPUT_ATTACHMENT_BIT);87798780BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_IDENTITY);8781BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ZERO);8782BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_ONE);8783BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_R);8784BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_G);8785BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_B);8786BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_A);8787BIND_ENUM_CONSTANT(TEXTURE_SWIZZLE_MAX);87888789BIND_ENUM_CONSTANT(TEXTURE_SLICE_2D);8790BIND_ENUM_CONSTANT(TEXTURE_SLICE_CUBEMAP);8791BIND_ENUM_CONSTANT(TEXTURE_SLICE_3D);87928793BIND_ENUM_CONSTANT(SAMPLER_FILTER_NEAREST);8794BIND_ENUM_CONSTANT(SAMPLER_FILTER_LINEAR);8795BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_REPEAT);8796BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRRORED_REPEAT);8797BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_EDGE);8798BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_CLAMP_TO_BORDER);8799BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MIRROR_CLAMP_TO_EDGE);8800BIND_ENUM_CONSTANT(SAMPLER_REPEAT_MODE_MAX);88018802BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK);8803BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_TRANSPARENT_BLACK);8804BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_BLACK);8805BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_BLACK);8806BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_FLOAT_OPAQUE_WHITE);8807BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_INT_OPAQUE_WHITE);8808BIND_ENUM_CONSTANT(SAMPLER_BORDER_COLOR_MAX);88098810BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_VERTEX);8811BIND_ENUM_CONSTANT(VERTEX_FREQUENCY_INSTANCE);88128813BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT16);8814BIND_ENUM_CONSTANT(INDEX_BUFFER_FORMAT_UINT32);88158816BIND_BITFIELD_FLAG(STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT);88178818BIND_BITFIELD_FLAG(BUFFER_CREATION_DEVICE_ADDRESS_BIT);8819BIND_BITFIELD_FLAG(BUFFER_CREATION_AS_STORAGE_BIT);8820// Not exposed on purpose. This flag is too dangerous to be exposed to regular GD users.8821//BIND_BITFIELD_FLAG(BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT);8822BIND_BITFIELD_FLAG(BUFFER_CREATION_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT);88238824BIND_BITFIELD_FLAG(ACCELERATION_STRUCTURE_GEOMETRY_OPAQUE);8825BIND_BITFIELD_FLAG(ACCELERATION_STRUCTURE_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION);88268827BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER); //for sampling only (sampler GLSL type)8828BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE); // for sampling only); but includes a texture); (samplerXX GLSL type)); first a sampler then a texture8829BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE); //only texture); (textureXX GLSL type)8830BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE); // storage image (imageXX GLSL type)); for compute mostly8831BIND_ENUM_CONSTANT(UNIFORM_TYPE_TEXTURE_BUFFER); // buffer texture (or TBO); textureBuffer type)8832BIND_ENUM_CONSTANT(UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER); // buffer texture with a sampler(or TBO); samplerBuffer type)8833BIND_ENUM_CONSTANT(UNIFORM_TYPE_IMAGE_BUFFER); //texel buffer); (imageBuffer type)); for compute mostly8834BIND_ENUM_CONSTANT(UNIFORM_TYPE_UNIFORM_BUFFER); //regular uniform buffer (or UBO).8835BIND_ENUM_CONSTANT(UNIFORM_TYPE_STORAGE_BUFFER); //storage buffer ("buffer" qualifier) like UBO); but supports storage); for compute mostly8836BIND_ENUM_CONSTANT(UNIFORM_TYPE_INPUT_ATTACHMENT); //used for sub-pass read/write); for mobile mostly8837BIND_ENUM_CONSTANT(UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC); // Exposed in case a BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT buffer created by C++ makes it into GD users.8838BIND_ENUM_CONSTANT(UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC); // Exposed in case a BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT buffer created by C++ makes it into GD users.8839BIND_ENUM_CONSTANT(UNIFORM_TYPE_ACCELERATION_STRUCTURE); //acceleration structure (TLAS)); for raytracing8840BIND_ENUM_CONSTANT(UNIFORM_TYPE_MAX);88418842BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_POINTS);8843BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES);8844BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINES_WITH_ADJACENCY);8845BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS);8846BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_LINESTRIPS_WITH_ADJACENCY);8847BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES);8848BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLES_WITH_ADJACENCY);8849BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS);8850BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_AJACENCY);8851BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);8852BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_TESSELATION_PATCH);8853BIND_ENUM_CONSTANT(RENDER_PRIMITIVE_MAX);88548855BIND_ENUM_CONSTANT(POLYGON_CULL_DISABLED);8856BIND_ENUM_CONSTANT(POLYGON_CULL_FRONT);8857BIND_ENUM_CONSTANT(POLYGON_CULL_BACK);88588859BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_CLOCKWISE);8860BIND_ENUM_CONSTANT(POLYGON_FRONT_FACE_COUNTER_CLOCKWISE);88618862BIND_ENUM_CONSTANT(STENCIL_OP_KEEP);8863BIND_ENUM_CONSTANT(STENCIL_OP_ZERO);8864BIND_ENUM_CONSTANT(STENCIL_OP_REPLACE);8865BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_CLAMP);8866BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_CLAMP);8867BIND_ENUM_CONSTANT(STENCIL_OP_INVERT);8868BIND_ENUM_CONSTANT(STENCIL_OP_INCREMENT_AND_WRAP);8869BIND_ENUM_CONSTANT(STENCIL_OP_DECREMENT_AND_WRAP);8870BIND_ENUM_CONSTANT(STENCIL_OP_MAX); //not an actual operator); just the amount of operators :D88718872BIND_ENUM_CONSTANT(COMPARE_OP_NEVER);8873BIND_ENUM_CONSTANT(COMPARE_OP_LESS);8874BIND_ENUM_CONSTANT(COMPARE_OP_EQUAL);8875BIND_ENUM_CONSTANT(COMPARE_OP_LESS_OR_EQUAL);8876BIND_ENUM_CONSTANT(COMPARE_OP_GREATER);8877BIND_ENUM_CONSTANT(COMPARE_OP_NOT_EQUAL);8878BIND_ENUM_CONSTANT(COMPARE_OP_GREATER_OR_EQUAL);8879BIND_ENUM_CONSTANT(COMPARE_OP_ALWAYS);8880BIND_ENUM_CONSTANT(COMPARE_OP_MAX);88818882BIND_ENUM_CONSTANT(LOGIC_OP_CLEAR);8883BIND_ENUM_CONSTANT(LOGIC_OP_AND);8884BIND_ENUM_CONSTANT(LOGIC_OP_AND_REVERSE);8885BIND_ENUM_CONSTANT(LOGIC_OP_COPY);8886BIND_ENUM_CONSTANT(LOGIC_OP_AND_INVERTED);8887BIND_ENUM_CONSTANT(LOGIC_OP_NO_OP);8888BIND_ENUM_CONSTANT(LOGIC_OP_XOR);8889BIND_ENUM_CONSTANT(LOGIC_OP_OR);8890BIND_ENUM_CONSTANT(LOGIC_OP_NOR);8891BIND_ENUM_CONSTANT(LOGIC_OP_EQUIVALENT);8892BIND_ENUM_CONSTANT(LOGIC_OP_INVERT);8893BIND_ENUM_CONSTANT(LOGIC_OP_OR_REVERSE);8894BIND_ENUM_CONSTANT(LOGIC_OP_COPY_INVERTED);8895BIND_ENUM_CONSTANT(LOGIC_OP_OR_INVERTED);8896BIND_ENUM_CONSTANT(LOGIC_OP_NAND);8897BIND_ENUM_CONSTANT(LOGIC_OP_SET);8898BIND_ENUM_CONSTANT(LOGIC_OP_MAX); //not an actual operator); just the amount of operators :D88998900BIND_ENUM_CONSTANT(BLEND_FACTOR_ZERO);8901BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE);8902BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_COLOR);8903BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_COLOR);8904BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_COLOR);8905BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_COLOR);8906BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA);8907BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);8908BIND_ENUM_CONSTANT(BLEND_FACTOR_DST_ALPHA);8909BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_DST_ALPHA);8910BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_COLOR);8911BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR);8912BIND_ENUM_CONSTANT(BLEND_FACTOR_CONSTANT_ALPHA);8913BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA);8914BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC_ALPHA_SATURATE);8915BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_COLOR);8916BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_COLOR);8917BIND_ENUM_CONSTANT(BLEND_FACTOR_SRC1_ALPHA);8918BIND_ENUM_CONSTANT(BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA);8919BIND_ENUM_CONSTANT(BLEND_FACTOR_MAX);89208921BIND_ENUM_CONSTANT(BLEND_OP_ADD);8922BIND_ENUM_CONSTANT(BLEND_OP_SUBTRACT);8923BIND_ENUM_CONSTANT(BLEND_OP_REVERSE_SUBTRACT);8924BIND_ENUM_CONSTANT(BLEND_OP_MINIMUM);8925BIND_ENUM_CONSTANT(BLEND_OP_MAXIMUM);8926BIND_ENUM_CONSTANT(BLEND_OP_MAX);89278928BIND_BITFIELD_FLAG(DYNAMIC_STATE_LINE_WIDTH);8929BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BIAS);8930BIND_BITFIELD_FLAG(DYNAMIC_STATE_BLEND_CONSTANTS);8931BIND_BITFIELD_FLAG(DYNAMIC_STATE_DEPTH_BOUNDS);8932BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_COMPARE_MASK);8933BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_WRITE_MASK);8934BIND_BITFIELD_FLAG(DYNAMIC_STATE_STENCIL_REFERENCE);89358936#ifndef DISABLE_DEPRECATED8937BIND_ENUM_CONSTANT(INITIAL_ACTION_LOAD);8938BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR);8939BIND_ENUM_CONSTANT(INITIAL_ACTION_DISCARD);8940BIND_ENUM_CONSTANT(INITIAL_ACTION_MAX);8941BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION);8942BIND_ENUM_CONSTANT(INITIAL_ACTION_CLEAR_REGION_CONTINUE);8943BIND_ENUM_CONSTANT(INITIAL_ACTION_KEEP);8944BIND_ENUM_CONSTANT(INITIAL_ACTION_DROP);8945BIND_ENUM_CONSTANT(INITIAL_ACTION_CONTINUE);89468947BIND_ENUM_CONSTANT(FINAL_ACTION_STORE);8948BIND_ENUM_CONSTANT(FINAL_ACTION_DISCARD);8949BIND_ENUM_CONSTANT(FINAL_ACTION_MAX);8950BIND_ENUM_CONSTANT(FINAL_ACTION_READ);8951BIND_ENUM_CONSTANT(FINAL_ACTION_CONTINUE);8952#endif89538954BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX);8955BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT);8956BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL);8957BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION);8958BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE);8959BIND_ENUM_CONSTANT(SHADER_STAGE_RAYGEN);8960BIND_ENUM_CONSTANT(SHADER_STAGE_ANY_HIT);8961BIND_ENUM_CONSTANT(SHADER_STAGE_CLOSEST_HIT);8962BIND_ENUM_CONSTANT(SHADER_STAGE_MISS);8963BIND_ENUM_CONSTANT(SHADER_STAGE_INTERSECTION);8964BIND_ENUM_CONSTANT(SHADER_STAGE_MAX);8965BIND_ENUM_CONSTANT(SHADER_STAGE_VERTEX_BIT);8966BIND_ENUM_CONSTANT(SHADER_STAGE_FRAGMENT_BIT);8967BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_CONTROL_BIT);8968BIND_ENUM_CONSTANT(SHADER_STAGE_TESSELATION_EVALUATION_BIT);8969BIND_ENUM_CONSTANT(SHADER_STAGE_COMPUTE_BIT);8970BIND_ENUM_CONSTANT(SHADER_STAGE_RAYGEN_BIT);8971BIND_ENUM_CONSTANT(SHADER_STAGE_ANY_HIT_BIT);8972BIND_ENUM_CONSTANT(SHADER_STAGE_CLOSEST_HIT_BIT);8973BIND_ENUM_CONSTANT(SHADER_STAGE_MISS_BIT);8974BIND_ENUM_CONSTANT(SHADER_STAGE_INTERSECTION_BIT);89758976BIND_ENUM_CONSTANT(SHADER_LANGUAGE_GLSL);8977BIND_ENUM_CONSTANT(SHADER_LANGUAGE_HLSL);89788979BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL);8980BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT);8981BIND_ENUM_CONSTANT(PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT);89828983BIND_ENUM_CONSTANT(SUPPORTS_METALFX_SPATIAL);8984BIND_ENUM_CONSTANT(SUPPORTS_METALFX_TEMPORAL);8985BIND_ENUM_CONSTANT(SUPPORTS_BUFFER_DEVICE_ADDRESS);8986BIND_ENUM_CONSTANT(SUPPORTS_IMAGE_ATOMIC_32_BIT);8987BIND_ENUM_CONSTANT(SUPPORTS_RAY_QUERY);8988BIND_ENUM_CONSTANT(SUPPORTS_RAYTRACING_PIPELINE);89898990BIND_ENUM_CONSTANT(LIMIT_MAX_BOUND_UNIFORM_SETS);8991BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS);8992BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_UNIFORM_SET);8993BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET);8994BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET);8995BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET);8996BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET);8997BIND_ENUM_CONSTANT(LIMIT_MAX_DRAW_INDEXED_INDEX);8998BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_HEIGHT);8999BIND_ENUM_CONSTANT(LIMIT_MAX_FRAMEBUFFER_WIDTH);9000BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_ARRAY_LAYERS);9001BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_1D);9002BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_2D);9003BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_3D);9004BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURE_SIZE_CUBE);9005BIND_ENUM_CONSTANT(LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);9006BIND_ENUM_CONSTANT(LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE);9007BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE);9008BIND_ENUM_CONSTANT(LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE);9009BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE);9010BIND_ENUM_CONSTANT(LIMIT_MAX_PUSH_CONSTANT_SIZE);9011BIND_ENUM_CONSTANT(LIMIT_MAX_UNIFORM_BUFFER_SIZE);9012BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET);9013BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES);9014BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDINGS);9015BIND_ENUM_CONSTANT(LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE);9016BIND_ENUM_CONSTANT(LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT);9017BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_SHARED_MEMORY_SIZE);9018BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X);9019BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y);9020BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z);9021BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS);9022BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X);9023BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y);9024BIND_ENUM_CONSTANT(LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z);9025BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_X);9026BIND_ENUM_CONSTANT(LIMIT_MAX_VIEWPORT_DIMENSIONS_Y);9027BIND_ENUM_CONSTANT(LIMIT_METALFX_TEMPORAL_SCALER_MIN_SCALE);9028BIND_ENUM_CONSTANT(LIMIT_METALFX_TEMPORAL_SCALER_MAX_SCALE);90299030BIND_ENUM_CONSTANT(MEMORY_TEXTURES);9031BIND_ENUM_CONSTANT(MEMORY_BUFFERS);9032BIND_ENUM_CONSTANT(MEMORY_TOTAL);90339034BIND_CONSTANT(INVALID_ID);9035BIND_CONSTANT(INVALID_FORMAT_ID);90369037BIND_ENUM_CONSTANT(NONE);9038BIND_ENUM_CONSTANT(REFLECTION_PROBES);9039BIND_ENUM_CONSTANT(SKY_PASS);9040BIND_ENUM_CONSTANT(LIGHTMAPPER_PASS);9041BIND_ENUM_CONSTANT(SHADOW_PASS_DIRECTIONAL);9042BIND_ENUM_CONSTANT(SHADOW_PASS_CUBE);9043BIND_ENUM_CONSTANT(OPAQUE_PASS);9044BIND_ENUM_CONSTANT(ALPHA_PASS);9045BIND_ENUM_CONSTANT(TRANSPARENT_PASS);9046BIND_ENUM_CONSTANT(POST_PROCESSING_PASS);9047BIND_ENUM_CONSTANT(BLIT_PASS);9048BIND_ENUM_CONSTANT(UI_PASS);9049BIND_ENUM_CONSTANT(DEBUG_PASS);90509051BIND_BITFIELD_FLAG(DRAW_DEFAULT_ALL);9052BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_0);9053BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_1);9054BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_2);9055BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_3);9056BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_4);9057BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_5);9058BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_6);9059BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_7);9060BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_MASK);9061BIND_BITFIELD_FLAG(DRAW_CLEAR_COLOR_ALL);9062BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_0);9063BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_1);9064BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_2);9065BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_3);9066BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_4);9067BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_5);9068BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_6);9069BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_7);9070BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_MASK);9071BIND_BITFIELD_FLAG(DRAW_IGNORE_COLOR_ALL);9072BIND_BITFIELD_FLAG(DRAW_CLEAR_DEPTH);9073BIND_BITFIELD_FLAG(DRAW_IGNORE_DEPTH);9074BIND_BITFIELD_FLAG(DRAW_CLEAR_STENCIL);9075BIND_BITFIELD_FLAG(DRAW_IGNORE_STENCIL);9076BIND_BITFIELD_FLAG(DRAW_CLEAR_ALL);9077BIND_BITFIELD_FLAG(DRAW_IGNORE_ALL);9078}90799080void RenderingDevice::make_current() {9081render_thread_id = Thread::get_caller_id();9082}90839084RenderingDevice::~RenderingDevice() {9085finalize();90869087if (singleton == this) {9088singleton = nullptr;9089}9090}90919092RenderingDevice::RenderingDevice() {9093if (singleton == nullptr) {9094singleton = this;9095}90969097render_thread_id = Thread::get_caller_id();9098}90999100/*****************/9101/**** BINDERS ****/9102/*****************/91039104RID RenderingDevice::_texture_create(const Ref<RDTextureFormat> &p_format, const Ref<RDTextureView> &p_view, const TypedArray<PackedByteArray> &p_data) {9105ERR_FAIL_COND_V(p_format.is_null(), RID());9106ERR_FAIL_COND_V(p_view.is_null(), RID());9107Vector<Vector<uint8_t>> data;9108for (int i = 0; i < p_data.size(); i++) {9109Vector<uint8_t> byte_slice = p_data[i];9110ERR_FAIL_COND_V(byte_slice.is_empty(), RID());9111data.push_back(byte_slice);9112}9113return texture_create(p_format->base, p_view->base, data);9114}91159116RID RenderingDevice::_texture_create_shared(const Ref<RDTextureView> &p_view, RID p_with_texture) {9117ERR_FAIL_COND_V(p_view.is_null(), RID());91189119return texture_create_shared(p_view->base, p_with_texture);9120}91219122RID RenderingDevice::_texture_create_shared_from_slice(const Ref<RDTextureView> &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) {9123ERR_FAIL_COND_V(p_view.is_null(), RID());91249125return texture_create_shared_from_slice(p_view->base, p_with_texture, p_layer, p_mipmap, p_mipmaps, p_slice_type);9126}91279128Ref<RDTextureFormat> RenderingDevice::_texture_get_format(RID p_rd_texture) {9129Ref<RDTextureFormat> rtf;9130rtf.instantiate();9131rtf->base = texture_get_format(p_rd_texture);91329133return rtf;9134}91359136RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create(const TypedArray<RDAttachmentFormat> &p_attachments, uint32_t p_view_count) {9137Vector<AttachmentFormat> attachments;9138attachments.resize(p_attachments.size());91399140for (int i = 0; i < p_attachments.size(); i++) {9141Ref<RDAttachmentFormat> af = p_attachments[i];9142ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);9143attachments.write[i] = af->base;9144}9145return framebuffer_format_create(attachments, p_view_count);9146}91479148RenderingDevice::FramebufferFormatID RenderingDevice::_framebuffer_format_create_multipass(const TypedArray<RDAttachmentFormat> &p_attachments, const TypedArray<RDFramebufferPass> &p_passes, uint32_t p_view_count) {9149Vector<AttachmentFormat> attachments;9150attachments.resize(p_attachments.size());91519152for (int i = 0; i < p_attachments.size(); i++) {9153Ref<RDAttachmentFormat> af = p_attachments[i];9154ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);9155attachments.write[i] = af->base;9156}91579158Vector<FramebufferPass> passes;9159for (int i = 0; i < p_passes.size(); i++) {9160Ref<RDFramebufferPass> pass = p_passes[i];9161ERR_CONTINUE(pass.is_null());9162passes.push_back(pass->base);9163}91649165return framebuffer_format_create_multipass(attachments, passes, p_view_count);9166}91679168RID RenderingDevice::_framebuffer_create(const TypedArray<RID> &p_textures, FramebufferFormatID p_format_check, uint32_t p_view_count) {9169Vector<RID> textures = Variant(p_textures);9170return framebuffer_create(textures, p_format_check, p_view_count);9171}91729173RID RenderingDevice::_framebuffer_create_multipass(const TypedArray<RID> &p_textures, const TypedArray<RDFramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {9174Vector<RID> textures = Variant(p_textures);9175Vector<FramebufferPass> passes;9176for (int i = 0; i < p_passes.size(); i++) {9177Ref<RDFramebufferPass> pass = p_passes[i];9178ERR_CONTINUE(pass.is_null());9179passes.push_back(pass->base);9180}9181return framebuffer_create_multipass(textures, passes, p_format_check, p_view_count);9182}91839184RID RenderingDevice::_sampler_create(const Ref<RDSamplerState> &p_state) {9185ERR_FAIL_COND_V(p_state.is_null(), RID());91869187return sampler_create(p_state->base);9188}91899190RenderingDevice::VertexFormatID RenderingDevice::_vertex_format_create(const TypedArray<RDVertexAttribute> &p_vertex_formats) {9191Vector<VertexAttribute> descriptions;9192descriptions.resize(p_vertex_formats.size());91939194for (int i = 0; i < p_vertex_formats.size(); i++) {9195Ref<RDVertexAttribute> af = p_vertex_formats[i];9196ERR_FAIL_COND_V(af.is_null(), INVALID_FORMAT_ID);9197descriptions.write[i] = af->base;9198}9199return vertex_format_create(descriptions);9200}92019202RID RenderingDevice::_vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const TypedArray<RID> &p_src_buffers, const Vector<int64_t> &p_offsets) {9203Vector<RID> buffers = Variant(p_src_buffers);92049205Vector<uint64_t> offsets;9206offsets.resize(p_offsets.size());9207for (int i = 0; i < p_offsets.size(); i++) {9208offsets.write[i] = p_offsets[i];9209}92109211return vertex_array_create(p_vertex_count, p_vertex_format, buffers, offsets);9212}92139214void RenderingDevice::_draw_list_bind_vertex_buffers_format(DrawListID p_list, VertexFormatID p_vertex_format, uint32_t p_vertex_count, const TypedArray<RID> &p_vertex_buffers, const Vector<int64_t> &p_offsets) {9215Vector<RID> buffers = Variant(p_vertex_buffers);92169217Vector<uint64_t> offsets;9218offsets.resize(p_offsets.size());9219for (int i = 0; i < p_offsets.size(); i++) {9220offsets.write[i] = p_offsets[i];9221}92229223draw_list_bind_vertex_buffers_format(p_list, p_vertex_format, p_vertex_count, buffers, offsets);9224}92259226Ref<RDShaderSPIRV> RenderingDevice::_shader_compile_spirv_from_source(const Ref<RDShaderSource> &p_source, bool p_allow_cache) {9227ERR_FAIL_COND_V(p_source.is_null(), Ref<RDShaderSPIRV>());92289229Ref<RDShaderSPIRV> bytecode;9230bytecode.instantiate();9231for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {9232String error;92339234ShaderStage stage = ShaderStage(i);9235String source = p_source->get_stage_source(stage);92369237if (!source.is_empty()) {9238Vector<uint8_t> spirv = shader_compile_spirv_from_source(stage, source, p_source->get_language(), &error, p_allow_cache);9239bytecode->set_stage_bytecode(stage, spirv);9240bytecode->set_stage_compile_error(stage, error);9241}9242}9243return bytecode;9244}92459246Vector<uint8_t> RenderingDevice::_shader_compile_binary_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name) {9247ERR_FAIL_COND_V(p_spirv.is_null(), Vector<uint8_t>());92489249Vector<ShaderStageSPIRVData> stage_data;9250for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {9251ShaderStage stage = ShaderStage(i);9252ShaderStageSPIRVData sd;9253sd.shader_stage = stage;9254String error = p_spirv->get_stage_compile_error(stage);9255ERR_FAIL_COND_V_MSG(!error.is_empty(), Vector<uint8_t>(), "Can't create a shader from an errored bytecode. Check errors in source bytecode.");9256sd.spirv = p_spirv->get_stage_bytecode(stage);9257if (sd.spirv.is_empty()) {9258continue;9259}9260stage_data.push_back(sd);9261}92629263return shader_compile_binary_from_spirv(stage_data, p_shader_name);9264}92659266RID RenderingDevice::_shader_create_from_spirv(const Ref<RDShaderSPIRV> &p_spirv, const String &p_shader_name) {9267ERR_FAIL_COND_V(p_spirv.is_null(), RID());92689269Vector<ShaderStageSPIRVData> stage_data;9270for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) {9271ShaderStage stage = ShaderStage(i);9272ShaderStageSPIRVData sd;9273sd.shader_stage = stage;9274String error = p_spirv->get_stage_compile_error(stage);9275ERR_FAIL_COND_V_MSG(!error.is_empty(), RID(), "Can't create a shader from an errored bytecode. Check errors in source bytecode.");9276sd.spirv = p_spirv->get_stage_bytecode(stage);9277if (sd.spirv.is_empty()) {9278continue;9279}9280stage_data.push_back(sd);9281}9282return shader_create_from_spirv(stage_data);9283}92849285RID RenderingDevice::_uniform_set_create(const TypedArray<RDUniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {9286LocalVector<Uniform> uniforms;9287uniforms.resize(p_uniforms.size());9288for (int i = 0; i < p_uniforms.size(); i++) {9289Ref<RDUniform> uniform = p_uniforms[i];9290ERR_FAIL_COND_V(uniform.is_null(), RID());9291uniforms[i] = uniform->base;9292}9293return uniform_set_create(uniforms, p_shader, p_shader_set);9294}92959296Error RenderingDevice::_buffer_update_bind(RID p_buffer, uint32_t p_offset, uint32_t p_size, const Vector<uint8_t> &p_data) {9297return buffer_update(p_buffer, p_offset, p_size, p_data.ptr());9298}92999300void RenderingDevice::_tlas_instances_buffer_fill(RID p_instances_buffer, const TypedArray<RID> &p_blases, const TypedArray<Transform3D> &p_transforms) {9301Vector<RID> blases = Variant(p_blases);9302Vector<Transform3D> transforms;9303transforms.resize(p_transforms.size());9304for (int i = 0; i < p_transforms.size(); i++) {9305transforms.write[i] = p_transforms[i];9306}9307tlas_instances_buffer_fill(p_instances_buffer, blases, transforms);9308}93099310static Vector<RenderingDevice::PipelineSpecializationConstant> _get_spec_constants(const TypedArray<RDPipelineSpecializationConstant> &p_constants) {9311Vector<RenderingDevice::PipelineSpecializationConstant> ret;9312ret.resize(p_constants.size());9313for (int i = 0; i < p_constants.size(); i++) {9314Ref<RDPipelineSpecializationConstant> c = p_constants[i];9315ERR_CONTINUE(c.is_null());9316RenderingDevice::PipelineSpecializationConstant &sc = ret.write[i];9317Variant value = c->get_value();9318switch (value.get_type()) {9319case Variant::BOOL: {9320sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;9321sc.bool_value = value;9322} break;9323case Variant::INT: {9324sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;9325sc.int_value = value;9326} break;9327case Variant::FLOAT: {9328sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;9329sc.float_value = value;9330} break;9331default: {9332}9333}93349335sc.constant_id = c->get_constant_id();9336}9337return ret;9338}93399340RID RenderingDevice::_render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const Ref<RDPipelineRasterizationState> &p_rasterization_state, const Ref<RDPipelineMultisampleState> &p_multisample_state, const Ref<RDPipelineDepthStencilState> &p_depth_stencil_state, const Ref<RDPipelineColorBlendState> &p_blend_state, BitField<PipelineDynamicStateFlags> p_dynamic_state_flags, uint32_t p_for_render_pass, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants) {9341PipelineRasterizationState rasterization_state;9342if (p_rasterization_state.is_valid()) {9343rasterization_state = p_rasterization_state->base;9344}93459346PipelineMultisampleState multisample_state;9347if (p_multisample_state.is_valid()) {9348multisample_state = p_multisample_state->base;9349for (int i = 0; i < p_multisample_state->sample_masks.size(); i++) {9350int64_t mask = p_multisample_state->sample_masks[i];9351multisample_state.sample_mask.push_back(mask);9352}9353}93549355PipelineDepthStencilState depth_stencil_state;9356if (p_depth_stencil_state.is_valid()) {9357depth_stencil_state = p_depth_stencil_state->base;9358}93599360PipelineColorBlendState color_blend_state;9361if (p_blend_state.is_valid()) {9362color_blend_state = p_blend_state->base;9363for (int i = 0; i < p_blend_state->attachments.size(); i++) {9364Ref<RDPipelineColorBlendStateAttachment> attachment = p_blend_state->attachments[i];9365if (attachment.is_valid()) {9366color_blend_state.attachments.push_back(attachment->base);9367}9368}9369}93709371return render_pipeline_create(p_shader, p_framebuffer_format, p_vertex_format, p_render_primitive, rasterization_state, multisample_state, depth_stencil_state, color_blend_state, p_dynamic_state_flags, p_for_render_pass, _get_spec_constants(p_specialization_constants));9372}93739374RID RenderingDevice::_compute_pipeline_create(RID p_shader, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants = TypedArray<RDPipelineSpecializationConstant>()) {9375return compute_pipeline_create(p_shader, _get_spec_constants(p_specialization_constants));9376}93779378RID RenderingDevice::_raytracing_pipeline_create(RID p_shader, const TypedArray<RDPipelineSpecializationConstant> &p_specialization_constants = TypedArray<RDPipelineSpecializationConstant>()) {9379return raytracing_pipeline_create(p_shader, _get_spec_constants(p_specialization_constants));9380}93819382#ifndef DISABLE_DEPRECATED9383Vector<int64_t> RenderingDevice::_draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const TypedArray<RID> &p_storage_textures) {9384ERR_FAIL_V_MSG(Vector<int64_t>(), "Deprecated. Split draw lists are used automatically by RenderingDevice.");9385}93869387Vector<int64_t> RenderingDevice::_draw_list_switch_to_next_pass_split(uint32_t p_splits) {9388ERR_FAIL_V_MSG(Vector<int64_t>(), "Deprecated. Split draw lists are used automatically by RenderingDevice.");9389}9390#endif93919392void RenderingDevice::_draw_list_set_push_constant(DrawListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size) {9393ERR_FAIL_COND(p_data_size > (uint32_t)p_data.size());9394draw_list_set_push_constant(p_list, p_data.ptr(), p_data_size);9395}93969397void RenderingDevice::_compute_list_set_push_constant(ComputeListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size) {9398ERR_FAIL_COND(p_data_size > (uint32_t)p_data.size());9399compute_list_set_push_constant(p_list, p_data.ptr(), p_data_size);9400}94019402void RenderingDevice::_raytracing_list_set_push_constant(RaytracingListID p_list, const Vector<uint8_t> &p_data, uint32_t p_data_size) {9403ERR_FAIL_COND(p_data_size > (uint32_t)p_data.size());9404raytracing_list_set_push_constant(p_list, p_data.ptr(), p_data_size);9405}94069407static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_NONE, RDG::RESOURCE_USAGE_NONE));9408static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_COPY_FROM, RDG::RESOURCE_USAGE_COPY_FROM));9409static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_COPY_TO, RDG::RESOURCE_USAGE_COPY_TO));9410static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_RESOLVE_FROM, RDG::RESOURCE_USAGE_RESOLVE_FROM));9411static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_RESOLVE_TO, RDG::RESOURCE_USAGE_RESOLVE_TO));9412static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_UNIFORM_BUFFER_READ, RDG::RESOURCE_USAGE_UNIFORM_BUFFER_READ));9413static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_INDIRECT_BUFFER_READ, RDG::RESOURCE_USAGE_INDIRECT_BUFFER_READ));9414static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_TEXTURE_BUFFER_READ, RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ));9415static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_TEXTURE_BUFFER_READ_WRITE, RDG::RESOURCE_USAGE_TEXTURE_BUFFER_READ_WRITE));9416static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_STORAGE_BUFFER_READ, RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ));9417static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_STORAGE_BUFFER_READ_WRITE, RDG::RESOURCE_USAGE_STORAGE_BUFFER_READ_WRITE));9418static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_VERTEX_BUFFER_READ, RDG::RESOURCE_USAGE_VERTEX_BUFFER_READ));9419static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_INDEX_BUFFER_READ, RDG::RESOURCE_USAGE_INDEX_BUFFER_READ));9420static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_TEXTURE_SAMPLE, RDG::RESOURCE_USAGE_TEXTURE_SAMPLE));9421static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_STORAGE_IMAGE_READ, RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ));9422static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_STORAGE_IMAGE_READ_WRITE, RDG::RESOURCE_USAGE_STORAGE_IMAGE_READ_WRITE));9423static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_ATTACHMENT_COLOR_READ_WRITE, RDG::RESOURCE_USAGE_ATTACHMENT_COLOR_READ_WRITE));9424static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_ATTACHMENT_DEPTH_STENCIL_READ_WRITE, RDG::RESOURCE_USAGE_ATTACHMENT_DEPTH_STENCIL_READ_WRITE));9425static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_GENERAL, RDG::RESOURCE_USAGE_GENERAL));9426static_assert(ENUM_MEMBERS_EQUAL(RD::CALLBACK_RESOURCE_USAGE_MAX, RDG::RESOURCE_USAGE_MAX));942794289429