Blender V5.3
mtl_ray_tracing.mm
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "mtl_ray_tracing.hh"
10
11#include "mtl_context.hh"
12#include "mtl_index_buffer.hh"
13#include "mtl_vertex_buffer.hh"
14
15namespace blender::gpu {
16
17/* Pack a column-major float4x4 into Metal's column-major 4x3 instance transform. */
18static MTLPackedFloat4x3 pack_transform(const float4x4 &m)
19{
20 MTLPackedFloat4x3 out;
21 for (int col = 0; col < 4; col++) {
22 out.columns[col].x = m[col].x;
23 out.columns[col].y = m[col].y;
24 out.columns[col].z = m[col].z;
25 }
26 return out;
27}
28
29/* -------------------------------------------------------------------- */
32
34
36{
37 if (acceleration_structure_ != nil) {
38 [acceleration_structure_ release];
39 acceleration_structure_ = nil;
40 }
41 if (geometry_ != nil) {
42 [geometry_ release];
43 geometry_ = nil;
44 }
45}
46
47void MTLBottomLevelAS::add_geometry(IndexBuf &index_buffer, VertBuf &vertex_buffer)
48{
49 /* Skip empty geometry, e.g. a mesh without faces has no Metal index buffer. */
50 if (index_buffer.index_len_get() == 0) {
51 return;
52 }
53
54 MTLVertBuf &mtl_vertex = static_cast<MTLVertBuf &>(vertex_buffer);
55 MTLIndexBuf &mtl_index = static_cast<MTLIndexBuf &>(index_buffer);
56
57 /* Ensure buffer contents are resident on the GPU. */
58 mtl_vertex.bind();
59 mtl_vertex.flag_used();
60 mtl_index.upload_data();
61
62 GPUPrimType prim_type = GPU_PRIM_TRIS;
63 uint index_count = index_buffer.index_len_get();
64 id<MTLBuffer> index_metal_buffer = mtl_index.get_index_buffer(prim_type, index_count);
65 id<MTLBuffer> vertex_metal_buffer = mtl_vertex.get_metal_buffer();
66 if (index_metal_buffer == nil || vertex_metal_buffer == nil) {
67 return;
68 }
69
70 MTLAccelerationStructureTriangleGeometryDescriptor *geo =
71 [MTLAccelerationStructureTriangleGeometryDescriptor descriptor];
72 geo.vertexBuffer = vertex_metal_buffer;
73 /* Metal has no base vertex for geometry descriptors, so it is folded into the buffer offset. */
74 geo.vertexBufferOffset = index_buffer.index_base_get() * vertex_buffer.format.stride;
75 geo.vertexStride = vertex_buffer.format.stride;
76 geo.vertexFormat = MTLAttributeFormatFloat3;
77 geo.indexBuffer = index_metal_buffer;
78 geo.indexBufferOffset = index_buffer.index_start_get() * to_bytesize(mtl_index.index_type());
79 geo.indexType = mtl_index.is_32bit() ? MTLIndexTypeUInt32 : MTLIndexTypeUInt16;
80 geo.triangleCount = index_count / 3;
81 geo.opaque = YES;
82
83 if (geometry_ == nil) {
84 geometry_ = [[NSMutableArray alloc] init];
85 }
86 [geometry_ addObject:geo];
87}
88
90{
91 /* Leave the structure nil without geometry, top level structures skip it. */
92 if (geometry_ == nil) {
93 return;
94 }
95
96 @autoreleasepool {
98 id<MTLDevice> device = ctx->device;
99
100 MTLPrimitiveAccelerationStructureDescriptor *desc =
101 [MTLPrimitiveAccelerationStructureDescriptor descriptor];
102 desc.geometryDescriptors = geometry_;
103
104 MTLAccelerationStructureSizes sizes = [device accelerationStructureSizesWithDescriptor:desc];
105
106 if (acceleration_structure_ != nil) {
107 [acceleration_structure_ release];
108 }
109 acceleration_structure_ = [device
110 newAccelerationStructureWithSize:sizes.accelerationStructureSize];
111
112 NSUInteger scratch_size = (sizes.buildScratchBufferSize > 0) ? sizes.buildScratchBufferSize :
113 256;
115 false);
116
119 [enc buildAccelerationStructure:acceleration_structure_
120 descriptor:desc
121 scratchBuffer:scratch->get_metal_buffer()
122 scratchBufferOffset:0];
123
124 scratch->free();
125 }
126}
127
129
130/* -------------------------------------------------------------------- */
133
134MTLTopLevelAS::MTLTopLevelAS(const char *name) : TopLevelAS(name) {}
135
137{
138 /* Clear any binding still referencing this structure to avoid a dangling pointer. */
140 if (ctx != nullptr) {
141 for (MTLAccelerationStructureBinding &binding :
143 {
144 if (binding.tlas == this) {
145 binding.tlas = nullptr;
146 binding.bound = false;
147 }
148 }
149 }
150 if (acceleration_structure_ != nil) {
151 [acceleration_structure_ release];
152 acceleration_structure_ = nil;
153 }
154}
155
157 const float4x4 &mat,
159{
160 InstanceID id = {int64_t(instances_.size())};
161 instances_.append({mat, static_cast<const MTLBottomLevelAS *>(&blas), mask});
162 is_dirty_ = true;
163 needs_rebuild_ = true;
164 return id;
165}
166
168{
169 if (instance_id.id < 0 || instance_id.id >= instances_.size()) {
170 return;
171 }
172 instances_[instance_id.id].transform = mat;
173 instances_[instance_id.id].mask = mask;
174 is_dirty_ = true;
175}
176
178{
179 if (acceleration_structure_ != nil && !is_dirty_) {
180 return;
181 }
182
183 @autoreleasepool {
185 id<MTLDevice> device = ctx->device;
186
187 const int64_t instance_count = instances_.size();
188
189 /* Instance descriptors + array of the referenced bottom level structures.
190 * Metal requires a non-nil instance descriptor buffer even for an empty TLAS. */
191 const int64_t descriptor_count = (instance_count > 0) ? instance_count : 1;
192 NSMutableArray<id<MTLAccelerationStructure>> *blas_array = [NSMutableArray
193 arrayWithCapacity:instance_count];
194
195 MTLInstanceAccelerationStructureDescriptor *desc =
196 [MTLInstanceAccelerationStructureDescriptor descriptor];
197 desc.usage = MTLAccelerationStructureUsageRefit;
198 desc.instanceDescriptorBufferOffset = 0;
199
200 /* userID is the Metal equivalent of the per-instance custom index. */
201 gpu::MTLBuffer *instance_buffer = nullptr;
203 descriptor_count * sizeof(MTLAccelerationStructureUserIDInstanceDescriptor), true);
204 MTLAccelerationStructureUserIDInstanceDescriptor *descs =
205 (MTLAccelerationStructureUserIDInstanceDescriptor *)instance_buffer->get_host_ptr();
206 /* Bottom level structures without geometry are nil and can't be added to the array. Keep
207 * their instances so instance indices match #add_instance, but reference another structure
208 * and mask them out so they are never hit. */
209 id<MTLAccelerationStructure> fallback_blas = nil;
210 for (const Instance &inst : instances_) {
211 if (inst.blas->acceleration_structure() != nil) {
212 fallback_blas = inst.blas->acceleration_structure();
213 break;
214 }
215 }
216
217 const int64_t descs_count = (fallback_blas != nil) ? instance_count : 0;
218 for (int64_t i = 0; i < descs_count; i++) {
219 const Instance &inst = instances_[i];
221 descs[i].transformationMatrix = pack_transform(inst.transform);
222 descs[i].options = MTLAccelerationStructureInstanceOptionOpaque;
223 descs[i].mask = (blas != nil) ? inst.mask : 0;
224 descs[i].intersectionFunctionTableOffset = 0;
225 descs[i].accelerationStructureIndex = uint32_t(i);
226 /* Per-instance custom index; hardcoded 0 to match Vulkan until add_instance exposes it. */
227 descs[i].userID = 0;
228 [blas_array addObject:(blas != nil) ? blas : fallback_blas];
229 }
230 desc.instanceCount = descs_count;
231 desc.instanceDescriptorType = MTLAccelerationStructureInstanceDescriptorTypeUserID;
232 desc.instanceDescriptorStride = sizeof(MTLAccelerationStructureUserIDInstanceDescriptor);
233
234 BLI_assert(instance_buffer != nullptr);
235 desc.instanceDescriptorBuffer = instance_buffer->get_metal_buffer();
236 desc.instancedAccelerationStructures = blas_array;
237
238 MTLAccelerationStructureSizes sizes = [device accelerationStructureSizesWithDescriptor:desc];
239
242
243 /* Refit in place when only instance data changed since the last build (no new instances). */
244 if (acceleration_structure_ != nil && !needs_rebuild_) {
245 NSUInteger scratch_size = (sizes.refitScratchBufferSize > 0) ? sizes.refitScratchBufferSize :
246 256;
248 false);
249 [enc refitAccelerationStructure:acceleration_structure_
250 descriptor:desc
251 destination:nil
252 scratchBuffer:scratch->get_metal_buffer()
253 scratchBufferOffset:0];
254 scratch->free();
255 }
256 else {
257 if (acceleration_structure_ != nil) {
258 [acceleration_structure_ release];
259 }
260 acceleration_structure_ = [device
261 newAccelerationStructureWithSize:sizes.accelerationStructureSize];
262
263 NSUInteger scratch_size = (sizes.buildScratchBufferSize > 0) ? sizes.buildScratchBufferSize :
264 256;
266 false);
267 [enc buildAccelerationStructure:acceleration_structure_
268 descriptor:desc
269 scratchBuffer:scratch->get_metal_buffer()
270 scratchBufferOffset:0];
271 scratch->free();
272 }
273
274 instance_buffer->free();
275 }
276
277 needs_rebuild_ = false;
278 is_dirty_ = false;
279}
280
282{
284 BLI_assert(ctx);
285 BLI_assert(slot >= 0 && slot < int(ctx->pipeline_state.acceleration_structure_bindings.size()));
288 binding.tlas = this;
289 binding.bound = true;
290}
291
293
294} // namespace blender::gpu
BottomLevelAS(const char *name)
uint32_t index_start_get() const
uint32_t index_base_get() const
GPUIndexBufType index_type() const
uint32_t index_len_get() const
void add_geometry(IndexBuf &index_buffer, VertBuf &vertex_buffer) override
id< MTLAccelerationStructure > acceleration_structure() const
gpu::MTLBuffer * allocate(uint64_t size, bool cpu_visible)
void * get_host_ptr() const
id< MTLBuffer > get_metal_buffer() const
id< MTLAccelerationStructureCommandEncoder > ensure_begin_acceleration_structure_encoder()
static MTLContext * get()
MTLContextGlobalShaderPipelineState pipeline_state
MTLCommandBufferManager main_command_buffer
static MTLBufferPool * get_global_memory_manager()
id< MTLBuffer > get_index_buffer(GPUPrimType &in_out_primitive_type, uint &in_out_v_count)
InstanceID add_instance(const BottomLevelAS &blas, const float4x4 &mat, uint8_t mask) override
void bind(int slot) override
void update_instance(InstanceID instance_id, const float4x4 &mat, uint8_t mask) override
TopLevelAS(const char *name)
#define instance_id
static MTLPackedFloat4x3 pack_transform(const float4x4 &m)
int to_bytesize(const DataFormat format)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
unsigned int uint
Definition BKE_text.h:55
MatBase< float, 4, 4 > float4x4
unsigned int uint32_t
Definition BKE_text.h:81
unsigned char uint8_t
Definition BKE_text.h:79
std::array< MTLAccelerationStructureBinding, 1 > acceleration_structure_bindings