Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

metal: fix various issues with Metal rendering; improve presentation

Stuart Carnie01795c253776
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt
index fafcf096985..09e779a251d 100644
--- a/COPYRIGHT.txt
+++ b/COPYRIGHT.txt
@@ -550,6 +550,11 @@ Comment: Multi-channel signed distance field generator
Copyright: 2014-2025, Viktor Chlumsky
License: Expat
+Files: thirdparty/offset_allocator/*
+Comment: OffsetAllocator
+Copyright: 2023, Sebastian Aaltonen
+License: Expat
+
Files: thirdparty/openxr/*
Comment: OpenXR Loader
Copyright: 2020-2025, The Khronos Group Inc.
diff --git a/drivers/apple/foundation_helpers.mm b/drivers/apple/foundation_helpers.mm
index df02ea2a1e2..97ddc23c959 100644
--- a/drivers/apple/foundation_helpers.mm
+++ b/drivers/apple/foundation_helpers.mm
@@ -35,6 +35,10 @@
#import <CoreFoundation/CFString.h>
+namespace NS {
+class String;
+}
+
namespace conv {
NSString *to_nsstring(const String &p_str) {
@@ -89,4 +93,9 @@ String to_string(NSString *p_str) {
return String::utf8(p_str.UTF8String);
}
+String to_string(NS::String *p_str) {
+ NSString *str = (__bridge NSString *)p_str;
+ return to_string(str);
+}
+
} //namespace conv
diff --git a/drivers/d3d12/rendering_device_driver_d3d12.cpp b/drivers/d3d12/rendering_device_driver_d3d12.cpp
index 663f55c2b5f..34ba6c08294 100644
--- a/drivers/d3d12/rendering_device_driver_d3d12.cpp
+++ b/drivers/d3d12/rendering_device_driver_d3d12.cpp
@@ -5953,7 +5953,9 @@ uint64_t RenderingDeviceDriverD3D12::api_trait_get(ApiTrait p_trait) {
return D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
case API_TRAIT_SECONDARY_VIEWPORT_SCISSOR:
return false;
- case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
+ case API_TRAIT_BUFFER_CLEARS_WITH_COPY_ENGINE:
+ return false;
+ case API_TRAIT_TEXTURE_CLEARS_WITH_COPY_ENGINE:
return false;
case API_TRAIT_USE_GENERAL_IN_COPY_QUEUES:
return true;
diff --git a/drivers/metal/SCsub b/drivers/metal/SCsub
index 8f85363072c..2508421e719 100644
--- a/drivers/metal/SCsub
+++ b/drivers/metal/SCsub
@@ -31,6 +31,11 @@ thirdparty_sources += [
"#thirdparty/metal-cpp/metal_cpp.cpp",
]
+# Include OffsetAllocator
+thirdparty_sources += [
+ "#thirdparty/offset_allocator/offsetAllocator.cpp",
+]
+
env_metal.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "/include"])
env_metal.Prepend(CPPPATH=[thirdparty_spirv_headers_dir + "include/spirv/unified1"])
diff --git a/drivers/metal/metal3_objects.cpp b/drivers/metal/metal3_objects.cpp
index f88299bfaf7..8bce8f30d16 100644
--- a/drivers/metal/metal3_objects.cpp
+++ b/drivers/metal/metal3_objects.cpp
@@ -63,35 +63,176 @@ MDCommandBuffer::MDCommandBuffer(MTL::CommandQueue *p_queue, ::RenderingDeviceDr
_scratch(p_device_driver->get_allocator()), queue(p_queue) {
device_driver = p_device_driver;
type = MDCommandBufferStateType::None;
- use_barriers = device_driver->use_barriers;
- if (use_barriers) {
- // Already validated availability if use_barriers is true.
- MTL::Device *device = p_queue->device();
- NS::SharedPtr<MTL::ResidencySetDescriptor> rs_desc = NS::TransferPtr(MTL::ResidencySetDescriptor::alloc()->init());
- rs_desc->setInitialCapacity(10);
- rs_desc->setLabel(MTLSTR("Command Residency Set"));
- NS::Error *error = nullptr;
- _frame_state.rs = NS::TransferPtr(device->newResidencySet(rs_desc.get(), &error));
- CRASH_COND_MSG(error != nullptr, vformat("Failed to create residency set: %s", String(error->localizedDescription()->utf8String())));
+ sync_mode = device_driver->sync_mode;
+ if (sync_mode != RDM::SyncMode::HazardTracking) {
+ _create_level_fences(p_device_driver->get_device());
+ }
+}
+
+void MDCommandBuffer::_encode_residency(MTL::RenderCommandEncoder *p_enc) {
+ if (sync_mode == RDM::SyncMode::HazardTracking) {
+ return; // ResourceTracker handles residency + hazards.
+ }
+ MetalAllocator *alloc = device_driver->get_allocator();
+ if (alloc->get_heap_generation() != _resident_heaps_generation) {
+ _resident_heaps.clear();
+ _resident_heaps_generation = alloc->get_heaps(_resident_heaps);
+ }
+ p_enc->useHeaps(_resident_heaps.ptr(), _resident_heaps.size(), MTL::RenderStageVertex | MTL::RenderStageFragment);
+ device_driver->encode_imported_resources(p_enc);
+}
+
+void MDCommandBuffer::_encode_residency(MTL::ComputeCommandEncoder *p_enc) {
+ if (sync_mode == RDM::SyncMode::HazardTracking) {
+ return;
+ }
+ MetalAllocator *alloc = device_driver->get_allocator();
+ if (alloc->get_heap_generation() != _resident_heaps_generation) {
+ _resident_heaps.clear();
+ _resident_heaps_generation = alloc->get_heaps(_resident_heaps);
+ }
+ p_enc->useHeaps(_resident_heaps.ptr(), _resident_heaps.size());
+ device_driver->encode_imported_resources(p_enc);
+}
+
+// Both render stages on both sides. Narrower masks (update after fragment, wait
+// before vertex) would allow more overlap, but the graph does not tell us which
+// stage of a pass reads or writes, so use the conservative mask.
+static constexpr MTL::RenderStages RENDER_FENCE_STAGES = MTL::RenderStageVertex | MTL::RenderStageFragment;
+
+void MDCommandBuffer::_fence_wait(MTL::RenderCommandEncoder *p_enc) {
+ MTL::Fence *fence = _fence_to_wait();
+ if (p_enc && fence) {
+ p_enc->waitForFence(fence, RENDER_FENCE_STAGES);
+ }
+}
+
+void MDCommandBuffer::_fence_wait(MTL::ComputeCommandEncoder *p_enc) {
+ MTL::Fence *fence = _fence_to_wait();
+ if (p_enc && fence) {
+ p_enc->waitForFence(fence);
+ }
+}
+
+void MDCommandBuffer::_fence_wait(MTL::BlitCommandEncoder *p_enc) {
+ MTL::Fence *fence = _fence_to_wait();
+ if (p_enc && fence) {
+ p_enc->waitForFence(fence);
+ }
+}
+
+void MDCommandBuffer::_fence_update(MTL::RenderCommandEncoder *p_enc) {
+ if (!p_enc) {
+ return;
+ }
+ if (MTL::Fence *fence = _fence_to_update()) {
+ p_enc->updateFence(fence, RENDER_FENCE_STAGES);
+ }
+}
+
+void MDCommandBuffer::_fence_update(MTL::ComputeCommandEncoder *p_enc) {
+ if (!p_enc) {
+ return;
+ }
+ if (MTL::Fence *fence = _fence_to_update()) {
+ p_enc->updateFence(fence);
+ }
+}
+
+void MDCommandBuffer::_fence_update(MTL::BlitCommandEncoder *p_enc) {
+ if (!p_enc) {
+ return;
+ }
+ if (MTL::Fence *fence = _fence_to_update()) {
+ p_enc->updateFence(fence);
}
}
void MDCommandBuffer::begin_label(const char *p_label_name, const Color &p_color) {
NS::SharedPtr<NS::String> s = NS::TransferPtr(NS::String::alloc()->init(p_label_name, NS::UTF8StringEncoding));
- command_buffer()->pushDebugGroup(s.get());
+ switch (type) {
+ case MDCommandBufferStateType::None:
+ command_buffer()->pushDebugGroup(s.get());
+ break;
+ case MDCommandBufferStateType::Render:
+ render.encoder->pushDebugGroup(s.get());
+ break;
+ case MDCommandBufferStateType::InlineRender:
+ inline_render.encoder->pushDebugGroup(s.get());
+ break;
+ case MDCommandBufferStateType::Compute:
+ compute.encoder->pushDebugGroup(s.get());
+ break;
+ case MDCommandBufferStateType::Blit:
+ blit.encoder->pushDebugGroup(s.get());
+ break;
+ }
+ label_stack.push_back({ type, false });
}
void MDCommandBuffer::end_label() {
- command_buffer()->popDebugGroup();
+ if (label_stack.is_empty()) {
+ return;
+ }
+ LabelStackEntry entry = label_stack[label_stack.size() - 1];
+ label_stack.remove_at(label_stack.size() - 1);
+ if (entry.stale) {
+ return;
+ }
+ switch (entry.type) {
+ case MDCommandBufferStateType::None:
+ command_buffer()->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::Render:
+ render.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::InlineRender:
+ inline_render.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::Compute:
+ compute.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::Blit:
+ blit.encoder->popDebugGroup();
+ break;
+ }
+}
+
+void MDCommandBuffer::_pop_active_encoder_labels() {
+ if (type == MDCommandBufferStateType::None) {
+ return;
+ }
+ for (int64_t i = (int64_t)label_stack.size() - 1; i >= 0; i--) {
+ LabelStackEntry &entry = label_stack[i];
+ if (entry.stale || entry.type != type) {
+ continue;
+ }
+ switch (type) {
+ case MDCommandBufferStateType::Render:
+ render.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::InlineRender:
+ inline_render.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::Compute:
+ compute.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::Blit:
+ blit.encoder->popDebugGroup();
+ break;
+ case MDCommandBufferStateType::None:
+ break;
+ }
+ entry.stale = true;
+ }
}
-void MDCommandBuffer::begin() {
- DEV_ASSERT(commandBuffer.get() == nullptr && !state_begin);
+void MDCommandBuffer::_begin() {
+ DEV_ASSERT(!commandBuffer && !state_begin);
state_begin = true;
- bzero(pending_after_stages, sizeof(pending_after_stages));
- bzero(pending_before_queue_stages, sizeof(pending_before_queue_stages));
binding_cache.clear();
_scratch.reset();
+ inline_render.reset();
release_resources();
}
@@ -99,12 +240,14 @@ MDCommandBuffer::Alloc MDCommandBuffer::allocate_arg_buffer(uint32_t p_size) {
return _scratch.allocate(p_size);
}
-void MDCommandBuffer::end() {
+void MDCommandBuffer::_end() {
switch (type) {
case MDCommandBufferStateType::None:
return;
case MDCommandBufferStateType::Render:
return render_end_pass();
+ case MDCommandBufferStateType::InlineRender:
+ return _end_inline_render();
case MDCommandBufferStateType::Compute:
return _end_compute_dispatch();
case MDCommandBufferStateType::Blit:
@@ -112,16 +255,8 @@ void MDCommandBuffer::end() {
}
}
-void MDCommandBuffer::commit() {
+void MDCommandBuffer::_commit() {
end();
- if (use_barriers) {
- if (_scratch.is_changed()) {
- Span<MTL::Buffer *const> bufs = _scratch.get_buffers();
- _frame_state.rs->addAllocations(reinterpret_cast<const MTL::Allocation *const *>(bufs.ptr()), bufs.size());
- _scratch.clear_changed();
- _frame_state.rs->commit();
- }
- }
commandBuffer->commit();
commandBuffer.reset();
state_begin = false;
@@ -129,97 +264,129 @@ void MDCommandBuffer::commit() {
MTL::CommandBuffer *MDCommandBuffer::command_buffer() {
DEV_ASSERT(state_begin);
- if (commandBuffer.get() == nullptr) {
+ if (!commandBuffer) {
commandBuffer = NS::RetainPtr(queue->commandBuffer());
- if (use_barriers) {
- commandBuffer->useResidencySet(_frame_state.rs.get());
- }
}
return commandBuffer.get();
}
-void MDCommandBuffer::_encode_barrier(MTL::CommandEncoder *p_enc) {
- DEV_ASSERT(p_enc);
-
- static const MTL::Stages empty_stages[STAGE_MAX] = { 0, 0, 0 };
- if (memcmp(&pending_before_queue_stages, empty_stages, sizeof(pending_before_queue_stages)) == 0) {
- return;
- }
-
- int stage = STAGE_MAX;
- // Determine encoder type by checking if it's the current active encoder.
- if (render.encoder.get() == p_enc && pending_after_stages[STAGE_RENDER] != 0) {
- stage = STAGE_RENDER;
- } else if (compute.encoder.get() == p_enc && pending_after_stages[STAGE_COMPUTE] != 0) {
- stage = STAGE_COMPUTE;
- } else if (blit.encoder.get() == p_enc && pending_after_stages[STAGE_BLIT] != 0) {
- stage = STAGE_BLIT;
- }
-
- if (stage == STAGE_MAX) {
- return;
- }
-
- p_enc->barrierAfterQueueStages(pending_after_stages[stage], pending_before_queue_stages[stage]);
- pending_before_queue_stages[stage] = 0;
- pending_after_stages[stage] = 0;
-}
-
void MDCommandBuffer::pipeline_barrier(BitField<RDD::PipelineStageBits> p_src_stages,
BitField<RDD::PipelineStageBits> p_dst_stages,
VectorView<RDD::MemoryAccessBarrier> p_memory_barriers,
VectorView<RDD::BufferBarrier> p_buffer_barriers,
VectorView<RDD::TextureBarrier> p_texture_barriers,
VectorView<RDD::AccelerationStructureBarrier> p_acceleration_structure_barriers) {
- MTL::Stages after_stages = convert_src_pipeline_stages_to_metal(p_src_stages);
- if (after_stages == 0) {
- return;
- }
+ // Nothing to do. Ordering between levels is carried by the level fences,
+ // which are driven by command_group_begin/command_group_end. The only live
+ // caller for Metal is the render graph's _group_barriers_for_render_commands;
+ // the transfer-worker calls in rendering_device.cpp are gated on
+ // API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS, which Metal returns false
+ // for, and RenderingDevice exposes no public barrier API.
+ DEV_ASSERT(!(render.encoder || compute.encoder || blit.encoder || inline_render.encoder));
+}
- MTL::Stages before_stages = convert_dst_pipeline_stages_to_metal(p_dst_stages);
- if (before_stages == 0) {
- return;
- }
+#pragma mark - Timestamp
- // Encode intra-encoder memory barrier if an encoder is active for matching stages.
- if (render.encoder.get() != nullptr) {
- MTL::RenderStages render_after = static_cast<MTL::RenderStages>(after_stages & (MTL::StageVertex | MTL::StageFragment));
- MTL::RenderStages render_before = static_cast<MTL::RenderStages>(before_stages & (MTL::StageVertex | MTL::StageFragment));
- if (render_after != 0 && render_before != 0) {
- render.encoder->memoryBarrier(MTL::BarrierScopeBuffers | MTL::BarrierScopeTextures, render_after, render_before);
- }
- } else if (compute.encoder.get() != nullptr) {
- if (after_stages & MTL::StageDispatch) {
- compute.encoder->memoryBarrier(MTL::BarrierScopeBuffers | MTL::BarrierScopeTextures);
+// metal-cpp does not expose MTLCounterDontSample or MTLCounterErrorValue.
+static constexpr NS::UInteger COUNTER_DONT_SAMPLE = NS::UIntegerMax;
+static constexpr uint64_t COUNTER_ERROR_VALUE = UINT64_MAX;
+
+QueryPool *QueryPool::create(MTL::Device *p_device, uint32_t p_count) {
+ MTL::CounterSet *counter_set = nullptr;
+ NS::Array *counter_sets = p_device->counterSets();
+ for (NS::UInteger i = 0; i < counter_sets->count(); i++) {
+ MTL::CounterSet *cs = counter_sets->object<MTL::CounterSet>(i);
+ if (cs->name()->isEqualToString(MTL::CommonCounterSetTimestamp)) {
+ counter_set = cs;
+ break;
}
}
- // Blit encoder has no memory barrier API.
+ if (counter_set == nullptr) {
+ return nullptr;
+ }
+
+ NS::SharedPtr<MTL::CounterSampleBufferDescriptor> desc = NS::TransferPtr(MTL::CounterSampleBufferDescriptor::alloc()->init());
+ desc->setCounterSet(counter_set);
+ // Shared storage makes the samples resolvable on the CPU, so no blit pass is
+ // needed to convert them.
+ desc->setStorageMode(MTL::StorageModeShared);
+ desc->setSampleCount(p_count);
+
+ NS::Error *error = nullptr;
+ NS::SharedPtr<MTL::CounterSampleBuffer> sample_buffer = NS::TransferPtr(p_device->newCounterSampleBuffer(desc.get(), &error));
+ ERR_FAIL_COND_V_MSG(error != nullptr, nullptr, vformat("Failed to create counter sample buffer: %s", String(error->localizedDescription()->utf8String())));
+
+ QueryPool *pool = memnew(QueryPool);
+ pool->sample_buffer = sample_buffer;
+ pool->dummy_buffer = NS::TransferPtr(p_device->newBuffer(1, MTL::ResourceStorageModePrivate | MTL::ResourceHazardTrackingModeUntracked));
+ pool->device = p_device;
+ p_device->sampleTimestamps(&pool->cpu_base, &pool->gpu_base);
+ pool->count = p_count;
+ return pool;
+}
- // Also cache for inter-pass barriers based on DESTINATION stages,
- // since barrierAfterQueueStages is called on the encoder that must wait.
- if (before_stages & (MTL::StageVertex | MTL::StageFragment)) {
- pending_after_stages[STAGE_RENDER] |= after_stages;
- pending_before_queue_stages[STAGE_RENDER] |= before_stages;
+double QueryPool::_resolve_timestamp_to_nano() {
+ if (timestamp_to_nano != 0.0) {
+ return timestamp_to_nano;
}
- if (before_stages & MTL::StageDispatch) {
- pending_after_stages[STAGE_COMPUTE] |= after_stages;
- pending_before_queue_stages[STAGE_COMPUTE] |= before_stages;
+ MTL::Timestamp cpu_now = 0;
+ MTL::Timestamp gpu_now = 0;
+ device->sampleTimestamps(&cpu_now, &gpu_now);
+ if (gpu_now <= gpu_base || cpu_now <= cpu_base) {
+ return 0.0; // Too soon to correlate; try again on the next readback.
}
+ timestamp_to_nano = (double)(cpu_now - cpu_base) / (double)(gpu_now - gpu_base);
+ return timestamp_to_nano;
+}
- if (before_stages & MTL::StageBlit) {
- pending_after_stages[STAGE_BLIT] |= after_stages;
- pending_before_queue_stages[STAGE_BLIT] |= before_stages;
+void QueryPool::get_results(uint32_t p_count, uint64_t *r_results) {
+ double to_nano = _resolve_timestamp_to_nano();
+ if (to_nano == 0.0) {
+ memset(r_results, 0, p_count * sizeof(uint64_t));
+ return;
}
+
+ NS::Data *data = sample_buffer->resolveCounterRange(NS::Range::Make(0, p_count));
+ ERR_FAIL_NULL(data);
+ const MTL::CounterResultTimestamp *src = (const MTL::CounterResultTimestamp *)data->bytes();
+ uint64_t last = 0;
+ for (uint32_t i = 0; i < p_count; i++) {
+ // A slot the GPU never wrote resolves to the error value; hold the previous
+ // reading so the profiler reports a zero length span rather than garbage.
+ last = src[i].timestamp == COUNTER_ERROR_VALUE ? last : uint64_t((double)src[i].timestamp * to_nano);
+ r_results[i] = last;
+ }
+}
+
+void MDCommandBuffer::timestamp_write(QueryPool *p_pool, uint32_t p_index) {
+ end();
+
+ NS::SharedPtr<MTL::BlitPassDescriptor> desc = NS::TransferPtr(MTL::BlitPassDescriptor::alloc()->init());
+ MTL::BlitPassSampleBufferAttachmentDescriptor *sba = desc->sampleBufferAttachments()->object(0);
+ sba->setSampleBuffer(p_pool->get_sample_buffer());
+ sba->setStartOfEncoderSampleIndex(p_index);
+ sba->setEndOfEncoderSampleIndex(COUNTER_DONT_SAMPLE);
+
+ // A self contained encoder: the state machine stays in the None state, so this
+ // must not go through _ensure_blit_encoder(), which cannot take a descriptor.
+ MTL::BlitCommandEncoder *enc = command_buffer()->blitCommandEncoder(desc.get());
+#ifdef DEV_ENABLED
+ enc->setLabel(NS::String::string(vformat("Timestamp %03d", p_index).utf8().get_data(), NS::UTF8StringEncoding));
+#endif
+ _fence_wait(enc);
+ // An encoder with no commands may be elided, which would drop the sample.
+ enc->fillBuffer(p_pool->get_dummy_buffer(), NS::Range::Make(0, 1), 0);
+ _fence_update(enc);
+ enc->endEncoding();
}
void MDCommandBuffer::bind_pipeline(RDD::PipelineID p_pipeline) {
MDPipeline *p = (MDPipeline *)(p_pipeline.id);
- // End current encoder if it is a compute encoder or blit encoder,
- // as they do not have a defined end boundary in the RDD like render.
- if (type == MDCommandBufferStateType::Compute) {
- _end_compute_dispatch();
+ // End the current encoder if the new pipeline requires a new encoder type.
+ if (type == MDCommandBufferStateType::InlineRender) {
+ _end_inline_render();
} else if (type == MDCommandBufferStateType::Blit) {
_end_blit();
}
@@ -228,7 +395,7 @@ void MDCommandBuffer::bind_pipeline(RDD::PipelineID p_pipeline) {
DEV_ASSERT(type == MDCommandBufferStateType::Render);
MDRenderPipeline *rp = (MDRenderPipeline *)p;
- if (render.encoder.get() == nullptr) {
+ if (!render.encoder) {
// This error would happen if the render pass failed.
ERR_FAIL_NULL_MSG(render.desc.get(), "Render pass descriptor is null.");
@@ -237,7 +404,8 @@ void MDCommandBuffer::bind_pipeline(RDD::PipelineID p_pipeline) {
render.desc->setDefaultRasterSampleCount(static_cast<NS::UInteger>(rp->sample_count));
render.encoder = NS::RetainPtr(command_buffer()->renderCommandEncoder(render.desc.get()));
- _encode_barrier(render.encoder.get());
+ _encode_residency(render.encoder.get());
+ _fence_wait(render.encoder.get());
}
if (render.pipeline != rp) {
@@ -260,8 +428,7 @@ void MDCommandBuffer::bind_pipeline(RDD::PipelineID p_pipeline) {
render.pipeline = rp;
}
} else if (p->type == MDPipelineType::Compute) {
- DEV_ASSERT(type == MDCommandBufferStateType::None);
- type = MDCommandBufferStateType::Compute;
+ DEV_ASSERT(type == MDCommandBufferStateType::Compute);
if (compute.pipeline != p) {
compute.dirty.set_flag(ComputeState::DIRTY_PIPELINE);
@@ -292,6 +459,9 @@ MTL::BlitCommandEncoder *MDCommandBuffer::_ensure_blit_encoder() {
case MDCommandBufferStateType::Render:
render_end_pass();
break;
+ case MDCommandBufferStateType::InlineRender:
+ _end_inline_render();
+ break;
case MDCommandBufferStateType::Compute:
_end_compute_dispatch();
break;
@@ -301,7 +471,7 @@ MTL::BlitCommandEncoder *MDCommandBuffer::_ensure_blit_encoder() {
type = MDCommandBufferStateType::Blit;
blit.encoder = NS::RetainPtr(command_buffer()->blitCommandEncoder());
- _encode_barrier(blit.encoder.get());
+ _fence_wait(blit.encoder.get());
return blit.encoder.get();
}
@@ -323,7 +493,7 @@ void MDCommandBuffer::resolve_texture(RDD::TextureID p_src_texture, RDD::Texture
mtlColorAttDesc->setResolveSlice(p_dst_layer);
MTL::RenderCommandEncoder *enc = get_new_render_encoder_with_descriptor(mtlRPD.get());
enc->setLabel(MTLSTR("Resolve Image"));
- enc->endEncoding();
+ _set_inline_render_encoder(enc);
}
void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, const Color &p_color, const RDD::TextureSubresourceRange &p_subresources) {
@@ -354,7 +524,7 @@ void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::Texture
uint32_t mipLvlCnt = p_subresources.mipmap_count;
uint32_t mipLvlEnd = mipLvlStart + mipLvlCnt;
- uint32_t levelCount = src_tex->mipmapLevelCount();
+ NS::UInteger levelCount = src_tex->mipmapLevelCount();
// Extract the cube or array layers (slices) that are to be updated.
bool is3D = src_tex->textureType() == MTL::TextureType3D;
@@ -364,7 +534,7 @@ void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::Texture
const MetalFeatures &features = device_driver->get_device_properties().features;
- // Iterate across mipmap levels and layers, and perform and empty render to clear each.
+ // Iterate across mipmap levels and layers, and perform an empty render to clear each.
for (uint32_t mipLvl = mipLvlStart; mipLvl < mipLvlEnd; mipLvl++) {
ERR_FAIL_INDEX_MSG(mipLvl, levelCount, "mip level out of range");
@@ -386,7 +556,12 @@ void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::Texture
desc->setRenderTargetArrayLength(layerCnt);
MTL::RenderCommandEncoder *enc = get_new_render_encoder_with_descriptor(desc.get());
enc->setLabel(MTLSTR("Clear Image"));
- enc->endEncoding();
+ if (mipLvl + 1 == mipLvlEnd) {
+ _set_inline_render_encoder(enc);
+ } else {
+ _fence_update(enc);
+ enc->endEncoding();
+ }
} else {
for (uint32_t layer = layerStart; layer < layerEnd; layer++) {
if (is3D) {
@@ -396,7 +571,12 @@ void MDCommandBuffer::clear_color_texture(RDD::TextureID p_texture, RDD::Texture
}
MTL::RenderCommandEncoder *enc = get_new_render_encoder_with_descriptor(desc.get());
enc->setLabel(MTLSTR("Clear Image"));
- enc->endEncoding();
+ if (mipLvl + 1 == mipLvlEnd && layer + 1 == layerEnd) {
+ _set_inline_render_encoder(enc);
+ } else {
+ _fence_update(enc);
+ enc->endEncoding();
+ }
}
}
}
@@ -501,7 +681,12 @@ void MDCommandBuffer::clear_depth_stencil_texture(RDD::TextureID p_texture, RDD:
desc->setRenderTargetArrayLength(layerCnt);
MTL::RenderCommandEncoder *enc = get_new_render_encoder_with_descriptor(desc.get());
enc->setLabel(MTLSTR("Clear Image"));
- enc->endEncoding();
+ if (mipLvl + 1 == mipLvlEnd) {
+ _set_inline_render_encoder(enc);
+ } else {
+ _fence_update(enc);
+ enc->endEncoding();
+ }
} else {
for (uint32_t layer = layerStart; layer < layerEnd; layer++) {
if (is3D) {
@@ -521,7 +706,12 @@ void MDCommandBuffer::clear_depth_stencil_texture(RDD::TextureID p_texture, RDD:
}
MTL::RenderCommandEncoder *enc = get_new_render_encoder_with_descriptor(desc.get());
enc->setLabel(MTLSTR("Clear Image"));
- enc->endEncoding();
+ if (mipLvl + 1 == mipLvlEnd && layer + 1 == layerEnd) {
+ _set_inline_render_encoder(enc);
+ } else {
+ _fence_update(enc);
+ enc->endEncoding();
+ }
}
}
}
@@ -564,9 +754,10 @@ void MDCommandBuffer::copy_texture(RDD::TextureID p_src_texture, RDD::TextureID
ERR_FAIL_MSG("not implemented: copy with intermediate buffer");
}
+ NS::SharedPtr<MTL::Texture> src_view;
if (src_fmt != dst_fmt) {
- // Map the source pixel format to the dst through a texture view on the source texture.
- src = src->newTextureView(dst_fmt);
+ src_view = NS::TransferPtr(src->newTextureView(dst_fmt));
+ src = src_view.get();
}
for (uint32_t i = 0; i < p_regions.size(); i++) {
@@ -705,6 +896,9 @@ MTL::RenderCommandEncoder *MDCommandBuffer::get_new_render_encoder_with_descript
case MDCommandBufferStateType::Render:
render_end_pass();
break;
+ case MDCommandBufferStateType::InlineRender:
+ _end_inline_render();
+ break;
case MDCommandBufferStateType::Compute:
_end_compute_dispatch();
break;
@@ -714,7 +908,8 @@ MTL::RenderCommandEncoder *MDCommandBuffer::get_new_render_encoder_with_descript
}
MTL::RenderCommandEncoder *enc = command_buffer()->renderCommandEncoder(p_desc);
- _encode_barrier(enc);
+ _encode_residency(enc);
+ _fence_wait(enc);
return enc;
}
@@ -792,12 +987,12 @@ void MDCommandBuffer::render_clear_attachments(VectorView<RDD::AttachmentClear>
const MDAttachment &mda = render.pass->attachments[attachment_index];
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_COLOR_BIT)) {
key.set_color_format(attachment_index, mda.format);
- clear_colors[attachment_index] = {
- attClear.value.color.r,
- attClear.value.color.g,
- attClear.value.color.b,
- attClear.value.color.a
- };
+
+ clear_colors[attachment_index] = simd_make_float4(
+ attClear.value.color.r,
+ attClear.value.color.g,
+ attClear.value.color.b,
+ attClear.value.color.a);
}
if (attClear.aspect.has_flag(RDD::TEXTURE_ASPECT_DEPTH_BIT)) {
@@ -810,12 +1005,7 @@ void MDCommandBuffer::render_clear_attachments(VectorView<RDD::AttachmentClear>
stencil_value = attClear.value.stencil;
}
}
- clear_colors[ClearAttKey::DEPTH_INDEX] = {
- depth_value,
- depth_value,
- depth_value,
- depth_value
- };
+ clear_colors[ClearAttKey::DEPTH_INDEX] = simd_make_float4(depth_value);
MTL::RenderCommandEncoder *enc = render.encoder.get();
@@ -903,7 +1093,7 @@ void MDCommandBuffer::_render_set_dirty_state() {
}
}
- if (!use_barriers) {
+ if (sync_mode == RDM::SyncMode::HazardTracking) {
render.resource_tracker.encode(render.encoder.get());
}
@@ -945,8 +1135,8 @@ void ResourceTracker::merge_from(const ::ResourceUsageMap &p_from) {
} else if (current_res > new_res) {
if (should_add_resource(new_res)) {
resources->insert(i, new_res);
+ i++;
}
- i++;
j++;
} else {
i++;
@@ -1062,7 +1252,7 @@ void MDCommandBuffer::_render_bind_uniform_sets() {
}
void MDCommandBuffer::render_begin_pass(RDD::RenderPassID p_render_pass, RDD::FramebufferID p_frameBuffer, RDD::CommandBufferType p_cmd_buffer_type, const Rect2i &p_rect, VectorView<RDD::RenderPassClearValue> p_clear_values) {
- DEV_ASSERT(command_buffer() != nullptr);
+ DEV_ASSERT(command_buffer());
end();
MDRenderPass *pass = (MDRenderPass *)(p_render_pass.id);
@@ -1070,7 +1260,7 @@ void MDCommandBuffer::render_begin_pass(RDD::RenderPassID p_render_pass, RDD::Fr
type = MDCommandBufferStateType::Render;
render.pass = pass;
- render.current_subpass = UINT32_MAX;
+ render.current_subpass = nullptr;
render.render_area = p_rect;
render.clear_values.resize(p_clear_values.size());
for (uint32_t i = 0; i < p_clear_values.size(); i++) {
@@ -1082,15 +1272,17 @@ void MDCommandBuffer::render_begin_pass(RDD::RenderPassID p_render_pass, RDD::Fr
}
void MDCommandBuffer::render_next_subpass() {
- DEV_ASSERT(command_buffer() != nullptr);
+ DEV_ASSERT(command_buffer());
- if (render.current_subpass == UINT32_MAX) {
- render.current_subpass = 0;
- } else {
+ MDSubpass *prev_subpass = render.current_subpass;
+ if (prev_subpass != nullptr) {
_end_render_pass();
- render.current_subpass++;
}
+ render.current_subpass = (prev_subpass == nullptr)
+ ? &render.pass->subpasses[0]
+ : prev_subpass + 1;
+
const MDFrameBuffer &fb = *render.frameBuffer;
const MDRenderPass &pass = *render.pass;
const MDSubpass &subpass = render.get_subpass();
@@ -1185,7 +1377,8 @@ void MDCommandBuffer::render_next_subpass() {
render.desc = desc;
} else {
render.encoder = NS::RetainPtr(command_buffer()->renderCommandEncoder(desc.get()));
- _encode_barrier(render.encoder.get());
+ _encode_residency(render.encoder.get());
+ _fence_wait(render.encoder.get());
if (!render.is_rendering_entire_area) {
_render_clear_render_area();
@@ -1243,7 +1436,7 @@ void MDCommandBuffer::render_bind_vertex_buffers(uint32_t p_binding_count, const
render.vertex_offsets[i] = dynamic_offset + p_offsets[p_binding_count - i - 1];
}
- if (render.encoder.get() != nullptr) {
+ if (render.encoder) {
uint32_t first = device_driver->get_metal_buffer_index_for_vertex_attribute_binding(p_binding_count - 1);
if (same) {
NS::UInteger *offset_ptr = render.vertex_offsets.ptr();
@@ -1338,6 +1531,8 @@ void MDCommandBuffer::render_draw_indirect_count(RDD::BufferID p_indirect_buffer
void MDCommandBuffer::render_end_pass() {
DEV_ASSERT(type == MDCommandBufferStateType::Render);
+ _pop_active_encoder_labels();
+ _fence_update(render.encoder.get());
render.end_encoding();
render.reset();
reset();
@@ -1349,7 +1544,7 @@ void MDCommandBuffer::RenderState::reset() {
pass = nullptr;
frameBuffer = nullptr;
pipeline = nullptr;
- current_subpass = UINT32_MAX;
+ current_subpass = nullptr;
render_area = {};
is_rendering_entire_area = false;
desc.reset();
@@ -1372,7 +1567,7 @@ void MDCommandBuffer::RenderState::reset() {
}
void MDCommandBuffer::RenderState::end_encoding() {
- if (encoder.get() == nullptr) {
+ if (!encoder) {
return;
}
@@ -1383,7 +1578,7 @@ void MDCommandBuffer::RenderState::end_encoding() {
#pragma mark - ComputeState
void MDCommandBuffer::ComputeState::end_encoding() {
- if (encoder.get() == nullptr) {
+ if (!encoder) {
return;
}
@@ -1393,10 +1588,36 @@ void MDCommandBuffer::ComputeState::end_encoding() {
#pragma mark - Compute
+void MDCommandBuffer::compute_begin_pass() {
+ ERR_FAIL_COND_MSG(type == MDCommandBufferStateType::Render, "Compute pass cannot begin while a render pass is active.");
+
+ if (type == MDCommandBufferStateType::InlineRender) {
+ _end_inline_render();
+ } else if (type == MDCommandBufferStateType::Blit) {
+ _end_blit();
+ }
+
+ type = MDCommandBufferStateType::Compute;
+ if (!compute.encoder) {
+ compute.encoder = NS::RetainPtr(command_buffer()->computeCommandEncoder(MTL::DispatchTypeConcurrent));
+ _encode_residency(compute.encoder.get());
+ _fence_wait(compute.encoder.get());
+ }
+}
+
+void MDCommandBuffer::compute_end_pass() {
+ if (type == MDCommandBufferStateType::Compute) {
+ _end_compute_dispatch();
+ }
+}
+
void MDCommandBuffer::_compute_set_dirty_state() {
if (compute.dirty.has_flag(ComputeState::DIRTY_PIPELINE)) {
- compute.encoder = NS::RetainPtr(command_buffer()->computeCommandEncoder(MTL::DispatchTypeConcurrent));
- _encode_barrier(compute.encoder.get());
+ if (!compute.encoder) {
+ compute.encoder = NS::RetainPtr(command_buffer()->computeCommandEncoder(MTL::DispatchTypeConcurrent));
+ _encode_residency(compute.encoder.get());
+ _fence_wait(compute.encoder.get());
+ }
compute.encoder->setComputePipelineState(compute.pipeline->state.get());
}
@@ -1408,7 +1629,7 @@ void MDCommandBuffer::_compute_set_dirty_state() {
}
}
- if (!use_barriers) {
+ if (sync_mode == RDM::SyncMode::HazardTracking) {
compute.resource_tracker.encode(compute.encoder.get());
}
@@ -1525,14 +1746,37 @@ void MDCommandBuffer::reset() {
void MDCommandBuffer::_end_compute_dispatch() {
DEV_ASSERT(type == MDCommandBufferStateType::Compute);
+ _pop_active_encoder_labels();
+ _fence_update(compute.encoder.get());
compute.end_encoding();
compute.reset();
reset();
}
+void MDCommandBuffer::_set_inline_render_encoder(MTL::RenderCommandEncoder *p_encoder) {
+ DEV_ASSERT(p_encoder != nullptr);
+ DEV_ASSERT(!render.encoder);
+ DEV_ASSERT(!inline_render.encoder);
+
+ type = MDCommandBufferStateType::InlineRender;
+ inline_render.encoder = NS::RetainPtr(p_encoder);
+}
+
+void MDCommandBuffer::_end_inline_render() {
+ DEV_ASSERT(type == MDCommandBufferStateType::InlineRender);
+
+ _pop_active_encoder_labels();
+ _fence_update(inline_render.encoder.get());
+ inline_render.encoder->endEncoding();
+ inline_render.reset();
+ reset();
+}
+
void MDCommandBuffer::_end_blit() {
DEV_ASSERT(type == MDCommandBufferStateType::Blit);
+ _pop_active_encoder_labels();
+ _fence_update(blit.encoder.get());
blit.encoder->endEncoding();
blit.reset();
reset();
@@ -1780,7 +2024,7 @@ void MDCommandBuffer::_bind_uniforms_direct(MDUniformSet *p_set, MDShader *p_sha
void MDCommandBuffer::_bind_uniforms_argument_buffers_compute(MDUniformSet *p_set, MDShader *p_shader, uint32_t p_set_index, uint32_t p_dynamic_offsets) {
DEV_ASSERT(p_shader->uses_argument_buffers);
- DEV_ASSERT(compute.encoder.get() != nullptr);
+ DEV_ASSERT(compute.encoder);
MTL::ComputeCommandEncoder *enc = compute.encoder.get();
compute.resource_tracker.merge_from(p_set->usage_to_resources);
diff --git a/drivers/metal/metal3_objects.h b/drivers/metal/metal3_objects.h
index 4e690cdc8fb..86914637408 100644
--- a/drivers/metal/metal3_objects.h
+++ b/drivers/metal/metal3_objects.h
@@ -51,6 +51,7 @@
/**************************************************************************/
#include "drivers/metal/metal_objects_shared.h"
+#include "drivers/metal/rendering_device_driver_metal.h"
#include "servers/rendering/rendering_device_driver.h"
#include <Metal/Metal.hpp>
@@ -260,6 +261,41 @@ struct DirectEncoder {
encoder(p_encoder), cache(p_cache), mode(p_mode) {}
};
+// A pool of GPU timestamps, backed by a timestamp counter sample buffer.
+//
+// The sample buffer uses shared storage, so results are resolved on the CPU and
+// no blit pass is required to make them readable.
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) QueryPool {
+ NS::SharedPtr<MTL::CounterSampleBuffer> sample_buffer;
+ // A one byte private buffer, filled by the timestamp encoder so it always
+ // carries at least one command.
+ NS::SharedPtr<MTL::Buffer> dummy_buffer;
+ // The counter sample buffer timestamp domain is not queryable, so it is
+ // correlated against the CPU clock. queryTimestampFrequency() describes the
+ // Metal 4 counter heap domain instead, and is roughly 33x off here.
+ MTL::Device *device = nullptr;
+ MTL::Timestamp cpu_base = 0;
+ MTL::Timestamp gpu_base = 0;
+ double timestamp_to_nano = 0.0;
+ uint32_t count = 0;
+
+ QueryPool() = default;
+
+ // Resolves the GPU to CPU tick ratio on first use, once enough time has
+ // elapsed since creation for the correlation to be meaningful.
+ double _resolve_timestamp_to_nano();
+
+public:
+ // Returns nullptr if the device does not expose the timestamp counter set.
+ static QueryPool *create(MTL::Device *p_device, uint32_t p_count);
+
+ MTL::CounterSampleBuffer *get_sample_buffer() const { return sample_buffer.get(); }
+ MTL::Buffer *get_dummy_buffer() const { return dummy_buffer.get(); }
+ uint32_t get_count() const { return count; }
+
+ void get_results(uint32_t p_count, uint64_t *r_results);
+};
+
class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDCommandBuffer : public MDCommandBufferBase {
friend class MDUniformSet;
@@ -278,22 +314,23 @@ private:
/// Allocates from the ring buffer for dynamic argument buffers.
Alloc allocate_arg_buffer(uint32_t p_size);
- struct {
- NS::SharedPtr<MTL::ResidencySet> rs;
- } _frame_state;
+ // Heaps made resident on this command buffer's encoders (barriers mode only).
+ LocalVector<MTL::Heap *> _resident_heaps;
+ uint64_t _resident_heaps_generation = 0;
+
+ void _encode_residency(MTL::RenderCommandEncoder *p_enc);
+ void _encode_residency(MTL::ComputeCommandEncoder *p_enc);
#pragma mark - Synchronization
- enum {
- STAGE_RENDER,
- STAGE_COMPUTE,
- STAGE_BLIT,
- STAGE_MAX,
- };
- bool use_barriers = false;
- MTL::Stages pending_after_stages[STAGE_MAX] = { 0, 0, 0 };
- MTL::Stages pending_before_queue_stages[STAGE_MAX] = { 0, 0, 0 };
- void _encode_barrier(MTL::CommandEncoder *p_enc);
+ RDM::SyncMode sync_mode = RDM::SyncMode::Barriers;
+
+ void _fence_wait(MTL::RenderCommandEncoder *p_enc);
+ void _fence_wait(MTL::ComputeCommandEncoder *p_enc);
+ void _fence_wait(MTL::BlitCommandEncoder *p_enc);
+ void _fence_update(MTL::RenderCommandEncoder *p_enc);
+ void _fence_update(MTL::ComputeCommandEncoder *p_enc);
+ void _fence_update(MTL::BlitCommandEncoder *p_enc);
void reset();
@@ -304,7 +341,10 @@ private:
MTL::CommandBuffer *command_buffer();
void _end_compute_dispatch();
+ void _end_inline_render();
void _end_blit();
+ void _pop_active_encoder_labels();
+ void _set_inline_render_encoder(MTL::RenderCommandEncoder *p_encoder);
MTL::BlitCommandEncoder *_ensure_blit_encoder();
enum class CopySource {
@@ -338,7 +378,10 @@ protected:
const MDSubpass &get_current_subpass() const override { return render.get_subpass(); }
LocalVector<RDD::RenderPassClearValue> &get_clear_values() override { return render.clear_values; }
const Rect2i &get_render_area() const override { return render.render_area; }
- void end_render_encoding() override { render.end_encoding(); }
+ void end_render_encoding() override {
+ _fence_update(render.encoder.get());
+ render.end_encoding();
+ }
public:
struct RenderState : public RenderStateBase {
@@ -346,7 +389,7 @@ public:
MDFrameBuffer *frameBuffer = nullptr;
MDRenderPipeline *pipeline = nullptr;
LocalVector<RDD::RenderPassClearValue> clear_values;
- uint32_t current_subpass = UINT32_MAX;
+ MDSubpass *current_subpass = nullptr;
Rect2i render_area;
bool is_rendering_entire_area = false;
NS::SharedPtr<MTL::RenderPassDescriptor> desc;
@@ -367,8 +410,8 @@ public:
void end_encoding();
_ALWAYS_INLINE_ const MDSubpass &get_subpass() const {
- DEV_ASSERT(pass != nullptr);
- return pass->subpasses[current_subpass];
+ DEV_ASSERT(current_subpass != nullptr);
+ return *current_subpass;
}
_FORCE_INLINE_ void mark_viewport_dirty() {
@@ -490,6 +533,14 @@ public:
}
} compute;
+ struct {
+ NS::SharedPtr<MTL::RenderCommandEncoder> encoder;
+
+ _FORCE_INLINE_ void reset() {
+ encoder.reset();
+ }
+ } inline_render;
+
// State specific to a blit pass.
struct {
NS::SharedPtr<MTL::BlitCommandEncoder> encoder;
@@ -502,9 +553,9 @@ public:
return commandBuffer.get();
}
- void begin() override;
- void commit() override;
- void end() override;
+ void _begin() override;
+ void _commit() override;
+ void _end() override;
void bind_pipeline(RDD::PipelineID p_pipeline) override;
@@ -540,6 +591,8 @@ public:
#pragma mark - Compute Commands
+ void compute_begin_pass() override;
+ void compute_end_pass() override;
void compute_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) override;
void compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) override;
void compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset) override;
@@ -559,6 +612,10 @@ public:
void copy_buffer_to_texture(RDD::BufferID p_src_buffer, RDD::TextureID p_dst_texture, VectorView<RDD::BufferTextureCopyRegion> p_regions) override;
void copy_texture_to_buffer(RDD::TextureID p_src_texture, RDD::BufferID p_dst_buffer, VectorView<RDD::BufferTextureCopyRegion> p_regions) override;
+#pragma mark - Timestamp
+
+ void timestamp_write(QueryPool *p_pool, uint32_t p_index);
+
#pragma mark - Synchronization
void pipeline_barrier(BitField<RDD::PipelineStageBits> p_src_stages,
diff --git a/drivers/metal/metal_allocator.cpp b/drivers/metal/metal_allocator.cpp
index 2df6de8fc18..9b289fe2d29 100644
--- a/drivers/metal/metal_allocator.cpp
+++ b/drivers/metal/metal_allocator.cpp
@@ -30,9 +30,29 @@
#include "drivers/metal/metal_allocator.h"
+namespace {
+
+class SpinLockGuard {
+ const SpinLock &lock;
+
+public:
+ explicit SpinLockGuard(const SpinLock &p_lock) :
+ lock(p_lock) {
+ lock.lock();
+ }
+ ~SpinLockGuard() {
+ lock.unlock();
+ }
+};
+
+} // namespace
+
#pragma mark - MetalAllocator
MetalAllocator *MetalAllocator::create(MTL::Device *p_device, bool p_use_heaps) {
+ if (p_use_heaps) {
+ return memnew(MetalHeapAllocator(p_device));
+ }
return memnew(MetalDeviceAllocator(p_device));
}
@@ -73,3 +93,306 @@ void MetalDeviceAllocator::get_stats(MetalAllocatorStats &r_stats) {
r_stats = MetalAllocatorStats();
}
#endif
+
+#pragma mark - MetalHeapAllocator
+
+namespace {
+constexpr NS::UInteger RESOURCE_CPU_CACHE_MODE_SHIFT = 0;
+constexpr NS::UInteger RESOURCE_CPU_CACHE_MODE_MASK = 0xFull << RESOURCE_CPU_CACHE_MODE_SHIFT;
+constexpr NS::UInteger RESOURCE_STORAGE_MODE_SHIFT = 4;
+constexpr NS::UInteger RESOURCE_STORAGE_MODE_MASK = 0xFull << RESOURCE_STORAGE_MODE_SHIFT;
+} // namespace
+
+uint64_t MetalHeapAllocator::_preferred_block_size(uint32_t p_pool) {
+ switch (p_pool) {
+ case POOL_PRIVATE:
+ return 128ull * 1024 * 1024;
+ case POOL_SHARED:
+ return 32ull * 1024 * 1024;
+ case POOL_SHARED_WC:
+ default:
+ return 16ull * 1024 * 1024;
+ }
+}
+
+uint32_t MetalHeapAllocator::_pool_for_options(MTL::ResourceOptions p_options) {
+ MTL::StorageMode storage = (MTL::StorageMode)((p_options & RESOURCE_STORAGE_MODE_MASK) >> RESOURCE_STORAGE_MODE_SHIFT);
+ MTL::CPUCacheMode cache = (MTL::CPUCacheMode)((p_options & RESOURCE_CPU_CACHE_MODE_MASK) >> RESOURCE_CPU_CACHE_MODE_SHIFT);
+ if (storage == MTL::StorageModeShared) {
+ return cache == MTL::CPUCacheModeWriteCombined ? POOL_SHARED_WC : POOL_SHARED;
+ }
+ // Private and Memoryless both land in the private pool.
+ return POOL_PRIVATE;
+}
+
+uint32_t MetalHeapAllocator::_pool_for_texture(const MTL::TextureDescriptor *p_desc) {
+ // Memoryless textures may be placed into any heap:
+ // newTextureWithDescriptor:offset: permits StorageModeMemoryless
+ // regardless of the heap's storage mode.
+ return p_desc->storageMode() == MTL::StorageModeShared ? POOL_SHARED : POOL_PRIVATE;
+}
+
+NS::SharedPtr<MTL::Heap> MetalHeapAllocator::_create_heap(uint32_t p_pool, uint64_t p_size) {
+ NS::SharedPtr<MTL::HeapDescriptor> desc = NS::TransferPtr(MTL::HeapDescriptor::alloc()->init());
+ desc->setType(MTL::HeapTypePlacement);
+ desc->setStorageMode(p_pool == POOL_PRIVATE ? MTL::StorageModePrivate : MTL::StorageModeShared);
+ desc->setCpuCacheMode(p_pool == POOL_SHARED_WC ? MTL::CPUCacheModeWriteCombined : MTL::CPUCacheModeDefaultCache);
+ desc->setHazardTrackingMode(MTL::HazardTrackingModeUntracked);
+ desc->setSize(p_size);
+ return NS::TransferPtr(device->newHeap(desc.get()));
+}
+
+bool MetalHeapAllocator::_pool_allocate(uint32_t p_pool, uint64_t p_size, uint64_t p_align, MetalAllocation &r_allocation, MTL::Heap *&r_heap, uint64_t &r_offset) {
+ Pool &pool = pools[p_pool];
+ uint64_t padded = p_size + (p_align > UNIT ? p_align - 1 : 0);
+ uint32_t units = (uint32_t)((padded + UNIT - 1) / UNIT);
+
+ SpinLockGuard lock(pool.mutex);
+
+ uint32_t block_index = UINT32_MAX;
+ OffsetAllocator::Allocation alloc{};
+ for (uint32_t i = 0; i < pool.blocks.size(); i++) {
+ if (pool.blocks[i].metadata == nullptr) {
+ continue; // Reclaimed slot.
+ }
+ alloc = pool.blocks[i].metadata->allocate(units);
+ if (alloc.offset != OffsetAllocator::Allocation::NO_SPACE) {
+ block_index = i;
+ break;
+ }
+ }
+
+ if (block_index == UINT32_MAX) {
+ uint64_t block_size = MAX(_preferred_block_size(p_pool), (padded + UNIT - 1) & ~(UNIT - 1));
+ NS::SharedPtr<MTL::Heap> heap = _create_heap(p_pool, block_size);
+ ERR_FAIL_NULL_V_MSG(heap.get(), false, "Unable to create placement heap.");
+
+ Block block;
+ block.heap = heap;
+ block.metadata = memnew(OffsetAllocator::Allocator((uint32_t)(block_size / UNIT), MAX_ALLOCS_PER_BLOCK));
+
+ // Reuse a reclaimed slot if one exists, else append. Block indices
+ // stored in live handles must stay stable, so blocks are never erased.
+ block_index = pool.blocks.size();
+ for (uint32_t i = 0; i < pool.blocks.size(); i++) {
+ if (pool.blocks[i].metadata == nullptr && pool.blocks[i].heap.get() == nullptr) {
+ block_index = i;
+ break;
+ }
+ }
+ if (block_index == pool.blocks.size()) {
+ pool.blocks.push_back(block);
+ } else {
+ pool.blocks[block_index] = block;
+ }
+#ifdef DEBUG_ENABLED
+ pool.stats.block_count++;
+ pool.stats.reserved_bytes += heap->size();
+#endif
+ generation.fetch_add(1, std::memory_order_relaxed);
+
+ alloc = pool.blocks[block_index].metadata->allocate(units);
+ ERR_FAIL_COND_V(alloc.offset == OffsetAllocator::Allocation::NO_SPACE, false);
+ }
+
+ Block &block = pool.blocks[block_index];
+ if (block.live == 0 && pool.empty_blocks > 0) {
+ pool.empty_blocks--;
+ }
+ block.live++;
+#ifdef DEBUG_ENABLED
+ pool.stats.allocation_count++;
+ pool.stats.used_bytes += (uint64_t)units * UNIT;
+#endif
+
+ uint64_t raw_offset = (uint64_t)alloc.offset * UNIT;
+ r_offset = (raw_offset + p_align - 1) & ~(p_align - 1);
+ r_heap = block.heap.get();
+ r_allocation.kind = MetalAllocation::Kind::POOL;
+ r_allocation.pool = (uint8_t)p_pool;
+ r_allocation.block = block_index;
+ r_allocation.alloc = alloc;
+ return true;
+}
+
+bool MetalHeapAllocator::_dedicated_allocate(uint32_t p_pool, uint64_t p_size, MetalAllocation &r_allocation, MTL::Heap *&r_heap) {
+ NS::SharedPtr<MTL::Heap> heap = _create_heap(p_pool, p_size);
+ ERR_FAIL_NULL_V_MSG(heap.get(), false, "Unable to create dedicated placement heap.");
+
+ Pool &pool = pools[p_pool];
+ SpinLockGuard lock(pool.mutex);
+ pool.dedicated_heaps.push_back(heap.get());
+ heap->retain(); // dedicated_heaps holds an owned reference.
+#ifdef DEBUG_ENABLED
+ pool.stats.dedicated_count++;
+ pool.stats.dedicated_bytes += heap->size();
+#endif
+ generation.fetch_add(1, std::memory_order_relaxed);
+
+ r_heap = heap.get();
+ r_allocation.kind = MetalAllocation::Kind::DEDICATED;
+ r_allocation.pool = (uint8_t)p_pool;
+ r_allocation.heap = heap.get();
+ r_allocation.heap->retain(); // Handle's owned reference, released in _free_allocation.
+ return true;
+}
+
+void MetalHeapAllocator::_free_allocation(MetalAllocation &p_allocation) {
+ // old_heap takes ownership of the MTL::Heap, so it is released outside any locks.
+ NS::SharedPtr<MTL::Heap> old_heap;
+
+ switch (p_allocation.kind) {
+ case MetalAllocation::Kind::INVALID:
+ break;
+ case MetalAllocation::Kind::POOL: {
+ Pool &pool = pools[p_allocation.pool];
+ SpinLockGuard lock(pool.mutex);
+ Block &block = pool.blocks[p_allocation.block];
+#ifdef DEBUG_ENABLED
+ uint64_t freed_bytes = (uint64_t)block.metadata->allocationSize(p_allocation.alloc) * UNIT;
+ pool.stats.allocation_count--;
+ pool.stats.used_bytes -= freed_bytes;
+#endif
+ block.metadata->free(p_allocation.alloc);
+ block.live--;
+ if (block.live == 0) {
+ pool.empty_blocks++;
+ // Keep one empty block cached; reclaim beyond that.
+ if (pool.empty_blocks > 1) {
+#ifdef DEBUG_ENABLED
+ pool.stats.block_count--;
+ pool.stats.reserved_bytes -= block.heap->size();
+#endif
+ memdelete(block.metadata);
+ block.metadata = nullptr;
+ old_heap = std::move(block.heap);
+ pool.empty_blocks--;
+ generation.fetch_add(1, std::memory_order_relaxed);
+ }
+ }
+ } break;
+ case MetalAllocation::Kind::DEDICATED: {
+ Pool &pool = pools[p_allocation.pool];
+ SpinLockGuard lock(pool.mutex);
+ int64_t idx = pool.dedicated_heaps.find(p_allocation.heap);
+ DEV_ASSERT(idx >= 0);
+ if (likely(idx >= 0)) {
+#ifdef DEBUG_ENABLED
+ pool.stats.dedicated_count--;
+ pool.stats.dedicated_bytes -= p_allocation.heap->size();
+#endif
+ pool.dedicated_heaps[idx]->release(); // not released here, as p_allocation also has a reference
+ pool.dedicated_heaps.remove_at_unordered(idx);
+ }
+ old_heap = NS::TransferPtr(p_allocation.heap);
+ p_allocation.heap = nullptr;
+ generation.fetch_add(1, std::memory_order_relaxed);
+ } break;
+ }
+ p_allocation.invalidate();
+}
+
+MetalBuffer MetalHeapAllocator::new_buffer(NS::UInteger p_length, MTL::ResourceOptions p_options) {
+ uint32_t pool_index = _pool_for_options(p_options);
+ MTL::SizeAndAlign sa = device->heapBufferSizeAndAlign(p_length, p_options);
+ // Placement-heap resources inherit the heap's hazard tracking; strip
+ // hazard bits and pass storage/cache + untracked only.
+ MTL::ResourceOptions heap_options = (p_options & (RESOURCE_STORAGE_MODE_MASK | RESOURCE_CPU_CACHE_MODE_MASK)) | MTL::ResourceHazardTrackingModeUntracked;
+
+ MetalBuffer result;
+ MTL::Heap *heap = nullptr;
+ if (sa.size > _preferred_block_size(pool_index) / 2) {
+ if (!_dedicated_allocate(pool_index, sa.size, result.allocation, heap)) {
+ return result;
+ }
+ result.buffer = NS::TransferPtr(heap->newBuffer(p_length, heap_options, 0));
+ } else {
+ uint64_t offset = 0;
+ if (!_pool_allocate(pool_index, sa.size, sa.align, result.allocation, heap, offset)) {
+ return result;
+ }
+ result.buffer = NS::TransferPtr(heap->newBuffer(p_length, heap_options, offset));
+ }
+ if (!result.buffer) {
+ _free_allocation(result.allocation);
+ }
+ return result;
+}
+
+MetalTexture MetalHeapAllocator::new_texture(const MTL::TextureDescriptor *p_desc) {
+ uint32_t pool_index = _pool_for_texture(p_desc);
+ MTL::SizeAndAlign sa = device->heapTextureSizeAndAlign(p_desc);
+
+ MetalTexture result;
+ MTL::Heap *heap = nullptr;
+ if (sa.size > _preferred_block_size(pool_index) / 2) {
+ if (!_dedicated_allocate(pool_index, sa.size, result.allocation, heap)) {
+ return result;
+ }
+ result.texture = NS::TransferPtr(heap->newTexture(p_desc, 0));
+ } else {
+ uint64_t offset = 0;
+ if (!_pool_allocate(pool_index, sa.size, sa.align, result.allocation, heap, offset)) {
+ return result;
+ }
+ result.texture = NS::TransferPtr(heap->newTexture(p_desc, offset));
+ }
+ if (!result.texture) {
+ _free_allocation(result.allocation);
+ }
+ return result;
+}
+
+void MetalHeapAllocator::free_buffer(MetalBuffer &p_buffer) {
+ p_buffer.buffer.reset();
+ _free_allocation(p_buffer.allocation);
+}
+
+void MetalHeapAllocator::free_texture(MetalTexture &p_texture) {
+ p_texture.texture.reset();
+ _free_allocation(p_texture.allocation);
+}
+
+uint64_t MetalHeapAllocator::get_heaps(LocalVector<MTL::Heap *> &r_heaps) {
+ uint64_t gen = generation.load(std::memory_order_relaxed);
+ for (uint32_t p = 0; p < POOL_COUNT; p++) {
+ Pool &pool = pools[p];
+ SpinLockGuard lock(pool.mutex);
+ for (const Block &block : pool.blocks) {
+ if (block.heap.get() != nullptr) {
+ r_heaps.push_back(block.heap.get());
+ }
+ }
+ for (MTL::Heap *heap : pool.dedicated_heaps) {
+ r_heaps.push_back(heap);
+ }
+ }
+ return gen;
+}
+
+uint64_t MetalHeapAllocator::get_heap_generation() const {
+ return generation.load(std::memory_order_relaxed);
+}
+
+#ifdef DEBUG_ENABLED
+void MetalHeapAllocator::get_stats(MetalAllocatorStats &r_stats) {
+ for (uint32_t p = 0; p < POOL_COUNT; p++) {
+ SpinLockGuard lock(pools[p].mutex);
+ r_stats.pools[p] = pools[p].stats;
+ }
+}
+#endif
+
+MetalHeapAllocator::~MetalHeapAllocator() {
+ for (uint32_t p = 0; p < POOL_COUNT; p++) {
+ Pool &pool = pools[p];
+ for (Block &block : pool.blocks) {
+ if (block.metadata != nullptr) {
+ memdelete(block.metadata);
+ }
+ }
+ for (MTL::Heap *heap : pool.dedicated_heaps) {
+ heap->release();
+ }
+ }
+}
diff --git a/drivers/metal/metal_allocator.h b/drivers/metal/metal_allocator.h
index 952b599f33a..cf0b1e36ed7 100644
--- a/drivers/metal/metal_allocator.h
+++ b/drivers/metal/metal_allocator.h
@@ -30,10 +30,15 @@
#pragma once
+#include "core/os/spin_lock.h"
#include "core/templates/local_vector.h"
+#include <thirdparty/offset_allocator/offsetAllocator.hpp>
+
#include <Metal/Metal.hpp>
+#include <atomic>
+
/// 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
@@ -47,8 +52,16 @@ struct MetalAllocation {
};
Kind kind = Kind::INVALID;
+ uint8_t pool = 0;
+ uint32_t block = 0; // POOL only.
+ OffsetAllocator::Allocation alloc; // POOL only.
+ MTL::Heap *heap = nullptr; // DEDICATED only.
_FORCE_INLINE_ bool is_valid() const { return kind != Kind::INVALID; }
+ _FORCE_INLINE_ void invalidate() {
+ kind = Kind::INVALID;
+ heap = nullptr;
+ }
};
struct MetalBuffer {
@@ -123,3 +136,83 @@ public:
void get_stats(MetalAllocatorStats &r_stats) override;
#endif
};
+
+/// Placement-heap suballocator for barriers mode. Three pools keyed by
+/// storage mode (+ CPU cache mode for the write-combined pool); blocks are
+/// placement heaps with OffsetAllocator metadata in 256-byte units;
+/// resources larger than half a pool's preferred block size get a dedicated
+/// single-resource heap.
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MetalHeapAllocator final : public MetalAllocator {
+public:
+ enum PoolIndex : uint32_t {
+ POOL_PRIVATE = 0, // StorageModePrivate; memoryless textures also land here.
+ POOL_SHARED = 1, // StorageModeShared, default CPU cache.
+ POOL_SHARED_WC = 2, // StorageModeShared, write-combined CPU cache.
+ POOL_COUNT = 3,
+ };
+
+ /// The smallest allocation the allocator works in, in bytes. OffsetAllocator
+ /// hands out ranges in whole units, so every offset is a multiple of 256,
+ /// which satisfies the alignment of every resource on Apple silicon
+ /// (buffers report 256, textures 128) with no per-allocation padding.
+ /// Should a format ever report more than 256, _pool_allocate defends
+ /// itself by overallocating and rounding the offset up.
+ static constexpr uint64_t UNIT = 256;
+ /// How many allocations one block can hold at once. OffsetAllocator
+ /// asks for this up front (its default is 128K) because it allocates
+ /// all of its bookkeeping in one go, at about 32 bytes per entry.
+ ///
+ /// 16K entries costs about 512 KiB of bookkeeping per block instead of
+ /// 4 MiB at the default.
+ static constexpr uint32_t MAX_ALLOCS_PER_BLOCK = 16384;
+
+private:
+ struct Block {
+ NS::SharedPtr<MTL::Heap> heap;
+ OffsetAllocator::Allocator *metadata = nullptr;
+ // The number of live allocations in this block.
+ uint32_t live = 0;
+ };
+
+ struct Pool {
+ SpinLock mutex;
+ LocalVector<Block> blocks;
+ LocalVector<MTL::Heap *> dedicated_heaps; // Owned (+1) refs, for get_heaps enumeration.
+#ifdef DEBUG_ENABLED
+ MetalAllocatorStats::Pool stats;
+#endif
+ uint32_t empty_blocks = 0;
+ };
+
+ MTL::Device *device = nullptr;
+ Pool pools[POOL_COUNT];
+ /// Incremented each time a heap is created or destroyed so clients know when to update
+ /// their own state and refresh residency.
+ std::atomic<uint64_t> generation = 1;
+
+ static uint64_t _preferred_block_size(uint32_t p_pool);
+ static uint32_t _pool_for_options(MTL::ResourceOptions p_options);
+ static uint32_t _pool_for_texture(const MTL::TextureDescriptor *p_desc);
+ NS::SharedPtr<MTL::Heap> _create_heap(uint32_t p_pool, uint64_t p_size);
+ /// Allocates p_size bytes aligned to p_align from pool p_pool.
+ /// On success fills r_allocation (Kind::POOL), r_heap and r_offset.
+ bool _pool_allocate(uint32_t p_pool, uint64_t p_size, uint64_t p_align, MetalAllocation &r_allocation, MTL::Heap *&r_heap, uint64_t &r_offset);
+ /// Creates a dedicated single-resource heap (Kind::DEDICATED).
+ bool _dedicated_allocate(uint32_t p_pool, uint64_t p_size, MetalAllocation &r_allocation, MTL::Heap *&r_heap);
+ void _free_allocation(MetalAllocation &p_allocation);
+
+public:
+ explicit MetalHeapAllocator(MTL::Device *p_device) :
+ device(p_device) {}
+ ~MetalHeapAllocator() override;
+
+ 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.cpp b/drivers/metal/metal_objects_shared.cpp
index 2c57309873d..e1f454afb36 100644
--- a/drivers/metal/metal_objects_shared.cpp
+++ b/drivers/metal/metal_objects_shared.cpp
@@ -265,7 +265,7 @@ fragment void fullscreenNoopFrag(float4 gl_FragCoord [[position]]) {
*p_error = err;
}
- if (mtlLib.get() == nullptr) {
+ if (!mtlLib) {
return {};
}
@@ -415,8 +415,8 @@ bool MDAttachment::shouldClear(const MDSubpass &p_subpass, bool p_is_stencil) co
return (p_is_stencil ? stencilLoadAction : loadAction) == MTL::LoadActionClear;
}
-MDRenderPass::MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses) :
- attachments(p_attachments), subpasses(p_subpasses) {
+MDRenderPass::MDRenderPass(LocalVector<MDAttachment> &&p_attachments, LocalVector<MDSubpass> &&p_subpasses) :
+ attachments(std::move(p_attachments)), subpasses(std::move(p_subpasses)) {
for (MDAttachment &att : attachments) {
att.linkToSubpass(*this);
}
@@ -424,6 +424,97 @@ MDRenderPass::MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass
#pragma mark - Command Buffer Base
+MDCommandBufferBase::~MDCommandBufferBase() {
+ release_resources();
+}
+
+void MDCommandBufferBase::_create_level_fences(MTL::Device *p_device) {
+ for (uint32_t i = 0; i < 2; i++) {
+ _fences[i] = NS::TransferPtr(p_device->newFence());
+#ifdef DEV_ENABLED
+ _fences[i]->setLabel(i == 0 ? MTLSTR("Level Fence 0") : MTLSTR("Level Fence 1"));
+#endif
+ }
+}
+
+MTL::Fence *MDCommandBufferBase::_fence_to_wait() {
+ if (!_fences[0]) {
+ return nullptr;
+ }
+ uint32_t i = (_fence_level + 1) & 1;
+#ifdef DEV_ENABLED
+ _fence_wait_issued = true;
+#endif
+ return _fence_updated[i] ? _fences[i].get() : nullptr;
+}
+
+MTL::Fence *MDCommandBufferBase::_fence_to_update() {
+ if (!_fences[0]) {
+ return nullptr;
+ }
+#ifdef DEV_ENABLED
+ DEV_ASSERT(_fence_wait_issued);
+ _fence_wait_issued = false;
+#endif
+ uint32_t i = _fence_level & 1;
+ _fence_updated[i] = true;
+ _fence_level_dirty = true;
+ return _fences[i].get();
+}
+
+void MDCommandBufferBase::advance_sync_level() {
+ // No encoder may straddle a level boundary: per-encoder fences are only
+ // sufficient if every encoder in level k closed before level k + 1 opens.
+ DEV_ASSERT(type == MDCommandBufferStateType::None);
+ // Must stay a no-op on a clean level: external_pass_fence() relies on the
+ // next level still waiting F_prev when nothing here updated F_cur.
+ if (!_fence_level_dirty) {
+ return;
+ }
+ _fence_level_dirty = false;
+ _fence_level++;
+}
+
+MTL::Fence *MDCommandBufferBase::external_pass_fence() {
+ // _fence_level_dirty only reflects closed encoders.
+ DEV_ASSERT(type == MDCommandBufferStateType::None);
+ if (!_fences[0]) {
+ return nullptr;
+ }
+ // MetalFX exposes a single fence that it both waits for and updates, which
+ // the alternating pair cannot express directly.
+ if (_fence_level_dirty) {
+ // An encoder in this level already waited F_prev and updated F_cur, so
+ // waiting F_cur transitively covers the prior level, and updating F_cur
+ // is what the next level waits on.
+#ifdef DEV_ENABLED
+ _fence_wait_issued = true; // The pass waits F_cur itself.
+#endif
+ return _fence_to_update();
+ }
+ // Nothing in this level has updated F_cur yet, so the pass joins the prior
+ // level from the fence's point of view: it waits F_prev and updates F_prev.
+ // Any later encoder in this level waits F_prev and so orders after the
+ // pass; if the level stays clean, the next level is still this one and
+ // waits F_prev too.
+ uint32_t i = (_fence_level + 1) & 1;
+ _fence_updated[i] = true;
+ return _fences[i].get();
+}
+
+void MDCommandBufferBase::begin() {
+ _begin();
+}
+
+void MDCommandBufferBase::commit() {
+ _commit();
+ advance_sync_level();
+}
+
+void MDCommandBufferBase::end() {
+ _end();
+}
+
void MDCommandBufferBase::retain_resource(CFTypeRef p_resource) {
CFRetain(p_resource);
_retained_resources.push_back(p_resource);
@@ -618,13 +709,19 @@ void MDCommandBufferBase::encode_push_constant_data(RDD::ShaderID p_shader, Vect
}
push_constant_binding = shader->push_constants.binding;
const void *ptr = p_data.ptr();
- push_constant_data_len = p_data.size() * sizeof(uint32_t);
+ uint32_t data_len = p_data.size() * sizeof(uint32_t);
+ // Round buffer length up to 16 bytes. SPIRV-Cross's MSL backend pads the
+ // generated push struct to its strictest member alignment (typically vec4 → 16),
+ // so Metal validates the bound buffer length against sizeof(struct), not the
+ // caller's unpadded data size. The trailing bytes are never read by the shader.
+ push_constant_data_len = (data_len + 15u) & ~15u;
DEV_ASSERT(push_constant_data_len <= sizeof(push_constant_data));
- memcpy(push_constant_data, ptr, push_constant_data_len);
+ memcpy(push_constant_data, ptr, data_len);
if (push_constant_data_len > 0) {
mark_push_constants_dirty();
}
} break;
+ case MDCommandBufferStateType::InlineRender:
case MDCommandBufferStateType::Blit:
case MDCommandBufferStateType::None:
return;
diff --git a/drivers/metal/metal_objects_shared.h b/drivers/metal/metal_objects_shared.h
index 28cf55721a9..037e8243f95 100644
--- a/drivers/metal/metal_objects_shared.h
+++ b/drivers/metal/metal_objects_shared.h
@@ -36,6 +36,10 @@
#include "drivers/metal/pixel_formats.h"
#include "drivers/metal/sha256_digest.h"
+#ifdef DEBUG_ENABLED
+#include "core/os/os.h"
+#endif
+
#include <CoreFoundation/CoreFoundation.h>
#include <memory>
@@ -142,21 +146,16 @@ private:
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;
uint32_t buffer_size = DEFAULT_BUFFER_SIZE;
- bool changed = false;
_FORCE_INLINE_ uint32_t alloc_segment() {
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 cached_buffers.size() - 1;
}
@@ -222,22 +221,6 @@ public:
}
current_segment = 0;
}
-
- /// Returns true if buffers were added or removed since last clear_changed().
- _FORCE_INLINE_ bool is_changed() const { return changed; }
-
- /// Clears the changed flag.
- _FORCE_INLINE_ void clear_changed() { changed = false; }
-
- /// Returns a Span of all backing buffers.
- _FORCE_INLINE_ Span<MTL::Buffer *const> get_buffers() const {
- return Span<MTL::Buffer *const>(buffers.ptr(), buffers.size());
- }
-
- /// Returns the number of buffer segments currently allocated.
- _FORCE_INLINE_ uint32_t get_segment_count() const {
- return buffers.size();
- }
};
#pragma mark - Resource Factory
@@ -309,42 +292,45 @@ _FORCE_INLINE_ static uint32_t to_index(RDD::ShaderStage p_s) {
}
class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDFrameBuffer {
- Vector<MTL::Texture *> textures;
-
public:
Size2i size;
MTL::RasterizationRateMap *rasterization_rate_map = nullptr;
- MDFrameBuffer(Vector<MTL::Texture *> p_textures, Size2i p_size) :
- textures(p_textures), size(p_size) {}
- MDFrameBuffer() {}
+ virtual MTL::Texture *get_texture(uint32_t p_idx) const = 0;
+ virtual bool has_texture(uint32_t p_idx) const = 0;
+
+ virtual ~MDFrameBuffer() = default;
+};
+
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDFrameBufferTexture : public MDFrameBuffer {
+ Vector<MTL::Texture *> textures;
- /// Returns the texture at the given index.
- _ALWAYS_INLINE_ MTL::Texture *get_texture(uint32_t p_idx) const {
+public:
+ MDFrameBufferTexture(Vector<MTL::Texture *> p_textures, Size2i p_size) {
+ textures = p_textures;
+ size = p_size;
+ }
+ MDFrameBufferTexture() {}
+
+ MTL::Texture *get_texture(uint32_t p_idx) const override {
return textures[p_idx];
}
- /// Returns true if the texture at the given index is not nil.
- _ALWAYS_INLINE_ bool has_texture(uint32_t p_idx) const {
+ bool has_texture(uint32_t p_idx) const override {
return textures[p_idx] != nullptr;
}
- /// Set the texture at the given index.
- _ALWAYS_INLINE_ void set_texture(uint32_t p_idx, MTL::Texture *p_texture) {
+ void set_texture(uint32_t p_idx, MTL::Texture *p_texture) {
textures.write[p_idx] = p_texture;
}
- /// Unset or nil the texture at the given index.
- _ALWAYS_INLINE_ void unset_texture(uint32_t p_idx) {
+ void unset_texture(uint32_t p_idx) {
textures.write[p_idx] = nullptr;
}
- /// Resizes buffers to the specified size.
- _ALWAYS_INLINE_ void set_texture_count(uint32_t p_size) {
+ void set_texture_count(uint32_t p_size) {
textures.resize(p_size);
}
-
- virtual ~MDFrameBuffer() = default;
};
template <>
@@ -505,14 +491,14 @@ public:
class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDRenderPass {
public:
- Vector<MDAttachment> attachments;
- Vector<MDSubpass> subpasses;
+ LocalVector<MDAttachment> attachments;
+ LocalVector<MDSubpass> subpasses;
uint32_t get_sample_count() const {
return attachments.is_empty() ? 1 : attachments[0].samples;
}
- MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses);
+ MDRenderPass(LocalVector<MDAttachment> &&p_attachments, LocalVector<MDSubpass> &&p_subpasses);
};
#pragma mark - Command Buffer Helpers
@@ -546,97 +532,14 @@ _FORCE_INLINE_ static bool operator==(MTL::Size p_a, MTL::Size p_b) {
return p_a.width == p_b.width && p_a.height == p_b.height && p_a.depth == p_b.depth;
}
-#pragma mark - Pipeline Stage Conversion
-
-GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wunguarded-availability")
-
-_FORCE_INLINE_ static MTL::Stages convert_src_pipeline_stages_to_metal(BitField<RDD::PipelineStageBits> p_stages) {
- p_stages.clear_flag(RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT);
-
- // BOTTOM_OF_PIPE or ALL_COMMANDS means "all prior work must complete".
- if (p_stages & (RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT)) {
- return MTL::StageAll;
- }
-
- MTL::Stages mtlStages = 0;
-
- // Vertex stage mappings.
- if (p_stages & (RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT | RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT | RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | RDD::PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
- mtlStages |= MTL::StageVertex;
- }
-
- // Fragment stage mappings.
- // Includes resolve and clear_storage, which on Metal use the render pipeline.
- if (p_stages & (RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT | RDD::PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT | RDD::PIPELINE_STAGE_RESOLVE_BIT | RDD::PIPELINE_STAGE_CLEAR_STORAGE_BIT)) {
- mtlStages |= MTL::StageFragment;
- }
-
- // Compute stage.
- if (p_stages & RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT) {
- mtlStages |= MTL::StageDispatch;
- }
-
- // Blit stage (transfer operations).
- if (p_stages & RDD::PIPELINE_STAGE_COPY_BIT) {
- mtlStages |= MTL::StageBlit;
- }
-
- // ALL_GRAPHICS_BIT special case.
- if (p_stages & RDD::PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
- mtlStages |= (MTL::StageVertex | MTL::StageFragment);
- }
-
- return mtlStages;
-}
-
-_FORCE_INLINE_ static MTL::Stages convert_dst_pipeline_stages_to_metal(BitField<RDD::PipelineStageBits> p_stages) {
- p_stages.clear_flag(RDD::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
-
- // TOP_OF_PIPE or ALL_COMMANDS means "wait before any work starts".
- if (p_stages & (RDD::PIPELINE_STAGE_ALL_COMMANDS_BIT | RDD::PIPELINE_STAGE_TOP_OF_PIPE_BIT)) {
- return MTL::StageAll;
- }
-
- MTL::Stages mtlStages = 0;
-
- // Vertex stage mappings.
- if (p_stages & (RDD::PIPELINE_STAGE_DRAW_INDIRECT_BIT | RDD::PIPELINE_STAGE_VERTEX_INPUT_BIT | RDD::PIPELINE_STAGE_VERTEX_SHADER_BIT | RDD::PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | RDD::PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | RDD::PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) {
- mtlStages |= MTL::StageVertex;
- }
-
- // Fragment stage mappings.
- // Includes resolve and clear_storage, which on Metal use the render pipeline.
- if (p_stages & (RDD::PIPELINE_STAGE_FRAGMENT_SHADER_BIT | RDD::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | RDD::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | RDD::PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT | RDD::PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT | RDD::PIPELINE_STAGE_RESOLVE_BIT | RDD::PIPELINE_STAGE_CLEAR_STORAGE_BIT)) {
- mtlStages |= MTL::StageFragment;
- }
-
- // Compute stage.
- if (p_stages & RDD::PIPELINE_STAGE_COMPUTE_SHADER_BIT) {
- mtlStages |= MTL::StageDispatch;
- }
-
- // Blit stage (transfer operations).
- if (p_stages & RDD::PIPELINE_STAGE_COPY_BIT) {
- mtlStages |= MTL::StageBlit;
- }
-
- // ALL_GRAPHICS_BIT special case.
- if (p_stages & RDD::PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
- mtlStages |= (MTL::StageVertex | MTL::StageFragment);
- }
-
- return mtlStages;
-}
-
-GODOT_CLANG_WARNING_POP
-
#pragma mark - Command Buffer Base
enum class MDCommandBufferStateType {
- None,
- Render,
- Compute,
- Blit, // Only used by Metal 3
+ None, // No encoder is currently active.
+ Render, // A render pass encoder opened by the regular render-pass flow is active.
+ InlineRender, // A one-off render encoder for clear/resolve helper commands is active.
+ Compute, // A compute encoder is active.
+ Blit, // A blit-style encoder is active.
};
/// Base struct for render state shared between MTL3 and MTL4 implementations.
@@ -673,16 +576,52 @@ protected:
MDCommandBufferStateType type = MDCommandBufferStateType::None;
- uint8_t push_constant_data[MAX_PUSH_CONSTANT_SIZE];
+ uint8_t push_constant_data[MAX_PUSH_CONSTANT_SIZE] = {};
uint32_t push_constant_data_len = 0;
uint32_t push_constant_binding = UINT32_MAX;
::RenderingDeviceDriverMetal *device_driver = nullptr;
+ // Tracks where each begin_label() pushed its debug group, so that end_label()
+ // can pop from the matching place. When an encoder is closed it pops every
+ // label still on it (keeping the encoder balanced) and flags those entries
+ // stale so the matching end_label() consumes the stack as a no-op.
+ struct LabelStackEntry {
+ MDCommandBufferStateType type;
+ bool stale;
+ };
+ LocalVector<LabelStackEntry> label_stack;
+
void release_resources();
+#pragma mark - Level Fences
+
+ // Alternating fences between render graph levels.
+ // Every encoder in level k waits on _fences[(k + 1) & 1]
+ // and updates _fences[k & 1]. _fence_level is used for k.
+ //
+ // Unused for hazard tracking
+ NS::SharedPtr<MTL::Fence> _fences[2];
+ uint32_t _fence_level = 0;
+ // true when a fence was updated in the prior level and therefore must be
+ // waited in the current level.
+ bool _fence_updated[2] = { false, false };
+ bool _fence_level_dirty = false;
+#ifdef DEV_ENABLED
+ // Set by _fence_to_wait(), consumed by _fence_to_update(): every encoder
+ // that updates F_cur must have waited F_prev, or the level chain breaks.
+ bool _fence_wait_issued = false;
+#endif
+
+ void _create_level_fences(MTL::Device *p_device);
+ MTL::Fence *_fence_to_wait();
+ MTL::Fence *_fence_to_update();
+
/// Called when push constants are modified to mark the appropriate dirty flags.
virtual void mark_push_constants_dirty() = 0;
+ virtual void _begin() = 0;
+ virtual void _commit() = 0;
+ virtual void _end() = 0;
/// Returns a reference to the render state base for viewport/scissor/blend operations.
virtual RenderStateBase &get_render_state_base() = 0;
@@ -704,11 +643,18 @@ protected:
void _render_clear_render_area();
public:
- virtual ~MDCommandBufferBase() { release_resources(); }
+ virtual ~MDCommandBufferBase();
+
+ void begin();
+ void commit();
+ void end();
+
+ /// Closes the current level (command group) and opens the next one.
+ void advance_sync_level();
- virtual void begin() = 0;
- virtual void commit() = 0;
- virtual void end() = 0;
+ /// Returns the fence an externally encoded pass (MetalFX) must wait for and
+ /// update, or nullptr under hazard tracking.
+ MTL::Fence *external_pass_fence();
virtual void bind_pipeline(RDD::PipelineID p_pipeline) = 0;
void encode_push_constant_data(RDD::ShaderID p_shader, VectorView<uint32_t> p_data);
@@ -750,6 +696,8 @@ public:
#pragma mark - Compute Commands
+ virtual void compute_begin_pass() = 0;
+ virtual void compute_end_pass() = 0;
virtual void compute_bind_uniform_sets(VectorView<RDD::UniformSetID> p_uniform_sets, RDD::ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) = 0;
virtual void compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) = 0;
virtual void compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset) = 0;
@@ -812,6 +760,8 @@ struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) UniformI
return slot;
case IndexType::ARG:
return arg_buffer;
+ default:
+ CRASH_NOW_MSG("Invalid IndexType");
}
}
};
@@ -1026,8 +976,6 @@ class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDRenderP
public:
NS::SharedPtr<MTL::RenderPipelineState> state;
NS::SharedPtr<MTL::DepthStencilState> depth_stencil;
- uint32_t push_constant_size = 0;
- uint32_t push_constant_stages_mask = 0;
SampleCount sample_count = SampleCount1;
struct {
@@ -1100,7 +1048,7 @@ public:
MDRenderPipeline() :
MDPipeline(MDPipelineType::Render) {}
- ~MDRenderPipeline() final = default;
+ ~MDRenderPipeline() override = default;
};
class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0), visionos(2.0)) MDComputePipeline final : public MDPipeline {
@@ -1114,5 +1062,5 @@ public:
explicit MDComputePipeline(NS::SharedPtr<MTL::ComputePipelineState> p_state) :
MDPipeline(MDPipelineType::Compute), state(std::move(p_state)) {}
- ~MDComputePipeline() final = default;
+ ~MDComputePipeline() override = default;
};
diff --git a/drivers/metal/rendering_context_driver_metal.cpp b/drivers/metal/rendering_context_driver_metal.cpp
index d134eb2a921..f90749b4fdf 100644
--- a/drivers/metal/rendering_context_driver_metal.cpp
+++ b/drivers/metal/rendering_context_driver_metal.cpp
@@ -113,10 +113,42 @@ void RenderingContextDriverMetal::driver_free(RenderingDeviceDriver *p_driver) {
memdelete(p_driver);
}
-class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) SurfaceLayer : public RenderingContextDriverMetal::Surface {
+/// A framebuffer that defers drawable acquisition from a CAMetalLayer
+/// until the texture is actually needed (via get_texture).
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDFrameBufferLayer final : public MDFrameBuffer {
CA::MetalLayer *layer = nullptr;
- LocalVector<MDFrameBuffer> frame_buffers;
- LocalVector<MTL::Drawable *> drawables;
+ mutable CA::MetalDrawable *drawable = nullptr;
+
+public:
+ MDFrameBufferLayer() {}
+ MDFrameBufferLayer(CA::MetalLayer *p_layer) :
+ layer(p_layer) {}
+
+ MTL::Texture *get_texture(uint32_t p_idx) const override {
+ DEV_ASSERT(p_idx == 0);
+ return get_drawable()->texture();
+ }
+
+ bool has_texture(uint32_t p_idx) const override {
+ DEV_ASSERT(p_idx == 0);
+ return drawable != nullptr;
+ }
+
+ CA::MetalDrawable *get_drawable() const {
+ if (drawable == nullptr) {
+ drawable = layer->nextDrawable();
+ }
+ return drawable;
+ }
+
+ void reset() {
+ drawable = nullptr;
+ }
+};
+
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) SurfaceLayer final : public RenderingContextDriverMetal::Surface {
+ CA::MetalLayer *layer = nullptr;
+ LocalVector<MDFrameBufferLayer> frame_buffers;
uint32_t rear = -1;
uint32_t front = 0;
uint32_t count = 0;
@@ -164,11 +196,9 @@ public:
break;
}
#endif
- drawables.resize(p_desired_framebuffer_count);
frame_buffers.resize(p_desired_framebuffer_count);
for (uint32_t i = 0; i < p_desired_framebuffer_count; i++) {
- // Reserve space for the drawable texture.
- frame_buffers[i].set_texture_count(1);
+ frame_buffers[i] = MDFrameBufferLayer(layer);
}
if (hdr_output) {
@@ -196,7 +226,7 @@ public:
return OK;
}
- RDD::FramebufferID acquire_next_frame_buffer() override final {
+ RDD::FramebufferID acquire_next_frame_buffer() override {
if (count == frame_buffers.size()) {
return RDD::FramebufferID();
}
@@ -204,46 +234,42 @@ public:
rear = (rear + 1) % frame_buffers.size();
count++;
- MDFrameBuffer &frame_buffer = frame_buffers[rear];
+ MDFrameBufferLayer &frame_buffer = frame_buffers[rear];
frame_buffer.size = Size2i(width, height);
-
- CA::MetalDrawable *drawable = layer->nextDrawable();
- ERR_FAIL_NULL_V_MSG(drawable, RDD::FramebufferID(), "no drawable available");
- drawables[rear] = drawable;
- frame_buffer.set_texture(0, drawable->texture());
+ frame_buffer.reset();
return RDD::FramebufferID(&frame_buffer);
}
- void present(MTL3::MDCommandBuffer *p_cmd_buffer) override final {
+ void present(MTL3::MDCommandBuffer *p_cmd_buffer) override {
if (count == 0) {
return;
}
- // Release texture and drawable.
- frame_buffers[front].unset_texture(0);
- MTL::Drawable *drawable = drawables[front];
- drawables[front] = nullptr;
+ MDFrameBufferLayer &frame_buffer = frame_buffers[front];
+ CA::MetalDrawable *drawable = frame_buffer.get_drawable();
+ frame_buffer.reset();
count--;
front = (front + 1) % frame_buffers.size();
- if (vsync_mode != DisplayServerEnums::VSYNC_DISABLED) {
- p_cmd_buffer->get_command_buffer()->presentDrawableAfterMinimumDuration(drawable, present_minimum_duration);
- } else {
- p_cmd_buffer->get_command_buffer()->presentDrawable(drawable);
+ if (drawable != nullptr) {
+ if (vsync_mode != DisplayServerEnums::VSYNC_DISABLED) {
+ p_cmd_buffer->get_command_buffer()->presentDrawableAfterMinimumDuration(drawable, present_minimum_duration);
+ } else {
+ p_cmd_buffer->get_command_buffer()->presentDrawable(drawable);
+ }
}
}
- MTL::Drawable *next_drawable() override final {
+ MTL::Drawable *next_drawable() override {
if (count == 0) {
return nullptr;
}
- // Release texture and drawable.
- frame_buffers[front].unset_texture(0);
- MTL::Drawable *drawable = drawables[front];
- drawables[front] = nullptr;
+ MDFrameBufferLayer &frame_buffer = frame_buffers[front];
+ CA::MetalDrawable *drawable = frame_buffer.get_drawable();
+ frame_buffer.reset();
count--;
front = (front + 1) % frame_buffers.size();
@@ -252,14 +278,14 @@ public:
}
API_AVAILABLE(macos(26.0), ios(26.0))
- MTL::ResidencySet *get_residency_set() const override final {
+ MTL::ResidencySet *get_residency_set() const override {
return layer->residencySet();
}
};
-class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) SurfaceOffscreen : public RenderingContextDriverMetal::Surface {
- int frame_buffer_size = 3;
- MDFrameBuffer *frame_buffers;
+class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) SurfaceOffscreen final : public RenderingContextDriverMetal::Surface {
+ static constexpr int frame_buffer_size = 3;
+ MDFrameBufferTexture frame_buffers[frame_buffer_size];
LocalVector<MTL::Texture *> textures;
LocalVector<MTL::Drawable *> drawables;
@@ -284,14 +310,12 @@ public:
textures.resize(frame_buffer_size);
drawables.resize(frame_buffer_size);
- frame_buffers = memnew_arr(MDFrameBuffer, frame_buffer_size);
for (int i = 0; i < frame_buffer_size; i++) {
frame_buffers[i].set_texture_count(1);
}
}
~SurfaceOffscreen() override {
- memdelete_arr(frame_buffers);
for (MTL::Texture *texture : textures) {
if (texture) {
texture->release();
@@ -299,7 +323,7 @@ public:
}
}
- Error resize(uint32_t p_desired_framebuffer_count, RDD::DataFormat &r_format, RDD::ColorSpace &r_color_space) override final {
+ Error resize(uint32_t p_desired_framebuffer_count, RDD::DataFormat &r_format, RDD::ColorSpace &r_color_space) override {
if (width == 0 || height == 0) {
// Very likely the window is minimized, don't create a swap chain.
return ERR_SKIP;
@@ -336,7 +360,7 @@ public:
return OK;
}
- RDD::FramebufferID acquire_next_frame_buffer() override final {
+ RDD::FramebufferID acquire_next_frame_buffer() override {
if (count.load(std::memory_order_relaxed) == 3) {
// Wait for a frame to be presented.
return RDD::FramebufferID();
@@ -345,7 +369,7 @@ public:
rear = (rear + 1) % 3;
count.fetch_add(1, std::memory_order_relaxed);
- MDFrameBuffer &frame_buffer = frame_buffers[rear];
+ MDFrameBufferTexture &frame_buffer = frame_buffers[rear];
MTL::Texture *texture = textures[rear];
if (texture == nullptr || texture->width() != width || texture->height() != height || texture->pixelFormat() != pixel_format) {
@@ -375,8 +399,8 @@ public:
return RDD::FramebufferID(&frame_buffers[rear]);
}
- void present(MTL3::MDCommandBuffer *p_cmd_buffer) override final {
- MDFrameBuffer *frame_buffer = &frame_buffers[rear];
+ void present(MTL3::MDCommandBuffer *p_cmd_buffer) override {
+ MDFrameBufferTexture *frame_buffer = &frame_buffers[rear];
if (drawables[rear] != nullptr) {
p_cmd_buffer->get_command_buffer()->presentDrawable(drawables[rear]);
@@ -389,12 +413,12 @@ public:
});
}
- MTL::Drawable *next_drawable() override final {
+ MTL::Drawable *next_drawable() override {
if (count == 0) {
return nullptr;
}
- MDFrameBuffer *frame_buffer = &frame_buffers[rear];
+ MDFrameBufferTexture *frame_buffer = &frame_buffers[rear];
MTL::Drawable *next = drawables[rear];
drawables[rear] = nullptr;
@@ -406,7 +430,7 @@ public:
}
API_AVAILABLE(macos(26.0), ios(26.0))
- MTL::ResidencySet *get_residency_set() const override final {
+ MTL::ResidencySet *get_residency_set() const override {
return layer->residencySet();
}
};
@@ -414,7 +438,7 @@ public:
#if TARGET_OS_VISION && defined(MODULE_VISIONOS_XR_ENABLED)
class SurfaceCompositorServices : public RenderingContextDriverMetal::Surface {
// Return a dummy framebuffer so present() is called on it, which relays the call to VisionOSXRInterface
- MDFrameBuffer dummy_framebuffer;
+ MDFrameBufferTexture dummy_framebuffer;
public:
SurfaceCompositorServices(MTL::Device *p_device) :
diff --git a/drivers/metal/rendering_device_driver_metal.cpp b/drivers/metal/rendering_device_driver_metal.cpp
index aedd8b09155..c8c93e0944d 100644
--- a/drivers/metal/rendering_device_driver_metal.cpp
+++ b/drivers/metal/rendering_device_driver_metal.cpp
@@ -150,8 +150,6 @@ RDD::BufferID RenderingDeviceDriverMetal::buffer_create(uint64_t p_size, BitFiel
}
*static_cast<MetalBuffer *>(buf_info) = buffer;
- _track_resource(buf_info->buffer.get());
-
return BufferID(buf_info);
}
@@ -163,8 +161,6 @@ bool RenderingDeviceDriverMetal::buffer_set_texel_format(BufferID p_buffer, Data
void RenderingDeviceDriverMetal::buffer_free(BufferID p_buffer) {
BufferInfo *buf_info = (BufferInfo *)p_buffer.id;
- _untrack_resource(buf_info->buffer.get());
-
allocator->free_buffer(*buf_info);
if (buf_info->is_dynamic()) {
@@ -431,12 +427,6 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create(const TextureFormat &p
ERR_FAIL_V_MSG(TextureID(), "Unable to create texture.");
}
- // 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(tex_info);
}
@@ -453,6 +443,8 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_from_extension(uint64_
return TextureID(tex_info);
}
+ tex_info->imported = true;
+
// 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) {
@@ -467,7 +459,15 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_from_extension(uint64_
tex_info->texture = NS::RetainPtr(res);
}
- _track_resource(tex_info->texture.get());
+ {
+ MutexLock lock(imported_textures_mutex);
+ imported_textures.push_back(tex_info->texture.get());
+ }
+
+ if (main_residency_set) {
+ main_residency_set->addAllocation(tex_info->texture.get());
+ main_residency_set->commit();
+ }
return TextureID(tex_info);
}
@@ -511,7 +511,6 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared(TextureID p_ori
#undef SWIZZLE
MTL::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);
TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
tex_info->texture = NS::TransferPtr(obj);
@@ -572,7 +571,6 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared_from_slice(Text
#undef SWIZZLE
MTL::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);
TextureInfo *tex_info = VersatileResource::allocate<TextureInfo>(resources_allocator);
tex_info->texture = NS::TransferPtr(obj);
@@ -581,10 +579,13 @@ RDD::TextureID RenderingDeviceDriverMetal::texture_create_shared_from_slice(Text
void RenderingDeviceDriverMetal::texture_free(TextureID p_texture) {
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());
+ if (tex_info->imported) {
+ MutexLock lock(imported_textures_mutex);
+ imported_textures.erase(tex_info->texture.get());
+
+ if (main_residency_set) {
+ main_residency_set->removeAllocation(tex_info->texture.get());
+ main_residency_set->commit();
}
}
allocator->free_texture(*tex_info);
@@ -965,10 +966,10 @@ void RenderingDeviceDriverMetal::_swap_chain_release_buffers(SwapChain *p_swap_c
RDD::SwapChainID RenderingDeviceDriverMetal::swap_chain_create(RenderingContextDriver::SurfaceID p_surface) {
const RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(p_surface);
- if (use_barriers) {
- GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wunguarded-availability")
- add_residency_set_to_main_queue(surface->get_residency_set());
- GODOT_CLANG_WARNING_POP
+ if (sync_mode != HazardTracking) {
+ if (__builtin_available(macOS 26.0, iOS 26.0, tvOS 26.0, visionOS 26.0, *)) {
+ add_residency_set_to_main_queue(surface->get_residency_set());
+ }
}
SwapChain *swap_chain = memnew(SwapChain);
@@ -1063,11 +1064,11 @@ void RenderingDeviceDriverMetal::swap_chain_set_max_fps(SwapChainID p_swap_chain
void RenderingDeviceDriverMetal::swap_chain_free(SwapChainID p_swap_chain) {
SwapChain *swap_chain = (SwapChain *)(p_swap_chain.id);
- if (use_barriers) {
- GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wunguarded-availability")
- RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
- remove_residency_set_to_main_queue(surface->get_residency_set());
- GODOT_CLANG_WARNING_POP
+ if (sync_mode != HazardTracking) {
+ if (__builtin_available(macOS 26.0, iOS 26.0, tvOS 26.0, visionOS 26.0, *)) {
+ RenderingContextDriverMetal::Surface *surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
+ remove_residency_set_to_main_queue(surface->get_residency_set());
+ }
}
_swap_chain_release(swap_chain);
memdelete(swap_chain);
@@ -1101,7 +1102,7 @@ RDD::FramebufferID RenderingDeviceDriverMetal::framebuffer_create(RenderPassID p
}
}
- MDFrameBuffer *fb = memnew(MDFrameBuffer(textures, Size2i(p_width, p_height)));
+ MDFrameBufferTexture *fb = memnew(MDFrameBufferTexture(textures, Size2i(p_width, p_height)));
fb->rasterization_rate_map = rasterization_rate_map;
return FramebufferID(fb);
}
@@ -1392,7 +1393,7 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Boun
}
};
#define ADD_USAGE(res, stage, usage) \
- if (!use_barriers) { \
+ if (sync_mode == HazardTracking) { \
add_usage(res, stage, usage); \
}
@@ -1489,7 +1490,7 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Boun
#undef ADD_USAGE
- if (!use_barriers) {
+ if (sync_mode == HazardTracking) {
for (const KeyValue<MTL::Resource *, StageResourceUsage> &keyval : bound_resources) {
ResourceVector *resources = set->usage_to_resources.getptr(keyval.value);
if (resources == nullptr) {
@@ -1509,7 +1510,6 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Boun
snprintf(label, sizeof(label), "Uniform Set %u", p_set_index);
set->arg_buffer.buffer->setLabel(NS::String::string(label, NS::UTF8StringEncoding));
#endif
- _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.
@@ -1531,9 +1531,6 @@ RDD::UniformSetID RenderingDeviceDriverMetal::uniform_set_create(VectorView<Boun
void RenderingDeviceDriverMetal::uniform_set_free(UniformSetID p_uniform_set) {
MDUniformSet *obj = (MDUniformSet *)p_uniform_set.id;
- if (obj->arg_buffer.buffer) {
- _untrack_resource(obj->arg_buffer.buffer.get());
- }
allocator->free_buffer(obj->arg_buffer);
memdelete(obj);
}
@@ -1687,10 +1684,10 @@ RDD::RenderPassID RenderingDeviceDriverMetal::render_pass_create(VectorView<Atta
size_t subpass_count = p_subpasses.size();
- Vector<MDSubpass> subpasses;
+ LocalVector<MDSubpass> subpasses;
subpasses.resize(subpass_count);
for (uint32_t i = 0; i < subpass_count; i++) {
- MDSubpass &subpass = subpasses.write[i];
+ MDSubpass &subpass = subpasses[i];
subpass.subpass_index = i;
subpass.view_count = p_view_count;
subpass.input_references = p_subpasses[i].input_references;
@@ -1711,12 +1708,12 @@ RDD::RenderPassID RenderingDeviceDriverMetal::render_pass_create(VectorView<Atta
MTL::StoreActionDontCare, // ATTACHMENT_STORE_OP_DONT_CARE
};
- Vector<MDAttachment> attachments;
+ LocalVector<MDAttachment> attachments;
attachments.resize(p_attachments.size());
for (uint32_t i = 0; i < p_attachments.size(); i++) {
const Attachment &a = p_attachments[i];
- MDAttachment &mda = attachments.write[i];
+ MDAttachment &mda = attachments[i];
MTL::PixelFormat format = pf.getMTLPixelFormat(a.format);
mda.format = format;
if (a.samples > TEXTURE_SAMPLES_1) {
@@ -1738,7 +1735,7 @@ RDD::RenderPassID RenderingDeviceDriverMetal::render_pass_create(VectorView<Atta
mda.type |= MDAttachmentType::Color;
}
}
- MDRenderPass *obj = memnew(MDRenderPass(attachments, subpasses));
+ MDRenderPass *obj = memnew(MDRenderPass(std::move(attachments), std::move(subpasses)));
return RenderPassID(obj);
}
@@ -2276,6 +2273,16 @@ RDD::PipelineID RenderingDeviceDriverMetal::render_pipeline_create(
// ----- COMMANDS -----
+void RenderingDeviceDriverMetal::command_begin_compute_pass(CommandBufferID p_cmd_buffer) {
+ MDCommandBufferBase *cb = (MDCommandBufferBase *)(p_cmd_buffer.id);
+ cb->compute_begin_pass();
+}
+
+void RenderingDeviceDriverMetal::command_end_compute_pass(CommandBufferID p_cmd_buffer) {
+ MDCommandBufferBase *cb = (MDCommandBufferBase *)(p_cmd_buffer.id);
+ cb->compute_end_pass();
+}
+
void RenderingDeviceDriverMetal::command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) {
MDCommandBufferBase *cb = (MDCommandBufferBase *)(p_cmd_buffer.id);
cb->bind_pipeline(p_pipeline);
@@ -2454,6 +2461,14 @@ void RenderingDeviceDriverMetal::command_end_label(CommandBufferID p_cmd_buffer)
cb->end_label();
}
+void RenderingDeviceDriverMetal::command_group_end(CommandBufferID p_cmd_buffer) {
+ MDCommandBufferBase *cb = (MDCommandBufferBase *)(p_cmd_buffer.id);
+ // Closing the encoder here is what guarantees no encoder straddles a level
+ // boundary, which is what makes per-encoder fences sufficient.
+ cb->end();
+ cb->advance_sync_level();
+}
+
#pragma mark - Debug
void RenderingDeviceDriverMetal::command_insert_breadcrumb(CommandBufferID p_cmd_buffer, uint32_t p_data) {
@@ -2586,7 +2601,6 @@ 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.buffer.get(), copy_queue_buffer_offset, p_dst_buffer, p_dst_offset, p_src_data.size());
_copy_queue_buffer_consume(p_src_data.size());
@@ -2597,16 +2611,12 @@ void RenderingDeviceDriverMetal::_copy_queue_flush() {
return;
}
- copy_queue_rs.get()->addAllocation(copy_queue_buffer.buffer.get());
- copy_queue_rs.get()->commit();
-
copy_queue_blit_encoder.get()->endEncoding();
copy_queue_blit_encoder.reset();
copy_queue_command_buffer.get()->commit();
copy_queue_command_buffer.get()->waitUntilCompleted();
copy_queue_command_buffer.reset();
copy_queue_buffer_offset = 0;
- copy_queue_rs.get()->removeAllAllocations();
}
Error RenderingDeviceDriverMetal::_copy_queue_initialize() {
@@ -2620,18 +2630,6 @@ Error RenderingDeviceDriverMetal::_copy_queue_initialize() {
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) {
- MTL::ResidencySetDescriptor *rs_desc = MTL::ResidencySetDescriptor::alloc()->init();
- rs_desc->setInitialCapacity(2);
- rs_desc->setLabel(MTLSTR("Copy Queue Residency Set"));
- NS::Error *error = nullptr;
- copy_queue_rs = NS::TransferPtr(device->newResidencySet(rs_desc, &error));
- rs_desc->release();
- copy_queue.get()->addResidencySet(copy_queue_rs.get());
- }
- }
-
return OK;
}
@@ -2765,8 +2763,12 @@ uint64_t RenderingDeviceDriverMetal::limit_get(Limit p_limit) {
uint64_t RenderingDeviceDriverMetal::api_trait_get(ApiTrait p_trait) {
switch (p_trait) {
case API_TRAIT_HONORS_PIPELINE_BARRIERS:
- return use_barriers;
- case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
+ return sync_mode == Barriers;
+ case API_TRAIT_BUFFER_CLEARS_WITH_COPY_ENGINE:
+ return true;
+ case API_TRAIT_TEXTURE_CLEARS_WITH_COPY_ENGINE:
+ return false;
+ case API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS:
return false;
default:
return RenderingDeviceDriver::api_trait_get(p_trait);
@@ -2856,6 +2858,12 @@ RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMet
archive_fail_on_miss = true;
}
+ // Barriers is the default; "none" selects native hazard tracking.
+ // Unrecognized values intentionally keep the default.
+ if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SYNC_MODE"); res == U"none") {
+ sync_mode = HazardTracking;
+ }
+
#if TARGET_OS_OSX
if (String res = OS::get_singleton()->get_environment("GODOT_MTL_SHADER_LOAD_STRATEGY"); res == U"lazy") {
_shader_load_strategy = ShaderLoadStrategy::LAZY;
@@ -2909,15 +2917,17 @@ Error RenderingDeviceDriverMetal::_create_device() {
return OK;
}
-void RenderingDeviceDriverMetal::_track_resource(MTL::Resource *p_resource) {
- if (use_barriers) {
- _residency_add.push_back(p_resource);
+void RenderingDeviceDriverMetal::encode_imported_resources(MTL::RenderCommandEncoder *p_enc) {
+ MutexLock lock(imported_textures_mutex);
+ if (!imported_textures.is_empty()) {
+ p_enc->useResources((const MTL::Resource *const *)imported_textures.ptr(), imported_textures.size(), MTL::ResourceUsageRead, MTL::RenderStageVertex | MTL::RenderStageFragment);
}
}
-void RenderingDeviceDriverMetal::_untrack_resource(MTL::Resource *p_resource) {
- if (use_barriers) {
- _residency_del.push_back(p_resource);
+void RenderingDeviceDriverMetal::encode_imported_resources(MTL::ComputeCommandEncoder *p_enc) {
+ MutexLock lock(imported_textures_mutex);
+ if (!imported_textures.is_empty()) {
+ p_enc->useResources((const MTL::Resource *const *)imported_textures.ptr(), imported_textures.size(), MTL::ResourceUsageRead);
}
}
@@ -2990,7 +3000,19 @@ Error RenderingDeviceDriverMetal::_initialize(uint32_t p_device_index, uint32_t
Error err = _create_device();
ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
- allocator = MetalAllocator::create(device, false);
+ // Must be resolved before the allocator is created, so use_heaps sees the
+ // final sync_mode.
+ _resolve_sync_mode();
+
+ // Must be created before _copy_queue_initialize(), which sources its scratch
+ // buffer from the allocator. Barriers mode implies heap suballocation:
+ // on Metal 3 it is the residency mechanism (useHeaps), and Metal 4 always
+ // runs barriers.
+ bool use_heaps = sync_mode == Barriers;
+ allocator = MetalAllocator::create(device, use_heaps);
+ if (use_heaps) {
+ print_verbose("Metal: heap suballocation enabled.");
+ }
device_properties = memnew(MetalDeviceProperties(device));
pixel_formats = memnew(PixelFormats(device, device_properties->features));
diff --git a/drivers/metal/rendering_device_driver_metal.h b/drivers/metal/rendering_device_driver_metal.h
index 49fe971a229..60e58619dda 100644
--- a/drivers/metal/rendering_device_driver_metal.h
+++ b/drivers/metal/rendering_device_driver_metal.h
@@ -67,6 +67,12 @@ class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) RenderingDeviceDriverMet
template <typename T>
using Result = std::variant<T, Error>;
+public:
+ enum SyncMode {
+ HazardTracking = 0,
+ Barriers,
+ };
+
#pragma mark - Generic
protected:
@@ -97,19 +103,11 @@ protected:
// DEV: When true, attempting to create a pipeline will fail if it cannot use the archive.
bool archive_fail_on_miss = false;
- /// Resources to be added to the `main_residency_set`.
- LocalVector<MTL::Resource *> _residency_add;
- /// Resources to be removed from the `main_residency_set`.
- LocalVector<MTL::Resource *> _residency_del;
-
#pragma mark - Copy Queue
Mutex copy_queue_mutex;
/// A command queue used for internal copy operations.
NS::SharedPtr<MTL::CommandQueue> copy_queue;
- GODOT_CLANG_WARNING_PUSH_AND_IGNORE("-Wunguarded-availability")
- NS::SharedPtr<MTL::ResidencySet> copy_queue_rs;
- GODOT_CLANG_WARNING_POP
// 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;
@@ -163,12 +161,24 @@ protected:
NS::SharedPtr<MTL::ResidencySet> main_residency_set;
GODOT_CLANG_WARNING_POP
- bool use_barriers = false;
+ SyncMode sync_mode = Barriers;
MTL::ResourceOptions base_hazard_tracking = MTL::ResourceHazardTrackingModeTracked;
+ /// Textures imported via texture_create_from_extension. They are not heap-backed,
+ /// so barriers mode must make them resident explicitly at encoder creation time.
+ Mutex imported_textures_mutex;
+ LocalVector<MTL::Texture *> imported_textures;
+
+public:
+ void encode_imported_resources(MTL::RenderCommandEncoder *p_enc);
+ void encode_imported_resources(MTL::ComputeCommandEncoder *p_enc);
+
+protected:
virtual Error _create_device();
- virtual void _track_resource(MTL::Resource *p_resource);
- virtual void _untrack_resource(MTL::Resource *p_resource);
+ /// Resolves the final sync_mode for this driver (may downgrade/upgrade
+ /// based on OS support). Called from _initialize() before the allocator
+ /// is created, so use_heaps sees the final value.
+ virtual void _resolve_sync_mode() {}
void _check_capabilities();
Error _initialize(uint32_t p_device_index, uint32_t p_frame_count);
@@ -230,6 +240,9 @@ public:
// 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;
+ // True for texture_create_from_extension imports (needs explicit
+ // residency in Metal 3 barriers mode; see encode_imported_resources).
+ bool imported = false;
};
virtual TextureID texture_create(const TextureFormat &p_format, const TextureView &p_view) override final;
@@ -460,6 +473,9 @@ public:
// ----- COMMANDS -----
+ virtual void command_begin_compute_pass(CommandBufferID p_cmd_buffer) override final;
+ virtual void command_end_compute_pass(CommandBufferID p_cmd_buffer) override final;
+
// Binding.
virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) override final;
virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) override final;
@@ -502,19 +518,20 @@ public:
// ----- TIMESTAMP -----
// Basic.
- virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override final;
- virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override final;
- virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override final;
- virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override final;
+ virtual QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override;
+ virtual void timestamp_query_pool_free(QueryPoolID p_pool_id) override;
+ virtual void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override;
+ virtual uint64_t timestamp_query_result_to_time(uint64_t p_result) override;
// Commands.
- virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override final;
- virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override final;
+ virtual void command_timestamp_query_pool_reset(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_query_count) override;
+ virtual void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override;
#pragma mark - Labels
virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) override final;
virtual void command_end_label(CommandBufferID p_cmd_buffer) override final;
+ virtual void command_group_end(CommandBufferID p_cmd_buffer) override final;
#pragma mark - Debug
diff --git a/drivers/metal/rendering_device_driver_metal3.cpp b/drivers/metal/rendering_device_driver_metal3.cpp
index 1fbd16fbd57..836d78e43bf 100644
--- a/drivers/metal/rendering_device_driver_metal3.cpp
+++ b/drivers/metal/rendering_device_driver_metal3.cpp
@@ -38,16 +38,20 @@
namespace MTL3 {
-#pragma mark - FenceEvent / FenceSemaphore
+#pragma mark - Fence
-void RenderingDeviceDriverMetal::FenceEvent::signal(MTL::CommandBuffer *p_cb) {
+void RenderingDeviceDriverMetal::Fence::signal(MTL::CommandBuffer *p_cb) {
if (p_cb) {
value++;
p_cb->encodeSignalEvent(event.get(), value);
}
}
-Error RenderingDeviceDriverMetal::FenceEvent::wait(uint32_t p_timeout_ms) {
+Error RenderingDeviceDriverMetal::Fence::wait(uint32_t p_timeout_ms) {
+ if (unlikely(value == 0)) {
+ WARN_PRINT_ONCE("Never signaled fence.");
+ return OK;
+ }
bool signaled = event->waitUntilSignaledValue(value, p_timeout_ms);
if (!signaled) {
#ifdef DEBUG_ENABLED
@@ -58,25 +62,6 @@ Error RenderingDeviceDriverMetal::FenceEvent::wait(uint32_t p_timeout_ms) {
return OK;
}
-void RenderingDeviceDriverMetal::FenceSemaphore::signal(MTL::CommandBuffer *p_cb) {
- if (p_cb) {
- p_cb->addCompletedHandler([this](MTL::CommandBuffer *) {
- dispatch_semaphore_signal(semaphore);
- });
- } else {
- dispatch_semaphore_signal(semaphore);
- }
-}
-
-Error RenderingDeviceDriverMetal::FenceSemaphore::wait(uint32_t p_timeout_ms) {
- dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, static_cast<int64_t>(p_timeout_ms) * 1000000);
- long result = dispatch_semaphore_wait(semaphore, timeout);
- if (result != 0) {
- return ERR_TIMEOUT;
- }
- return OK;
-}
-
#pragma mark - Constructor / Destructor
RenderingDeviceDriverMetal::RenderingDeviceDriverMetal(RenderingContextDriverMetal *p_context_driver) :
@@ -102,67 +87,43 @@ Error RenderingDeviceDriverMetal::_create_device() {
return OK;
}
+void RenderingDeviceDriverMetal::_resolve_sync_mode() {
+ if (sync_mode == Barriers) {
+ print_verbose("Metal 3: Barrier synchronization enabled.");
+ base_hazard_tracking = MTL::ResourceHazardTrackingModeUntracked;
+ // Apple GPUs only sample counters at stage boundaries, which is all the
+ // timestamp encoders rely on.
+ timestamp_queries_supported = device->supportsCounterSampling(MTL::CounterSamplingPointAtStageBoundary);
+ } else {
+ print_verbose("Metal 3: Native hazard tracking enabled.");
+ }
+}
+
Error RenderingDeviceDriverMetal::initialize(uint32_t p_device_index, uint32_t p_frame_count) {
Error err = _initialize(p_device_index, p_frame_count);
ERR_FAIL_COND_V(err, err);
- // Barriers are still experimental in Metal 3, so they are disabled by default
- // and can only be enabled via an environment variable.
- bool barriers_enabled = OS::get_singleton()->get_environment("GODOT_MTL_FORCE_BARRIERS") == "1";
- if (__builtin_available(macos 26.0, ios 26.0, tvos 26.0, visionos 26.0, *)) {
- if (barriers_enabled) {
- print_line("Metal 3: Resource barriers enabled.");
- NS::SharedPtr<MTL::ResidencySetDescriptor> rs_desc = NS::TransferPtr(MTL::ResidencySetDescriptor::alloc()->init());
- rs_desc->setInitialCapacity(250);
- rs_desc->setLabel(MTLSTR("Main Residency Set"));
- NS::Error *error = nullptr;
- NS::SharedPtr<MTL::ResidencySet> mrs = NS::TransferPtr(device->newResidencySet(rs_desc.get(), &error));
- if (!mrs) {
- String error_msg = error ? String(error->localizedDescription()->utf8String()) : "Unknown error";
- print_error(vformat("Resource barriers unavailable. Failed to create main residency set for explicit resource barriers: %s", error_msg));
- } else {
- use_barriers = true;
- base_hazard_tracking = MTL::ResourceHazardTrackingModeUntracked;
- main_residency_set = mrs;
- device_queue->addResidencySet(mrs.get());
- }
- }
- } else {
- if (barriers_enabled) {
- // Application or user has requested barriers, but the OS doesn't support them.
- print_verbose("Metal 3: Resource barriers are not supported on this OS version.");
- barriers_enabled = false;
- }
- }
-
return OK;
}
#pragma mark - Residency
void RenderingDeviceDriverMetal::add_residency_set_to_main_queue(MTL::ResidencySet *p_set) {
- device_queue->addResidencySet(p_set);
}
void RenderingDeviceDriverMetal::remove_residency_set_to_main_queue(MTL::ResidencySet *p_set) {
- device_queue->removeResidencySet(p_set);
}
#pragma mark - Fences
RDD::FenceID RenderingDeviceDriverMetal::fence_create() {
- Fence *fence = nullptr;
- if (__builtin_available(macOS 12.0, iOS 15.0, tvOS 15.0, visionOS 1.0, *)) {
- fence = memnew(FenceEvent(NS::TransferPtr(device->newSharedEvent())));
- } else {
- fence = memnew(FenceSemaphore());
- }
+ Fence *fence = memnew(Fence(NS::TransferPtr(device->newSharedEvent())));
return FenceID(fence);
}
Error RenderingDeviceDriverMetal::fence_wait(FenceID p_fence) {
Fence *fence = (Fence *)(p_fence.id);
- return fence->wait(1000);
+ return fence->wait(2000);
}
void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
@@ -173,7 +134,7 @@ void RenderingDeviceDriverMetal::fence_free(FenceID p_fence) {
#pragma mark - Semaphores
RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
- if (use_barriers) {
+ if (sync_mode != HazardTracking) {
Semaphore *sem = memnew(Semaphore(NS::TransferPtr(device->newEvent())));
return SemaphoreID(sem);
}
@@ -181,7 +142,7 @@ RDD::SemaphoreID RenderingDeviceDriverMetal::semaphore_create() {
}
void RenderingDeviceDriverMetal::semaphore_free(SemaphoreID p_semaphore) {
- if (use_barriers) {
+ if (sync_mode != HazardTracking) {
Semaphore *sem = (Semaphore *)(p_semaphore.id);
memdelete(sem);
}
@@ -199,22 +160,6 @@ Error RenderingDeviceDriverMetal::_execute_and_present_barriers(CommandQueueID p
return OK;
}
- bool changed = false;
- MTL::ResidencySet *mrs = main_residency_set.get();
- if (!_residency_add.is_empty()) {
- mrs->addAllocations(reinterpret_cast<const MTL::Allocation *const *>(_residency_add.ptr()), _residency_add.size());
- _residency_add.clear();
- changed = true;
- }
- if (!_residency_del.is_empty()) {
- mrs->removeAllocations(reinterpret_cast<const MTL::Allocation *const *>(_residency_del.ptr()), _residency_del.size());
- _residency_del.clear();
- changed = true;
- }
- if (changed) {
- mrs->commit();
- }
-
if (p_wait_sem.size() > 0) {
MTL::CommandBuffer *cb = device_queue->commandBuffer();
#ifdef DEV_ENABLED
@@ -241,42 +186,10 @@ Error RenderingDeviceDriverMetal::_execute_and_present_barriers(CommandQueueID p
fence->signal(cb);
}
- struct DrawRequest {
- NS::SharedPtr<MTL::Drawable> drawable;
- DisplayServerEnums::VSyncMode vsync_mode;
- double duration;
- };
-
- if (p_swap_chains.size() > 0) {
- Vector<DrawRequest> drawables;
- drawables.reserve(p_swap_chains.size());
-
- for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
- SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
- RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
- MTL::Drawable *drawable = metal_surface->next_drawable();
- if (drawable) {
- drawables.push_back(DrawRequest{
- .drawable = NS::RetainPtr(drawable),
- .vsync_mode = metal_surface->vsync_mode,
- .duration = metal_surface->present_minimum_duration,
- });
- }
- }
-
- MTL::CommandBuffer *cb = cmd_buffer->get_command_buffer();
- cb->addCompletedHandler([drawables = std::move(drawables)](MTL::CommandBuffer *) {
- for (const DrawRequest &dr : drawables) {
- switch (dr.vsync_mode) {
- case DisplayServerEnums::VSYNC_DISABLED: {
- dr.drawable->present();
- } break;
- default: {
- dr.drawable->presentAfterMinimumDuration(dr.duration);
- } break;
- }
- }
- });
+ for (uint32_t i = 0; i < p_swap_chains.size(); i++) {
+ SwapChain *swap_chain = (SwapChain *)(p_swap_chains[i].id);
+ RenderingContextDriverMetal::Surface *metal_surface = (RenderingContextDriverMetal::Surface *)(swap_chain->surface);
+ metal_surface->present(cmd_buffer);
}
cmd_buffer->commit();
@@ -327,7 +240,7 @@ Error RenderingDeviceDriverMetal::_execute_and_present(CommandQueueID p_cmd_queu
Error RenderingDeviceDriverMetal::command_queue_execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_sem, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_sem, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains) {
Error res;
- if (use_barriers) {
+ if (sync_mode != HazardTracking) {
res = _execute_and_present_barriers(p_cmd_queue, p_wait_sem, p_cmd_buffers, p_cmd_sem, p_cmd_fence, p_swap_chains);
} else {
res = _execute_and_present(p_cmd_queue, p_wait_sem, p_cmd_buffers, p_cmd_sem, p_cmd_fence, p_swap_chains);
@@ -362,6 +275,49 @@ void RenderingDeviceDriverMetal::command_pool_free(CommandPoolID p_cmd_pool) {
// Nothing to free - the device_queue is managed by SharedPtr.
}
+#pragma mark - Timestamp
+
+RDD::QueryPoolID RenderingDeviceDriverMetal::timestamp_query_pool_create(uint32_t p_query_count) {
+ if (timestamp_queries_supported) {
+ QueryPool *pool = QueryPool::create(device, p_query_count);
+ if (pool != nullptr) {
+ return QueryPoolID(pool);
+ }
+ WARN_PRINT_ONCE("Metal 3: The device does not expose the timestamp counter set; GPU timestamps are unavailable.");
+ timestamp_queries_supported = false;
+ }
+ return ::RenderingDeviceDriverMetal::timestamp_query_pool_create(p_query_count);
+}
+
+void RenderingDeviceDriverMetal::timestamp_query_pool_free(QueryPoolID p_pool_id) {
+ if (!timestamp_queries_supported) {
+ return ::RenderingDeviceDriverMetal::timestamp_query_pool_free(p_pool_id);
+ }
+ QueryPool *pool = (QueryPool *)(p_pool_id.id);
+ memdelete(pool);
+}
+
+void RenderingDeviceDriverMetal::timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) {
+ if (!timestamp_queries_supported) {
+ return ::RenderingDeviceDriverMetal::timestamp_query_pool_get_results(p_pool_id, p_query_count, r_results);
+ }
+ QueryPool *pool = (QueryPool *)(p_pool_id.id);
+ pool->get_results(p_query_count, r_results);
+}
+
+uint64_t RenderingDeviceDriverMetal::timestamp_query_result_to_time(uint64_t p_result) {
+ return p_result; // Already converted to nanoseconds in get_results.
+}
+
+void RenderingDeviceDriverMetal::command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) {
+ if (!timestamp_queries_supported) {
+ return ::RenderingDeviceDriverMetal::command_timestamp_write(p_cmd_buffer, p_pool_id, p_index);
+ }
+ MDCommandBuffer *cmd = (MDCommandBuffer *)(p_cmd_buffer.id);
+ QueryPool *pool = (QueryPool *)(p_pool_id.id);
+ cmd->timestamp_write(pool, p_index);
+}
+
#pragma mark - Command Buffers
RDD::CommandBufferID RenderingDeviceDriverMetal::command_buffer_create(CommandPoolID p_cmd_pool) {
diff --git a/drivers/metal/rendering_device_driver_metal3.h b/drivers/metal/rendering_device_driver_metal3.h
index d87fa438ac5..659b5be92e4 100644
--- a/drivers/metal/rendering_device_driver_metal3.h
+++ b/drivers/metal/rendering_device_driver_metal3.h
@@ -44,26 +44,12 @@ class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) RenderingDeviceDriverMet
NS::SharedPtr<MTL::CommandQueue> device_queue;
struct Fence {
- virtual void signal(MTL::CommandBuffer *p_cmd_buffer) = 0;
- virtual Error wait(uint32_t p_timeout_ms) = 0;
- virtual ~Fence() = default;
- };
-
- struct FenceEvent : Fence {
NS::SharedPtr<MTL::SharedEvent> event;
uint64_t value = 0;
- FenceEvent(NS::SharedPtr<MTL::SharedEvent> p_event) :
+ Fence(NS::SharedPtr<MTL::SharedEvent> p_event) :
event(p_event) {}
- void signal(MTL::CommandBuffer *p_cb) override;
- Error wait(uint32_t p_timeout_ms) override;
- };
-
- struct FenceSemaphore : Fence {
- dispatch_semaphore_t semaphore;
- FenceSemaphore() :
- semaphore(dispatch_semaphore_create(0)) {}
- void signal(MTL::CommandBuffer *p_cb) override;
- Error wait(uint32_t p_timeout_ms) override;
+ void signal(MTL::CommandBuffer *p_cb);
+ Error wait(uint32_t p_timeout_ms);
};
struct Semaphore {
@@ -75,14 +61,19 @@ class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) RenderingDeviceDriverMet
Vector<MDCommandBuffer *> command_buffers;
- Error _create_device() override;
+ // GPU timestamps require barrier synchronization, so the level fences order the
+ // timestamp encoders against the work they bracket.
+ bool timestamp_queries_supported = false;
+
Error _execute_and_present_barriers(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains);
Error _execute_and_present(CommandQueueID p_cmd_queue, VectorView<SemaphoreID> p_wait_semaphores, VectorView<CommandBufferID> p_cmd_buffers, VectorView<SemaphoreID> p_cmd_semaphores, FenceID p_cmd_fence, VectorView<SwapChainID> p_swap_chains);
protected:
+ Error _create_device() override;
+ void _resolve_sync_mode() override;
MTL::CommandQueue *get_command_queue() const override { return device_queue.get(); }
- void add_residency_set_to_main_queue(MTL::ResidencySet *p_set) override;
- void remove_residency_set_to_main_queue(MTL::ResidencySet *p_set) override;
+ void add_residency_set_to_main_queue(MTL::ResidencySet *p_set) override API_AVAILABLE(macos(15.0), ios(18.0), tvos(18.0), visionos(2.0));
+ void remove_residency_set_to_main_queue(MTL::ResidencySet *p_set) override API_AVAILABLE(macos(15.0), ios(18.0), tvos(18.0), visionos(2.0));
public:
Error initialize(uint32_t p_device_index, uint32_t p_frame_count) override;
@@ -104,6 +95,14 @@ public:
CommandBufferID command_buffer_create(CommandPoolID p_cmd_pool) override;
+#pragma mark - Timestamp
+
+ QueryPoolID timestamp_query_pool_create(uint32_t p_query_count) override;
+ void timestamp_query_pool_free(QueryPoolID p_pool_id) override;
+ void timestamp_query_pool_get_results(QueryPoolID p_pool_id, uint32_t p_query_count, uint64_t *r_results) override;
+ uint64_t timestamp_query_result_to_time(uint64_t p_result) override;
+ void command_timestamp_write(CommandBufferID p_cmd_buffer, QueryPoolID p_pool_id, uint32_t p_index) override;
+
#pragma mark - Miscellaneous
String get_api_name() const override { return "Metal"; }
diff --git a/servers/rendering/renderer_rd/effects/metal_fx.cpp b/servers/rendering/renderer_rd/effects/metal_fx.cpp
index e596ae91bec..4076d0bee50 100644
--- a/servers/rendering/renderer_rd/effects/metal_fx.cpp
+++ b/servers/rendering/renderer_rd/effects/metal_fx.cpp
@@ -62,6 +62,7 @@ void MFXSpatialEffect::callback(RDD *p_driver, RDD::CommandBufferID p_command_bu
MTL::Texture *dst_texture = reinterpret_cast<MTL::Texture *>(p_userdata->dst.id);
MTLFX::SpatialScalerBase *scaler = p_userdata->scaler;
+ scaler->setFence(obj->external_pass_fence());
scaler->setColorTexture(src_texture);
scaler->setOutputTexture(dst_texture);
MTLFX::SpatialScaler *s = static_cast<MTLFX::SpatialScaler *>(scaler);
@@ -170,12 +171,15 @@ void MFXTemporalEffect::process(RendererRD::MFXTemporalContext *p_ctx, RendererR
RDD::TextureID(RD::get_singleton()->get_driver_resource(RDC::DRIVER_RESOURCE_TEXTURE, p_params.dst)),
*p_ctx,
p_params.reset);
- RD::CallbackResource res[3] = {
+ RD::CallbackResource res[5] = {
{ .rid = p_params.src, .usage = RD::CALLBACK_RESOURCE_USAGE_TEXTURE_SAMPLE },
{ .rid = p_params.depth, .usage = RD::CALLBACK_RESOURCE_USAGE_TEXTURE_SAMPLE },
+ { .rid = p_params.motion, .usage = RD::CALLBACK_RESOURCE_USAGE_TEXTURE_SAMPLE },
{ .rid = p_params.dst, .usage = RD::CALLBACK_RESOURCE_USAGE_STORAGE_IMAGE_READ_WRITE },
+ { .rid = p_params.exposure, .usage = RD::CALLBACK_RESOURCE_USAGE_TEXTURE_SAMPLE },
};
- RD::get_singleton()->driver_callback_add((RDD::DriverCallback)MFXTemporalEffect::callback, userdata, VectorView<RD::CallbackResource>(res, 3));
+ uint32_t res_count = p_params.exposure.is_valid() ? 5 : 4;
+ RD::get_singleton()->driver_callback_add((RDD::DriverCallback)MFXTemporalEffect::callback, userdata, VectorView<RD::CallbackResource>(res, res_count));
}
void MFXTemporalEffect::callback(RDD *p_driver, RDD::CommandBufferID p_command_buffer, CallbackArgs *p_userdata) {
@@ -190,6 +194,7 @@ void MFXTemporalEffect::callback(RDD *p_driver, RDD::CommandBufferID p_command_b
MTL::Texture *dst_texture = reinterpret_cast<MTL::Texture *>(p_userdata->dst.id);
MTLFX::TemporalScalerBase *scaler = p_userdata->scaler;
+ scaler->setFence(obj->external_pass_fence());
scaler->setReset(p_userdata->reset);
scaler->setColorTexture(src_texture);
scaler->setDepthTexture(depth);
diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp
index 719cdb249ca..f6c2edf549c 100644
--- a/servers/rendering/rendering_device.cpp
+++ b/servers/rendering/rendering_device.cpp
@@ -153,6 +153,34 @@ static RD::HitShaderBindingTableRange _encode_hit_sbt_range(uint32_t p_offset, u
#define SECONDARY_COMMAND_BUFFERS_PER_FRAME 0
+#ifdef DEBUG_ENABLED
+
+// The settings above can also be overridden at runtime with environment variables for debugging purposes.
+
+void RenderingDevice::_configure_draw_graph_flags() {
+ draw_graph_reorder_commands = (RENDER_GRAPH_REORDER == 1);
+ draw_graph_full_barriers = (RENDER_GRAPH_FULL_BARRIERS == 1);
+
+ String reorder = OS::get_singleton()->get_environment("GODOT_RG_REORDER");
+ String full_barriers = OS::get_singleton()->get_environment("GODOT_RG_FULL_BARRIERS");
+
+ if (!reorder.is_empty()) {
+ draw_graph_reorder_commands = (reorder == "1");
+ }
+ if (!full_barriers.is_empty()) {
+ draw_graph_full_barriers = (full_barriers == "1");
+ }
+
+ if (!draw_graph_reorder_commands) {
+ print_line("RG: Disable reordering");
+ }
+ if (draw_graph_full_barriers) {
+ print_line("RG: Enable full barriers");
+ }
+}
+
+#endif
+
RenderingDevice *RenderingDevice::singleton = nullptr;
RenderingDevice *RenderingDevice::get_singleton() {
@@ -914,6 +942,9 @@ Error RenderingDevice::_insert_staging_block(StagingBuffers &p_staging_buffers)
block.driver_id = driver->buffer_create(p_staging_buffers.block_size, p_staging_buffers.usage_bits, RDD::MEMORY_ALLOCATION_TYPE_CPU, frames_drawn);
ERR_FAIL_COND_V(!block.driver_id, ERR_CANT_CREATE);
+#if DEV_ENABLED
+ driver->set_object_name(RDD::OBJECT_TYPE_BUFFER, block.driver_id, "Staging");
+#endif
block.frame_used = 0;
block.fill_amount = 0;
@@ -2166,7 +2197,7 @@ Error RenderingDevice::_texture_initialize(RID p_texture, uint32_t p_layer, cons
write_ptr = driver->buffer_map(transfer_worker->staging_buffer);
ERR_FAIL_NULL_V(write_ptr, ERR_CANT_CREATE);
- if (driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
+ if (driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS) && driver->api_trait_get(RDD::API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS)) {
// Transition the texture to the optimal layout.
RDD::TextureBarrier tb;
tb.texture = texture->driver_id;
@@ -2233,7 +2264,7 @@ Error RenderingDevice::_texture_initialize(RID p_texture, uint32_t p_layer, cons
driver->buffer_unmap(transfer_worker->staging_buffer);
// If the texture does not have a tracker, it means it must be transitioned to the sampling state.
- if (texture->draw_tracker == nullptr && driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS)) {
+ if (texture->draw_tracker == nullptr && driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS) && driver->api_trait_get(RDD::API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS)) {
RDD::TextureBarrier tb;
tb.texture = texture->driver_id;
tb.src_access = RDD::BARRIER_ACCESS_COPY_WRITE_BIT;
@@ -8182,8 +8213,16 @@ void RenderingDevice::_end_frame() {
GodotProfileZoneGrouped(_profile_zone, "_submit_transfer_barriers");
_submit_transfer_barriers(command_buffer);
+#ifdef DEBUG_ENABLED
+ bool reorder_commands = draw_graph_reorder_commands;
+ bool full_barriers = draw_graph_full_barriers;
+#else
+ constexpr bool reorder_commands = (RENDER_GRAPH_REORDER == 1);
+ constexpr bool full_barriers = (RENDER_GRAPH_FULL_BARRIERS == 1);
+#endif
+
GodotProfileZoneGrouped(_profile_zone, "draw_graph.end");
- draw_graph.end(RENDER_GRAPH_REORDER == 1, RENDER_GRAPH_FULL_BARRIERS == 1, command_buffer, frames[frame].command_buffer_pool);
+ draw_graph.end(reorder_commands, full_barriers, command_buffer, frames[frame].command_buffer_pool);
GodotProfileZoneGrouped(_profile_zone, "driver->command_buffer_end");
driver->command_buffer_end(command_buffer);
GodotProfileZoneGrouped(_profile_zone, "driver->end_segment");
@@ -8589,6 +8628,11 @@ Error RenderingDevice::initialize(RenderingContextDriver *p_context, DisplayServ
driver->command_buffer_begin(frames[0].command_buffer);
// Create draw graph and start it initialized as well.
+
+#ifdef DEBUG_ENABLED
+ _configure_draw_graph_flags();
+#endif
+
draw_graph.initialize(driver, &_render_pass_create_from_graph, frames.size(), main_queue_family, SECONDARY_COMMAND_BUFFERS_PER_FRAME);
draw_graph.begin();
diff --git a/servers/rendering/rendering_device.h b/servers/rendering/rendering_device.h
index f99204e6d20..8abcd1b6f9c 100644
--- a/servers/rendering/rendering_device.h
+++ b/servers/rendering/rendering_device.h
@@ -1753,6 +1753,13 @@ private:
RenderingDeviceGraph draw_graph;
+#ifdef DEBUG_ENABLED
+ bool draw_graph_reorder_commands = true;
+ bool draw_graph_full_barriers = false;
+
+ void _configure_draw_graph_flags();
+#endif
+
/**************************/
/**** QUEUE MANAGEMENT ****/
/**************************/
diff --git a/servers/rendering/rendering_device_driver.cpp b/servers/rendering/rendering_device_driver.cpp
index abc57e44167..1fc530fa2e8 100644
--- a/servers/rendering/rendering_device_driver.cpp
+++ b/servers/rendering/rendering_device_driver.cpp
@@ -47,12 +47,16 @@ uint64_t RenderingDeviceDriver::api_trait_get(ApiTrait p_trait) {
return 1;
case API_TRAIT_SECONDARY_VIEWPORT_SCISSOR:
return 1;
- case API_TRAIT_CLEARS_WITH_COPY_ENGINE:
+ case API_TRAIT_BUFFER_CLEARS_WITH_COPY_ENGINE:
+ return true;
+ case API_TRAIT_TEXTURE_CLEARS_WITH_COPY_ENGINE:
return true;
case API_TRAIT_USE_GENERAL_IN_COPY_QUEUES:
return false;
case API_TRAIT_BUFFERS_REQUIRE_TRANSITIONS:
return false;
+ case API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS:
+ return true;
case API_TRAIT_TEXTURE_OUTPUTS_REQUIRE_CLEARS:
return false;
default:
@@ -62,4 +66,10 @@ uint64_t RenderingDeviceDriver::api_trait_get(ApiTrait p_trait) {
/******************/
+void RenderingDeviceDriver::command_begin_compute_pass(CommandBufferID p_cmd_buffer) {
+}
+
+void RenderingDeviceDriver::command_end_compute_pass(CommandBufferID p_cmd_buffer) {
+}
+
RenderingDeviceDriver::~RenderingDeviceDriver() {}
diff --git a/servers/rendering/rendering_device_driver.h b/servers/rendering/rendering_device_driver.h
index 9de349b61f0..c9d566f215f 100644
--- a/servers/rendering/rendering_device_driver.h
+++ b/servers/rendering/rendering_device_driver.h
@@ -728,6 +728,9 @@ public:
// ----- COMMANDS -----
+ virtual void command_begin_compute_pass(CommandBufferID p_cmd_buffer);
+ virtual void command_end_compute_pass(CommandBufferID p_cmd_buffer);
+
// Binding.
virtual void command_bind_compute_pipeline(CommandBufferID p_cmd_buffer, PipelineID p_pipeline) = 0;
virtual void command_bind_compute_uniform_sets(CommandBufferID p_cmd_buffer, VectorView<UniformSetID> p_uniform_sets, ShaderID p_shader, uint32_t p_first_set_index, uint32_t p_set_count, uint32_t p_dynamic_offsets) = 0;
@@ -840,6 +843,12 @@ public:
virtual void command_begin_label(CommandBufferID p_cmd_buffer, const char *p_label_name, const Color &p_color) = 0;
virtual void command_end_label(CommandBufferID p_cmd_buffer) = 0;
+ // Marks the start/end of a coherent batch of commands. Drivers may use this
+ // to flush incidental encoder state (e.g. a still-open blit encoder used for
+ // housekeeping copies) so subsequent commands start fresh. Default no-op.
+ virtual void command_group_begin(CommandBufferID p_cmd_buffer) {}
+ virtual void command_group_end(CommandBufferID p_cmd_buffer) {}
+
/****************/
/**** DEBUG *****/
/****************/
@@ -901,9 +910,11 @@ public:
API_TRAIT_TEXTURE_TRANSFER_ALIGNMENT,
API_TRAIT_TEXTURE_DATA_ROW_PITCH_STEP,
API_TRAIT_SECONDARY_VIEWPORT_SCISSOR,
- API_TRAIT_CLEARS_WITH_COPY_ENGINE,
+ API_TRAIT_BUFFER_CLEARS_WITH_COPY_ENGINE,
+ API_TRAIT_TEXTURE_CLEARS_WITH_COPY_ENGINE,
API_TRAIT_USE_GENERAL_IN_COPY_QUEUES,
API_TRAIT_BUFFERS_REQUIRE_TRANSITIONS,
+ API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS,
API_TRAIT_TEXTURE_OUTPUTS_REQUIRE_CLEARS,
API_TRAIT_ACCELERATION_STRUCTURE_INSTANCE_SIZE,
API_TRAIT_SHADER_GROUP_HANDLE_SIZE,
diff --git a/servers/rendering/rendering_device_graph.cpp b/servers/rendering/rendering_device_graph.cpp
index ae6a1e1b747..5518a039785 100644
--- a/servers/rendering/rendering_device_graph.cpp
+++ b/servers/rendering/rendering_device_graph.cpp
@@ -40,7 +40,10 @@
RenderingDeviceGraph::RenderingDeviceGraph() {
driver_honors_barriers = false;
- driver_clears_with_copy_engine = false;
+ driver_buffer_clears_with_copy_engine = false;
+ driver_texture_clears_with_copy_engine = false;
+ driver_buffers_require_transitions = false;
+ driver_textures_require_layout_transitions = false;
}
RenderingDeviceGraph::~RenderingDeviceGraph() {
@@ -84,8 +87,16 @@ String RenderingDeviceGraph::_usage_to_string(ResourceUsage p_usage) {
return "Attachment Color Read Write";
case RESOURCE_USAGE_ATTACHMENT_DEPTH_STENCIL_READ_WRITE:
return "Attachment Depth Stencil Read Write";
+ case RESOURCE_USAGE_ATTACHMENT_FRAGMENT_SHADING_RATE_READ:
+ return "Attachment Fragment Shading Rate Read";
+ case RESOURCE_USAGE_ATTACHMENT_FRAGMENT_DENSITY_MAP_READ:
+ return "Attachment Fragment Density Map Read";
case RESOURCE_USAGE_GENERAL:
return "General";
+ case RESOURCE_USAGE_ACCELERATION_STRUCTURE_READ:
+ return "Acceleration Structure Read";
+ case RESOURCE_USAGE_ACCELERATION_STRUCTURE_READ_WRITE:
+ return "Acceleration Structure Read Write";
default:
ERR_FAIL_V_MSG("Invalid", vformat("Invalid resource usage %d.", p_usage));
}
@@ -629,8 +640,8 @@ void RenderingDeviceGraph::_add_command_to_graph(ResourceTracker **p_resource_tr
if (different_usage) {
// Even if the usage of the resource isn't a write usage explicitly, a different usage implies a transition and it should therefore be considered a write.
- // In the case of buffers however, this is not exactly necessary if the driver does not consider different buffer usages as different states.
- write_usage = write_usage || bool(resource_tracker->texture_driver_id) || driver_buffers_require_transitions;
+ // However, this is not necessary if the driver does not consider different usages as different states (e.g. no image layouts).
+ write_usage = write_usage || (driver_textures_require_layout_transitions && bool(resource_tracker->texture_driver_id)) || driver_buffers_require_transitions;
resource_tracker->usage = new_resource_usage;
}
@@ -1101,6 +1112,7 @@ void RenderingDeviceGraph::_wait_for_secondary_command_buffer_tasks() {
}
void RenderingDeviceGraph::_run_render_commands(int32_t p_level, const RecordedCommandSort *p_sorted_commands, uint32_t p_sorted_commands_count, RDD::CommandBufferID &r_command_buffer, CommandBufferPool &r_command_buffer_pool, int32_t &r_current_label_index, int32_t &r_current_label_level) {
+ driver->command_group_begin(r_command_buffer);
for (uint32_t i = 0; i < p_sorted_commands_count; i++) {
const uint32_t command_index = p_sorted_commands[i].index;
const uint32_t command_data_offset = command_data_offsets[command_index];
@@ -1165,7 +1177,9 @@ void RenderingDeviceGraph::_run_render_commands(int32_t p_level, const RecordedC
}
const RecordedComputeListCommand *compute_list_command = reinterpret_cast<const RecordedComputeListCommand *>(command);
+ driver->command_begin_compute_pass(r_command_buffer);
_run_compute_list_command(r_command_buffer, compute_list_command->instruction_data(), compute_list_command->instruction_data_size);
+ driver->command_end_compute_pass(r_command_buffer);
} break;
case RecordedCommand::TYPE_DRAW_LIST: {
if (driver_workarounds.avoid_compute_after_draw) {
@@ -1250,6 +1264,7 @@ void RenderingDeviceGraph::_run_render_commands(int32_t p_level, const RecordedC
}
}
}
+ driver->command_group_end(r_command_buffer);
}
void RenderingDeviceGraph::_run_label_command_change(RDD::CommandBufferID p_command_buffer, int32_t p_new_label_index, int32_t p_new_level, bool p_ignore_previous_value, bool p_use_label_for_empty, const RecordedCommandSort *p_sorted_commands, uint32_t p_sorted_commands_count, int32_t &r_current_label_index, int32_t &r_current_label_level) {
@@ -1761,8 +1776,10 @@ void RenderingDeviceGraph::initialize(RDD *p_driver, RenderPassCreationFunction
}
driver_honors_barriers = driver->api_trait_get(RDD::API_TRAIT_HONORS_PIPELINE_BARRIERS);
- driver_clears_with_copy_engine = driver->api_trait_get(RDD::API_TRAIT_CLEARS_WITH_COPY_ENGINE);
+ driver_buffer_clears_with_copy_engine = driver->api_trait_get(RDD::API_TRAIT_BUFFER_CLEARS_WITH_COPY_ENGINE);
+ driver_texture_clears_with_copy_engine = driver->api_trait_get(RDD::API_TRAIT_TEXTURE_CLEARS_WITH_COPY_ENGINE);
driver_buffers_require_transitions = driver->api_trait_get(RDD::API_TRAIT_BUFFERS_REQUIRE_TRANSITIONS);
+ driver_textures_require_layout_transitions = driver->api_trait_get(RDD::API_TRAIT_TEXTURES_REQUIRE_LAYOUT_TRANSITIONS);
}
void RenderingDeviceGraph::finalize() {
@@ -1878,7 +1895,7 @@ void RenderingDeviceGraph::add_buffer_clear(RDD::BufferID p_dst, ResourceTracker
command->size = p_size;
ResourceUsage usage;
- if (driver_clears_with_copy_engine) {
+ if (driver_buffer_clears_with_copy_engine) {
command->self_stages = RDD::PIPELINE_STAGE_COPY_BIT;
usage = RESOURCE_USAGE_COPY_TO;
} else {
@@ -2430,7 +2447,7 @@ void RenderingDeviceGraph::add_texture_clear_color(RDD::TextureID p_dst, Resourc
command->range = p_range;
ResourceUsage usage;
- if (driver_clears_with_copy_engine) {
+ if (driver_texture_clears_with_copy_engine) {
command->self_stages = RDD::PIPELINE_STAGE_COPY_BIT;
usage = RESOURCE_USAGE_COPY_TO;
} else {
@@ -2460,7 +2477,7 @@ void RenderingDeviceGraph::add_texture_clear_depth_stencil(RDD::TextureID p_dst,
command->range = p_range;
ResourceUsage usage;
- if (driver_clears_with_copy_engine) {
+ if (driver_texture_clears_with_copy_engine) {
command->self_stages = RDD::PIPELINE_STAGE_COPY_BIT;
usage = RESOURCE_USAGE_COPY_TO;
} else {
diff --git a/servers/rendering/rendering_device_graph.h b/servers/rendering/rendering_device_graph.h
index 1c98a8654bc..3c0215f14ea 100644
--- a/servers/rendering/rendering_device_graph.h
+++ b/servers/rendering/rendering_device_graph.h
@@ -843,8 +843,10 @@ private:
bool command_synchronization_pending = false;
BarrierGroup barrier_group;
bool driver_honors_barriers : 1;
- bool driver_clears_with_copy_engine : 1;
+ bool driver_buffer_clears_with_copy_engine : 1;
+ bool driver_texture_clears_with_copy_engine : 1;
bool driver_buffers_require_transitions : 1;
+ bool driver_textures_require_layout_transitions : 1;
WorkaroundsState workarounds_state;
TightLocalVector<Frame> frames;
uint32_t frame = 0;
diff --git a/thirdparty/README.md b/thirdparty/README.md
index 4f09953afe6..fbc5cd4fb7a 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -882,6 +882,18 @@ Patches:
- `0001-remove-unused-save-features.patch` ([GH-113965](https://github.com/godotengine/godot/issues/113965))
+## offset_allocator
+
+- Upstream: https://github.com/sebbbi/OffsetAllocator
+- Version: git (3610a7377088b1e8c8f1525f458c96038a4e6fc0, 2026)
+- License: MIT
+
+Files extracted from upstream source:
+
+- `offsetAllocator.cpp`, `offsetAllocator.hpp`
+- `LICENSE`
+
+
## openxr
- Upstream: https://github.com/KhronosGroup/OpenXR-SDK
diff --git a/thirdparty/offset_allocator/LICENSE b/thirdparty/offset_allocator/LICENSE
new file mode 100644
index 00000000000..60cd17caf90
--- /dev/null
+++ b/thirdparty/offset_allocator/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Sebastian Aaltonen
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/thirdparty/offset_allocator/apply-patches.sh b/thirdparty/offset_allocator/apply-patches.sh
new file mode 100755
index 00000000000..295b1aa0711
--- /dev/null
+++ b/thirdparty/offset_allocator/apply-patches.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+set -eu
+
+script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+repository_root=$(CDPATH= cd -- "$script_dir/../.." && pwd)
+
+for patch in "$script_dir"/patches/*.patch; do
+ printf 'Applying %s\n' "$(basename -- "$patch")"
+ git -C "$repository_root" apply --check "$patch"
+ git -C "$repository_root" apply "$patch"
+done
diff --git a/thirdparty/offset_allocator/offsetAllocator.cpp b/thirdparty/offset_allocator/offsetAllocator.cpp
new file mode 100644
index 00000000000..4da3d7fd96b
--- /dev/null
+++ b/thirdparty/offset_allocator/offsetAllocator.cpp
@@ -0,0 +1,492 @@
+// (C) Sebastian Aaltonen 2023
+// MIT License (see file: LICENSE)
+
+#include "offsetAllocator.hpp"
+
+#ifdef DEBUG
+#include <assert.h>
+#define ASSERT(x) assert(x)
+//#define DEBUG_VERBOSE
+#else
+#define ASSERT(x)
+#endif
+
+#ifdef DEBUG_VERBOSE
+#include <stdio.h>
+#endif
+
+#ifdef _MSC_VER
+#include <intrin.h>
+#endif
+
+#include <cstring>
+
+namespace OffsetAllocator
+{
+ inline uint32 lzcnt_nonzero(uint32 v)
+ {
+#ifdef _MSC_VER
+ unsigned long retVal;
+ _BitScanReverse(&retVal, v);
+ return 31 - retVal;
+#else
+ return __builtin_clz(v);
+#endif
+ }
+
+ inline uint32 tzcnt_nonzero(uint32 v)
+ {
+#ifdef _MSC_VER
+ unsigned long retVal;
+ _BitScanForward(&retVal, v);
+ return retVal;
+#else
+ return __builtin_ctz(v);
+#endif
+ }
+
+ namespace SmallFloat
+ {
+ static constexpr uint32 MANTISSA_BITS = 3;
+ static constexpr uint32 MANTISSA_VALUE = 1 << MANTISSA_BITS;
+ static constexpr uint32 MANTISSA_MASK = MANTISSA_VALUE - 1;
+
+ // Bin sizes follow floating point (exponent + mantissa) distribution (piecewise linear log approx)
+ // This ensures that for each size class, the average overhead percentage stays the same
+ uint32 uintToFloatRoundUp(uint32 size)
+ {
+ uint32 exp = 0;
+ uint32 mantissa = 0;
+
+ if (size < MANTISSA_VALUE)
+ {
+ // Denorm: 0..(MANTISSA_VALUE-1)
+ mantissa = size;
+ }
+ else
+ {
+ // Normalized: Hidden high bit always 1. Not stored. Just like float.
+ uint32 leadingZeros = lzcnt_nonzero(size);
+ uint32 highestSetBit = 31 - leadingZeros;
+
+ uint32 mantissaStartBit = highestSetBit - MANTISSA_BITS;
+ exp = mantissaStartBit + 1;
+ mantissa = (size >> mantissaStartBit) & MANTISSA_MASK;
+
+ uint32 lowBitsMask = (uint32(1) << mantissaStartBit) - 1;
+
+ // Round up!
+ if ((size & lowBitsMask) != 0)
+ mantissa++;
+ }
+
+ return (exp << MANTISSA_BITS) + mantissa; // + allows mantissa->exp overflow for round up
+ }
+
+ uint32 uintToFloatRoundDown(uint32 size)
+ {
+ uint32 exp = 0;
+ uint32 mantissa = 0;
+
+ if (size < MANTISSA_VALUE)
+ {
+ // Denorm: 0..(MANTISSA_VALUE-1)
+ mantissa = size;
+ }
+ else
+ {
+ // Normalized: Hidden high bit always 1. Not stored. Just like float.
+ uint32 leadingZeros = lzcnt_nonzero(size);
+ uint32 highestSetBit = 31 - leadingZeros;
+
+ uint32 mantissaStartBit = highestSetBit - MANTISSA_BITS;
+ exp = mantissaStartBit + 1;
+ mantissa = (size >> mantissaStartBit) & MANTISSA_MASK;
+ }
+
+ return (exp << MANTISSA_BITS) | mantissa;
+ }
+
+ uint32 floatToUint(uint32 floatValue)
+ {
+ uint32 exponent = floatValue >> MANTISSA_BITS;
+ uint32 mantissa = floatValue & MANTISSA_MASK;
+ if (exponent == 0)
+ {
+ // Denorms
+ return mantissa;
+ }
+ else
+ {
+ return (mantissa | MANTISSA_VALUE) << (exponent - 1);
+ }
+ }
+ }
+
+ // Utility functions
+ uint32 findLowestSetBitAfter(uint32 bitMask, uint32 startBitIndex)
+ {
+ if (startBitIndex >= 32) return Allocation::NO_SPACE;
+ uint32 maskBeforeStartIndex = (uint32(1) << startBitIndex) - 1;
+ uint32 maskAfterStartIndex = ~maskBeforeStartIndex;
+ uint32 bitsAfter = bitMask & maskAfterStartIndex;
+ if (bitsAfter == 0) return Allocation::NO_SPACE;
+ return tzcnt_nonzero(bitsAfter);
+ }
+
+ // Allocator...
+ Allocator::Allocator(uint32 size, uint32 maxAllocs) :
+ m_size(size),
+ m_maxAllocs(maxAllocs),
+ m_nodes(nullptr),
+ m_freeNodes(nullptr)
+ {
+ if (sizeof(NodeIndex) == 2)
+ {
+ ASSERT(maxAllocs <= static_cast<uint32>(Node::unused) - 1);
+ }
+ reset();
+ }
+
+ Allocator::Allocator(Allocator &&other) :
+ m_size(other.m_size),
+ m_maxAllocs(other.m_maxAllocs),
+ m_freeStorage(other.m_freeStorage),
+ m_usedBinsTop(other.m_usedBinsTop),
+ m_nodes(other.m_nodes),
+ m_freeNodes(other.m_freeNodes),
+ m_freeOffset(other.m_freeOffset)
+ {
+ memcpy(m_usedBins, other.m_usedBins, sizeof(uint8) * NUM_TOP_BINS);
+ memcpy(m_binIndices, other.m_binIndices, sizeof(NodeIndex) * NUM_LEAF_BINS);
+
+ other.m_nodes = nullptr;
+ other.m_freeNodes = nullptr;
+ other.m_freeOffset = 0;
+ other.m_maxAllocs = 0;
+ other.m_usedBinsTop = 0;
+ }
+
+ void Allocator::reset()
+ {
+ m_freeStorage = 0;
+ m_usedBinsTop = 0;
+ m_freeOffset = m_maxAllocs;
+
+ for (uint32 i = 0 ; i < NUM_TOP_BINS; i++)
+ m_usedBins[i] = 0;
+
+ for (uint32 i = 0 ; i < NUM_LEAF_BINS; i++)
+ m_binIndices[i] = Node::unused;
+
+ if (m_nodes) delete[] m_nodes;
+ if (m_freeNodes) delete[] m_freeNodes;
+
+ m_nodes = new Node[m_maxAllocs + 1];
+ m_freeNodes = new NodeIndex[m_maxAllocs + 1];
+
+ // Freelist is a stack. Nodes in inverse order so that [0] pops first.
+ for (uint32 i = 0; i < m_maxAllocs + 1; i++)
+ {
+ m_freeNodes[i] = static_cast<NodeIndex>(m_maxAllocs - i);
+ }
+
+ // Start state: Whole storage as one big node
+ // Algorithm will split remainders and push them back as smaller nodes
+ insertNodeIntoBin(m_size, 0);
+ }
+
+ Allocator::~Allocator()
+ {
+ delete[] m_nodes;
+ delete[] m_freeNodes;
+ }
+
+ Allocation Allocator::allocate(uint32 size)
+ {
+ // Out of allocations?
+ if (m_freeOffset == Allocation::NO_SPACE)
+ {
+ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
+ }
+
+ // Round up to bin index to ensure that alloc >= bin
+ // Gives us min bin index that fits the size
+ uint32 minBinIndex = SmallFloat::uintToFloatRoundUp(size);
+ if (minBinIndex == 240) minBinIndex = 239; // 4 GiB bin overflows uint32
+
+ uint32 minTopBinIndex = minBinIndex >> TOP_BINS_INDEX_SHIFT;
+ uint32 minLeafBinIndex = minBinIndex & LEAF_BINS_INDEX_MASK;
+
+ uint32 topBinIndex = minTopBinIndex;
+ uint32 leafBinIndex = Allocation::NO_SPACE;
+
+ // If top bin exists, scan its leaf bin. This can fail (NO_SPACE).
+ if (m_usedBinsTop & (uint32(1) << topBinIndex))
+ {
+ leafBinIndex = findLowestSetBitAfter(m_usedBins[topBinIndex], minLeafBinIndex);
+ }
+
+ // If we didn't find space in top bin, we search top bin from +1
+ if (leafBinIndex == Allocation::NO_SPACE)
+ {
+ topBinIndex = findLowestSetBitAfter(m_usedBinsTop, minTopBinIndex + 1);
+
+ // Out of space?
+ if (topBinIndex == Allocation::NO_SPACE)
+ {
+ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
+ }
+
+ // All leaf bins here fit the alloc, since the top bin was rounded up. Start leaf search from bit 0.
+ // NOTE: This search can't fail since at least one leaf bit was set because the top bit was set.
+ leafBinIndex = tzcnt_nonzero(m_usedBins[topBinIndex]);
+ }
+
+ uint32 binIndex = (topBinIndex << TOP_BINS_INDEX_SHIFT) | leafBinIndex;
+
+ // Pop the top node of the bin. Bin top = node.next.
+ NodeIndex nodeIndex = m_binIndices[binIndex];
+ Node& node = m_nodes[nodeIndex];
+ uint32 nodeTotalSize = node.dataSize;
+ if (nodeTotalSize < size)
+ {
+ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
+ }
+ node.dataSize = size;
+ node.used = true;
+ m_binIndices[binIndex] = node.binListNext;
+ if (node.binListNext != Node::unused) m_nodes[node.binListNext].binListPrev = Node::unused;
+ m_freeStorage -= nodeTotalSize;
+#ifdef DEBUG_VERBOSE
+ printf("Free storage: %u (-%u) (allocate)\n", m_freeStorage, nodeTotalSize);
+#endif
+
+ // Bin empty?
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Remove a leaf bin mask bit
+ m_usedBins[topBinIndex] &= ~(uint32(1) << leafBinIndex);
+
+ // All leaf bins empty?
+ if (m_usedBins[topBinIndex] == 0)
+ {
+ // Remove a top bin mask bit
+ m_usedBinsTop &= ~(uint32(1) << topBinIndex);
+ }
+ }
+
+ // Push back reminder N elements to a lower bin
+ uint32 reminderSize = nodeTotalSize - size;
+ if (reminderSize > 0)
+ {
+ NodeIndex newNodeIndex = insertNodeIntoBin(reminderSize, node.dataOffset + size);
+
+ // Link nodes next to each other so that we can merge them later if both are free
+ // And update the old next neighbor to point to the new node (in middle)
+ if (node.neighborNext != Node::unused) m_nodes[node.neighborNext].neighborPrev = newNodeIndex;
+ m_nodes[newNodeIndex].neighborPrev = nodeIndex;
+ m_nodes[newNodeIndex].neighborNext = node.neighborNext;
+ node.neighborNext = newNodeIndex;
+ }
+
+ return {.offset = node.dataOffset, .metadata = nodeIndex};
+ }
+
+ void Allocator::free(Allocation allocation)
+ {
+ ASSERT(allocation.metadata != Allocation::NO_SPACE_METADATA);
+ if (!m_nodes) return;
+
+ NodeIndex nodeIndex = allocation.metadata;
+ Node& node = m_nodes[nodeIndex];
+
+ // Double delete check
+ ASSERT(node.used == true);
+
+ // Merge with neighbors...
+ uint32 offset = node.dataOffset;
+ uint32 size = node.dataSize;
+
+ if ((node.neighborPrev != Node::unused) && (m_nodes[node.neighborPrev].used == false))
+ {
+ // Previous (contiguous) free node: Change offset to previous node offset. Sum sizes
+ Node& prevNode = m_nodes[node.neighborPrev];
+ offset = prevNode.dataOffset;
+ size += prevNode.dataSize;
+
+ // Remove node from the bin linked list and put it in the freelist
+ removeNodeFromBin(node.neighborPrev);
+
+ ASSERT(prevNode.neighborNext == nodeIndex);
+ node.neighborPrev = prevNode.neighborPrev;
+ }
+
+ if ((node.neighborNext != Node::unused) && (m_nodes[node.neighborNext].used == false))
+ {
+ // Next (contiguous) free node: Offset remains the same. Sum sizes.
+ Node& nextNode = m_nodes[node.neighborNext];
+ size += nextNode.dataSize;
+
+ // Remove node from the bin linked list and put it in the freelist
+ removeNodeFromBin(node.neighborNext);
+
+ ASSERT(nextNode.neighborPrev == nodeIndex);
+ node.neighborNext = nextNode.neighborNext;
+ }
+
+ NodeIndex neighborNext = node.neighborNext;
+ NodeIndex neighborPrev = node.neighborPrev;
+
+ // Insert the removed node to freelist
+#ifdef DEBUG_VERBOSE
+ printf("Putting node %u into freelist[%u] (free)\n", nodeIndex, m_freeOffset + 1);
+#endif
+ m_freeNodes[++m_freeOffset] = nodeIndex;
+
+ // Insert the (combined) free node to bin
+ NodeIndex combinedNodeIndex = insertNodeIntoBin(size, offset);
+
+ // Connect neighbors with the new combined node
+ if (neighborNext != Node::unused)
+ {
+ m_nodes[combinedNodeIndex].neighborNext = neighborNext;
+ m_nodes[neighborNext].neighborPrev = combinedNodeIndex;
+ }
+ if (neighborPrev != Node::unused)
+ {
+ m_nodes[combinedNodeIndex].neighborPrev = neighborPrev;
+ m_nodes[neighborPrev].neighborNext = combinedNodeIndex;
+ }
+ }
+
+ NodeIndex Allocator::insertNodeIntoBin(uint32 size, uint32 dataOffset)
+ {
+ // Round down to bin index to ensure that bin >= alloc
+ uint32 binIndex = SmallFloat::uintToFloatRoundDown(size);
+
+ uint32 topBinIndex = binIndex >> TOP_BINS_INDEX_SHIFT;
+ uint32 leafBinIndex = binIndex & LEAF_BINS_INDEX_MASK;
+
+ // Bin was empty before?
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Set bin mask bits
+ m_usedBins[topBinIndex] |= uint32(1) << leafBinIndex;
+ m_usedBinsTop |= uint32(1) << topBinIndex;
+ }
+
+ // Take a freelist node and insert on top of the bin linked list (next = old top)
+ NodeIndex topNodeIndex = m_binIndices[binIndex];
+ NodeIndex nodeIndex = m_freeNodes[m_freeOffset--];
+#ifdef DEBUG_VERBOSE
+ printf("Getting node %u from freelist[%u]\n", nodeIndex, m_freeOffset + 1);
+#endif
+ m_nodes[nodeIndex] = {.dataOffset = dataOffset, .dataSize = size, .binListNext = topNodeIndex};
+ if (topNodeIndex != Node::unused) m_nodes[topNodeIndex].binListPrev = nodeIndex;
+ m_binIndices[binIndex] = nodeIndex;
+
+ m_freeStorage += size;
+#ifdef DEBUG_VERBOSE
+ printf("Free storage: %u (+%u) (insertNodeIntoBin)\n", m_freeStorage, size);
+#endif
+
+ return nodeIndex;
+ }
+
+ void Allocator::removeNodeFromBin(NodeIndex nodeIndex)
+ {
+ Node &node = m_nodes[nodeIndex];
+
+ if (node.binListPrev != Node::unused)
+ {
+ // Easy case: We have previous node. Just remove this node from the middle of the list.
+ m_nodes[node.binListPrev].binListNext = node.binListNext;
+ if (node.binListNext != Node::unused) m_nodes[node.binListNext].binListPrev = node.binListPrev;
+ }
+ else
+ {
+ // Hard case: We are the first node in a bin. Find the bin.
+
+ // Round down to bin index to ensure that bin >= alloc
+ uint32 binIndex = SmallFloat::uintToFloatRoundDown(node.dataSize);
+
+ uint32 topBinIndex = binIndex >> TOP_BINS_INDEX_SHIFT;
+ uint32 leafBinIndex = binIndex & LEAF_BINS_INDEX_MASK;
+
+ m_binIndices[binIndex] = node.binListNext;
+ if (node.binListNext != Node::unused) m_nodes[node.binListNext].binListPrev = Node::unused;
+
+ // Bin empty?
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Remove a leaf bin mask bit
+ m_usedBins[topBinIndex] &= ~(uint32(1) << leafBinIndex);
+
+ // All leaf bins empty?
+ if (m_usedBins[topBinIndex] == 0)
+ {
+ // Remove a top bin mask bit
+ m_usedBinsTop &= ~(uint32(1) << topBinIndex);
+ }
+ }
+ }
+
+ // Insert the node to freelist
+#ifdef DEBUG_VERBOSE
+ printf("Putting node %u into freelist[%u] (removeNodeFromBin)\n", nodeIndex, m_freeOffset + 1);
+#endif
+ m_freeNodes[++m_freeOffset] = nodeIndex;
+
+ m_freeStorage -= node.dataSize;
+#ifdef DEBUG_VERBOSE
+ printf("Free storage: %u (-%u) (removeNodeFromBin)\n", m_freeStorage, node.dataSize);
+#endif
+ }
+
+ uint32 Allocator::allocationSize(Allocation allocation) const
+ {
+ if (allocation.metadata == Allocation::NO_SPACE_METADATA) return 0;
+ if (!m_nodes) return 0;
+
+ return m_nodes[allocation.metadata].dataSize;
+ }
+
+ StorageReport Allocator::storageReport() const
+ {
+ uint32 largestFreeRegion = 0;
+ uint32 freeStorage = 0;
+
+ // Out of allocations? -> Zero free space
+ if ((m_nodes != nullptr) && (m_freeOffset != Allocation::NO_SPACE))
+ {
+ freeStorage = m_freeStorage;
+ if (m_usedBinsTop)
+ {
+ uint32 topBinIndex = 31 - lzcnt_nonzero(m_usedBinsTop);
+ uint32 leafBinIndex = 31 - lzcnt_nonzero(m_usedBins[topBinIndex]);
+ largestFreeRegion = SmallFloat::floatToUint((topBinIndex << TOP_BINS_INDEX_SHIFT) | leafBinIndex);
+ ASSERT(freeStorage >= largestFreeRegion);
+ }
+ }
+
+ return {.totalFreeSpace = freeStorage, .largestFreeRegion = largestFreeRegion};
+ }
+
+ StorageReportFull Allocator::storageReportFull() const
+ {
+ StorageReportFull report;
+ for (uint32 i = 0; i < NUM_LEAF_BINS; i++)
+ {
+ uint32 count = 0;
+ NodeIndex nodeIndex = m_binIndices[i];
+ while (nodeIndex != Node::unused)
+ {
+ nodeIndex = m_nodes[nodeIndex].binListNext;
+ count++;
+ }
+ report.freeRegions[i] = { .size = SmallFloat::floatToUint(i), .count = count };
+ }
+ return report;
+ }
+}
diff --git a/thirdparty/offset_allocator/offsetAllocator.hpp b/thirdparty/offset_allocator/offsetAllocator.hpp
new file mode 100644
index 00000000000..0991f7aa034
--- /dev/null
+++ b/thirdparty/offset_allocator/offsetAllocator.hpp
@@ -0,0 +1,101 @@
+// (C) Sebastian Aaltonen 2023
+// MIT License (see file: LICENSE)
+
+#ifndef OFFSET_ALLOCATOR_HPP
+#define OFFSET_ALLOCATOR_HPP
+
+//#define USE_16_BIT_OFFSETS
+
+namespace OffsetAllocator
+{
+ typedef unsigned char uint8;
+ typedef unsigned short uint16;
+ typedef unsigned int uint32;
+
+ // 16 bit offsets mode will halve the metadata storage cost
+ // But it only supports up to 65534 maximum allocation count
+#ifdef USE_16_BIT_NODE_INDICES
+ typedef uint16 NodeIndex;
+#else
+ typedef uint32 NodeIndex;
+#endif
+
+ static constexpr uint32 NUM_TOP_BINS = 32;
+ static constexpr uint32 BINS_PER_LEAF = 8;
+ static constexpr uint32 TOP_BINS_INDEX_SHIFT = 3;
+ static constexpr uint32 LEAF_BINS_INDEX_MASK = 0x7;
+ static constexpr uint32 NUM_LEAF_BINS = NUM_TOP_BINS * BINS_PER_LEAF;
+
+ struct Allocation
+ {
+ static constexpr uint32 NO_SPACE = 0xffffffff;
+ static constexpr NodeIndex NO_SPACE_METADATA = static_cast<NodeIndex>(-1);
+
+ uint32 offset = NO_SPACE;
+ NodeIndex metadata = NO_SPACE_METADATA; // internal: node index
+ };
+
+ struct StorageReport
+ {
+ uint32 totalFreeSpace;
+ uint32 largestFreeRegion;
+ };
+
+ struct StorageReportFull
+ {
+ struct Region
+ {
+ uint32 size;
+ uint32 count;
+ };
+
+ Region freeRegions[NUM_LEAF_BINS];
+ };
+
+ class Allocator
+ {
+ public:
+ Allocator(uint32 size, uint32 maxAllocs = 128 * 1024);
+ Allocator(Allocator &&other);
+ ~Allocator();
+ void reset();
+
+ Allocation allocate(uint32 size);
+ void free(Allocation allocation);
+
+ uint32 allocationSize(Allocation allocation) const;
+ StorageReport storageReport() const;
+ StorageReportFull storageReportFull() const;
+
+ private:
+ NodeIndex insertNodeIntoBin(uint32 size, uint32 dataOffset);
+ void removeNodeFromBin(NodeIndex nodeIndex);
+
+ struct Node
+ {
+ static constexpr NodeIndex unused = static_cast<NodeIndex>(-1);
+
+ uint32 dataOffset = 0;
+ uint32 dataSize = 0;
+ NodeIndex binListPrev = unused;
+ NodeIndex binListNext = unused;
+ NodeIndex neighborPrev = unused;
+ NodeIndex neighborNext = unused;
+ bool used = false; // TODO: Merge as bit flag
+ };
+
+ uint32 m_size;
+ uint32 m_maxAllocs;
+ uint32 m_freeStorage;
+
+ uint32 m_usedBinsTop;
+ uint8 m_usedBins[NUM_TOP_BINS];
+ NodeIndex m_binIndices[NUM_LEAF_BINS];
+
+ Node* m_nodes;
+ NodeIndex* m_freeNodes;
+ uint32 m_freeOffset;
+ };
+}
+
+#endif
diff --git a/thirdparty/offset_allocator/patches/0001-fix-allocation-count-tracking.patch b/thirdparty/offset_allocator/patches/0001-fix-allocation-count-tracking.patch
new file mode 100644
index 00000000000..1eaa8e24271
--- /dev/null
+++ b/thirdparty/offset_allocator/patches/0001-fix-allocation-count-tracking.patch
@@ -0,0 +1,48 @@
+diff --git a/thirdparty/offset_allocator/offsetAllocator.cpp b/thirdparty/offset_allocator/offsetAllocator.cpp
+--- a/thirdparty/offset_allocator/offsetAllocator.cpp
++++ b/thirdparty/offset_allocator/offsetAllocator.cpp
+@@ -170,7 +170,7 @@ namespace OffsetAllocator
+ {
+ m_freeStorage = 0;
+ m_usedBinsTop = 0;
+- m_freeOffset = m_maxAllocs - 1;
++ m_freeOffset = m_maxAllocs;
+
+ for (uint32 i = 0 ; i < NUM_TOP_BINS; i++)
+ m_usedBins[i] = 0;
+@@ -181,13 +181,13 @@ namespace OffsetAllocator
+ if (m_nodes) delete[] m_nodes;
+ if (m_freeNodes) delete[] m_freeNodes;
+
+- m_nodes = new Node[m_maxAllocs];
+- m_freeNodes = new NodeIndex[m_maxAllocs];
++ m_nodes = new Node[m_maxAllocs + 1];
++ m_freeNodes = new NodeIndex[m_maxAllocs + 1];
+
+ // Freelist is a stack. Nodes in inverse order so that [0] pops first.
+- for (uint32 i = 0; i < m_maxAllocs; i++)
++ for (uint32 i = 0; i < m_maxAllocs + 1; i++)
+ {
+- m_freeNodes[i] = m_maxAllocs - i - 1;
++ m_freeNodes[i] = m_maxAllocs - i;
+ }
+
+ // Start state: Whole storage as one big node
+@@ -204,7 +204,7 @@ namespace OffsetAllocator
+ Allocation Allocator::allocate(uint32 size)
+ {
+ // Out of allocations?
+- if (m_freeOffset == 0)
++ if (m_freeOffset == Allocation::NO_SPACE)
+ {
+ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE};
+ }
+@@ -452,7 +452,7 @@ namespace OffsetAllocator
+ uint32 freeStorage = 0;
+
+ // Out of allocations? -> Zero free space
+- if (m_freeOffset > 0)
++ if ((m_nodes != nullptr) && (m_freeOffset != Allocation::NO_SPACE))
+ {
+ freeStorage = m_freeStorage;
+ if (m_usedBinsTop)
diff --git a/thirdparty/offset_allocator/patches/0002-fix-16-bit-node-indices.patch b/thirdparty/offset_allocator/patches/0002-fix-16-bit-node-indices.patch
new file mode 100644
index 00000000000..385a7cbee85
--- /dev/null
+++ b/thirdparty/offset_allocator/patches/0002-fix-16-bit-node-indices.patch
@@ -0,0 +1,177 @@
+diff --git a/thirdparty/offset_allocator/offsetAllocator.hpp b/thirdparty/offset_allocator/offsetAllocator.hpp
+--- a/thirdparty/offset_allocator/offsetAllocator.hpp
++++ b/thirdparty/offset_allocator/offsetAllocator.hpp
+@@ -10,7 +10,7 @@ namespace OffsetAllocator
+ typedef unsigned int uint32;
+
+ // 16 bit offsets mode will halve the metadata storage cost
+- // But it only supports up to 65536 maximum allocation count
++ // But it only supports up to 65534 maximum allocation count
+ #ifdef USE_16_BIT_NODE_INDICES
+ typedef uint16 NodeIndex;
+ #else
+@@ -26,9 +26,10 @@ namespace OffsetAllocator
+ struct Allocation
+ {
+ static constexpr uint32 NO_SPACE = 0xffffffff;
++ static constexpr NodeIndex NO_SPACE_METADATA = static_cast<NodeIndex>(-1);
+
+ uint32 offset = NO_SPACE;
+- NodeIndex metadata = NO_SPACE; // internal: node index
++ NodeIndex metadata = NO_SPACE_METADATA; // internal: node index
+ };
+
+ struct StorageReport
+@@ -64,12 +65,12 @@ namespace OffsetAllocator
+ StorageReportFull storageReportFull() const;
+
+ private:
+- uint32 insertNodeIntoBin(uint32 size, uint32 dataOffset);
+- void removeNodeFromBin(uint32 nodeIndex);
++ NodeIndex insertNodeIntoBin(uint32 size, uint32 dataOffset);
++ void removeNodeFromBin(NodeIndex nodeIndex);
+
+ struct Node
+ {
+- static constexpr NodeIndex unused = 0xffffffff;
++ static constexpr NodeIndex unused = static_cast<NodeIndex>(-1);
+
+ uint32 dataOffset = 0;
+ uint32 dataSize = 0;
+diff --git a/thirdparty/offset_allocator/offsetAllocator.cpp b/thirdparty/offset_allocator/offsetAllocator.cpp
+--- a/thirdparty/offset_allocator/offsetAllocator.cpp
++++ b/thirdparty/offset_allocator/offsetAllocator.cpp
+@@ -142,7 +142,7 @@ namespace OffsetAllocator
+ {
+ if (sizeof(NodeIndex) == 2)
+ {
+- ASSERT(maxAllocs <= 65536);
++ ASSERT(maxAllocs <= static_cast<uint32>(Node::unused) - 1);
+ }
+ reset();
+ }
+@@ -187,7 +187,7 @@ namespace OffsetAllocator
+ // Freelist is a stack. Nodes in inverse order so that [0] pops first.
+ for (uint32 i = 0; i < m_maxAllocs + 1; i++)
+ {
+- m_freeNodes[i] = m_maxAllocs - i;
++ m_freeNodes[i] = static_cast<NodeIndex>(m_maxAllocs - i);
+ }
+
+ // Start state: Whole storage as one big node
+@@ -206,7 +206,7 @@ namespace OffsetAllocator
+ // Out of allocations?
+ if (m_freeOffset == Allocation::NO_SPACE)
+ {
+- return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE};
++ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
+ }
+
+ // Round up to bin index to ensure that alloc >= bin
+@@ -233,7 +233,7 @@ namespace OffsetAllocator
+ // Out of space?
+ if (topBinIndex == Allocation::NO_SPACE)
+ {
+- return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE};
++ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
+ }
+
+ // All leaf bins here fit the alloc, since the top bin was rounded up. Start leaf search from bit 0.
+@@ -244,7 +244,7 @@ namespace OffsetAllocator
+ uint32 binIndex = (topBinIndex << TOP_BINS_INDEX_SHIFT) | leafBinIndex;
+
+ // Pop the top node of the bin. Bin top = node.next.
+- uint32 nodeIndex = m_binIndices[binIndex];
++ NodeIndex nodeIndex = m_binIndices[binIndex];
+ Node& node = m_nodes[nodeIndex];
+ uint32 nodeTotalSize = node.dataSize;
+ node.dataSize = size;
+@@ -274,7 +274,7 @@ namespace OffsetAllocator
+ uint32 reminderSize = nodeTotalSize - size;
+ if (reminderSize > 0)
+ {
+- uint32 newNodeIndex = insertNodeIntoBin(reminderSize, node.dataOffset + size);
++ NodeIndex newNodeIndex = insertNodeIntoBin(reminderSize, node.dataOffset + size);
+
+ // Link nodes next to each other so that we can merge them later if both are free
+ // And update the old next neighbor to point to the new node (in middle)
+@@ -289,10 +289,10 @@ namespace OffsetAllocator
+
+ void Allocator::free(Allocation allocation)
+ {
+- ASSERT(allocation.metadata != Allocation::NO_SPACE);
++ ASSERT(allocation.metadata != Allocation::NO_SPACE_METADATA);
+ if (!m_nodes) return;
+
+- uint32 nodeIndex = allocation.metadata;
++ NodeIndex nodeIndex = allocation.metadata;
+ Node& node = m_nodes[nodeIndex];
+
+ // Double delete check
+@@ -329,8 +329,8 @@ namespace OffsetAllocator
+ node.neighborNext = nextNode.neighborNext;
+ }
+
+- uint32 neighborNext = node.neighborNext;
+- uint32 neighborPrev = node.neighborPrev;
++ NodeIndex neighborNext = node.neighborNext;
++ NodeIndex neighborPrev = node.neighborPrev;
+
+ // Insert the removed node to freelist
+ #ifdef DEBUG_VERBOSE
+@@ -339,7 +339,7 @@ namespace OffsetAllocator
+ m_freeNodes[++m_freeOffset] = nodeIndex;
+
+ // Insert the (combined) free node to bin
+- uint32 combinedNodeIndex = insertNodeIntoBin(size, offset);
++ NodeIndex combinedNodeIndex = insertNodeIntoBin(size, offset);
+
+ // Connect neighbors with the new combined node
+ if (neighborNext != Node::unused)
+@@ -354,7 +354,7 @@ namespace OffsetAllocator
+ }
+ }
+
+- uint32 Allocator::insertNodeIntoBin(uint32 size, uint32 dataOffset)
++ NodeIndex Allocator::insertNodeIntoBin(uint32 size, uint32 dataOffset)
+ {
+ // Round down to bin index to ensure that bin >= alloc
+ uint32 binIndex = SmallFloat::uintToFloatRoundDown(size);
+@@ -371,8 +371,8 @@ namespace OffsetAllocator
+ }
+
+ // Take a freelist node and insert on top of the bin linked list (next = old top)
+- uint32 topNodeIndex = m_binIndices[binIndex];
+- uint32 nodeIndex = m_freeNodes[m_freeOffset--];
++ NodeIndex topNodeIndex = m_binIndices[binIndex];
++ NodeIndex nodeIndex = m_freeNodes[m_freeOffset--];
+ #ifdef DEBUG_VERBOSE
+ printf("Getting node %u from freelist[%u]\n", nodeIndex, m_freeOffset + 1);
+ #endif
+@@ -388,7 +388,7 @@ namespace OffsetAllocator
+ return nodeIndex;
+ }
+
+- void Allocator::removeNodeFromBin(uint32 nodeIndex)
++ void Allocator::removeNodeFromBin(NodeIndex nodeIndex)
+ {
+ Node &node = m_nodes[nodeIndex];
+
+@@ -440,7 +440,7 @@ namespace OffsetAllocator
+
+ uint32 Allocator::allocationSize(Allocation allocation) const
+ {
+- if (allocation.metadata == Allocation::NO_SPACE) return 0;
++ if (allocation.metadata == Allocation::NO_SPACE_METADATA) return 0;
+ if (!m_nodes) return 0;
+
+ return m_nodes[allocation.metadata].dataSize;
+@@ -473,7 +473,7 @@ namespace OffsetAllocator
+ for (uint32 i = 0; i < NUM_LEAF_BINS; i++)
+ {
+ uint32 count = 0;
+- uint32 nodeIndex = m_binIndices[i];
++ NodeIndex nodeIndex = m_binIndices[i];
+ while (nodeIndex != Node::unused)
+ {
+ nodeIndex = m_nodes[nodeIndex].binListNext;
diff --git a/thirdparty/offset_allocator/patches/0003-fix-maximum-allocation-size.patch b/thirdparty/offset_allocator/patches/0003-fix-maximum-allocation-size.patch
new file mode 100644
index 00000000000..f90b1d43faf
--- /dev/null
+++ b/thirdparty/offset_allocator/patches/0003-fix-maximum-allocation-size.patch
@@ -0,0 +1,93 @@
+diff --git a/thirdparty/offset_allocator/offsetAllocator.cpp b/thirdparty/offset_allocator/offsetAllocator.cpp
+--- a/thirdparty/offset_allocator/offsetAllocator.cpp
++++ b/thirdparty/offset_allocator/offsetAllocator.cpp
+@@ -73,7 +73,7 @@ namespace OffsetAllocator
+ exp = mantissaStartBit + 1;
+ mantissa = (size >> mantissaStartBit) & MANTISSA_MASK;
+
+- uint32 lowBitsMask = (1 << mantissaStartBit) - 1;
++ uint32 lowBitsMask = (uint32(1) << mantissaStartBit) - 1;
+
+ // Round up!
+ if ((size & lowBitsMask) != 0)
+@@ -126,7 +126,8 @@ namespace OffsetAllocator
+ // Utility functions
+ uint32 findLowestSetBitAfter(uint32 bitMask, uint32 startBitIndex)
+ {
+- uint32 maskBeforeStartIndex = (1 << startBitIndex) - 1;
++ if (startBitIndex >= 32) return Allocation::NO_SPACE;
++ uint32 maskBeforeStartIndex = (uint32(1) << startBitIndex) - 1;
+ uint32 maskAfterStartIndex = ~maskBeforeStartIndex;
+ uint32 bitsAfter = bitMask & maskAfterStartIndex;
+ if (bitsAfter == 0) return Allocation::NO_SPACE;
+@@ -212,6 +213,7 @@ namespace OffsetAllocator
+ // Round up to bin index to ensure that alloc >= bin
+ // Gives us min bin index that fits the size
+ uint32 minBinIndex = SmallFloat::uintToFloatRoundUp(size);
++ if (minBinIndex == 240) minBinIndex = 239; // 4 GiB bin overflows uint32
+
+ uint32 minTopBinIndex = minBinIndex >> TOP_BINS_INDEX_SHIFT;
+ uint32 minLeafBinIndex = minBinIndex & LEAF_BINS_INDEX_MASK;
+@@ -220,7 +222,7 @@ namespace OffsetAllocator
+ uint32 leafBinIndex = Allocation::NO_SPACE;
+
+ // If top bin exists, scan its leaf bin. This can fail (NO_SPACE).
+- if (m_usedBinsTop & (1 << topBinIndex))
++ if (m_usedBinsTop & (uint32(1) << topBinIndex))
+ {
+ leafBinIndex = findLowestSetBitAfter(m_usedBins[topBinIndex], minLeafBinIndex);
+ }
+@@ -247,6 +249,10 @@ namespace OffsetAllocator
+ NodeIndex nodeIndex = m_binIndices[binIndex];
+ Node& node = m_nodes[nodeIndex];
+ uint32 nodeTotalSize = node.dataSize;
++ if (nodeTotalSize < size)
++ {
++ return {.offset = Allocation::NO_SPACE, .metadata = Allocation::NO_SPACE_METADATA};
++ }
+ node.dataSize = size;
+ node.used = true;
+ m_binIndices[binIndex] = node.binListNext;
+@@ -260,13 +266,13 @@ namespace OffsetAllocator
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Remove a leaf bin mask bit
+- m_usedBins[topBinIndex] &= ~(1 << leafBinIndex);
++ m_usedBins[topBinIndex] &= ~(uint32(1) << leafBinIndex);
+
+ // All leaf bins empty?
+ if (m_usedBins[topBinIndex] == 0)
+ {
+ // Remove a top bin mask bit
+- m_usedBinsTop &= ~(1 << topBinIndex);
++ m_usedBinsTop &= ~(uint32(1) << topBinIndex);
+ }
+ }
+
+@@ -366,8 +372,8 @@ namespace OffsetAllocator
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Set bin mask bits
+- m_usedBins[topBinIndex] |= 1 << leafBinIndex;
+- m_usedBinsTop |= 1 << topBinIndex;
++ m_usedBins[topBinIndex] |= uint32(1) << leafBinIndex;
++ m_usedBinsTop |= uint32(1) << topBinIndex;
+ }
+
+ // Take a freelist node and insert on top of the bin linked list (next = old top)
+@@ -415,13 +421,13 @@ namespace OffsetAllocator
+ if (m_binIndices[binIndex] == Node::unused)
+ {
+ // Remove a leaf bin mask bit
+- m_usedBins[topBinIndex] &= ~(1 << leafBinIndex);
++ m_usedBins[topBinIndex] &= ~(uint32(1) << leafBinIndex);
+
+ // All leaf bins empty?
+ if (m_usedBins[topBinIndex] == 0)
+ {
+ // Remove a top bin mask bit
+- m_usedBinsTop &= ~(1 << topBinIndex);
++ m_usedBinsTop &= ~(uint32(1) << topBinIndex);
+ }
+ }
+ }
diff --git a/thirdparty/offset_allocator/patches/0004-add-header-guard.patch b/thirdparty/offset_allocator/patches/0004-add-header-guard.patch
new file mode 100644
index 00000000000..cd0cb0c0ecf
--- /dev/null
+++ b/thirdparty/offset_allocator/patches/0004-add-header-guard.patch
@@ -0,0 +1,19 @@
+diff --git a/thirdparty/offset_allocator/offsetAllocator.hpp b/thirdparty/offset_allocator/offsetAllocator.hpp
+--- a/thirdparty/offset_allocator/offsetAllocator.hpp
++++ b/thirdparty/offset_allocator/offsetAllocator.hpp
+@@ -1,6 +1,9 @@
+ // (C) Sebastian Aaltonen 2023
+ // MIT License (see file: LICENSE)
+
++#ifndef OFFSET_ALLOCATOR_HPP
++#define OFFSET_ALLOCATOR_HPP
++
+ //#define USE_16_BIT_OFFSETS
+
+ namespace OffsetAllocator
+@@ -94,3 +97,5 @@ namespace OffsetAllocator
+ uint32 m_freeOffset;
+ };
+ }
++
++#endif