Godot Engine – Multi-platform 2D and 3D game engine
Metal,XR: Fix extension texture creation and API usage
Stuart Carnied9d68bfe7b0e
diff --git a/drivers/metal/metal3_objects.cpp b/drivers/metal/metal3_objects.cppindex 5816dfff29d..f88299bfaf7 100644--- a/drivers/metal/metal3_objects.cpp+++ b/drivers/metal/metal3_objects.cpp@@ -60,7 +60,7 @@using namespace MTL3;MDCommandBuffer::MDCommandBuffer(MTL::CommandQueue *p_queue, ::RenderingDeviceDriverMetal *p_device_driver) :- _scratch(p_queue->device()), queue(p_queue) {+ _scratch(p_device_driver->get_allocator()), queue(p_queue) {device_driver = p_device_driver;type = MDCommandBufferStateType::None;use_barriers = device_driver->use_barriers;@@ -307,8 +307,8 @@ MTL::BlitCommandEncoder *MDCommandBuffer::_ensure_blit_encoder() {}void MDCommandBuffer::resolve_texture(RDD::TextureID p_src_texture, RDD::TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, RDD::TextureID p_dst_texture, RDD::TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap) {- MTL::Texture *src_tex = rid::get<MTL::Texture>(p_src_texture);- MTL::Texture *dst_tex = rid::get<MTL::Texture>(p_dst_texture);+ MTL::Texture *src_tex = rid::get<RDM::TextureInfo>(p_src_texture)->texture.get();+ MTL::Texture *dst_tex = rid::get<RDM::TextureInfo>(p_dst_texture)->texture.get();NS::SharedPtr<MTL::RenderPassDescriptor> mtlRPD = NS::TransferPtr(MTL::RenderPassDescriptor::alloc()->init());MTL::RenderPassColorAttachmentDescriptor *mtlColorAttDesc = mtlRPD->colorAttachments()->object(0);@@ -327,7 +327,7 @@ void MDCommandBuffer::resolve_texture(RDD::TextureID p_src_texture, RDD::Texture}void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, const Color &p_color, const RDD::TextureSubresourceRange &p_subresources) {- MTL::Texture *src_tex = rid::get<MTL::Texture>(p_texture);+ MTL::Texture *src_tex = rid::get<RDM::TextureInfo>(p_texture)->texture.get();if (src_tex->parentTexture()) {// Clear via the parent texture rather than the view.@@ -407,11 +407,11 @@ void MDCommandBuffer::clear_buffer(RDD::BufferID p_buffer, uint64_t p_offset, uiMTL::BlitCommandEncoder *blit_enc = _ensure_blit_encoder();const RDM::BufferInfo *buffer = (const RDM::BufferInfo *)p_buffer.id;- blit_enc->fillBuffer(buffer->metal_buffer.get(), NS::Range(p_offset, p_size), 0);+ blit_enc->fillBuffer(buffer->buffer.get(), NS::Range(p_offset, p_size), 0);}void MDCommandBuffer::clear_depth_stencil_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const RDD::TextureSubresourceRange &p_subresources) {- MTL::Texture *src_tex = rid::get<MTL::Texture>(p_texture);+ MTL::Texture *src_tex = rid::get<RDM::TextureInfo>(p_texture)->texture.get();if (src_tex->parentTexture()) {// Clear via the parent texture rather than the view.@@ -536,14 +536,14 @@ void MDCommandBuffer::copy_buffer(RDD::BufferID p_src_buffer, RDD::BufferID p_dsfor (uint32_t i = 0; i < p_regions.size(); i++) {RDD::BufferCopyRegion region = p_regions[i];- enc->copyFromBuffer(src->metal_buffer.get(), region.src_offset,- dst->metal_buffer.get(), region.dst_offset, region.size);+ enc->copyFromBuffer(src->buffer.get(), region.src_offset,+ dst->buffer.get(), region.dst_offset, region.size);}}void MDCommandBuffer::copy_texture(RDD::TextureID p_src_texture, RDD::TextureID p_dst_texture, VectorView<RDD::TextureCopyRegion> p_regions) {- MTL::Texture *src = rid::get<MTL::Texture>(p_src_texture);- MTL::Texture *dst = rid::get<MTL::Texture>(p_dst_texture);+ MTL::Texture *src = rid::get<RDM::TextureInfo>(p_src_texture)->texture.get();+ MTL::Texture *dst = rid::get<RDM::TextureInfo>(p_dst_texture)->texture.get();MTL::BlitCommandEncoder *enc = _ensure_blit_encoder();PixelFormats &pf = device_driver->get_pixel_formats();@@ -635,7 +635,7 @@ void MDCommandBuffer::_copy_texture_buffer(CopySource p_source,RDD::BufferID p_buffer,VectorView<RDD::BufferTextureCopyRegion> p_regions) {const RDM::BufferInfo *buffer = (const RDM::BufferInfo *)p_buffer.id;- MTL::Texture *texture = rid::get<MTL::Texture>(p_texture);+ MTL::Texture *texture = rid::get<RDM::TextureInfo>(p_texture)->texture.get();MTL::BlitCommandEncoder *enc = _ensure_blit_encoder();@@ -686,11 +686,14 @@ void MDCommandBuffer::_copy_texture_buffer(CopySource p_source,}if (p_source == CopySource::Buffer) {- enc->copyFromBuffer(buffer->metal_buffer.get(), region.buffer_offset, bytesPerRow, bytesPerImg, txt_size,+ enc->copyFromBuffer(buffer->buffer.get(), region.buffer_offset,+ bytesPerRow, bytesPerImg, txt_size,texture, region.texture_subresource.layer, mip_level, txt_origin, blit_options);} else {- enc->copyFromTexture(texture, region.texture_subresource.layer, mip_level, txt_origin, txt_size,- buffer->metal_buffer.get(), region.buffer_offset, bytesPerRow, bytesPerImg, blit_options);+ enc->copyFromTexture(texture, region.texture_subresource.layer, mip_level,+ txt_origin, txt_size,+ buffer->buffer.get(), region.buffer_offset,+ bytesPerRow, bytesPerImg, blit_options);}}}@@ -1232,8 +1235,8 @@ void MDCommandBuffer::render_bind_vertex_buffers(uint32_t p_binding_count, constp_dynamic_offsets >>= 2;dynamic_offset = frame_idx * dyn_buf->size_bytes;}- if (render.vertex_buffers[i] != buf_info->metal_buffer.get()) {- render.vertex_buffers[i] = buf_info->metal_buffer.get();+ if (render.vertex_buffers[i] != buf_info->buffer.get()) {+ render.vertex_buffers[i] = buf_info->buffer.get();same = false;}@@ -1262,7 +1265,7 @@ void MDCommandBuffer::render_bind_index_buffer(RDD::BufferID p_buffer, RDD::Indeconst RenderingDeviceDriverMetal::BufferInfo *buffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_buffer.id;- render.index_buffer = buffer->metal_buffer.get();+ render.index_buffer = buffer->buffer.get();render.index_type = p_format == RDD::IndexBufferFormat::INDEX_BUFFER_FORMAT_UINT16 ? MTL::IndexTypeUInt16 : MTL::IndexTypeUInt32;render.index_offset = p_offset;}@@ -1302,7 +1305,7 @@ void MDCommandBuffer::render_draw_indexed_indirect(RDD::BufferID p_indirect_buffNS::UInteger indirect_offset = p_offset;for (uint32_t i = 0; i < p_draw_count; i++) {- enc->drawIndexedPrimitives(render.pipeline->raster_state.render_primitive, render.index_type, render.index_buffer, 0, indirect_buffer->metal_buffer.get(), indirect_offset);+ enc->drawIndexedPrimitives(render.pipeline->raster_state.render_primitive, render.index_type, render.index_buffer, 0, indirect_buffer->buffer.get(), indirect_offset);indirect_offset += p_stride;}}@@ -1323,7 +1326,7 @@ void MDCommandBuffer::render_draw_indirect(RDD::BufferID p_indirect_buffer, uintNS::UInteger indirect_offset = p_offset;for (uint32_t i = 0; i < p_draw_count; i++) {- enc->drawPrimitives(render.pipeline->raster_state.render_primitive, indirect_buffer->metal_buffer.get(), indirect_offset);+ enc->drawPrimitives(render.pipeline->raster_state.render_primitive, indirect_buffer->buffer.get(), indirect_offset);indirect_offset += p_stride;}}@@ -1509,7 +1512,7 @@ void MDCommandBuffer::compute_dispatch_indirect(RDD::BufferID p_indirect_buffer,const RenderingDeviceDriverMetal::BufferInfo *indirectBuffer = (const RenderingDeviceDriverMetal::BufferInfo *)p_indirect_buffer.id;MTL::ComputeCommandEncoder *enc = compute.encoder.get();- enc->dispatchThreadgroups(indirectBuffer->metal_buffer.get(), p_offset, compute.pipeline->compute_state.local);+ enc->dispatchThreadgroups(indirectBuffer->buffer.get(), p_offset, compute.pipeline->compute_state.local);}void MDCommandBuffer::reset() {@@ -1652,15 +1655,15 @@ void MDCommandBuffer::_bind_uniforms_argument_buffers(MDUniformSet *p_set, MDShauint32_t frame_idx = (p_dynamic_offsets >> shift) & 0xf;const MetalBufferDynamicInfo *buf_info = (const MetalBufferDynamicInfo *)uniform.ids[0].id;- uint64_t gpu_address = buf_info->metal_buffer.get()->gpuAddress() + frame_idx * buf_info->size_bytes;+ uint64_t gpu_address = buf_info->buffer.get()->gpuAddress() + frame_idx * buf_info->size_bytes;*(uint64_t *)(ptr + idx.buffer) = gpu_address;}enc->setVertexBuffer(alloc.buffer, alloc.offset, p_set_index);enc->setFragmentBuffer(alloc.buffer, alloc.offset, p_set_index);} else {- enc->setVertexBuffer(p_set->arg_buffer.get(), 0, p_set_index);- enc->setFragmentBuffer(p_set->arg_buffer.get(), 0, p_set_index);+ enc->setVertexBuffer(p_set->arg_buffer.buffer.get(), 0, p_set_index);+ enc->setFragmentBuffer(p_set->arg_buffer.buffer.get(), 0, p_set_index);}}@@ -1701,7 +1704,7 @@ void MDCommandBuffer::_bind_uniforms_direct(MDUniformSet *p_set, MDShader *p_shaMTL::SamplerState **samplers = ALLOCA_ARRAY(MTL::SamplerState *, count);for (uint32_t j = 0; j < count; j += 1) {samplers[j] = rid::get<MTL::SamplerState>(uniform.ids[j * 2 + 0]);- textures[j] = rid::get<MTL::Texture>(uniform.ids[j * 2 + 1]);+ textures[j] = rid::get<RDM::TextureInfo>(uniform.ids[j * 2 + 1])->texture.get();}NS::Range sampler_range = { indexes.sampler, count };NS::Range texture_range = { indexes.texture, count };@@ -1712,7 +1715,7 @@ void MDCommandBuffer::_bind_uniforms_direct(MDUniformSet *p_set, MDShader *p_shasize_t count = uniform.ids.size();MTL::Texture **objects = ALLOCA_ARRAY(MTL::Texture *, count);for (size_t j = 0; j < count; j += 1) {- objects[j] = rid::get<MTL::Texture>(uniform.ids[j]);+ objects[j] = rid::get<RDM::TextureInfo>(uniform.ids[j])->texture.get();}NS::Range texture_range = { indexes.texture, count };p_enc.set(objects, texture_range);@@ -1721,7 +1724,7 @@ void MDCommandBuffer::_bind_uniforms_direct(MDUniformSet *p_set, MDShader *p_shasize_t count = uniform.ids.size();MTL::Texture **objects = ALLOCA_ARRAY(MTL::Texture *, count);for (size_t j = 0; j < count; j += 1) {- objects[j] = rid::get<MTL::Texture>(uniform.ids[j]);+ objects[j] = rid::get<RDM::TextureInfo>(uniform.ids[j])->texture.get();}NS::Range texture_range = { indexes.texture, count };p_enc.set(objects, texture_range);@@ -1752,18 +1755,18 @@ void MDCommandBuffer::_bind_uniforms_direct(MDUniformSet *p_set, MDShader *p_shacase RDD::UNIFORM_TYPE_UNIFORM_BUFFER:case RDD::UNIFORM_TYPE_STORAGE_BUFFER: {const RDM::BufferInfo *buf_info = (const RDM::BufferInfo *)uniform.ids[0].id;- p_enc.set(buf_info->metal_buffer.get(), 0, indexes.buffer);+ p_enc.set(buf_info->buffer.get(), 0, indexes.buffer);} break;case RDD::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC:case RDD::UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {const MetalBufferDynamicInfo *buf_info = (const MetalBufferDynamicInfo *)uniform.ids[0].id;- p_enc.set(buf_info->metal_buffer.get(), frame_idx * buf_info->size_bytes, indexes.buffer);+ p_enc.set(buf_info->buffer.get(), frame_idx * buf_info->size_bytes, indexes.buffer);} break;case RDD::UNIFORM_TYPE_INPUT_ATTACHMENT: {size_t count = uniform.ids.size();MTL::Texture **objects = ALLOCA_ARRAY(MTL::Texture *, count);for (size_t j = 0; j < count; j += 1) {- objects[j] = rid::get<MTL::Texture>(uniform.ids[j]);+ objects[j] = rid::get<RDM::TextureInfo>(uniform.ids[j])->texture.get();}NS::Range texture_range = { indexes.texture, count };p_enc.set(objects, texture_range);@@ -1808,13 +1811,13 @@ void MDCommandBuffer::_bind_uniforms_argument_buffers_compute(MDUniformSet *p_seuint32_t frame_idx = (p_dynamic_offsets >> shift) & 0xf;const MetalBufferDynamicInfo *buf_info = (const MetalBufferDynamicInfo *)uniform.ids[0].id;- uint64_t gpu_address = buf_info->metal_buffer.get()->gpuAddress() + frame_idx * buf_info->size_bytes;+ uint64_t gpu_address = buf_info->buffer.get()->gpuAddress() + frame_idx * buf_info->size_bytes;*(uint64_t *)(ptr + idx.buffer) = gpu_address;}enc->setBuffer(alloc.buffer, alloc.offset, p_set_index);} else {- enc->setBuffer(p_set->arg_buffer.get(), 0, p_set_index);+ enc->setBuffer(p_set->arg_buffer.buffer.get(), 0, p_set_index);}}diff --git a/drivers/metal/metal_allocator.cpp b/drivers/metal/metal_allocator.cppnew file mode 100644index 00000000000..2df6de8fc18--- /dev/null+++ b/drivers/metal/metal_allocator.cpp@@ -0,0 +1,75 @@+/**************************************************************************/+/* metal_allocator.cpp */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* Permission is hereby granted, free of charge, to any person obtaining */+/* a copy of this software and associated documentation files (the */+/* "Software"), to deal in the Software without restriction, including */+/* without limitation the rights to use, copy, modify, merge, publish, */+/* distribute, sublicense, and/or sell copies of the Software, and to */+/* permit persons to whom the Software is furnished to do so, subject to */+/* the following conditions: */+/* */+/* The above copyright notice and this permission notice shall be */+/* included in all copies or substantial portions of the Software. */+/* */+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */+/**************************************************************************/++#include "drivers/metal/metal_allocator.h"++#pragma mark - MetalAllocator++MetalAllocator *MetalAllocator::create(MTL::Device *p_device, bool p_use_heaps) {+ return memnew(MetalDeviceAllocator(p_device));+}++#pragma mark - MetalDeviceAllocator++MetalBuffer MetalDeviceAllocator::new_buffer(NS::UInteger p_length, MTL::ResourceOptions p_options) {+ MetalBuffer result;+ result.buffer = NS::TransferPtr(device->newBuffer(p_length, p_options));+ return result;+}++MetalTexture MetalDeviceAllocator::new_texture(const MTL::TextureDescriptor *p_desc) {+ MetalTexture result;+ result.texture = NS::TransferPtr(device->newTexture(p_desc));+ return result;+}++void MetalDeviceAllocator::free_buffer(MetalBuffer &p_buffer) {+ DEV_ASSERT(!p_buffer.allocation.is_valid());+ p_buffer.buffer.reset();+}++void MetalDeviceAllocator::free_texture(MetalTexture &p_texture) {+ DEV_ASSERT(!p_texture.allocation.is_valid());+ p_texture.texture.reset();+}++uint64_t MetalDeviceAllocator::get_heaps(LocalVector<MTL::Heap *> &r_heaps) {+ return 0;+}++uint64_t MetalDeviceAllocator::get_heap_generation() const {+ return 0;+}++#ifdef DEBUG_ENABLED+void MetalDeviceAllocator::get_stats(MetalAllocatorStats &r_stats) {+ r_stats = MetalAllocatorStats();+}+#endifdiff --git a/drivers/metal/metal_allocator.h b/drivers/metal/metal_allocator.hnew file mode 100644index 00000000000..952b599f33a--- /dev/null+++ b/drivers/metal/metal_allocator.h@@ -0,0 +1,125 @@+/**************************************************************************/+/* metal_allocator.h */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* Permission is hereby granted, free of charge, to any person obtaining */+/* a copy of this software and associated documentation files (the */+/* "Software"), to deal in the Software without restriction, including */+/* without limitation the rights to use, copy, modify, merge, publish, */+/* distribute, sublicense, and/or sell copies of the Software, and to */+/* permit persons to whom the Software is furnished to do so, subject to */+/* the following conditions: */+/* */+/* The above copyright notice and this permission notice shall be */+/* included in all copies or substantial portions of the Software. */+/* */+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */+/**************************************************************************/++#pragma once++#include "core/templates/local_vector.h"++#include <Metal/Metal.hpp>++/// Opaque allocation handle. POOL entries reference a pool block plus the+/// OffsetAllocator range (in 256-byte units); DEDICATED entries own a+/// single-resource placement heap. INVALID means there is nothing to return+/// to the allocator (passthrough allocations, committed resources, texture+/// views, external imports).+struct MetalAllocation {+ enum class Kind : uint8_t {+ INVALID,+ POOL,+ DEDICATED,+ };++ Kind kind = Kind::INVALID;++ _FORCE_INLINE_ bool is_valid() const { return kind != Kind::INVALID; }+};++struct MetalBuffer {+ NS::SharedPtr<MTL::Buffer> buffer;+ MetalAllocation allocation;+};++struct MetalTexture {+ NS::SharedPtr<MTL::Texture> texture;+ MetalAllocation allocation;+};++#ifdef DEBUG_ENABLED+struct MetalAllocatorStats {+ /// Live statistics for the associated pool.+ struct Pool {+ uint64_t reserved_bytes = 0;+ uint64_t used_bytes = 0;+ // The number of blocks.+ uint32_t block_count = 0;+ // Total number of allocations.+ uint32_t allocation_count = 0;+ // Total number of dedicated heaps.+ uint32_t dedicated_count = 0;+ // Total size of dedicated heaps.+ uint64_t dedicated_bytes = 0;+ };+ Pool pools[3];+};+#endif++/// Abstract allocation interface for the Metal driver. The driver holds a+/// single instance selected by sync mode.+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MetalAllocator {+public:+ static MetalAllocator *create(MTL::Device *p_device, bool p_use_heaps);+ virtual ~MetalAllocator() = default;++ virtual MetalBuffer new_buffer(NS::UInteger p_length, MTL::ResourceOptions p_options) = 0;+ virtual MetalTexture new_texture(const MTL::TextureDescriptor *p_desc) = 0;+ virtual void free_buffer(MetalBuffer &p_buffer) = 0;+ virtual void free_texture(MetalTexture &p_texture) = 0;++ /// Appends all live heaps to r_heaps and returns the generation the+ /// snapshot corresponds to. The generation increments whenever a heap is+ /// created or destroyed; callers cache their heap arrays against it.+ virtual uint64_t get_heaps(LocalVector<MTL::Heap *> &r_heaps) = 0;+ virtual uint64_t get_heap_generation() const = 0;++#ifdef DEBUG_ENABLED+ virtual void get_stats(MetalAllocatorStats &r_stats) = 0;+#endif+};++/// Passthrough: forwards to MTL::Device, returns empty allocation handles.+/// Used in hazard tracking mode. Behavior identical to the pre-allocator+/// driver.+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MetalDeviceAllocator final : public MetalAllocator {+ MTL::Device *device = nullptr;++public:+ explicit MetalDeviceAllocator(MTL::Device *p_device) :+ device(p_device) {}++ MetalBuffer new_buffer(NS::UInteger p_length, MTL::ResourceOptions p_options) override;+ MetalTexture new_texture(const MTL::TextureDescriptor *p_desc) override;+ void free_buffer(MetalBuffer &p_buffer) override;+ void free_texture(MetalTexture &p_texture) override;+ uint64_t get_heaps(LocalVector<MTL::Heap *> &r_heaps) override;+ uint64_t get_heap_generation() const override;+#ifdef DEBUG_ENABLED+ void get_stats(MetalAllocatorStats &r_stats) override;+#endif+};diff --git a/drivers/metal/metal_objects_shared.h b/drivers/metal/metal_objects_shared.hindex 44d8594c5da..28cf55721a9 100644--- a/drivers/metal/metal_objects_shared.h+++ b/drivers/metal/metal_objects_shared.h@@ -30,6 +30,7 @@#pragma once+#include "drivers/metal/metal_allocator.h"#include "drivers/metal/metal_device_properties.h"#include "drivers/metal/metal_utils.h"#include "drivers/metal/pixel_formats.h"@@ -97,6 +98,26 @@ struct ClearAttKey {}};+#pragma mark - Cached Buffer++struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDCachedBuffer {+ MTL::Buffer *buffer = nullptr;+ void *contents = nullptr;+ uint64_t gpu_address = 0;+ NS::UInteger length = 0;++ MDCachedBuffer() = default;++ explicit MDCachedBuffer(MTL::Buffer *p_buffer) :+ buffer(p_buffer),+ contents(p_buffer->contents()),+ length(p_buffer->length()) {+ if (__builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, *)) {+ gpu_address = p_buffer->gpuAddress();+ }+ }+};+#pragma mark - Ring Buffer/// A ring buffer backed by MTLBuffer instances for transient GPU allocations.@@ -118,7 +139,10 @@ public:};private:- MTL::Device *device = nullptr;+ MetalAllocator *allocator = nullptr;+ LocalVector<MetalBuffer> segments;+ LocalVector<MDCachedBuffer> cached_buffers;+ // Mirror of the raw `MTL::Buffer *` of each segment, for encoder residency.LocalVector<MTL::Buffer *> buffers;LocalVector<uint32_t> heads;uint32_t current_segment = 0;@@ -126,23 +150,26 @@ private:bool changed = false;_FORCE_INLINE_ uint32_t alloc_segment() {- MTL::Buffer *buffer = device->newBuffer(buffer_size, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);+ MetalBuffer segment = allocator->new_buffer(buffer_size, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);+ MTL::Buffer *buffer = segment.buffer.get();+ segments.push_back(segment);+ cached_buffers.push_back(MDCachedBuffer(buffer));buffers.push_back(buffer);heads.push_back(0);changed = true;- return buffers.size() - 1;+ return cached_buffers.size() - 1;}public:MDRingBuffer() = default;- MDRingBuffer(MTL::Device *p_device, uint32_t p_buffer_size = DEFAULT_BUFFER_SIZE) :- device(p_device), buffer_size(p_buffer_size) {}+ MDRingBuffer(MetalAllocator *p_allocator, uint32_t p_buffer_size = DEFAULT_BUFFER_SIZE) :+ allocator(p_allocator), buffer_size(p_buffer_size) {}~MDRingBuffer() {- for (MTL::Buffer *buffer : buffers) {- buffer->release();+ for (MetalBuffer &segment : segments) {+ allocator->free_buffer(segment);}}@@ -152,7 +179,7 @@ public:p_size = MAX(p_size, MIN_BLOCK_SIZE);p_size = (p_size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);- if (buffers.is_empty()) {+ if (cached_buffers.is_empty()) {alloc_segment();}@@ -161,7 +188,7 @@ public:if (aligned_head + p_size > buffer_size) {// Current segment exhausted, try to find one with space or allocate new.bool found = false;- for (uint32_t i = 0; i < buffers.size(); i++) {+ for (uint32_t i = 0; i < cached_buffers.size(); i++) {uint32_t ah = (heads[i] + ALIGNMENT - 1) & ~(ALIGNMENT - 1);if (ah + p_size <= buffer_size) {current_segment = i;@@ -177,14 +204,12 @@ public:}}- MTL::Buffer *buffer = buffers[current_segment];+ MDCachedBuffer &cb = cached_buffers[current_segment];Allocation alloc;- alloc.buffer = buffer;+ alloc.buffer = cb.buffer;alloc.offset = aligned_head;- alloc.ptr = static_cast<uint8_t *>(buffer->contents()) + aligned_head;- if (__builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, *)) {- alloc.gpu_address = buffer->gpuAddress() + aligned_head;- }+ alloc.ptr = static_cast<uint8_t *>(cb.contents) + aligned_head;+ alloc.gpu_address = cb.gpu_address + aligned_head;heads[current_segment] = aligned_head + p_size;return alloc;@@ -974,7 +999,7 @@ _FORCE_INLINE_ MTL::ResourceUsage resource_usage_for_stage(StageResourceUsage p_class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDUniformSet {public:- NS::SharedPtr<MTL::Buffer> arg_buffer;+ MetalBuffer arg_buffer;Vector<uint8_t> arg_buffer_data; // Stored for dynamic uniform sets.ResourceUsageMap usage_to_resources; // Used by Metal 3 for resource tracking.Vector<RDD::BoundUniform> uniforms;diff --git a/drivers/metal/rendering_device_driver_metal.cpp b/drivers/metal/rendering_device_driver_metal.cppindex ef5fd049341..aedd8b09155 100644--- a/drivers/metal/rendering_device_driver_metal.cpp+++ b/drivers/metal/rendering_device_driver_metal.cpp@@ -132,12 +132,13 @@ RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitFielbreak;}- MTL::Buffer *obj = device->newBuffer(p_size, options);- ERR_FAIL_NULL_V_MSG(obj, BufferID(), "Can't create buffer of size: " + itos(p_size));+ MetalBuffer buffer = allocator->new_buffer(p_size, options);+ ERR_FAIL_NULL_V_MSG(buffer.buffer.get(), BufferID(), "Can't create buffer of size: " + itos(p_size));BufferInfo *buf_info;if (p_usage.has_flag(BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT)) {- MetalBufferDynamicInfo *dyn_buffer = memnew(MetalBufferDynamicInfo);+ static_assert(sizeof(MetalBufferDynamicInfo) <= sizeof(VersatileResource));+ MetalBufferDynamicInfo *dyn_buffer = VersatileResource::allocate<MetalBufferDynamicInfo>(resources_allocator);buf_info = dyn_buffer;#ifdef DEBUG_ENABLEDdyn_buffer->last_frame_mapped = p_frames_drawn - 1ul;@@ -145,11 +146,11 @@ RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitFieldyn_buffer->set_frame_index(0u);dyn_buffer->size_bytes = round_up_to_alignment(original_size, 16u);} else {- buf_info = memnew(BufferInfo);+ buf_info = VersatileResource::allocate<BufferInfo>(resources_allocator);}- buf_info->metal_buffer = NS::TransferPtr(obj);+ *static_cast<MetalBuffer *>(buf_info) = buffer;- _track_resource(buf_info->metal_buffer.get());+ _track_resource(buf_info->buffer.get());return BufferID(buf_info);}@@ -162,24 +163,26 @@ bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, Datavoid RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {BufferInfo *buf_info = (BufferInfo *)p_buffer.id;- _untrack_resource(buf_info->metal_buffer.get());+ _untrack_resource(buf_info->buffer.get());++ allocator->free_buffer(*buf_info);if (buf_info->is_dynamic()) {- memdelete((MetalBufferDynamicInfo *)buf_info);+ VersatileResource::free(resources_allocator, (MetalBufferDynamicInfo *)buf_info);} else {- memdelete(buf_info);+ VersatileResource::free(resources_allocator, buf_info);}}uint64_t RenderingDeviceDriverMetal::buffer_get_allocation_size(BufferID p_buffer) {const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;- return buf_info->metal_buffer.get()->allocatedSize();+ return buf_info->buffer.get()->allocatedSize();}uint8_t *RenderingDeviceDriverMetal::buffer_map(BufferID p_buffer) {const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;- ERR_FAIL_COND_V_MSG(buf_info->metal_buffer.get()->storageMode() != MTL::StorageModeShared, nullptr, "Unable to map private buffers");- return (uint8_t *)buf_info->metal_buffer.get()->contents();+ ERR_FAIL_COND_V_MSG(buf_info->buffer.get()->storageMode() != MTL::StorageModeShared, nullptr, "Unable to map private buffers");+ return (uint8_t *)buf_info->buffer.get()->contents();}void RenderingDeviceDriverMetal::buffer_unmap(BufferID p_buffer) {@@ -193,7 +196,7 @@ uint8_t *RenderingDeviceDriverMetal::buffer_persistent_map_advance(BufferID p_buERR_FAIL_COND_V_MSG(buf_info->last_frame_mapped == p_frames_drawn, nullptr, "Buffers with BUFFER_USAGE_DYNAMIC_PERSISTENT_BIT must only be mapped once per frame. Otherwise there could be race conditions with the GPU. Amalgamate all data uploading into one map(), use an extra buffer or remove the bit.");buf_info->last_frame_mapped = p_frames_drawn;#endif- return (uint8_t *)buf_info->metal_buffer.get()->contents() + buf_info->next_frame_index(_frame_count) * buf_info->size_bytes;+ return (uint8_t *)buf_info->buffer.get()->contents() + buf_info->next_frame_index(_frame_count) * buf_info->size_bytes;}uint64_t RenderingDeviceDriverMetal::buffer_get_dynamic_offsets(Span<BufferID> p_buffers) {@@ -216,7 +219,7 @@ uint64_t RenderingDeviceDriverMetal::buffer_get_dynamic_offsets(Span<BufferID> puint64_t RenderingDeviceDriverMetal::buffer_get_device_address(BufferID p_buffer) {if (__builtin_available(iOS 16.0, macOS 13.0, *)) {const BufferInfo *buf_info = (const BufferInfo *)p_buffer.id;- return buf_info->metal_buffer.get()->gpuAddress();+ return buf_info->buffer.get()->gpuAddress();} else {#if DEV_ENABLEDWARN_PRINT_ONCE("buffer_get_device_address is not supported on this OS version.");@@ -405,7 +408,7 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p// Allocate memory.- MTL::Texture *obj = nullptr;+ TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);if (is_linear) {// Linear textures are restricted to 2D textures, a single mipmap level and a single array layer.MTL::PixelFormat pixel_format = desc->pixelFormat();@@ -415,42 +418,65 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &psize_t bytes_per_layer = formats.getBytesPerLayer(pixel_format, bytes_per_row, p_format.height);size_t byte_count = bytes_per_layer * p_format.depth * p_format.array_layers;- MTL::Buffer *buf = device->newBuffer(byte_count, options);- obj = buf->newTexture(desc.get(), 0, bytes_per_row);- buf->release();-- _track_resource(buf);+ tex_info->linear_backing = allocator->new_buffer(byte_count, options);+ if (tex_info->linear_backing.buffer) {+ tex_info->texture = NS::TransferPtr(tex_info->linear_backing.buffer->newTexture(desc.get(), 0, bytes_per_row));+ }} else {- obj = device->newTexture(desc.get());+ *static_cast<MetalTexture *>(tex_info) = allocator->new_texture(desc.get());+ }+ if (!tex_info->texture) {+ allocator->free_buffer(tex_info->linear_backing);+ VersatileResource::free(resources_allocator, tex_info);+ ERR_FAIL_V_MSG(TextureID(), "Unable to create texture.");}- ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create texture.");- _track_resource(obj);+ // Track after the error path, so a failed create leaves nothing in the residency list.+ if (tex_info->linear_backing.buffer) {+ _track_resource(tex_info->linear_backing.buffer.get());+ }+ _track_resource(tex_info->texture.get());- return TextureID(reinterpret_cast<uint64_t>(obj));+ return TextureID(tex_info);}RDD::TextureID RenderingDeviceDriverMetal::texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) {MTL::Texture *res = reinterpret_cast<MTL::Texture *>(p_native_texture);+ TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);++ id native_obj = (id)(void *)p_native_texture;+ if (class_conforms_to_protocol_recursive(object_getClass(native_obj), objc_getProtocol("MTLRasterizationRateMap"))) {+ // A rate map is not a texture. Do not create a view, track residency, or set a label.+ tex_info->rasterization_rate_map = true;+ tex_info->texture = NS::RetainPtr(reinterpret_cast<MTL::Texture *>(p_native_texture));+ return TextureID(tex_info);+ }+// If the requested format is different, we need to create a view.MTL::PixelFormat format = (MTL::PixelFormat)pixel_formats->getMTLPixelFormat(p_format);if (res->pixelFormat() != format) {MTL::TextureSwizzleChannels swizzle = MTL::TextureSwizzleChannels::Default();- // newTextureView returns retain count of 1.- res = res->newTextureView(format, res->textureType(), NS::Range::Make(0, res->mipmapLevelCount()), NS::Range::Make(0, p_array_layers), swizzle);- ERR_FAIL_NULL_V_MSG(res, TextureID(), "Unable to create texture view.");+ MTL::Texture *view = res->newTextureView(format, res->textureType(), NS::Range::Make(0, res->mipmapLevelCount()), NS::Range::Make(0, p_array_layers), swizzle);+ if (view == nullptr) {+ VersatileResource::free(resources_allocator, tex_info);+ ERR_FAIL_V_MSG(TextureID(), "Unable to create texture view.");+ }+ tex_info->texture = NS::TransferPtr(view);} else {- res->retain();+ tex_info->texture = NS::RetainPtr(res);}- _track_resource(res);+ _track_resource(tex_info->texture.get());- return TextureID(reinterpret_cast<uint64_t>(res));+ return TextureID(tex_info);}RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_original_texture, const TextureView &p_view) {- MTL::Texture *src_texture = reinterpret_cast<MTL::Texture *>(p_original_texture.id);+ TextureInfo *src_info = (TextureInfo *)p_original_texture.id;+ ERR_FAIL_COND_V_MSG(src_info->rasterization_rate_map, TextureID(), "Cannot create a shared texture from a rasterization rate map.");++ MTL::Texture *src_texture = src_info->texture.get();NS::UInteger slices = src_texture->arrayLength();if (src_texture->textureType() == MTL::TextureTypeCube) {@@ -486,11 +512,17 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_oriMTL::Texture *obj = src_texture->newTextureView(format, src_texture->textureType(), NS::Range::Make(0, src_texture->mipmapLevelCount()), NS::Range::Make(0, slices), swizzle);ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");_track_resource(obj);- return TextureID(reinterpret_cast<uint64_t>(obj));++ TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);+ tex_info->texture = NS::TransferPtr(obj);+ return TextureID(tex_info);}RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared_from_slice(TextureID p_original_texture, const TextureView &p_view, TextureSliceType p_slice_type, uint32_t p_layer, uint32_t p_layers, uint32_t p_mipmap, uint32_t p_mipmaps) {- MTL::Texture *src_texture = reinterpret_cast<MTL::Texture *>(p_original_texture.id);+ TextureInfo *src_info = (TextureInfo *)p_original_texture.id;+ ERR_FAIL_COND_V_MSG(src_info->rasterization_rate_map, TextureID(), "Cannot create a shared texture from a rasterization rate map.");++ MTL::Texture *src_texture = src_info->texture.get();static const MTL::TextureType VIEW_TYPES[] = {MTL::TextureType1D, // MTLTextureType1D@@ -541,25 +573,38 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared_from_slice(TextMTL::Texture *obj = src_texture->newTextureView(format, textureType, NS::Range::Make(p_mipmap, p_mipmaps), NS::Range::Make(p_layer, p_layers), swizzle);ERR_FAIL_NULL_V_MSG(obj, TextureID(), "Unable to create shared texture");_track_resource(obj);- return TextureID(reinterpret_cast<uint64_t>(obj));++ TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);+ tex_info->texture = NS::TransferPtr(obj);+ return TextureID(tex_info);}void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {- MTL::Texture *obj = reinterpret_cast<MTL::Texture *>(p_texture.id);- _untrack_resource(obj);- obj->release();+ TextureInfo *tex_info = (TextureInfo *)p_texture.id;+ if (!tex_info->rasterization_rate_map) {+ _untrack_resource(tex_info->texture.get());+ if (tex_info->linear_backing.buffer) {+ _untrack_resource(tex_info->linear_backing.buffer.get());+ }+ }+ allocator->free_texture(*tex_info);+ allocator->free_buffer(tex_info->linear_backing);+ VersatileResource::free(resources_allocator, tex_info);}uint64_t RenderingDeviceDriverMetal::texture_get_allocation_size(TextureID p_texture) {- // p_texture can contain a wrapped MTLRasterizationRateMap as returned by VisionOSXRInterface,- // which (unlike MTLTexture) lacks the allocatedSize method. sendMessageSafe will check that- // it responds to the selector before calling it- NS::Object *obj = reinterpret_cast<NS::Object *>(p_texture.id);- return NS::Object::sendMessageSafe<NS::UInteger>(obj, _MTL_PRIVATE_SEL(allocatedSize));+ TextureInfo *tex_info = (TextureInfo *)p_texture.id;+ if (tex_info->rasterization_rate_map) {+ return 0;+ }+ return tex_info->texture.get()->allocatedSize();}void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture, const TextureSubresource &p_subresource, TextureCopyableLayout *r_layout) {- MTL::Texture *obj = reinterpret_cast<MTL::Texture *>(p_texture.id);+ TextureInfo *tex_info = (TextureInfo *)p_texture.id;+ ERR_FAIL_COND_MSG(tex_info->rasterization_rate_map, "Cannot get copyable layout for rasterization rate map.");++ MTL::Texture *obj = tex_info->texture.get();PixelFormats &pf = *pixel_formats;DataFormat format = pf.getDataFormat(obj->pixelFormat());@@ -578,7 +623,10 @@ void RenderingDeviceDriverMetal::texture_get_copyable_layout(TextureID p_texture}Vector<uint8_t> RenderingDeviceDriverMetal::texture_get_data(TextureID p_texture, uint32_t p_layer) {- MTL::Texture *obj = reinterpret_cast<MTL::Texture *>(p_texture.id);+ TextureInfo *tex_info = (TextureInfo *)p_texture.id;+ ERR_FAIL_COND_V_MSG(tex_info->rasterization_rate_map, Vector<uint8_t>(), "Cannot get data for a rasterization rate map.");++ MTL::Texture *obj = tex_info->texture.get();ERR_FAIL_COND_V_MSG(obj->storageMode() != MTL::StorageModeShared, Vector<uint8_t>(), "Texture must be created with TEXTURE_USAGE_CPU_READ_BIT set.");MTL::Buffer *buf = obj->buffer();@@ -1036,30 +1084,21 @@ RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID pfor (uint32_t i = 0; i < p_attachments.size(); i += 1) {const MDAttachment &a = pass->attachments[i];- id native_attachment = (id)(void *)p_attachments[i].id;- Class cls = object_getClass(native_attachment);-- MTL::Texture *tex = nullptr;- bool attachment_is_rasterization_rate_map = false;- if (class_conforms_to_protocol_recursive(cls, objc_getProtocol("MTLRasterizationRateMap"))) {- rasterization_rate_map = reinterpret_cast<MTL::RasterizationRateMap *>(p_attachments[i].id);- attachment_is_rasterization_rate_map = true;- } else if (class_conforms_to_protocol_recursive(cls, objc_getProtocol("MTLTexture"))) {- tex = reinterpret_cast<MTL::Texture *>(p_attachments[i].id);- }- if (tex == nullptr && !attachment_is_rasterization_rate_map) {-#if DEV_ENABLED- WARN_PRINT("Invalid texture for attachment " + itos(i));-#endif+ TextureInfo *tex_info = (TextureInfo *)p_attachments[i].id;+ if (tex_info->rasterization_rate_map) {+ rasterization_rate_map = reinterpret_cast<MTL::RasterizationRateMap *>(tex_info->texture.get());+ textures.write[i] = nullptr;+ } else {+ textures.write[i] = tex_info->texture.get();}if (a.samples > 1) {+ MTL::Texture *tex = textures[i];if (tex != nullptr && tex->sampleCount() != a.samples) {#if DEV_ENABLEDWARN_PRINT("Mismatched sample count for attachment " + itos(i) + "; expected " + itos(a.samples) + ", got " + itos(tex->sampleCount()));#endif}}- textures.write[i] = tex;}MDFrameBuffer *fb = memnew(MDFrameBuffer(textures, Size2i(p_width, p_height)));@@ -1376,7 +1415,7 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bounuint32_t count = uniform.ids.size() / 2;for (uint32_t j = 0; j < count; j += 1) {MTL::SamplerState *sampler = reinterpret_cast<MTL::SamplerState *>(uniform.ids[j * 2 + 0].id);- MTL::Texture *texture = reinterpret_cast<MTL::Texture *>(uniform.ids[j * 2 + 1].id);+ MTL::Texture *texture = ((TextureInfo *)uniform.ids[j * 2 + 1].id)->texture.get();*(MTL::ResourceID *)(ptr + idx.texture + j) = texture->gpuResourceID();*(MTL::ResourceID *)(ptr + idx.sampler + j) = sampler->gpuResourceID();@@ -1386,7 +1425,7 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bouncase UNIFORM_TYPE_TEXTURE: {size_t count = uniform.ids.size();for (size_t j = 0; j < count; j += 1) {- MTL::Texture *texture = reinterpret_cast<MTL::Texture *>(uniform.ids[j].id);+ MTL::Texture *texture = ((TextureInfo *)uniform.ids[j].id)->texture.get();*(MTL::ResourceID *)(ptr + idx.texture + j) = texture->gpuResourceID();ADD_USAGE(texture, ui.active_stages, ui.usage);@@ -1395,7 +1434,7 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bouncase UNIFORM_TYPE_IMAGE: {size_t count = uniform.ids.size();for (size_t j = 0; j < count; j += 1) {- MTL::Texture *texture = reinterpret_cast<MTL::Texture *>(uniform.ids[j].id);+ MTL::Texture *texture = ((TextureInfo *)uniform.ids[j].id)->texture.get();*(MTL::ResourceID *)(ptr + idx.texture + j) = texture->gpuResourceID();ADD_USAGE(texture, ui.active_stages, ui.usage);@@ -1421,14 +1460,14 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bouncase UNIFORM_TYPE_STORAGE_BUFFER:case UNIFORM_TYPE_UNIFORM_BUFFER: {const BufferInfo *buffer = (const BufferInfo *)uniform.ids[0].id;- *(MTLGPUAddress *)(ptr + idx.buffer) = buffer->metal_buffer.get()->gpuAddress();+ *(MTLGPUAddress *)(ptr + idx.buffer) = buffer->buffer.get()->gpuAddress();- ADD_USAGE(buffer->metal_buffer.get(), ui.active_stages, ui.usage);+ ADD_USAGE(buffer->buffer.get(), ui.active_stages, ui.usage);} break;case UNIFORM_TYPE_INPUT_ATTACHMENT: {size_t count = uniform.ids.size();for (size_t j = 0; j < count; j += 1) {- MTL::Texture *texture = reinterpret_cast<MTL::Texture *>(uniform.ids[j].id);+ MTL::Texture *texture = ((TextureInfo *)uniform.ids[j].id)->texture.get();*(MTL::ResourceID *)(ptr + idx.texture + j) = texture->gpuResourceID();ADD_USAGE(texture, ui.active_stages, ui.usage);@@ -1438,9 +1477,9 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bouncase UNIFORM_TYPE_STORAGE_BUFFER_DYNAMIC: {// Encode the base GPU address (frame 0); it will be updated at bind time.const MetalBufferDynamicInfo *buffer = (const MetalBufferDynamicInfo *)uniform.ids[0].id;- *(MTLGPUAddress *)(ptr + idx.buffer) = buffer->metal_buffer.get()->gpuAddress();+ *(MTLGPUAddress *)(ptr + idx.buffer) = buffer->buffer.get()->gpuAddress();- ADD_USAGE(buffer->metal_buffer.get(), ui.active_stages, ui.usage);+ ADD_USAGE(buffer->buffer.get(), ui.active_stages, ui.usage);} break;default: {DEV_ASSERT(false);@@ -1464,14 +1503,14 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Boun}if (!is_dynamic) {- set->arg_buffer = NS::TransferPtr(device->newBuffer(shader_set.buffer_size, base_hazard_tracking | MTL::ResourceStorageModePrivate));+ set->arg_buffer = allocator->new_buffer(shader_set.buffer_size, base_hazard_tracking | MTL::ResourceStorageModePrivate);#if DEV_ENABLEDchar label[64];snprintf(label, sizeof(label), "Uniform Set %u", p_set_index);- set->arg_buffer->setLabel(NS::String::string(label, NS::UTF8StringEncoding));+ set->arg_buffer.buffer->setLabel(NS::String::string(label, NS::UTF8StringEncoding));#endif- _track_resource(set->arg_buffer.get());- _copy_queue_copy_to_buffer(arg_buffer_data, set->arg_buffer.get());+ _track_resource(set->arg_buffer.buffer.get());+ _copy_queue_copy_to_buffer(arg_buffer_data, set->arg_buffer.buffer.get());} else {// Store the arg buffer data for dynamic uniform sets.// It will be copied and updated at bind time.@@ -1492,9 +1531,10 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Bounvoid RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;- if (obj->arg_buffer) {- _untrack_resource(obj->arg_buffer.get());+ if (obj->arg_buffer.buffer) {+ _untrack_resource(obj->arg_buffer.buffer.get());}+ allocator->free_buffer(obj->arg_buffer);memdelete(obj);}@@ -2439,15 +2479,17 @@ void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_switch (p_type) {case OBJECT_TYPE_TEXTURE: {- MTL::Texture *tex = reinterpret_cast<MTL::Texture *>(p_driver_id.id);- tex->setLabel(label);+ TextureInfo *tex_info = (TextureInfo *)p_driver_id.id;+ if (!tex_info->rasterization_rate_map) {+ tex_info->texture.get()->setLabel(label);+ }} break;case OBJECT_TYPE_SAMPLER: {// Can't set label after creation.} break;case OBJECT_TYPE_BUFFER: {const BufferInfo *buf_info = (const BufferInfo *)p_driver_id.id;- buf_info->metal_buffer.get()->setLabel(label);+ buf_info->buffer.get()->setLabel(label);} break;case OBJECT_TYPE_SHADER: {MDShader *shader = (MDShader *)(p_driver_id.id);@@ -2462,7 +2504,7 @@ void RenderingDeviceDriverMetal::set_object_name(ObjectType p_type, ID p_driver_} break;case OBJECT_TYPE_UNIFORM_SET: {MDUniformSet *set = (MDUniformSet *)(p_driver_id.id);- set->arg_buffer->setLabel(label);+ set->arg_buffer.buffer->setLabel(label);} break;case OBJECT_TYPE_PIPELINE: {// Can't set label after creation.@@ -2491,10 +2533,18 @@ uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource preturn 0;}case DRIVER_RESOURCE_TEXTURE: {- return p_driver_id.id;+ if (p_driver_id.id == 0) {+ return 0;+ }+ TextureInfo *tex_info = (TextureInfo *)p_driver_id.id;+ return (uint64_t)(uintptr_t)tex_info->texture.get();}case DRIVER_RESOURCE_TEXTURE_VIEW: {- return p_driver_id.id;+ if (p_driver_id.id == 0) {+ return 0;+ }+ TextureInfo *tex_info = (TextureInfo *)p_driver_id.id;+ return (uint64_t)(uintptr_t)tex_info->texture.get();}case DRIVER_RESOURCE_TEXTURE_DATA_FORMAT: {return 0;@@ -2506,7 +2556,11 @@ uint64_t RenderingDeviceDriverMetal::get_resource_native_handle(DriverResource preturn 0;}case DRIVER_RESOURCE_BUFFER: {- return p_driver_id.id;+ if (p_driver_id.id == 0) {+ return 0;+ }+ const BufferInfo *buf_info = (const BufferInfo *)p_driver_id.id;+ return (uint64_t)(uintptr_t)buf_info->buffer.get();}case DRIVER_RESOURCE_COMPUTE_PIPELINE: {MDComputePipeline *pipeline = (MDComputePipeline *)(p_driver_id.id);@@ -2533,7 +2587,7 @@ void RenderingDeviceDriverMetal::_copy_queue_copy_to_buffer(Span<uint8_t> p_src_memcpy(_copy_queue_buffer_ptr(), p_src_data.ptr(), p_src_data.size());copy_queue_rs.get()->addAllocation(p_dst_buffer);- blit_encoder->copyFromBuffer(copy_queue_buffer.get(), copy_queue_buffer_offset, p_dst_buffer, p_dst_offset, p_src_data.size());+ blit_encoder->copyFromBuffer(copy_queue_buffer.buffer.get(), copy_queue_buffer_offset, p_dst_buffer, p_dst_offset, p_src_data.size());_copy_queue_buffer_consume(p_src_data.size());}@@ -2543,7 +2597,7 @@ void RenderingDeviceDriverMetal::_copy_queue_flush() {return;}- copy_queue_rs.get()->addAllocation(copy_queue_buffer.get());+ copy_queue_rs.get()->addAllocation(copy_queue_buffer.buffer.get());copy_queue_rs.get()->commit();copy_queue_blit_encoder.get()->endEncoding();@@ -2563,8 +2617,8 @@ Error RenderingDeviceDriverMetal::_copy_queue_initialize() {ERR_FAIL_COND_V(!copy_queue, ERR_CANT_CREATE);// Reserve 64 KiB for copy commands. If the buffer fills, it will be flushed automatically.- copy_queue_buffer = NS::TransferPtr(device->newBuffer(64 * 1024, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked));- copy_queue_buffer.get()->setLabel(MTLSTR("Copy Command Scratch Buffer"));+ copy_queue_buffer = allocator->new_buffer(64 * 1024, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);+ copy_queue_buffer.buffer.get()->setLabel(MTLSTR("Copy Command Scratch Buffer"));if (__builtin_available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 1.0, *)) {if (device_properties->features.supports_residency_sets) {@@ -2820,6 +2874,27 @@ RenderingDeviceDriverMetal::~RenderingDeviceDriverMetal() {memdelete(shader_container_format);memdelete(pixel_formats);memdelete(device_properties);++ if (allocator != nullptr) {+ allocator->free_buffer(copy_queue_buffer);++#ifdef DEBUG_ENABLED+ if (OS::get_singleton()->is_stdout_verbose()) {+ MetalAllocatorStats stats;+ allocator->get_stats(stats);+ const char *pool_names[3] = { "private", "shared", "shared_wc" };+ for (uint32_t i = 0; i < 3; i++) {+ const MetalAllocatorStats::Pool &p = stats.pools[i];+ print_verbose(vformat("Metal allocator pool %s: %d blocks, %s reserved, %s used, %d live allocations, %d dedicated (%s).",+ pool_names[i], p.block_count, String::humanize_size(p.reserved_bytes), String::humanize_size(p.used_bytes),+ p.allocation_count, p.dedicated_count, String::humanize_size(p.dedicated_bytes)));+ }+ }+#endif++ memdelete(allocator);+ allocator = nullptr;+ }}#pragma mark - Initialization@@ -2915,6 +2990,8 @@ Error RenderingDeviceDriverMetal::_initialize(uint32_t p_device_index, uint32_tError err = _create_device();ERR_FAIL_COND_V(err, ERR_CANT_CREATE);+ allocator = MetalAllocator::create(device, false);+device_properties = memnew(MetalDeviceProperties(device));pixel_formats = memnew(PixelFormats(device, device_properties->features));device_profile = device_profile_from_properties(device_properties);diff --git a/drivers/metal/rendering_device_driver_metal.h b/drivers/metal/rendering_device_driver_metal.hindex 9d110a10193..49fe971a229 100644--- a/drivers/metal/rendering_device_driver_metal.h+++ b/drivers/metal/rendering_device_driver_metal.h@@ -30,6 +30,8 @@#pragma once+#include "core/templates/paged_allocator.h"+#include "drivers/metal/metal_allocator.h"#include "drivers/metal/metal_device_profile.h"#include "drivers/metal/metal_objects_shared.h"#include "servers/rendering/rendering_device_driver.h"@@ -71,6 +73,7 @@ protected:RenderingContextDriverMetal *context_driver = nullptr;RenderingContextDriver::Device context_device;MTL::Device *device = nullptr;+ MetalAllocator *allocator = nullptr;uint32_t _frame_count = 1;/// frame_index is a cyclic counter derived from the current frame number modulo frame_count,@@ -110,11 +113,11 @@ protected:// If this is not nullptr, there are pending copy operations.NS::SharedPtr<MTL::CommandBuffer> copy_queue_command_buffer;NS::SharedPtr<MTL::BlitCommandEncoder> copy_queue_blit_encoder;- NS::SharedPtr<MTL::Buffer> copy_queue_buffer;+ MetalBuffer copy_queue_buffer;NS::UInteger copy_queue_buffer_offset = 0;_FORCE_INLINE_ NS::UInteger _copy_queue_buffer_available() const {- return copy_queue_buffer.get()->length() - copy_queue_buffer_offset;+ return copy_queue_buffer.buffer.get()->length() - copy_queue_buffer_offset;}/// Marks p_size bytes as consumed from the copy queue buffer, aligning the new offset to 16 bytes.@@ -126,7 +129,7 @@ protected:/// Returns a pointer to the current position in the copy queue buffer._FORCE_INLINE_ void *_copy_queue_buffer_ptr() const {- return static_cast<uint8_t *>(copy_queue_buffer.get()->contents()) + copy_queue_buffer_offset;+ return static_cast<uint8_t *>(copy_queue_buffer.buffer.get()->contents()) + copy_queue_buffer_offset;}_FORCE_INLINE_ MTL::CommandBuffer *_copy_queue_command_buffer() {@@ -193,9 +196,7 @@ public:#pragma mark - Bufferspublic:- struct BufferInfo {- NS::SharedPtr<MTL::Buffer> metal_buffer;-+ struct BufferInfo : MetalBuffer {_FORCE_INLINE_ bool is_dynamic() const { return _frame_idx != UINT32_MAX; }_FORCE_INLINE_ uint32_t frame_index() const { return _frame_idx; }_FORCE_INLINE_ void set_frame_index(uint32_t p_frame_index) { _frame_idx = p_frame_index; }@@ -223,6 +224,14 @@ private:bool is_valid_linear(const TextureFormat &p_format) const;public:+ struct TextureInfo : MetalTexture {+ // Backing buffer for linear (buffer-backed) textures; empty otherwise.+ MetalBuffer linear_backing;+ // True if `texture` stores an MTLRasterizationRateMap in place of a texture.+ // If this flag is set, cast `texture` to MTL::RasterizationRateMap before use.+ bool rasterization_rate_map = false;+ };+virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;virtual TextureID texture_create_from_extension(uint64_t p_native_texture, TextureType p_type, DataFormat p_format, uint32_t p_array_layers, bool p_depth_stencil, uint32_t p_mipmaps) override final;virtual TextureID texture_create_shared(TextureID p_original_texture, const TextureView &p_view) override final;@@ -535,6 +544,7 @@ public:// Metal-specific.MTL::Device *get_device() const { return device; }+ MetalAllocator *get_allocator() const { return allocator; }PixelFormats &get_pixel_formats() const { return *pixel_formats; }MDResourceCache &get_resource_cache() const { return *resource_cache; }const MetalDeviceProperties &get_device_properties() const { return *device_properties; }@@ -550,7 +560,19 @@ public:_FORCE_INLINE_ uint32_t frame_index() const { return _frame_index; }_FORCE_INLINE_ uint32_t frames_drawn() const { return _frames_drawn; }+private:+ /*********************/+ /**** BOOKKEEPING ****/+ /*********************/++ using VersatileResource = VersatileResourceTemplate<+ BufferInfo,+ TextureInfo>;+ PagedAllocator<VersatileResource, true> resources_allocator;+/******************/++public:RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver);~RenderingDeviceDriverMetal();};diff --git a/modules/visionos_xr/visionos_xr_interface.h b/modules/visionos_xr/visionos_xr_interface.hindex ece0f1d88c2..bf0ff5e73a5 100644--- a/modules/visionos_xr/visionos_xr_interface.h+++ b/modules/visionos_xr/visionos_xr_interface.h@@ -135,7 +135,6 @@ private:RID current_color_texture_id;RD::Texture current_depth_texture;RID current_depth_texture_id;- RD::Texture current_rasterization_rate_map;RID current_rasterization_rate_map_id;// Cached render target size, set in pre_render() on the render threaddiff --git a/modules/visionos_xr/visionos_xr_interface.mm b/modules/visionos_xr/visionos_xr_interface.mmindex 0dca39f244d..75deeff4b99 100644--- a/modules/visionos_xr/visionos_xr_interface.mm+++ b/modules/visionos_xr/visionos_xr_interface.mm@@ -255,13 +255,13 @@ void VisionOSXRInterface::RenderThread::initialize() {void VisionOSXRInterface::RenderThread::uninitialize() {ERR_NOT_ON_RENDER_THREAD;if (current_color_texture_id != RID()) {- rendering_device->texture_owner.free(current_color_texture_id);+ rendering_device->free_rid(current_color_texture_id);}if (current_depth_texture_id != RID()) {- rendering_device->texture_owner.free(current_depth_texture_id);+ rendering_device->free_rid(current_depth_texture_id);}if (current_rasterization_rate_map_id != RID()) {- rendering_device->texture_owner.free(current_rasterization_rate_map_id);+ rendering_device->free_rid(current_rasterization_rate_map_id);}initialized = false;}@@ -724,7 +724,7 @@ RID VisionOSXRInterface::RenderThread::get_color_texture() {}if (current_color_texture_id != RID()) {- rendering_device->texture_owner.free(current_color_texture_id);+ rendering_device->free_rid(current_color_texture_id);}ERR_FAIL_NULL_V_MSG(current_drawable, RID(), "Current drawable is nil, pre_render() has probably not been called.");@@ -753,7 +753,7 @@ RID VisionOSXRInterface::RenderThread::get_depth_texture() {}if (current_depth_texture_id != RID()) {- rendering_device->texture_owner.free(current_depth_texture_id);+ rendering_device->free_rid(current_depth_texture_id);}ERR_FAIL_NULL_V_MSG(current_drawable, RID(), "Current drawable is nil, pre_render() has probably not been called.");@@ -782,7 +782,7 @@ RID VisionOSXRInterface::RenderThread::get_vrs_texture() {}if (current_rasterization_rate_map_id != RID()) {- rendering_device->texture_owner.free(current_rasterization_rate_map_id);+ rendering_device->free_rid(current_rasterization_rate_map_id);}ERR_FAIL_NULL_V_MSG(current_drawable, RID(), "Current drawable is nil, pre_render() has probably not been called.");@@ -791,23 +791,19 @@ RID VisionOSXRInterface::RenderThread::get_vrs_texture() {id<MTLRasterizationRateMap> rasterization_rate_map = cp_drawable_get_rasterization_rate_map(current_drawable, 0);MTLSize logical_size = rasterization_rate_map.screenSize;- RD::Texture texture;- texture.driver_id = RDD::TextureID((__bridge void *)rasterization_rate_map);- texture.usage_flags = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_VRS_ATTACHMENT_BIT;- texture.width = logical_size.width;- texture.height = logical_size.height;- texture.layers = rasterization_rate_map.layerCount;- // The following spoofed values are unused, but they are required- // to pass RenderingDevice::_render_pass_create() validation- texture.type = RDD::TEXTURE_TYPE_2D_ARRAY;- texture.format = RDD::DATA_FORMAT_R8_UINT;- texture.samples = RDD::TEXTURE_SAMPLES_1;- texture.depth = 1;- texture.mipmaps = 1;- ERR_FAIL_COND_V(!texture.driver_id, RID());-- current_rasterization_rate_map = texture;- current_rasterization_rate_map_id = rendering_device->texture_owner.make_rid(current_rasterization_rate_map);+ // The type, format and sample count are spoofed. They satisfy+ // RenderingDevice::_render_pass_create() validation and have no other use.+ current_rasterization_rate_map_id = rendering_device->texture_create_from_extension(+ RD::TEXTURE_TYPE_2D_ARRAY,+ RD::DATA_FORMAT_R8_UINT,+ RD::TEXTURE_SAMPLES_1,+ RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_VRS_ATTACHMENT_BIT,+ (uint64_t)(__bridge void *)rasterization_rate_map,+ logical_size.width,+ logical_size.height,+ 1,+ rasterization_rate_map.layerCount,+ 1);return current_rasterization_rate_map_id;}