imgui_impl_metal.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. // dear imgui: Renderer Backend for Metal
  2. // This needs to be used along with a Platform Backend (e.g. OSX)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
  7. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  8. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  9. // Learn about Dear ImGui:
  10. // - FAQ https://dearimgui.com/faq
  11. // - Getting Started https://dearimgui.com/getting-started
  12. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  13. // - Introduction, links and more at the top of imgui.cpp
  14. // CHANGELOG
  15. // (minor and older changes stripped away, please see git history for details)
  16. // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown.
  17. // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture().
  18. // 2025-02-03: Metal: Crash fix. (#8367)
  19. // 2025-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419).
  20. // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
  21. // 2022-07-05: Metal: Add dispatch synchronization.
  22. // 2022-06-30: Metal: Use __bridge for ARC based systems.
  23. // 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
  24. // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
  25. // 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
  26. // 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
  27. // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
  28. // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  29. // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
  30. // 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
  31. // 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  32. // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  33. // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
  34. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  35. // 2018-07-05: Metal: Added new Metal backend implementation.
  36. #include "imgui.h"
  37. #ifndef IMGUI_DISABLE
  38. #include "imgui_impl_metal.h"
  39. #import <time.h>
  40. #import <Metal/Metal.h>
  41. #pragma mark - Support classes
  42. // A wrapper around a MTLBuffer object that knows the last time it was reused
  43. @interface MetalBuffer : NSObject
  44. @property (nonatomic, strong) id<MTLBuffer> buffer;
  45. @property (nonatomic, assign) double lastReuseTime;
  46. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
  47. @end
  48. // An object that encapsulates the data necessary to uniquely identify a
  49. // render pipeline state. These are used as cache keys.
  50. @interface FramebufferDescriptor : NSObject<NSCopying>
  51. @property (nonatomic, assign) unsigned long sampleCount;
  52. @property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
  53. @property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
  54. @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
  55. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
  56. @end
  57. @interface MetalTexture : NSObject
  58. @property (nonatomic, strong) id<MTLTexture> metalTexture;
  59. - (instancetype)initWithTexture:(id<MTLTexture>)metalTexture;
  60. @end
  61. // A singleton that stores long-lived objects that are needed by the Metal
  62. // renderer backend. Stores the render pipeline state cache and the default
  63. // font texture, and manages the reusable buffer cache.
  64. @interface MetalContext : NSObject
  65. @property (nonatomic, strong) id<MTLDevice> device;
  66. @property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
  67. @property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient
  68. @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
  69. @property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
  70. @property (nonatomic, assign) double lastBufferCachePurge;
  71. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
  72. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
  73. @end
  74. struct ImGui_ImplMetal_Data
  75. {
  76. MetalContext* SharedMetalContext;
  77. ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
  78. };
  79. static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
  80. static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
  81. static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
  82. #ifdef IMGUI_IMPL_METAL_CPP
  83. #pragma mark - Dear ImGui Metal C++ Backend API
  84. bool ImGui_ImplMetal_Init(MTL::Device* device)
  85. {
  86. return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
  87. }
  88. void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
  89. {
  90. ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
  91. }
  92. void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
  93. MTL::CommandBuffer* commandBuffer,
  94. MTL::RenderCommandEncoder* commandEncoder)
  95. {
  96. ImGui_ImplMetal_RenderDrawData(draw_data,
  97. (__bridge id<MTLCommandBuffer>)(commandBuffer),
  98. (__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
  99. }
  100. bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
  101. {
  102. return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
  103. }
  104. #endif // #ifdef IMGUI_IMPL_METAL_CPP
  105. #pragma mark - Dear ImGui Metal Backend API
  106. bool ImGui_ImplMetal_Init(id<MTLDevice> device)
  107. {
  108. ImGuiIO& io = ImGui::GetIO();
  109. IMGUI_CHECKVERSION();
  110. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  111. ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
  112. io.BackendRendererUserData = (void*)bd;
  113. io.BackendRendererName = "imgui_impl_metal";
  114. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  115. io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
  116. bd->SharedMetalContext = [[MetalContext alloc] init];
  117. bd->SharedMetalContext.device = device;
  118. return true;
  119. }
  120. void ImGui_ImplMetal_Shutdown()
  121. {
  122. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  123. IM_UNUSED(bd);
  124. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  125. ImGuiIO& io = ImGui::GetIO();
  126. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  127. ImGui_ImplMetal_DestroyDeviceObjects();
  128. ImGui_ImplMetal_DestroyBackendData();
  129. io.BackendRendererName = nullptr;
  130. io.BackendRendererUserData = nullptr;
  131. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures);
  132. platform_io.ClearRendererHandlers();
  133. }
  134. void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
  135. {
  136. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  137. IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
  138. #ifdef IMGUI_IMPL_METAL_CPP
  139. bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease];
  140. #else
  141. bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
  142. #endif
  143. if (bd->SharedMetalContext.depthStencilState == nil)
  144. ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
  145. }
  146. static void ImGui_ImplMetal_SetupRenderState(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer,
  147. id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
  148. MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
  149. {
  150. IM_UNUSED(commandBuffer);
  151. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  152. [commandEncoder setCullMode:MTLCullModeNone];
  153. [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
  154. // Setup viewport, orthographic projection matrix
  155. // Our visible imgui space lies from draw_data->DisplayPos (top left) to
  156. // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  157. MTLViewport viewport =
  158. {
  159. .originX = 0.0,
  160. .originY = 0.0,
  161. .width = (double)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x),
  162. .height = (double)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y),
  163. .znear = 0.0,
  164. .zfar = 1.0
  165. };
  166. [commandEncoder setViewport:viewport];
  167. float L = draw_data->DisplayPos.x;
  168. float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
  169. float T = draw_data->DisplayPos.y;
  170. float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
  171. float N = (float)viewport.znear;
  172. float F = (float)viewport.zfar;
  173. const float ortho_projection[4][4] =
  174. {
  175. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  176. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  177. { 0.0f, 0.0f, 1/(F-N), 0.0f },
  178. { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
  179. };
  180. [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
  181. [commandEncoder setRenderPipelineState:renderPipelineState];
  182. [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
  183. [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
  184. }
  185. // Metal Render function.
  186. void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
  187. {
  188. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  189. MetalContext* ctx = bd->SharedMetalContext;
  190. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  191. int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  192. int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  193. if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0)
  194. return;
  195. // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
  196. // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
  197. if (draw_data->Textures != nullptr)
  198. for (ImTextureData* tex : *draw_data->Textures)
  199. if (tex->Status != ImTextureStatus_OK)
  200. ImGui_ImplMetal_UpdateTexture(tex);
  201. // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
  202. // The hit rate for this cache should be very near 100%.
  203. id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
  204. if (renderPipelineState == nil)
  205. {
  206. // No luck; make a new render pipeline state
  207. renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
  208. // Cache render pipeline state for later reuse
  209. ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
  210. }
  211. size_t vertexBufferLength = (size_t)draw_data->TotalVtxCount * sizeof(ImDrawVert);
  212. size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx);
  213. MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
  214. MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
  215. ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
  216. // Will project scissor/clipping rectangles into framebuffer space
  217. ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
  218. ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  219. // Render command lists
  220. size_t vertexBufferOffset = 0;
  221. size_t indexBufferOffset = 0;
  222. for (const ImDrawList* draw_list : draw_data->CmdLists)
  223. {
  224. memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  225. memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  226. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  227. {
  228. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  229. if (pcmd->UserCallback)
  230. {
  231. // User callback, registered via ImDrawList::AddCallback()
  232. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  233. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  234. ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
  235. else
  236. pcmd->UserCallback(draw_list, pcmd);
  237. }
  238. else
  239. {
  240. // Project scissor/clipping rectangles into framebuffer space
  241. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  242. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  243. // Clamp to viewport as setScissorRect() won't accept values that are off bounds
  244. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  245. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  246. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  247. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  248. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  249. continue;
  250. if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this
  251. continue;
  252. // Apply scissor/clipping rectangle
  253. MTLScissorRect scissorRect =
  254. {
  255. .x = NSUInteger(clip_min.x),
  256. .y = NSUInteger(clip_min.y),
  257. .width = NSUInteger(clip_max.x - clip_min.x),
  258. .height = NSUInteger(clip_max.y - clip_min.y)
  259. };
  260. [commandEncoder setScissorRect:scissorRect];
  261. // Bind texture, Draw
  262. if (ImTextureID tex_id = pcmd->GetTexID())
  263. [commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(void*)(intptr_t)(tex_id) atIndex:0];
  264. [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
  265. [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
  266. indexCount:pcmd->ElemCount
  267. indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
  268. indexBuffer:indexBuffer.buffer
  269. indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
  270. }
  271. }
  272. vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
  273. indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
  274. }
  275. MetalContext* sharedMetalContext = bd->SharedMetalContext;
  276. [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
  277. {
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. @synchronized(sharedMetalContext.bufferCache)
  280. {
  281. [sharedMetalContext.bufferCache addObject:vertexBuffer];
  282. [sharedMetalContext.bufferCache addObject:indexBuffer];
  283. }
  284. });
  285. }];
  286. }
  287. static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex)
  288. {
  289. if (MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData))
  290. {
  291. IM_ASSERT(backend_tex.metalTexture == (__bridge id<MTLTexture>)(void*)(intptr_t)tex->TexID);
  292. backend_tex.metalTexture = nil;
  293. // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
  294. tex->SetTexID(ImTextureID_Invalid);
  295. tex->BackendUserData = nullptr;
  296. }
  297. tex->SetStatus(ImTextureStatus_Destroyed);
  298. }
  299. void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex)
  300. {
  301. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  302. if (tex->Status == ImTextureStatus_WantCreate)
  303. {
  304. // Create and upload new texture to graphics system
  305. //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
  306. IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
  307. IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
  308. // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
  309. // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
  310. // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
  311. // You can make that change in your implementation.
  312. MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
  313. width:(NSUInteger)tex->Width
  314. height:(NSUInteger)tex->Height
  315. mipmapped:NO];
  316. textureDescriptor.usage = MTLTextureUsageShaderRead;
  317. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  318. textureDescriptor.storageMode = MTLStorageModeManaged;
  319. #else
  320. textureDescriptor.storageMode = MTLStorageModeShared;
  321. #endif
  322. id <MTLTexture> texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor];
  323. [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4];
  324. MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture];
  325. // Store identifiers
  326. tex->SetTexID((ImTextureID)(intptr_t)texture);
  327. tex->SetStatus(ImTextureStatus_OK);
  328. tex->BackendUserData = (__bridge_retained void*)(backend_tex);
  329. }
  330. else if (tex->Status == ImTextureStatus_WantUpdates)
  331. {
  332. // Update selected blocks. We only ever write to textures regions which have never been used before!
  333. // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
  334. MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData);
  335. for (ImTextureRect& r : tex->Updates)
  336. {
  337. [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h)
  338. mipmapLevel:0
  339. withBytes:tex->GetPixelsAt(r.x, r.y)
  340. bytesPerRow:(NSUInteger)tex->Width * 4];
  341. }
  342. tex->SetStatus(ImTextureStatus_OK);
  343. }
  344. else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
  345. {
  346. ImGui_ImplMetal_DestroyTexture(tex);
  347. }
  348. }
  349. bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
  350. {
  351. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  352. MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
  353. depthStencilDescriptor.depthWriteEnabled = NO;
  354. depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
  355. bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
  356. #ifdef IMGUI_IMPL_METAL_CPP
  357. [depthStencilDescriptor release];
  358. #endif
  359. return true;
  360. }
  361. void ImGui_ImplMetal_DestroyDeviceObjects()
  362. {
  363. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  364. // Destroy all textures
  365. for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
  366. if (tex->RefCount == 1)
  367. ImGui_ImplMetal_DestroyTexture(tex);
  368. [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
  369. }
  370. #pragma mark - MetalBuffer implementation
  371. @implementation MetalBuffer
  372. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
  373. {
  374. if ((self = [super init]))
  375. {
  376. _buffer = buffer;
  377. _lastReuseTime = GetMachAbsoluteTimeInSeconds();
  378. }
  379. return self;
  380. }
  381. @end
  382. #pragma mark - FramebufferDescriptor implementation
  383. @implementation FramebufferDescriptor
  384. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
  385. {
  386. if ((self = [super init]))
  387. {
  388. _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
  389. _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
  390. _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
  391. _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
  392. }
  393. return self;
  394. }
  395. - (nonnull id)copyWithZone:(nullable NSZone*)zone
  396. {
  397. FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
  398. copy.sampleCount = self.sampleCount;
  399. copy.colorPixelFormat = self.colorPixelFormat;
  400. copy.depthPixelFormat = self.depthPixelFormat;
  401. copy.stencilPixelFormat = self.stencilPixelFormat;
  402. return copy;
  403. }
  404. - (NSUInteger)hash
  405. {
  406. NSUInteger sc = _sampleCount & 0x3;
  407. NSUInteger cf = _colorPixelFormat & 0x3FF;
  408. NSUInteger df = _depthPixelFormat & 0x3FF;
  409. NSUInteger sf = _stencilPixelFormat & 0x3FF;
  410. NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
  411. return hash;
  412. }
  413. - (BOOL)isEqual:(id)object
  414. {
  415. FramebufferDescriptor* other = object;
  416. if (![other isKindOfClass:[FramebufferDescriptor class]])
  417. return NO;
  418. return other.sampleCount == self.sampleCount &&
  419. other.colorPixelFormat == self.colorPixelFormat &&
  420. other.depthPixelFormat == self.depthPixelFormat &&
  421. other.stencilPixelFormat == self.stencilPixelFormat;
  422. }
  423. @end
  424. #pragma mark - MetalTexture implementation
  425. @implementation MetalTexture
  426. - (instancetype)initWithTexture:(id<MTLTexture>)metalTexture
  427. {
  428. if ((self = [super init]))
  429. self.metalTexture = metalTexture;
  430. return self;
  431. }
  432. @end
  433. #pragma mark - MetalContext implementation
  434. @implementation MetalContext
  435. - (instancetype)init
  436. {
  437. if ((self = [super init]))
  438. {
  439. self.renderPipelineStateCache = [NSMutableDictionary dictionary];
  440. self.bufferCache = [NSMutableArray array];
  441. _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
  442. }
  443. return self;
  444. }
  445. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
  446. {
  447. uint64_t now = GetMachAbsoluteTimeInSeconds();
  448. @synchronized(self.bufferCache)
  449. {
  450. // Purge old buffers that haven't been useful for a while
  451. if (now - self.lastBufferCachePurge > 1.0)
  452. {
  453. NSMutableArray* survivors = [NSMutableArray array];
  454. for (MetalBuffer* candidate in self.bufferCache)
  455. if (candidate.lastReuseTime > self.lastBufferCachePurge)
  456. [survivors addObject:candidate];
  457. self.bufferCache = [survivors mutableCopy];
  458. self.lastBufferCachePurge = now;
  459. }
  460. // See if we have a buffer we can reuse
  461. MetalBuffer* bestCandidate = nil;
  462. for (MetalBuffer* candidate in self.bufferCache)
  463. if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
  464. bestCandidate = candidate;
  465. if (bestCandidate != nil)
  466. {
  467. [self.bufferCache removeObject:bestCandidate];
  468. bestCandidate.lastReuseTime = now;
  469. return bestCandidate;
  470. }
  471. }
  472. // No luck; make a new buffer
  473. id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
  474. return [[MetalBuffer alloc] initWithBuffer:backing];
  475. }
  476. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  477. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
  478. {
  479. NSError* error = nil;
  480. NSString* shaderSource = @""
  481. "#include <metal_stdlib>\n"
  482. "using namespace metal;\n"
  483. "\n"
  484. "struct Uniforms {\n"
  485. " float4x4 projectionMatrix;\n"
  486. "};\n"
  487. "\n"
  488. "struct VertexIn {\n"
  489. " float2 position [[attribute(0)]];\n"
  490. " float2 texCoords [[attribute(1)]];\n"
  491. " uchar4 color [[attribute(2)]];\n"
  492. "};\n"
  493. "\n"
  494. "struct VertexOut {\n"
  495. " float4 position [[position]];\n"
  496. " float2 texCoords;\n"
  497. " float4 color;\n"
  498. "};\n"
  499. "\n"
  500. "vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
  501. " constant Uniforms &uniforms [[buffer(1)]]) {\n"
  502. " VertexOut out;\n"
  503. " out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
  504. " out.texCoords = in.texCoords;\n"
  505. " out.color = float4(in.color) / float4(255.0);\n"
  506. " return out;\n"
  507. "}\n"
  508. "\n"
  509. "fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
  510. " texture2d<half, access::sample> texture [[texture(0)]]) {\n"
  511. " constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
  512. " half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
  513. " return half4(in.color) * texColor;\n"
  514. "}\n";
  515. id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
  516. if (library == nil)
  517. {
  518. NSLog(@"Error: failed to create Metal library: %@", error);
  519. return nil;
  520. }
  521. id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
  522. id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
  523. if (vertexFunction == nil || fragmentFunction == nil)
  524. {
  525. NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
  526. return nil;
  527. }
  528. MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
  529. vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
  530. vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
  531. vertexDescriptor.attributes[0].bufferIndex = 0;
  532. vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
  533. vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
  534. vertexDescriptor.attributes[1].bufferIndex = 0;
  535. vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
  536. vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
  537. vertexDescriptor.attributes[2].bufferIndex = 0;
  538. vertexDescriptor.layouts[0].stepRate = 1;
  539. vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
  540. vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
  541. MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
  542. pipelineDescriptor.vertexFunction = vertexFunction;
  543. pipelineDescriptor.fragmentFunction = fragmentFunction;
  544. pipelineDescriptor.vertexDescriptor = vertexDescriptor;
  545. pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
  546. pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
  547. pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
  548. pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
  549. pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
  550. pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  551. pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
  552. pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
  553. pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  554. pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
  555. pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
  556. id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
  557. if (error != nil)
  558. NSLog(@"Error: failed to create Metal pipeline state: %@", error);
  559. return renderPipelineState;
  560. }
  561. @end
  562. //-----------------------------------------------------------------------------
  563. #endif // #ifndef IMGUI_DISABLE