imgui_impl_metal.mm 27 KB

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