Everything You Ever Wanted to Know About Level 0 Engine

The Definitive Architectural Codex, System Internals, Survival Field Manual, and Contributor Handbook

Vanilla ES6 Modules Three.js r160 (Vendored) Seeded Procedural Horror Zero Bundlers / Zero npm
The Three Inviolable Architectural Questions

In fidelity to the Level 0 Engineering Codex, every system, tool, and entity in this manual is evaluated through three lenses: What It Does (player behavior, visible manifestations, sensory feedback), How It Works (internal algorithms, web worker pipelines, DSP circuits, spatial indices), and Why It Works (psychological horror design, mathematical guarantees, and zero-allocation performance rules).


Book I: Systems Philosophy & Rules of Reality

1. The Soul of the Backrooms

In liminal fiction, the infinite yellow corridors of Level 0 are often mistaken for mere repetitive chaos. Level 0 Engine operates on a fundamentally different paradigm: The facility has memory, bureaucratic decay, and mathematical logic.

You are not wandering an abstract void; you are navigating a decommissioned corporate subterranean complex trapped in self-replicating spatial recursion. Fluorescent ballasts buzz at precise acoustic frequencies. Shift logs, coffee fund rosters, and disciplinary notices cling to desks and lockers. Behind every door lies not randomness, but a seeded deterministic world where truth can be excavated through careful fact-finding.

The Core Axioms of Level 0
  1. No Bundlers, No Build Step for Development: The repository serves directly to the browser via ES6 modules. What you edit is immediately what executes.
  2. Determinism Over Randomness: Every corridor, prop, document, and entity spawn is derived mathematically from a 32-bit seed. A single seed produces the exact same labyrinth across machines.
  3. Hot Paths Never Allocate: The player tick, collision detection, and entity perception loops operate with preallocated scratch vectors. Zero garbage collection stuttering during moments of horror.
  4. The Player is an Investigator, Not an Action Hero: Survival is attained through patience, kinetic battery management, stealth, and corroborating fragmented documentary claims.
  5. Verified Means Observed: Claims are invalid until proven by automated headless browser smoke tests or in-engine diagnostic instrumentation.

2. The Zero-Bundler Imperative

Modern web development frequently buries simple 3D experiences beneath brittle stacks of Webpack, Vite, Babel, and node_modules dependencies. Level 0 Engine rejects this ceremony.

All engine code runs as pure, un-transpiled ES6 modules loaded natively by modern browser engines. A lightweight Node HTTP server (engine_server.js) serves static files and injects cross-origin isolation headers. THREE is provided as a trusted global via locally vendored r160.js (Decision D-001). There is zero compilation time, zero bundler configuration drift, and zero risk of supply-chain package compromise.

3. Determinism as Law

In Level 0 Engine, pseudo-randomness is divided into two strict categories:

4. The Cold Case & Fact-Finding

Unlike generic survival games with arbitrary keys, Level 0 centers on the Finding of Fact. Each seed generates a cold case surrounding a missing staff member. Documents scattered throughout the facility make specific documentary claims regarding rules, dates, and names.

Uncorroborated documents induce Paranoia, which physically degrades your kinetic flashlight's battery ceiling. To escape, the player must corroborate claims across disparate macro sectors, assemble the 4-digit PIN for the blast elevator, and submit the cold-case truth at the final Inquest Terminal.


Book II: The Engine Room & Architecture

Level 0 Engine is structured into decoupled, single-responsibility ES6 modules connected through a centralized runtime orchestrator (Environment.js).

+-----------------------------------------------------------------------------------+
|                                  BROWSER RUNTIME                                  |
|                                                                                   |
|   index.html  ==>  engine.html  ==>  r160.js (THREE Global) + purify.min.js       |
|                                         |                                         |
|                                         v                                         |
|                                      main.js                                      |
|                                         |                                         |
|                                         v                                         |
|                             src/core/Environment.js                               |
|                                (THE ORCHESTRATOR)                                 |
|                                         |                                         |
|        +--------------------------------+--------------------------------+        |
|        |                                |                                |        |
|        v                                v                                v        |
|  RenderEngine.js                ChunkManager.js                  PlayerController |
|  - WebGLRenderer                - ChunkStreamer (Queue)          - SomaticInput   |
|  - PostProcessing (CRT/Aberr)   - ChunkBuilder (Mesh)            - Flashlight     |
|  - LumenGrid (Area Lights)      - ChunkWorker.js (Worker)        - Compass        |
|        |                                |                                |        |
|        +--------------------------------+--------------------------------+        |
|                                         |                                         |
|        +--------------------------------+--------------------------------+        |
|        |                                |                                |        |
|        v                                v                                v        |
|  EntityManager.js               StoryEngine.js                   AcousticEngine   |
|  - Anomaly (Roaming)            - data/*.json Dealing            - Web Audio DSP  |
|  - Sector Entities              - CaseFiles & Clues              - Wall Occlusion |
|  - SpatialHashGrid              - JSEP Condition Evaluator       - Foley / Mixer  |
+-----------------------------------------------------------------------------------+

5. Julia Maze & Chunk Streaming Pipeline

Files: src/world/ChunkManager.js, ChunkStreamer.js, ChunkBuilder.js, ChunkWorker.js

What It Does

Dynamically streams an infinite 3D labyrinth around the player in fixed-size chunks (typically 16×16 cells), building and tearing down geometries in real time without dropping frames.

How It Works
  1. Offloaded Math: ChunkStreamer tracks the player's grid coordinates and calculates chunks within streaming radius. Requests are dispatched to ChunkWorker.js running on a separate Web Worker thread.
  2. Julia Set Formulation: The worker computes wall topologies by iterating a 2D complex rational map. Cells where \(|z| > \text{threshold}\) collapse into walls, while interior coordinates carve out open hallways.
  3. Geometry Synthesis: ChunkBuilder receives cell matrices from the worker, applies macro sector rules from Sectors.js, selects structural blueprints from StructuralBlueprints.js, and stitches meshes via StructureKit.js.
  4. Batch Disposal: As chunks exit the streaming envelope, buffers, collision lines, and dynamic light instances are cleanly disposed of to reclaim GPU VRAM.
Why It Works

Offloading fractal computation to a web worker guarantees that the main JavaScript execution thread never hitches. The render loop maintains locked 60fps even as massive macro sectors materialize on the horizon.

6. LumenGrid & Shadow Hysteresis

Files: src/aesthetics/LumenGrid.js, src/aesthetics/RectAreaLightUniforms.js

What It Does

Manages the atmospheric illumination of Level 0, powering fluorescent ceiling panels, emergency strobe conduits, breaker blackout cascades, and cast shadows.

How It Works
  1. Ceiling Area Lights: Utilizes vendored RectAreaLightUniformsLib to simulate rectangular diffuse fixtures without the sharp artificial artifacts of point lights.
  2. Fixed Shadow Caster Pool: Real-time shadows on mobile and integrated GPUs are expensive. LumenGrid maintains a strictly capped budget (e.g., 4 active shadow casters) allocated by proximity to the player camera.
  3. Distance Hysteresis: Lights crossing the shadow-caster threshold utilize a 2-unit hysteresis buffer, preventing visible shadow popping when the player oscillates near a boundary.
Why It Works

Enforces hardware performance predictability. The engine achieves rich, claustrophobic volumetric atmosphere while respecting mobile WebGL texture unit and shadow map limits.

7. Web Audio DSP & Real-Time Occlusion

Files: src/audio/AcousticEngine.js, Mixer.js, Foley.js

What It Does

The auditory heart of Level 0. Synthesizes procedural room tones, footstep impacts, fluorescent hums, heartbeat adrenaline pumps, and physically muffles sound when blocked by walls.

How It Works
  1. Procedural Synthesis: Tone generators create layered sine, sawtooth, and filtered noise sources for the fluorescent hum (60Hz ground hum with micro-phase harmonics).
  2. Raycast Occlusion Filter: When spatial audio sources (e.g. entity groans or radio static) emit, AcousticEngine casts rays through the SpatialHashGrid to the player. Each intersecting wall applies an exponential low-pass BiquadFilter, creating realistic wall dampening.
  3. Exhaustion DSP: When the player sprint stamina or oxygen runs dry, a master dynamics compressor and low-pass filter squashes world audio, elevating internal bodily respiration and erratic heartbeats.
Why It Works

Horror relies more heavily on acoustics than visuals. Hearing an entity's muffled gait around two corners prompts genuine dread, informing player tactical decisions before visual contact occurs.

8. Procedural Canvas Textures & Material Library

Files: src/aesthetics/ProceduralTextureFactory.js, MaterialLibrary.js

What It Does

Generates all wall, floor, ceiling, and metal textures dynamically at runtime via HTML5 Canvas 2D drawing routines, with zero network asset downloads.

How It Works
  1. Canvas Synthesis: ProceduralTextureFactory draws perlin noise, stained watermarks, worn wallpaper seams, subway tile grout, and acoustic tile perforations onto off-screen canvas elements.
  2. Mipmap Generation: Canvases are converted to THREE.CanvasTexture instances with anisotropic filtering enabled, and cached in MaterialLibrary.js.
  3. Static Fallback: If WebGL context creation constraints or dev tuners require it, textures can fall back to pre-baked PNGs in assets/textures/.
Why It Works

Shrinks initial page load to under 2 megabytes while eliminating HTTP request roundtrips. Every surface carries procedural variation, avoiding obvious tiling repetition.

9. Dual-Key LocalStorage Persistence

Files: src/system/SaveManager.js

What It Does

Maintains player session progress, active cold-case leads, gathered document inventory, pulled surge breakers, and custom engine settings.

How It Works
  1. Dual-Key Safeguard: Before writing new game state to localStorage['level0_state'], SaveManager copies the existing state to level0_state_backup.
  2. Integrity Check: On engine boot, JSON parsing is wrapped in strict try/catch blocks. If corruption is detected, the backup is automatically restored, and telemetry logs a warning.
  3. Purge Mechanics: "Purge Memory" resets the session while preserving player settings; "Purge & Start New Game" restores baseline seed state.
Why It Works

Protects player progress against accidental browser closures, battery failures, or localStorage write crashes.


Book III: Procedural Topography & Macro-Sectors

The maze hierarchy operates in three distinct structural tiers:

10. Zone Bounds & Blast Thresholds

Files: src/world/ZoneBounds.js, src/world/AirlockApron.js, src/world/AirlockLayout.js, src/world/SectorPlacement.js, src/world/SetPieces.js

What It Does

Governs the volumetric fog, acoustic transitions, and heavy mechanical blast doors that seal macro sectors from the surrounding Backrooms.

How It Works
  1. Boundary Sealing: Every macro sector is sealed by exactly one true blast threshold at its entry boundary.
  2. Airlock Apron: AirlockApron.js bridges the transitional corridor, aligning subway tiles and corner pillar materials between sectors. Every sector chunk has one airlock per side at a fixed cross-cell (AirlockLayout.js), so neighbouring maze chunks derive those positions from the seed instead of waiting for the sector to build.
  3. Volumetric Interpolation: As the player crosses the apron threshold, AtmosphereManager lerps fog color, density, and ambient lighting smoothly over 2.5 seconds, eliminating jarring visual pops.
Why It Works

Gives the player a palpable sense of entering a new hazardous subterranean biome, providing clear spatial landmarks in an infinite world.

11. The 14 Macro Sectors Tour

Files: src/world/sectors/*.js, src/world/Sectors.js

What It Does

The facility comprises 14 distinct themed macro zones, each featuring custom architectural blueprints, ambient color schemes, and narrative props.

How It Works
Sector Visual Identity Atmosphere & Fog Key Features
NORMAL Classic Level 0 mono-yellow wallpaper, damp carpet Warm amber tint, moderate falloff Starting hub, foundational transitional corridors
ARCHIVE Endless rows of steel file stacks, sorting tables Muted sepia dust fog Dense paper documents, Archivist entity presence
ATRIUM Soaring vertical courtyards, skylights, railings Pale blue ethereal glow, low drag Multi-level verticality, echoed acoustic reverb
ANNEX Low drop-ceiling sterile cubicles, fluorescent tubes Harsh institutional white haze Broken office amenities, cubicle mazes
ACME High-voltage research wing, warning hazard stripes Electric cyan tint, ozone hum Prototype test chambers, breaker relays
BOARDROOM Mahogany wall paneling, conference tables, drapes Deep burgundy shadow, dead silence Executive cold-case files, encrypted safes
CHASM Sheer drop-offs, suspended steel catwalks Pitch black bottomless void Narrow footing, falling hazards, vast reverb
CHECKPOINT Reinforced security gates, turnstiles, guard booths Cold slate grey, security strobes Warden entity patrols, keycard readers
CLINIC Bleached ceramic tiles, gurneys, surgical lamps Sterile pale green wash Medical logs, biohazard quarantine lockers
EXIT Reinforced blast bunker, airlock bulkheads Heavy emergency red floodlights The Inquest Terminal, final elevator airlock
IMPOUND Chain-link fence cages, tagged evidence lockers Dirty amber sodium-vapor fog Seized artifacts, classified staff dossiers
INCINERATOR Charred brick, floor grates over magma vents Thick red smoke, heat wave distortion Incinerator entity, burned record scraps
MAINTENANCE Exposed steam pipes, concrete conduits, floor puddles Humid yellow condensation mist Crawlspace ducts, sump pumps, tight vents
SERVER Towering server racks, blinking optical LEDs Deep cobalt blue, sub-zero chill Backup Daemon entity, mainframe terminals
Why It Works

Diverse biomes prevent visual fatigue, give players cognitive maps of their exploration progress, and provide thematic contexts for cold-case evidence.


Book IV: Survival Field Manual (How to Play)

12. The Opening: Arrival, Sighting & First Breaker

Files: src/narrative/OpeningDirector.js, src/narrative/OpeningPlan.js, src/world/ElevatorSpawn.js

What It Does

Every new run starts in an arrival car and plays a short scripted sequence. The car settles and the doors release. You glimpse something at the end of a hall. The objective comes online, and the first breaker is close enough to reach before the facility starts hunting you. A resumed save skips all of this and puts you back where you left off.

How It Works
  1. Arrival: The car is lit at a quarter of normal ambient light, as emergency lighting. On a first run the flashlight starts half charged. The car rumbles, dings at 4.2 s, and releases its doors at 5 s. Returning players enter the override code from the maintenance note on the wall until the keypad remembers it.
  2. The Objective Comes Online: The RESTORE POWER line and the POI signal stay hidden until you step out of the car.
  3. The Sighting: When you step out, the director looks for open cells within 24 m of the car that have a straight sight line of at least 16 m, outside every sector. The one nearest the car wins. The first time you look down that corridor in the next 45 s, the Anomaly stands at its far end, 12 to 24 m away. After 1.8 s, or sooner if you close to 9 m, the lights stutter and it is gone. It cannot hurt you here: it is still in its grace period.
  4. The First Breaker: The first hunt points straight at a breaker podium planted 28 to 56 m from the seed's spawn point. Later hunts may send you through 0 to 2 Points of Interest first, then to a podium placed further ahead.
  5. Grace From The Doorway: The Anomaly's 90 s grace period does not start until you leave the car, so the first real hunt comes about a minute and a half after you step out, however long you spend reading.
  6. Learning The Crank: The first time your flashlight dies, a one-time hint explains how to recharge it.
Why It Works

The first minute decides whether a player, or a stream's audience, stays. The opening shows you the threat before it can reach you, then gives you a goal you can achieve quickly. The sighting is chosen from the layout around the car, not from your route, so everyone on a shared seed sees the same corridor. Each beat logs an [OPENING] timing mark to the console and to the Debug HUD's OPEN line, so the pacing can be measured on any seed.

13. The Kinetic Flashlight & Crank Physics

Files: src/player/Flashlight.js, src/player/SomaticInput.js

What It Does

Your primary survival instrument and psychological shield. The heavy flashlight illuminates dark corridors and freezes the Anomaly in its beam, but rapidly drains power.

How It Works
  1. Kinetic Charging: The flashlight has no disposable batteries. It is charged mechanically by sprinting (converting movement inertia) or by rapidly shaking the camera (cranking the dyno mechanism). It only charges while switched off, never past its ceiling of 100% minus accumulated paranoia, and not during the 10 s cooldown after it runs flat. A first run starts at 50%.
  2. Parabolic Beam: Casts a focused central beam with quadratic distance attenuation and a wider subtle ambient cone.
  3. Flicker Warning: When charge drops below 15%, the bulb begins irregular brownout flickers, reducing beam efficacy and triggering entity agitation.
Why It Works

Forces dynamic physical engagement. Recharging demands noisy, erratic actions (shaking or running) that risk attracting nearby entities, creating high-tension tactical dilemmas.

14. Paranoia & The Corroboration Loop

Files: src/narrative/StoryEngine.js, src/player/PlayerController.js

What It Does

A direct mechanical bridge connecting narrative discovery with player physical survival. Reading uncorroborated documents increases Paranoia, which places a hard cap on your maximum flashlight battery charge.

How It Works
  1. Unverified Claims: When you read a document making an uncorroborated claim (e.g. "Rule 14 was enacted in 1984"), paranoia ticks up, capping battery maximum to 80%, 60%, or lower.
  2. Cross-Sector Corroboration: To bleed off paranoia and restore full battery capacity, you must explore and locate a second document in a different macro sector that corroborates the identical claim.
  3. Resolution: Corroborated claims turn green in your PDA Journal (J), permanently dispelling paranoia and solidifying an objective truth for the Inquest.
Why It Works

Prevents lore from being treated as passive background decoration. Reading and understanding the narrative is a mandatory survival requirement.

15. Somatic Movement, Exhaustion & Compression

Files: src/player/PlayerController.js, src/system/SomaticController.js

What It Does

Models realistic physical presence: inertia, footstep cadence, wall impacts, and squeezing through tight bottlenecks.

How It Works
  1. Wall Collisions & Camera Trauma: Crashing into walls at high speed jolts the camera with physics trauma, triggers a heavy dull thud, and rattles your flashlight.
  2. Terminal Exhaustion: Sprinting burns oxygen twice as fast. When exhausted, the player stumbles, hearing muffled breathing DSP, while their hearing radius expands—making them easier for the Anomaly to detect.
  3. Compression Mode (Q): Pressing Q lowers your camera and narrows collision extents, allowing you to compress through tight ductwork, collapsed crevices, and floor vents.
Why It Works

Grounds the player in a fragile physical body. You cannot simply sprint blindly through corridors without suffering disorientation and acoustic penalties.

17. The Assembled Lock & Inquest Escape

Files: src/ui/InquestController.js, src/world/sectors/ExitSector.js

What It Does

The ultimate victory condition of Level 0 Engine. Unlock the blast elevator, submit the Finding of Fact, and ascend to the surface.

How It Works
  1. The 4-Digit Assembled Lock: The exit elevator door is sealed by a mechanical PIN assembled from three distinct clues scattered across the complex: the Rule Number, the Enactment Year, and the Pen Color Code.
  2. The Finding of Fact: At the glowing green terminal inside the Exit Bunker, you are prompted to present the true sequence of events regarding the cold case.
  3. Chat's Verdict (Streamer Mode): With streamer mode connected to a Twitch channel, viewers vote while the terminal is open with !1, !2, !3 or !vote N, one vote each. The terminal shows the tally, and pressing 4 files chat's leading finding. A tie files nothing.
  4. The Elevator Ascent: Entering the correct PIN and fact finding activates the elevator winch, locking the doors and triggering the victory sequence.
Why It Works

Transforms escape into an intellectual triumph. Victory requires both physical mastery of the maze and mental mastery of its lore.


Book V: Hazards, Entities & Phenomena

18. The Anomaly (The Roaming Predator)

Files: src/entities/Anomaly.js

What It Does

The default macro predator of Level 0. A fast, relentless entity that roams the halls hunting the player by acoustic signature and line-of-sight.

How It Works
  1. Acoustic Hearing Radius: Calculates player noise generation (sneaking: 2m, walking: 8m, sprinting: 20m, terminal exhaustion stumble: 35m).
  2. Direct Flashlight Observation Freeze: When illuminated by the active flashlight with clear line of sight, distance under 25 m, and a dot product above 0.85 (the central ~31.8° forward cone), the Anomaly freezes in place, screeching with rage.
  3. Rage Buildup: Freezing is temporary. Each second the beam holds it, the Anomaly accumulates rage. When your battery flickers out or you look away, it surges forward with increased velocity!
  4. Grace Period: After every reset (a new run, a respawn, or leaving a sector) the Anomaly waits 90 s before it hunts or hears anything. On a new run that clock starts when you step out of the arrival car. When it resumes prowling it reappears 40 to 55 m from you.
  5. Proximity Aberration: As it approaches, the screen suffers severe chromatic aberration, audio crushing, and claustrophobic vignettes.
Why It Works

Inverts conventional horror tropes: facing the monster saves you, but locks you in a terrifying staredown while your flashlight battery drains towards zero.

19. Sector-Locked Entities

Files: src/entities/*.js

What It Does

Specialized entities bound to specific macro sectors, enforcing unique behavioral hazards.

How It Works
  • The Archivist (Archive Sector): Spectral entity that patrols between file stacks, homing in on the sound of footsteps and document pickups.
  • Backup Daemon (Server Sector): High-voltage construct that teleports along cable runs, predicts player velocity, and launches electrical shard bursts.
  • The Claw (Atrium Sector): Ceiling-mounted motorized gantry that drops a four-pronged hydraulic claw when players linger in central courtyards.
  • Incinerator Entity (Incinerator Sector): Thermodynamic molten core predator that chases aggressively while radiating stamina-sapping heat.
  • Sentry Cone (Maintenance Sector): Tripwire construction hazard that wakes on breaker trips or pylon collisions, pursuing at 4.2 m/s with multi-tier steering.
  • The Warden (Impound Sector): Heavily armored monolithic juggernaut that smashes through chain-link fences during cage patrols.
Why It Works

Forces the player to adapt their survival strategies as they transition between different sector biomes.

20. Surge Breakers & Blackout Cascades

Files: src/world/BreakerPodium.js, src/world/sectors/MaintenanceSector.js, src/player/InteractionController.js

What It Does

Heavy high-voltage electrical levers found on walls. Pulling them with E disrupts local facility power, opening secured airlocks while plunging sectors into pitch blackness.

How It Works
  1. Blackout Cascade: Pulling the lever instantly shatters local fluorescent tubes with particle debris and sound FX.
  2. Cascade Delay: Neighboring lights sequentially extinguish down the hall in a terrifying domino wave.
  3. Emergency Reboot: After a timed blackout duration, emergency amber or red warning strobes initiate an irregular flicking reboot sequence.
Why It Works

Delivers visceral, player-initiated environmental shock. You must willingly plunge yourself into total darkness to progress through locked gates.

21. Liminal Breaches, Faraday Cages & Ephemera

What It Does

Rare anomalous environmental fixtures providing sanctuary, spatial shortcuts, or atmospheric world-building.

How It Works
  • The Faraday Cage: A rare, copper-plated room blueprint completely shielded from entities. Step inside to recharge your flashlight, check your journal, and catch your breath in total safety.
  • Liminal Breaches: Procedural stairwells have a 25% chance to spawn as open breaches, allowing you to warp thousands of units across the grid without mutating the underlying seed.
  • Ephemera: Coffee funds, lost wedding rings, and shift schedules scattered near the Exit Bunker. They carry no claims or PIN digits—they are haunting human echoes of the missing workforce.
Why It Works

Provides necessary moments of emotional reprieve (Faraday Cages) and deepens the tragic human context behind the corporate facility.


Book VI: Narrative & Story Engine

22. Seeded Narrative Dealing

Files: src/narrative/StoryEngine.js, data/*.json

What It Does

Generates a coherent, non-repeating cold-case mystery from thousands of narrative fragments stored in JSON data files.

How It Works
  1. Card Dealing: On level generation, StoryEngine creates a shuffled deck of clues, foreshadowing snippets, and lore logs seeded by the level seed.
  2. Data Repositories: Draws from clues.json, lore.json, foreshadow.json, finales.json, and ephemera.json.
  3. Placement: Distributes documents onto generated desks, file cabinets, and clipboards as chunks materialize around the player.
Why It Works

Ensures that no two runs tell the exact same story, while guaranteeing that essential clues required to assemble the PIN code are always placed in reachable sectors.

23. Prop Attachment & Evidence Types

Files: src/world/NarrativeProps.js, src/narrative/CaseFiles.js

What It Does

Spawns tangible 3D interactive props that carry written or recorded testimony.

How It Works
  • Sticky Notes & Paper Files: Simple paper notes fixed to walls and clipboards.
  • Rugged Laptops: Glowing screens displaying terminal email logs and staff memos.
  • Reel-to-Reel Tape Recorders: Interactive audio logs that play voice transcripts via text and muffled audio cues.
Why It Works

Grounds narrative in physical space. Documents are not abstract UI popups, but tangible objects found sitting in the world.

24. JSEP Logic & Safe AST Templating

Files: src/utils/SafeEval.js, lore-editor/js/rendering.js

What It Does

Safely evaluates complex display conditions (e.g. ctx.sector === 'ANNEX' && c.lead) and templates variables into text without dangerous JavaScript eval() or new Function().

How It Works
  1. Vendored JSEP: Expression strings are parsed into an Abstract Syntax Tree (AST) using vendored jsep.min.js.
  2. AST Walk: SafeEval.js evaluates identifiers and operators against a sanitized context object.
  3. XSS Sanitization: Before rendered text touches the DOM, it is passed through vendored purify.min.js (DOMPurify).
Why It Works

Enforces complete security isolation (Decision D-001). Community lore expansions or user-edited JSON files cannot execute arbitrary JavaScript in the player's browser.


Book VII: Developer Tooling & The Lore Editor

25. The Standalone Lore Editor (Port 3000)

Files: lore-editor/index.html, editor_server.js, coverage.js

What It Does

A dedicated visual web application for authoring, editing, and validating the game's narrative JSON databases without touching engine code.

How It Works
  1. Dedicated Server: Launched via ./start_editor.sh (Node server listening on port 3000).
  2. Data Synchronization: Reads from and writes directly to data/*.json on disk.
  3. Coverage Report: Features a built-in Coverage view aggregating total available entries per sector, warning writers when sector pools are running thin.
  4. Factory Reset: Backed by data/factory/ as an immutable reset baseline.
Why It Works

Empowers narrative writers and designers to expand the game's lore without needing 3D graphics or Three.js programming experience.

26. AST Pre-Save Validation

Files: lore-editor/js/rendering.js

What It Does

Intercepts Lore Editor saves and verifies that all conditions, variables, threads, and sector references exist, preventing broken entries from entering the game.

How It Works
  1. Pre-Save Hook: When the author clicks "Save", runPreSaveConditionChecks parses all condition expressions with JSEP.
  2. Cross-File Audit: Verifies that every referenced variable exists in parameters.json, every thread in threads.json, and every sector in Sectors.js.
  3. Save Abort: If an unknown identifier is detected, saving is aborted with a clear diagnostic dialog.
Why It Works

Guarantees data integrity at the authoring boundary, catching typos before they can manifest as runtime errors during gameplay.

27. In-Engine Atmosphere & Light Tuners

Files: src/ui/AtmosphereTuner.js, LightTuner.js, SectorTunerFactory.js

What It Does

Live, in-game developer sliders that allow real-time tuning of fog density, light intensity, and colors, with instant disk persistence.

How It Works
  1. Interactive UI: Pressing dev keys displays interactive sliders over the 3D viewport.
  2. Disk Save: Clicking "Save to Disk" dispatches POST requests to /save-light or /save-atmosphere on engine_server.js.
  3. Source Rewriting: The server parses and updates the source code of Sectors.js directly on disk!
Why It Works

Eliminates the tedious loop of tweaking numbers in code, reloading, and checking. Lighting designers can sculpt the horror atmosphere directly inside the running scene.


Book VIII: The Proving Ground

"Verified Means Observed"

In Level 0 Engine, code that looks correct in a code review is not considered complete until it has been proven by automated observation in a real browser engine.

28. Headless Playwright Smoke Tests

Files: test/p4_01_smoke.test.js

What It Does

An automated headless Chromium integration suite that launches the game, traverses all 14 macro sectors, and verifies procedural generation is completely error-free.

How It Works
  1. Headless Boot: Spawns Chromium via Playwright, loads http://localhost:8080/engine.html, and monitors console errors.
  2. Targeted Sector Warp: Extracts explicit chunk coordinates from SectorPlacement.js for fixed seed 0x12345678. Warps camera to each sector and forces ChunkStreamer generation.
  3. Assertion Matrix: Verifies that all meshes, materials, and lights compile without WebGL warnings or uncaught exceptions.
Why It Works

Guarantees that generator changes or sector refactors cannot silently introduce broken imports or geometry synthesis crashes.

29. Frame-Time Baseline Budgets

Files: test/perf_baseline.json

What It Does

Enforces an automated CPU generation budget across all sectors to prevent performance regressions from creeping into the engine.

How It Works
  1. Timing Capture: During headless smoke runs, the test measures total milliseconds spent in environment.genStats.totalMs.
  2. Baseline Comparison: Compares results against stored measurements in test/perf_baseline.json.
  3. Regression Gate: If CPU generation time regresses by more than 1.5x against the baseline, the test suite fails automatically.
Why It Works

Keeps procedural generation lean and fast, ensuring low-end laptops and mobile browsers maintain silky 60fps performance.


Book IX: Contributor's Protocol

30. Engineering Conventions & Invariants

What It Does

Strict software engineering rules governing all code contributions to the repository.

How It Works
  • No Per-Frame Allocations: Hot paths (player movement, entity pathfinding, spatial hash queries) must reuse preallocated scratch vectors. Never call new THREE.Vector3() inside render loops!
  • Pure ES6 Modules: Never add bundlers, transpilers, or Babel configurations.
  • THREE is a Global: Never write import * as THREE from 'three'. The global is supplied by r160.js.
  • Sum to 1.0000: Probabilities registered in StructuralBlueprints.js must sum to exactly 1.0000.
Why It Works

Preserves maximum performance, eliminates GC stuttering, and keeps the engine universally runnable in any browser without build tooling.

31. Protected Areas & Conventions

What It Does

Guards critical repository files against accidental modification.

How It Works
Path / Area Rule Rationale
r160.js, jsep.min.js, purify.min.js Never edit by hand Vendored third-party libraries (Decision D-001)
data/factory/ Never edit without permission The Lore Editor's immutable factory-reset baseline
build/ Do not commit to git Output of npm run build
Why It Works

Maintains clean boundaries between project code, third-party libraries, and generated artifacts.

32. Single-Maintainer Git Workflow

What It Does

The process for landing changes directly on master.

How It Works
  1. Direct-to-master workflow managed by maintainer gordonk.
  2. Commit format uses the release version number (e.g. 1.5.8.9). Release numbers are internal (D-009): they live in docs/CHANGELOG.md, package.json and commit messages, never on public pages, and tools/check_docs.py enforces it.
  3. Before committing, run python3 tools/check_docs.py and npm test.
  4. Update docs/CHANGELOG.md and docs/HANDOFF.md with every functional change.
Why It Works

Keeps git history concise, transparent, and aligned with release tags.


Technical Appendices

Appendix A: Master Controls & Keybindings Matrix

Key / Input Action System / Subsystem
W, A, S, D Move forward, strafe left, move backward, strafe right PlayerController.js
Mouse Movement First-person camera pitch and yaw PlayerController.js
Left Click Interact (pickup documents, pull breakers, use terminals, open doors) InteractionController.js
Shift Sprint (burns oxygen, recharges flashlight kinetically) PlayerController.js, Flashlight.js
Q Compress / Crouch (squeeze through tight ducts, crevices, vents) PlayerController.js
F Toggle Kinetic Flashlight on/off Flashlight.js
E Pull Surge Breakers / Activate Machinery InteractionController.js
M Raise Threshold Compass (points to nearest sector / exit bunker) Compass.js
J Open PDA Journal (review gathered lore, leads, virtual cursor) JournalViewer.js
P Equip Paintball Gun (fire luminescent UV maze markers) PaintballGun.js
Tab Open Engine Settings Panel (aspect ratio, resolution, fog, seed) Environment.js, UIManager.js
Menu → Copy Link Copy a link that starts this run's seed from the beginning (blackout and floor suffixes removed) SeedLink.js, main.js
Menu → Rebuild Geometry Rebuild the seed's world around you in place; position and run progress are kept Environment.js
Menu → Streamer Mode Show the seed and chat panel, read a Twitch channel's chat anonymously, and let chat vote on the Inquest (!1-!3) or trigger !blackout and !lure StreamerMode.js, TwitchChat.js
Menu → Ghost Runs Show a translucent ghost of your best run on this seed (or an imported one), export it as a file, or import someone else's GhostRuns.js, GhostCodec.js
4 (at the Inquest) File chat's leading finding (streamer mode only) StreamerMode.js
X Capture Clean Screenshot (PNG download) RenderEngine.js
` (Backtick) Toggle Debug HUD (FPS, draw calls, active chunk coordinates) DebugHUD.js
G Toggle God Mode (Dev cheat: collision off, fly speed) PlayerController.js
Z Sector Warp (Dev cheat: cycle between macro sectors) Environment.js

Appendix B: URL Debug Flags & Parameters

Query Flag Values Effect
?seed=<str> Any string (64 characters at most) Starts a new run on this seed. Works on terminal.html and engine.html. If a different session is saved, the continue prompt offers to resume it or start the linked seed.
?seed=daily Keyword Starts the daily seed: a five-card hand dealt from the UTC date, the same for everyone that day
?ssaodebug normal, ao Renders raw normal buffer or ambient occlusion buffer for debugging
?logdepth Boolean toggle Enables logarithmic depth buffer for massive render view distances

Appendix C: Sectors.js Registry Schema

// src/world/Sectors.js schema structure:
export const SECTORS = {
    NORMAL: {
        hasMaze: false,
        anomalyAllowed: true,
        rectLightIntensity: 2.35,
        shadowRadius: 3.25,
        lightRange: 2.15,
        lightColor: 0xffffff,
        lightIntensity: 1.05,
        fogColor: 0xa6a6a6,
        fog: 0.015,
        ambient: 0.3,
        groundColor: 0xededed,
        ambience: {
            noise: 0.0, rumble: 60, freq: 250, freqOcc: 120, whine: 0.0005, dynamicWhine: true
        },
        foley: { oscFreq: 85, filterType: 'lowpass', filterFreq: 1200, gain: 0.09, attack: 0.02, decay: 0.11 },
        reverb: { rt60: 0.8, predelay: 0.010, wet: 0.14 }
    },
    ARCHIVE: { ... },
    ATRIUM: { ... },
    // 14 macro sectors defined
};

Appendix D: Saved State Schema

// localStorage['level0_state'] JSON structure (SaveManager.js):
{
    "px": 12.4, "py": 1.2, "pz": -45.8,
    "rx": 0.0, "ry": 1.57,
    "stamina": 100, "battery": 85.0,
    "flashlightActive": true,
    "isCrouching": false, "isCrawling": false,
    "hasExitKey": false, "depth": 3, "bestDepth": 5,
    "seed": "0x12345678",
    "aspect": "1.3333333333", "fog": "5", "fov": "75", "speed": "100", "res": "1.0",
    "shadows": "high", "shadowLights": "6", "renderDist": "1",
    "vol": "100", "gamma": "70", "aa": "4", "fxaa": true, "post": true,
    "headBob": true, "ssao": false,
    "macroChunks": ["0,0", "1,0", "0,1"],
    "discoveredSectors": [["NORMAL", 1700000000000], ["ARCHIVE", 1700000050000]],
    "story": { "cluesFound": [], "corroborated": [], "locks": [] }
}