Technical specification for the Neith sovereign runtime kernel: Cargo workspace organization, public Rust API contracts, the type system of the foundational
coreworkspace, build targets, and integration interfaces.Status: IMPLEMENTED. Neith is a polyglot domain consisting of ~60 Cargo workspaces under
libs/neith/plus a small set of standalone TypeScript packages. The crate workspaces contain real, production-quality Rust — for example thecoreworkspace alone spans ~19,600 lines across six crates, and theaudio-runtimeworkspace spans ~74,000 lines. This document is grounded in the source of the foundationalcore,crypto,hal,net,rendereranduiworkspaces, which were read directly. Crates outside those six workspaces are inventoried by name and described from theirCargo.tomlmanifests and crate-level documentation; their exhaustive type surfaces are not enumerated here. Any item below labelled(planned)does not yet exist in source.
This document serves as the engineering reference for Neith's public API surface
and workspace organization. A new engineer should read features.md first for a
conceptual overview of what each workspace does, then return here when they need
the actual types, method signatures, enums, and configuration parameters that
code must use.
The document is organized from the ground up: the technology stack table comes
first (what versions of what libraries underpin everything), then the workspace
inventory (what exists in source), then the full type surfaces of the six
foundational engine workspaces in dependency order — core first, then
crypto, then hal, net, renderer, and ui. Build integration and the
sovereignty invariant close the document.
Technology Stack#
The table below lists every third-party crate that the foundational six workspaces depend on, together with the pinned version. Anything not listed here is either a Neith-internal crate (no third-party dependency) or is used only in the extended workspaces (audio-suite, creative tools, etc.) that are inventoried separately.
| Layer | Technology |
|---|---|
| Language | Rust, 2021 edition (edition.workspace = true) |
| Workspace versioning | version = "0.1.0", license = "Apache-2.0" (workspace pkg) |
| Async runtime | Custom work-stealing executor on crossbeam-deque + mio |
| Concurrency crates | crossbeam-deque, crossbeam-channel, crossbeam-utils, parking_lot |
| Serialization | serde + serde_json + rmp-serde (MessagePack) + ciborium (CBOR) |
| Compression | lz4_flex, zstd |
| Hashing (core) | blake3 |
| Logging / tracing | log, tracing, tracing-subscriber, opentelemetry 0.27 |
| Error handling | thiserror 2.0, anyhow |
| TLS | rustls 0.23 (with ring), rustls-pki-types, webpki-roots, rcgen |
| Audio backend | cpal 0.15 (in neith-audio-hal) |
| Accessibility | accesskit 0.24 (in the ui workspace) |
| Build orchestration | Cargo workspaces driven by Nx nx:run-commands executor |
| Test framework | Rust built-in #[test] (extensive per-crate mod tests) |
Common misconceptions to avoid: the
renderer/halcrates do not depend onwgpu, andneith-physicsdoes not depend onrapier3d.neith-gpuis a self-contained GPU abstraction with its ownBackendenum and handle types;neith-physicsimplements its own broadphase, GJK/EPA narrowphase, and constraint solver over plain[f32; 3]math types. The only external real-time crate actually used in the six core workspaces iscpal(audio HAL). There is also nowasm-bindgenornapi-rsdependency in the core six workspaces — the engine crates are consumed as native Rust crates, not via WASM/Node bindings.
Workspace Organization#
Neith is not six workspaces — libs/neith/ now contains roughly 290
workspace directories, each with its own Cargo.toml ([workspace] manifest),
crates/ directory, project.json (Nx wiring), and usually a
rust-toolchain.toml. A small number of directories are standalone TypeScript
packages instead (they carry package.json + tsconfig.json + src/). The
tables below inventory the foundational, audio, and creative workspaces; the
sovereignty-closure families (Phases 156–174) are inventoried in the "Closure
workspace families" section below. Consult features.md's sovereignty roadmap
section for the per-phase capability envelopes and for the later-phase
workspaces that do not yet have directories.
Foundational engine workspaces (six)#
| Workspace | Crates |
|---|---|
core/ |
neith-runtime, neith-alloc, neith-serde, neith-reflect, neith-events, neith-log |
crypto/ |
neith-sym, neith-asym, neith-hash, neith-rand, neith-tls |
hal/ |
neith-gpu, neith-audio-hal, neith-input, neith-sensor, neith-camera, neith-net-hal, neith-storage |
net/ |
neith-transport, neith-game-net, neith-webrtc, neith-http |
renderer/ |
neith-render-graph, neith-gpu-driven, neith-pbr, neith-material-graph, neith-gi, neith-shadows, neith-lighting, neith-virt-geom, neith-postfx, neith-atmosphere, neith-physics, neith-audio, neith-ecs, neith-scripting, neith-animation, neith-gaussian-splatting |
ui/ |
neith-render2d, neith-text, neith-layout, neith-widgets, neith-animation, neith-theme |
The
renderer/workspace is a 16-crate workspace — it contains not only the ten rendering crates but alsoneith-physics,neith-audio,neith-ecs,neith-scripting,neith-animationandneith-gaussian-splattingas workspace members. Theui/workspace also has a crate namedneith-animation; it is distinct from the renderer'sneith-animationcrate.
Game-AI, scene, asset, and platform workspaces#
The workspaces below extend the foundational six with higher-level engine
capabilities. Each follows the same structure: a Cargo.toml workspace
manifest, a crates/ directory, and a project.json for Nx integration.
| Workspace | Crates |
|---|---|
ai-runtime/ |
neith-navigation, neith-behavior-tree, neith-ai-fsm, neith-perception, neith-crowd, neith-ml-inference, neith-llm, neith-npc |
scene/ |
neith-scene-graph, neith-level-stream, neith-world |
assets/ |
neith-asset-format, neith-asset-import, neith-asset-proc, neith-asset-stream, neith-asset-registry |
particles/ |
neith-particle-core, neith-vfx-graph |
procgen/ |
neith-diff-procgen, neith-inverse-procgen, neith-jfa, neith-neuro-facade, neith-neural-flora, neith-scene-agent, neith-nca, neith-physarum, neith-texture-synth, neith-terrain-ml, neith-tiling, neith-wave-noise |
weaver/ |
neith-copernicus, neith-node-graph, neith-geo-nodes, neith-terrain, neith-building |
embedded/ |
neith-embedded-rtos, neith-embedded-sync, neith-embedded-hal, neith-embedded-net, neith-embedded-fs, neith-embedded-security, neith-embedded-power, neith-embedded-sensors, neith-embedded-device |
android/ |
neith-android-core, neith-android-ui, neith-android-privacy, neith-android-perf, neith-android-creative, neith-android-hal, neith-android-connectivity, neith-android-build |
vr-os/ |
neith-vr-runtime, neith-vr-input, neith-vr-display, neith-vr-tracking, neith-vr-guardian, neith-vr-mixed-reality, neith-vr-audio, neith-vr-social, neith-vr-app |
browser/ |
neith-browser-engine, neith-browser-rendering, neith-browser-layout, neith-browser-script, neith-browser-webapi, neith-browser-webgl, neith-browser-media, neith-browser-net, neith-browser-storage, neith-browser-shell |
linux/ |
neith-distro-core, neith-pkg-manager, neith-overlay-manager, neith-kernel-builder, neith-workload-tuner, neith-update-agent, neith-shell, neith-services, neith-audio, neith-graphics, neith-storage, neith-network, neith-security, neith-pkg, neith-settings, neith-creative, neith-installer (plus kernel/, modules/, iso/, packages/, partitions/, flake.nix) |
Audio-suite workspaces#
The audio suite is a collection of Cargo workspaces covering the full
professional audio stack from driver HAL to DAW features. These are all present
in source. Their crate-level type surfaces are not enumerated in this document
but are described in features.md under Phases 132–133.
audio-runtime/, audio-graph/, audio-fileio/, audio-telemetry/, audio/
(crate neith-diff-audio), midi-io/, net-audio/, controllers/,
vst3-host/, au-host/, lv2-host/, clap-host/, plugin-sandbox/,
plugin-validator/, composer/ (crates neith-daw-core, neith-mixer,
neith-midi, neith-synth, neith-spatial-audio), notation/,
session-view/, comping/, restoration/, pitch/, mastering/,
synth-advanced/, modular/, patch-lab/, live-code/, scoring/,
sample-content/, dj/, adr-foley/, foley/, realtime-assist/.
Creative-tool workspaces#
The creative tools are Cargo workspaces (not npm packages) that implement the
Blender-class 3D creation suite. See features.md Phase 44 for the feature
description of each tool.
sculptor/ (crates neith-mesh-edit, neith-sculpt, neith-uv,
neith-tex-paint, neith-sculptor-render), animator/ (crates neith-motion,
neith-rig, neith-timeline, neith-mocap, neith-facial), cutter/ (crates
neith-video-timeline, neith-vfx, neith-color-grade, neith-export),
forge-core/ (crate forge-doc-graph).
Standalone TypeScript packages#
These directories are TypeScript libraries (package.json + src/), not Cargo
workspaces. They provide infrastructure concerns — cloud management,
observability, domain integration adapters — that do not belong in the Rust
crates. Each is built with tsup/tsc and participates in the Nx graph via a
project.json, but it does not expose any Rust bindings.
| Package | name |
Purpose (from package.json) |
|---|---|---|
cloud/ |
@neith/cloud |
Cloud infrastructure management — Kubernetes, GPU, storage, network |
docs/ |
@neith/docs |
Documentation system — developer docs, user guides, API docs |
observability/ |
@neith/observability |
Observability infrastructure — metrics, logging, distributed tracing |
security/ |
@neith/security |
Security infrastructure — identity & access, secrets, compliance |
qa/ |
@neith/qa |
QA infrastructure (private package) |
testing/ |
@neith/testing |
Test infrastructure — unit, integration, E2E, performance |
training/ |
@neith/training |
Training/education — courses, onboarding, certifications |
release/ |
@neith/release |
Release tooling (private package) |
integration-bellona/ |
@neith/integration-bellona |
Bellona (build & engine) integration |
integration-hathor/ |
@neith/integration-hathor |
Hathor (worldbuilding) integration |
integration-isis/ |
@neith/integration-isis |
Isis (generative AI factory) integration |
integration-maya/ |
@neith/integration-maya |
Maya (game engine / metaverse) integration |
integration-sophia/ |
@neith/integration-sophia |
Sophia integration (private package) |
integration-yemaya/ |
@neith/integration-yemaya |
Yemaya (creative studio) integration |
The
core/andscene/workspaces additionally carry apackage.json(@neith/core, etc.) alongside their Cargo manifest; this declares the Nx project so the Rust workspace participates in the Nx graph. It does not indicate a published JavaScript surface.
Closure workspace families (Phases 156–174)#
The sovereignty-closure phases are present in source as workspace families
under libs/neith/ (roughly 200 workspaces beyond the foundational/audio/
creative sets above). Each family's per-phase capability envelope is in
features.md; the family members are:
| Phase | Family | Workspaces |
|---|---|---|
| 156 | gpen-* |
anim, lineart, modifier, object, rig, shade, storyboard, testing, tools, vr |
| 157 | sim-* |
cloth, core, farm, forces, games, gas, liquid, mpm, ocean, particles, render, rigid, surface, validation |
| 158 | vse-* |
audio, conform, core, effects, ingest, playback, render, review, storyboard, testing, transitions |
| 159 | oss-* |
abstraction, anti-cheat, identity, matchmaking, observability, pixel, prediction, presence, replay, replication, rpc, session, testing, transport, voice |
| 160 | profiler-* |
asset, audio, capture, crash, gpu, memory, net, physics, sample, shader, stat, testing, timing, ui |
| 161 | vfx-* |
attribute, core, data-interfaces, editor, library, modules, perf, renderers, sim, spawn, testing |
| 162 | dh-* |
animator, bodyrig, clothing, core, creator, ethics, eyes, facerig, retarget, sdk, sim, skin, testing, voice |
| 163 | vp-* |
broadcast, camera, cluster, color, control, core, frustum, mr, pipeline, record, scene, testing, wall |
| 164 | liveops-* |
ads, analytics, attribution, cloud-save, compliance, conformance, crm, cs, economy, experiments, iap, portal, remote |
| 165 | market-* |
buyer-portal, catalog, commerce, conformance, creator, creator-analytics, discover, dl, licensing, moderation, review, sdk |
| 166 | spatial-* |
anchors-collab, audio, avatars, conformance, core, input, os, physics, render, sdk, volumes |
| 167 | audio-* (engine) |
accessibility, bus-graph, conformance, dialogue, environment, mix, music, profiler, source, spatial, synth, tooling, voice (the audio-graph/audio-runtime/audio-fileio/audio-telemetry runtime crates are shared with Phases 132–133) |
| 168 | gi-* |
ao, conformance, core, emissive, lightmap, lumen, probe, sdfgi, shadow, sky, volumetric, voxel |
| 169 | compute-* |
abstraction, conformance, debug, dispatch, lang, memory, ml, render, resources, sdk, sim, wave |
| 170 | sculpt-*, npr-* |
sculpt: brushes, core, export, face-sets, layers, mask, polypaint, retopo, testing, topology; npr: cel, inking, line |
| 171 | engine-* (shipped subset) |
engine-verse, engine-lwc, engine-level-instances, engine-megalights, engine-rvt, engine-lights (the rest of 171 and all of the 172–174 engine-*/dcc-* package surface is planned) |
Note the engine-audio family (Phase 167) deliberately names its bus/graph crate
audio-bus-graph to avoid colliding with the Phase-132 audio-graph runtime
workspace.
core Workspace — Sovereign Runtime Kernel#
The core workspace is the bedrock every other Neith crate builds on. It
provides the async executor that runs all tasks, the memory allocators that
serve all subsystems, the serialization layer that crosses all boundaries, the
reflection system that powers editors and scripting, the event bus that connects
subsystems, and the diagnostics layer that makes everything observable. No Neith
crate may depend on a third-party async runtime instead of neith-runtime, and
no Neith crate may use serde directly instead of routing through
neith-serde.
libs/neith/core/Cargo.toml declares the workspace, pins all third-party
dependency versions in [workspace.dependencies], and sets three Cargo
profiles: dev/test at opt-level = 0, release with lto = true,
codegen-units = 1, opt-level = 3. The six member crates path-depend on each
other via neith-runtime = { path = "crates/neith-runtime" } style entries.
neith-runtime — Async Executor#
neith-runtime is a custom work-stealing async executor designed for game
engines and real-time systems. Unlike Tokio, it has no implicit global thread
pool and makes no assumptions about blocking I/O patterns — tasks carry explicit
priority levels, and the executor can be driven from a game loop's fixed-tick
cadence. A consumer creates exactly one Runtime instance, spawns tasks onto
it, and drives it with block_on or from a dedicated thread.
Source: core/crates/neith-runtime/src/. The crate's lib.rs re-exports the
public surface; the crate is organized into modules affinity, backpressure,
cancel, channel, executor, fiber, io, local, metrics, pool,
scheduler, sync, timer.
Runtime and configuration#
Runtime (executor/mod.rs) is the primary entry point and the only type most
consumers need directly. It wraps an Arc<RuntimeInner> so it can be cheaply
cloned and passed across subsystems. The table below lists every public method
on Runtime.
| Method | Behaviour |
|---|---|
Runtime::builder() -> RuntimeBuilder |
Construct a fluent builder. |
block_on<F: Future>(&self, future: F) -> F::Output |
Drive a future to completion on the calling thread, polling I/O and the timer wheel while pending. |
spawn<F>(&self, future: F) -> TaskHandle<F::Output> |
Spawn a task at TaskPriority::Normal. Requires F: Future + Send + 'static, F::Output: Send + 'static. |
spawn_with_priority<F>(&self, priority: TaskPriority, future: F) -> TaskHandle<F::Output> |
Spawn at an explicit priority. |
metrics(&self) -> RuntimeMetrics |
Return a snapshot of runtime counters. |
shutdown_timeout(&self, timeout: Duration) |
Graceful shutdown, waiting up to timeout for active tasks. |
Drop for Runtime calls shutdown(Duration::from_secs(5)).
RuntimeConfig is the read-only configuration snapshot returned by
RuntimeBuilder::build. All fields have sensible defaults; most consumers only
need to override worker_threads to match the target CPU count.
| Field | Type | Default | Meaning |
|---|---|---|---|
worker_threads |
usize |
num_cpus::get().max(1) |
Number of work-stealing worker threads. |
thread_name |
String |
"neith-worker" |
Prefix for worker thread names ({name}-{idx}). |
thread_stack_size |
usize |
2 * 1024 * 1024 (2 MiB) |
Per-worker thread stack size. |
max_blocking_threads |
usize |
512 |
Cap for the blocking thread pool. |
io_poll_interval |
Duration |
1 ms |
I/O reactor poll cadence. |
timer_resolution |
Duration |
1 ms |
Timer wheel tick resolution. |
RuntimeBuilder exposes chainable setters worker_threads (asserts >= 1),
thread_name, thread_stack_size, max_blocking_threads, io_poll_interval,
and build() -> Result<Runtime, RuntimeError>.
RuntimeError (thiserror):
ThreadSpawn(std::io::Error)— a worker thread failed to spawn (#[from]).ShutDown— the runtime was already shut down.
Scheduler internals. Understanding the scheduler helps when diagnosing
latency spikes. RuntimeInner holds four per-priority Injector queues
(PriorityInjectors = Arc<[Arc<Injector<RawTask>>; 4]>, index 0 = Critical … 3
= Low), a Vec<Stealer<RawTask>>, a park condvar pair
(Arc<(Mutex<usize>, Condvar)>) for sleeping workers, a shutdown_flag
(AtomicBool), a task_counter (AtomicU64), the MetricsCollector, the
IoDriver, and the TimerWheel. Each worker owns a Chase-Lev LIFO deque
(Worker::new_lifo()); the worker poll loop drains its own deque (LIFO, warm
cache), then steals from the global priority injectors (FIFO), then steals from
a random peer, then parks on the I/O reactor.
TaskPriority (scheduler.rs)#
Every spawned task carries a TaskPriority. The scheduler processes higher
priority tasks before lower priority ones within the same tick. Critical tasks
are polled before all other work, making them suitable for physics ticks and
input processing; Low tasks are only scheduled when nothing higher is pending.
#[repr(u8)] enum, Default = Normal:
| Variant | Value | poll_weight() |
Meaning |
|---|---|---|---|
Critical |
0 | u32::MAX |
Polled before all other work every scheduler tick. |
High |
1 | 4 |
Polled 4× as often as Normal. |
Normal |
2 | 1 |
Default scheduling weight. |
Low |
3 | 0 |
Background; only scheduled when nothing higher is pending. |
Helpers: TaskPriority::ALL (the four variants in descending priority order),
name() -> &'static str, poll_weight() -> u32, beats(self, other) -> bool
(true when (self as u8) < (other as u8)). Implements Display.
TaskState (executor/task.rs)#
Tasks progress through a defined lifecycle. The TaskState enum models that
lifecycle as a #[repr(u8)] value that can be read atomically without locks:
Runnable = 0, Running = 1, Waiting = 2, Completed = 3, Cancelled = 4.
Fibers (fiber.rs)#
"Fibers" are cooperative coroutines built on Rust's native stackless async/await — they run as normal tasks inside the work-stealing executor. The fiber API provides named handles, explicit yield points, one-shot synchronization signals, and a counted variant for fan-out/join patterns.
FiberId(pub u64)— monotonically increasing fiber identifier.FiberPriority— a re-export ofscheduler::TaskPriority.FiberStateenum — externally observable lifecycle state:Runnable,Yielded,WaitingSignal,WaitingLatch,WaitingTimer,Completed,Cancelled.yield_now() -> YieldNow— relinquish the executor for exactly one poll cycle, then resume.yield_ticks(n: u32) -> YieldTicks— yield for exactlyncycles.Signal— one-shot synchronisation primitive (fired: AtomicBool,waiters: Mutex<Vec<Waker>>).Signal::new() -> Arc<Self>,fire()wakes all waiters,is_fired() -> bool.wait_signal(Arc<Signal>) -> WaitSignalparks until fired.CountedSignal— fires its innerSignalwhen anAtomicU64counter reaches zero.CountedSignal::new(count: u64) -> Arc<Self>,decrement(),wait() -> WaitSignal,remaining() -> u64.
Cancellation (cancel.rs)#
CancellationToken—new(),cancelled()(already-cancelled token),cancel(),is_cancelled() -> bool,cancelled_future() -> CancelledFuture(a future that resolves on cancellation),child_token() -> CancellationTokenChild.CancellationTokenChild— a child token whose cancellation propagates from its parent (tree propagation).CancelledFuture— the future yielded bycancelled_future().
Timers (timer.rs)#
TimerWheel— hierarchical timer wheel.new(),insert(deadline: Instant, waker: Waker) -> Arc<AtomicBool>(returns a cancellation flag),advance() -> usize(fires due timers, returns count fired).TimerHandle—cancel().Sleep— future created bysleep(duration: Duration) -> Sleeporsleep_until(deadline: Instant) -> Sleep.timeout(...)— wraps a future with a deadline; on expiry yieldsElapsed.Instant— runtime instant type re-exported at crate root.
Channels (channel/)#
neith-runtime provides three async channel families for task coordination,
each suited to a different producer/consumer cardinality. All three are
pub use-d at the crate root:
mpsc—mpsc_channel(),MpscSender,MpscReceiver.mpmc—mpmc_channel(),MpmcSender,MpmcReceiver.broadcast—broadcast_channel(),BroadcastSender,BroadcastReceiver.
Backpressure (backpressure.rs)#
bounded_channel() yields a BoundedSender / BoundedReceiver pair; the
sender applies async back-pressure when the bound is reached.
Async sync primitives (sync/)#
AsyncMutex+AsyncMutexGuardAsyncRwLock+AsyncReadGuard+AsyncWriteGuardAsyncSemaphore+SemaphorePermitAsyncBarrier+BarrierWaitResultAsyncLatch
Task-local storage (local.rs)#
TaskLocal — per-task storage slot analogous to thread-local storage.
Blocking pool (pool.rs)#
BlockingPool + BlockingPoolConfig — a dynamically sized thread pool for
CPU-bound / blocking work, kept off the async worker threads.
RuntimeMetrics (metrics.rs)#
RuntimeMetrics is a Clone + Default point-in-time snapshot returned by
Runtime::metrics(). Use it to diagnose scheduler imbalance, excessive steal
contention, or stalled tasks. The derived methods make the raw counters
actionable without requiring arithmetic at the call site.
| Field | Type | Meaning |
|---|---|---|
tasks_spawned |
u64 |
Total tasks ever spawned. |
tasks_completed |
u64 |
Tasks that ran to completion. |
tasks_cancelled |
u64 |
Tasks cancelled before completion. |
steal_successes |
u64 |
Successful work-steals. |
steal_attempts |
u64 |
Total steal attempts (success + failure). |
io_events |
u64 |
I/O events processed by the reactor. |
timer_fires |
u64 |
Timer entries that fired. |
worker_polls |
Vec<u64> |
Per-worker poll counts. |
Derived methods: tasks_active() (spawned − completed − cancelled,
saturating), steal_efficiency() -> f64 (successes / attempts; 1.0 if zero
attempts), avg_polls_per_worker() -> f64,
busiest_worker() -> Option<(usize, u64)>,
idlest_worker() -> Option<(usize, u64)>, load_imbalance() -> f64
((busiest − idlest) / busiest; 0.0 balanced, 1.0 fully unbalanced).
Implements Display.
neith-alloc — Memory Allocators#
neith-alloc provides a suite of specialized allocators, each optimized for a
specific access pattern. Using the right allocator for each subsystem eliminates
GC pauses, reduces fragmentation, and ensures predictable allocation latency —
all critical concerns for a real-time game engine. The system allocator is
appropriate for setup code; everything inside a frame tick should use one of the
allocators below.
Source: core/crates/neith-alloc/src/ — fifteen modules. Allocators target
distinct allocation patterns:
| Allocator / utility | Module | Exported types |
|---|---|---|
| Arena (frame-temporary scratch) | arena |
Arena, ArenaScope, BumpArena |
| Buddy (power-of-two blocks) | buddy |
BuddyAllocator |
| Memory budget | budget |
MemoryBudget, MemoryBudgetError |
| Memory-mapped files | mmap |
MemoryMappedFile |
| Out-of-memory handling | oom |
OomHandler, OomPolicy, set_oom_handler |
| Pool (fixed-size objects) | pool |
Handle, ObjectPool |
| Slab (component/entity storage) | slab |
SlabAllocator, SlabHandle |
| Stack (hierarchical LIFO) | stack |
DoubleEndedStack, StackAllocator, StackMarker |
| Memory tagging (debug) | tag |
MemTag, tag_alloc, tag_free |
| TLSF (two-level segregated fit) | tlsf |
TlsfAllocator |
| Allocation tracking | track |
AllocationRecord, AllocationTracker |
| Virtual memory | virt |
VirtualMemory, VirtualMemoryFlags |
Additional modules without re-exports at the crate root: defrag
(defragmentation strategies), huge (huge-page support), shared (shared
memory / IPC).
neith-serde — Serialization#
neith-serde is the serialization layer used wherever Neith data crosses a
boundary: writing save files, sending game state over the network, persisting
editor state, or passing data between Rust and TypeScript. Its primary format is
NBF (Neith Binary Format), a custom zero-copy binary format. It also supports
JSON (human-readable debugging and Neith-to-JS interop), MessagePack (compact
interop), and CBOR (constrained environments). All formats share the same schema
definition and versioning infrastructure.
Source: core/crates/neith-serde/src/lib.rs. Modules: nbf, schema,
json_ext, compress, partial, validate.
Neith Binary Format (nbf)#
NBF is a custom compact binary format designed for zero-copy deserialization: the in-memory layout matches the wire format closely enough that serialized data can be memory-mapped and accessed without a separate parsing step. Every NBF frame starts with a fixed 20-byte header that identifies the type and payload length, followed by the payload (MessagePack by default, or JSON for the debug variant).
The wire layout is:
[0..6] magic b"NEITH\x01" (constant MAGIC)
[6..8] version u16 big-endian (FORMAT_VERSION = 1; 0x8001 = JSON payload)
[8..16] type_hash u64 big-endian (first 8 bytes of BLAKE3 of the type name)
[16..20] payload_len u32 big-endian
[20..] payload raw bytes (MessagePack by default, or JSON)
MAGIC: &[u8; 6] = b"NEITH\x01",FORMAT_VERSION: u16 = 1,HEADER_LEN: usize = 20.type_hash_for(type_name: &str) -> u64— BLAKE3-derived 8-byte type hash.NbfHeader { version: u16, type_hash: u64, payload_len: u32 }.NbfEncoder { strict_types: bool }(defaulttrue) —encode<T: Serialize>(type_name, value) -> Result<Bytes, NbfError>(MessagePack payload),encode_json<T>(...)(JSON payload, version word0x8001).NbfDecoder { strict_types: bool }— decodes NBF frames back into typed values, validating the type hash whenstrict_typesis set.NbfErrorvariants:BadMagic,UnsupportedVersion(u16),LengthMismatch { expected: u32, actual: usize },TypeHashMismatch { encoded: u64, expected: u64 },MsgPack(String),Io(String).
Schema, compression, deltas, validation#
schema—SchemaVersion,SchemaMigration,SchemaRegistry(versioning and migration chains for forward/backward compatibility).compress—compress_lz4/decompress_lz4,compress_zstd/decompress_zstd,CompressionLevel.partial—DeltaEncoder,DeltaDecoder,FieldDelta(serialize only changed fields for network state sync).validate—Validator,ValidationError,ValidationResult.
neith-reflect — Runtime Reflection#
neith-reflect provides runtime type metadata that enables editor property
panels, scripting language bindings, automated serialization, and diff/patch
workflows — all without hand-written glue code per type. Any Rust type annotated
with impl_reflect_struct! (or a custom Reflect implementation) becomes
inspectable at runtime: the editor can read and write its fields by name, the
scripting layer can create and clone instances, and the undo/redo system can
diff two instances and produce a minimal change patch.
Source: core/crates/neith-reflect/src/lib.rs. Modules: type_info, reflect,
registry, access, diff, attr, impls, macros.
TypeKindenum —Struct,Enum,Primitive,Opaque.FieldInfo { name: &'static str, type_name: &'static str, byte_offset: usize, is_optional: bool }. Constructedconst-ly viaFieldInfo::new(name, type_name, byte_offset);.optional()marksis_optional = true.TypeInfo { type_name: &'static str, kind: TypeKind, fields: &'static [FieldInfo], size: usize, align: usize }. Constructorsnew_struct(...),new_primitive(...). Methodsfield(name) -> Option<&FieldInfo>,field_count() -> usize.Reflecttrait +ReflectValue(reflectmodule) — dynamic field inspection / mutation.ReflectRegistry+RegistryError— global type registry with factory and clone support.get_field/set_field+AccessError— name-keyed runtime field access.ReflectDiff+FieldChange— reflection-based diff/patch (undo-redo, network delta sync).AttributeMap+AttributeValue— attribute/annotation system read by editors.impl_reflect_struct!macro (macrosmodule) — derives aReflectimplementation for a struct.
neith-events — Typed Event Bus#
neith-events is the in-process messaging backbone between engine subsystems.
The key design decision is that channels are typed at the Rust type level:
trying to publish an event of the wrong type is a compile error, not a runtime
panic. This eliminates an entire class of string-keyed event bus bugs common in
other game engines.
The crate supports both synchronous delivery (for input events and physics callbacks that need to be processed immediately) and asynchronous queued delivery (for less latency-sensitive events). It also supports event sourcing patterns — where state is derived entirely from event history — enabling complete undo and deterministic replay for debugging.
Source: core/crates/neith-events/src/lib.rs (~2,555 lines, single file with
inline modules). Modules: event, channel, bus, reader, filter,
batch, replay, source, stats, async_dispatch, priority_channel,
cancellable, weak_bus, ipc, flow_graph.
Core event types (event)#
Note that Priority values here are ordered from Low = 0 upward, which is the
reverse of runtime::TaskPriority where Critical = 0. This is an
intentional design choice: event priority represents urgency on a rising scale,
while task priority uses a descending representation for efficient array
indexing. Be careful not to confuse the two.
Priorityenum (Serialize/Deserialize, ordered) —Low = 0,Normal = 1,High = 2,Critical = 3.Default = Normal.EventMeta { sequence: u64, timestamp_ms: u64, source_id: Option<u64>, priority: Priority }.EventMeta::new(sequence)setstimestamp_msfrom the system clock; builders.with_priority(p),.with_source(id).EventInstance<T> { payload: T, meta: EventMeta }— a concrete event.Event— blanket marker trait, auto-implemented for everyClone + Send + Sync + 'statictype.
Channels and the bus#
EventChannel<T>(channel) — a double-buffered typed channel: writerssend(payload)/send_with_meta(payload, meta)into the write buffer;swap()atomically swaps write↔read at the frame boundary;read_events()returns a guard over the stable read buffer;drain_immediate()takes all pending events without swapping. Sequence numbers assigned via an internalAtomicU64.EventBus(bus) — type-erased router holdingHashMap<TypeId, BoxedChannel>.register::<T>(type_name)adds a channel (idempotent),send::<T>(event) -> Result<(), BusError>,is_registered::<T>() -> bool,registered_count() -> usize.BusError—NoChannel(String)(no channel for the given type name),TypeMismatch(downcast failure).SwappingBus— anEventBusvariant that also stores per-type swap closures soswap_all()can swap every registered channel at the frame boundary.
Reading, filtering, batching, replay, sourcing#
EventCursor/EventReader(reader) — cursor-based incremental reads.EventFilter/FilterResult(filter) — predicate-based routing.EventBatch(batch) — collect events and submit atomically.EventReplay(replay) — record events and replay deterministically for debugging.EventSource/Projection(source) — append-only event log with projection and snapshots (event-sourcing pattern).EventStats(stats) — per-type counts and dropped-event counts.AsyncEventDispatcher/AsyncEventQueue(async_dispatch) — priority-ordered queued (async) dispatch.PriorityEventChannel(priority_channel) — four-tier priority queues.CancellableEvent/CancellationContext/EventChain(cancellable) — stoppable propagation chains.WeakEventBus(weak_bus) — listeners held viaWeak; dead listeners are auto-culled.subscribe(f)returns theArc<ListenerFn<T>>the caller must retain;subscribe_weak(Weak<...>)registers without ownership.IpcEvent/IpcEventBus/IpcEventReader(ipc) — file-based cross-process event bus.EventFlowGraph(flow_graph) — DOT/Mermaid dispatch tracing.
neith-log — Diagnostics#
neith-log is the observability layer for Rust code. It bridges to the
TypeScript observability stack at domain boundaries via W3C Trace Context
propagation, so a span started in a Rust game-loop can be correlated with a
TypeScript API call that triggered it. Log calls below the configured level are
compiled out entirely in release builds, ensuring zero overhead on hot paths.
Source: core/crates/neith-log/src/lib.rs (~4,337 lines). Modules:
structured, custom, error_info, level, rotate, metric, health,
assert_sys, perf, crash, async_log, binary, tracing_otel,
profiling, remote, analysis.
LogLevelenum (level) —Trace = 0,Debug = 1,Info = 2,Warn = 3,Error = 4,Fatal = 5,Off = 6(Serialize/Deserialize, ordered).LevelFilterapplies a runtime threshold.StructuredLogger+LogRecord(structured) — key-value structured records, JSON output.CustomLoggerfamily (custom) —CustomLoggertrait,CallbackLogger,CustomLogSink,CustomLoggerConfig,CustomLoggerRegistry,CustomLoggerError,CustomLoggerFailure,CustomLogResult.error_info—DetailedErrorInfo,DetailedErrorBuilder,ErrorCategory,ErrorCause,ErrorLocation,ErrorSeverity,DetailedResult+DetailedResultExt.RotationPolicy+LogRotator(rotate) — size / count / date-based rotation.MetricRegistry+Counter+Gauge+Histogram(metric).HealthChecker+HealthStatus+CheckResult(health).PerformanceMarker+ScopeTimer(perf).CrashReporter+CrashReport+BacktraceMode+DebugBacktrace(crash) —catch_unwind-based crash capture with minidump-style reports.AsyncLogger(async_log) — non-blocking background writer.binary—BinaryLogEncoder/BinaryLogDecoder,BinaryLogSink/BinaryLogReader,BinaryLogRecord.tracing_otel— OpenTelemetry-style distributed tracing:TraceId,SpanId,SpanContext,Span,SpanEvent,SpanStatus,SpanRecord,Tracer,TracerProvider,SpanExporter,ConsoleSpanExporter, andW3CTraceContext(W3C Trace Context propagation).profiling—ProfilingSpan,ProfilingSession,ProfilingReport,ProfilingSummary(wall / CPU / alloc reporting).remote—RemoteLogSink,RemoteLogTarget,RemoteLogFormat,SyslogFormatter(RFC 5424).analysis—LogAnalyzer,LogPattern,AlertRule,AlertTrigger,LogStats.
crypto Workspace — Cryptographic Primitives#
The crypto workspace owns every cryptographic operation in Neith — hashing,
symmetric encryption, asymmetric signatures and key exchange, random number
generation, and TLS. Centralizing cryptography in a single workspace ensures
consistent primitive selection, avoids duplicate dependencies on incompatible
crates, and makes security audits tractable.
libs/neith/crypto/Cargo.toml pins rand, rand_core, rustls
(features = ["ring"]), rustls-pki-types, webpki-roots, and rcgen. Each
of the five crates is a single substantial lib.rs covering one cryptographic
concern area.
neith-sym(~2,400 lines) —SymErrorandSymResult<T>. Implements AES-256-GCM from FIPS 197 primitives (S-box, MixColumns, ShiftRows, KeyExpansion present in source), ChaCha20-Poly1305 AEAD, HKDF, PBKDF2, streaming encryption, and secure memory wiping. Errors:AuthTagMismatch,AuthenticationFailed,InvalidKeyLength { expected, actual },InvalidNonceLength { expected, actual },CiphertextTooShort,StreamNotInitialized,ChunkTooLarge(usize),InvalidInput(String).neith-asym(~5,545 lines) —AsymErrorandAsymResult<T>. Ed25519 signing/verification over Twisted-Edwards Curve25519 field arithmetic (primep = 2^255 − 19, 4×u64little-endian limbs), X25519 ECDH key exchange, key serialization, certificate-like structures. Errors:InvalidPublicKey,InvalidPrivateKey,VerificationFailed,InvalidSignatureFormat,SerializationError(String),UnsupportedAlgorithm(String).neith-hash(~1,838 lines) —HashErrorandHashResult<T>. SHA-256 and SHA-512 (FIPS 180-4 constant tables in source), BLAKE3, HMAC, incremental hasher, Merkle trees, a content-addressable store, Argon2id password hashing, HKDF, and timing-safe comparison. Errors:EmptyInput,InvalidProof,HashNotFound(String),Argon2Error(String).neith-rand(~797 lines) —RandErrorandRandResult<T>.NeithCsprngwrapsOsRng(next_u64/next_u32); plus a hardware-RDRAND source, a deterministic ChaCha20-based RNG, UUID v4 generation, an entropy pool, a health monitor, a fork-safe RNG, bias-free sampling, a Fisher-Yates shuffle, and serializable RNG state. Errors:HardwareRngUnavailable,HealthCheckFailed(String),InvalidRange { min, max },EmptyCharset,Serialization(String).neith-tls(~3,627 lines) — TLS 1.3 / secure-channel layer built onrustls. The crate additionally contains a Noise-protocol-style secure channel whose symmetric primitives are documented in source as simulated for portability (the structure mirrors the real protocol; this is explicitly stated, not a hidden stub).
hal Workspace — Hardware Abstraction Layer#
The hal workspace is the portability layer between Neith's engine code and the
physical hardware it runs on. Every platform API difference — GPU backends,
audio drivers, input event formats, camera capture APIs — is absorbed here.
Above the HAL, all code is platform-agnostic; below it, platform-specific
backend implementations handle the details. libs/neith/hal/Cargo.toml pins
cpal 0.15, rustls, bitflags, sha2, and aes-gcm. The workspace contains
seven crates.
neith-gpu — GPU Abstraction#
neith-gpu is the most critical crate in the HAL workspace: all rendering code
in Neith is written against the GpuDevice trait defined here, and never
against a concrete backend. Switching the backend (Vulkan → Metal, for example)
requires only changing the Backend variant passed at device initialization,
not rewriting any rendering code.
Source: hal/crates/neith-gpu/src/lib.rs (~1,566 lines). A self-contained
GPU abstraction — it defines its own backend, handle, and descriptor types
rather than wrapping wgpu.
The GpuDevice trait is the central abstraction. Concrete backends implement
it; renderer crates call it. The key enums, handle newtypes, and descriptor
structs below define the full vocabulary of the GPU API:
Backend—Vulkan,Metal,DirectX12,WebGPU,Software.DeviceType—Integrated,Discrete,Virtual(plus further variants).Vendor— GPU vendor identification.ShaderStage,ShaderSource.MemoryLocation,AllocationStrategy.CommandBufferState,Command.LoadOp,StoreOp,ImageLayout.TextureFormat.PrimitiveTopology,CullMode,FrontFace,PolygonMode.BlendFactor,BlendOp(Add,Subtract,ReverseSubtract,Min,Max).DescriptorType,QueueFamily,PipelineVariant,FenceState(Unsignaled,Signaled).
All GPU resources are referenced via opaque integer handle newtypes. This
prevents accidental mixing of handle types (e.g. passing a ShaderModuleHandle
where a PipelineHandle is expected) at compile time. The full set:
DeviceId(u32), ShaderModuleHandle(u64), AllocationHandle(u64),
CommandBufferHandle(u64), CommandPoolHandle(u64), RenderPassHandle(u64),
PipelineHandle(u64), PipelineLayoutHandle(u64), DescriptorSetHandle(u64),
DescriptorLayoutHandle(u64), QueueHandle(u64), FenceHandle(u64),
SemaphoreHandle(u64).
Descriptor / resource structs include DriverInfo, GpuDeviceInfo,
GpuCapabilities, ShaderModule, AllocationRequest, Allocation,
VmaAllocator (a VMA-style suballocator with
allocate(req: AllocationRequest) -> GpuResult<Allocation>), CommandBuffer,
CommandPool, AttachmentDesc, RenderPassDesc, RenderPass, BlendState,
GraphicsPipelineDesc, ComputePipelineDesc, Pipeline, DescriptorBinding,
DescriptorLayout, DescriptorSet, PipelineLayout, SubmitInfo, Queue,
Fence.
The device interface is the GpuDevice trait (Send + Sync). Concrete
backends provide a struct that implements this trait; renderer code holds
Arc<dyn GpuDevice> and calls only these methods:
pub trait GpuDevice: Send + Sync {
fn id(&self) -> DeviceId;
fn info(&self) -> &GpuDeviceInfo;
fn capabilities(&self) -> &GpuCapabilities;
fn backend(&self) -> Backend;
fn allocator(&self) -> &VmaAllocator;
fn create_shader_module(&self, source: ShaderSource, stage: ShaderStage, entry_point: &str) -> GpuResult<ShaderModule>;
fn create_command_pool(&self, family: QueueFamily) -> GpuResult<CommandPool>;
fn create_render_pass(&self, desc: RenderPassDesc) -> GpuResult<RenderPass>;
fn create_graphics_pipeline(&self, desc: GraphicsPipelineDesc) -> GpuResult<Pipeline>;
fn create_compute_pipeline(&self, desc: ComputePipelineDesc) -> GpuResult<Pipeline>;
fn create_descriptor_layout(&self, bindings: Vec<DescriptorBinding>) -> GpuResult<DescriptorLayout>;
fn create_descriptor_set(&self, layout: &DescriptorLayout) -> GpuResult<DescriptorSet>;
fn create_pipeline_layout(&self, desc_layouts: Vec<DescriptorLayoutHandle>, push_constants: Vec<(ShaderStage, u32, u32)>) -> GpuResult<PipelineLayout>;
fn create_fence(&self, signaled: bool) -> GpuResult<Fence>;
fn create_semaphore(&self, kind: SemaphoreKind) -> GpuResult<Semaphore>;
fn graphics_queue(&self) -> Option<&Queue>;
fn compute_queue(&self) -> Option<&Queue>;
fn transfer_queue(&self) -> Option<&Queue>;
fn profiler(&self) -> &GpuProfiler;
fn wait_idle(&self) -> GpuResult<()>;
}
A GpuInstance enumerates devices:
enumerate_devices(&self) -> &[Arc<dyn GpuDevice>]. GpuError is the failure
type (with GpuResult<T> alias) — variants include NoDevicesFound,
DeviceNotFound(DeviceId), UnsupportedBackend(Backend),
ShaderCompilation(String), OutOfMemory { requested, available },
NotRecording, NotExecutable, SubmissionFailed(String), SyncTimeout(u64),
FeatureNotSupported(String), InvalidHandle, PipelineLayoutMismatch, and a
descriptor-set out-of-bounds variant.
Other HAL crates#
The remaining six HAL crates follow the same pattern as neith-gpu: they define
a platform-agnostic trait or type set, with platform-specific backends hidden
behind it. Their sizes reflect their implementation scope:
neith-audio-hal(~1,301 lines) — audio device streams overcpal(CpalBackend); device enumeration and stream management.neith-input(~3,336 lines, two source files) — unified input event abstraction across keyboard, mouse, gamepad, touch and XR sources.neith-sensor(~671 lines) — IMU / sensor abstraction.neith-camera(~1,445 lines) — camera capture abstraction.neith-net-hal(~1,641 lines) — network-interface HAL.neith-storage(~1,586 lines) — async file I/O and storage abstraction.
net Workspace — Networking Stack#
The net workspace provides game-optimized networking that standard TCP/HTTP
libraries cannot deliver. Game networking requires sub-20ms latency, reliable
delivery without head-of-line blocking, lag compensation, and delta compression.
@neith/net addresses all of these. libs/neith/net/Cargo.toml pins hmac,
sha1, aes, ctr, and digest. The workspace contains four crates, each
targeting a different layer of the network stack.
neith-transport(~1,533 lines) — reliable-UDP transport: acknowledgement, retransmission, ordered/unordered channels, congestion control.neith-game-net(~1,422 lines) — game networking: client-side prediction, server reconciliation, snapshot interpolation, lag compensation, delta compression, interest management, RPC.neith-webrtc(~4,007 lines) — WebRTC data channels and media, including a STUN implementation.neith-http(~4,965 lines) — HTTP client/server stack.
renderer Workspace — Rendering, Physics, ECS, Scripting#
The renderer workspace is the largest and most complex workspace in Neith. Its 16 crates implement everything needed for a frame: the render graph that orchestrates pass ordering, the physically-based rendering pipeline, global illumination, post-processing, and the supporting runtime systems (physics, ECS, audio, scripting, animation) that determine what to render each frame.
libs/neith/renderer/Cargo.toml is a 16-member workspace. It pins bitflags
(features = ["serde"]), smallvec, slotmap, indexmap, ahash, notify
(file watching for hot-reload), petgraph, and bytemuck.
neith-render-graph — Frame Graph#
The frame graph is the central coordination mechanism for the entire rendering pipeline. Rather than calling GPU commands imperatively, renderer code declares passes and their resource dependencies as nodes in a directed acyclic graph. The frame graph compiler then automatically determines execution order (via Kahn topological sort), inserts GPU pipeline barriers, and aliases transient resources to minimize GPU memory usage. The result is that renderer crates never need to write manual synchronization.
Source: renderer/crates/neith-render-graph/src/ (22 files, ~7,256 lines). A
production-quality frame graph. Modules (each mapped to a build task in the
crate's own doc comment): graph (builder + compiled graph), lifetime
(resource lifetime management), compiler + compiler::ordering (Kahn
topological sort for pass ordering), aliasing (resource aliasing / memory
reuse), async_compute, transient, conditional (conditional passes,
FeatureFlags), debug (visualization), serial (JSON / msgpack
serialization), multiview (VR stereo), tiled (tile-based rendering),
profiler (GPU + CPU timings), dynamic_res (dynamic resolution scaling),
hot_reload, fragment_density (fragment density map attachments),
vulkan_mobile, resource (TextureDesc, TextureFormat), pass
(TextureAccess). The builder entry point is RenderGraphBuilder::new(name)
with add_texture, add_graphics_pass, etc.
neith-physics — Multi-Physics Simulation#
neith-physics is a fully self-contained physics engine with no dependency on
rapier3d or any other third-party physics library. It implements its own
sweep-and-prune/BVH broadphase, GJK/EPA narrowphase, and iterative constraint
solver from first principles. This gives Neith complete control over the physics
simulation step — including deterministic reproduction, custom constraint types,
and tight integration with the ECS component model — without being limited by
rapier3d's API surface.
Source: renderer/crates/neith-physics/src/ (12 files, ~10,062 lines). Modules:
rigid_body, character, vehicle, ragdoll, cloth, soft_body, fluid,
destruction, math, collision_merge, tilemap2d.
Math types (math module) are plain arrays: Vec3 = [f32; 3],
Vec4 = [f32; 4], Mat3 = [[f32; 3]; 3], Quat = [f32; 4], plus an Aabb
struct.
rigid_body module key types:
CollisionShapeenum —Sphere { r: f32 },Box { half: Vec3 },Capsule { r: f32, h: f32 },ConvexHull { verts: Vec<Vec3> },TriangleMesh { verts: Vec<Vec3>, tris: Vec<[usize; 3]> }.CompoundShape— a collection of shapes with local transforms.CollisionFilter { ... }—new(layer: u32, mask: u32); layer/mask filtering.PhysicsMaterial— restitution / friction material parameters.RigidBody— fieldspos: Vec3,rot: Quat,vel: Vec3,ang_vel: Vec3,mass: f32,inv_mass: f32,inertia_tensor_inv: Mat3,restitution: f32(default0.3),friction: f32(default0.5),force_accum: Vec3,torque_accum: Vec3.RigidBody::new(pos, mass)derivesinv_mass(0.0whenmass <= 0.0, i.e. a static body) and a diagonal inverse inertia tensor. Methodsapply_force(f: Vec3),apply_impulse(impulse: Vec3, contact_point: Vec3).JointTypeenum —Fixed;Hinge { axis: Vec3, limits: Option<[f32; 2]> };Slider { axis: Vec3, limits: Option<[f32; 2]> };Ball;Spring { rest_len: f32, stiffness: f32, damping: f32 }.Joint,MotorConstraint,BreakableJoint(new(joint, max_force)).SapBroadphase— sweep-and-prune broadphase;BvhTree/BvhNode— a BVH broadphase alternative.- Narrowphase:
gjk_closest_points(...),epa_penetration(...),generate_contacts(...), withContactInfo,ContactManifold,ManifoldCache. SleepState+update_sleep(...)+wake_body(...)— island sleeping.- Continuous collision detection:
ccd_sphere_sphere(...),ccd_aabb_aabb(...). InterpolatedTransform— physics-to-render interpolation.PhysicsWorld— the simulation container:PhysicsWorld::new(),add_body(body: RigidBody, shape: Option<CollisionShape>) -> usize,step(dt: f32).
Other renderer-workspace crates#
The remaining renderer crates each own a specific sub-pipeline. The source sizes below give a rough sense of implementation depth; all are real, substantial crates with domain-specific algorithms (not CRUD wrappers).
| Crate | Source size (approx.) | Scope |
|---|---|---|
neith-gpu-driven |
18 files, ~11,799 lines | GPU-driven rendering — frustum/occlusion/Hi-Z culling, indirect draws, persistent buffers. |
neith-gi |
22 files, ~11,834 lines | Global illumination — probes, SDF GI, reflections. |
neith-pbr |
9 files, ~7,175 lines | Physically based rendering — GGX BRDF, IBL, area lights. |
neith-postfx |
18 files, ~6,549 lines | Post-processing — TAA, SSAO/GTAO, bloom, DoF, tonemap. |
neith-virt-geom |
13 files, ~5,407 lines | Virtualized (Nanite-class) geometry — GPU-resident clusters. |
neith-gaussian-splatting |
20 files, ~5,992 lines | 3D Gaussian splatting renderer. |
neith-audio |
8 files, ~5,652 lines | Engine audio (within the renderer workspace). |
neith-material-graph |
8 files, ~4,733 lines | Node-based material graph. |
neith-animation |
7 files, ~3,775 lines | Skeletal / blend-tree animation. |
neith-lighting |
6 files, ~3,506 lines | Directional/point/spot/area lights, IES, clustered/deferred, MegaLights. |
neith-scripting |
4 files, ~2,863 lines | Multi-language scripting — Lua, WASM, visual scripting. |
neith-atmosphere |
13 files, ~2,804 lines | Atmospheric scattering, clouds. |
neith-shadows |
8 files, ~2,494 lines | Cascaded / point / soft shadows. |
neith-ecs |
5 files, ~2,181 lines | Archetype-based entity component system. |
ui Workspace — GPU-Accelerated UI Toolkit#
The ui workspace provides a self-contained, GPU-accelerated UI toolkit
independent of any web-technology stack. libs/neith/ui/Cargo.toml pins
accesskit 0.24 (for accessibility tree integration) and bitflags. The six
crates form a layered stack — neith-render2d and neith-text are the
rendering foundation, neith-layout positions elements, neith-widgets
provides controls, neith-animation handles motion, and neith-theme provides
the design token system.
| Crate | Source size (approx.) | Scope |
|---|---|---|
neith-widgets |
2 files, ~4,409 lines | Retained-mode widget library. |
neith-text |
1 file, ~2,495 lines | Font / text rendering, shaping. |
neith-theme |
1 file, ~2,331 lines | Design-token theming system. |
neith-render2d |
1 file, ~2,300 lines | GPU-accelerated 2D vector renderer. |
neith-layout |
1 file, ~1,913 lines | Flexbox / grid layout engine. |
neith-animation |
1 file, ~1,187 lines | UI animation (spring physics, gesture-driven). |
Build and Nx Integration#
Every Cargo workspace has a project.json exposing Nx targets via the
nx:run-commands executor. This lets the monorepo's Nx build graph treat Rust
crates as first-class projects alongside TypeScript packages — dependency
tracking, affected builds, and caching all work uniformly. The core
workspace's project.json is representative of the pattern; every other
workspace follows the same four-target structure:
| Nx target | Command |
|---|---|
build |
cargo build --release --manifest-path libs/neith/core/Cargo.toml |
test |
cargo test --manifest-path libs/neith/core/Cargo.toml |
lint |
cargo clippy --manifest-path libs/neith/core/Cargo.toml -- -D warnings |
fmt |
cargo fmt --manifest-path libs/neith/core/Cargo.toml |
Each workspace pins its toolchain via a rust-toolchain.toml file. The
standalone TypeScript packages instead carry a tsconfig.json, a Vitest config
(vitest.config.ts) where tests exist, and a tsup build config where they
ship a bundle (e.g. cloud/tsup.config.ts).
Because the worktree layout can produce duplicate Nx project names (each
worktree registers the same projects), Nx sometimes fails with a duplicate
project error. In that situation, bypass Nx entirely and run the Cargo commands
directly (cargo build/cargo test/cargo clippy) — the commands above work
identically when run from the workspace directory.
Sovereignty Invariant#
Neith is the lowest layer of the Oshun stack. The Rust workspaces import nothing
from other Oshun domains or libs/shared/ — they depend only on third-party
crates pinned in each workspace's [workspace.dependencies]. This keeps every
Neith crate independently buildable and embeddable outside the Oshun monorepo.
The invariant is enforced architecturally, not just by convention: because
libs/neith/ is a set of isolated Cargo workspaces, any attempt to add a
path-dependency on another Oshun domain would require adding it to the Cargo
manifest — which would be immediately visible in code review.
Downstream domains (Maya's game engine and metaverse layer, Bellona's
external-engine export bridges, and others) consume Neith crates; Neith never
depends on them. The TypeScript integration packages (@neith/integration-maya,
@neith/integration-bellona, etc.) provide the Neith → domain boundary for
TypeScript consumers; they are TypeScript libraries, not Rust crates, and do not
violate the sovereignty invariant.
Acceptance Criteria#
Every change to a Neith crate must pass all five criteria below before merging.
These checks are automated via the Nx lint, build, and test targets, but
the final review must verify criteria 4 and 5 manually.
A change to a Neith crate is acceptable when:
- The crate compiles under its workspace toolchain
(
cargo build --manifest-path libs/neith/<workspace>/Cargo.toml). cargo clippy -- -D warningsis clean for the workspace.- The crate's own
#[test]modules pass (cargo test); the foundational crates carry inlinemod testsexercising domain correctness (priority ordering, NBF round-trips, metric arithmetic, GJK/EPA contact generation, etc.). - New public types are added to the relevant crate
lib.rsre-export block so the workspace surface stays discoverable. - The sovereignty invariant holds — no dependency on other Oshun domains or
libs/shared/.
Planned Surface#
The Neith feature inventory (features.md) and TODO phases describe further
sovereign systems that extend beyond what is specified in this document.
Where directories already exist under libs/neith/ — for example
audio-runtime/, browser/, linux/, ai-runtime/, embedded/, vr-os/,
and the creative-tool and audio-suite workspaces — those workspaces are present
in source and inventoried in the workspace tables above. Their internal type
surfaces are described in features.md but not enumerated in full here.
Items in features.md for which no directory exists under libs/neith/ —
including the @neith/os-kernel, @neith/drivers, @neith/fs, and
@neith/pkg operating-system packages mentioned in Phase 45, and the named
packages of the Phase 132–174 sovereignty-closure roadmap that have no
corresponding folder — are (planned) and are not specified here. Any such item
added to the codebase should be inventoried in the workspace tables above and,
if it is part of the foundational six workspaces, have its public type surface
documented in this file.