renderer-metal
Garnet Metal renderer
require "garnet-renderer-metal" provides Garnet::Metal::Renderer, consuming the same generic graphics values as OpenGL. It has no ECS, decoder, GLFW or AppKit dependency and creates no device on require.
require "garnet-renderer-metal"
renderer = Garnet::Metal::Renderer.new
begin
# Application-owned Array(Graphics::Draw), using generic meshes/materials.
output = renderer.render(draws, Garnet::Graphics::RenderTarget.new(256, 256))
native = output.to_gpu(renderer) # already resident; no upload or readback
pixels = renderer.readback(output) # explicit CPU Image, if needed
ensure
renderer.close
end
This is an API sketch; the complete window example builds its own geometry and texture. The separate AppKit shard exports AppKit::MetalWindow, with main-thread event polling, backing-pixel dimensions and GPU presentation through present(Metal::Texture). The renderer depends on the general-purpose Metal shard; its fixed graphics profile and shaders remain owned by Garnet. Rendering, uploads and readback use typed Crystal Metal objects; there is no renderer-specific native bridge.
Resource and execution contract
The initial profile matches OpenGL: indexed XY/UV triangles, atlas regions including clockwise packing, copied transforms, tint, nearest/linear clamp sampling, sRGB/linear RGBA8 input and straight/premultiplied alpha. Output is top-left, linear, premultiplied RGBA8; each render produces a distinct immutable output version. Metal remaps the shared clip-depth convention internally.
Preparation opens and closes source IO only on a cache miss, validates decoded metadata, and copies through temporary staging allocations into private Metal textures/buffers. Neither the cache nor native wrapper retains decoded pixels. Memory-backed sources intentionally keep their original bytes; disk-backed sources do not. Native-source textures are reused on their producing renderer; unsupported foreign imports raise Graphics::IncompatibleDevice.
Texture descriptor and mesh-stream caches use weak source references guarded against identity reuse. collect sweeps expired entries; evict drops preparations. Retained native wrappers/output textures survive eviction. close ends the renderer session and invalidates retained outputs. Call it explicitly on the owner thread. The Metal shard owns native lifetimes through its typed objects and finalizers; native allocations held by surviving wrappers remain alive until those references are released. Run collect at maintenance points even when not repainting. present also sweeps automatically every auto_collect_interval (two seconds by default; nil disables it), so removing content from a scene is enough to release its GPU copies once the GC has reclaimed the source. GC timing is not a hard VRAM budget.
All upload, render, readback and presentation submissions currently wait for completion before returning. The offscreen renderer is owner-thread confined. The optional AppKit host requires the main thread.
Depth-tested 3D
Renderer#render_3d accepts indexed XYZ meshes (Graphics::Mesh3D), affine object-to-world transforms and an application-supplied view-projection matrix. Math::Mat4.perspective uses a right-handed view with −Z forward and clip depth from 0 to w. The pass clears depth each time and returns a regular GPU-resident Graphics::Texture that can be presented or used in 2D composition.
The shared Renderer#render(frame) path takes per-material textures and fragment programs, lighting, shadows, instancing and skinning on Metal. See the shared 3D contract for material and binding details. Meshes draw with the Metal Shading Language that garnet shaders build generates from the shared Slang programs (Graphics::Shaders::Mesh3D and each material's Fragment3D): one per-draw Draw3D uniform buffer from a reused ring, a vertex descriptor for the mesh streams, and textures and samplers at the reflected bindings.
Waystone Lab is an iOS verification fixture for 3D scenery and a depth-tested 2D character.
Build and verification
Building the examples requires macOS, Crystal 1.19.1+, Xcode and a Metal-capable device. The renderer compiles its shaders at runtime. The AppKit example builds its own window bridge, and the iPhone example uses UIKit and CAMetalLayer.
To run the window example from this shard's directory:
cd renderer-metal # from the workspace root
shards install
crystal run examples/primitives.cr
The example requires its own shard entrypoint by a relative path; dependencies use their shard exports. Set GARNET_EXAMPLE_FRAMES=120 to exit after a bounded number of frames.
For the full verification commands, from the workspace root:
scripts/check-metal gpu
scripts/check-metal parity
scripts/check-metal build
GARNET_EXAMPLE_FRAMES=120 "${TMPDIR:-/tmp}/garnet-renderer-metal-example"
The GPU specs cover cache reuse, reader closure on success/failure, padded image rows, deformation stream sharing, output version retention, eviction, incompatible devices, unsupported extents and recovery. Parity renders the same atlas/filter/tint/transform fixture on Metal and OpenGL, then samples each native output in a second pass and compares all channels within two byte levels. Parity requires GLFW/OpenGL; standalone Metal does not.
The implementation follows Apple's private-resource upload model and custom Metal view presentation. Future targets can provide their own surface adapters without changing generic draw data.
Mixed composition
This renderer also accepts Graphics::Drawing, including vector/mesh/image content, group opacity, alpha/luminance/inverted masks and viewport outputs. See scene, vector, and the shared gallery. Mask sampling and composition remain native GPU operations.
Gradient materials use local geometry coordinates and native fragment evaluation on this backend. Linear and centered radial gradients support pad/repeat/reflect spread and up to 16 stops. See the shared paint contract for interpolation and limits.
Image-pattern materials support per-axis repeat/reflect/pad/transparent addressing and local paint transforms. Native shaders honor atlas rotation/trim and filter premultiplied texels without atlas-neighbor bleed. Captured GPU textures are valid pattern sources; see the image-pattern contract.
The shared composition pipeline also supports two-circle gradients, Gaussian blur, color-matrix effect chains and all sixteen isolated blend modes. See the graphics effect contract for ordering, color space and limits. These are native GPU passes; optional Clipper2 geometry arrives as ordinary meshes.
renderer-metal
- 0
- 0
- 0
- 1
- 6
- about 8 hours ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 04:40:11 GMT