Engine Internals
Engine dist packaging (npm) — source vs dist resolution
Section titled “Engine dist packaging (npm) — source vs dist resolution”Published @downdraft/* packages ship a per-file transpiled ESM dist/ alongside source. node scripts/build-dist.mjs (plain Node, ts.transpileModule) mirrors every source file into dist/, baking out Vite-isms: ?raw/.wgsl → inlined strings, ?url → import.meta.resolve, ?json → inline, relative .ts specifiers → .js, new URL("./x.ts", import.meta.url) worker refs → .js, import.meta.dir/.dirname/.filename → import.meta.url-derived locals. Output is incremental (.dd-manifest.json hashes) and stays native-importable — deep imports preserve 1:1 module identity, so Vite’s server-consumer env externalizes it entirely (near-zero runner transform cost).
Every export entry carries three conditions:
".": { "types": "./core/src/index.ts", "downdraft-source": "./core/src/index.ts", "default": "./dist/core/src/index.js" }draft dev(monorepo) defaults to engine=source: the CLI spawns the dev shell with--conditions=downdraft-source(Bun/Node flag;DENO_CONDITIONSenv for Deno) andDD_ENGINE_SOURCE=1; worker threads propagate the same condition viaexecArgv(seedom-polyfills.ts/worker-bootstrap.mjs). Full engine module graph → granular tiered HMR.draft dev --engine-distomits the condition → all@downdraft/*imports resolvedist/— faster cold start, but engine source edits require re-runningnode scripts/build-dist.mjsand engine HMR is coarse.vite-config.mjssetsresolve.conditionsfor thenativeenv fromDD_ENGINE_SOURCEand resolveswgslRegistryPathagainst whichever universe is active — keep the two in sync when touching it.
Rules for engine/platform-native code that resolves filesystem paths relative to itself (crate dirs, staged assets, package metadata): never hardcode ".." segment counts off import.meta.url/import.meta.dir — dist nests modules one level deeper than src and the math escapes into dist/. Anchor at the package root instead: findPackageRoot(dir) walks up to the nearest package.json (@downdraft/engine/platform/pkg-root for engine code; packageRoot/findPackageRoot exported from platform-native/src/ffi/lib-paths.ts), then append the package-relative path explicitly.
Publishing (scripts/publish-packages.mjs, publish.yml) runs the dist build before npm publish; files includes dist. Apps consume the published packages via bun install; to run one against unpublished engine changes, use bun link.
RenderSurface and overlay layering
Section titled “RenderSurface and overlay layering”On the native runtime there is no DOM or HTML document. The single render target is the RenderSurface contract (core/src/platform/render-surface.ts), implemented by NativeSurface (a wgpu-backed native window surface). UI overlays render into the same surface via offscreen wgpu textures (modules/native-osr) and are composited as final-present quads.
How it works
Section titled “How it works”AppModule.renderer: (surface: RenderSurface) => IRenderer— the surface is injected bybootstrapApp(); never querydocumentfor a canvas.ctx.surface/AppRenderer.getSurface()are the canonical accessors. There is no DOM compositor on native (hasDom()isfalse) — never querydocumentfor the render target.- App UI uses
modules/html-ui(Blitz — see the shared-APIs table above); there is no DOM-overlay mount hook. - Multiple render areas (minimap, picture-in-picture) are implemented as additional OSR surfaces or viewport regions, not stacked canvases.
Per-app storage isolation
Section titled “Per-app storage isolation”Each app MUST pass a unique appId (downdraft-<app>) so the native host resolves a per-app userData directory (e.g. ~/.config/downdraft-my-app/). Save files, SQLite import cache, debug artifacts, and the singleton lock all live under it — sharing one between apps would corrupt save state and collide on the lock.
When appId is set, createNativeHost() (via runNativeAppModule) also:
- Acquires a singleton lock (
<userData>/singleton.lock, PID-owned) — prevents two instances of the same app from running concurrently (which would corrupt storage). Skipped in deterministic/test mode (DOWNDRAFT_DETERMINISTIC=1): the test harness controls process lifecycle itself (dynamic MCP ports + process-group kills).DOWNDRAFT_MULTI_INSTANCE=1opts out of the lock in any mode. - Cleans up stale lock artifacts from a previous run that crashed or was killed. In non-deterministic mode this is safe because the single-instance lock guarantees no live process is using the directory; in deterministic mode the test harness guarantees no concurrent instance.
- Sets the window’s desktop identity —
appIdis forwarded intoNativeWindowConfig.appId, which becomes the Waylandapp_idand both X11WM_CLASSparts (viadd_window_set_app_namebefore window create). Without it every dev-run window maps with no identity and the WM groups all apps under one taskbar entry. The dev shell’s early boot (early-host.ts) appliesnative.appIdfromdowndraft.config.jsonthe same way — keep the config’sappIdin sync with the entry’s, since the identity is baked at window create and an adopted early window can’t be re-identified.
packages/platform-native/src/bridge/user-data-dir.ts—resolveNativeUserDataDir()(builds the per-app path).packages/platform-native/src/host-lifecycle.ts— singleton lock acquisition + stale-lock cleanup increateNativeHost().
Adding a new app
Section titled “Adding a new app”draft new <dir> --template <minimal|physics|full> --name <name> scaffolds an app project (a separate repo, per the layout above). Always set appId in the app’s src/native-entry.ts:
await runNativeAppModule(appModule, { appId: "downdraft-my-app", // → ~/.config/downdraft-my-app/ title: "My App",});Unified DevTools API
Section titled “Unified DevTools API”The DevTools system has a single registration surface (devtools singleton from @downdraft/engine/modules/debug) that auto-detects whether it’s running in the main realm or a worker realm and chooses the appropriate transport:
- Main realm: feeds/commands registered directly on
window.__downdraftDevtoolsviaDevToolsDataBridge. - Worker realm: data feeds written to a devtools SharedArrayBuffer (zero-copy, synchronous reads); commands forwarded via IPC RPC.
Architecture
Section titled “Architecture”devtoolssingleton (packages/engine/modules/debug/src/api.ts) — the unified API. Auto-detects realm. Modules importdevtoolsand callregisterDataFeed(),registerCommand(),registerSABStat(). Same code works in both realms.DevToolsSABLayout— dedicated SAB region for JSON-serialized data feed results + direct numeric stats. Worker writes viaflushDataFeeds()(called from sim loop); renderer reads synchronously. No IPC polling.exposeDevToolsApi()(packages/engine/modules/debug/src/worker-expose.ts) — wraps a worker’sexpose()API with__devtoolsGetManifest,__devtoolsCallCommand,__devtoolsGetSABRPC methods.syncWorkerManifests()(packages/engine/modules/debug/src/worker-sync.ts) — renderer-side: fetches manifest from workers, wires SAB data feed readers, wires command forwarders.createDevToolsRendererAdapter()(packages/engine/modules/debug/src/renderer-adapter.ts) — feature-detects renderer capabilities (gpuProfiler, telemetryCollector, gpuResourceTracker, gcController) and builds anIDevToolsDataRenderer.createSimStatsProvider()(packages/engine/modules/debug/src/sim-stats-provider.ts) — reusableISimStatsProviderfactory with 10Hz polling + pause/resume/step/speed/clear delegation. Eliminates duplicated boilerplate across sim apps.initDevTools()(packages/engine/modules/debug/src/init.ts) — one-line wiring per app. Creates bridge, wires providers, merges global feed/command registrations, syncs worker manifests, exposes onwindow.__downdraftDevtools.
Module integration
Section titled “Module integration”Both ModuleContext (sim) and RendererModuleContext (renderer) have a devtools property. Modules self-register during register():
// In a renderer moduleregister(ctx: RendererModuleContext) { ctx.devtools.registerDataFeed("getPhysicsStats", () => ({ bodyCount: ... }));}
// In a sim module (worker realm)register(ctx: ModuleContext) { ctx.devtools.registerDataFeed("getWildlifeStats", () => ({ count: ... })); ctx.devtools.registerCommand("cullWildlife", (max: number) => { ... });}The host injects the devtools singleton via ModuleHost.setDevToolsAPI() / RendererModuleHost.setDevToolsAPI(). If not set, a no-op stub is used (modules that call ctx.devtools.register*() silently no-op).
Deterministic mode
Section titled “Deterministic mode”DOWNDRAFT_DETERMINISTIC=1 exposes downdraft.deterministic on the bridge; bootstrap reads it for autosave/render-loop behavior. Devtools is unaffected by default — autoShow is already opt-in (default false) and F12 still toggles. Apps that want the dock fully off in tests can set devtools.ui: "none" or toggleKey: null when ctx.deterministic is true.
Unified Material System
Section titled “Unified Material System”The material system is unified around the shader graph as the single source of truth. The 8 hand-written material-types/*.wgsl files serve as fallbacks (loaded via Vite ?raw as inlineShaderSource). The graph compiler generates WGSL from MaterialGraph nodes; the Material class compiles the graph at construction time and caches the result in inlineShaderSource.
Architecture
Section titled “Architecture”MaterialDefinition(packages/engine/core/src/material/material.ts) — the material definition. Key fields:graph?: MaterialGraph(primary),inlineShaderSource?: string(compiled graph or fallback .wgsl),variantFlags?: MaterialVariantFlags,profile?: string.MaterialLibrary(packages/engine/core/src/material/library.ts) — creates and registers materials. The 8create*methods (Physical, Toon, Matcap, SSS, Sprite, Normal, Line, Depth) load their.wgslfallbacks via?rawimports. Graph preset methods (createPBRGraph,createGBufferGraph) buildMaterialGraphinstances.GraphCompiler(packages/engine/shader-graph/src/compiler.ts) — compiles aMaterialGraphto WGSL. Supports multi-render-target (GBuffer) profiles viaoutputFormats/outputNames, and variant-aware compilation viavariantFlagsinCompileOptions.MaterialVariantFlags(packages/engine/core/src/material/variants.ts) — hybrid variant strategy: compile-time permutations forshadowCaster/skinning/alphaMode/morph/instanced;fogstays a dynamic branch (NOT part of the variant key).variantKey()produces a deterministic string key;permutationCount()= 48.graph-bridge.ts(packages/engine/core/src/material/graph-bridge.ts) —compileGraphToMaterialVariantscompiles all variants for a material;compileVariantcompiles a single variant.OpaquePass(packages/engine/core/src/render/passes/opaque.ts) —setMaterial()sets a graph-compiled material;setMaterialVariant()compiles + caches a per-variant pipeline (bounded LRU, max 24).getProfileTargets()emits multi-targetGPUColorTargetState[]for GBuffer profiles.
Profiles
Section titled “Profiles”SIMPLE_PROFILE,PBR_PROFILE,PBR_TEXTURED_PROFILE,PBR_SKINNED_PROFILE,PBR_INSTANCED_PROFILE,PBR_COLOR_VERTEX_PROFILE— single-target.GBUFFER_PROFILE— multi-render-target deferred surface shader. 4 targets: albedo+AO, normal+roughness, metallic+emissive, velocity. Graph output nodes use names:"albedo","normal","metallicEmissive","velocity".
Material adapter (libraries/models)
Section titled “Material adapter (libraries/models)”materialDataToMaterial() (packages/engine/libraries/models/src/material-adapter.ts) bridges serialized MaterialData (glTF/obj format) to the core Material surface. Maps baseColor/metallic/roughness/emissive to uniforms, sets inlineShaderSource from the physical fallback .wgsl. materialDataArrayToMaterials() batch-converts. The app’s RendererAccessors.uploadModel() calls this to register materials in a MaterialLibrary.
Model Import Normalization Pipeline
Section titled “Model Import Normalization Pipeline”The engine has a unified model import normalization pipeline that corrects common anomalies (incorrect scaling, rotation, up-axis) at load time. This replaces ad-hoc hardcoded fixes in individual apps.
Architecture
Section titled “Architecture”ImportSettings(packages/engine/core/src/assets/import-settings.ts) — per-model normalization config:upAxis,units,scale,rotation,centerToOrigin,autoFit,nodeTransforms. Resolved from sidecar files or parser-detected defaults.model-normalizer.ts(packages/engine/core/src/assets/model-normalizer.ts) — pure transform math:applyUpAxisConversion(Z-up→Y-up),applyUnitScale(source units→meters),applyRootScale,applyRootRotation(quaternion),computeBounds,centerToOrigin,autoFit,isExtremeScale. Operates on interleaved [pos(3)+normal(3)] mesh vertices (6 floats/vertex).bake-node-transforms.ts(packages/engine/libraries/models/src/bake-node-transforms.ts) — bakes glTF/FBX node hierarchy transforms (translation, rotation, scale) into mesh vertices. Promoted from downdraft-model-viewer to the engine so all apps benefit.normalize.ts(packages/engine/libraries/models/src/normalize.ts) — orchestrates the full pipeline: up-axis → unit scale → node-transform baking → root rotation → user scale → bounds → center → auto-fit.normalizeModel()applies settings;normalizeModelWithResolution()resolves sidecars then normalizes.loadModel()(packages/engine/libraries/models/src/loader.ts) — now normalizes by default after parsing. Passnormalize: falseto skip (e.g. for apps that handle their own transforms). PasssidecarResolverfor custom sidecar resolution.
Sidecar System
Section titled “Sidecar System”Per-model import settings are stored in sidecar files, tried in priority order:
.ddmeta.json(our format, JSON-with-comments viacomment-json)- Unity
.meta(YAML,scaleFactorfield) - Godot
.import(INI,scale/rotationparams) - Blender extras (glTF
asset.extras.glTF2ExportSettings.YUP)
Sidecar parsers: packages/engine/libraries/models/src/sidecar/ — ddmeta.ts, unity-meta.ts, godot-import.ts, blender-extras.ts, resolver.ts.
Parser Detection
Section titled “Parser Detection”FBX parser reads GlobalSettings for UpAxis (0/1=Y-up, 2=Z-up) and UnitScaleFactor (units per cm). glTF parser checks asset.extras.glTF2ExportSettings.YUP. DAE parser reads <asset><up_axis> and <unit meter="...">. Stored on ModelData.sourceUpAxis and ModelData.sourceUnits.
Import Cache
Section titled “Import Cache”ImportCache (packages/engine/core/src/assets/import-cache.ts) caches resolved ImportSettings keyed by model path. MemoryImportCache is the in-memory fallback. On native, createHostImportCache() wraps downdraft.importCache* — the host keeps a SQLite-backed cache beside saves/ in the app’s userData dir, and the wrapper warms an in-memory mirror asynchronously so get() stays synchronous.
Save system / storage backends
Section titled “Save system / storage backends”ISaveStore (packages/engine/core/src/save/persist-types.ts) is the storage interface for versioned app saves: save/load (blobs, thumbnails, properties, generation control via SaveOptions/LoadOptions), listSaves/listGenerations/deleteSave/deleteGeneration, setThumbnail/getThumbnail, setProperties/getProperties, onWarning. Saves are a zstd-compressed JSON body of per-component sections (each with its own schema version) plus a header (engine version, timestamp, entity/player counts, XXH128 hash). MigrationRegistry runs per-component fromVersion→toVersion migrations on load; forward-incompatible saves are refused. Implementations live in packages/engine/libraries/persistence/:
FileSaveStore(file-save-store.ts) — filesystem backend, the store that runs on the native host (host mode). One.ddsavefile per slot (header + zstd body), rotated to.bakeach save (load fallback on corruption); blobs in<slot>.blobs/, thumbnail in<slot>.thumb, properties in<slot>.props.json. Node-only (node:fs).DirectorySaveStore(directory-save-store.ts) — directory-handle store:navigator.storage.getDirectory()(OPFS) in browsers, anode:fs-backed File System Access handle on native (Bun/Node/Deno). Generation history, blobs, thumbnails, properties;meta.jsonwritten last as the commit point.HostSaveStore/BridgeJsonSaveStore— plumbing for the"host"/"auto"modes (typed bridge store, or legacy JSON-serialized bridge fallback).
Save modes (app selects via SaveConfig.mode): "host" (main thread writes through the host’s typed ISaveStore → FileSaveStore — the native default), "worker" (the sim worker owns a DirectorySaveStore), "auto" (default: typed host store if the bridge provides one, else BridgeJsonSaveStore). createSaveStore() (app/src/main/save-store-factory.ts) picks; SimBridgeDeps.saveMode tells the sim bridge which path is active.
Devtools Auto-Fit
Section titled “Devtools Auto-Fit”BaseSceneInspector.importModel() returns needsAutoFit and warnings when a model has extreme scale (< 0.01m or > 100m). autoFitModel(nodeId, targetMaxDim) re-normalizes and generates a .ddmeta.json sidecar for persistence; generateSidecar(nodeId) creates a starter sidecar with commented-out fields. (These are __downdraftDevtools methods — callable from the devtools REPL; no dedicated prompt UI in the Blitz dock yet.)
Devtools material editor
Section titled “Devtools material editor”BaseSceneInspector (packages/engine/modules/debug/src/scene-inspector.ts) exposes a functional material editor API: compileMaterialGraph, createMaterialFromGraph, saveMaterialToLibrary, listMaterials, exportMaterialAsJSON, importMaterialFromJSON, previewMaterialGraph (live preview via setPreviewMeshRenderer).
Hot reload
Section titled “Hot reload”HotReloader (packages/engine/core/src/render/hot-reload.ts) writes reloaded shader source into material.inlineShaderSource (not the dead shader string field) and calls material.invalidateVariants() to flush the variant cache.
Compute Graph System
Section titled “Compute Graph System”The engine has a node-based compute shader authoring system that parallels the material graph. It provides a higher-level alternative to hand-writing WGSL compute shaders (the “gpu.js replacement” for WebGPU).
Architecture
Section titled “Architecture”ComputeGraph(packages/engine/shader-graph/src/compute-graph.ts) — the compute graph data structure. Separate fromMaterialGraph(which is vertex/fragment only). Contains nodes + connections +StorageBufferDecl/UniformBufferDecldeclarations +ComputeDispatchConfig(workgroup size + dispatch count).ComputeGraphCompiler(packages/engine/shader-graph/src/compute-compiler.ts) — compiles aComputeGraphto WGSL@compute @workgroup_size(...)shader. Emits struct declarations from buffer decls,@group/@bindingvar declarations, and acs_mainentry point withglobal_invocation_id/local_invocation_id/workgroup_id/num_workgroupsbuiltins. Compute-specific nodes:global_id,buffer_load,buffer_store,atomic_add/sub/min/max/exchange,workgroup_barrier,storage_barrier. Math nodes (multiply, add, sin, etc.) are shared with the material compiler.ComputeProfile(packages/engine/shader-graph/src/compute-profiles.ts) — simpler thanShaderGraphProfile: justname,chunks,workgroupSize. Built-in profiles:SIMPLE_COMPUTE_PROFILE(64x1x1),PARTICLE_COMPUTE_PROFILE(64x1x1),TEXTURE_COMPUTE_PROFILE(8x8x1),VOLUMETRIC_COMPUTE_PROFILE(4x4x4).GraphComputePass(packages/engine/core/src/render/passes/graph-compute.ts) —RenderPasssubclass withPassType.Custom. Integrates with the frame graph (dispatches on the shared encoder). Supports both auto-allocated buffers (fromStorageBufferDecl/UniformBufferDecl) and externally-provided buffers (setExternalBuffer()).recompile()supports hot-reload. Uses localBUFFER_USAGE/SHADER_STAGE_COMPUTEconstants instead of WebGPU globals for testability.runComputeKernel()(packages/engine/core/src/render/compute-kernel.ts) — thin imperative helper for quick one-off GPGPU. Takes WGSL + typed inputs, dispatches once, returns areadBuffer()function for CPU readback. No graph, no frame graph needed.
Buffer management
Section titled “Buffer management”GraphComputePass supports two modes:
- Auto-allocated (default): creates
GPUBuffers fromStorageBufferDecl/UniformBufferDecldeclarations. Storage buffers useSTORAGE | COPY_DST | COPY_SRC; uniform buffers useUNIFORM | COPY_DST. Runtime-sized arrays default to 1 MB. - Externally provided:
setExternalBuffer(name, buffer)skips auto-allocation for that buffer. Used for interop with existing systems (e.g. particle buffers fromParticleComputePass).
Data is written via writeUniform(name, data) (queued, flushed before dispatch) and writeStorage(name, data) (immediate queue.writeBuffer).
Bindless rendering model
Section titled “Bindless rendering model”The engine uses a bindless material binding model to eliminate per-draw bind-group churn. Material parameters (baseColor, roughness, texture indices) live in a single SSBO; textures are registered into global texture_2d_array buckets keyed by format/dimensions/mips. A single bind group (@group(3)) is set once per frame and shared by all draw calls.
Core infrastructure (packages/engine/core/src/render/bindless/)
Section titled “Core infrastructure (packages/engine/core/src/render/bindless/)”BindlessTextureRegistry— managestexture_2d_arraybuckets. Textures are registered bysourceId(stable string key) and packed into array layers.registerFromTexture(src, GPUTexture, key)andregisterFromImageBitmap(src, ImageBitmap, format, mipCount)are the entry points.getHandle(sourceId)returns a packed(pageIndex << 16) | layerIndexhandle.defaultWhiteHandleis a 1x1 white fallback.BindlessMaterialManager— manages the material SSBO.registerMaterial(MaterialParams)returns amaterialIndex;updateMaterial(index, params)updates in place;unregisterMaterial(index)frees the slot.BindlessFrameBindings— owns the@group(3)bind group layout + bind group.prepareFrame()flushes the material SSBO and returns the bind group.getBindGroup()returns the cached bind group.bindless.wgsl.ts— WGSL chunks (BINDLESS_MATERIAL_CHUNK) for theBindlessMaterialstruct +unpackArrayIndex/unpackLayerIndexhelpers.
WGSL binding convention
Section titled “WGSL binding convention”@group(0)— per-draw uniform (camera, model matrix,materialIndex: u32). The materialIndex selects the material from the SSBO.@group(1)— lighting data (storage buffer).@group(2)— IBL bind group (brdfLUT, irradiance, prefilter).@group(3)— bindless materials:binding(0)= material SSBO,binding(1..8)= 8 separatetexture_2d_arraybindings (WGSL does NOT allowarray<texture_2d_array<f32>, N>— each array must be a separate@binding),binding(9)= repeat sampler,binding(10)= clamp sampler.- Texture handles pack
(globalArrayIndex << 16) | layerIndex. TheglobalArrayIndexis a monotonic flat index across all buckets/pages — assigned when a page is appended, never reused. Shaders usesampleBindlessArray(arr, uv, layer)(a switch over arr 0..7) to sample the correct binding.
Device limits
Section titled “Device limits”device.ts, app-renderer.ts, and native-host.ts request maxTextureArrayLayers up to 512 (clamped to what the adapter reports) in requiredLimits. GPUDeviceManager.requestDevice checks for the limit before requesting.
Bindless consumers
Section titled “Bindless consumers”ModelRenderer (libraries/entities, via setBindlessDeps()/setBindlessBindGroup()), OpaquePass PBR path (materialIndex uniform at @group(0) binding(3)), DecalPass, PBR_TEXTURED_PROFILE/PBR_SKINNED_PROFILE shader-graph profiles, and bridgeMaterial() (registers textures when given a registry). Apps’ own renderers (e.g. my-app’s PlayerMeshRenderer) wire it the same way.
WebGPU + Rapier gotchas
Section titled “WebGPU + Rapier gotchas”GPUTexelCopyTextureInfoandGPUCopyExternalImageDestInfouseorigin: [x, y, layer](z component = array layer), not a separatearrayLayerproperty.GPUSupportedLimits→Record<string, number>conversion requiresanycast.@dimforge/rapier3d-compatdoes not exportRawRigidBodySet/RawColliderSet—rapier-physics-system.tsusesanyfor raw body/collider refs.- WASM borrow aliasing: Rapier returns
RawVector/RawRotation/RawColliderShapeobjects from methods likebody.translation(),controller.computedMovement(), andColliderDesc.trimesh(). These hold WASM borrows that must be explicitly.free()d beforeworld.step(). Therapier-backend.tsaddColliderfreescd.shapeafterworld.createCollider()(the collider set clones theSharedShapeArc). Same forgetColliderPosition,getBodyTransform,characterMove, and the raw fast-path fallbacks. Failure to free causes “recursive use of an object detected which would lead to unsafe aliasing in rust” panics duringworld.step(). - Raw fast-path handle mapping: The
*Rawmethods inrapier-backend.tsreceivebodyId(the app’sPhysicsBody.id, sequential: 1, 2, 3…) but must pass the Rapier rigid-body handle (body.handle, starts at 0) to WASM functions likerbSetTranslation. The raw fast paths look up theRigidBodyfrombodyMapsto getbody.handle. PassingbodyIddirectly causes out-of-bounds WASM access that corrupts internal state and triggers the aliasing panic. swapColliderShapeRawshape type:ColliderDesc.trimesh()returns aSharedShape(Eg) which stores vertices/indices but does NOT hold aRawColliderShape.coSetShapeexpects aRawShape(OA). Callshape.intoRaw()to get theRawColliderShape, pass it tocoSetShape, then.free()it.
Universal Physics Module (physics-rapier 0.2.0)
Section titled “Universal Physics Module (physics-rapier 0.2.0)”- The
PhysicsBackendinterface is nowPhysicsBody-keyed (opaque body refs). Raw RapierRigidBodyHandleis no longer exported from@downdraft/engine. - Multi-realm LOD:
RealmManagerdrives near/mid/far tiers with promote/demote + dwell hysteresis. Static bodies are duplicated into all realms by default. UniversalPhysicsAPI(@downdraft/engine/libraries/physics-rapier) is the single public surface: body lifecycle, validated state access, realm queries, interpolation, raycast, snapshots, hooks.- Subsystems:
PhysicsAccumulator(fixed timestep),InterpolationBuffer(double-buffered),LoadShedder(island-aware freeze),SafetyLayer(NaN/Inf + hard-lock),CCDHeuristic(per-body),SnapshotManager(multiplayer),RealmWorkerPool(nested-worker parallelism,workerCount:0= single-threaded). PhysicsSystem(ECS,Stage.Physics) wires all subsystems together; created viacreatePhysicsSystem(resources).- Raw fast paths (
*Rawmethods onUniversalPhysicsAPI/PhysicsBackend): scalar transform sync/readback,isSleepingRaw,swapColliderShapeRaw(in-place trimesh shape swap, avoids broadphase re-insertion),reserveMemory,setIntegrationDt. These bypass safety validation and avoid JS object allocation — callers must validate inputs. Use in hot loops (e.g.my-app’s per-entity sync runs every tick).
Host SDK (@downdraft/engine/app — runtime-agnostic host layer)
Section titled “Host SDK (@downdraft/engine/app — runtime-agnostic host layer)”The native host (packages/platform-native) owns the process: it creates the winit window, the wgpu device/surface, installs the globalThis.downdraft HostAPI bridge in-process (no IPC, no preload), and runs the MCP server. An app boots from src/native-entry.ts → runNativeAppModule() / startNativeApp() / createNativeHost().
Subpath exports
Section titled “Subpath exports”@downdraft/engine/app/main—startApp()/bootstrapApp()(run on the native main thread), typeddowndraftHostAPI accessor (stubs to no-op when absent), save-store factory, standard MCP automation tools.@downdraft/engine/app/shared— theHostAPIcontract types (packages/engine/app/src/shared/types.ts).
Process model
Section titled “Process model”Single process: the app module, renderer, host services, sim-worker host, and MCP server all live in the one JS-runtime process; the simulation runs in a dedicated worker thread (SAB channels, unchanged). Recovery is restart-based — downdraft.requestRestart(reason) respawns the process (see packages/platform-native/src/native-restart.ts); window.location.reload() is not a recovery path on native. Devtools + OSR are in-process WebGPU overlays (modules/native-osr), not embedded web panels.
UI typography: minimum font size
Section titled “UI typography: minimum font size”All UI text rendered by the engine and apps MUST use a font size of at least 12px. This applies to in-app HUDs, menus, tooltips, DevTools panels, and any UI document content generated by the framework.
- Do not set
font-sizebelow12px(e.g. no10px,11px, or0.7rem-style values that resolve below 12px) in CSS, inline styles, or stylesheet theme overrides. - When adapting third-party component styles or copying reference markup, bump any sub-12px font sizes up to 12px.
- The base stylesheet (
packages/engine/app/src/main/downdraft-base.css) should not introduce a root font size below 12px; app theme overrides layered on top of it must also respect this floor. - This is a readability/accessibility floor, not a target — larger sizes are fine where appropriate.