# Project XiaoChun

> 100% client-native anime companion & transparent desktop pet (Tauri 2.x + Web) — WebLLM (WebGPU), on-device streaming STT (`@firetable/stream-asr` WASM + neural VAD barge-in interruption), EMAGE motion (ONNX wasm INT8), Edge-TTS with Tone.js 3D spatial vocal DSP, 24h Beach 3D solar stage, StoryDirector interactive prologue, and Inter-process Protocol (`xiaochun://`). Private interactive VRM companion, zero cloud backend.

## Overview
Project XiaoChun is a dual-mode anime companion application running both in modern browser tabs and as a native, borderless, transparent desktop pet powered by **Tauri 2.x**. The 3D scene renders via `three.js` + `@pixiv/three-vrm` (MToon NPR shading) with native **VRM 1.0 & VRM 0.x dual-standard compatibility**; conversation, motion, and speech are generated 100% client-side: WebLLM on WebGPU, EMAGE on ONNX Runtime Web **wasm + INT8**, and Edge-TTS audio streaming. The desktop build features a real-time 60Hz Alpha Bitmask click-through engine and a system-level IPC URL scheme (`xiaochun://`) allowing external applications and AI agents to awaken and command her.

## Core Features
- **Decoupled 3D Architecture**: Modular `VRMEngine` coordinating specialized subsystems:
  - `Beach3DWorld`: Procedural anime MMD-stage beach with real sand, wave swashes, tiered palm trees, lighthouse, and sandcastle. Features a 24-hour astronomical solar/lunar arc smoothly blending Dawn, Day, Sunset, and Night palettes, synchronized directional sun and dynamic character shadows, and polar atan2 SceneTimeCard HUD.
  - `LineworkWorld`: Minimalist procedural line-art outdoor world with Light / Dark dual themes (sun with radial rays, 19 buildings, wireframe ground, 5 tree archetypes).
  - `StudioLighting`: 3-channel lighting (dir: 1.00 / hemi: 0.95 / fill: 1.40) with 2048 PCFSoft shadow camera.
  - `PostFxPipeline`: Cinematic post-processing (UnrealBloomPass with background luminance filtering, merged ColorGrading LUT/BC/HS, ACESFilmic ToneMapping, and physical bypass).
  - `VRMMaterialManager`: Semantic material categorization with dynamic `uMatSaturation` fragment shader injection.
  - `OutfitSwap & Delta Addons`: Atomic outfit switching with 0-frame T-pose pop-in (state snapshot & in-memory pre-restore). Delta packaging via `.vrmbase` (~5.9MB) + 5 `.vrmaddon` patches (Techwear, Cheongsam, Bikini, Maid, Swimsuit) with WASM bspatch and 2-tier IndexedDB caching. Serialized via `LatestWinsQueue`.
  - `GazeController`: Level-head gaze tracking, micro-saccades, and thinking head sways.
  - `BubbleTracker`: High-performance 3D-to-2D screen projection with 1.5px dead-zone filtering.
  - `Runtime VRM Upload`: Live drag-and-drop or file upload supporting arbitrary standard VRM 1.0 and VRM 0.x avatars.
- **Universal Motion Pipeline**: Layered pose hierarchy with Quintic Smootherstep ($6t^5 - 15t^4 + 10t^3$) inbetweening, mocap-driven attentive listening (`ListeningMotionSystem`), full/upper-body masking, inverse quaternion LookAt decoupling, automated lifecycle return-to-idle, and transparent VRM 0.x / 1.0 coordinate space translation.
- **StoryDirector Engine**: Interactive cinematic visual novel engine orchestrating Act 0 prologue onboarding ("Meeting XiaoChun") with branching choice cards, dynamic camera moves (spiral orbit, Dutch tilt, backlight reveal), and procedural audio.
- **28-Parameter Orthogonal Bone Morphing**: Live customization across head, neck, shoulders, torso thickness, waist, belly, hips, buttocks, bust, arms, fingers, thighs, calves, and feet (VRoid 1.0 guarded). Shoulder width defaults to 110% with an extended range up to 250%. UI groups the 28 sliders into 7 body-region sub-cards. Dynamic crown height measured live from mesh vertices; per-section state isolation keeps dragging fluid.
- **LLM & Multimodal Vision (WebLLM, default)**: Workspace-patched `@firetable/web-llm` (`v0.2.88`) + `@firetable/web-runtime` (`0.28.0-dev2`) running MiniCPM5 2B (q4f16_1) on WebGPU (fallback Qwen2.5 0.5B) and MiniCPM-V 4.7 1B (`MiniCPM-V-4.7-1B-q4f16_1-MLC`) for 100% on-device multimodal vision (model-gated ChatBar image upload, drag-and-drop, and clipboard paste up to 4 images). Adaptive `desktop`/`mobile` cooperative WebGPU frame pacing preserves ~60 FPS 3D rendering across `0.5B`–`8B` model loading, ViT encoding, and LLM prefill/decode.
- **LLM (Custom OpenAI-Compatible Providers)**: Plug any OpenAI-compatible HTTP service (Ollama / LM Studio / vLLM / LocalAI / OpenAI / DeepSeek / Qwen API) via in-app config dialog. Profiles AES-GCM encrypted in IndexedDB. Active custom provider unloads WebLLM to free 1-2 GB VRAM. Unified `runChat(opts)` contract for both providers via `chatWorkflow` factory.
- **Cinematic Intro**: When the loading overlay exits, `vrmEngine.cinematicIntro(1100)` tweens camera from a 3.3× distant position to the current position with `easeOutCubic`, synchronized with overlay's `scale-125 + blur-md` break transition.
- **Motion Generation**: EMAGE (PantoMatrix, CVPR 2024) in a Dedicated Worker — **wasm EP + INT8**, streaming `motion_chunk` (T=64), A/V hold, hop/seams via `APP_CONFIG.emage.motion`. **Not** WebGPU-EMAGE. See `/docs` EMAGE_MODEL.
- **STT**: 100% on-device streaming Speech-to-Text via `@firetable/stream-asr` (WASM, neural VAD, real-time interim text, auto punctuation) with conversational barge-in interruption and acoustic bleed gating; no audio leaves the device. See `/docs/STT.md`.
- **TTS & Vocal Post-Processing**: Microsoft Edge-TTS XiaoyiNeural zh-CN (+10 Hz) via native `src/lib/edge-tts-core.ts` (no third-party TTS SDK), paired with client-side **Tone.js 15.x Vocal Post-Processing Pipeline** (`vocalProcessor.ts`): low-cut highpass filter, 3-band EQ, radio compressor, subtle room reverb, bit-exact bypass routing, and **3D camera distance acoustics** (intimate $<2.2\text{m}$ proximity boost, $2.2\sim 8\text{m}$ flat dialogue, and $>8\text{m}$ smooth distance attenuation). Dev proxy via `TTS_PROXY_URL` (EU egress workaround).
- **Desktop Companion Mode (Tauri 2.x)**: Operates borderless and chromeless with true transparent desktop compositing, 60Hz Alpha Bitmask hit-testing thread for click-through, and persistent window state (`tauri-plugin-window-state`).
- **Inter-Process Protocol (`xiaochun://`)**: System-wide IPC URL Scheme allowing external applications, CLI scripts, and autonomous AI agents to wake up XiaoChun and drive `speakText` with full-body motion, lip-syncing, and dialog bubbles.
- **3D Holographic Guides & Aerodynamics**: In-world WebGL controls including `TurnGuide3D` (yaw guide ring with reactive light beacon), `PitchGuide3D` (elevation arc), `CameraYGuide3D` (floating 3D height rail), and localized cursor wind drag impulses (`windForce.ts`).
- **Client-Side Cognitive Memory**: IndexedDB (`client-memory-db` via `@firetable/client-memory`) local persistence — 4-tier cognitive architecture with short-term turns, zero-GPU intent/fact extraction, long-term episodic narrative journals, Stanford Generative Agents 3D decay scoring, and SillyTavern compatible lorebook injection. 100% local privacy guarantee with zero telemetry.
- **i18n & SSR**: TanStack Start full-stack SSR with cookie-based language hydration; ships zh-CN / en / ja; adaptive prompt matching user input language.
- **Mobile-First UI**: iOS HIG 44 pt / Material 48 dp touch targets, liquid-glass aesthetic, SSR pre-rendered LoadingOverlay. Chat input remains editable during response so users can pre-type.
- **Debug Drawer (localhost only)**: Schema-driven **11-section** panel (expressions / motion / vocal / camera / saturation / bone morph / wardrobe / lighting / postfx / emagePerf / voiceAnalysis). Per-section state isolation + per-frame / commit slider split. Full architecture in `docs/ARCHITECTURE_AND_RULES.md` §3.

## Links & API Contracts
- [Full Documentation](/llms-full.txt): Complete technical architecture, dependency list, motion/TTS pipelines, deployment guide.
- [RFC 9727 API Catalog](/.well-known/api-catalog): Machine-readable linkset catalog of all service documents and endpoints.
- [Agent Auth Policy](/auth.md): Public and anonymous access whitepaper for autonomous agents and LLM crawlers.
- [Story Director Guide](/docs/STORY_DIRECTOR.md): Interactive cinematic story engine, beat lifecycle, camera moves, and procedural audio.
- [Beach 3D World Guide](/docs/BEACH3D_SCENE.md): Real-time anime MMD-stage beach, 24-hour solar arc, and SceneTimeCard HUD.
- [Client Memory Architecture Guide](/docs/CLIENT_MEMORY.md): Cognitive memory system (@firetable/client-memory), 4-tier IndexedDB hierarchy, SillyTavern lorebooks, and episodic scoring.
- [Motion Pipeline Guide](/docs/MOTION_PIPELINE.md): Universal motion pipeline, Quintic 0.75s blending, FootIK, and BodyTurn stepping.
- [Performance Guide](/docs/PERFORMANCE.md): Model slimming, zero-drop outfit swap, and mobile GPU lifecycle.
- [TTS & Vocal Post-Processing Guide](/docs/TTS.md): Edge-TTS proxy architecture and Tone.js 3D spatial vocal processing.
- [Desktop Companion Docs](/docs/HYBRID_DESKTOP_APP.md): Architecture of the Tauri 2.x hybrid desktop mode.
- [Protocol Specification](/docs/PROTOCOL.md): Detailed specification of the `xiaochun://` URL scheme.
- [Embed / SDK Guide](/docs/EMBED.md): iframe embed + `@firetable/project-xiaochun` SDK. Host audio: `speakAudio(data, { audible: false, hostClock: true })` (0.1.35+, skips the thinking pose), hold the page player until `utterance start`, then `syncClock({ time, playing, playbackRate?, seek? })` (`xc.clock`) every ~250 ms and on play / pause / seeked / waiting so motion + lip-sync follow the page audio. Check `supportsHostClock()` (`capabilities.audio.hostClock`); older embeds need stop/restart on pause and seek. Fetch the audio once and share it between the page `<audio>` and `speakAudio`.
- [Agent Skill Guide](/docs/AGENT_SKILL.md): Standard AI Agent skill for autonomous control of XiaoChun.
- [STT Guide](/docs/STT.md): On-device streaming STT via `@firetable/stream-asr` (WASM + neural VAD), conversational barge-in interruption, and acoustic bleed gating.
- [Live Demo](https://xiaochun.firetable.tech): Full-stack SSR deploy on Cloudflare Workers.
- [GitHub Repository](https://github.com/FireTable/Project-XiaoChun): Source code, setup instructions, and issue tracker.
- Edge API: `GET /api/tts?text=...&voice=zh-CN-XiaoyiNeural&pitch=%2B10Hz` returns `audio/mpeg`. `POST /api/stt` (retained server-side, hidden from UI) returns transcribed JSON text via Whisper Turbo. Protected by Origin Guard (`src/server/originGuard.ts`).
- Custom Providers: in-app **Custom Model Service** dialog (top-bar / chat-bar). Templates: Ollama, LM Studio, vLLM, LocalAI, Generic OpenAI-compatible. Test connection button probes `/v1/models` endpoint before save.
