imgui_impl_metal.mm 27 KB

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