Debian Codegraph @

extern/imgui_patched/backends/imgui_impl_metal.mm

raw
1 // dear imgui: Renderer Backend for Metal
2 // This needs to be used along with a Platform Backend (e.g. OSX)
3
4 // Implemented features:
5 // [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
6 // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7 // [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
8 // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
10 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12 // Learn about Dear ImGui:
13 // - FAQ https://dearimgui.com/faq
14 // - Getting Started https://dearimgui.com/getting-started
15 // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16 // - Introduction, links and more at the top of imgui.cpp
17
18 // CHANGELOG
19 // (minor and older changes stripped away, please see git history for details)
20 // 2025-XX-XX: Metal: Added support for multiple windows via the ImGuiPlatformIO interface.
21 // 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture().
22 // 2025-02-03: Metal: Crash fix. (#8367)
23 // 2025-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419).
24 // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
25 // 2022-07-05: Metal: Add dispatch synchronization.
26 // 2022-06-30: Metal: Use __bridge for ARC based systems.
27 // 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
28 // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
29 // 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
30 // 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
31 // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
32 // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
33 // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
34 // 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
35 // 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
36 // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
37 // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
38 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
39 // 2018-07-05: Metal: Added new Metal backend implementation.
40
41 #include "imgui.h"
42 #ifndef IMGUI_DISABLE
43 #include "imgui_impl_metal.h"
44 #import <time.h>
45 #import <Metal/Metal.h>
46
47 // Forward Declarations
48 static void ImGui_ImplMetal_InitMultiViewportSupport();
49 static void ImGui_ImplMetal_ShutdownMultiViewportSupport();
50 static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
51 static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
52
53 #pragma mark - Support classes
54
55 // A wrapper around a MTLBuffer object that knows the last time it was reused
56 @interface MetalBuffer : NSObject
57 @property (nonatomic, strong) id<MTLBuffer> buffer;
58 @property (nonatomic, assign) double lastReuseTime;
59 - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
60 @end
61
62 // An object that encapsulates the data necessary to uniquely identify a
63 // render pipeline state. These are used as cache keys.
64 @interface FramebufferDescriptor : NSObject<NSCopying>
65 @property (nonatomic, assign) unsigned long sampleCount;
66 @property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
67 @property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
68 @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
69 - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
70 @end
71
72 @interface MetalTexture : NSObject
73 @property (nonatomic, strong) id<MTLTexture> metalTexture;
74 - (instancetype)initWithTexture:(id<MTLTexture>)metalTexture;
75 @end
76
77 // A singleton that stores long-lived objects that are needed by the Metal
78 // renderer backend. Stores the render pipeline state cache and the default
79 // font texture, and manages the reusable buffer cache.
80 @interface MetalContext : NSObject
81 @property (nonatomic, strong) id<MTLDevice> device;
82 @property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
83 @property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient
84 @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
85 @property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
86 @property (nonatomic, assign) double lastBufferCachePurge;
87 - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
88 - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
89 @end
90
91 struct ImGui_ImplMetal_Data
92 {
93 MetalContext* SharedMetalContext;
94
95 ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
96 };
97
98 static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
99 static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
100
101 static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
102
103 #ifdef IMGUI_IMPL_METAL_CPP
104
105 #pragma mark - Dear ImGui Metal C++ Backend API
106
107 bool ImGui_ImplMetal_Init(MTL::Device* device)
108 {
109 return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
110 }
111
112 void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
113 {
114 ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
115 }
116
117 void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
118 MTL::CommandBuffer* commandBuffer,
119 MTL::RenderCommandEncoder* commandEncoder)
120 {
121 ImGui_ImplMetal_RenderDrawData(draw_data,
122 (__bridge id<MTLCommandBuffer>)(commandBuffer),
123 (__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
124
125 }
126
127 bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
128 {
129 return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
130 }
131
132 #endif // #ifdef IMGUI_IMPL_METAL_CPP
133
134 #pragma mark - Dear ImGui Metal Backend API
135
136 bool ImGui_ImplMetal_Init(id<MTLDevice> device)
137 {
138 ImGuiIO& io = ImGui::GetIO();
139 IMGUI_CHECKVERSION();
140 IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
141
142 ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
143 io.BackendRendererUserData = (void*)bd;
144 io.BackendRendererName = "imgui_impl_metal";
145 io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
146 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
147 io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
148
149 bd->SharedMetalContext = [[MetalContext alloc] init];
150 bd->SharedMetalContext.device = device;
151
152 ImGui_ImplMetal_InitMultiViewportSupport();
153
154 return true;
155 }
156
157 void ImGui_ImplMetal_Shutdown()
158 {
159 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
160 IM_UNUSED(bd);
161 IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
162 ImGui_ImplMetal_ShutdownMultiViewportSupport();
163 ImGui_ImplMetal_DestroyDeviceObjects();
164 ImGui_ImplMetal_DestroyBackendData();
165
166 ImGuiIO& io = ImGui::GetIO();
167 io.BackendRendererName = nullptr;
168 io.BackendRendererUserData = nullptr;
169 io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports);
170 }
171
172 void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
173 {
174 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
175 IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
176 // TODO: enable IMGUI_IMPL_METAL_CPP and get rid of this hack?
177 IM_ASSERT(bd->SharedMetalContext != nil && "No Metal context. Did you call ImGui_ImplMetal_Init() ?");
178 if (bd->SharedMetalContext.framebufferDescriptor != nil) {
179 [bd->SharedMetalContext.framebufferDescriptor release];
180 }
181 #ifdef IMGUI_IMPL_METAL_CPP
182 bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease];
183 #else
184 bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
185 #endif
186 if (bd->SharedMetalContext.depthStencilState == nil)
187 ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
188 }
189
190 static void ImGui_ImplMetal_SetupRenderState(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer,
191 id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
192 MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
193 {
194 IM_UNUSED(commandBuffer);
195 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
196 [commandEncoder setCullMode:MTLCullModeNone];
197 [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
198
199 // Setup viewport, orthographic projection matrix
200 // Our visible imgui space lies from draw_data->DisplayPos (top left) to
201 // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
202 MTLViewport viewport =
203 {
204 .originX = 0.0,
205 .originY = 0.0,
206 .width = (double)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x),
207 .height = (double)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y),
208 .znear = 0.0,
209 .zfar = 1.0
210 };
211 [commandEncoder setViewport:viewport];
212
213 float L = draw_data->DisplayPos.x;
214 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
215 float T = draw_data->DisplayPos.y;
216 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
217 float N = (float)viewport.znear;
218 float F = (float)viewport.zfar;
219 const float ortho_projection[4][4] =
220 {
221 { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
222 { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
223 { 0.0f, 0.0f, 1/(F-N), 0.0f },
224 { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
225 };
226 [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
227
228 [commandEncoder setRenderPipelineState:renderPipelineState];
229
230 [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
231 [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
232 }
233
234 // Metal Render function.
235 void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
236 {
237 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
238 MetalContext* ctx = bd->SharedMetalContext;
239
240 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
241 int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
242 int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
243 if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0)
244 return;
245
246 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
247 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
248 if (draw_data->Textures != nullptr)
249 for (ImTextureData* tex : *draw_data->Textures)
250 if (tex->Status != ImTextureStatus_OK)
251 ImGui_ImplMetal_UpdateTexture(tex);
252
253 // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
254 // The hit rate for this cache should be very near 100%.
255 id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
256 if (renderPipelineState == nil)
257 {
258 // No luck; make a new render pipeline state
259 renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
260
261 // Cache render pipeline state for later reuse
262 ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
263 }
264
265 size_t vertexBufferLength = (size_t)draw_data->TotalVtxCount * sizeof(ImDrawVert);
266 size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx);
267 MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
268 MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
269
270 ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
271
272 // Will project scissor/clipping rectangles into framebuffer space
273 ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
274 ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
275
276 // Render command lists
277 size_t vertexBufferOffset = 0;
278 size_t indexBufferOffset = 0;
279 for (const ImDrawList* draw_list : draw_data->CmdLists)
280 {
281 memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
282 memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
283
284 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
285 {
286 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
287 if (pcmd->UserCallback)
288 {
289 // User callback, registered via ImDrawList::AddCallback()
290 // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
291 if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
292 ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
293 else
294 pcmd->UserCallback(draw_list, pcmd);
295 }
296 else
297 {
298 // Project scissor/clipping rectangles into framebuffer space
299 ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
300 ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
301
302 // Clamp to viewport as setScissorRect() won't accept values that are off bounds
303 if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
304 if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
305 if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
306 if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
307 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
308 continue;
309 if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this
310 continue;
311
312 // Apply scissor/clipping rectangle
313 MTLScissorRect scissorRect =
314 {
315 .x = NSUInteger(clip_min.x),
316 .y = NSUInteger(clip_min.y),
317 .width = NSUInteger(clip_max.x - clip_min.x),
318 .height = NSUInteger(clip_max.y - clip_min.y)
319 };
320 [commandEncoder setScissorRect:scissorRect];
321
322 // Bind texture, Draw
323 if (ImTextureID tex_id = pcmd->GetTexID())
324 [commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(void*)(intptr_t)(tex_id) atIndex:0];
325
326 [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
327 [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
328 indexCount:pcmd->ElemCount
329 indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
330 indexBuffer:indexBuffer.buffer
331 indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
332 }
333 }
334
335 vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
336 indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
337 }
338
339 MetalContext* sharedMetalContext = bd->SharedMetalContext;
340 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
341 {
342 dispatch_async(dispatch_get_main_queue(), ^{
343 @synchronized(sharedMetalContext.bufferCache)
344 {
345 [sharedMetalContext.bufferCache addObject:vertexBuffer];
346 [sharedMetalContext.bufferCache addObject:indexBuffer];
347 }
348 });
349 }];
350 }
351
352 static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex)
353 {
354 MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData);
355 if (backend_tex == nullptr)
356 return;
357 IM_ASSERT(backend_tex.metalTexture == (__bridge id<MTLTexture>)(void*)(intptr_t)tex->TexID);
358 backend_tex.metalTexture = nil;
359
360 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
361 tex->SetTexID(ImTextureID_Invalid);
362 tex->SetStatus(ImTextureStatus_Destroyed);
363 tex->BackendUserData = nullptr;
364 }
365
366 void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex)
367 {
368 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
369 if (tex->Status == ImTextureStatus_WantCreate)
370 {
371 // Create and upload new texture to graphics system
372 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
373 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
374 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
375
376 // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
377 // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
378 // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
379 // You can make that change in your implementation.
380 MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
381 width:(NSUInteger)tex->Width
382 height:(NSUInteger)tex->Height
383 mipmapped:NO];
384 textureDescriptor.usage = MTLTextureUsageShaderRead;
385 #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
386 textureDescriptor.storageMode = MTLStorageModeManaged;
387 #else
388 textureDescriptor.storageMode = MTLStorageModeShared;
389 #endif
390 id <MTLTexture> texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor];
391 [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4];
392 MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture];
393
394 // Store identifiers
395 tex->SetTexID((ImTextureID)(intptr_t)texture);
396 tex->SetStatus(ImTextureStatus_OK);
397 tex->BackendUserData = (__bridge_retained void*)(backend_tex);
398 }
399 else if (tex->Status == ImTextureStatus_WantUpdates)
400 {
401 // Update selected blocks. We only ever write to textures regions which have never been used before!
402 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
403 MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData);
404 for (ImTextureRect& r : tex->Updates)
405 {
406 [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h)
407 mipmapLevel:0
408 withBytes:tex->GetPixelsAt(r.x, r.y)
409 bytesPerRow:(NSUInteger)tex->Width * 4];
410 }
411 tex->SetStatus(ImTextureStatus_OK);
412 }
413 else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
414 {
415 ImGui_ImplMetal_DestroyTexture(tex);
416 }
417 }
418
419 bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
420 {
421 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
422 MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
423 depthStencilDescriptor.depthWriteEnabled = NO;
424 depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
425 bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
426 ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
427 #ifdef IMGUI_IMPL_METAL_CPP
428 [depthStencilDescriptor release];
429 #endif
430
431 return true;
432 }
433
434 void ImGui_ImplMetal_DestroyDeviceObjects()
435 {
436 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
437
438 // Destroy all textures
439 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
440 if (tex->RefCount == 1)
441 ImGui_ImplMetal_DestroyTexture(tex);
442
443 ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
444 [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
445 }
446
447 #pragma mark - Multi-viewport support
448
449 #import <QuartzCore/CAMetalLayer.h>
450
451 #if TARGET_OS_OSX
452 #import <Cocoa/Cocoa.h>
453 #endif
454
455 //--------------------------------------------------------------------------------------------------------
456 // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
457 // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
458 // 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..
459 //--------------------------------------------------------------------------------------------------------
460
461 struct ImGuiViewportDataMetal
462 {
463 CAMetalLayer* MetalLayer;
464 id<MTLCommandQueue> CommandQueue;
465 MTLRenderPassDescriptor* RenderPassDescriptor;
466 void* Handle = nullptr;
467 bool FirstFrame = true;
468 };
469
470 static void ImGui_ImplMetal_CreateWindow(ImGuiViewport* viewport)
471 {
472 ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
473 ImGuiViewportDataMetal* data = IM_NEW(ImGuiViewportDataMetal)();
474 viewport->RendererUserData = data;
475
476 // PlatformHandleRaw should always be a NSWindow*, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
477 // Some back-ends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the NSWindow*.
478 void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
479 IM_ASSERT(handle != nullptr);
480
481 id<MTLDevice> device = bd->SharedMetalContext.device;
482 CAMetalLayer* layer = [CAMetalLayer layer];
483 layer.device = device;
484 layer.framebufferOnly = YES;
485 layer.pixelFormat = bd->SharedMetalContext.framebufferDescriptor.colorPixelFormat;
486 #if TARGET_OS_OSX
487 NSWindow* window = (__bridge NSWindow*)handle;
488 NSView* view = window.contentView;
489 view.layer = layer;
490 view.wantsLayer = YES;
491 #endif
492 data->MetalLayer = layer;
493 data->CommandQueue = [device newCommandQueue];
494 data->RenderPassDescriptor = [[MTLRenderPassDescriptor alloc] init];
495 data->Handle = handle;
496 }
497
498 static void ImGui_ImplMetal_DestroyWindow(ImGuiViewport* viewport)
499 {
500 // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
501 if (ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData)
502 IM_DELETE(data);
503 viewport->RendererUserData = nullptr;
504 }
505
506 inline static CGSize MakeScaledSize(CGSize size, CGFloat scale)
507 {
508 return CGSizeMake(size.width * scale, size.height * scale);
509 }
510
511 static void ImGui_ImplMetal_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
512 {
513 ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
514 data->MetalLayer.drawableSize = MakeScaledSize(CGSizeMake(size.x, size.y), viewport->DpiScale);
515 }
516
517 static void ImGui_ImplMetal_RenderWindow(ImGuiViewport* viewport, void*)
518 {
519 ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
520
521 #if TARGET_OS_OSX
522 void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
523 NSWindow* window = (__bridge NSWindow*)handle;
524
525 // Always render the first frame, regardless of occlusionState, to avoid an initial flicker
526 if ((window.occlusionState & NSWindowOcclusionStateVisible) == 0 && !data->FirstFrame)
527 {
528 // Do not render windows which are completely occluded. Calling -[CAMetalLayer nextDrawable] will hang for
529 // approximately 1 second if the Metal layer is completely occluded.
530 return;
531 }
532 data->FirstFrame = false;
533
534 float fb_scale = (float)window.backingScaleFactor;
535 if (data->MetalLayer.contentsScale != fb_scale)
536 {
537 data->MetalLayer.contentsScale = fb_scale;
538 data->MetalLayer.drawableSize = MakeScaledSize(window.frame.size, fb_scale);
539 }
540 #endif
541
542 id <CAMetalDrawable> drawable = [data->MetalLayer nextDrawable];
543 if (drawable == nil)
544 return;
545
546 MTLRenderPassDescriptor* renderPassDescriptor = data->RenderPassDescriptor;
547 renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
548 renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0);
549 if ((viewport->Flags & ImGuiViewportFlags_NoRendererClear) == 0)
550 renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
551
552 id <MTLCommandBuffer> commandBuffer = [data->CommandQueue commandBuffer];
553 id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
554 ImGui_ImplMetal_RenderDrawData(viewport->DrawData, commandBuffer, renderEncoder);
555 [renderEncoder endEncoding];
556
557 [commandBuffer presentDrawable:drawable];
558 [commandBuffer commit];
559 }
560
561 static void ImGui_ImplMetal_InitMultiViewportSupport()
562 {
563 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
564 platform_io.Renderer_CreateWindow = ImGui_ImplMetal_CreateWindow;
565 platform_io.Renderer_DestroyWindow = ImGui_ImplMetal_DestroyWindow;
566 platform_io.Renderer_SetWindowSize = ImGui_ImplMetal_SetWindowSize;
567 platform_io.Renderer_RenderWindow = ImGui_ImplMetal_RenderWindow;
568 }
569
570 static void ImGui_ImplMetal_ShutdownMultiViewportSupport()
571 {
572 ImGui::DestroyPlatformWindows();
573 }
574
575 static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows()
576 {
577 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
578 for (int i = 1; i < platform_io.Viewports.Size; i++)
579 if (!platform_io.Viewports[i]->RendererUserData)
580 ImGui_ImplMetal_CreateWindow(platform_io.Viewports[i]);
581 }
582
583 static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows()
584 {
585 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
586 for (int i = 1; i < platform_io.Viewports.Size; i++)
587 if (platform_io.Viewports[i]->RendererUserData)
588 ImGui_ImplMetal_DestroyWindow(platform_io.Viewports[i]);
589 }
590
591 #pragma mark - MetalBuffer implementation
592
593 @implementation MetalBuffer
594 - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
595 {
596 if ((self = [super init]))
597 {
598 _buffer = buffer;
599 _lastReuseTime = GetMachAbsoluteTimeInSeconds();
600 }
601 return self;
602 }
603 @end
604
605 #pragma mark - FramebufferDescriptor implementation
606
607 @implementation FramebufferDescriptor
608 - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
609 {
610 if ((self = [super init]))
611 {
612 _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
613 _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
614 _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
615 _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
616 }
617 return self;
618 }
619
620 - (nonnull id)copyWithZone:(nullable NSZone*)zone
621 {
622 FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
623 copy.sampleCount = self.sampleCount;
624 copy.colorPixelFormat = self.colorPixelFormat;
625 copy.depthPixelFormat = self.depthPixelFormat;
626 copy.stencilPixelFormat = self.stencilPixelFormat;
627 return copy;
628 }
629
630 - (NSUInteger)hash
631 {
632 NSUInteger sc = _sampleCount & 0x3;
633 NSUInteger cf = _colorPixelFormat & 0x3FF;
634 NSUInteger df = _depthPixelFormat & 0x3FF;
635 NSUInteger sf = _stencilPixelFormat & 0x3FF;
636 NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
637 return hash;
638 }
639
640 - (BOOL)isEqual:(id)object
641 {
642 FramebufferDescriptor* other = object;
643 if (![other isKindOfClass:[FramebufferDescriptor class]])
644 return NO;
645 return other.sampleCount == self.sampleCount &&
646 other.colorPixelFormat == self.colorPixelFormat &&
647 other.depthPixelFormat == self.depthPixelFormat &&
648 other.stencilPixelFormat == self.stencilPixelFormat;
649 }
650
651 @end
652
653 #pragma mark - MetalTexture implementation
654
655 @implementation MetalTexture
656 - (instancetype)initWithTexture:(id<MTLTexture>)metalTexture
657 {
658 if ((self = [super init]))
659 self.metalTexture = metalTexture;
660 return self;
661 }
662
663 @end
664
665 #pragma mark - MetalContext implementation
666
667 @implementation MetalContext
668 - (instancetype)init
669 {
670 if ((self = [super init]))
671 {
672 self.renderPipelineStateCache = [NSMutableDictionary dictionary];
673 self.bufferCache = [NSMutableArray array];
674 _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
675 }
676 return self;
677 }
678
679 - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
680 {
681 uint64_t now = GetMachAbsoluteTimeInSeconds();
682
683 @synchronized(self.bufferCache)
684 {
685 // Purge old buffers that haven't been useful for a while
686 if (now - self.lastBufferCachePurge > 1.0)
687 {
688 NSMutableArray* survivors = [NSMutableArray array];
689 for (MetalBuffer* candidate in self.bufferCache)
690 if (candidate.lastReuseTime > self.lastBufferCachePurge)
691 [survivors addObject:candidate];
692 self.bufferCache = [survivors mutableCopy];
693 self.lastBufferCachePurge = now;
694 }
695
696 // See if we have a buffer we can reuse
697 MetalBuffer* bestCandidate = nil;
698 for (MetalBuffer* candidate in self.bufferCache)
699 if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
700 bestCandidate = candidate;
701
702 if (bestCandidate != nil)
703 {
704 [self.bufferCache removeObject:bestCandidate];
705 bestCandidate.lastReuseTime = now;
706 return bestCandidate;
707 }
708 }
709
710 // No luck; make a new buffer
711 id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
712 return [[MetalBuffer alloc] initWithBuffer:backing];
713 }
714
715 // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
716 - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
717 {
718 NSError* error = nil;
719
720 NSString* shaderSource = @""
721 "#include <metal_stdlib>\n"
722 "using namespace metal;\n"
723 "\n"
724 "struct Uniforms {\n"
725 " float4x4 projectionMatrix;\n"
726 "};\n"
727 "\n"
728 "struct VertexIn {\n"
729 " float2 position [[attribute(0)]];\n"
730 " float2 texCoords [[attribute(1)]];\n"
731 " uchar4 color [[attribute(2)]];\n"
732 "};\n"
733 "\n"
734 "struct VertexOut {\n"
735 " float4 position [[position]];\n"
736 " float2 texCoords;\n"
737 " float4 color;\n"
738 "};\n"
739 "\n"
740 "vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
741 " constant Uniforms &uniforms [[buffer(1)]]) {\n"
742 " VertexOut out;\n"
743 " out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
744 " out.texCoords = in.texCoords;\n"
745 " out.color = float4(in.color) / float4(255.0);\n"
746 " return out;\n"
747 "}\n"
748 "\n"
749 "fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
750 " texture2d<half, access::sample> texture [[texture(0)]]) {\n"
751 " constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
752 " half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
753 " return half4(in.color) * texColor;\n"
754 "}\n";
755
756 id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
757 if (library == nil)
758 {
759 NSLog(@"Error: failed to create Metal library: %@", error);
760 return nil;
761 }
762
763 id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
764 id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
765
766 if (vertexFunction == nil || fragmentFunction == nil)
767 {
768 NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
769 return nil;
770 }
771
772 MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
773 vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
774 vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
775 vertexDescriptor.attributes[0].bufferIndex = 0;
776 vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
777 vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
778 vertexDescriptor.attributes[1].bufferIndex = 0;
779 vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
780 vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
781 vertexDescriptor.attributes[2].bufferIndex = 0;
782 vertexDescriptor.layouts[0].stepRate = 1;
783 vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
784 vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
785
786 MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
787 pipelineDescriptor.vertexFunction = vertexFunction;
788 pipelineDescriptor.fragmentFunction = fragmentFunction;
789 pipelineDescriptor.vertexDescriptor = vertexDescriptor;
790 pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
791 pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
792 pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
793 pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
794 pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
795 pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
796 pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
797 pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
798 pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
799 pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
800 pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
801
802 id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
803 if (error != nil)
804 NSLog(@"Error: failed to create Metal pipeline state: %@", error);
805
806 return renderPipelineState;
807 }
808
809 @end
810
811 //-----------------------------------------------------------------------------
812
813 #endif // #ifndef IMGUI_DISABLE