imgui_impl_metal.mm 33 KB

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