content
Garnet Content
Reusable byte sources using Crystal IO. No graphics, audio, decoder or native dependency.
require "garnet-content"
source = Garnet::Content::FileSource.new("asset.bin")
source.open do |io|
# Independent reader at byte offset zero, closed on leaving this block.
end
reader = source.open
begin
# Caller owns closing a reader returned without a block.
ensure
reader.close
end
Implement Source#open : IO to supply custom storage. Each open must reproduce the same content revision or fail, with its own cursor and lifetime. A decoder may require seekable IO or support sequential readers; not every Crystal IO can seek. Playback time seeking belongs to the decoder/player, not the byte source.
MemorySource.new(bytes) copies once and opens independent read-only readers over the retained immutable storage. Readers expose no backing slice. FileSource stores an absolute path and SHA-256 revision. Construction hashes using a bounded buffer; opening validates that revision on the opened file and rewinds it. Cached native content does not reopen the source. Reload publishes a new FileSource/resource descriptor. Missing files or changed revisions fail explicitly on the next load, not by silently changing an old resource's contents.
Published files must not be modified in place while a reader is active. Publish replacements atomically (or use immutable versioned files); a path/hash is not an OS snapshot or protection against a writer changing bytes during a read. Current file opening intentionally spends an extra sequential read verifying the revision. It does not keep whole-file bytes in memory.
Source implementations may be read concurrently if their storage is immutable. Open IO instances are mutable cursor state owned by one consumer. The block overload always closes, including when decoding raises. Memory retention is a property of the chosen source, not a requirement of all resources.
Packaged assets
A version 1 manifest maps game-defined IDs to package-relative paths. Entries can declare dependencies and their expected SHA-256. The manifest validates dependency references and cycles, and resolves each dependency once.
{"version":1,"assets":[{"id":"level","path":"levels/one.json","dependencies":["tiles"]},{"id":"tiles","path":"art/tiles.png"}]}
Generate a release manifest before bundling the asset directory. The command reads the source manifest and writes the manifest with SHA-256 digests to stdout.
crystal run content/tools/digest_manifest.cr -- assets assets.source.json > manifest.json
manifest = File.open("manifest.json") { |io| Garnet::Content::Manifest.from_json(io) }
loader = Garnet::Content::Loader.new(manifest, "assets", capacity: 16)
request = loader.request(["level"]) do |sources|
sources["level"].open { |io| JSON.parse(io) }
end
During a frame, check request.state and call value when it is ready. Use wait for blocking startup or tooling. Publish ECS data and upload GPU resources on their respective owners. Failures are available through value and wait.
Decode blocks never run on the calling thread, not even inside wait. They run on Garnet::Jobs.shared (or the jobs: pool passed to Loader.new) when it has workers, which needs -Dpreview_mt -Dexecution_context, and otherwise on the loader's own garnet-assets thread. try_request returns nil when capacity requests are outstanding or the job queue is full.
request.close (formerly cancel, now a deprecated alias) cancels a pending request and drops its result. A decode that has not started is skipped, and one still resolving its sources stops before the decode block runs. Close the loader on its creating thread at shutdown; close cancels outstanding requests and waits for decodes that are already running.
Content failures raise Garnet::Content::Error (a Garnet::Error) or a subclass: ClosedError for a closed loader, resident set or lease, ChangedSource, ReimportError and AssetError. The byte-level IO readers still raise IO::Error, and every closable type answers closed?.
Resident assets
Use ResidentSet(T) when several scenes share an asset ID. Its worker returns a Staged(T) with an upload byte estimate and a block to run on the owner thread. acquire(id) returns an AssetLease(T). Call pump once per frame before publishing dependent game state. A pump enforces upload_budget and upload_count. resident_limit bounds the estimated cost of leased assets. Allow room for both scenes when preparing a replacement.
Pending acquisitions wait for an available worker slot when the loader is full.
Read the result from a ready lease and close the lease when its consumer is done. Acquisitions of the same ID share the request and result. Releasing the last lease cancels a pending request or calls the optional retirement block. Release scene leases before closing the resident set and its loader.
Reimporting assets
Publish replacement files with atomic renames or immutable versioned paths, then call resources.reimport("tiles") on the resident set's owner thread. For a manifest with digests or changed paths or dependencies, pass the complete replacement manifest as resources.reimport("tiles", manifest: revised). The resident set reloads affected leased assets, including assets whose dependencies changed.
Call pump before updating the scene and extracting the next frame. The worker resolves and decodes the replacement. Uploads use the same frame budget as initial acquisitions, and the resident byte limit must accommodate both revisions during staging. Existing leases return the previous values during staging, then see all replacement values in the same pump. Read lease.value when building the next frame or refreshing a retained component. A previously read value still represents its original revision.
The returned Reimport reports Pending, Ready, Failed, or Canceled. On Failed, error identifies the asset ID and cause. The published manifest and values from ready leases stay live. A newer accepted reimport supersedes pending work. Releasing the last lease for an affected asset during staging also cancels the transaction. Affected assets with initial decode requests still outstanding must settle before reimport. Use the retirement block for superseded resident values and any staged uploads discarded during rollback. Defer native destruction until any in-flight GPU work using the value finishes.
Asset database
AssetDatabase tracks an editable project asset directory. Each tracked file has a sidecar named <file>.garnet.json beside it:
{"guid": "5d7c1b9e-2f0a-4c41-9d1e-6b3f8a2c4e10", "kind": "scene", "id": "example.gate_scene", "settings": {}}
The GUID is the asset's stable identity, separate from its editable path. It survives renames as long as the sidecar moves with the file; move renames both. kind selects an importer, the optional id is a readable logical ID, and settings are the per-asset import settings. Code and documents can refer to an asset by GUID, logical ID or path.
database = Garnet::Content::AssetDatabase.new("assets")
database.register(TextureImporter.new)
changes = database.scan # creates sidecars for new files of registered extensions
database.kind?("ui/button") # => "texture"
database.import("ui/button") # derived artifact, cached
database.dependents("ui/button") # assets and recorded owners that reference it
loader = Garnet::Content::Loader.new(database.manifest, database.root)
scan hashes new or changed files (same size and modification times are skipped), runs each importer's dependency hook and resolves the returned references (GUIDs, logical IDs, or paths relative to the asset) to GUIDs. It reports Added, Modified, Moved and Removed changes. track(path, kind, id:) starts tracking a file without a registered extension, and update(reference, settings:, id:) rewrites a sidecar. Directories starting with . are skipped.
Importers and the artifact cache
Subclass Importer and override kind, extensions, version, default_settings, import (defaults to copying the source), dependencies and thumbnail. Importer.loader(kind, extensions, Type) wraps any type with a Type.load(source : Content::Source) class method, validating each import with the loader; LoaderImporter(T).new(kind) { |source, settings| ... } wraps a block. importer.load(database.import(id)) decodes the artifact.
Default importers
Format shards register a process-wide default importer when required, using Importer.register(importer). Importer.defaults lists them, Importer.default?(kind) looks one up, and a later registration for a kind replaces the earlier one (Importer.unregister(kind) removes it). An AssetDatabase never uses them implicitly: AssetDatabase.new starts empty and database.register_defaults adopts each default whose kind is not yet registered. Register custom importers first; scan gives a shared extension to the earliest registered importer.
| Shard | Kind | Extensions | Loader |
|---|---|---|---|
garnet-graphics-stb |
texture |
.png .jpg .jpeg .bmp .tga .gif .psd .pnm .ppm .pgm |
Graphics::Texture.load(source) |
garnet-audio |
sound |
.wav .flac .mp3 |
Audio::Sound.load(source) |
garnet-text-harfbuzz |
font |
.ttf .otf .ttc .otc |
Text::HarfBuzzFont.load(source) |
garnet-svg |
svg |
.svg |
SVG::Document.load(source) |
garnet-lottie |
lottie |
none (use track) |
Lottie::Document.load(source) |
garnet-model-gltf |
model |
.glb |
GLTF.load(source) |
require "garnet-svg"
require "garnet-graphics-stb"
database = Garnet::Content::AssetDatabase.new("assets")
database.register(MyLevelImporter.new)
database.register_defaults
database.scan
icon = database.importer?("svg").as(Garnet::Content::LoaderImporter(Garnet::SVG::Document))
.load(database.import("ui/icon"))
Loaders that need more than a source (Spine atlases and page textures, Effekseer textures, tile map palettes) have load overloads but no default importer; wrap them with LoaderImporter(T).new(kind) { |source, settings| ... }.
ArtifactCache stores derived artifacts under <root>/.garnet/artifacts, keyed by the SHA-256 of the importer kind and version, the source's FileSource revision and the canonical settings JSON. Changing any of them reimports; an existing key is reused. thumbnail(reference) caches the importer's thumbnail bytes the same way. manifest(artifacts: true) imports every asset and returns a manifest relative to the cache directory.
Manifest entries now record an optional kind and guid, which Manifest#ids(kind) and Manifest#[]? expose. Version 1 manifests without them still load.
Reverse index
dependencies(reference) and dependents(reference) answer both directions. record_references(owner, ids) adds references from outside the database, such as an open scene document's SceneData::Registry#asset_references.
Watching for changes
Watcher.new(database, interval) rescans at most once per interval when poll is called on the owner thread. On changes it builds one replacement manifest and calls ResidentSet#reimport on each subscribed set, so changed assets and their leased dependents publish together. on_change reports the changes to tools.
watcher = Garnet::Content::Watcher.new(database)
watcher.subscribe(textures) # loaded with database.manifest and database.root
loop do
watcher.poll
textures.pump
end
content
- 0
- 0
- 0
- 6
- 1
- 1 day ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:08:49 GMT