Drawing a triangle with Metal 4
At a glance
| Item | Summary |
|---|---|
| Purpose | Render a colorful, rotating 2D triangle by running draw commands with a render pipeline on a GPU. |
| App architecture | A C, C/Objective-C header, Metal, Objective-C sample with the source-visible chain main → ViewController → Metal4Renderer → metal_stdlib APIs. |
| Main patterns | Protocol-oriented abstraction, Delegate or data-source callbacks |
| Project style | 28 scanned source file(s) across C, C/Objective-C header, Metal, Objective-C, organized around ranked entry, type, and file boundaries. |
| Execution model | No structured execution marker indexed; callback threading requires source review. |
| State/event model | No structured observation or publisher-scheduling marker indexed. |
| Key frameworks/packages | Availability.h, metal_stdlib, simd, string.h, TargetConditionals.h; these are source dependencies, not architecture labels. |
Project structure
Source bundle/
├── Application/
│ ├── main.m
│ ├── AppDelegate.h
│ ├── AppDelegate.m
│ ├── WindowSceneDelegate.h
│ └── WindowSceneDelegate.m
├── Metal 4 renderer/
│ ├── Metal4Renderer.h
│ └── Metal4Renderer.m
├── Metal renderer/
│ ├── MetalRenderer.h
│ └── MetalRenderer.m
└── View controller/
├── MetalKitViewDelegate.h
├── MetalKitViewDelegate.m
└── ViewController.h
Structure observations
- Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
- Primary languages: C, C/Objective-C header, Metal, Objective-C.
- The verified tree contains 9 project/configuration file(s) and 8 source declaration(s).
Overall architecture
flowchart LR
N1["main"]
N2["ViewController"]
N3["Metal4Renderer"]
N4["metal_stdlib APIs"]
N1 --> N2
N2 --> N3
N3 --> N4
Reference code
Application/main.m:19 — architecture anchor
#if defined(TARGET_IOS) || defined(TARGET_TVOS)
int main(int argc, char * argv[]) {
// ...
#error No simulator support for Metal API for this SDK version. Must build for a device
// ...
}
#endifInterpretation
The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into Metal.
Ownership and state
classDiagram
WindowSceneDelegate o-- UIWindow : window
Metal4Renderer o-- id : device
Metal4Renderer o-- id : defaultLibrary
MetalRenderer o-- id : device
Ownership evidence
Application/WindowSceneDelegate.h:13 — stored dependency or nearest verified ownership anchor
@interface WindowSceneDelegate : UIResponder <UIWindowSceneDelegate>
@property (nonatomic, strong) UIWindow *window;
@end| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
WindowSceneDelegate |
UIWindow (window) |
retains or copies an assigned value | Header-visible collaborators |
Metal4Renderer |
id (device) |
stores or receives | The declaring implementation writes; property clients read |
Metal4Renderer |
id (defaultLibrary) |
stores or receives | The declaring implementation writes; property clients read |
MetalRenderer |
id (device) |
stores or receives | The declaring implementation writes; property clients read |
Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
No source-visible execution, scheduling, or synchronization boundary was found in the indexed source.
@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| Source import | Availability.h |
The cited file imports this module; runtime use and architectural role are not inferred. | Application/main.m:11 |
| Source import | metal_stdlib |
The cited file imports this module; runtime use and architectural role are not inferred. | Shaders/Shaders.metal:8 |
| Source import | simd |
The cited file imports this module; runtime use and architectural role are not inferred. | Shaders/ShaderTypes.h:11 |
| Source import | string.h |
The cited file imports this module; runtime use and architectural role are not inferred. | Renderer common/TriangleData.c:10 |
| Source import | TargetConditionals.h |
The cited file imports this module; runtime use and architectural role are not inferred. | Application/main.m:10 |
receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.
Class and protocol design
Renderer common/RendererProtocol.h:11 — representative type boundary
@protocol Renderer <NSObject>
// ...
@end| Type | Responsibility | Depends on or conforms to |
|---|---|---|
Renderer |
Defines a capability or collaboration contract | NSObject |
AppDelegate |
Receives callback-driven events | UIResponder, UIApplicationDelegate |
WindowSceneDelegate |
Receives callback-driven events | UIResponder, UIWindowSceneDelegate |
Metal4Renderer |
Owns drawing, GPU, or presentation processing | NSObject, Renderer |
MetalRenderer |
Owns drawing, GPU, or presentation processing | NSObject, Renderer |
MetalKitViewDelegate |
Receives callback-driven events | NSObject, MTKViewDelegate |
ViewController |
View lifecycle, callbacks, and feature coordination | PlatformViewController |
RasterizerData |
Represents feature data | Concrete collaborators/imported frameworks |
The source explicitly defines local protocol relationships: Metal4Renderer → Renderer, MetalRenderer → Renderer.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
window (Application/WindowSceneDelegate.h:13) |
header-visible |
The declaration is exposed to translation units that import the header. | Inference: declare a contract needed by other Objective-C/C translation units. |
device (Metal 4 renderer/Metal4Renderer.h:20) |
header-visible |
The declaration is exposed to translation units that import the header. | Inference: declare a contract needed by other Objective-C/C translation units. |
defaultLibrary (Metal 4 renderer/Metal4Renderer.h:26) |
header-visible |
The declaration is exposed to translation units that import the header. | Inference: declare a contract needed by other Objective-C/C translation units. |
device (Metal renderer/MetalRenderer.h:19) |
header-visible |
The declaration is exposed to translation units that import the header. | Inference: declare a contract needed by other Objective-C/C translation units. |
Reference code
Application/WindowSceneDelegate.h:13 — representative boundary
@interface WindowSceneDelegate : UIResponder <UIWindowSceneDelegate>
@property (nonatomic, strong) UIWindow *window;
@endSwift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| View lifecycle, callbacks, and feature coordination | ViewController |
The source’s Controller suffix makes this role explicit. |
| Receives callback-driven events | AppDelegate, MetalKitViewDelegate, WindowSceneDelegate |
The source’s Delegate suffix makes this role explicit. |
| Owns drawing, GPU, or presentation processing | Metal4Renderer, MetalRenderer, Renderer |
The source’s Renderer suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Protocol-oriented abstraction | Metal 4 renderer/Metal4Renderer.h:14 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Delegate or data-source callbacks | Application/AppDelegate.h:11 |
Callback protocols invert event delivery back into the sample’s owner. |
Main application flow
sequenceDiagram
participant Metal4Renderer
participant device
participant residencySet
participant commandQueue
Metal4Renderer->>Metal4Renderer: init()
Metal4Renderer->>device: newMTL4CommandQueue()
Metal4Renderer->>device: newCommandBuffer()
Metal4Renderer->>device: newDefaultLibrary()
Metal4Renderer->>residencySet: addAllocation()
Metal4Renderer->>residencySet: commit()
Metal4Renderer->>commandQueue: addResidencySet()
Metal4Renderer->>Metal4Renderer: updateViewportSize()
Reference code
Metal 4 renderer/Metal4Renderer.m:129 — initWithMetalKitView()
- (nonnull instancetype) initWithMetalKitView:(nonnull MTKView *) view
{
// ...
self = [super init];
if (nil == self) { return nil; }
_device = view.device;
commandQueue = [self.device newMTL4CommandQueue];
commandBuffer = [self.device newCommandBuffer];
_defaultLibrary = [self.device newDefaultLibrary];
triangleVertexBuffers = [self makeTriangleDataBuffers:kMaxFramesInFlight];
argumentTable = [self makeArgumentTable];
residencySet = [self makeResidencySet];
commandAllocators = [self makeCommandAllocators:kMaxFramesInFlight];
viewportSizeBuffer = [self.device newBufferWithLength:sizeof(viewportSize)
options:MTLResourceStorageModeShared];
renderPipelineState = [self compileRenderPipeline:view.colorPixelFormat];
frameNumber = 0;
sharedEvent = [self.device newSharedEvent];
sharedEvent.signaledValue = frameNumber;
[residencySet addAllocation:viewportSizeBuffer];
for (id<MTLBuffer> triangleVertexBuffer in triangleVertexBuffers) {
[residencySet addAllocation:triangleVertexBuffer];
}
[residencySet commit];
[commandQueue addResidencySet:residencySet];
[commandQueue addResidencySet:((CAMetalLayer *)view.layer).residencySet];
[self updateViewportSize:view.drawableSize];
return self;
}Naming conventions
- Types: Controller: ViewController; Delegate: AppDelegate, MetalKitViewDelegate, WindowSceneDelegate; Renderer: Metal4Renderer, MetalRenderer, Renderer.
- Protocols:
Renderer. - Methods:
application,scene,sceneDidDisconnect,initWithMetalKitView,updateViewportSize,renderFrameToView,isMissingRequirementsFromView. - Files:
Application/AppDelegate.h,Application/AppDelegate.m,Application/WindowSceneDelegate.h,Application/WindowSceneDelegate.m,Metal 4 renderer/Metal4Renderer.h,Metal 4 renderer/Metal4Renderer.m.
Architecture takeaways
mainis the main source-visible entry or composition anchor for this sample.- Framework work reaches metal_stdlib, simd through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
- Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
- Access-control conclusions separate verified language visibility from the likely design rationale.
- Local protocol relationships provide an explicit substitution boundary.
Source map
| Source file | Relevant symbols |
|---|---|
Application/main.m |
Cited implementation, Availability.h, TargetConditionals.h, Feature implementation |
Application/WindowSceneDelegate.h |
Cited implementation, window, WindowSceneDelegate |
Renderer common/RendererProtocol.h |
Renderer |
Metal 4 renderer/Metal4Renderer.h |
device, defaultLibrary, Cited implementation, Metal4Renderer |
Metal renderer/MetalRenderer.h |
device, MetalRenderer |
Application/AppDelegate.h |
Cited implementation, AppDelegate |
Shaders/Shaders.metal |
metal_stdlib, RasterizerData |
Shaders/ShaderTypes.h |
simd, Feature implementation |
Renderer common/TriangleData.c |
string.h, Feature implementation |
Application/AppDelegate.m |
AppDelegate |
Application/WindowSceneDelegate.m |
WindowSceneDelegate |
Metal 4 renderer/Metal4Renderer.m |
Metal4Renderer |
Metal renderer/MetalRenderer.m |
MetalRenderer |
View controller/MetalKitViewDelegate.h |
MetalKitViewDelegate |
View controller/MetalKitViewDelegate.m |
MetalKitViewDelegate |
View controller/ViewController.h |
ViewController |