TachyonUI 1.1.0
High-performance UI for building tools.
Loading...
Searching...
No Matches
metal_device.h
Go to the documentation of this file.
1#pragma once
2
3// Inside the Metal backend (Objective-C++ only): the device and what its graphics context and
4// window contexts share. Every commit counts up `submitted`, the way the Vulkan backend's
5// timeline does: a frame slot waits for its count, and what's let go waits for it before it's
6// freed.
7//
8// A buffer the shaders read is named by a DeviceAddress the backend makes up: the buffer's
9// handle in the top 32 bits and the offset in the low 32 (Resolve). Draws bind the buffer at
10// that offset, so the shaders need no pointers.
11
12#import <Metal/Metal.h>
13
18
19#include <array>
20#include <atomic>
21#include <deque>
22#include <functional>
23#include <memory>
24#include <mutex>
25#include <optional>
26#include <span>
27#include <string>
28#include <unordered_map>
29#include <unordered_set>
30#include <utility>
31#include <vector>
32
33namespace tachyon
34{
35 class StyleManager;
36 class GradientManager;
37}
38
40{
42 inline constexpr MTLPixelFormat kDrawFormat = MTLPixelFormatBGRA8Unorm;
43 inline constexpr MTLPixelFormat kDepthFormat = MTLPixelFormatDepth32Float;
44
46 inline constexpr uint32_t kMaxImageSlots = 500000;
47
50 namespace binding
51 {
52 inline constexpr NSUInteger kConstants = 0;
53 inline constexpr NSUInteger kPrimitives = 1;
54 inline constexpr NSUInteger kBoxStyles = 6;
55 inline constexpr NSUInteger kColorStyles = 7;
56 inline constexpr NSUInteger kImageSamplers = 8;
57 inline constexpr NSUInteger kImages = 9;
58 inline constexpr NSUInteger kSamplers = 0;
59 }
60
64 {
65 float worldColumns[16];
67 uint32_t firstVertex;
68 uint32_t _pad[2];
69 };
70 static_assert(sizeof(RootConstants) == 80);
71
73 struct Buffer
74 {
75 id<MTLBuffer> buffer = nil;
76 uint32_t handle = 0;
77 size_t size = 0;
78
79 void* Mapped() const { return buffer != nil ? buffer.contents : nullptr; }
80 DeviceAddress Address(size_t offset) const { return (DeviceAddress(handle) << 32) | DeviceAddress(offset); }
81 explicit operator bool() const { return buffer != nil; }
82 };
83
86 class MetalImage final : public Image
87 {
88 public:
89 id<MTLTexture> texture = nil;
90 bool external = false;
91 MTLPixelFormat format = MTLPixelFormatInvalid;
95 std::optional<ImageFormat> sourceFormat;
96 };
97
99 uint32_t SamplerSlot(Sampler sampler);
100
104 class MetalImageSet final : public ImageSet
105 {
106 public:
107 void Create(uint32_t capacity) { m_capacity = capacity; }
108
109 void Clear() override;
110 ImageIndex Add(Image* image) override;
111 void Remove(ImageIndex index) override;
115 void SetImage(ImageIndex index, MetalImage* image);
116
117 uint32_t Capacity() const { return m_capacity; }
119 uint32_t SlotsInUse() const { return uint32_t(m_images.size()); }
120 const std::vector<MetalImage*>& Images() const { return m_images; }
122 const std::vector<uint32_t>& SamplerSlots() const { return m_samplers; }
123
124 private:
125 ImageIndex Allocate();
126
127 uint32_t m_capacity = 0;
128 std::vector<MetalImage*> m_images;
129 std::vector<uint32_t> m_samplers;
130 std::vector<uint32_t> m_free;
131 };
132
134 {
136 std::string gpuPreference;
137 std::string deviceName;
138 uint32_t imageSlots = 4096;
139
140 id<MTLDevice> device = nil;
141 id<MTLCommandQueue> queue = nil;
142
143 // ---- Commits ---------------------------------------------------------------------
146 std::atomic<uint64_t> submitted = 0;
148 std::mutex inFlightMutex;
149 std::deque<std::pair<uint64_t, id<MTLCommandBuffer>>> inFlight;
150 uint64_t completed = 0;
153 std::atomic<bool> removed = false;
154
156 uint64_t Commit(id<MTLCommandBuffer> commandBuffer);
158 void Wait(uint64_t value);
160 void WaitIdle();
162 uint64_t Completed();
163
164 // ---- Memory ----------------------------------------------------------------------
167 std::unordered_map<uint32_t, id<MTLBuffer>> buffers;
168 uint32_t nextBufferHandle = 1;
170 Buffer CreateBuffer(size_t size);
172 void ReleaseBuffer(Buffer& buffer);
174 std::pair<id<MTLBuffer>, NSUInteger> Resolve(DeviceAddress address) const;
175
178 void DestroyAfterGpu(std::unique_ptr<MetalImage> image, uint64_t afterValue);
179 void DestroyAfterGpu(id<MTLResource> resource, uint64_t afterValue);
182
183 struct Garbage
184 {
185 uint64_t afterValue = 0;
186 std::unique_ptr<MetalImage> image;
187 id<MTLResource> resource = nil;
188 };
189 std::mutex garbageMutex;
190 std::vector<Garbage> garbage;
191
192 // ---- Uploads, recorded at the start of the next window frame -------------------
196 {
197 MetalImage* image = nullptr;
198 id<MTLBuffer> staging = nil;
199 NSUInteger rowPitch = 0;
200 uint32_t firstRow = 0;
201 uint32_t rowCount = 0;
202 };
203 std::mutex uploadMutex;
204 std::vector<ImageUpload> imageUploads;
205 std::vector<ImageUpload> uploadScratch;
206
208 void RecordPendingUploads(id<MTLCommandBuffer> commandBuffer);
209
210 // ---- Resident buffers (RHI::UploadResidentBuffers) ------------------------------
213 std::unordered_map<RHI::ResidentBufferId, Buffer> residents;
215
216 RHI::ResidentBufferId CreateResidentBuffer(std::span<const RHI::UploadRequest> requests,
217 std::span<DeviceAddress> addresses);
220
221 // ---- Images ----------------------------------------------------------------------
224 std::unordered_set<MetalImage*> liveImages;
225
226 // ---- What every frame draws with ----------------------------------------------
232 std::vector<ImageIndex> gradientPages;
235 float lastTime = 0.0f;
237 std::vector<id<MTLRenderPipelineState>> pipelineStates;
238 std::array<RHI::GpuPipeline, kPrimitiveKindCount> pipelines {};
239 id<MTLDepthStencilState> depthTest = nil;
240 id<MTLDepthStencilState> depthWrite = nil;
241 std::array<id<MTLSamplerState>, 3> samplers {};
243 id<MTLBuffer> quadIndices = nil;
244 uint32_t quadCapacity = 0;
246 id<MTLBuffer> emptyBuffer = nil;
248
250 bool EnsureQuadIndices(uint32_t quads);
251
252 // ---- Scenes the app draws (RenderScene) ----------------------------------------
253 static constexpr MTLPixelFormat kSceneColorFormat = MTLPixelFormatRGBA8Unorm;
254 static constexpr uint64_t kSceneKeepFrames = 4;
255
258 struct Scene
259 {
260 MetalImage* color = nullptr;
261 MetalImage* depth = nullptr;
264 uint64_t lastFrame = 0;
265 };
267 {
271 std::function<void(const ScenePayload& scene)> record;
272 };
273 std::unordered_map<ID, Scene> scenes;
274 std::vector<SceneRequest> sceneRequests;
275 uint64_t sceneFrame = 0;
276
278 std::unordered_map<uint32_t, std::unique_ptr<MetalImage>> externalImages;
279
281 void RecordScenes(id<MTLCommandBuffer> commandBuffer, ID window);
282
285 MetalImage* CreateTargetImage(uint2 size, MTLPixelFormat format, MTLTextureUsage usage, Sampler sampler);
286 };
287}
The atlas that the colors of color styles are baked into: pages of 2D textures, one row per gradient,...
Definition gui_gradient_manager.h:65
The images the shaders can sample, each at an ImageIndex. Implemented by the backend.
Definition gui_image.h:106
An image made by GraphicsContext::CreateImage; the backend defines its contents.
Definition gui_image.h:102
What GraphicsContext::RenderScene's record gets: the backend's recording state, as the struct of the ...
Definition gui_graphics_api.h:41
Bakes serializable Styles into deduplicated runtime layout/visual styles; a StyleRef holds indices in...
Definition gui_style_manager.h:39
The images the shaders sample, by ImageIndex (1-based; the shaders' slot is one less).
Definition metal_device.h:105
const std::vector< MetalImage * > & Images() const
Definition metal_device.h:120
uint32_t Capacity() const
Definition metal_device.h:117
ImageIndex Add(Image *image) override
Adds an image (not owned) and returns its index.
void Create(uint32_t capacity)
Definition metal_device.h:107
uint32_t SlotsInUse() const
One past the highest slot handed out: what a frame writes.
Definition metal_device.h:119
ImageIndex ReserveIndex()
A slot with no image yet, for one that comes later (a text atlas page).
const std::vector< uint32_t > & SamplerSlots() const
Each slot's sampler (SamplerSlot), as the shaders' table holds them.
Definition metal_device.h:122
void Remove(ImageIndex index) override
Frees the index for reuse; the image itself stays.
void SetImage(ImageIndex index, MetalImage *image)
Points the slot at another image.
void Clear() override
Removes every image, freeing all indices.
An image (GraphicsContext::CreateImage): a texture sampled by the shaders.
Definition metal_device.h:87
uint2 size
Definition metal_device.h:93
id< MTLTexture > texture
Definition metal_device.h:89
std::optional< ImageFormat > sourceFormat
Made by CreateImage from pixels of this format: UpdateImageRows can write into it.
Definition metal_device.h:95
Sampler sampler
Definition metal_device.h:92
MTLPixelFormat format
Definition metal_device.h:91
bool external
Definition metal_device.h:90
uint64_t ResidentBufferId
GPU storage kept across frames (UploadResidentBuffers); 0 is none.
Definition gui_rhi.h:36
Sampler
How an image is filtered and addressed when sampled.
Definition gui_image.h:89
ImageIndex
Index of an image in the graphics context's image set, as the shaders sample it.
Definition gui_image.h:99
uint64_t DeviceAddress
Shader-visible buffer address.
Definition gui_render_primitives.h:206
ResidentState
Where a resident buffer is.
Definition gui_rhi.h:40
@ NearestRepeat
Definition gui_image.h:92
@ Invalid
Definition gui_image.h:99
Where the shaders find their resources (all_common.slang, sdf_color.slang): buffer,...
Definition metal_device.h:51
constexpr NSUInteger kBoxStyles
Definition metal_device.h:54
constexpr NSUInteger kConstants
RootConstants.
Definition metal_device.h:52
constexpr NSUInteger kImages
each image slot's MTLResourceID
Definition metal_device.h:57
constexpr NSUInteger kImageSamplers
each image slot's sampler, a uint each
Definition metal_device.h:56
constexpr NSUInteger kPrimitives
Definition metal_device.h:53
constexpr NSUInteger kColorStyles
Definition metal_device.h:55
constexpr NSUInteger kSamplers
nearest repeat, linear repeat, linear clamp
Definition metal_device.h:58
Definition metal_device.h:40
uint32_t SamplerSlot(Sampler sampler)
The sampler (0, 1, 2) the shaders sample an image with: its entry in the per-image table.
constexpr uint32_t kMaxImageSlots
The most images the shaders' image table holds (all_common.slang's kMetalMaxImages).
Definition metal_device.h:46
constexpr MTLPixelFormat kDepthFormat
Definition metal_device.h:43
constexpr MTLPixelFormat kDrawFormat
What a window frame draws into, as on the other APIs: 8-bit BGRA, and 32-bit float depth.
Definition metal_device.h:42
Definition gui_logging.h:24
Definition gui_render_primitives.h:257
A 64-bit element ID whose bit layout depends on its IDMode.
Definition gui_id.h:23
Definition gui_base_types.h:394
A buffer the CPU writes and the GPU reads (shared storage), and its handle for addresses.
Definition metal_device.h:74
DeviceAddress Address(size_t offset) const
Definition metal_device.h:80
uint32_t handle
0: none
Definition metal_device.h:76
id< MTLBuffer > buffer
Definition metal_device.h:75
void * Mapped() const
Definition metal_device.h:79
size_t size
Definition metal_device.h:77
A host's device and queue, for the GUI to render on (SetExternalDevice) instead of making its own.
Definition metal_graphics_context.h:39
std::unique_ptr< MetalImage > image
Definition metal_device.h:186
id< MTLResource > resource
Definition metal_device.h:187
uint64_t afterValue
Definition metal_device.h:185
A whole image's pixels, or with partial a band of rows from firstRow written into an image already up...
Definition metal_device.h:196
uint32_t firstRow
Definition metal_device.h:200
uint32_t rowCount
Definition metal_device.h:201
id< MTLBuffer > staging
Definition metal_device.h:198
MetalImage * image
Definition metal_device.h:197
NSUInteger rowPitch
Definition metal_device.h:199
std::function< void(const ScenePayload &scene)> record
Definition metal_device.h:271
color4f clear
Definition metal_device.h:270
What RenderScene keeps for a key: its color texture (in the image set) and depth, both in liveImages.
Definition metal_device.h:259
uint64_t lastFrame
the frame it was last asked for
Definition metal_device.h:264
uint2 extent
Definition metal_device.h:263
ImageIndex index
Definition metal_device.h:262
MetalImage * color
Definition metal_device.h:260
MetalImage * depth
Definition metal_device.h:261
Definition metal_device.h:134
void Wait(uint64_t value)
Waits on the CPU until the commit counted value (and every one before) is done.
id< MTLDevice > device
Definition metal_device.h:140
RHI::ResidentBufferId CreateResidentBuffer(std::span< const RHI::UploadRequest > requests, std::span< DeviceAddress > addresses)
uint32_t nextBufferHandle
Definition metal_device.h:168
MetalImageSet imageSet
Definition metal_device.h:227
id< MTLBuffer > quadIndices
p * 4 + { 0, 1, 3, 0, 3, 2 } for each quad p.
Definition metal_device.h:243
void FlushDeletions()
Frees what the GPU is done with.
GradientManager * lastGradients
Definition metal_device.h:234
bool EnsureQuadIndices(uint32_t quads)
Grows the quads' index buffer to hold quads; false when it can't.
std::vector< ImageUpload > uploadScratch
Definition metal_device.h:205
float lastTime
Definition metal_device.h:235
void RecordPendingUploads(id< MTLCommandBuffer > commandBuffer)
Records the queued image copies into commandBuffer, ahead of its draws.
uint64_t Completed()
The highest value all commits up to are done.
uint64_t Commit(id< MTLCommandBuffer > commandBuffer)
Commits commandBuffer and counts it; its value.
std::string deviceName
Definition metal_device.h:137
std::pair< id< MTLBuffer >, NSUInteger > Resolve(DeviceAddress address) const
The buffer and offset an address names; nil for 0 or a buffer let go of.
uint64_t completed
Definition metal_device.h:150
std::deque< std::pair< uint64_t, id< MTLCommandBuffer > > > inFlight
Definition metal_device.h:149
std::vector< ImageUpload > imageUploads
Definition metal_device.h:204
std::unordered_map< RHI::ResidentBufferId, Buffer > residents
Shared memory: written at once and never again, so ready for the draws recorded from now on.
Definition metal_device.h:213
GPUDrawPushConstants pushConstants
the styles' addresses and the time, from PrepareFrame
Definition metal_device.h:247
std::string gpuPreference
Definition metal_device.h:136
std::mutex inFlightMutex
The command buffers committed and not seen complete, oldest first.
Definition metal_device.h:148
std::unordered_map< ID, Scene > scenes
Definition metal_device.h:273
std::vector< id< MTLRenderPipelineState > > pipelineStates
By PrimitiveKind; GpuPipeline::pipeline is the id<MTLRenderPipelineState>, unretained.
Definition metal_device.h:237
uint32_t imageSlots
asked for with SetImageSlotCount
Definition metal_device.h:138
std::vector< ImageIndex > gradientPages
each gradient page's index in the image set
Definition metal_device.h:232
ExternalDevice external
the host's device and queue, when it gave them
Definition metal_device.h:135
id< MTLDepthStencilState > depthWrite
GREATER_EQUAL, writes (occluders).
Definition metal_device.h:240
MetalImage * CreateTargetImage(uint2 size, MTLPixelFormat format, MTLTextureUsage usage, Sampler sampler)
A texture the GPU draws into (a scene's), in liveImages so DestroyImageAtEnd frees it; null on failur...
std::mutex uploadMutex
images are made on any thread
Definition metal_device.h:203
StyleManager * lastStyles
PrepareFrame's, for a live resize's redraw.
Definition metal_device.h:233
std::unordered_map< uint32_t, id< MTLBuffer > > buffers
Every buffer the shaders read, by its handle (Buffer::handle); handles are never handed out twice.
Definition metal_device.h:167
void RecordScenes(id< MTLCommandBuffer > commandBuffer, ID window)
Records the scenes asked for in window this frame, before its UI.
std::array< RHI::GpuPipeline, kPrimitiveKindCount > pipelines
Definition metal_device.h:238
RHI::ResidentBufferId boxStyles
The box styles (a resident buffer), made again when they change; 0: none.
Definition metal_device.h:229
std::vector< Garbage > garbage
Definition metal_device.h:190
void WaitIdle()
Waits until everything committed so far is done.
std::mutex garbageMutex
images are let go on any thread
Definition metal_device.h:189
static constexpr uint64_t kSceneKeepFrames
a scene not asked for this long goes
Definition metal_device.h:254
void DestroyAfterGpu(std::unique_ptr< MetalImage > image, uint64_t afterValue)
What's let go is freed once the GPU is past afterValue: the next commit (submitted + 1) for anything ...
uint64_t sceneFrame
Definition metal_device.h:275
static constexpr MTLPixelFormat kSceneColorFormat
Definition metal_device.h:253
std::atomic< bool > removed
A command buffer failed in a way that loses the device: told once, and the GUI is told through Device...
Definition metal_device.h:153
void ReleaseBuffer(Buffer &buffer)
Its handle given back: draws recorded with it keep the buffer (Metal holds it).
std::atomic< uint64_t > submitted
Every commit counts the next value: submitted is the last one.
Definition metal_device.h:146
uint32_t quadCapacity
Definition metal_device.h:244
std::unordered_set< MetalImage * > liveImages
Every image made and not let go for a frame (DeviceScope::Frame): those handed over for the applicati...
Definition metal_device.h:224
id< MTLCommandQueue > queue
Definition metal_device.h:141
void ReleaseResident(RHI::ResidentBufferId id)
std::vector< SceneRequest > sceneRequests
Definition metal_device.h:274
RHI::ResidentBufferId colorStyles
The color styles, with their gradient pages' slots, likewise.
Definition metal_device.h:231
void DestroyAfterGpu(id< MTLResource > resource, uint64_t afterValue)
std::unordered_map< uint32_t, std::unique_ptr< MetalImage > > externalImages
By image index: what the image set points at for a host's texture.
Definition metal_device.h:278
std::array< id< MTLSamplerState >, 3 > samplers
SamplerSlot's order.
Definition metal_device.h:241
RHI::ResidentBufferId nextResident
Definition metal_device.h:214
id< MTLBuffer > emptyBuffer
Bound where a draw's buffer address is 0, so every buffer the shaders declare is bound.
Definition metal_device.h:246
id< MTLDepthStencilState > depthTest
GREATER_EQUAL, no writes.
Definition metal_device.h:239
Buffer CreateBuffer(size_t size)
A shared buffer the shaders can read, with a handle. Empty on failure.
RHI::ResidentState ResidentState(RHI::ResidentBufferId id) const
The constants each draw sets (setVertexBytes): the world matrix's four columns, the time,...
Definition metal_device.h:64
uint32_t firstVertex
Definition metal_device.h:67
float elapsedTime
Definition metal_device.h:66
uint32_t _pad[2]
Definition metal_device.h:68
float worldColumns[16]
Definition metal_device.h:65
Definition gui_base_types.h:74