imgui_impl_metal.mm 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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 ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
  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-XX-XX: Metal: Added support for multiple windows via the ImGuiPlatformIO interface.
  17. // 2025-02-03: Metal: Crash fix. (#8367)
  18. // 2025-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419).
  19. // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
  20. // 2022-07-05: Metal: Add dispatch synchronization.
  21. // 2022-06-30: Metal: Use __bridge for ARC based systems.
  22. // 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
  23. // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
  24. // 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
  25. // 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
  26. // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
  27. // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  28. // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
  29. // 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
  30. // 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  31. // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  32. // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
  33. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  34. // 2018-07-05: Metal: Added new Metal backend implementation.
  35. #include "imgui.h"
  36. #ifndef IMGUI_DISABLE
  37. #include "imgui_impl_metal.h"
  38. #import <time.h>
  39. #import <Metal/Metal.h>
  40. // Forward Declarations
  41. static void ImGui_ImplMetal_InitMultiViewportSupport();
  42. static void ImGui_ImplMetal_ShutdownMultiViewportSupport();
  43. static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
  44. static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
  45. #pragma mark - Support classes
  46. // A wrapper around a MTLBuffer object that knows the last time it was reused
  47. @interface MetalBuffer : NSObject
  48. @property (nonatomic, strong) id<MTLBuffer> buffer;
  49. @property (nonatomic, assign) double lastReuseTime;
  50. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
  51. @end
  52. // An object that encapsulates the data necessary to uniquely identify a
  53. // render pipeline state. These are used as cache keys.
  54. @interface FramebufferDescriptor : NSObject<NSCopying>
  55. @property (nonatomic, assign) unsigned long sampleCount;
  56. @property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
  57. @property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
  58. @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
  59. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
  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, nullable) id<MTLTexture> fontTexture;
  70. @property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
  71. @property (nonatomic, assign) double lastBufferCachePurge;
  72. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
  73. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
  74. @end
  75. struct ImGui_ImplMetal_Data
  76. {
  77. MetalContext* SharedMetalContext;
  78. ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
  79. };
  80. static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
  81. static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
  82. static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
  83. #ifdef IMGUI_IMPL_METAL_CPP
  84. #pragma mark - Dear ImGui Metal C++ Backend API
  85. bool ImGui_ImplMetal_Init(MTL::Device* device)
  86. {
  87. return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
  88. }
  89. void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
  90. {
  91. ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
  92. }
  93. void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
  94. MTL::CommandBuffer* commandBuffer,
  95. MTL::RenderCommandEncoder* commandEncoder)
  96. {
  97. ImGui_ImplMetal_RenderDrawData(draw_data,
  98. (__bridge id<MTLCommandBuffer>)(commandBuffer),
  99. (__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
  100. }
  101. bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device)
  102. {
  103. return ImGui_ImplMetal_CreateFontsTexture((__bridge id<MTLDevice>)(device));
  104. }
  105. bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
  106. {
  107. return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
  108. }
  109. #endif // #ifdef IMGUI_IMPL_METAL_CPP
  110. #pragma mark - Dear ImGui Metal Backend API
  111. bool ImGui_ImplMetal_Init(id<MTLDevice> device)
  112. {
  113. ImGuiIO& io = ImGui::GetIO();
  114. IMGUI_CHECKVERSION();
  115. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  116. ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
  117. io.BackendRendererUserData = (void*)bd;
  118. io.BackendRendererName = "imgui_impl_metal";
  119. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  120. io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
  121. bd->SharedMetalContext = [[MetalContext alloc] init];
  122. bd->SharedMetalContext.device = device;
  123. ImGui_ImplMetal_InitMultiViewportSupport();
  124. return true;
  125. }
  126. void ImGui_ImplMetal_Shutdown()
  127. {
  128. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  129. IM_UNUSED(bd);
  130. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  131. ImGui_ImplMetal_ShutdownMultiViewportSupport();
  132. ImGui_ImplMetal_DestroyDeviceObjects();
  133. ImGui_ImplMetal_DestroyBackendData();
  134. ImGuiIO& io = ImGui::GetIO();
  135. io.BackendRendererName = nullptr;
  136. io.BackendRendererUserData = nullptr;
  137. io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
  138. }
  139. void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
  140. {
  141. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  142. IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
  143. #ifdef IMGUI_IMPL_METAL_CPP
  144. bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease];
  145. #else
  146. bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
  147. #endif
  148. if (bd->SharedMetalContext.depthStencilState == nil)
  149. ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
  150. }
  151. static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer,
  152. id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
  153. MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
  154. {
  155. IM_UNUSED(commandBuffer);
  156. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  157. [commandEncoder setCullMode:MTLCullModeNone];
  158. [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
  159. // Setup viewport, orthographic projection matrix
  160. // Our visible imgui space lies from draw_data->DisplayPos (top left) to
  161. // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  162. MTLViewport viewport =
  163. {
  164. .originX = 0.0,
  165. .originY = 0.0,
  166. .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x),
  167. .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y),
  168. .znear = 0.0,
  169. .zfar = 1.0
  170. };
  171. [commandEncoder setViewport:viewport];
  172. float L = drawData->DisplayPos.x;
  173. float R = drawData->DisplayPos.x + drawData->DisplaySize.x;
  174. float T = drawData->DisplayPos.y;
  175. float B = drawData->DisplayPos.y + drawData->DisplaySize.y;
  176. float N = (float)viewport.znear;
  177. float F = (float)viewport.zfar;
  178. const float ortho_projection[4][4] =
  179. {
  180. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  181. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  182. { 0.0f, 0.0f, 1/(F-N), 0.0f },
  183. { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
  184. };
  185. [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
  186. [commandEncoder setRenderPipelineState:renderPipelineState];
  187. [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
  188. [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
  189. }
  190. // Metal Render function.
  191. void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
  192. {
  193. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  194. MetalContext* ctx = bd->SharedMetalContext;
  195. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  196. int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x);
  197. int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y);
  198. if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0)
  199. return;
  200. // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
  201. // The hit rate for this cache should be very near 100%.
  202. id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
  203. if (renderPipelineState == nil)
  204. {
  205. // No luck; make a new render pipeline state
  206. renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
  207. // Cache render pipeline state for later reuse
  208. ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
  209. }
  210. size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert);
  211. size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx);
  212. MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
  213. MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
  214. ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
  215. // Will project scissor/clipping rectangles into framebuffer space
  216. ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports
  217. ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  218. // Render command lists
  219. size_t vertexBufferOffset = 0;
  220. size_t indexBufferOffset = 0;
  221. for (int n = 0; n < drawData->CmdListsCount; n++)
  222. {
  223. const ImDrawList* draw_list = drawData->CmdLists[n];
  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(drawData, 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. bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device)
  288. {
  289. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  290. ImGuiIO& io = ImGui::GetIO();
  291. // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
  292. // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
  293. // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
  294. // You can make that change in your implementation.
  295. unsigned char* pixels;
  296. int width, height;
  297. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  298. MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
  299. width:(NSUInteger)width
  300. height:(NSUInteger)height
  301. mipmapped:NO];
  302. textureDescriptor.usage = MTLTextureUsageShaderRead;
  303. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  304. textureDescriptor.storageMode = MTLStorageModeManaged;
  305. #else
  306. textureDescriptor.storageMode = MTLStorageModeShared;
  307. #endif
  308. id <MTLTexture> texture = [device newTextureWithDescriptor:textureDescriptor];
  309. [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4];
  310. bd->SharedMetalContext.fontTexture = texture;
  311. io.Fonts->SetTexID((ImTextureID)(intptr_t)(__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == ImU64
  312. return (bd->SharedMetalContext.fontTexture != nil);
  313. }
  314. void ImGui_ImplMetal_DestroyFontsTexture()
  315. {
  316. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  317. ImGuiIO& io = ImGui::GetIO();
  318. bd->SharedMetalContext.fontTexture = nil;
  319. io.Fonts->SetTexID(0);
  320. }
  321. bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
  322. {
  323. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  324. MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
  325. depthStencilDescriptor.depthWriteEnabled = NO;
  326. depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
  327. bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
  328. ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
  329. #ifdef IMGUI_IMPL_METAL_CPP
  330. [depthStencilDescriptor release];
  331. #endif
  332. ImGui_ImplMetal_CreateFontsTexture(device);
  333. return true;
  334. }
  335. void ImGui_ImplMetal_DestroyDeviceObjects()
  336. {
  337. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  338. ImGui_ImplMetal_DestroyFontsTexture();
  339. ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
  340. [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
  341. }
  342. #pragma mark - Multi-viewport support
  343. #import <QuartzCore/CAMetalLayer.h>
  344. #if TARGET_OS_OSX
  345. #import <Cocoa/Cocoa.h>
  346. #endif
  347. //--------------------------------------------------------------------------------------------------------
  348. // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
  349. // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
  350. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
  351. //--------------------------------------------------------------------------------------------------------
  352. struct ImGuiViewportDataMetal
  353. {
  354. CAMetalLayer* MetalLayer;
  355. id<MTLCommandQueue> CommandQueue;
  356. MTLRenderPassDescriptor* RenderPassDescriptor;
  357. void* Handle = nullptr;
  358. bool FirstFrame = true;
  359. };
  360. static void ImGui_ImplMetal_CreateWindow(ImGuiViewport* viewport)
  361. {
  362. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  363. ImGuiViewportDataMetal* data = IM_NEW(ImGuiViewportDataMetal)();
  364. viewport->RendererUserData = data;
  365. // PlatformHandleRaw should always be a NSWindow*, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
  366. // Some back-ends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the NSWindow*.
  367. void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
  368. IM_ASSERT(handle != nullptr);
  369. id<MTLDevice> device = bd->SharedMetalContext.device;
  370. CAMetalLayer* layer = [CAMetalLayer layer];
  371. layer.device = device;
  372. layer.framebufferOnly = YES;
  373. layer.pixelFormat = bd->SharedMetalContext.framebufferDescriptor.colorPixelFormat;
  374. #if TARGET_OS_OSX
  375. NSWindow* window = (__bridge NSWindow*)handle;
  376. NSView* view = window.contentView;
  377. view.layer = layer;
  378. view.wantsLayer = YES;
  379. #endif
  380. data->MetalLayer = layer;
  381. data->CommandQueue = [device newCommandQueue];
  382. data->RenderPassDescriptor = [[MTLRenderPassDescriptor alloc] init];
  383. data->Handle = handle;
  384. }
  385. static void ImGui_ImplMetal_DestroyWindow(ImGuiViewport* viewport)
  386. {
  387. // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
  388. if (ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData)
  389. IM_DELETE(data);
  390. viewport->RendererUserData = nullptr;
  391. }
  392. inline static CGSize MakeScaledSize(CGSize size, CGFloat scale)
  393. {
  394. return CGSizeMake(size.width * scale, size.height * scale);
  395. }
  396. static void ImGui_ImplMetal_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
  397. {
  398. ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
  399. data->MetalLayer.drawableSize = MakeScaledSize(CGSizeMake(size.x, size.y), viewport->DpiScale);
  400. }
  401. static void ImGui_ImplMetal_RenderWindow(ImGuiViewport* viewport, void*)
  402. {
  403. ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
  404. #if TARGET_OS_OSX
  405. void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
  406. NSWindow* window = (__bridge NSWindow*)handle;
  407. // Always render the first frame, regardless of occlusionState, to avoid an initial flicker
  408. if ((window.occlusionState & NSWindowOcclusionStateVisible) == 0 && !data->FirstFrame)
  409. {
  410. // Do not render windows which are completely occluded. Calling -[CAMetalLayer nextDrawable] will hang for
  411. // approximately 1 second if the Metal layer is completely occluded.
  412. return;
  413. }
  414. data->FirstFrame = false;
  415. viewport->DpiScale = (float)window.backingScaleFactor;
  416. if (data->MetalLayer.contentsScale != viewport->DpiScale)
  417. {
  418. data->MetalLayer.contentsScale = viewport->DpiScale;
  419. data->MetalLayer.drawableSize = MakeScaledSize(window.frame.size, viewport->DpiScale);
  420. }
  421. viewport->DrawData->FramebufferScale = ImVec2(viewport->DpiScale, viewport->DpiScale);
  422. #endif
  423. id <CAMetalDrawable> drawable = [data->MetalLayer nextDrawable];
  424. if (drawable == nil)
  425. return;
  426. MTLRenderPassDescriptor* renderPassDescriptor = data->RenderPassDescriptor;
  427. renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
  428. renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0);
  429. if ((viewport->Flags & ImGuiViewportFlags_NoRendererClear) == 0)
  430. renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
  431. id <MTLCommandBuffer> commandBuffer = [data->CommandQueue commandBuffer];
  432. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  433. ImGui_ImplMetal_RenderDrawData(viewport->DrawData, commandBuffer, renderEncoder);
  434. [renderEncoder endEncoding];
  435. [commandBuffer presentDrawable:drawable];
  436. [commandBuffer commit];
  437. }
  438. static void ImGui_ImplMetal_InitMultiViewportSupport()
  439. {
  440. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  441. platform_io.Renderer_CreateWindow = ImGui_ImplMetal_CreateWindow;
  442. platform_io.Renderer_DestroyWindow = ImGui_ImplMetal_DestroyWindow;
  443. platform_io.Renderer_SetWindowSize = ImGui_ImplMetal_SetWindowSize;
  444. platform_io.Renderer_RenderWindow = ImGui_ImplMetal_RenderWindow;
  445. }
  446. static void ImGui_ImplMetal_ShutdownMultiViewportSupport()
  447. {
  448. ImGui::DestroyPlatformWindows();
  449. }
  450. static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows()
  451. {
  452. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  453. for (int i = 1; i < platform_io.Viewports.Size; i++)
  454. if (!platform_io.Viewports[i]->RendererUserData)
  455. ImGui_ImplMetal_CreateWindow(platform_io.Viewports[i]);
  456. }
  457. static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows()
  458. {
  459. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  460. for (int i = 1; i < platform_io.Viewports.Size; i++)
  461. if (platform_io.Viewports[i]->RendererUserData)
  462. ImGui_ImplMetal_DestroyWindow(platform_io.Viewports[i]);
  463. }
  464. #pragma mark - MetalBuffer implementation
  465. @implementation MetalBuffer
  466. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
  467. {
  468. if ((self = [super init]))
  469. {
  470. _buffer = buffer;
  471. _lastReuseTime = GetMachAbsoluteTimeInSeconds();
  472. }
  473. return self;
  474. }
  475. @end
  476. #pragma mark - FramebufferDescriptor implementation
  477. @implementation FramebufferDescriptor
  478. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
  479. {
  480. if ((self = [super init]))
  481. {
  482. _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
  483. _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
  484. _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
  485. _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
  486. }
  487. return self;
  488. }
  489. - (nonnull id)copyWithZone:(nullable NSZone*)zone
  490. {
  491. FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
  492. copy.sampleCount = self.sampleCount;
  493. copy.colorPixelFormat = self.colorPixelFormat;
  494. copy.depthPixelFormat = self.depthPixelFormat;
  495. copy.stencilPixelFormat = self.stencilPixelFormat;
  496. return copy;
  497. }
  498. - (NSUInteger)hash
  499. {
  500. NSUInteger sc = _sampleCount & 0x3;
  501. NSUInteger cf = _colorPixelFormat & 0x3FF;
  502. NSUInteger df = _depthPixelFormat & 0x3FF;
  503. NSUInteger sf = _stencilPixelFormat & 0x3FF;
  504. NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
  505. return hash;
  506. }
  507. - (BOOL)isEqual:(id)object
  508. {
  509. FramebufferDescriptor* other = object;
  510. if (![other isKindOfClass:[FramebufferDescriptor class]])
  511. return NO;
  512. return other.sampleCount == self.sampleCount &&
  513. other.colorPixelFormat == self.colorPixelFormat &&
  514. other.depthPixelFormat == self.depthPixelFormat &&
  515. other.stencilPixelFormat == self.stencilPixelFormat;
  516. }
  517. @end
  518. #pragma mark - MetalContext implementation
  519. @implementation MetalContext
  520. - (instancetype)init
  521. {
  522. if ((self = [super init]))
  523. {
  524. self.renderPipelineStateCache = [NSMutableDictionary dictionary];
  525. self.bufferCache = [NSMutableArray array];
  526. _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
  527. }
  528. return self;
  529. }
  530. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
  531. {
  532. uint64_t now = GetMachAbsoluteTimeInSeconds();
  533. @synchronized(self.bufferCache)
  534. {
  535. // Purge old buffers that haven't been useful for a while
  536. if (now - self.lastBufferCachePurge > 1.0)
  537. {
  538. NSMutableArray* survivors = [NSMutableArray array];
  539. for (MetalBuffer* candidate in self.bufferCache)
  540. if (candidate.lastReuseTime > self.lastBufferCachePurge)
  541. [survivors addObject:candidate];
  542. self.bufferCache = [survivors mutableCopy];
  543. self.lastBufferCachePurge = now;
  544. }
  545. // See if we have a buffer we can reuse
  546. MetalBuffer* bestCandidate = nil;
  547. for (MetalBuffer* candidate in self.bufferCache)
  548. if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
  549. bestCandidate = candidate;
  550. if (bestCandidate != nil)
  551. {
  552. [self.bufferCache removeObject:bestCandidate];
  553. bestCandidate.lastReuseTime = now;
  554. return bestCandidate;
  555. }
  556. }
  557. // No luck; make a new buffer
  558. id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
  559. return [[MetalBuffer alloc] initWithBuffer:backing];
  560. }
  561. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  562. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
  563. {
  564. NSError* error = nil;
  565. NSString* shaderSource = @""
  566. "#include <metal_stdlib>\n"
  567. "using namespace metal;\n"
  568. "\n"
  569. "struct Uniforms {\n"
  570. " float4x4 projectionMatrix;\n"
  571. "};\n"
  572. "\n"
  573. "struct VertexIn {\n"
  574. " float2 position [[attribute(0)]];\n"
  575. " float2 texCoords [[attribute(1)]];\n"
  576. " uchar4 color [[attribute(2)]];\n"
  577. "};\n"
  578. "\n"
  579. "struct VertexOut {\n"
  580. " float4 position [[position]];\n"
  581. " float2 texCoords;\n"
  582. " float4 color;\n"
  583. "};\n"
  584. "\n"
  585. "vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
  586. " constant Uniforms &uniforms [[buffer(1)]]) {\n"
  587. " VertexOut out;\n"
  588. " out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
  589. " out.texCoords = in.texCoords;\n"
  590. " out.color = float4(in.color) / float4(255.0);\n"
  591. " return out;\n"
  592. "}\n"
  593. "\n"
  594. "fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
  595. " texture2d<half, access::sample> texture [[texture(0)]]) {\n"
  596. " constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
  597. " half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
  598. " return half4(in.color) * texColor;\n"
  599. "}\n";
  600. id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
  601. if (library == nil)
  602. {
  603. NSLog(@"Error: failed to create Metal library: %@", error);
  604. return nil;
  605. }
  606. id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
  607. id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
  608. if (vertexFunction == nil || fragmentFunction == nil)
  609. {
  610. NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
  611. return nil;
  612. }
  613. MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
  614. vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
  615. vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
  616. vertexDescriptor.attributes[0].bufferIndex = 0;
  617. vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
  618. vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
  619. vertexDescriptor.attributes[1].bufferIndex = 0;
  620. vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
  621. vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
  622. vertexDescriptor.attributes[2].bufferIndex = 0;
  623. vertexDescriptor.layouts[0].stepRate = 1;
  624. vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
  625. vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
  626. MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
  627. pipelineDescriptor.vertexFunction = vertexFunction;
  628. pipelineDescriptor.fragmentFunction = fragmentFunction;
  629. pipelineDescriptor.vertexDescriptor = vertexDescriptor;
  630. pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
  631. pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
  632. pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
  633. pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
  634. pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
  635. pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  636. pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
  637. pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
  638. pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  639. pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
  640. pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
  641. id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
  642. if (error != nil)
  643. NSLog(@"Error: failed to create Metal pipeline state: %@", error);
  644. return renderPipelineState;
  645. }
  646. @end
  647. //-----------------------------------------------------------------------------
  648. #endif // #ifndef IMGUI_DISABLE