engine

Garnet modular game engine

garnet-engine

The shared runtime advances a Garnet::World from the host clock. Compose it with the renderer, input, physics and audio shards your game uses.

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      garnet-engine:
        github: garnet-engine/garnet-engine
    
  2. Run shards install

Usage

A game's entry point constructs a world, adds plugins and runs it:

require "garnet-engine/desktop"
include Garnet::Prelude

world = World.new
world.add_plugin(App::Desktop.new(title: "Hello", width: 960, height: 540))
world.add_plugin(MyGame.new)
world.run

See examples/hello for a complete sprite moved by the default :move action in about 30 lines, its iOS entry point, and the headless spec that drives it with scripted input.

  • require "garnet-engine" loads the portable core: ECS, runtime, input, scene, the app core (App::Rendering, App::Viewport, App::Capture, App::Screenshot), scene activation, navigation and Garnet::Prelude. It loads no window system or GPU backend.
  • require "garnet-engine/desktop" adds App::Desktop (GLFW + OpenGL by default; Vulkan and AppKit Metal behind -Dgarnet_vulkan / -Dgarnet_metal).
  • require "garnet-engine/ios" adds App::IOS over the shared UIKit host.

Prelude

include Garnet::Prelude (in your game namespace or class, or at the top of an entry file) gives short, documented names (World, Entity, Mut, Plugin, Key, Actions, Player, Sprite, Transform, Screen, RenderQueue, Color, Vec2, Vec3, Quaternion, Rect, Mat4, FileSource, ...) plus module aliases (Input, Graphics, Scene, Content, App, and Audio, UI, Layout, Physics when those shards are required). Use it instead of per-file alias lists.

include Garnet::Prelude

speed = 120
velocity = world.resource(Actions).vec2(:move) * speed # a Vec2, no _f32
tint = Color.hex("#ff8800")                                  # sRGB -> linear
hero << Transform.new(Vec2.new(40, 12))

Desktop app plugin

App::Desktop.new(title:, width:, height:, backend:, visible:, vsync:, render_scale:, render_scale_base:, virtual_size:, integer_scaling:, clear_color:, max_frame:, pause_when_unfocused:, gc_policy:, pipelined:, min_size:, window_mode:, display_settings:) installs Input::Plugin, App::Rendering, Scene::Screen, Scene::RenderQueue, App::Viewport, App::Window, FramePolicy and a driver. world.run opens the window, then each iteration:

  1. polls events into Input::Devices (window points mapped to logical units, including letterboxing) and snapshots gamepads;
  2. turns focus and minimising into Resume/Suspend and SurfaceAvailable/SurfaceLost through Runtime (Lifecycle subscribers hear them immediately), clamping each delta to max_frame;
  3. updates Viewport and Scene::Screen and advances one frame.

Closing the window or world.exit stops the loop. Teardown closes the world first (plugins release GPU objects while the renderer lives), then the renderer, input callbacks and window. While running, the window (Platform::GLFWHost, Platform::VulkanGLFWHost or AppKit::MetalWindow), the concrete renderer and the App::Presenter are resources for custom passes.

render_scale sizes the render target relative to the framebuffer, or to window points with render_scale_base: :points (1.0 then renders one pixel per point on a Retina display); viewport.render_scale = 0.75 changes it at runtime. virtual_size: {320, 180} fixes the logical resolution and letterboxes it (integer_scaling: true for pixel art); pointer input is mapped into the same space. viewport.virtual_size = {480, 270} or = nil switches at runtime, for example letterboxed menus over full-window play.

The App::Window resource holds the window mode (windowed, full screen, borderless), windowed size, vsync, minimum size, monitor and full-screen video mode; changes apply before the next frame. With a Garnet::Settings resource (Garnet::Storage), the window follows Settings#display from startup and on every change, so a settings menu only edits the settings (display_settings: false opts out). Vsync applies to OpenGL and Metal.

Set Input::Devices#pointer_lock = true for mouse look: the cursor is hidden and held in the window while it has focus, and Mouse#delta keeps reporting relative movement. A running App::Capture never pauses for lost focus, whatever the plugin order.

Rendering

Plugins submit drawings in logical coordinates to Scene::RenderQueue during PrepareRender (UI at RenderQueue::UI). App::Rendering's render.frame system then, in Render:

  • builds an immutable App::Frame (clear color, logical-to-pixel scale, letterbox bars) with App::FrameBuilder on the world thread, the only step that reads world state, and clears the queue;
  • hands the frame to the App::Presenter resource, which renders, presents and collects using only the frame and the renderer it owns.

Render pipelining. App::Desktop.new(pipelined: true) (and App::IOS.new(pipelined: true)) submits on a dedicated render thread: the presenter resource becomes an App::PipelinedPresenter whose depth-1 Garnet::Pipeline owns the real presenter, created on that thread so the Metal or Vulkan renderer's owner checks bind there. The World simulates frame N+1 while frame N is encoded and presented, and waits only when the GPU falls a frame behind. Build with -Dpreview_mt -Dexecution_context; without them the pipeline runs inline. Details:

  • OpenGL raises: its context stays on the main thread.
  • GLFW polling and AppKit window calls stay on the main thread; frames carry the framebuffer size. iOS drawables are retained and travel with their frame.
  • Present waits (AppKit's native present with waitUntilCompleted, Vulkan's queue idle wait) run inside GC_do_blocking, so a collection on the World thread doesn't suspend a render thread parked on the GPU. The render thread runs at the main thread's QoS.
  • Capture readback runs on the render thread after the frames before it.
  • While pipelined the concrete renderer is not a world resource; use the App::Presenter resource. Teardown closes the world, then drains the pipeline and closes the renderer on its thread, then the window.
  • Measured on hello: frames are byte-identical with and without pipelining; frame time is on par, because these frames are dominated by render-thread work (see docs/threading.md).

Releasing GPU memory. App::OwnedGPU.new(texture) (or meshes:) on an entity releases those resources' GPU copies when the entity is destroyed or the component removed, through Presenter#release and the renderer's release list (freed after the frames in flight are done), instead of waiting for the garbage collector. Only list resources no other live entity draws.

GC policy. gc_policy: Garnet::GCPolicy.new installs Boehm frame-boundary collection (see ecs/README.md); on iOS a memory warning then also requests an unmapping collection.

Thread affinity without pipelining: the OpenGL context is bound to the thread that opened the window, and on macOS GLFW and AppKit event polling and presentation stay on the main thread.

Without a presenter (headless worlds), frames are still built and kept in App::Rendering#last_frame for tests.

Capture and smoke runs

App::Capture replaces per-example smoke branches and PPM writers: frame limit, one fixed step per frame, sRGB-correct PNG screenshots, H.264 + AAC .mp4 video capture with frame-locked audio, scripted input via Input::Tape, and on_finish { |world| ... } checks that may raise. App::Desktop installs it from the environment:

GARNET_CAPTURE_FRAMES=120 GARNET_CAPTURE_DIR=/tmp/shots GARNET_CAPTURE_SHOTS=1,120 \
GARNET_CAPTURE_TAPE=script.json ./game

# Pure-Crystal headless MP4 capture with synchronized audio (zero external tools):
GARNET_CAPTURE_FRAMES=300 GARNET_CAPTURE_VIDEO=/tmp/run.mp4 \
GARNET_CAPTURE_FPS=30 GARNET_CAPTURE_VIDEO_SCALE=1280 \
GARNET_CAPTURE_TAPE=script.json ./game

Shots can be named (App::Capture.new(named: {"title" => 1}), or GARNET_CAPTURE_SHOTS=1,title=40) to write title.png, and any system can take one on demand with world.plugin?(App::Capture).try &.shoot("boss-roar"). GARNET_CAPTURE_VIDEO=path.mp4 encodes H.264 Baseline (yuv420p, avc1) and AAC-LC audio into a +faststart MP4 directly in pure Crystal via Kino (kino-h264, kino-aac, kino-mp4) with zero external binaries. Whenever Audio::Plugin is installed, audio mixes deterministically on the world thread (GARNET_CAPTURE_VIDEO_AUDIO=0 omits audio; GARNET_CAPTURE_FPS controls output framerate while keeping full audio sync; GARNET_CAPTURE_VIDEO_SCALE accepts WIDTH, WIDTHxHEIGHT, or HEIGHTp; GARNET_CAPTURE_VIDEO_REGION crops a viewport sub-rectangle x,y,w,h; GARNET_CAPTURE_VIDEO_CRF sets quality 0..51; GARNET_CAPTURE_VIDEO_FRAGMENTED=1 writes fragmented MP4). App::VideoRecorder.new(io, fragmented: true) streams continuous fragmented MP4 directly to any Crystal IO, and App::VideoCamera attaches a recorder or live stream to any Camera2D or Camera3D entity at any resolution. GARNET_CAPTURE_RECORD=path saves the input of a session as a tape, GARNET_CAPTURE_REALTIME=1 keeps the wall clock and GARNET_CAPTURE_VISIBLE=1 shows the window. App::Screenshot.write(image, path) writes a fast PNG (zlib level 1 by default, Screenshot.png_level), QOI or PPM, picked by the extension, from any renderer readback. QOI writes a 1920×1200 frame in about 16 ms against 81 ms for PNG, for bulk captures.

iOS

App::IOS runs a world on the shared UIKit host in native/ios/host.m; a game needs no Objective-C. The host forwards lifecycle and audio-session interruptions (HostEvent through Lifecycle, so Audio::Plugin follows them), touches in points (mapped to logical units), full standard gamepads through GameController, and optional gravity (App::IOS.new(motion: true), CoreMotion loaded on demand) into Devices#motion. All callbacks run on the main thread, which also owns the world and Metal submission. Link the Crystal object with host.m and UIKit, QuartzCore, Metal, GameController and AVFAudio. The legacy Garnet::IOS.run callbacks remain available.

Android

App::Android (require "garnet-engine/android") runs a world in a NativeActivity. DefaultPlugins adds it when that file is loaded, so an Android entry looks like the desktop one:

require "garnet-engine/android"
require "./game"

world = Garnet::World.new
world.add_plugins(Garnet::DefaultPlugins.new)
world.add_plugin(MyGame.new)
world.run

garnet build --target android links the shared C host in native/android/host.c, so a game needs no Java or C. The host:

  • runs android_main on the NativeActivity glue's app thread. It copies the APK's game files to internal storage, exports that directory as GARNET_PROJECT, and calls Crystal's main on the same thread.
  • owns the event loop and a GLES 3 EGL context. The context survives a lost window, so GPU resources live as long as the activity.
  • forwards pause, resume, window loss and low memory as HostEvents.
  • forwards touches, mapped to logical units with the display density, and hardware keys (keyboards, the D-pad) as Input::Keys.
  • sends Crystal's standard output and error to logcat under the garnet tag.

All callbacks run on the app thread, which also owns the world and the GL context. Back finishes the activity unless the game handles it (App::Android.new(handle_back: true) delivers it as Escape). When the activity is destroyed the process exits, so every launch starts a fresh Crystal runtime. Garnet::Android exposes files_dir, display_scale, vsync=, sdk_version and finish.

Legacy loop

Garnet::OpenGL::Loop and Garnet::OpenGL::Systems::Render/Input in garnet-renderer-gl are deprecated in favour of App::Desktop and App::Rendering, and are no longer loaded by require "garnet-engine".

Runtime without the app plugins

For a headless or custom host, install the garnet-runtime shard and require garnet-runtime. Desktop applications can continue to require garnet-engine/runtime with the engine dependency. Forward Resume, Suspend, SurfaceAvailable, SurfaceLost and Close with Runtime#handle on the world owner thread. Runtime#frame advances the world's existing schedule while the host is active. The first frame after activation has zero elapsed time, and later deltas are bounded by max_frame. Supply on_event to route memory and audio notifications to the services your game owns.

For the GLFW OpenGL host, require garnet-engine/glfw_runtime, poll the host, and call runtime.frame(host). It reports false if simulation is paused or the window is closing. An unfocused window can keep running with pause_when_unfocused: false.

Pass a Garnet::Diagnostics instance to record frame timings. Use measure and count to instrument stages or game systems. samples returns a bounded history, and write_trace(io) exports it with counters in trace-event JSON.

Use SceneActivation(T) with a Content::ResidentSet(T) to replace a scene at a World boundary. Call request(ids) with a block that receives the ready assets and builds a detached Entity subtree. Use the helper on the shared World and renderer owner thread, and call poll after pumping the resident set. A failure is exposed via error while the current subtree and its leases remain active.

Games using authored scenes can add the garnet-scene-data shard and opt in with require "garnet-engine/authored_scene_activation". The adapter depends on SceneData and the engine activation helper. SceneData and Content remain independently usable. Register the logical IDs with Registry#asset and declare their kind with Field.asset on the typed binding. The inspector and the activation request then use the same schema.

After an edit succeeds, submit the committed JSON between World updates. For example, the navigation fixture attaches a ready grid to a detached room.

activation.request_scene(registry, document.to_json, "nav-grid") do |scene, grids|
  room = scene.root
  room << Walkable.new(grids[room[Setup].grid])
end

The registry expands reusable scenes, validates fields and constructs the detached configuration before the adapter requests any assets. An invalid document raises synchronously. The resident set loads the referenced IDs of the selected kind. Pump it and poll the activation as above. The block runs at publication time and should configure only the candidate. Activation owns the leases through replacement, cancellation or close. See the navigation fixture for both loading paths.

request_instance(registry, "room", "nav-grid", node: "level", overrides: [...]) activates a registered scene asset without writing a document. Pass snapshot: to either request to restore runtime state captured with SceneData::Registry#snapshot, for example after the game was rebuilt and relaunched. The state is written to the candidate before it is adopted.

garnet-engine/navigation provides a weighted four-connected Grid and a Y-up Mesh over authored walkable triangles. Grid queries return cells. Mesh queries locate triangles and return a corridor of triangle indices and their shared portal edges. Game code owns baking and agent steering.

Windows

garnet-engine/desktop runs on Windows with the OpenGL backend (and Vulkan with -Dgarnet_vulkan and the Vulkan SDK). Crystal links with MSVC there, so install Visual Studio 2022 Build Tools ("Desktop development with C++") and GLFW 3.4's prebuilt binaries (glfw-3.4.bin.WIN64.zip), adding its lib-vc2022 folder to CRYSTAL_LIBRARY_PATH (;-separated). opengl32.dll exports only OpenGL 1.1 on Windows; Platform::GLFWHost installs GLFW's glfwGetProcAddress as the GL.load resolver, so nothing else is needed.

garnet build writes <executable>.exe with glfw3.dll, the Crystal runtime DLLs and any other imported DLLs beside it (see the cli README). Machines without a GPU driver, such as CI runners, can run it on Mesa's llvmpipe by placing its opengl32.dll beside the executable; the engine's Windows CI job runs the specs that way.

Development

See the standalone release guide for packaging an independent game with a pinned SDK, bundled assets, and debug symbols.

Use Crystal 1.19.1 or later. Run from the workspace root. The same invocation accepts gl, gles, metal or vulkan to run backend composition fixtures on a configured host.

scripts/check-composition unit --release
scripts/check-composition metal --release

The project supports code using the shard entry points and the public methods documented in each shard's README. Prefer typed public values, handles, and explicit teardown. Native bridge symbols and built-in shader uniform layouts move with the matching renderer and archive from the same source revision. The packaged asset manifest carries a checked schema version so unsupported manifest versions fail during load.

Contributing

  1. Fork it (https://github.com/garnet-engine/garnet-engine/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

Relay example

Relay is a small playable composition of World scheduling, scene extraction, Box2D, animation, audio, and UI. Use the arrow keys to move the paddle and return the falling puck. Restart using the UI button or Tab and Enter.

scripts/check-composition example-relay
"${TMPDIR:-/tmp}/garnet-relay"

Run with GARNET_RELAY_SMOKE=1 for a scripted native run that presents 108 frames, verifies a return and completed voice, and restarts through the presented UI. The game also has a headless spec in the composition unit suite.

Lantern Quay

Lantern Quay is a playable 2.5D island with two settlements, furnished interiors, a forest road, and a beach cave. Animated sprites, NPC dialogue, and a short errand share a scene with normal-mapped materials, changing daylight and dusk, and custom water shaders. See the play and capture instructions.

Waystone Lab for iPhone

Waystone Lab is a 2.5D rendering playground. Drag horizontally to orbit the stone ruins, animated crystal, and pixel-art traveler. The character is a camera-facing cutout that shares the 3D terrain's depth buffer. The terrain, crystal and character shading are authored in Metal Shading Language.

Build the arm64 iPhone app from the workspace root on a Mac with Xcode, Crystal 1.19.1, CMake and the Boehm GC 8.2.12 source tree.

GARNET_IOS_GC_SOURCE=/path/to/bdwgc scripts/build-ios-example waystone_lab /tmp/waystone-ios

The build produces WaystoneLab.app for iOS 18 or later. Sign it with your development identity and provisioning profile before installing it on an iPhone. Launch with --smoke to exercise camera movement, read back the scene and confirm a drawable reached the display.

Reusable iOS host

Prefer App::IOS (above). For custom hosts, garnet-engine/ios_host and engine/native/ios/host.m provide the UIKit and Metal display loop. Pass lifecycle, frame, touch and controller callbacks. Callbacks execute on UIKit's main thread. Frame callbacks receive drawable pixels and borrowed Metal pointers. Touches use UIKit points. Use Garnet::IOS.display_scale to convert between them.

The host emits Garnet::HostEvent values. Adopt them in Runtime#handle and keep game-owned audio state across suspension. request_audio_activation requests session restoration asynchronously and dispatches AudioRestored when the session is ready. Controller callbacks carry connection state, an IOS::ControllerButtons mask and left-stick axes.

The host is full screen: it hides the status bar and home indicator and defers system edge gestures, so swipes near the edges reach the game. Garnet::IOS.safe_area returns the surface's safe-area insets in points (top, left, bottom, right) for placing HUD and buttons clear of the notch and rounded corners.

Device motion comes from CoreMotion. Call Garnet::IOS.start_motion once (it returns false without motion sensors, as in the Simulator); the host then samples the latest update once per frame, just before the frame callback. Garnet::IOS.motion returns that sample, or nil, with gravity, user acceleration, rotation rate and attitude in device coordinates plus the interface orientation. Turn it into a steering axis with Garnet::Input::Tilt, and raw touches into taps and swipe-and-hold with Garnet::Input::TouchGestures (see the garnet-input README). Link -framework CoreMotion.

Garnet::IOS.start_motion
tilt = Garnet::Input::Tilt.new(range: 0.45_f32, deadzone: 0.04_f32)
# In the frame callback:
if motion = Garnet::IOS.motion
  x, y, _ = motion.gravity
  orientation = Garnet::Input::ScreenOrientation.from_value?(motion.orientation) || Garnet::Input::ScreenOrientation::Unknown
  steer = tilt.value(x, y, orientation) # call tilt.calibrate(x, y, orientation) at run start
end

The optimized host probe exercises the shared runtime, Metal, a streamed voice and the UIKit UI bridge. Build its arm64 app and sign it for a paired iPhone.

GARNET_IOS_GC_SOURCE=/path/to/bdwgc \
GARNET_IOS_UI_LIBS=/path/to/prebuilt-ios-ui-libs \
  scripts/build-ios-example ios_host /tmp/garnet-ios-host

scripts/build-ios-ui-libs can build the archives using the selected FriBidi and libunibreak sources. The host probe targets iOS 18 or later.

Driving subsystems

Use the World schedule to poll input, step physics on fixed ticks, sync 2D or 3D positional audio after simulation, and prepare render snapshots. Runtime#frame advances that schedule from the host clock. World access stays on the simulation owner. Graphics submission stays on the renderer owner, including when a platform requires it to be the main thread. world.schedule.fixed_seconds gives the configured fixed step in seconds. Keep the registration returned by schedule.add to detach that system with close on the simulation owner. Closing twice is safe. A system closed during dispatch skips any remaining calls, even if the closing callback raises.

Audio devices consume queued PCM on their native callback threads.

The same subsystems can also run independently of Runtime and the World schedule. A custom loop can step the physics world directly, pass recorded drawings to a renderer, or submit PCM from Mixer#render to its own audio output.

Repository

engine

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 29
  • about 3 hours ago
  • November 30, 2026
License

MIT License

Links
Synced at

Thu, 03 Dec 2026 03:11:27 GMT

Languages