# Quantum Forge Documentation > Full documentation for building games with real quantum mechanics. Quantum Forge is a quantum simulation SDK for game developers, available for TypeScript/Web (npm) and Unity (UPM). This site documents the complete API, quantum mechanics concepts, framework tools, and showcase games. ## Getting Started ### TypeScript/Web Scaffold a new project. The CLI ships in the ENGINE package. From core 2.7.0 `npx quantum-forge init` works too (the core package hands off to the engine); older core releases have no bin and fail. ```bash npx quantum-forge-engine init my-game ``` Non-interactive (CI, containers, AI agents). Pass every flag and nothing prompts: ```bash npx -y quantum-forge-engine init my-game \ --template starter --platforms web --edition qutrit --no-claude-skill ``` Flags: `--template starter|quantum-pong`, `--edition qutrit|qubit`, `--platforms web[,desktop,ios,android]` (web is always included), `--claude-skill` / `--no-claude-skill`. Anything omitted becomes a prompt: project name, template, platforms, edition, Claude skill. The init flow prompts you to choose an **edition**: | Edition | Dimensions | Max Qudits | Trade-off | |---------|-----------|------------|-----------| | **Qutrit** (default) | 2–3 | 12 | Supports qutrits (3-state) but fewer total qudits | | **Qubit** | 2 only | 20 | More quantum objects, but locked to binary states | Skip the prompt with `--edition qubit` or `--edition qutrit`. Or install manually: ```bash npm install quantum-forge # Quantum core only npm install quantum-forge-engine # Full game framework (includes core) ``` Configure Vite: ```typescript import { quantumForgeVitePlugin } from "quantum-forge/vite-plugin"; export default defineConfig({ plugins: [quantumForgeVitePlugin()], }); ``` Note: Packages are ESM-only. Use `vite.config.mjs` or add `"type": "module"` to `package.json`. Initialize quantum simulation before use: ```typescript import { ensureLoaded, QuantumPropertyManager } from "quantum-forge/quantum"; await ensureLoaded(); ``` For the Qubit edition, call `useQuantumForgeBuild("qubit")` before `ensureLoaded()`: ```typescript import { useQuantumForgeBuild, ensureLoaded } from "quantum-forge/quantum"; useQuantumForgeBuild("qubit"); await ensureLoaded(); ``` ### Unity Install via Package Manager → Add package from git URL: ``` https://github.com/quantum-native/quantum-forge-unity.git ``` ## Quantum Mechanics for Games ### Core Concepts - **Quantum Properties**: A handle to one qudit (quantum digit) in a shared quantum state. Create via `QuantumPropertyManager.acquireProperty()`. Dimension configurable: 2 (qubit) or 3 (qutrit), depending on edition. - **Superposition**: A property exists in multiple states simultaneously until measured. Created by gates like `hadamard()`. - **Measurement**: Collapses superposition to a single definite value. Call `measure_properties([prop])`. Read probabilities without collapse via `probabilities([prop])` (takes an array, even for one property). - **Entanglement**: Link two properties so measuring one instantly determines the other. Created by two-property gates like `i_swap()` or conditional predicates. - **Interference**: Phase relationships between states cause constructive/destructive probability patterns. Manipulate with `clock()` and `phase_rotate()`. ### Gates Reference Single-property gates: - `hadamard(prop)` — Equal superposition of all states - `inverse_hadamard(prop)` — Reverse of hadamard - `cycle(prop)` — Deterministic rotation: |0⟩→|1⟩→|2⟩→|0⟩ - `clock(prop)` — Phase rotation (Z gate for qubits) - `shift(prop)` — Value shift (X gate for qubits) - `y(prop)` — Y gate (qubit-only, dimension=2) Two-property gates: - `i_swap(prop1, prop2, fraction, predicates?)` — Entangling swap (anti-correlated). `fraction` is REQUIRED and positional, not optional. - `swap(prop1, prop2, predicates?)` — Value swap. Takes no fraction. Fractions: - `cycle`, `shift`, `clock`, `hadamard`, `x`, `y`, `z` take an optional `fraction` (0.0–1.0) for partial application. - `inverse_hadamard` and `swap` take NO fraction. `i_swap` requires one. - Omitting the fraction on a gate that accepts one calls the non-fractional DISCRETE gate. That is a different operation from passing `1.0`, not a shorthand for it. Most gates accept an optional trailing `predicates` array for conditional execution (creates entanglement). Exceptions: `phase_rotate(predicates, angle)` takes predicates FIRST and requires them; `reset` takes none. To predicate a discrete gate, pass `undefined` for the fraction: `m.shift(target, undefined, [control.is(1)])`. ### Entanglement Patterns 1. **Entangle-Split (i_swap)**: One object splits into an anti-correlated pair. If one measures 0, the other measures 1. Build it from definite states: `cycle(p1)` (p1 → |1⟩, p2 stays |0⟩) then `i_swap(p1, p2, 0.5)` gives (|10⟩ + i|01⟩)/√2. Applying i_swap to two properties that are ALREADY in superposition does not produce anti-correlated outcomes. 2. **Correlated Pair (CNOT via predicates)**: Both objects measure the same value. 3. **Controlled Entanglement**: Gate on A,B conditioned on C. Entanglement only exists when C is in a specific state. ### Phase and Interference - `clock()` rotates phase without changing measurement probabilities - Phase becomes visible when followed by another gate (e.g., i_swap, hadamard) - Constructive interference: phases align → probability increases - Destructive interference: phases cancel → probability decreases - Grover oracle pattern: mark target with phase, then diffuse ### Recording and Replay ```typescript import { QuantumRecorder } from "quantum-forge/quantum"; const recorder = new QuantumRecorder(qpm); recorder.startRecording(); // ... perform quantum operations ... const log = recorder.stopRecording(); // returns the operation log // or, while still recording: recorder.getOperationLog() // Later: replay deterministically recorder.replayLog(log); // Measurements forced to recorded outcomes ``` There is no `recorder.getLog()`. Use `getOperationLog()` or the return value of `stopRecording()`. ## Framework Architecture ### Engine Pattern (Four Layers) 1. **Pure Functions** — Game logic in separate modules, no side effects 2. **Engine** — State coordinator: `Engine` with `getState()`, `setState()`, `getHelpers()`, `reset()` 3. **Renderer** — Derives visuals from state: `PixiRenderer` (WebGL/WebGPU) or `CanvasRenderer` 4. **Controller** — Wires Engine + Renderer + Input + GameLoop ### Package Exports ```typescript // Core quantum package import { ensureLoaded, QuantumPropertyManager, QuantumRecorder } from "quantum-forge/quantum"; import { Logger } from "quantum-forge/logging"; import { quantumForgeVitePlugin } from "quantum-forge/vite-plugin"; // Engine package import { Engine } from "quantum-forge-engine/engine"; import { PixiRenderer, CanvasRenderer, GameLoop, Camera } from "quantum-forge-engine/rendering"; import { InputManager, LocalMultiplayerManager, GamepadButtons } from "quantum-forge-engine/input"; import { EventBus } from "quantum-forge-engine/events"; // Optional packages (install via `npx quantum-forge-engine add-system`) import { ... } from "quantum-forge-engine/collision"; import { ... } from "quantum-forge-engine/audio"; import { ... } from "quantum-forge-engine/particles"; import { ... } from "quantum-forge-engine/animation"; import { ... } from "quantum-forge-engine/entities"; import { ... } from "quantum-forge-engine/state-machine"; import { ... } from "quantum-forge-engine/timer"; import { ... } from "quantum-forge-engine/save"; import { ... } from "quantum-forge-engine/scenes"; import { ... } from "quantum-forge-engine/operations"; ``` ### Rendering - **PixiRenderer**: WebGL/WebGPU via PixiJS 8. Requires `await renderer.init()` before use. - **CanvasRenderer**: Canvas 2D for simpler games. - **GameLoop**: Fixed-timestep update/render cycle with configurable target FPS. - **Camera**: World-space transforms for scrolling (no zoom API; width/height required). ### Input System ```typescript const input = new InputManager({ logger }); input.bind("jump", { type: "key", code: "Space" }, { type: "gamepad-button", index: GamepadButtons.A }); // In update loop: if (input.isActionJustPressed("jump")) { ... } ``` Supports keyboard, mouse, gamepad (buttons + axes), and touch (zones, joysticks, gestures). ### Optional Packages - **Collision**: AABB, circle, point detection + SpatialGrid - **Audio**: Howler.js wrapper for sound effects and music - **Particles**: Burst, trail, and continuous emitters - **Animation**: Tweening with easing functions - **Entities**: Entity management with spatial queries - **State Machine**: Finite state machine - **Timer**: Pause-aware timers - **Save**: Versioned save/load - **Scenes**: Stack-based scene lifecycle ## CLI Tools The CLI ships in the ENGINE package. `npx quantum-forge-engine ` always works; `npx quantum-forge ` works from core 2.7.0 onward. ```bash npx quantum-forge-engine init my-game # Scaffold new project (prompts) npx quantum-forge-engine init my-game --template quantum-pong # With full example npx quantum-forge-engine init my-game --edition qubit # Qubit edition (20 qubits) npx quantum-forge-engine init my-game --platforms web,desktop # Add an Electron target npx quantum-forge-engine add-system # Add optional packages interactively npx quantum-forge-engine validate # Architecture pattern scoring npx quantum-forge-engine doctor # Environment diagnostics ``` Non-interactive scaffold: ```bash npx -y quantum-forge-engine init my-game \ --template starter --platforms web --edition qutrit --no-claude-skill ``` `add-system`, `validate`, and `doctor` are subcommands of the engine bin and require quantum-forge-engine 1.3.0 or later. On older versions they were monorepo-only scripts and cannot be run from a scaffolded project. Scaffolded projects have NO `npm run add-system` / `npm run validate` / `npm run doctor` scripts, so do not suggest those. Templates: `starter` generates a Vite + TypeScript project with pure logic modules, an Engine subclass, a PixiJS renderer, a controller in `main.ts`, and a vitest file. From engine 1.3.0 it also writes `CLAUDE.md` and `AGENTS.md`. `quantum-pong` generates a complete game with a QuantumRegistry, pong logic, audio assets, and 75 tests. ## Unity Integration ### Installation Unity Package Manager → Add package from git URL: ``` https://github.com/quantum-native/quantum-forge-unity.git ``` Pin a version by appending a tag, e.g. `https://github.com/quantum-native/quantum-forge-unity.git#unity-v1.4.0`. ### Core Components - **Basis** (ScriptableObject): Defines quantum dimension and state labels - **QuantumProperty** (MonoBehaviour): Attaches quantum state to a GameObject - **Action components**: Hadamard, Cycle, Clock, iSwap, etc. — wire to UI buttons - **ProbabilityTracker**: Visualizes quantum state probabilities in real time ### Inspector Workflow 1. Create Basis ScriptableObject (e.g., dimension=2, labels=["Dead","Alive"]) 2. Add QuantumProperty component to GameObject, assign Basis 3. Add action components (e.g., Hadamard), configure in inspector 4. Wire the action's apply() method to button clicks 5. Add ProbabilityTracker for visualization ## Showcase Games - **Quantum Pong**: Entangle-split balls, phase-biased scoring (dim=2, RDM visualization) - **Quantris** (quantris.io): Quantum existence in puzzle pieces (dim=2) - **Hex Diffusion**: Probability diffusion across hex grid (dim=7, fractional Hadamard, Grover oracle). Runs on a custom internal build; public editions cap at dimension 3 (Qutrit) or 2 (Qubit), so this is not reproducible with a shipped build. - **Bloch Invaders**: Bloch sphere navigation via Y/Z gates (dim=2) - **Ponq** (ponq.io): Coherence-driven ball physics via density matrix (dim=2) ## AI Agent Support The `quantum-forge` npm package includes `QUANTUM_FORGE.md`, a complete framework reference for AI coding assistants. It covers gates, entanglement patterns, measurement, rendering, input, and performance, with code examples throughout. To use it, point your AI assistant at `node_modules/quantum-forge/QUANTUM_FORGE.md`. Claude Code users get it as a `/quantum-forge` skill by passing `--claude-skill` at scaffold time (`npx quantum-forge-engine init my-game --claude-skill`), which copies the file to `.claude/skills/quantum-forge/SKILL.md`. There is no post-hoc install command yet; copy the file by hand to add it to an existing project. ### Non-interactive scaffold ```bash npx -y quantum-forge-engine init my-game \ --template starter --platforms web --edition qutrit --no-claude-skill ``` ### Running quantum code headlessly (Node, vitest, CI) The loader resolves WASM artifacts from a URL path by default, which works under Vite but not under bare Node. Set an ABSOLUTE filesystem base path before `ensureLoaded()`: ```typescript import { resolve } from "node:path"; import { setWasmBasePath, ensureLoaded, QuantumPropertyManager } from "quantum-forge/quantum"; setWasmBasePath(resolve(process.cwd(), "node_modules/quantum-forge/dist")); await ensureLoaded(); const qpm = new QuantumPropertyManager({ dimension: 2 }); const m = qpm.getModule(); const a = qpm.acquireProperty(); // |0⟩ const b = qpm.acquireProperty(); // |0⟩ m.cycle(a); // a → |1⟩ m.i_swap(a, b, 0.5); // (|10⟩ + i|01⟩)/√2 const [va, vb] = m.measure_properties([a, b]); // always 1,0 or 0,1 qpm.releaseProperty(a, va); qpm.releaseProperty(b, vb); ``` ### Common agent mistakes - `npx quantum-forge init`: wrong, the bin is in `quantum-forge-engine`. - `measureProperties` / `iSwap`: wrong, method names on the WASM module are snake_case and are reached through `getModule()`. - `probabilities(prop)`: wrong, it takes an array. - `m.i_swap(a, b)`: wrong, the fraction is required. - `hadamard(prop, 1.0)` is NOT the same as `hadamard(prop)`. - Requesting dimension > 3: shipped builds hard-cap at 3. - Mutating `engine.getState()`: it returns `Readonly`; spread into `setState`. - `Engine` subclasses must implement both `getHelpers()` and `reset()`; both are abstract. ## Links - Developer site: https://quantum.dev - GitHub: https://github.com/quantum-native - Discord: https://discord.gg/quantumforge - Contact: hello@quantum.dev ## License - TypeScript framework + Unity C# source: MIT - WASM binaries + native plugins: Proprietary (free under $100K annual revenue with attribution)