@ringozz/godot
v4.7.2-614
Published
Node-API bindings for Godot Engine — call Godot classes from JavaScript
Readme
@ringozz/godot
Node-API bindings for the Godot Engine — call Godot classes, value types, and utility functions from JavaScript.
This is the core runtime package. The React layer is a separate package (@ringozz/react-godot).
Installation
bun add @ringozz/godotThe package ships no engine binary itself — it auto-selects a platform addon from its optional dependencies on install: @ringozz/godot-macos-arm64, @ringozz/godot-windows-x86_64, or @ringozz/godot-web-wasm32 (the WASM build is installed everywhere and used on web). No project.godot is required — the engine boots from engine defaults with res:// = your working directory (if a project.godot is present at cwd, it is loaded and res:// still maps to cwd).
Usage
On desktop, the engine is already running when you import — getGodot() returns the instance synchronously. Pump frames with runGodot():
import { runGodot } from '@ringozz/godot';
import { Engine } from '@ringozz/godot/Engine';
import { SceneTree } from '@ringozz/godot/SceneTree';
const tree = Engine.getMainLoop() as SceneTree;
const root = tree.root;
const label = new Label();
label.text = 'hello from godot-node';
root.addChild(label);
const done = runGodot(); // pumps frames until abortedWeb
The wasm engine boots asynchronously, so on web the entry script must boot it before importing the app: @ringozz/godot/boot's preloadGodot() starts the engine, and @ringozz/godot/runtime then reads the booted module synchronously (the package's exports map routes ./boot to the web leaf in browser-targeted bundles). This keeps the shared module graph top-level-await free, which is also what makes Bun's HMR dev server work. On desktop preloadGodot() is a no-op — the engine boots at import.
// your web entry (referenced by <script type="module"> in the HTML)
import { preloadGodot } from '@ringozz/godot/boot';
await preloadGodot();
await import('./app.ts'); // may now import @ringozz/godot / react-godot freely(That's exactly what dev/demo.html.ts does in this repo. A second <script type="module"> tag can't replace the dynamic import — Bun's fullstack HTML bundler merges all script entries into one chunk, so the browser's in-order script/TLA serialization never applies.)
What's exported where
| Specifier | Contents |
|---|---|
| @ringozz/godot | Value types (Vector3, Color, …), global enums, heap types, utility functions, global constants, runGodot(), RAF polyfills |
| @ringozz/godot/ClassName | Classes, one per module — e.g. @ringozz/godot/Label, @ringozz/godot/Node |
| @ringozz/godot/runtime | Low-level dispatch: _C, _S, _R, _G, _P, _V, toValueType, getGodot, GodotVar |
| @ringozz/godot/boot | Platform boot: getNativeModule(); web preloadGodot() (awaited before importing the app; no-op on desktop) |
| @ringozz/godot/load | Async resource loading: loadResourceAsync |
| @ringozz/godot/debug | initDebug(), dumpStr, snapshot, inspect, click, find, gc |
Class-scoped enums use bare names (import ProcessMode from @ringozz/godot/Node, not NodeProcessMode).
Value types
Godot's built-in value types (Vector3, Color, Transform3D, …) are named tuples — labeled array aliases, not classes. Import each type module as a namespace and call its math as functions; constructors are fromXxx factories:
import * as v3 from '@ringozz/godot/Vector3';
import * as basis from '@ringozz/godot/Basis';
import type { Vector3 } from '@ringozz/godot/Vector3';
const v: Vector3 = [1, 2, 3]; // flat tuple, labels in the type
const n = v3.normalized(v); // math API per type module
const b = basis.fromAxisAngle([0, 1, 0], 1.57);- Shapes: flat types are scalar-labeled (
Vector3 = [x: number, y: number, z: number],Color = [r, g, b, a?]); nested types are row-labeled tuples of the flat alias (Transform3D = [x, y, z, origin],AABB = [position, size]). Wrong-arity arrays fail typecheck;Color'sais the only optional element (alpha defaults 1). - Getters/setters/props all use the same tuple shapes —
node.position = [1, 2, 3]reads back[x, y, z]; JSX props in@ringozz/react-godotaccept them too. - A plain tuple stored in a Variant-typed slot (
setMeta, a directtweenPropertyfinal value) becomes a generic GodotArray— a tuple carries no type. Wrap it withtoValueType(node, 'prop', tuple)from@ringozz/godot/runtimeto store the typed value.
Async resource loading
The engine loads pre-baked native resources (.scn, .ctex, …) through ResourceLoader. On desktop these are real files (res:// = cwd); on web there is no filesystem, so the asset's bundled files — .import sidecars as text and imported products (.scn/.ctex) as emitted asset paths — are staged into Emscripten's in-memory MEMFS (transient, no IndexedDB, no persistent copy) by the generated asset modules, handing the fetched bytes straight to MEMFS via Godot's own copyToFS (FS.createDataFile with canOwn — zero copy, JS-heap only). On web, .ctex files are decoded first: the embedded PNG/WebP blobs go through the browser's createImageBitmap and the container is rebuilt as raw RGBA (DATA_FORMAT_IMAGE), so no image codec runs in wasm. The source file itself is never fetched.
import { loadResourceAsync } from '@ringozz/godot/load';
import { PackedScene } from '@ringozz/godot/PackedScene';
import { Texture2D } from '@ringozz/godot/Texture2D';
const scene = await loadResourceAsync('res://models/foo.gltf', PackedScene); // PackedScene
const node = scene.instantiate();
const tex = await loadResourceAsync('res://textures/icon.jpg', Texture2D); // Texture2DloadResourceAsync(path, cls, files?)— generic over the Godot class:cls.nameis theResourceLoadertype hint, and the return type isInstanceType<typeof cls>. Loads in the background (loadThreadedRequest+ status polling). Godot default arguments apply: the napi dispatch truncates trailingundefinedargs, soloadThreadedRequestuses its defaultCACHE_MODE_REUSEand the resource stays cached in the engine (scene re-references don't re-read the file). On web it only works for paths already staged into MEMFS (generated asset modules handle this). When the asset'sfilesmap is passed, the staged product files (.ctex/.scn/native sources) are deleted from MEMFS after the resource loads — only the.importsidecars are kept, since they route imported source paths to their products. The decoded texture bytes don't linger in the JS heap.loadAsset(path, cls, files, deps, data)— the generated asset modules' entry point (also usable directly): returns{ materialize, load }. It checks the engine'sResourceCachefirst (when the asset is already loaded,loadresolves to the cached instance and staging is skipped), stages the bundled files via Godot'scopyToFS(zero-copy handover of the fetched bytes; a no-op on desktop where the files already exist), loads vialoadResourceAsync, and memoizesloadondata(passimport.meta.hot.data) so HMR re-evaluations reuse the same fulfilled promise.
Asset imports are resolved by @ringozz/godot/preload (a Bun plugin, registered via bunfig.toml preload for bun run/bun test and via [serve.static] plugins for Bun.serve's fullstack HTML routes; the module's default export is the single plugin object) into a module per asset. Only JS imports are virtualized — HTML asset references (<link rel="icon">, <img src>) and CSS url() refs fall through to Bun's normal (content-hashed) asset handling, so favicons and other web assets co-exist with Godot imports:
import foo from './models/foo.gltf';
const scene = await foo; // PackedSceneEach asset module's default export is its load promise (const { materialize, load } = loadAsset(resPath, Class, files, deps, import.meta.hot.data) — the default is load, memoized on the module's HMR data), started eagerly at module import, and it also exports a materialize promise (its own files plus its deps' files). The files Godot reads are bundled into the module — .import sidecars and native text sources (tscn/tres/po/gd) are inlined as text, imported products (.scn/.ctex) are emitted as files — and the module imports its dependencies as generated modules too, waiting only for their materialize before loading itself (dep loads start at module evaluation and run concurrently). Text-based source assets (.gltf/.tscn/.tres/.obj/.gd) are scanned for references (res:// paths and relative paths ending in known asset extensions); referenced loadable assets become dep modules, native-text leaves are staged as raw text so the engine loads them by res:// on web, raw .mtl files (OBJ materials) are recursed into, and raw .bin buffers are import-time only. The modules are virtual (namespace godot), and every import of the same asset resolves to the same one (evaluated once) — so the promise is a stable singleton, read with await or React 19's use():
import foo from './models/foo.gltf';
import { Suspense, use } from 'react';
function Foo() {
const scene = use(foo); // suspends until the scene loads
return <FooView scene={scene} />;
}
<Suspense fallback={<Label text="Loading…" />}>
<Foo />
</Suspense>Each extension maps to its Godot class (source assets only — gltf/tscn/obj → PackedScene, gd → GDScript, jpg/jpeg/png/webp/svg → CompressedTexture2D, exr/hdr → TextureLayered, wav → AudioStreamWAV, ogg → AudioStreamOggVorbis, mp3 → AudioStreamMP3, ttf/otf → FontFile, tres → Resource, po → Translation), declared in src/assets.d.ts. Imported products (.scn/.ctex) are never imported directly. .gd scripts import as Promise<GDScript>, so import script from './x.gd'; const gd = await script; works like any other resource — and when a .tscn references the same .gd, Godot's ResourceLoader cache returns the same instance (parsed once).
Textures are shared only through Godot's ResourceLoader path cache. The glTF import pipeline may produce per-scene texture instances (same res:// path, separate objects), so don't assume two scenes referencing the same image share one texture object.
Debugging
import { initDebug } from '@ringozz/godot/debug';
initDebug();
// singletons + helpers now on globalThis.$: $.Engine, $.tree, $.dumpStr(node), $.snapshot([pattern]), $.inspect(path), $.click(path), $.find([pattern], [type]), $.paused, $.gc()dumpStr(obj)renders value types inline ((1.0, 2.0, 3.0), arrays, dictionaries) via Godot'sstr()and dumps objects via Godot'svar_to_str, with the node'snameprepended.snapshot(pattern?, node?)dumps the scene tree from the rootWindowasClass "name" (N children)lines; pass a string (case-insensitive substring) orRegExpto filter.$.snapshot()with no arg dumps the whole tree.inspect(path)resolves a node by absolute NodePath (/root/Box) or name/glob pattern (findChild) and returns itsdumpStr.click(path)synthesizes a left-click at the center of aControlviaWindow.pushInput(device-space coordinates), returning the node'sdumpStrornullif it isn't aControl.find(pattern?, type?)returns a JS array of nodes matching a name glob and/or class ($.find('*', 'RigidBody3D')lists all physics bodies).$.treeis the liveSceneTree;$.paused = truefreezes the scene tree for inspection;$.paused = falseresumes.
initDebug also registers an uncaughtException handler that keeps the process alive, polyfills DOMRect (not defined in Bun, needed by getBoundingClientRect()), and adds getBoundingClientRect() to CanvasItem/Node3D (Node3D covers descendant meshes; returns CSS-pixel coordinates).
Notes
- Memory: non-RefCounted objects (
Node,Node2D,Node3D, …) must callfree()explicitly. RefCounted objects are managed by Godot's ref counting; callingfree()clears the JS wrapper (decrements the ref). - Class-registration tree-shaking:
ClassDB.instantiate('X')requires the JS class to be value-imported (import { Label } from '@ringozz/godot/Label'). If a class is only type-used (e.g.as Labelcasts), bundlers may drop its registration side effect, and wrappers fall back to an ancestor class. Render through JSX is unaffected. Workaround: keep a value reference (void Label;).
Development
gen/ is generated (and gitignored) by dev/codegen.ts from godot --dump-extension-api-with-docs. From the repo root: bun run prebuild (codegen + typecheck), bun run predev (imports dev/assets/ via the editor), bun run build (native addon), bun run test, and bun run dev (web dev server). See AGENTS.md for the full workflow.
