graphics
Garnet Graphics
Generic resource descriptors and value descriptions, independent of native backends. Requires Crystal 1.19.1 or newer. Byte acquisition uses garnet-content; format decoding is separate from source access and GPU preparation.
require "garnet-graphics"
alias G = Garnet::Graphics
# Raw RGBA bytes with known metadata; encoded files use an image decoder.
source = Garnet::Content::FileSource.new("texture.rgba")
info = G::ImageInfo.new(256, 256)
texture = G::Texture.load(source, G::RGBA8Decoder.new(info))
region = G::TextureRegion.new(texture, 0, 0, 64, 64)
# Runs on the renderer's owner. A cache hit neither opens nor decodes the source.
native = texture.to_gpu(renderer)
For PNG/JPEG and other supported encoded images:
require "garnet-graphics-stb"
texture = G::Texture.load(
Garnet::Content::FileSource.new("characters.png"), G::STBDecoder.new)
With garnet-graphics-stb required, G::Texture.load(source) uses a default STBDecoder. Asset loaders across Garnet follow this X.load(source : Garnet::Content::Source, ...) convention; TileMap.load(source, palette) is the tile map's.
Texture.load borrows a newly opened IO to read metadata, then closes it. TextureResource retains that metadata, the source, and the decoder configuration—not decoded pixels. A new descriptor identifies a new content version. Reuse one descriptor for an atlas; regions share its native realization.
Ownership and memory
Content::Source#open returns a fresh cursor; the opening consumer closes it. Decoders borrow readers and leave them open. Renderer preparation closes readers on success/failure and retains temporary decode/upload bytes only for the operation. Memory sources intentionally retain immutable bytes for replay; file sources retain a path and revision. Eviction therefore does not imply every resource has a CPU copy available.
Image is explicitly CPU-accessible RGBA8 data, suitable for decoding, inspection, or readback. Texture.new(image) is an explicit retained-memory convenience. For low-retention disk-backed assets use Texture.load(FileSource, decoder) instead. Constructors defensively copy memory input; private mutable arrays can be used to build replacement content, but no published allocation exposes writable storage.
Texture, TextureRegion, Mesh, Material, Sampler, Draw and RenderTarget are value descriptions. Copies retain shared resource identities. Editing a local Draw does not change another draw. Mutable IO cursors, component stores, decoder sessions and renderer caches remain execution-owned.
Errors
Graphics and renderer failures raise Garnet::Graphics::Error, a Garnet::Error. Its subclasses are ClosedError (a renderer, device or host used after close), BackendError (native API failures and missing device capabilities), IncompatibleDevice (a resource from another device) and TransientBudgetExceeded. Renderer misuse, such as calls from outside the owner thread or readback during a render pass, raises Graphics::Error itself. Invalid arguments still raise ArgumentError.
Mesh streams
Stream(T) is now a scalar source descriptor, with count and little-endian representation. It supports UInt8, UInt32 and Float32. Array construction chooses retained memory explicitly; from_source(source, count) can use disk/archive content without retaining an array. Construction from a source is lazy; mesh validation and GPU preparation read it as needed.
positions = G::Stream(Float32).from_source(
Garnet::Content::FileSource.new("positions.f32"), 6)
uvs = G::Stream(Float32).new([0_f32, 0_f32, 1_f32, 0_f32, 0_f32, 1_f32])
indices = G::Stream(UInt32).new([0_u32, 1_u32, 2_u32])
mesh = G::Mesh.new(positions, uvs, indices)
edited = positions.to_a
edited[2] = 2_f32
changed = mesh.with_positions(G::Stream(Float32).new(edited))
# Old positions are unchanged; UV/index descriptors and native caches are shared.
Enumerate or call to_a for bulk access; scalar indexing opens a reader and skips to the requested value. Do not use repeated indexing as a bulk file-read strategy. Supplied bytes must match the declared count. Mesh construction validates matching XY/UV pairs, finite values and UInt32 triangle indices.
An optional VertexTint on a mesh stores one packed linear 0xRRGGBBAA light color per vertex, plus an optional dark color. Renderers interpolate the channels and apply (rgb * light.rgb + (alpha - rgb) * dark.rgb) * light.a to premultiplied RGB. Output alpha is multiplied by light alpha. Dark alpha is unused. Geometry-only clips ignore vertex tint.
Each Draw also carries a DirectBlend value. SourceOver is the default. Additive sums premultiplied components, Multiply uses the destination RGB as its source factor, and Screen uses one minus source RGB as its destination factor. Alpha uses source-over outside additive draws. BlendOp remains the interface for isolated group blending and its distinct formulas.
Native content and output
NativeTextureSource permits backend-specific retained GPU content without a fake IO interface. Texture#to_gpu(renderer) delegates to the concrete renderer's prepare. Compatible native content is reused directly; unsupported imports fail explicitly.
output = renderer.render(draws, G::RenderTarget.new(512, 512))
output.to_gpu(renderer) # retained GPU allocation, no readback/re-upload
image = renderer.readback(output) # explicit CPU acquisition
Each render creates a new logical output. Old versions remain valid while retained. Closing the producing device explicitly ends the native resources' validity.
Streaming CPU pixels
Graphics::StreamingTexture is the backend-neutral way to show pixels the game rewrites every frame (a software renderer, video, an emulator screen). The game never touches a renderer: it publishes frames on its own thread and draws #texture or #region like any other texture, in RenderQueue drawings, sprites or materials.
screen = Graphics::StreamingTexture.new(320, 200)
screen.update(pixels) # copy a whole RGBA8 frame (optional stride:)
screen.write { |back| fill(back) } # or fill the back buffer in place
canvas.draw_mesh(Graphics::Drawing::QUAD, Graphics::Material.new(screen.region))
When a renderer (OpenGL, Metal or Vulkan) prepares the texture for a frame, on its owner thread, it allocates a GPU texture once, caches it like a decoded texture (release frees it, collect sweeps it after the stream is collected) and uploads the most recently published frame, once per revision. Frames are double-buffered under a lock held only for the publish swap and the upload copy, so a pipelined render thread never sees a torn frame; a frame drawn after newer pixels were published shows the newer ones. Publish from one thread at a time. #write yields the frame from two publishes ago, so overwrite every pixel.
StreamingTexture.new(w, h, mipmaps: true) keeps a mip chain that the renderer regenerates on the GPU each time it uploads a newer revision (one mip generation per published frame).
Publishing a dynamic texture revision
OpenGL (including GLES), Metal and Vulkan expose the same owner-thread calls for code that drives a renderer directly. A drawing or sprite referencing a dynamic texture samples its current contents when rendered. Upload all texels before first use. To publish a particular frame, pin the texture after uploading it and record the returned handle.
live = renderer.dynamic_texture(width, height)
renderer.update_texture(live, pixels_a)
frame_a = renderer.pin_texture(live)
drawing = Graphics::Drawing.record do |canvas|
canvas.draw_image(Graphics::TextureRegion.new(frame_a), width.to_f32, height.to_f32)
end
renderer.update_texture(live, pixels_b)
Each pin allocates a renderer-owned texture and copies the full RGBA8 image on the GPU, preserving top-down orientation, color space and alpha mode. The pinned texture accepts no further uploads and stays valid while retained and the renderer is open. OpenGL orders the copy with subsequent uploads on the same context. Metal and Vulkan reuse their existing synchronous command submission so the copy completes before return. Ordinary updates keep using the original allocation and incur no snapshot cost.
Initial graphics profile
RGBA8 images, sRGB/linear input, straight/premultiplied alpha, top-left rows, explicit byte stride; clockwise-packed atlas regions with trim metadata; XY/UV triangle meshes; unlit tint, nearest/linear sampling with optional mipmaps (see Mipmaps and minification); copied Mat4 placement. Render targets produce linear premultiplied RGBA8. Sampling clamps to the whole texture, so linear-filtered atlas regions need gutters. Trim metadata does not automatically reposition meshes.
Custom shaders, arbitrary vertex layouts, clipping and vector painting remain subsequent profiles. Concrete renderers consume clip-space coordinates after transform; the optional scene producer supplies its view mapping.
Run scripts/check-graphics unit, scene, decoder, gpu, build, or card from the workspace. The script resolves local shard sources without dependency downloads. Decoder/card builds need the STB archive (make -C LibSTBImage/src/lib_stb_image/ext). GPU tests require an actual desktop context and do not silently skip on failure. See OpenGL usage and Metal usage.
Numbers and vectors
Recorder transforms (translate, scale, rotate, draw_image, layer opacity), TextureRegion#uv, Material3D cutoff, PhysicalMaterial3D factors, light ranges/intensities/angles and ViewportProjection points accept any Number. Recorder#translate/#scale and ViewportProjection#inside?/#ray/#pick also accept a Garnet::Math::Vec2.
Mixed drawing and composition
Graphics::Drawing.record builds an immutable ordered snapshot using draw(primitive), draw_mesh, draw_image, scoped save, transforms, and scoped layer(opacity:, mask:, mask_mode:, inverted:). Masks passed directly to the recorder are drawings in the same picture coordinate space. garnet-vector adds fill/stroke/clip recording; garnet-scene extracts mixed ECS subtrees into this same description.
draw(existing_drawing) instances a retained drawing under the recorder's current transform. Its neutral PictureOp preserves internal composition, including layers and masks. This is also the operation used by scene Picture components for reusable drawings and loaded SVG documents.
All concrete renderers implement render(drawing, target, samples: 2) alongside the existing render(draws, target). Drawings use top-left pixel units; legacy Draw arrays retain clip-space transforms. samples is 1 or 2 per axis. Group opacity, alpha/luminance/inverted masks, and viewport outputs execute as GPU passes. A Material may carry a CoverageMask, sampled with the mesh's original normalized UVs; ordinary materials keep their previous behavior. MaskMode::Luminance computes coverage from linear premultiplied RGB with Rec.709 coefficients. MaskMode::LuminanceSRGB first recovers straight RGB, encodes it to sRGB, then multiplies luminance by alpha; fully transparent pixels contribute zero. Both modes support inversion after coverage calculation. CPU readback remains explicit.
The current shared planner elides identity groups and otherwise uses full-size intermediate targets. It preserves order and output versions. Vector preparation and pass planning are shared code; native texture binding and mask shaders live in each backend. Each backend remains usable without ECS or vector modules. Blur/color-matrix effects and isolated blend groups extend this planner as described below; pass pooling and richer filter profiles remain future work.
Gradient paints
LinearGradient, centered RadialGradient, and TwoCircleGradient are immutable descriptions usable on any Material, including ordinary textured meshes. The gradient multiplies the sampled premultiplied texture color; tint and mask then apply as usual. Vector fills/strokes use a white texture with the same material.
stops = [
G::GradientStop.new(0, Garnet::Color.new(1_f32, 0_f32, 0_f32, 1_f32)),
G::GradientStop.new(1, Garnet::Color.new(0_f32, 0_f32, 1_f32, 1_f32)),
]
paint = G::LinearGradient.new(0, 0, 200, 0, stops, spread: :reflect)
material = G::Material.new(G::TextureRegion.new(G::Drawing.white), gradient: paint)
# With garnet-vector:
drawing = G::Drawing.record { |d| d.fill(Garnet::Vector::Path.rect(0, 0, 400, 100), paint) }
Coordinates are geometry-local XY, independent of mesh UVs and atlas regions. PaintTransform maps local coordinates into paint coordinates: x' = a*x + c*y + e, y' = b*x + d*y + f. Pass it as transform: to a gradient. For example, PaintTransform.new(a: 0.5_f32) doubles a radial gradient's horizontal extent. Scene transforms subsequently move geometry and paint together.
Stops must be ordered, have normalized offsets and colors, and contain at least one entry. Input and returned stop arrays are copied. Duplicate offsets make hard transitions, with the last stop at an exact offset winning. Interpolation defaults to premultiplied linear RGBA. Pass interpolation: :linear_rgb or interpolation: :srgb for straight-alpha interpolation in those color spaces, as used by SVG gradients. Stop colors are always supplied in straight linear RGBA; renderers perform any encoding before interpolation and return premultiplied linear output. First/last colors extend outside the stop range. spread: is :pad (default), :repeat or :reflect, applied to the gradient parameter before stop lookup. Coincident linear endpoints and nonpositive radial radii are rejected. RadialGradient.new(x, y, radius, stops) is centered; TwoCircleGradient supplies focal and general two-circle forms.
GL/GLES, Metal and Vulkan evaluate gradients in their fragment shaders with up to 16 stops per draw, rejecting larger descriptions explicitly. The core description has no backend stop limit. These are small uniform descriptions, not rasterized gradient textures; no image-sized CPU allocation or readback is involved. Vulkan uses a separate uniform buffer so draw push constants remain within the existing 112-byte layout. Gradient uniform caching and unrestricted precision/coordinate ranges are not part of this first profile.
Image-pattern paints
ImagePattern retains a TextureRegion and describes a tile in geometry-local coordinates. It can paint vector fills/strokes or ordinary meshes. Use Material.new(pattern) for meshes; the material obtains its region and sampler from the pattern. Optional tint, gradient and mask modulation work as with other materials.
pattern = G::ImagePattern.new(G::TextureRegion.new(texture), width: 32, height: 32,
transform: G::PaintTransform.new(e: -10_f32, f: -20_f32),
extend_x: :repeat, extend_y: :transparent, sampler: G::Sampler.new(:linear))
drawing = G::Drawing.record do |d|
d.fill(Garnet::Vector::Path.round_rect(10, 20, 240, 32, 8), pattern)
end
The tile starts at paint coordinate (0, 0); width/height default to the region's original untrimmed dimensions. PaintTransform maps local coordinates into that space independently of mesh UVs, and scene transforms move geometry and paint together. Each axis supports :repeat (default), :reflect, :pad (extend the edge), or :transparent (no repetition). Negative coordinates obey the same addressing rules. Tile extents must be positive and finite.
Atlas rotation is decoded and trimmed margins remain transparent within the original tile. Nearest filtering is the default. Linear filtering fetches and addresses each texel independently, interpolating premultiplied linear RGBA. This keeps atlas neighbors and transparent texel colors from bleeding into the pattern, including across repeated seams. Mipmaps and anisotropic filtering are not implemented; strongly minified patterns can alias.
A texture returned by renderer.render or scene.render_to_texture is also valid pattern content. Compatible native textures are reused directly without readback or re-upload, and the pattern retains that captured version. To update an ImagePattern, supply a new texture version. For live scene sources, use the scene Pattern component described below.
Drawing-backed patterns
PatternMapping(width, height, transform:, extend_x:, extend_y:, sampler:) contains the same placement options as ImagePattern, independently of content. ImagePattern.new(region, mapping) applies it to an image. Recorder#draw_pattern(content, target, primitive, mapping) applies a drawing tile to any primitive:
tile = G::Drawing.record do |d|
d.fill(Garnet::Vector::Path.circle(8, 8, 5), Garnet::Color::WHITE)
end
geometry = Garnet::Vector::Shape.new(
Garnet::Vector::Path.round_rect(0, 0, 240, 80, 12), Garnet::Color::WHITE)
drawing = G::Drawing.record do |d|
d.draw_pattern(tile, G::RenderTarget.new(16, 16), geometry, G::PatternMapping.new(32, 32))
end
The target specifies raster resolution and source drawing coordinates; mapping specifies how large the tile appears on the destination geometry. Omitting mapping uses the target dimensions as the tile size. The planner renders the source to a GPU texture and then applies the existing image-pattern path. Source drawings may contain vectors, meshes, images, layers, masks and further patterns. Consumer tint, gradient modulation, material mask and geometry transforms are retained; the original source image/pattern is replaced. Use white geometry paint for an unmodulated tile.
PatternOp is the immutable operation emitted by the recorder and by scene pattern extraction. It contains a drawing snapshot rather than entity references. Each use currently renders a fresh tile with the normal drawing antialiasing profile. Tile pooling, shared-use caching and automatic resolution selection remain future work. This provides nested vector-pattern composition without requiring an SVG or Lottie module.
Two-circle gradients
TwoCircleGradient.new(x0, y0, radius0, x1, y1, radius1, stops, ...) sweeps between two finite, distinct circles with nonnegative radii. It uses the same stop, interpolation, spread and paint-transform APIs as other gradients. A zero initial radius gives a focal gradient; shrinking and displaced circles are supported. A point selects the largest parameter whose interpolated circle has nonnegative radius; points outside the swept cone are transparent. Spread applies after that geometric selection. The existing centered RadialGradient remains a convenience description. Shader arithmetic uses Float32; almost-degenerate cones use a linear solve.
Group effects and blending
Composition intermediates use renderer-owned scoped scratch targets. Published render results remain distinct immutable versions and are never returned to the scratch pool. Ordered segments retire their intermediate inputs after submission, so a long list of isolated siblings does not retain all its scratch images at once.
transient_idle_budget defaults to 128 MiB, while transient_active_limit defaults to 512 MiB. Set either in bytes on the renderer. The idle budget trims immediately; exceeding the active limit raises TransientBudgetExceeded and unwinds acquired scratch targets. Budgets count nominal RGBA8 texture bytes, not driver overhead, published output versions, or imported asset storage. Counters expose transient_allocations, transient_reuses, transient_active_bytes, transient_peak_active_bytes and transient_idle_bytes. evict/close discard idle scratch targets on the device owner. GL deletion waits for completion; Metal/Vulkan currently complete submissions synchronously. Custom renderer implementations of DrawingRenderer provide private render_into(draws, target, destination) and destroy_transient(texture) hooks; the mutable destination hook is internal and must not publish reused targets.
Uploaded source textures and scalar streams also use a nominal byte budget: resident_cache_budget defaults to 128 MiB. Least recently used entries are evicted at outer render boundaries and during collection; the setter trims immediately outside rendering. cached_resource_bytes reports cache ownership and cache_evictions counts budget evictions. Budget changes inside rendering are rejected. Evicted mesh buffers are retired after submission completion; dropping texture cache ownership preserves separately retained native texture references. Source descriptions remain reusable and reload on the next cache miss. Driver overhead, user-retained native/output references and scratch storage are separate from this cache budget.
chain = Garnet::Graphics::EffectChain.new([
Garnet::Graphics::GaussianBlur.new(3).as(Garnet::Graphics::ImageEffect),
])
drawing = Garnet::Graphics::Drawing.record do |r|
r.blend(:screen) do
r.effects(chain) do
r.draw(vector_shape)
r.draw_mesh(mesh, material)
r.draw_image(region, 32_f32, 32_f32)
end
end
end
EffectChain copies its ordered array of immutable effects. EffectsOp processes a group's combined output, regardless of the primitive types inside it. ColorMatrix accepts twenty finite Float32 coefficients in row-major 4×5 order, operating on straight linear RGBA with a constant final column; it clamps and premultiplies the result. GaussianBlur accepts horizontal/vertical standard deviations from 0 to 32. Its default BlurSpace::OutputPixels remains constant under drawing transforms. BlurSpace::DrawingUnits scales with the drawing and is intended for format adapters whose blur lives in document coordinates. A rotated anisotropic drawing-unit kernel cannot be represented by the current two screen-axis passes and raises; uniform blur under rotation remains valid. The separable kernel is truncated at three sigma, uses transparent pixels beyond the output boundary, and adjusts for antialias supersampling. Zero sigma skips that axis. Effects are clipped to the explicit render target; reserve target space when a glow or blur should extend beyond content bounds.
blend(mode) { ... } / BlendOp creates an isolated group and blends its rendered result with preceding siblings in its containing drawing. The original sixteen BlendMode values are normal, multiply, screen, overlay, darken, lighten, color dodge/burn, hard/soft light, difference, exclusion, hue, saturation, color and luminosity. Their formulas follow W3C compositing and blending, evaluated in linear RGB, followed by premultiplied source-over composition. Additive additionally performs saturating addition of premultiplied color and alpha (Porter-Duff plus). This is an explicit engine color-space choice; it does not claim CSS's complete color-management behavior. Children inside an isolated group cannot see the outer backdrop. Plain nested pictures retain their existing nonisolated ordering.
Recorder nesting specifies ordering: for example, place effects inside a masked layer and that layer inside a blend group to filter, mask/apply opacity, then blend. Scene Effects, Layer/Mask/Clip, and Blend components apply in that order to an entity subtree. All intermediate images remain GPU textures. Filters and blend captures currently use full-target passes with no pooling, bounds cropping or persistent effect cache; performance optimization is deferred. Custom filter shaders, displacement, morphology, backdrop filters, extended Porter–Duff operators and HDR targets remain outside this profile.
Backdrop displacement
Record canvas.displace(x, y) { ... } with a drawing for the displacement map. Linear straight red and green encode signed X/Y offsets with a neutral midpoint of 0.5, and alpha controls coverage. Strength is in output pixels. The operation samples the preceding drawing with a shifted UV, then interpolates premultiplied results over its coverage. Drawing-unit bases are also available through DisplacementOp for rotated or scaled particle views.
Mipmaps and minification
A texture drawn much smaller than its size puts many texels on each pixel. Sampling only the full-size level then picks a few of them per pixel, so thin detail (1-px ink lines in a 2048² character atlas drawn 40 px tall) flickers or drops out. Create the texture with mipmaps: true and sample it with a mip filter:
# A linear-space detail atlas (height, AO, redness, ink) decoded in Crystal.
image = G::Image.new(2048, 2048, rgba_bytes, color_space: :linear)
atlas = G::Texture.new(image, mipmaps: true) # or Texture.load(source, decoder, mipmaps: true)
trilinear = G::Sampler3D.trilinear(anisotropy: 8) # min/mag/mip linear, clamped to the device maximum
material = G::Material3D.new(texture: atlas, sampler: trilinear, program: character_shading)
# Physical data maps take the same sampler: G::MaterialMap3D.new(atlas, trilinear)
- Generation. Renderers allocate
Graphics.mip_levels(w, h)=floor(log2(max(w, h))) + 1levels and fill them on upload: OpenGL withglGenerateMipmap, Metal with a blit encoder'sgenerateMipmapsForTexture, Vulkan with avkCmdBlitImagechain, or on the CPU (Graphics::MipChain) when the device cannot linearly blit RGBA8. Linear images are averaged as stored. sRGB images use sRGB formats, so every backend averages them in linear light; a black/white sRGB checker minifies to the same grey as its linear-space equivalent, not a darker one. - Memory. The chain adds about a third.
TextureResource#gpu_bytesand the resident cache budget (cached_resource_bytes) count it;releaseandcollectfree it with the texture. - Sampling.
Sampler3D.new(min:, mag:, mip:, anisotropy:, lod_bias:, min_lod:, max_lod:)orSampler3D.trilinear(wrap_u, wrap_v, anisotropy:).filter(the first argument) still setsminandmagtogether.mip: :none(the default) samples only the full-size level, so existing materials draw as before even on mipmapped textures. A mip filter on a texture without mipmaps samples its full-size level, without error.anisotropy(1..16) is clamped torenderer.max_anisotropy: OpenGL 4.6 orGL_EXT/ARB_texture_filter_anisotropic, Metal 16, VulkanmaxSamplerAnisotropywhen thesamplerAnisotropyfeature exists (1 otherwise). OpenGL ES ignoreslod_bias, and Metal applies it on macOS/iOS 26 and newer. - 2D.
Sampler.new(:linear, mip: :linear, anisotropy: 4)orSampler.trilineardoes the same for sprites andMaterials drawing a mipmapped texture. Image patterns always sample the full-size level.
Depth-tested scenes
Mesh3D carries indexed XYZ triangles, optional UVs and optional normals. Material3D defines linear tint, an optional texture/atlas region, sampling and wrap, culling and opaque/cutout/blended alpha. Frame3D adds the target, view-projection, environment and optional light shadow maps.
Render a 3D color frame to RenderTarget.new(width, height, format: ColorFormat::RGBA16F) to preserve values above one through opaque and translucent draws. Use ToneMap.new(exposure: gain).drawing(hdr_texture, overlay: hud) to produce a regular RGBA8 drawing for presentation and readback. The tone mapper uses a Reinhard curve in linear space. The HUD is composited at display brightness. Keep silhouette passes on RGBA8 frames.
Light3D.spot(position, direction, range, inner:, outer:) adds a local cone light on GL/GLES, Metal and Vulkan. Use radians for the inner and outer half angles and point the direction outward from the light. Spot, point and directional lights share the view's eight-light budget. OpenGL/GLES, Metal and Vulkan consume the same frame and return an ordinary GPU-resident Texture. The coordinate convention is right-handed with −Z forward, Y up and clip depth 0..w. UV origin is top-left.
Opaque and cutout draws write depth. Blended draws test depth and composite premultiplied output in submission order. The scene extractor orders blended draws back-to-front by their centers. Backends instance adjacent opaque draws with the same streams and material in groups of up to 32. Skinning uses four influences per vertex and a palette of up to 128 joints per draw.
Environment3D supports ambient, directional, point and spot lights with distance and ground fog layers. Distance fog can scatter sunlight (Fog3D's scatter, anisotropy and toward): the air between the eye and what it sees picks up the first directional light's colour, most when looking toward the sun, so haze brightens round the sun as real haze does. Shadow3D supplies independently culled casters so geometry outside the main camera crop can contribute. Supply up to four BoundShadow3D values to bind projector and six-face point maps to individual light indices. A single shadow can also use the original shadow: entry point. Set filtered: true on Shadow3D.new or the scene's ShadowView3D to soften directional edges using a 3 × 3 percentage-closer filter. Hard shadows use one depth comparison per sample.
Set Environment3D#specular_environment to a SpecularEnvironment3D constructed from an equirectangular texture. Use +X as the longitude seam and +Y as the north pole. The estimated reflection broadens with material roughness and combines with the diffuse probe and direct lights.
Use renderer.prepare(mesh) to populate the immutable GPU geometry cache before an asset's first draw. Mesh3D#upload_bytes reports stream bytes for the asset pump's frame budget.
TextureRegion#grid(frame_width, frame_height, columns:, rows:, margin:, spacing:, count:) slices a sprite sheet (or an atlas region) into frames in row-major order. SpriteAtlas#frames(prefix) returns the regions whose names start with prefix in natural order (run_2 before run_10), and SpriteAtlas#has?(name) tests for a region.
SpriteAtlas.pack turns named RGBA8 images into a shared texture with padded regions. TileMap.from_json (or TileMap.load(source, palette) for a content source) reads finite row-major layers with width, height, tile_width, tile_height and layers fields. Game code supplies a palette mapping integer IDs to regions and collision flags. Zero denotes an empty tile. Extract a subset of rows and columns for drawing, or use solid_bounds for merged solid rectangles (solid_rects returns them as Garnet::Math::Rect values, top-left origin, Y down).
Set highlighted: true on an opaque or cutout draw and supply Outline3D on the frame to draw a soft screen-space outline around the visible silhouette. The mask pass uses scene depth and the regular texture cutoff. The outer ring uses the same separable blur and composition primitives as 2D drawing.
For cel-shaded ink, line weights are set in screen pixels, so a line keeps its weight at any distance:
Material3D.new(outline_pixels: 2)draws a mesh as an outline shell. The vertex stage pushes each vertex out across the screen along its projected normal by that many render-target pixels. Build the shell as an inverted hull: the surface's positions, reversed winding, normals averaged over coincident vertices anddouble_sided: false. Each object-space normal's length scales that vertex's width, which allows per-vertex line weight such as thinner lines across a face.outline_distance:keeps the width up to that view distance and thins it beyond, like a world-space line.Frame3D#edges = Edges3D.new(...)adds inner lines from the depth of the frame's opaque draws: contours where a nearer surface overlaps a farther one (drawn on the far side) and creases where a surface folds more sharply thancrease_angle. Contours and creases have their own pixel widths. The renderer draws these lines before outline shells and blended draws.Frame3D#outline_scalemultiplies both kinds of width, so one set of materials looks the same at any render resolution or pixel density.
Custom fragment programs
A custom Fragment3D replaces a material's fragment stage and keeps its vertex stage, alpha/depth state and textures. Write it once in Slang: every renderer (OpenGL, OpenGL ES, Metal and Vulkan) runs the same program. All fragments that blend must return premultiplied linear RGBA.
// shaders/glow.slang
import garnet.lighting;
struct GlowParameters {
[Color] [Label("Glow colour")] float3 color;
[Range(0, 4)] float strength;
};
[[vk::binding(9, 0)]] ConstantBuffer<GlowParameters> parameters;
[shader("fragment")]
float4 glowFragment(Varyings input) : SV_Target {
float3 rgb = garnetFog(parameters.color * parameters.strength, input.worldPosition);
return float4(rgb, 1.0);
}
List the program in the directory's shaders.json and run garnet shaders build shaders (see the shader compiler). That writes every backend's code and a Crystal module with the entry point and a typed parameter struct:
GLOW = Graphics::Fragment3D.new(Shaders::Glow::GLOW_FRAGMENT, Shaders::Glow::GlowParameters)
parameters = Shaders::Glow::GlowParameters.new
parameters.color = StaticArray[1_f32, 0.6_f32, 0.2_f32]
parameters.strength = 2_f32
material = Graphics::Material3D.new(program: GLOW, parameters: Graphics::ShaderParameters.new(parameters))
-
import garnet.mesh3dgives the per-drawDraw3Dblock (draw.tint,draw.material,draw.environment, ...), the textures (base,normalMap,shadowImage,sceneDepthImage, ...) and the varyings (input.worldPosition,worldNormal,texcoord,vertexColor, thepositionin window coordinates). See shaders/garnet/mesh3d.slang for the bindings. -
import garnet.lightingadds the scene helpers:garnetLightCount(),garnetLight(i, worldPosition, out direction, out radiance)andgarnetDirectional(i)for the lightsgarnetAmbient()andgarnetEyePosition()garnetShadowVisibility(worldPosition)and the softgarnetShadowPCSS(worldPosition, normal, sunDirection, input.position.xy)garnetFog(rgb, worldPosition)andgarnetFogColor(view)for distance and ground foggarnetSoftFade,garnetSceneDepthandgarnetSceneDepthDistancefor materials that read the opaque scene depth (reads_scene_depth: true)garnetTime(),garnetWind()andgarnetInteractor()fromEnvironment3DgarnetBaseUV(input.texcoord), the base texture coordinate with the material's texture region applied
With these, a program can implement its own lighting model, such as banded cel shading, without depending on the renderer's internals.
-
The screen-space derivative
ddyUppoints toward the top of the image on every backend, and textures a renderer stores bottom-up are flagged indraw.optionsanddraw.mapFlags(usegarnetBaseUV,orientedUVandshadowAtlasUV), so derivative-based normals and texture lookups agree across backends. -
A
Mesh3Dmay carry optional per-vertex linear RGBAcolors. The built-in shading multiplies them into the material tint and alpha, so one mesh and one material can hold many colours and draw in a single call. Custom programs read them asinput.vertexColor. -
The parameter struct's
[Label],[Range],[Color]and[Toggle]attributes reachFragment3D#parameter_fields.SceneData::ShaderMaterials.registerturns them into an inspector schema, so the parameters are edited and saved like any component's. -
To use a backend-specific feature, pass hand-written code for one backend:
Fragment3D.new(entry, metal: source)(alsometal_ios:,glsl:,essl:). Start from the generated file and keep its interface: entry point name, varyings, bindings and blocks.
Built-in shader programs
The built-in 3D mesh program (shaders/mesh3d.slang) and the Materials3D programs (stylized_lit.slang, lit_sprite.slang, terrain_splat.slang, stylized_water.slang, foliage_wind.slang, fire_particle.slang, light_shaft.slang) are written in Slang on the modules in shaders/garnet. garnet shaders build graphics/shaders compiles them for Vulkan (SPIR-V), Metal (macOS and iOS) and OpenGL/GLES (GLSL 330, ESSL 300) into shaders/generated, and regenerates the modules in src/garnet-graphics/shaders. Graphics::Shaders::Mesh3D::Draw3D is the typed std140 packer for the per-draw block, which Mesh3DUniforms fills for every renderer. The outputs are committed, so building Garnet needs no shader compiler. Run the command after editing a .slang file, and garnet shaders build graphics/shaders --check to confirm the committed outputs are current. See the shader compiler for the translation rules and checks.
Use Surface3D to render a 2D drawing onto a mesh and View3DOp to place a 3D frame in a drawing. Both can nest with existing composition operations.
Physically based direct lighting
Pass Material3D.new(physical: PhysicalMaterial3D.new(metallic: 0.3_f32, roughness: 0.4_f32)) to use metallic/roughness lighting. Metal, OpenGL, OpenGL ES and Vulkan share the GGX specular model. Base color comes from the material texture and tint. Emission adds linear light to the material surface before fog. The view uses direct directional and point lights and a diffuse ambient term. Materials without the physical parameters keep the existing diffuse lighting model. Custom fragment programs continue to use their existing parameter bindings.
PhysicalMaterial3D accepts a normal map, a combined metallic/roughness map, an occlusion map, and an emissive map. A MaterialMap3D supplies a texture and its own sampler. Maps sample the mesh's primary UVs. The data maps use linear channels. Roughness is green, metallic is blue, and occlusion is red. Normal maps use tangent-space RGB with a configurable XY scale. Emissive maps multiply the emissive color.
DiffuseProbe3D.from_equirectangular(image) builds an ambient cube from an environment image. Assign it through Environment3D.new(diffuse_probe: probe). The probe illuminates the diffuse lobe of physical materials, using the same surface normals and ambient occlusion as the direct-light material. The image's top is +Y and its longitude seam starts at +X.
graphics
- 0
- 0
- 0
- 10
- 4
- about 13 hours ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:08:53 GMT