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