imgui_impl_metal.mm 34 KB

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