Debian Codegraph @

drivers/metal/metal_objects.h

raw symbols SCIP
1 /**************************************************************************/
2 /* metal_objects.h */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #pragma once
32
33 /**************************************************************************/
34 /* */
35 /* Portions of this code were derived from MoltenVK. */
36 /* */
37 /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
38 /* (http://www.brenwill.com) */
39 /* */
40 /* Licensed under the Apache License, Version 2.0 (the "License"); */
41 /* you may not use this file except in compliance with the License. */
42 /* You may obtain a copy of the License at */
43 /* */
44 /* http://www.apache.org/licenses/LICENSE-2.0 */
45 /* */
46 /* Unless required by applicable law or agreed to in writing, software */
47 /* distributed under the License is distributed on an "AS IS" BASIS, */
48 /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
49 /* implied. See the License for the specific language governing */
50 /* permissions and limitations under the License. */
51 /**************************************************************************/
52
53 #import "metal_device_properties.h"
54 #import "metal_objects_shared.h"
55 #import "metal_utils.h"
56 #import "pixel_formats.h"
57 #import "sha256_digest.h"
58
59 #include "servers/rendering/rendering_device_driver.h"
60
61 #import <CommonCrypto/CommonDigest.h>
62 #import <Foundation/Foundation.h>
63 #import <Metal/Metal.h>
64 #import <QuartzCore/CAMetalLayer.h>
65 #import <simd/simd.h>
66 #import <zlib.h>
67 #import <initializer_list>
68 #import <memory>
69 #import <optional>
70
71 enum StageResourceUsage : uint32_t {
72 ResourceUnused = 0,
73 VertexRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_VERTEX * 2),
74 VertexWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_VERTEX * 2),
75 FragmentRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_FRAGMENT * 2),
76 FragmentWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_FRAGMENT * 2),
77 TesselationControlRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
78 TesselationControlWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
79 TesselationEvaluationRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
80 TesselationEvaluationWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
81 ComputeRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_COMPUTE * 2),
82 ComputeWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_COMPUTE * 2),
83 };
84
85 typedef id<MTLResource> __unsafe_unretained MTLResourceUnsafe;
86
87 template <>
88 struct HashMapHasherDefaultImpl<MTLResourceUnsafe> {
89 static _FORCE_INLINE_ uint32_t hash(const MTLResourceUnsafe p_pointer) { return hash_one_uint64((uint64_t)p_pointer); }
90 };
91
92 typedef LocalVector<MTLResourceUnsafe> ResourceVector;
93 typedef HashMap<StageResourceUsage, ResourceVector> ResourceUsageMap;
94
95 struct ResourceUsageEntry {
96 StageResourceUsage usage = ResourceUnused;
97 uint32_t unused = 0;
98
99 ResourceUsageEntry() {}
100 ResourceUsageEntry(StageResourceUsage p_usage) :
101 usage(p_usage) {}
102 };
103
104 template <>
105 struct is_zero_constructible<ResourceUsageEntry> : std::true_type {};
106
107 /*! Track the cumulative usage for a resource during a render or compute pass */
108 typedef HashMap<MTLResourceUnsafe, ResourceUsageEntry> ResourceToStageUsage;
109
110 /*! Track resource and ensure they are resident prior to dispatch or draw commands.
111 *
112 * The primary purpose of this data structure is to track all the resources that must be made resident prior
113 * to issuing the next dispatch or draw command. It aggregates all resources used from argument buffers.
114 *
115 * As an optimization, this data structure also tracks previous usage for resources, so that
116 * it may avoid binding them again in later commands if the resource is already resident and its usage flagged.
117 */
118 struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) ResourceTracker {
119 // A constant specifying how many iterations a resource can remain in
120 // the _previous HashSet before it will be removed permanently.
121 //
122 // Keeping them in the _previous HashMap reduces churn if resources are regularly
123 // bound. 256 is arbitrary, but if an object remains unused for 256 encoders,
124 // it will be released.
125 static constexpr uint32_t RESOURCE_UNUSED_CLEANUP_COUNT = 256;
126
127 // Used as a scratch buffer to periodically clean up resources from _previous.
128 ResourceVector _scratch;
129 // Tracks all resources and their prior usage for the duration of the encoder.
130 ResourceToStageUsage _previous;
131 // Tracks resources for the current command that must be made resident
132 ResourceUsageMap _current;
133
134 void merge_from(const ResourceUsageMap &p_from);
135 void encode(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc);
136 void encode(id<MTLComputeCommandEncoder> __unsafe_unretained p_enc);
137 void reset();
138 };
139
140 enum class MDCommandBufferStateType {
141 None,
142 Render,
143 Compute,
144 Blit,
145 };
146
147 enum class MDPipelineType {
148 None,
149 Render,
150 Compute,
151 };
152
153 class MDRenderPass;
154 class MDPipeline;
155 class MDRenderPipeline;
156 class MDComputePipeline;
157 class RenderingDeviceDriverMetal;
158 class MDUniformSet;
159 class MDShader;
160
161 struct MetalBufferDynamicInfo;
162
163 using RDM = RenderingDeviceDriverMetal;
164
165 #pragma mark - Resource Factory
166
167 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceFactory {
168 private:
169 RenderingDeviceDriverMetal *device_driver;
170
171 id<MTLFunction> new_func(NSString *p_source, NSString *p_name, NSError **p_error);
172 id<MTLFunction> new_clear_vert_func(ClearAttKey &p_key);
173 id<MTLFunction> new_clear_frag_func(ClearAttKey &p_key);
174 NSString *get_format_type_string(MTLPixelFormat p_fmt);
175
176 public:
177 id<MTLRenderPipelineState> new_clear_pipeline_state(ClearAttKey &p_key, NSError **p_error);
178 id<MTLDepthStencilState> new_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
179
180 MDResourceFactory(RenderingDeviceDriverMetal *p_device_driver) :
181 device_driver(p_device_driver) {}
182 ~MDResourceFactory() = default;
183 };
184
185 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceCache {
186 private:
187 typedef HashMap<ClearAttKey, id<MTLRenderPipelineState>> HashMap;
188 std::unique_ptr<MDResourceFactory> resource_factory;
189 HashMap clear_states;
190
191 struct {
192 id<MTLDepthStencilState> all;
193 id<MTLDepthStencilState> depth_only;
194 id<MTLDepthStencilState> stencil_only;
195 id<MTLDepthStencilState> none;
196 } clear_depth_stencil_state;
197
198 public:
199 id<MTLRenderPipelineState> get_clear_render_pipeline_state(ClearAttKey &p_key, NSError **p_error);
200 id<MTLDepthStencilState> get_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
201
202 explicit MDResourceCache(RenderingDeviceDriverMetal *p_device_driver) :
203 resource_factory(new MDResourceFactory(p_device_driver)) {}
204 ~MDResourceCache() = default;
205 };
206
207 enum class MDAttachmentType : uint8_t {
208 None = 0,
209 Color = 1 << 0,
210 Depth = 1 << 1,
211 Stencil = 1 << 2,
212 };
213
214 _FORCE_INLINE_ MDAttachmentType &operator|=(MDAttachmentType &p_a, MDAttachmentType p_b) {
215 flags::set(p_a, p_b);
216 return p_a;
217 }
218
219 _FORCE_INLINE_ bool operator&(MDAttachmentType p_a, MDAttachmentType p_b) {
220 return uint8_t(p_a) & uint8_t(p_b);
221 }
222
223 struct MDSubpass {
224 uint32_t subpass_index = 0;
225 uint32_t view_count = 0;
226 LocalVector<RDD::AttachmentReference> input_references;
227 LocalVector<RDD::AttachmentReference> color_references;
228 RDD::AttachmentReference depth_stencil_reference;
229 LocalVector<RDD::AttachmentReference> resolve_references;
230
231 MTLFmtCaps getRequiredFmtCapsForAttachmentAt(uint32_t p_index) const;
232 };
233
234 struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDAttachment {
235 private:
236 uint32_t index = 0;
237 uint32_t firstUseSubpassIndex = 0;
238 uint32_t lastUseSubpassIndex = 0;
239
240 public:
241 MTLPixelFormat format = MTLPixelFormatInvalid;
242 MDAttachmentType type = MDAttachmentType::None;
243 MTLLoadAction loadAction = MTLLoadActionDontCare;
244 MTLStoreAction storeAction = MTLStoreActionDontCare;
245 MTLLoadAction stencilLoadAction = MTLLoadActionDontCare;
246 MTLStoreAction stencilStoreAction = MTLStoreActionDontCare;
247 uint32_t samples = 1;
248
249 /*!
250 * @brief Returns true if this attachment is first used in the given subpass.
251 * @param p_subpass
252 * @return
253 */
254 _FORCE_INLINE_ bool isFirstUseOf(MDSubpass const &p_subpass) const {
255 return p_subpass.subpass_index == firstUseSubpassIndex;
256 }
257
258 /*!
259 * @brief Returns true if this attachment is last used in the given subpass.
260 * @param p_subpass
261 * @return
262 */
263 _FORCE_INLINE_ bool isLastUseOf(MDSubpass const &p_subpass) const {
264 return p_subpass.subpass_index == lastUseSubpassIndex;
265 }
266
267 void linkToSubpass(MDRenderPass const &p_pass);
268
269 MTLStoreAction getMTLStoreAction(MDSubpass const &p_subpass,
270 bool p_is_rendering_entire_area,
271 bool p_has_resolve,
272 bool p_can_resolve,
273 bool p_is_stencil) const;
274 bool configureDescriptor(MTLRenderPassAttachmentDescriptor *p_desc,
275 PixelFormats &p_pf,
276 MDSubpass const &p_subpass,
277 id<MTLTexture> p_attachment,
278 bool p_is_rendering_entire_area,
279 bool p_has_resolve,
280 bool p_can_resolve,
281 bool p_is_stencil) const;
282 /** Returns whether this attachment should be cleared in the subpass. */
283 bool shouldClear(MDSubpass const &p_subpass, bool p_is_stencil) const;
284 };
285
286 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPass {
287 public:
288 Vector<MDAttachment> attachments;
289 Vector<MDSubpass> subpasses;
290
291 uint32_t get_sample_count() const {
292 return attachments.is_empty() ? 1 : attachments[0].samples;
293 }
294
295 MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses);
296 };
297
298 struct BindingCache {
299 struct BufferBinding {
300 id<MTLBuffer> __unsafe_unretained buffer = nil;
301 NSUInteger offset = 0;
302
303 bool operator!=(const BufferBinding &p_other) const {
304 return buffer != p_other.buffer || offset != p_other.offset;
305 }
306 };
307
308 LocalVector<id<MTLTexture> __unsafe_unretained> textures;
309 LocalVector<id<MTLSamplerState> __unsafe_unretained> samplers;
310 LocalVector<BufferBinding> buffers;
311
312 _FORCE_INLINE_ void clear() {
313 textures.clear();
314 samplers.clear();
315 buffers.clear();
316 }
317
318 private:
319 template <typename T>
320 _FORCE_INLINE_ void ensure_size(LocalVector<T> &p_vec, uint32_t p_required) {
321 if (p_vec.size() < p_required) {
322 p_vec.resize_initialized(p_required);
323 }
324 }
325
326 public:
327 _FORCE_INLINE_ bool update(NSRange p_range, id<MTLTexture> __unsafe_unretained const *p_values) {
328 if (p_range.length == 0) {
329 return false;
330 }
331 uint32_t required = (uint32_t)(p_range.location + p_range.length);
332 ensure_size(textures, required);
333 bool changed = false;
334 for (NSUInteger i = 0; i < p_range.length; ++i) {
335 uint32_t slot = (uint32_t)(p_range.location + i);
336 id<MTLTexture> value = p_values[i];
337 if (textures[slot] != value) {
338 textures[slot] = value;
339 changed = true;
340 }
341 }
342 return changed;
343 }
344
345 _FORCE_INLINE_ bool update(NSRange p_range, id<MTLSamplerState> __unsafe_unretained const *p_values) {
346 if (p_range.length == 0) {
347 return false;
348 }
349 uint32_t required = (uint32_t)(p_range.location + p_range.length);
350 ensure_size(samplers, required);
351 bool changed = false;
352 for (NSUInteger i = 0; i < p_range.length; ++i) {
353 uint32_t slot = (uint32_t)(p_range.location + i);
354 id<MTLSamplerState> __unsafe_unretained value = p_values[i];
355 if (samplers[slot] != value) {
356 samplers[slot] = value;
357 changed = true;
358 }
359 }
360 return changed;
361 }
362
363 _FORCE_INLINE_ bool update(NSRange p_range, id<MTLBuffer> __unsafe_unretained const *p_values, const NSUInteger *p_offsets) {
364 if (p_range.length == 0) {
365 return false;
366 }
367 uint32_t required = (uint32_t)(p_range.location + p_range.length);
368 ensure_size(buffers, required);
369 BufferBinding *buffers_ptr = buffers.ptr() + p_range.location;
370 bool changed = false;
371 for (NSUInteger i = 0; i < p_range.length; ++i) {
372 BufferBinding &binding = *buffers_ptr;
373 BufferBinding new_binding = {
374 .buffer = p_values[i],
375 .offset = p_offsets[i],
376 };
377 if (binding != new_binding) {
378 binding = new_binding;
379 changed = true;
380 }
381 ++buffers_ptr;
382 }
383 return changed;
384 }
385
386 _FORCE_INLINE_ bool update(id<MTLBuffer> __unsafe_unretained p_buffer, NSUInteger p_offset, uint32_t p_index) {
387 uint32_t required = p_index + 1;
388 ensure_size(buffers, required);
389 BufferBinding &binding = buffers.ptr()[p_index];
390 BufferBinding new_binding = {
391 .buffer = p_buffer,
392 .offset = p_offset,
393 };
394 if (binding != new_binding) {
395 binding = new_binding;
396 return true;
397 }
398 return false;
399 }
400 };
401
402 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDCommandBuffer {
403 friend class MDUniformSet;
404
405 private:
406 #pragma mark - Common State
407
408 // From RenderingDevice
409 static constexpr uint32_t MAX_PUSH_CONSTANT_SIZE = 128;
410
411 uint8_t push_constant_data[MAX_PUSH_CONSTANT_SIZE];
412 uint32_t push_constant_data_len = 0;
413 uint32_t push_constant_binding = UINT32_MAX;
414
415 BindingCache binding_cache;
416
417 void reset();
418
419 RenderingDeviceDriverMetal *device_driver = nullptr;
420 id<MTLCommandQueue> queue = nil;
421 id<MTLCommandBuffer> commandBuffer = nil;
422 bool state_begin = false;
423
424 _FORCE_INLINE_ id<MTLCommandBuffer> command_buffer() {
425 DEV_ASSERT(state_begin);
426 if (commandBuffer == nil) {
427 commandBuffer = queue.commandBuffer;
428 }
429 return commandBuffer;
430 }
431
432 void _end_compute_dispatch();
433 void _end_blit();
434 id<MTLBlitCommandEncoder> _ensure_blit_encoder();
435
436 enum class CopySource {
437 Buffer,
438 Texture,
439 };
440 void _copy_texture_buffer(CopySource p_source,
441 RDD::TextureID p_texture,
442 RDD::BufferID p_buffer,
443 VectorView<RDD::BufferTextureCopyRegion> p_regions);
444
445 #pragma mark - Render
446
447 void _render_set_dirty_state();
448 void _render_bind_uniform_sets();
449
450 void _populate_vertices(simd::float4 *p_vertices, Size2i p_fb_size, VectorView<Rect2i> p_rects);
451 uint32_t _populate_vertices(simd::float4 *p_vertices, uint32_t p_index, Rect2i const &p_rect, Size2i p_fb_size);
452 void _end_render_pass();
453 void _render_clear_render_area();
454
455 #pragma mark - Compute
456
457 void _compute_set_dirty_state();
458 void _compute_bind_uniform_sets();
459
460 public:
461 MDCommandBufferStateType type = MDCommandBufferStateType::None;
462
463 struct RenderState {
464 MDRenderPass *pass = nullptr;
465 MDFrameBuffer *frameBuffer = nullptr;
466 MDRenderPipeline *pipeline = nullptr;
467 LocalVector<RDD::RenderPassClearValue> clear_values;
468 LocalVector<MTLViewport> viewports;
469 LocalVector<MTLScissorRect> scissors;
470 std::optional<Color> blend_constants;
471 uint32_t current_subpass = UINT32_MAX;
472 Rect2i render_area = {};
473 bool is_rendering_entire_area = false;
474 MTLRenderPassDescriptor *desc = nil;
475 id<MTLRenderCommandEncoder> encoder = nil;
476 id<MTLBuffer> __unsafe_unretained index_buffer = nil; // Buffer is owned by RDD.
477 MTLIndexType index_type = MTLIndexTypeUInt16;
478 uint32_t index_offset = 0;
479 LocalVector<id<MTLBuffer> __unsafe_unretained> vertex_buffers;
480 LocalVector<NSUInteger> vertex_offsets;
481 ResourceTracker resource_tracker;
482 // clang-format off
483 enum DirtyFlag: uint16_t {
484 DIRTY_NONE = 0,
485 DIRTY_PIPELINE = 1 << 0, //! pipeline state
486 DIRTY_UNIFORMS = 1 << 1, //! uniform sets
487 DIRTY_PUSH = 1 << 2, //! push constants
488 DIRTY_DEPTH = 1 << 3, //! depth / stencil state
489 DIRTY_VERTEX = 1 << 4, //! vertex buffers
490 DIRTY_VIEWPORT = 1 << 5, //! viewport rectangles
491 DIRTY_SCISSOR = 1 << 6, //! scissor rectangles
492 DIRTY_BLEND = 1 << 7, //! blend state
493 DIRTY_RASTER = 1 << 8, //! encoder state like cull mode
494 DIRTY_ALL = (1 << 9) - 1,
495 };
496 // clang-format on
497 BitField<DirtyFlag> dirty = DIRTY_NONE;
498
499 LocalVector<MDUniformSet *> uniform_sets;
500 uint32_t dynamic_offsets = 0;
501 // Bit mask of the uniform sets that are dirty, to prevent redundant binding.
502 uint64_t uniform_set_mask = 0;
503
504 _FORCE_INLINE_ void reset();
505 void end_encoding();
506
507 _ALWAYS_INLINE_ const MDSubpass &get_subpass() const {
508 DEV_ASSERT(pass != nullptr);
509 return pass->subpasses[current_subpass];
510 }
511
512 _FORCE_INLINE_ void mark_viewport_dirty() {
513 if (viewports.is_empty()) {
514 return;
515 }
516 dirty.set_flag(DirtyFlag::DIRTY_VIEWPORT);
517 }
518
519 _FORCE_INLINE_ void mark_scissors_dirty() {
520 if (scissors.is_empty()) {
521 return;
522 }
523 dirty.set_flag(DirtyFlag::DIRTY_SCISSOR);
524 }
525
526 _FORCE_INLINE_ void mark_vertex_dirty() {
527 if (vertex_buffers.is_empty()) {
528 return;
529 }
530 dirty.set_flag(DirtyFlag::DIRTY_VERTEX);
531 }
532
533 _FORCE_INLINE_ void mark_uniforms_dirty(std::initializer_list<uint32_t> l) {
534 if (uniform_sets.is_empty()) {
535 return;
536 }
537 for (uint32_t i : l) {
538 if (i < uniform_sets.size() && uniform_sets[i] != nullptr) {
539 uniform_set_mask |= 1 << i;
540 }
541 }
542 dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
543 }
544
545 _FORCE_INLINE_ void mark_uniforms_dirty(void) {
546 if (uniform_sets.is_empty()) {
547 return;
548 }
549 for (uint32_t i = 0; i < uniform_sets.size(); i++) {
550 if (uniform_sets[i] != nullptr) {
551 uniform_set_mask |= 1 << i;
552 }
553 }
554 dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
555 }
556
557 _FORCE_INLINE_ void mark_blend_dirty() {
558 if (!blend_constants.has_value()) {
559 return;
560 }
561 dirty.set_flag(DirtyFlag::DIRTY_BLEND);
562 }
563
564 MTLScissorRect clip_to_render_area(MTLScissorRect p_rect) const {
565 uint32_t raLeft = render_area.position.x;
566 uint32_t raRight = raLeft + render_area.size.width;
567 uint32_t raBottom = render_area.position.y;
568 uint32_t raTop = raBottom + render_area.size.height;
569
570 p_rect.x = CLAMP(p_rect.x, raLeft, MAX(raRight - 1, raLeft));
571 p_rect.y = CLAMP(p_rect.y, raBottom, MAX(raTop - 1, raBottom));
572 p_rect.width = MIN(p_rect.width, raRight - p_rect.x);
573 p_rect.height = MIN(p_rect.height, raTop - p_rect.y);
574
575 return p_rect;
576 }
577
578 Rect2i clip_to_render_area(Rect2i p_rect) const {
579 int32_t raLeft = render_area.position.x;
580 int32_t raRight = raLeft + render_area.size.width;
581 int32_t raBottom = render_area.position.y;
582 int32_t raTop = raBottom + render_area.size.height;
583
584 p_rect.position.x = CLAMP(p_rect.position.x, raLeft, MAX(raRight - 1, raLeft));
585 p_rect.position.y = CLAMP(p_rect.position.y, raBottom, MAX(raTop - 1, raBottom));
586 p_rect.size.width = MIN(p_rect.size.width, raRight - p_rect.position.x);
587 p_rect.size.height = MIN(p_rect.size.height, raTop - p_rect.position.y);
588
589 return p_rect;
590 }
591
592 } render;
593
594 // State specific for a compute pass.
595 struct ComputeState {
596 MDComputePipeline *pipeline = nullptr;
597 id<MTLComputeCommandEncoder> encoder = nil;
598 ResourceTracker resource_tracker;
599 // clang-format off
600 enum DirtyFlag: uint16_t {
601 DIRTY_NONE = 0,
602 DIRTY_PIPELINE = 1 << 0, //! pipeline state
603 DIRTY_UNIFORMS = 1 << 1, //! uniform sets
604 DIRTY_PUSH = 1 << 2, //! push constants
605 DIRTY_ALL = (1 << 3) - 1,
606 };
607 // clang-format on
608 BitField<DirtyFlag> dirty = DIRTY_NONE;
609
610 LocalVector<MDUniformSet *> uniform_sets;
611 uint32_t dynamic_offsets = 0;
612 // Bit mask of the uniform sets that are dirty, to prevent redundant binding.
613 uint64_t uniform_set_mask = 0;
614
615 _FORCE_INLINE_ void reset();
616 void end_encoding();
617
618 _FORCE_INLINE_ void mark_uniforms_dirty(void) {
619 if (uniform_sets.is_empty()) {
620 return;
621 }
622 for (uint32_t i = 0; i < uniform_sets.size(); i++) {
623 if (uniform_sets[i] != nullptr) {
624 uniform_set_mask |= 1 << i;
625 }
626 }
627 dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
628 }
629 } compute;
630
631 // State specific to a blit pass.
632 struct {
633 id<MTLBlitCommandEncoder> encoder = nil;
634 _FORCE_INLINE_ void reset() {
635 encoder = nil;
636 }
637 } blit;
638
639 _FORCE_INLINE_ id<MTLCommandBuffer> get_command_buffer() const {
640 return commandBuffer;
641 }
642
643 void begin();
644 void commit();
645 void end();
646
647 void bind_pipeline(RDD::PipelineID p_pipeline);
648 void encode_push_constant_data(RDD::ShaderID p_shader, VectorView<uint32_t> p_data);
649
650 #pragma mark - Render Commands
651
652 void render_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);
653 void render_clear_attachments(VectorView<RDD::AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects);
654 void render_set_viewport(VectorView<Rect2i> p_viewports);
655 void render_set_scissor(VectorView<Rect2i> p_scissors);
656 void render_set_blend_constants(const Color &p_constants);
657 void render_begin_pass(RDD::RenderPassID p_render_pass,
658 RDD::FramebufferID p_frameBuffer,
659 RDD::CommandBufferType p_cmd_buffer_type,
660 const Rect2i &p_rect,
661 VectorView<RDD::RenderPassClearValue> p_clear_values);
662 void render_next_subpass();
663 void render_draw(uint32_t p_vertex_count,
664 uint32_t p_instance_count,
665 uint32_t p_base_vertex,
666 uint32_t p_first_instance);
667 void render_bind_vertex_buffers(uint32_t p_binding_count, const RDD::BufferID *p_buffers, const uint64_t *p_offsets, uint64_t p_dynamic_offsets);
668 void render_bind_index_buffer(RDD::BufferID p_buffer, RDD::IndexBufferFormat p_format, uint64_t p_offset);
669
670 void render_draw_indexed(uint32_t p_index_count,
671 uint32_t p_instance_count,
672 uint32_t p_first_index,
673 int32_t p_vertex_offset,
674 uint32_t p_first_instance);
675
676 void render_draw_indexed_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
677 void render_draw_indexed_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride);
678 void render_draw_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
679 void render_draw_indirect_count(RDD::BufferID p_indirect_buffer, uint64_t p_offset, RDD::BufferID p_count_buffer, uint64_t p_count_buffer_offset, uint32_t p_max_draw_count, uint32_t p_stride);
680
681 void render_end_pass();
682
683 #pragma mark - Compute Commands
684
685 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);
686 void compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
687 void compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset);
688
689 #pragma mark - Transfer
690
691 private:
692 void encodeRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor *p_desc, NSString *p_label);
693
694 public:
695 void resolve_texture(RDD::TextureID p_src_texture, RDD::TextureLayout p_src_texture_layout, uint32_t p_src_layer, uint32_t p_src_mipmap, RDD::TextureID p_dst_texture, RDD::TextureLayout p_dst_texture_layout, uint32_t p_dst_layer, uint32_t p_dst_mipmap);
696 void clear_color_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, const Color &p_color, const RDD::TextureSubresourceRange &p_subresources);
697 void clear_depth_stencil_texture(RDD::TextureID p_texture, RDD::TextureLayout p_texture_layout, float p_depth, uint8_t p_stencil, const RDD::TextureSubresourceRange &p_subresources);
698 void clear_buffer(RDD::BufferID p_buffer, uint64_t p_offset, uint64_t p_size);
699 void copy_buffer(RDD::BufferID p_src_buffer, RDD::BufferID p_dst_buffer, VectorView<RDD::BufferCopyRegion> p_regions);
700 void copy_texture(RDD::TextureID p_src_texture, RDD::TextureID p_dst_texture, VectorView<RDD::TextureCopyRegion> p_regions);
701 void copy_buffer_to_texture(RDD::BufferID p_src_buffer, RDD::TextureID p_dst_texture, VectorView<RDD::BufferTextureCopyRegion> p_regions);
702 void copy_texture_to_buffer(RDD::TextureID p_src_texture, RDD::BufferID p_dst_buffer, VectorView<RDD::BufferTextureCopyRegion> p_regions);
703
704 #pragma mark - Debugging
705
706 void begin_label(const char *p_label_name, const Color &p_color);
707 void end_label();
708
709 MDCommandBuffer(id<MTLCommandQueue> p_queue, RenderingDeviceDriverMetal *p_device_driver) :
710 device_driver(p_device_driver), queue(p_queue) {
711 type = MDCommandBufferStateType::None;
712 }
713
714 MDCommandBuffer() = default;
715 };
716
717 #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED < 140000) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED < 170000)
718 #define MTLBindingAccess MTLArgumentAccess
719 #define MTLBindingAccessReadOnly MTLArgumentAccessReadOnly
720 #define MTLBindingAccessReadWrite MTLArgumentAccessReadWrite
721 #define MTLBindingAccessWriteOnly MTLArgumentAccessWriteOnly
722 #endif
723
724 struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformInfo {
725 uint32_t binding;
726 BitField<RDD::ShaderStage> active_stages;
727 MTLDataType dataType = MTLDataTypeNone;
728 MTLBindingAccess access = MTLBindingAccessReadOnly;
729 MTLResourceUsage usage = 0;
730 MTLTextureType textureType = MTLTextureType2D;
731 uint32_t imageFormat = 0;
732 uint32_t arrayLength = 0;
733 bool isMultisampled = 0;
734
735 struct Indexes {
736 uint32_t buffer = UINT32_MAX;
737 uint32_t texture = UINT32_MAX;
738 uint32_t sampler = UINT32_MAX;
739 };
740 Indexes slot;
741 Indexes arg_buffer;
742
743 enum class IndexType {
744 SLOT,
745 ARG,
746 };
747
748 _FORCE_INLINE_ Indexes &get_indexes(IndexType p_type) {
749 switch (p_type) {
750 case IndexType::SLOT:
751 return slot;
752 case IndexType::ARG:
753 return arg_buffer;
754 }
755 }
756 };
757
758 struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformSet {
759 LocalVector<UniformInfo> uniforms;
760 LocalVector<uint32_t> dynamic_uniforms;
761 uint32_t buffer_size = 0;
762 };
763
764 struct ShaderCacheEntry;
765
766 enum class ShaderLoadStrategy {
767 IMMEDIATE,
768 LAZY,
769
770 /// The default strategy is to load the shader immediately.
771 DEFAULT = IMMEDIATE,
772 };
773
774 /// A Metal shader library.
775 @interface MDLibrary : NSObject {
776 ShaderCacheEntry *_entry;
777 NSString *_original_source;
778 };
779 - (id<MTLLibrary>)library;
780 - (NSError *)error;
781 - (void)setLabel:(NSString *)label;
782 #ifdef DEV_ENABLED
783 - (NSString *)originalSource;
784 #endif
785
786 + (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry
787 device:(id<MTLDevice>)device
788 source:(NSString *)source
789 options:(MTLCompileOptions *)options
790 strategy:(ShaderLoadStrategy)strategy;
791
792 + (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry
793 device:(id<MTLDevice>)device
794 #ifdef DEV_ENABLED
795 source:(NSString *)source
796 #endif
797 data:(dispatch_data_t)data;
798 @end
799
800 /// A cache entry for a Metal shader library.
801 struct ShaderCacheEntry {
802 RenderingDeviceDriverMetal &owner;
803 /// A hash of the Metal shader source code.
804 SHA256Digest key;
805 CharString name;
806 RD::ShaderStage stage = RD::SHADER_STAGE_VERTEX;
807 /// This reference must be weak, to ensure that when the last strong reference to the library
808 /// is released, the cache entry is freed.
809 MDLibrary *__weak library = nil;
810
811 /// Notify the cache that this entry is no longer needed.
812 void notify_free() const;
813
814 ShaderCacheEntry(RenderingDeviceDriverMetal &p_owner, SHA256Digest p_key) :
815 owner(p_owner), key(p_key) {
816 }
817 ~ShaderCacheEntry() = default;
818 };
819
820 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) DynamicOffsetLayout {
821 struct Data {
822 uint8_t offset : 4;
823 uint8_t count : 4;
824 };
825
826 union {
827 Data data[MAX_DYNAMIC_BUFFERS];
828 uint64_t _val = 0;
829 };
830
831 public:
832 _FORCE_INLINE_ bool is_empty() const { return _val == 0; }
833
834 _FORCE_INLINE_ uint32_t get_count(uint32_t p_set_index) const {
835 return data[p_set_index].count;
836 }
837
838 _FORCE_INLINE_ uint32_t get_offset(uint32_t p_set_index) const {
839 return data[p_set_index].offset;
840 }
841
842 _FORCE_INLINE_ void set_offset_count(uint32_t p_set_index, uint8_t p_offset, uint8_t p_count) {
843 data[p_set_index].offset = p_offset;
844 data[p_set_index].count = p_count;
845 }
846
847 _FORCE_INLINE_ uint32_t get_offset_index_shift(uint32_t p_set_index, uint32_t p_dynamic_index = 0) const {
848 return (data[p_set_index].offset + p_dynamic_index) * 4u;
849 }
850 };
851
852 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDShader {
853 public:
854 CharString name;
855 Vector<UniformSet> sets;
856 struct {
857 BitField<RDD::ShaderStage> stages = {};
858 uint32_t binding = UINT32_MAX;
859 uint32_t size = 0;
860 } push_constants;
861 DynamicOffsetLayout dynamic_offset_layout;
862 bool uses_argument_buffers = true;
863
864 MDShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers) :
865 name(p_name), sets(p_sets), uses_argument_buffers(p_uses_argument_buffers) {}
866 virtual ~MDShader() = default;
867 };
868
869 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputeShader final : public MDShader {
870 public:
871 MTLSize local = {};
872
873 MDLibrary *kernel;
874
875 MDComputeShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers, MDLibrary *p_kernel);
876 };
877
878 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderShader final : public MDShader {
879 public:
880 bool needs_view_mask_buffer = false;
881
882 MDLibrary *vert;
883 MDLibrary *frag;
884
885 MDRenderShader(CharString p_name,
886 Vector<UniformSet> p_sets,
887 bool p_needs_view_mask_buffer,
888 bool p_uses_argument_buffers,
889 MDLibrary *p_vert, MDLibrary *p_frag);
890 };
891
892 _FORCE_INLINE_ StageResourceUsage &operator|=(StageResourceUsage &p_a, uint32_t p_b) {
893 p_a = StageResourceUsage(uint32_t(p_a) | p_b);
894 return p_a;
895 }
896
897 _FORCE_INLINE_ StageResourceUsage stage_resource_usage(RDC::ShaderStage p_stage, MTLResourceUsage p_usage) {
898 return StageResourceUsage(p_usage << (p_stage * 2));
899 }
900
901 _FORCE_INLINE_ MTLResourceUsage resource_usage_for_stage(StageResourceUsage p_usage, RDC::ShaderStage p_stage) {
902 return MTLResourceUsage((p_usage >> (p_stage * 2)) & 0b11);
903 }
904
905 template <>
906 struct HashMapComparatorDefault<RDD::ShaderID> {
907 static bool compare(const RDD::ShaderID &p_lhs, const RDD::ShaderID &p_rhs) {
908 return p_lhs.id == p_rhs.id;
909 }
910 };
911
912 template <>
913 struct HashMapComparatorDefault<RDD::BufferID> {
914 static bool compare(const RDD::BufferID &p_lhs, const RDD::BufferID &p_rhs) {
915 return p_lhs.id == p_rhs.id;
916 }
917 };
918
919 template <>
920 struct HashMapComparatorDefault<RDD::TextureID> {
921 static bool compare(const RDD::TextureID &p_lhs, const RDD::TextureID &p_rhs) {
922 return p_lhs.id == p_rhs.id;
923 }
924 };
925
926 template <>
927 struct HashMapHasherDefaultImpl<RDD::BufferID> {
928 static _FORCE_INLINE_ uint32_t hash(const RDD::BufferID &p_value) {
929 return HashMapHasherDefaultImpl<uint64_t>::hash(p_value.id);
930 }
931 };
932
933 template <>
934 struct HashMapHasherDefaultImpl<RDD::TextureID> {
935 static _FORCE_INLINE_ uint32_t hash(const RDD::TextureID &p_value) {
936 return HashMapHasherDefaultImpl<uint64_t>::hash(p_value.id);
937 }
938 };
939
940 // A type used to encode resources directly to a MTLCommandEncoder
941 struct DirectEncoder {
942 id<MTLCommandEncoder> __unsafe_unretained encoder;
943 BindingCache &cache;
944 enum Mode {
945 RENDER,
946 COMPUTE
947 };
948 Mode mode;
949
950 void set(id<MTLBuffer> __unsafe_unretained *p_buffers, const NSUInteger *p_offsets, NSRange p_range);
951 void set(id<MTLBuffer> __unsafe_unretained p_buffer, const NSUInteger p_offset, uint32_t p_index);
952 void set(id<MTLTexture> __unsafe_unretained *p_textures, NSRange p_range);
953 void set(id<MTLSamplerState> __unsafe_unretained *p_samplers, NSRange p_range);
954
955 DirectEncoder(id<MTLCommandEncoder> __unsafe_unretained p_encoder, BindingCache &p_cache) :
956 encoder(p_encoder), cache(p_cache) {
957 if ([p_encoder conformsToProtocol:@protocol(MTLRenderCommandEncoder)]) {
958 mode = RENDER;
959 } else {
960 mode = COMPUTE;
961 }
962 }
963 };
964
965 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDUniformSet {
966 public:
967 uint32_t index = 0;
968 id<MTLBuffer> arg_buffer = nil;
969 ResourceUsageMap usage_to_resources;
970 LocalVector<RDD::BoundUniform> uniforms;
971
972 void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::RenderState &p_state, uint32_t p_set_index, uint32_t p_dynamic_offsets, uint32_t p_frame_idx, uint32_t p_frame_count);
973 void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state, uint32_t p_set_index, uint32_t p_dynamic_offsets, uint32_t p_frame_idx, uint32_t p_frame_count);
974 void bind_uniforms_direct(MDShader *p_shader, DirectEncoder p_enc, uint32_t p_set_index, uint32_t p_dynamic_offsets);
975 };
976
977 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDPipeline {
978 public:
979 MDPipelineType type;
980
981 explicit MDPipeline(MDPipelineType p_type) :
982 type(p_type) {}
983 virtual ~MDPipeline() = default;
984 };
985
986 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPipeline final : public MDPipeline {
987 public:
988 id<MTLRenderPipelineState> state = nil;
989 id<MTLDepthStencilState> depth_stencil = nil;
990 uint32_t push_constant_size = 0;
991 uint32_t push_constant_stages_mask = 0;
992 SampleCount sample_count = SampleCount1;
993
994 struct {
995 MTLCullMode cull_mode = MTLCullModeNone;
996 MTLTriangleFillMode fill_mode = MTLTriangleFillModeFill;
997 MTLDepthClipMode clip_mode = MTLDepthClipModeClip;
998 MTLWinding winding = MTLWindingClockwise;
999 MTLPrimitiveType render_primitive = MTLPrimitiveTypePoint;
1000
1001 struct {
1002 bool enabled = false;
1003 } depth_test;
1004
1005 struct {
1006 bool enabled = false;
1007 float depth_bias = 0.0;
1008 float slope_scale = 0.0;
1009 float clamp = 0.0;
1010 _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
1011 if (!enabled) {
1012 return;
1013 }
1014 [p_enc setDepthBias:depth_bias slopeScale:slope_scale clamp:clamp];
1015 }
1016 } depth_bias;
1017
1018 struct {
1019 bool enabled = false;
1020 uint32_t front_reference = 0;
1021 uint32_t back_reference = 0;
1022 _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
1023 if (!enabled) {
1024 return;
1025 }
1026 [p_enc setStencilFrontReferenceValue:front_reference backReferenceValue:back_reference];
1027 }
1028 } stencil;
1029
1030 struct {
1031 bool enabled = false;
1032 float r = 0.0;
1033 float g = 0.0;
1034 float b = 0.0;
1035 float a = 0.0;
1036
1037 _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
1038 //if (!enabled)
1039 // return;
1040 [p_enc setBlendColorRed:r green:g blue:b alpha:a];
1041 }
1042 } blend;
1043
1044 _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
1045 [p_enc setCullMode:cull_mode];
1046 [p_enc setTriangleFillMode:fill_mode];
1047 [p_enc setDepthClipMode:clip_mode];
1048 [p_enc setFrontFacingWinding:winding];
1049 depth_bias.apply(p_enc);
1050 stencil.apply(p_enc);
1051 blend.apply(p_enc);
1052 }
1053
1054 } raster_state;
1055
1056 MDRenderShader *shader = nil;
1057
1058 MDRenderPipeline() :
1059 MDPipeline(MDPipelineType::Render) {}
1060 ~MDRenderPipeline() final = default;
1061 };
1062
1063 class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputePipeline final : public MDPipeline {
1064 public:
1065 id<MTLComputePipelineState> state = nil;
1066 struct {
1067 MTLSize local = {};
1068 } compute_state;
1069
1070 MDComputeShader *shader = nil;
1071
1072 explicit MDComputePipeline(id<MTLComputePipelineState> p_state) :
1073 MDPipeline(MDPipelineType::Compute), state(p_state) {}
1074 ~MDComputePipeline() final = default;
1075 };
1076
1077 namespace rid {
1078 #define MAKE_ID(FROM, TO) \
1079 _FORCE_INLINE_ TO make(FROM p_obj) { \
1080 return TO(owned(p_obj)); \
1081 }
1082
1083 MAKE_ID(id<MTLCommandQueue>, RDD::CommandPoolID)
1084
1085 #undef MAKE_ID
1086 } //namespace rid