metal_objects.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. /* */
  32. /* Portions of this code were derived from MoltenVK. */
  33. /* */
  34. /* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. */
  35. /* (http://www.brenwill.com) */
  36. /* */
  37. /* Licensed under the Apache License, Version 2.0 (the "License"); */
  38. /* you may not use this file except in compliance with the License. */
  39. /* You may obtain a copy of the License at */
  40. /* */
  41. /* http://www.apache.org/licenses/LICENSE-2.0 */
  42. /* */
  43. /* Unless required by applicable law or agreed to in writing, software */
  44. /* distributed under the License is distributed on an "AS IS" BASIS, */
  45. /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
  46. /* implied. See the License for the specific language governing */
  47. /* permissions and limitations under the License. */
  48. /**************************************************************************/
  49. #ifndef METAL_OBJECTS_H
  50. #define METAL_OBJECTS_H
  51. #import "metal_device_properties.h"
  52. #import "metal_utils.h"
  53. #import "pixel_formats.h"
  54. #import "servers/rendering/rendering_device_driver.h"
  55. #import <CommonCrypto/CommonDigest.h>
  56. #import <Foundation/Foundation.h>
  57. #import <Metal/Metal.h>
  58. #import <QuartzCore/CAMetalLayer.h>
  59. #import <simd/simd.h>
  60. #import <zlib.h>
  61. #import <initializer_list>
  62. #import <optional>
  63. // These types can be used in Vector and other containers that use
  64. // pointer operations not supported by ARC.
  65. namespace MTL {
  66. #define MTL_CLASS(name) \
  67. class name { \
  68. public: \
  69. name(id<MTL##name> obj = nil) : m_obj(obj) {} \
  70. operator id<MTL##name>() const { \
  71. return m_obj; \
  72. } \
  73. id<MTL##name> m_obj; \
  74. };
  75. MTL_CLASS(Texture)
  76. } //namespace MTL
  77. /// Metal buffer index for the view mask when rendering multi-view.
  78. const uint32_t VIEW_MASK_BUFFER_INDEX = 24;
  79. enum ShaderStageUsage : uint32_t {
  80. None = 0,
  81. Vertex = RDD::SHADER_STAGE_VERTEX_BIT,
  82. Fragment = RDD::SHADER_STAGE_FRAGMENT_BIT,
  83. TesselationControl = RDD::SHADER_STAGE_TESSELATION_CONTROL_BIT,
  84. TesselationEvaluation = RDD::SHADER_STAGE_TESSELATION_EVALUATION_BIT,
  85. Compute = RDD::SHADER_STAGE_COMPUTE_BIT,
  86. };
  87. _FORCE_INLINE_ ShaderStageUsage &operator|=(ShaderStageUsage &p_a, int p_b) {
  88. p_a = ShaderStageUsage(uint32_t(p_a) | uint32_t(p_b));
  89. return p_a;
  90. }
  91. enum StageResourceUsage : uint32_t {
  92. VertexRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_VERTEX * 2),
  93. VertexWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_VERTEX * 2),
  94. FragmentRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_FRAGMENT * 2),
  95. FragmentWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_FRAGMENT * 2),
  96. TesselationControlRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
  97. TesselationControlWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_CONTROL * 2),
  98. TesselationEvaluationRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
  99. TesselationEvaluationWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_TESSELATION_EVALUATION * 2),
  100. ComputeRead = (MTLResourceUsageRead << RDD::SHADER_STAGE_COMPUTE * 2),
  101. ComputeWrite = (MTLResourceUsageWrite << RDD::SHADER_STAGE_COMPUTE * 2),
  102. };
  103. typedef LocalVector<__unsafe_unretained id<MTLResource>> ResourceVector;
  104. typedef HashMap<StageResourceUsage, ResourceVector> ResourceUsageMap;
  105. enum class MDCommandBufferStateType {
  106. None,
  107. Render,
  108. Compute,
  109. Blit,
  110. };
  111. enum class MDPipelineType {
  112. None,
  113. Render,
  114. Compute,
  115. };
  116. class MDRenderPass;
  117. class MDPipeline;
  118. class MDRenderPipeline;
  119. class MDComputePipeline;
  120. class MDFrameBuffer;
  121. class RenderingDeviceDriverMetal;
  122. class MDUniformSet;
  123. class MDShader;
  124. #pragma mark - Resource Factory
  125. struct ClearAttKey {
  126. const static uint32_t COLOR_COUNT = MAX_COLOR_ATTACHMENT_COUNT;
  127. const static uint32_t DEPTH_INDEX = COLOR_COUNT;
  128. const static uint32_t STENCIL_INDEX = DEPTH_INDEX + 1;
  129. const static uint32_t ATTACHMENT_COUNT = STENCIL_INDEX + 1;
  130. enum Flags : uint16_t {
  131. CLEAR_FLAGS_NONE = 0,
  132. CLEAR_FLAGS_LAYERED = 1 << 0,
  133. };
  134. Flags flags = CLEAR_FLAGS_NONE;
  135. uint16_t sample_count = 0;
  136. uint16_t pixel_formats[ATTACHMENT_COUNT] = { 0 };
  137. _FORCE_INLINE_ void set_color_format(uint32_t p_idx, MTLPixelFormat p_fmt) { pixel_formats[p_idx] = p_fmt; }
  138. _FORCE_INLINE_ void set_depth_format(MTLPixelFormat p_fmt) { pixel_formats[DEPTH_INDEX] = p_fmt; }
  139. _FORCE_INLINE_ void set_stencil_format(MTLPixelFormat p_fmt) { pixel_formats[STENCIL_INDEX] = p_fmt; }
  140. _FORCE_INLINE_ MTLPixelFormat depth_format() const { return (MTLPixelFormat)pixel_formats[DEPTH_INDEX]; }
  141. _FORCE_INLINE_ MTLPixelFormat stencil_format() const { return (MTLPixelFormat)pixel_formats[STENCIL_INDEX]; }
  142. _FORCE_INLINE_ void enable_layered_rendering() { flags::set(flags, CLEAR_FLAGS_LAYERED); }
  143. _FORCE_INLINE_ bool is_enabled(uint32_t p_idx) const { return pixel_formats[p_idx] != 0; }
  144. _FORCE_INLINE_ bool is_depth_enabled() const { return pixel_formats[DEPTH_INDEX] != 0; }
  145. _FORCE_INLINE_ bool is_stencil_enabled() const { return pixel_formats[STENCIL_INDEX] != 0; }
  146. _FORCE_INLINE_ bool is_layered_rendering_enabled() const { return flags::any(flags, CLEAR_FLAGS_LAYERED); }
  147. _FORCE_INLINE_ bool operator==(const ClearAttKey &p_rhs) const {
  148. return memcmp(this, &p_rhs, sizeof(ClearAttKey)) == 0;
  149. }
  150. uint32_t hash() const {
  151. uint32_t h = hash_murmur3_one_32(flags);
  152. h = hash_murmur3_one_32(sample_count, h);
  153. h = hash_murmur3_buffer(pixel_formats, ATTACHMENT_COUNT * sizeof(pixel_formats[0]), h);
  154. return hash_fmix32(h);
  155. }
  156. };
  157. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceFactory {
  158. private:
  159. RenderingDeviceDriverMetal *device_driver;
  160. id<MTLFunction> new_func(NSString *p_source, NSString *p_name, NSError **p_error);
  161. id<MTLFunction> new_clear_vert_func(ClearAttKey &p_key);
  162. id<MTLFunction> new_clear_frag_func(ClearAttKey &p_key);
  163. NSString *get_format_type_string(MTLPixelFormat p_fmt);
  164. public:
  165. id<MTLRenderPipelineState> new_clear_pipeline_state(ClearAttKey &p_key, NSError **p_error);
  166. id<MTLDepthStencilState> new_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
  167. MDResourceFactory(RenderingDeviceDriverMetal *p_device_driver) :
  168. device_driver(p_device_driver) {}
  169. ~MDResourceFactory() = default;
  170. };
  171. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDResourceCache {
  172. private:
  173. typedef HashMap<ClearAttKey, id<MTLRenderPipelineState>, HashableHasher<ClearAttKey>> HashMap;
  174. std::unique_ptr<MDResourceFactory> resource_factory;
  175. HashMap clear_states;
  176. struct {
  177. id<MTLDepthStencilState> all;
  178. id<MTLDepthStencilState> depth_only;
  179. id<MTLDepthStencilState> stencil_only;
  180. id<MTLDepthStencilState> none;
  181. } clear_depth_stencil_state;
  182. public:
  183. id<MTLRenderPipelineState> get_clear_render_pipeline_state(ClearAttKey &p_key, NSError **p_error);
  184. id<MTLDepthStencilState> get_depth_stencil_state(bool p_use_depth, bool p_use_stencil);
  185. explicit MDResourceCache(RenderingDeviceDriverMetal *p_device_driver) :
  186. resource_factory(new MDResourceFactory(p_device_driver)) {}
  187. ~MDResourceCache() = default;
  188. };
  189. enum class MDAttachmentType : uint8_t {
  190. None = 0,
  191. Color = 1 << 0,
  192. Depth = 1 << 1,
  193. Stencil = 1 << 2,
  194. };
  195. _FORCE_INLINE_ MDAttachmentType &operator|=(MDAttachmentType &p_a, MDAttachmentType p_b) {
  196. flags::set(p_a, p_b);
  197. return p_a;
  198. }
  199. _FORCE_INLINE_ bool operator&(MDAttachmentType p_a, MDAttachmentType p_b) {
  200. return uint8_t(p_a) & uint8_t(p_b);
  201. }
  202. struct MDSubpass {
  203. uint32_t subpass_index = 0;
  204. uint32_t view_count = 0;
  205. LocalVector<RDD::AttachmentReference> input_references;
  206. LocalVector<RDD::AttachmentReference> color_references;
  207. RDD::AttachmentReference depth_stencil_reference;
  208. LocalVector<RDD::AttachmentReference> resolve_references;
  209. MTLFmtCaps getRequiredFmtCapsForAttachmentAt(uint32_t p_index) const;
  210. };
  211. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDAttachment {
  212. private:
  213. uint32_t index = 0;
  214. uint32_t firstUseSubpassIndex = 0;
  215. uint32_t lastUseSubpassIndex = 0;
  216. public:
  217. MTLPixelFormat format = MTLPixelFormatInvalid;
  218. MDAttachmentType type = MDAttachmentType::None;
  219. MTLLoadAction loadAction = MTLLoadActionDontCare;
  220. MTLStoreAction storeAction = MTLStoreActionDontCare;
  221. MTLLoadAction stencilLoadAction = MTLLoadActionDontCare;
  222. MTLStoreAction stencilStoreAction = MTLStoreActionDontCare;
  223. uint32_t samples = 1;
  224. /*!
  225. * @brief Returns true if this attachment is first used in the given subpass.
  226. * @param p_subpass
  227. * @return
  228. */
  229. _FORCE_INLINE_ bool isFirstUseOf(MDSubpass const &p_subpass) const {
  230. return p_subpass.subpass_index == firstUseSubpassIndex;
  231. }
  232. /*!
  233. * @brief Returns true if this attachment is last used in the given subpass.
  234. * @param p_subpass
  235. * @return
  236. */
  237. _FORCE_INLINE_ bool isLastUseOf(MDSubpass const &p_subpass) const {
  238. return p_subpass.subpass_index == lastUseSubpassIndex;
  239. }
  240. void linkToSubpass(MDRenderPass const &p_pass);
  241. MTLStoreAction getMTLStoreAction(MDSubpass const &p_subpass,
  242. bool p_is_rendering_entire_area,
  243. bool p_has_resolve,
  244. bool p_can_resolve,
  245. bool p_is_stencil) const;
  246. bool configureDescriptor(MTLRenderPassAttachmentDescriptor *p_desc,
  247. PixelFormats &p_pf,
  248. MDSubpass const &p_subpass,
  249. id<MTLTexture> p_attachment,
  250. bool p_is_rendering_entire_area,
  251. bool p_has_resolve,
  252. bool p_can_resolve,
  253. bool p_is_stencil) const;
  254. /** Returns whether this attachment should be cleared in the subpass. */
  255. bool shouldClear(MDSubpass const &p_subpass, bool p_is_stencil) const;
  256. };
  257. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPass {
  258. public:
  259. Vector<MDAttachment> attachments;
  260. Vector<MDSubpass> subpasses;
  261. uint32_t get_sample_count() const {
  262. return attachments.is_empty() ? 1 : attachments[0].samples;
  263. }
  264. MDRenderPass(Vector<MDAttachment> &p_attachments, Vector<MDSubpass> &p_subpasses);
  265. };
  266. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDCommandBuffer {
  267. private:
  268. RenderingDeviceDriverMetal *device_driver = nullptr;
  269. id<MTLCommandQueue> queue = nil;
  270. id<MTLCommandBuffer> commandBuffer = nil;
  271. void _end_compute_dispatch();
  272. void _end_blit();
  273. #pragma mark - Render
  274. void _render_set_dirty_state();
  275. void _render_bind_uniform_sets();
  276. void _populate_vertices(simd::float4 *p_vertices, Size2i p_fb_size, VectorView<Rect2i> p_rects);
  277. uint32_t _populate_vertices(simd::float4 *p_vertices, uint32_t p_index, Rect2i const &p_rect, Size2i p_fb_size);
  278. void _end_render_pass();
  279. void _render_clear_render_area();
  280. public:
  281. MDCommandBufferStateType type = MDCommandBufferStateType::None;
  282. struct RenderState {
  283. MDRenderPass *pass = nullptr;
  284. MDFrameBuffer *frameBuffer = nullptr;
  285. MDRenderPipeline *pipeline = nullptr;
  286. LocalVector<RDD::RenderPassClearValue> clear_values;
  287. LocalVector<MTLViewport> viewports;
  288. LocalVector<MTLScissorRect> scissors;
  289. std::optional<Color> blend_constants;
  290. uint32_t current_subpass = UINT32_MAX;
  291. Rect2i render_area = {};
  292. bool is_rendering_entire_area = false;
  293. MTLRenderPassDescriptor *desc = nil;
  294. id<MTLRenderCommandEncoder> encoder = nil;
  295. id<MTLBuffer> __unsafe_unretained index_buffer = nil; // Buffer is owned by RDD.
  296. MTLIndexType index_type = MTLIndexTypeUInt16;
  297. uint32_t index_offset = 0;
  298. LocalVector<id<MTLBuffer> __unsafe_unretained> vertex_buffers;
  299. LocalVector<NSUInteger> vertex_offsets;
  300. ResourceUsageMap resource_usage;
  301. // clang-format off
  302. enum DirtyFlag: uint8_t {
  303. DIRTY_NONE = 0b0000'0000,
  304. DIRTY_PIPELINE = 0b0000'0001, //! pipeline state
  305. DIRTY_UNIFORMS = 0b0000'0010, //! uniform sets
  306. DIRTY_DEPTH = 0b0000'0100, //! depth / stenci state
  307. DIRTY_VERTEX = 0b0000'1000, //! vertex buffers
  308. DIRTY_VIEWPORT = 0b0001'0000, //! viewport rectangles
  309. DIRTY_SCISSOR = 0b0010'0000, //! scissor rectangles
  310. DIRTY_BLEND = 0b0100'0000, //! blend state
  311. DIRTY_RASTER = 0b1000'0000, //! encoder state like cull mode
  312. DIRTY_ALL = 0xff,
  313. };
  314. // clang-format on
  315. BitField<DirtyFlag> dirty = DIRTY_NONE;
  316. LocalVector<MDUniformSet *> uniform_sets;
  317. // Bit mask of the uniform sets that are dirty, to prevent redundant binding.
  318. uint64_t uniform_set_mask = 0;
  319. _FORCE_INLINE_ void reset();
  320. void end_encoding();
  321. _ALWAYS_INLINE_ const MDSubpass &get_subpass() const {
  322. DEV_ASSERT(pass != nullptr);
  323. return pass->subpasses[current_subpass];
  324. }
  325. _FORCE_INLINE_ void mark_viewport_dirty() {
  326. if (viewports.is_empty()) {
  327. return;
  328. }
  329. dirty.set_flag(DirtyFlag::DIRTY_VIEWPORT);
  330. }
  331. _FORCE_INLINE_ void mark_scissors_dirty() {
  332. if (scissors.is_empty()) {
  333. return;
  334. }
  335. dirty.set_flag(DirtyFlag::DIRTY_SCISSOR);
  336. }
  337. _FORCE_INLINE_ void mark_vertex_dirty() {
  338. if (vertex_buffers.is_empty()) {
  339. return;
  340. }
  341. dirty.set_flag(DirtyFlag::DIRTY_VERTEX);
  342. }
  343. _FORCE_INLINE_ void mark_uniforms_dirty(std::initializer_list<uint32_t> l) {
  344. if (uniform_sets.is_empty()) {
  345. return;
  346. }
  347. for (uint32_t i : l) {
  348. if (i < uniform_sets.size() && uniform_sets[i] != nullptr) {
  349. uniform_set_mask |= 1 << i;
  350. }
  351. }
  352. dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
  353. }
  354. _FORCE_INLINE_ void mark_uniforms_dirty(void) {
  355. if (uniform_sets.is_empty()) {
  356. return;
  357. }
  358. for (uint32_t i = 0; i < uniform_sets.size(); i++) {
  359. if (uniform_sets[i] != nullptr) {
  360. uniform_set_mask |= 1 << i;
  361. }
  362. }
  363. dirty.set_flag(DirtyFlag::DIRTY_UNIFORMS);
  364. }
  365. _FORCE_INLINE_ void mark_blend_dirty() {
  366. if (!blend_constants.has_value()) {
  367. return;
  368. }
  369. dirty.set_flag(DirtyFlag::DIRTY_BLEND);
  370. }
  371. MTLScissorRect clip_to_render_area(MTLScissorRect p_rect) const {
  372. uint32_t raLeft = render_area.position.x;
  373. uint32_t raRight = raLeft + render_area.size.width;
  374. uint32_t raBottom = render_area.position.y;
  375. uint32_t raTop = raBottom + render_area.size.height;
  376. p_rect.x = CLAMP(p_rect.x, raLeft, MAX(raRight - 1, raLeft));
  377. p_rect.y = CLAMP(p_rect.y, raBottom, MAX(raTop - 1, raBottom));
  378. p_rect.width = MIN(p_rect.width, raRight - p_rect.x);
  379. p_rect.height = MIN(p_rect.height, raTop - p_rect.y);
  380. return p_rect;
  381. }
  382. Rect2i clip_to_render_area(Rect2i p_rect) const {
  383. int32_t raLeft = render_area.position.x;
  384. int32_t raRight = raLeft + render_area.size.width;
  385. int32_t raBottom = render_area.position.y;
  386. int32_t raTop = raBottom + render_area.size.height;
  387. p_rect.position.x = CLAMP(p_rect.position.x, raLeft, MAX(raRight - 1, raLeft));
  388. p_rect.position.y = CLAMP(p_rect.position.y, raBottom, MAX(raTop - 1, raBottom));
  389. p_rect.size.width = MIN(p_rect.size.width, raRight - p_rect.position.x);
  390. p_rect.size.height = MIN(p_rect.size.height, raTop - p_rect.position.y);
  391. return p_rect;
  392. }
  393. } render;
  394. // State specific for a compute pass.
  395. struct ComputeState {
  396. MDComputePipeline *pipeline = nullptr;
  397. id<MTLComputeCommandEncoder> encoder = nil;
  398. ResourceUsageMap resource_usage;
  399. _FORCE_INLINE_ void reset() {
  400. pipeline = nil;
  401. encoder = nil;
  402. // Keep the keys, as they are likely to be used again.
  403. for (KeyValue<StageResourceUsage, LocalVector<__unsafe_unretained id<MTLResource>>> &kv : resource_usage) {
  404. kv.value.clear();
  405. }
  406. }
  407. void end_encoding();
  408. } compute;
  409. // State specific to a blit pass.
  410. struct {
  411. id<MTLBlitCommandEncoder> encoder = nil;
  412. _FORCE_INLINE_ void reset() {
  413. encoder = nil;
  414. }
  415. } blit;
  416. _FORCE_INLINE_ id<MTLCommandBuffer> get_command_buffer() const {
  417. return commandBuffer;
  418. }
  419. void begin();
  420. void commit();
  421. void end();
  422. id<MTLBlitCommandEncoder> blit_command_encoder();
  423. void encodeRenderCommandEncoderWithDescriptor(MTLRenderPassDescriptor *p_desc, NSString *p_label);
  424. void bind_pipeline(RDD::PipelineID p_pipeline);
  425. #pragma mark - Render Commands
  426. void render_bind_uniform_set(RDD::UniformSetID p_uniform_set, RDD::ShaderID p_shader, uint32_t p_set_index);
  427. 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);
  428. void render_clear_attachments(VectorView<RDD::AttachmentClear> p_attachment_clears, VectorView<Rect2i> p_rects);
  429. void render_set_viewport(VectorView<Rect2i> p_viewports);
  430. void render_set_scissor(VectorView<Rect2i> p_scissors);
  431. void render_set_blend_constants(const Color &p_constants);
  432. void render_begin_pass(RDD::RenderPassID p_render_pass,
  433. RDD::FramebufferID p_frameBuffer,
  434. RDD::CommandBufferType p_cmd_buffer_type,
  435. const Rect2i &p_rect,
  436. VectorView<RDD::RenderPassClearValue> p_clear_values);
  437. void render_next_subpass();
  438. void render_draw(uint32_t p_vertex_count,
  439. uint32_t p_instance_count,
  440. uint32_t p_base_vertex,
  441. uint32_t p_first_instance);
  442. void render_bind_vertex_buffers(uint32_t p_binding_count, const RDD::BufferID *p_buffers, const uint64_t *p_offsets);
  443. void render_bind_index_buffer(RDD::BufferID p_buffer, RDD::IndexBufferFormat p_format, uint64_t p_offset);
  444. void render_draw_indexed(uint32_t p_index_count,
  445. uint32_t p_instance_count,
  446. uint32_t p_first_index,
  447. int32_t p_vertex_offset,
  448. uint32_t p_first_instance);
  449. void render_draw_indexed_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
  450. 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);
  451. void render_draw_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset, uint32_t p_draw_count, uint32_t p_stride);
  452. 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);
  453. void render_end_pass();
  454. #pragma mark - Compute Commands
  455. void compute_bind_uniform_set(RDD::UniformSetID p_uniform_set, RDD::ShaderID p_shader, uint32_t p_set_index);
  456. 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);
  457. void compute_dispatch(uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups);
  458. void compute_dispatch_indirect(RDD::BufferID p_indirect_buffer, uint64_t p_offset);
  459. MDCommandBuffer(id<MTLCommandQueue> p_queue, RenderingDeviceDriverMetal *p_device_driver) :
  460. device_driver(p_device_driver), queue(p_queue) {
  461. type = MDCommandBufferStateType::None;
  462. }
  463. MDCommandBuffer() = default;
  464. };
  465. #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED < 140000) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED < 170000)
  466. #define MTLBindingAccess MTLArgumentAccess
  467. #define MTLBindingAccessReadOnly MTLArgumentAccessReadOnly
  468. #define MTLBindingAccessReadWrite MTLArgumentAccessReadWrite
  469. #define MTLBindingAccessWriteOnly MTLArgumentAccessWriteOnly
  470. #endif
  471. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) BindingInfo {
  472. MTLDataType dataType = MTLDataTypeNone;
  473. uint32_t index = 0;
  474. MTLBindingAccess access = MTLBindingAccessReadOnly;
  475. MTLResourceUsage usage = 0;
  476. MTLTextureType textureType = MTLTextureType2D;
  477. int imageFormat = 0;
  478. uint32_t arrayLength = 0;
  479. bool isMultisampled = false;
  480. inline MTLArgumentDescriptor *new_argument_descriptor() const {
  481. MTLArgumentDescriptor *desc = MTLArgumentDescriptor.argumentDescriptor;
  482. desc.dataType = dataType;
  483. desc.index = index;
  484. desc.access = access;
  485. desc.textureType = textureType;
  486. desc.arrayLength = arrayLength;
  487. return desc;
  488. }
  489. size_t serialize_size() const {
  490. return sizeof(uint32_t) * 8 /* 8 uint32_t fields */;
  491. }
  492. template <typename W>
  493. void serialize(W &p_writer) const {
  494. p_writer.write((uint32_t)dataType);
  495. p_writer.write(index);
  496. p_writer.write((uint32_t)access);
  497. p_writer.write((uint32_t)usage);
  498. p_writer.write((uint32_t)textureType);
  499. p_writer.write(imageFormat);
  500. p_writer.write(arrayLength);
  501. p_writer.write(isMultisampled);
  502. }
  503. template <typename R>
  504. void deserialize(R &p_reader) {
  505. p_reader.read((uint32_t &)dataType);
  506. p_reader.read(index);
  507. p_reader.read((uint32_t &)access);
  508. p_reader.read((uint32_t &)usage);
  509. p_reader.read((uint32_t &)textureType);
  510. p_reader.read((uint32_t &)imageFormat);
  511. p_reader.read(arrayLength);
  512. p_reader.read(isMultisampled);
  513. }
  514. };
  515. using RDC = RenderingDeviceCommons;
  516. typedef API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) HashMap<RDC::ShaderStage, BindingInfo> BindingInfoMap;
  517. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformInfo {
  518. uint32_t binding;
  519. ShaderStageUsage active_stages = None;
  520. BindingInfoMap bindings;
  521. BindingInfoMap bindings_secondary;
  522. };
  523. struct API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) UniformSet {
  524. LocalVector<UniformInfo> uniforms;
  525. uint32_t buffer_size = 0;
  526. HashMap<RDC::ShaderStage, uint32_t> offsets;
  527. HashMap<RDC::ShaderStage, id<MTLArgumentEncoder>> encoders;
  528. };
  529. struct ShaderCacheEntry;
  530. enum class ShaderLoadStrategy {
  531. DEFAULT,
  532. LAZY,
  533. };
  534. /// A Metal shader library.
  535. @interface MDLibrary : NSObject {
  536. ShaderCacheEntry *_entry;
  537. };
  538. - (id<MTLLibrary>)library;
  539. - (NSError *)error;
  540. - (void)setLabel:(NSString *)label;
  541. + (instancetype)newLibraryWithCacheEntry:(ShaderCacheEntry *)entry
  542. device:(id<MTLDevice>)device
  543. source:(NSString *)source
  544. options:(MTLCompileOptions *)options
  545. strategy:(ShaderLoadStrategy)strategy;
  546. @end
  547. struct SHA256Digest {
  548. unsigned char data[CC_SHA256_DIGEST_LENGTH];
  549. uint32_t hash() const {
  550. uint32_t c = crc32(0, data, CC_SHA256_DIGEST_LENGTH);
  551. return c;
  552. }
  553. SHA256Digest() {
  554. bzero(data, CC_SHA256_DIGEST_LENGTH);
  555. }
  556. SHA256Digest(const char *p_data, size_t p_length) {
  557. CC_SHA256(p_data, (CC_LONG)p_length, data);
  558. }
  559. _FORCE_INLINE_ uint32_t short_sha() const {
  560. return __builtin_bswap32(*(uint32_t *)&data[0]);
  561. }
  562. };
  563. template <>
  564. struct HashMapComparatorDefault<SHA256Digest> {
  565. static bool compare(const SHA256Digest &p_lhs, const SHA256Digest &p_rhs) {
  566. return memcmp(p_lhs.data, p_rhs.data, CC_SHA256_DIGEST_LENGTH) == 0;
  567. }
  568. };
  569. /// A cache entry for a Metal shader library.
  570. struct ShaderCacheEntry {
  571. RenderingDeviceDriverMetal &owner;
  572. /// A hash of the Metal shader source code.
  573. SHA256Digest key;
  574. CharString name;
  575. RD::ShaderStage stage = RD::SHADER_STAGE_VERTEX;
  576. /// This reference must be weak, to ensure that when the last strong reference to the library
  577. /// is released, the cache entry is freed.
  578. MDLibrary *__weak library = nil;
  579. /// Notify the cache that this entry is no longer needed.
  580. void notify_free() const;
  581. ShaderCacheEntry(RenderingDeviceDriverMetal &p_owner, SHA256Digest p_key) :
  582. owner(p_owner), key(p_key) {
  583. }
  584. ~ShaderCacheEntry() = default;
  585. };
  586. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDShader {
  587. public:
  588. CharString name;
  589. Vector<UniformSet> sets;
  590. bool uses_argument_buffers = true;
  591. virtual void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) = 0;
  592. MDShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers) :
  593. name(p_name), sets(p_sets), uses_argument_buffers(p_uses_argument_buffers) {}
  594. virtual ~MDShader() = default;
  595. };
  596. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputeShader final : public MDShader {
  597. public:
  598. struct {
  599. uint32_t binding = -1;
  600. uint32_t size = 0;
  601. } push_constants;
  602. MTLSize local = {};
  603. MDLibrary *kernel;
  604. #if DEV_ENABLED
  605. CharString kernel_source;
  606. #endif
  607. void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) final;
  608. MDComputeShader(CharString p_name, Vector<UniformSet> p_sets, bool p_uses_argument_buffers, MDLibrary *p_kernel);
  609. };
  610. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderShader final : public MDShader {
  611. public:
  612. struct {
  613. struct {
  614. int32_t binding = -1;
  615. uint32_t size = 0;
  616. } vert;
  617. struct {
  618. int32_t binding = -1;
  619. uint32_t size = 0;
  620. } frag;
  621. } push_constants;
  622. bool needs_view_mask_buffer = false;
  623. MDLibrary *vert;
  624. MDLibrary *frag;
  625. #if DEV_ENABLED
  626. CharString vert_source;
  627. CharString frag_source;
  628. #endif
  629. void encode_push_constant_data(VectorView<uint32_t> p_data, MDCommandBuffer *p_cb) final;
  630. MDRenderShader(CharString p_name,
  631. Vector<UniformSet> p_sets,
  632. bool p_needs_view_mask_buffer,
  633. bool p_uses_argument_buffers,
  634. MDLibrary *p_vert, MDLibrary *p_frag);
  635. };
  636. _FORCE_INLINE_ StageResourceUsage &operator|=(StageResourceUsage &p_a, uint32_t p_b) {
  637. p_a = StageResourceUsage(uint32_t(p_a) | p_b);
  638. return p_a;
  639. }
  640. _FORCE_INLINE_ StageResourceUsage stage_resource_usage(RDC::ShaderStage p_stage, MTLResourceUsage p_usage) {
  641. return StageResourceUsage(p_usage << (p_stage * 2));
  642. }
  643. _FORCE_INLINE_ MTLResourceUsage resource_usage_for_stage(StageResourceUsage p_usage, RDC::ShaderStage p_stage) {
  644. return MTLResourceUsage((p_usage >> (p_stage * 2)) & 0b11);
  645. }
  646. template <>
  647. struct HashMapComparatorDefault<RDD::ShaderID> {
  648. static bool compare(const RDD::ShaderID &p_lhs, const RDD::ShaderID &p_rhs) {
  649. return p_lhs.id == p_rhs.id;
  650. }
  651. };
  652. struct BoundUniformSet {
  653. id<MTLBuffer> buffer;
  654. ResourceUsageMap usage_to_resources;
  655. /// Perform a 2-way merge each key of `ResourceVector` resources from this set into the
  656. /// destination set.
  657. ///
  658. /// Assumes the vectors of resources are sorted.
  659. void merge_into(ResourceUsageMap &p_dst) const;
  660. };
  661. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDUniformSet {
  662. private:
  663. void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::RenderState &p_state);
  664. void bind_uniforms_direct(MDShader *p_shader, MDCommandBuffer::RenderState &p_state);
  665. void bind_uniforms_argument_buffers(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state);
  666. void bind_uniforms_direct(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state);
  667. public:
  668. uint32_t index;
  669. LocalVector<RDD::BoundUniform> uniforms;
  670. HashMap<MDShader *, BoundUniformSet> bound_uniforms;
  671. void bind_uniforms(MDShader *p_shader, MDCommandBuffer::RenderState &p_state);
  672. void bind_uniforms(MDShader *p_shader, MDCommandBuffer::ComputeState &p_state);
  673. BoundUniformSet &bound_uniform_set(MDShader *p_shader, id<MTLDevice> p_device, ResourceUsageMap &p_resource_usage);
  674. };
  675. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDPipeline {
  676. public:
  677. MDPipelineType type;
  678. explicit MDPipeline(MDPipelineType p_type) :
  679. type(p_type) {}
  680. virtual ~MDPipeline() = default;
  681. };
  682. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDRenderPipeline final : public MDPipeline {
  683. public:
  684. id<MTLRenderPipelineState> state = nil;
  685. id<MTLDepthStencilState> depth_stencil = nil;
  686. uint32_t push_constant_size = 0;
  687. uint32_t push_constant_stages_mask = 0;
  688. SampleCount sample_count = SampleCount1;
  689. struct {
  690. MTLCullMode cull_mode = MTLCullModeNone;
  691. MTLTriangleFillMode fill_mode = MTLTriangleFillModeFill;
  692. MTLDepthClipMode clip_mode = MTLDepthClipModeClip;
  693. MTLWinding winding = MTLWindingClockwise;
  694. MTLPrimitiveType render_primitive = MTLPrimitiveTypePoint;
  695. struct {
  696. bool enabled = false;
  697. } depth_test;
  698. struct {
  699. bool enabled = false;
  700. float depth_bias = 0.0;
  701. float slope_scale = 0.0;
  702. float clamp = 0.0;
  703. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  704. if (!enabled) {
  705. return;
  706. }
  707. [p_enc setDepthBias:depth_bias slopeScale:slope_scale clamp:clamp];
  708. }
  709. } depth_bias;
  710. struct {
  711. bool enabled = false;
  712. uint32_t front_reference = 0;
  713. uint32_t back_reference = 0;
  714. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  715. if (!enabled) {
  716. return;
  717. }
  718. [p_enc setStencilFrontReferenceValue:front_reference backReferenceValue:back_reference];
  719. }
  720. } stencil;
  721. struct {
  722. bool enabled = false;
  723. float r = 0.0;
  724. float g = 0.0;
  725. float b = 0.0;
  726. float a = 0.0;
  727. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  728. //if (!enabled)
  729. // return;
  730. [p_enc setBlendColorRed:r green:g blue:b alpha:a];
  731. }
  732. } blend;
  733. _FORCE_INLINE_ void apply(id<MTLRenderCommandEncoder> __unsafe_unretained p_enc) const {
  734. [p_enc setCullMode:cull_mode];
  735. [p_enc setTriangleFillMode:fill_mode];
  736. [p_enc setDepthClipMode:clip_mode];
  737. [p_enc setFrontFacingWinding:winding];
  738. depth_bias.apply(p_enc);
  739. stencil.apply(p_enc);
  740. blend.apply(p_enc);
  741. }
  742. } raster_state;
  743. MDRenderShader *shader = nil;
  744. MDRenderPipeline() :
  745. MDPipeline(MDPipelineType::Render) {}
  746. ~MDRenderPipeline() final = default;
  747. };
  748. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDComputePipeline final : public MDPipeline {
  749. public:
  750. id<MTLComputePipelineState> state = nil;
  751. struct {
  752. MTLSize local = {};
  753. } compute_state;
  754. MDComputeShader *shader = nil;
  755. explicit MDComputePipeline(id<MTLComputePipelineState> p_state) :
  756. MDPipeline(MDPipelineType::Compute), state(p_state) {}
  757. ~MDComputePipeline() final = default;
  758. };
  759. class API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) MDFrameBuffer {
  760. Vector<MTL::Texture> textures;
  761. public:
  762. Size2i size;
  763. MDFrameBuffer(Vector<MTL::Texture> p_textures, Size2i p_size) :
  764. textures(p_textures), size(p_size) {}
  765. MDFrameBuffer() {}
  766. /// Returns the texture at the given index.
  767. _ALWAYS_INLINE_ MTL::Texture get_texture(uint32_t p_idx) const {
  768. return textures[p_idx];
  769. }
  770. /// Returns true if the texture at the given index is not nil.
  771. _ALWAYS_INLINE_ bool has_texture(uint32_t p_idx) const {
  772. return textures[p_idx] != nil;
  773. }
  774. /// Set the texture at the given index.
  775. _ALWAYS_INLINE_ void set_texture(uint32_t p_idx, MTL::Texture p_texture) {
  776. textures.write[p_idx] = p_texture;
  777. }
  778. /// Unset or nil the texture at the given index.
  779. _ALWAYS_INLINE_ void unset_texture(uint32_t p_idx) {
  780. textures.write[p_idx] = nil;
  781. }
  782. /// Resizes buffers to the specified size.
  783. _ALWAYS_INLINE_ void set_texture_count(uint32_t p_size) {
  784. textures.resize(p_size);
  785. }
  786. virtual ~MDFrameBuffer() = default;
  787. };
  788. // These functions are used to convert between Objective-C objects and
  789. // the RIDs used by Godot, respecting automatic reference counting.
  790. namespace rid {
  791. // Converts an Objective-C object to a pointer, and incrementing the
  792. // reference count.
  793. _FORCE_INLINE_
  794. void *owned(id p_id) {
  795. return (__bridge_retained void *)p_id;
  796. }
  797. #define MAKE_ID(FROM, TO) \
  798. _FORCE_INLINE_ TO make(FROM p_obj) { \
  799. return TO(owned(p_obj)); \
  800. }
  801. MAKE_ID(id<MTLTexture>, RDD::TextureID)
  802. MAKE_ID(id<MTLBuffer>, RDD::BufferID)
  803. MAKE_ID(id<MTLSamplerState>, RDD::SamplerID)
  804. MAKE_ID(MTLVertexDescriptor *, RDD::VertexFormatID)
  805. MAKE_ID(id<MTLCommandQueue>, RDD::CommandPoolID)
  806. // Converts a pointer to an Objective-C object without changing the reference count.
  807. _FORCE_INLINE_
  808. auto get(RDD::ID p_id) {
  809. return (p_id.id) ? (__bridge ::id)(void *)p_id.id : nil;
  810. }
  811. // Converts a pointer to an Objective-C object, and decrements the reference count.
  812. _FORCE_INLINE_
  813. auto release(RDD::ID p_id) {
  814. return (__bridge_transfer ::id)(void *)p_id.id;
  815. }
  816. } // namespace rid
  817. #endif // METAL_OBJECTS_H