From 9964f45185ba1a20195c4be1e977042616840b43 Mon Sep 17 00:00:00 2001 From: hyperion Date: Thu, 22 Oct 2026 08:56:25 +0200 Subject: [PATCH] chore: migrate from old project --- apps/demo/src/routes/+page.svelte | 1408 ++++++++++++++++- packages/shimejic/src/core/animation.ts | 194 +++ packages/shimejic/src/core/assets.ts | 376 +++++ packages/shimejic/src/core/behavior.ts | 692 ++++++++ packages/shimejic/src/core/camera.ts | 48 + .../shimejic/src/core/character-config.ts | 369 +++++ packages/shimejic/src/core/chatter-overlay.ts | 554 +++++++ packages/shimejic/src/core/chatter-parser.ts | 475 ++++++ packages/shimejic/src/core/chatter-types.ts | 340 ++++ packages/shimejic/src/core/cursor.ts | 188 +++ packages/shimejic/src/core/entity.ts | 228 +++ packages/shimejic/src/core/index.ts | 126 ++ packages/shimejic/src/core/mumble.ts | 628 ++++++++ packages/shimejic/src/core/physics.ts | 296 ++++ .../shimejic/src/core/render-primitives.ts | 0 packages/shimejic/src/core/renderer.ts | 415 +++++ packages/shimejic/src/core/system.ts | 27 + packages/shimejic/src/core/world.ts | 204 +++ packages/shimejic/src/features/index.ts | 0 packages/shimejic/src/index.ts | 3 +- packages/shimejic/src/systems/index.ts | 3 + .../shimejic/src/systems/physics-system.ts | 66 + .../shimejic/src/systems/render-system.ts | 242 +++ 23 files changed, 6879 insertions(+), 3 deletions(-) create mode 100644 packages/shimejic/src/core/animation.ts create mode 100644 packages/shimejic/src/core/assets.ts create mode 100644 packages/shimejic/src/core/behavior.ts create mode 100644 packages/shimejic/src/core/camera.ts create mode 100644 packages/shimejic/src/core/character-config.ts create mode 100644 packages/shimejic/src/core/chatter-overlay.ts create mode 100644 packages/shimejic/src/core/chatter-parser.ts create mode 100644 packages/shimejic/src/core/chatter-types.ts create mode 100644 packages/shimejic/src/core/cursor.ts create mode 100644 packages/shimejic/src/core/entity.ts create mode 100644 packages/shimejic/src/core/index.ts create mode 100644 packages/shimejic/src/core/mumble.ts create mode 100644 packages/shimejic/src/core/physics.ts create mode 100644 packages/shimejic/src/core/render-primitives.ts create mode 100644 packages/shimejic/src/core/renderer.ts create mode 100644 packages/shimejic/src/core/system.ts create mode 100644 packages/shimejic/src/core/world.ts create mode 100644 packages/shimejic/src/features/index.ts create mode 100644 packages/shimejic/src/systems/index.ts create mode 100644 packages/shimejic/src/systems/physics-system.ts create mode 100644 packages/shimejic/src/systems/render-system.ts diff --git a/apps/demo/src/routes/+page.svelte b/apps/demo/src/routes/+page.svelte index cc88df0..d3bf886 100644 --- a/apps/demo/src/routes/+page.svelte +++ b/apps/demo/src/routes/+page.svelte @@ -1,2 +1,1406 @@ -

Welcome to SvelteKit

-

Visit svelte.dev/docs/kit to read the documentation

+ + + + +
+

Asset Playground

+ + {#if errorMsg} +

{errorMsg}

+ {:else if !ready} +

Loading assets…

+ {:else} + +
State
+
+ {#each availableStates as s} + + {/each} +
+ + + {#if availableEvents.length > 0} +
Trigger event
+
+ {#each availableEvents as ev} + {@const key = `${ev.state}:${ev.name}`} + {@const cd = debug?.cooldowns[key] ?? 0} + {@const isQueued = debug?.queuedEvent === ev.name && debug?.state === ev.state} + {@const isActive = debug?.activeEvent === ev.name && debug?.state === ev.state} + {@const stateMismatch = currentState !== ev.state} + + {/each} +
+ {#if pendingTrigger} +

+ Switching to {pendingTrigger.state} to queue + {pendingTrigger.event}… +

+ {/if} + {/if} + + +
Chatter test
+
+ +
+ + + {#if debug} +
+
state
+
{debug.state}
+
track
+
{debug.track}
+
frame
+
{debug.frameIndex} / {debug.frameCount - 1}
+
look folder
+
{debug.lookFolder ?? '—'}
+
matched
+
{debug.matchedFolder ?? '—'}
+
active event
+
{debug.activeEvent ?? '—'}
+
queued event
+
{debug.queuedEvent ?? '—'}
+ {#if Object.keys(debug.cooldowns).length > 0} +
cooldowns
+
+ {#each Object.entries(debug.cooldowns) as [key, sec]} +
{key.replace(':', ' / ')}: {sec.toFixed(1)}s
+ {/each} +
+ {/if} +
+ {/if} + + {#if cursorInfo} +
+
angle {cursorInfo.angle.toFixed(1)}°
+
distance {cursorInfo.distance.toFixed(0)} px
+
+ {/if} + + {#if chatterLog.length > 0} +
+ {#each chatterLog as line} +
{line}
+ {/each} +
+ {/if} + +
+
Loaded clips
+ {#each clipSummary as clip} +
+ {clip.role} + {clip.name} + {clip.frames}f · {clip.fps}fps +
+ {/each} + {#if stats} + + {/if} +
+ +

hover to look · drop PNGs in src/lib/assets/

+ {/if} +
+ + \ No newline at end of file diff --git a/packages/shimejic/src/core/animation.ts b/packages/shimejic/src/core/animation.ts new file mode 100644 index 0000000..303d49c --- /dev/null +++ b/packages/shimejic/src/core/animation.ts @@ -0,0 +1,194 @@ +/** + * animation.ts — frame sequencing. + * + * An AnimationClip is a list of frames + fps + loop flag. An Animator plays + * one clip at a time and exposes the current frame. It knows nothing about + * what the frames contain. + * + * `staticSprite` and `animatedSprite` produce SpriteSlot-conforming objects. + * Both have the same interface — the renderer can't tell them apart. + */ + +import type { SpriteFrame, SpriteSlot } from "./entity.ts"; + +export interface AnimationClip { + frames: CanvasImageSource[]; + fps: number; + /** Default true. When false, holds the last frame after one pass. */ + loop?: boolean; +} + +/* ------------------------------------------------------------------ */ +/* Animator */ +/* ------------------------------------------------------------------ */ + +export class Animator { + private clip: AnimationClip | null = null; + private elapsed = 0; + private finished = false; + private playing = false; + + /** Begin playing a clip. No-op if it's already the current clip. */ + play(clip: AnimationClip | null): void { + if (clip === this.clip) return; + this.clip = clip; + this.elapsed = 0; + this.finished = false; + this.playing = clip !== null && clip.frames.length > 0; + } + + /** Restart the current clip from frame zero. */ + restart(): void { + if (this.clip === null) return; + this.elapsed = 0; + this.finished = false; + this.playing = this.clip.frames.length > 0; + } + + /** Freeze the clip. Does not clear the current frame. */ + stop(): void { + this.playing = false; + } + + /** + * Advance by `dt` seconds. + * `timeScale` multiplies the rate. Use it to make playback speed + * proportional to something — ground speed, for example. + */ + update(dt: number, timeScale = 1): void { + const c = this.clip; + if (!this.playing || c === null || this.finished) return; + + this.elapsed += dt * timeScale; + + if (c.loop === false) { + const duration = c.frames.length / c.fps; + if (this.elapsed >= duration) { + this.elapsed = duration; + this.finished = true; + } + } + } + + get frame(): CanvasImageSource | null { + const c = this.clip; + if (c === null || c.frames.length === 0) return null; + return c.frames[this.frameIndex] ?? null; + } + + get frameIndex(): number { + const c = this.clip; + if (c === null || c.frames.length === 0) return 0; + const raw = Math.floor(this.elapsed * c.fps); + if (c.loop === false) return Math.min(raw, c.frames.length - 1); + return raw % c.frames.length; + } + + get done(): boolean { + return this.finished; + } + + get time(): number { + return this.elapsed; + } + + get currentClip(): AnimationClip | null { + return this.clip; + } +} + +/* ------------------------------------------------------------------ */ +/* Image sizing */ +/* ------------------------------------------------------------------ */ + +/** + * Best-effort size detection across CanvasImageSource variants. + * HTMLImageElement uses naturalWidth/naturalHeight; everything else + * (canvas, ImageBitmap, OffscreenCanvas, video) uses width/height. + */ +export function imageSize(image: CanvasImageSource): { width: number; height: number } { + const anyImg = image as unknown as Record; + const nw = anyImg.naturalWidth; + const nh = anyImg.naturalHeight; + if (typeof nw === "number" && typeof nh === "number") { + return { width: nw, height: nh }; + } + const w = anyImg.width; + const h = anyImg.height; + if (typeof w === "number" && typeof h === "number") { + return { width: w, height: h }; + } + return { width: 0, height: 0 }; +} + +/* ------------------------------------------------------------------ */ +/* Sprite factories */ +/* ------------------------------------------------------------------ */ + +/** A sprite slot that always returns the same frame. */ +export function staticSprite(image: CanvasImageSource, scale = 1): SpriteSlot { + const size = imageSize(image); + const frame: SpriteFrame = { + image, + width: size.width * scale, + height: size.height * scale, + sx: 0, + sy: 0, + sw: size.width, + sh: size.height, + }; + return { + frame: () => frame, + }; +} + +export interface AnimatedSpriteOptions { + loop?: boolean; + scale?: number; +} + +export interface AnimatedSprite extends SpriteSlot { + readonly animator: Animator; +} + +/** + * A sprite slot backed by an Animator. The animator is exposed so callers + * can swap clips or restart playback without rebuilding the slot. + */ +export function animatedSprite( + frames: CanvasImageSource[], + fps: number, + opts: AnimatedSpriteOptions = {}, +): AnimatedSprite { + const scale = opts.scale ?? 1; + const clip: AnimationClip = { + frames, + fps, + loop: opts.loop ?? true, + }; + const animator = new Animator(); + animator.play(clip); + + const first = frames[0]; + const size = first !== undefined ? imageSize(first) : { width: 0, height: 0 }; + const displayWidth = size.width * scale; + const displayHeight = size.height * scale; + + return { + animator, + update: (dt: number) => animator.update(dt), + frame: () => { + const img = animator.frame; + if (img === null) return null; + return { + image: img, + width: displayWidth, + height: displayHeight, + sx: 0, + sy: 0, + sw: size.width, + sh: size.height, + }; + }, + }; +} diff --git a/packages/shimejic/src/core/assets.ts b/packages/shimejic/src/core/assets.ts new file mode 100644 index 0000000..121e399 --- /dev/null +++ b/packages/shimejic/src/core/assets.ts @@ -0,0 +1,376 @@ +/** + * assets.ts — image loading with byte tracking. + * + * IMPORTANT — what "bytes" means here: + * + * decodedBytes = width × height × 4 + * The size of the RGBA8 bitmap the browser holds to draw this image. + * This is what you pay in RAM/VRAM every frame the image is alive. + * It is NOT what DevTools will show (DevTools varies by tool and + * browser) and NOT what's on disk. + * + * fileBytes = size of the response body (compressed) + * What you downloaded. A palette PNG can be 10× smaller than its + * decoded size, and this number tells you which. + * + * The toolkit controls decodedBytes. It cannot control what the browser's + * GPU layer does on top of that. Both are tracked so you can reason about + * the cost you own. + * + * Concurrency: + * Fetches and decodes are gated by a semaphore (default 6 concurrent). + * Without this, preload() fires every request at once, producing a + * spike on the network graph and contending for decode threads. With + * it, requests stream through a fixed window — same total work, no + * spike, and finished slots free up immediately for the next asset. + * + * No eviction. The cache reports; the caller decides. + */ + +/* ------------------------------------------------------------------ */ +/* Types */ +/* ------------------------------------------------------------------ */ + +export interface ImageManifest { + [name: string]: string; +} + +export interface LoadedImage { + image: CanvasImageSource; + width: number; + height: number; + fileBytes: number; +} + +export interface ImageInfo { + image: CanvasImageSource; + width: number; + height: number; + decodedBytes: number; + fileBytes: number; +} + +export interface CacheStats { + count: number; + decodedBytes: number; + fileBytes: number; + byPrefix: Record; +} + +export type WarnMetric = "decoded" | "file" | "both"; + +export interface AssetCacheConfig { + manifest: ImageManifest; + warnMetric?: WarnMetric; + warnThresholdBytes?: number; + onWarn?: (message: string) => void; + loader?: (url: string) => Promise; + /** + * Maximum concurrent fetches/decodes. Default 6 — matches the classic + * browser per-origin limit and keeps the network graph flat. On HTTP/2 + * you can push higher (10–16), but decode contention usually offsets + * the benefit past ~12. Set to 1 for strictly serial loads. + */ + concurrency?: number; +} + +/* ------------------------------------------------------------------ */ +/* Default loader */ +/* ------------------------------------------------------------------ */ + +async function blobToImageElement(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const objectUrl = URL.createObjectURL(blob); + const img = new Image(); + img.onload = () => { + URL.revokeObjectURL(objectUrl); + resolve(img); + }; + img.onerror = () => { + URL.revokeObjectURL(objectUrl); + reject(new Error("image load failed")); + }; + img.src = objectUrl; + }); +} + +async function defaultLoader(url: string): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP ${response.status} for ${url}`); + } + const blob = await response.blob(); + const fileBytes = blob.size; + + if (typeof createImageBitmap === "function") { + const bitmap = await createImageBitmap(blob); + return { image: bitmap, width: bitmap.width, height: bitmap.height, fileBytes }; + } + + const element = await blobToImageElement(blob); + return { + image: element, + width: element.naturalWidth, + height: element.naturalHeight, + fileBytes, + }; +} + +/* ------------------------------------------------------------------ */ +/* Cache */ +/* ------------------------------------------------------------------ */ + +export class AssetCache { + private readonly manifest: ImageManifest; + private readonly loader: (url: string) => Promise; + private readonly warnMetric: WarnMetric; + private readonly warnThresholdBytes: number; + private readonly onWarn: (message: string) => void; + private readonly concurrency: number; + + private readonly images = new Map(); + private readonly inFlight = new Map>(); + private warned = false; + + /** Concurrency gate — number of slots currently in use. */ + private activeLoads = 0; + /** Queued waiters, FIFO. Each is a resolve callback waiting for a slot. */ + private readonly loadQueue: Array<() => void> = []; + + constructor(cfg: AssetCacheConfig) { + this.manifest = cfg.manifest; + this.loader = cfg.loader ?? defaultLoader; + this.warnMetric = cfg.warnMetric ?? "decoded"; + this.warnThresholdBytes = + cfg.warnThresholdBytes ?? (this.warnMetric === "file" ? 32 * 1024 * 1024 : 256 * 1024 * 1024); + this.onWarn = cfg.onWarn ?? (msg => console.warn(msg)); + this.concurrency = Math.max(1, cfg.concurrency ?? 6); + } + + /* -------------------------------------------------------------- */ + /* Loading */ + /* -------------------------------------------------------------- */ + + async preload(names?: string[]): Promise { + const targets = names ?? Object.keys(this.manifest); + await this.preloadWhere(name => targets.includes(name)); + } + + async preloadPrefix(prefix: string): Promise { + await this.preloadWhere(name => name.startsWith(prefix)); + } + + async preloadPattern(pattern: RegExp): Promise { + await this.preloadWhere(name => pattern.test(name)); + } + + private async preloadWhere(predicate: (name: string) => boolean): Promise { + const tasks: Promise[] = []; + for (const name of Object.keys(this.manifest)) { + if (!predicate(name)) continue; + if (this.images.has(name)) continue; + tasks.push(this.loadOne(name).catch(() => undefined)); + } + await Promise.all(tasks); + this.checkThreshold(); + } + + private loadOne(name: string): Promise { + const existing = this.images.get(name); + if (existing) return Promise.resolve(existing); + + const pending = this.inFlight.get(name); + if (pending) return pending; + + const url = this.manifest[name]; + if (url === undefined) { + return Promise.reject(new Error(`Unknown asset "${name}"`)); + } + + const promise = this.loadGated(name, url); + this.inFlight.set(name, promise); + return promise; + } + + private async loadGated(name: string, url: string): Promise { + await this.acquireSlot(); + try { + const loaded = await this.loader(url); + const info: ImageInfo = { + image: loaded.image, + width: loaded.width, + height: loaded.height, + decodedBytes: loaded.width * loaded.height * 4, + fileBytes: loaded.fileBytes, + }; + this.images.set(name, info); + return info; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + throw new Error(`Failed to load "${name}" from "${url}": ${msg}`); + } finally { + this.inFlight.delete(name); + this.releaseSlot(); + } + } + + private acquireSlot(): Promise { + if (this.activeLoads < this.concurrency) { + this.activeLoads++; + return Promise.resolve(); + } + return new Promise(resolve => { + this.loadQueue.push(resolve); + }); + } + + private releaseSlot(): void { + const next = this.loadQueue.shift(); + if (next) { + // Hand the slot directly to the next waiter — no decrement, + // so activeLoads stays accurate under contention. + next(); + } else { + this.activeLoads--; + } + } + + /* -------------------------------------------------------------- */ + /* Query */ + /* -------------------------------------------------------------- */ + + has(name: string): boolean { + return this.images.has(name); + } + + get(name: string): ImageInfo | undefined { + return this.images.get(name); + } + + require(name: string): ImageInfo { + const info = this.images.get(name); + if (!info) throw new Error(`Asset "${name}" not loaded`); + return info; + } + + names(): string[] { + return [...this.images.keys()]; + } + + namesWithPrefix(prefix: string): string[] { + const out: string[] = []; + for (const name of this.images.keys()) { + if (name.startsWith(prefix)) out.push(name); + } + return out; + } + + /* -------------------------------------------------------------- */ + /* Stats */ + /* -------------------------------------------------------------- */ + + stats(): CacheStats { + let decodedBytes = 0; + let fileBytes = 0; + const byPrefix: Record = {}; + + for (const [name, info] of this.images) { + decodedBytes += info.decodedBytes; + fileBytes += info.fileBytes; + const slash = name.indexOf("/"); + const prefix = slash >= 0 ? name.slice(0, slash) : name; + const bucket = byPrefix[prefix] ?? { count: 0, decodedBytes: 0, fileBytes: 0 }; + bucket.count += 1; + bucket.decodedBytes += info.decodedBytes; + bucket.fileBytes += info.fileBytes; + byPrefix[prefix] = bucket; + } + + return { count: this.images.size, decodedBytes, fileBytes, byPrefix }; + } + + /* -------------------------------------------------------------- */ + /* Unload */ + /* -------------------------------------------------------------- */ + + unload(names: string[]): void { + for (const name of names) { + const info = this.images.get(name); + if (!info) continue; + closeImage(info.image); + this.images.delete(name); + } + this.checkThreshold(); + } + + unloadPrefix(prefix: string): void { + const toRemove: string[] = []; + for (const name of this.images.keys()) { + if (name.startsWith(prefix)) toRemove.push(name); + } + this.unload(toRemove); + } + + unloadPattern(pattern: RegExp): void { + const toRemove: string[] = []; + for (const name of this.images.keys()) { + if (pattern.test(name)) toRemove.push(name); + } + this.unload(toRemove); + } + + unloadAll(): void { + this.unload([...this.images.keys()]); + } + + /* -------------------------------------------------------------- */ + /* Internals */ + /* -------------------------------------------------------------- */ + + private currentMetricValue(): number { + let decoded = 0; + let file = 0; + for (const info of this.images.values()) { + decoded += info.decodedBytes; + file += info.fileBytes; + } + if (this.warnMetric === "file") return file; + if (this.warnMetric === "both") return Math.max(decoded, file); + return decoded; + } + + private checkThreshold(): void { + const value = this.currentMetricValue(); + if (value > this.warnThresholdBytes) { + if (!this.warned) { + this.warned = true; + const mb = (value / 1024 / 1024).toFixed(1); + const limitMb = (this.warnThresholdBytes / 1024 / 1024).toFixed(1); + const metric = + this.warnMetric === "file" + ? "compressed file size" + : this.warnMetric === "both" + ? "decoded or file size" + : "decoded RGBA size"; + this.onWarn( + `[shimejic] Asset cache ${metric} is ${mb} MB ` + + `(threshold ${limitMb} MB). Consider reducing sprite ` + + `resolution or using preload: 'lazy'.`, + ); + } + } else { + this.warned = false; + } + } +} + +function closeImage(image: CanvasImageSource): void { + const candidate = image as { close?: () => void }; + if (typeof candidate.close === "function") { + try { + candidate.close(); + } catch { + // Some sources throw if already released. + } + } +} diff --git a/packages/shimejic/src/core/behavior.ts b/packages/shimejic/src/core/behavior.ts new file mode 100644 index 0000000..963b5bd --- /dev/null +++ b/packages/shimejic/src/core/behavior.ts @@ -0,0 +1,692 @@ +/** + * behavior.ts — the animation state machine. + * + * Given a state name (from the app), a cursor (optional), and a dt, decides + * which clip to play and at what frame. Maintains the invariants: + * + * - Every clip plays from frame 0 (except look, see below). + * - Events queue to cycle boundaries, never interrupt mid-clip. + * - Look swaps are frame-synced: entering look at base frame N plays + * look at (N+1)%L. Exiting at look frame M plays base at (M+1)%L. + * - Look and events are mutually exclusive: neither can start while + * the other is active or queued. + * - State changes reset to frame 0 (or enter clip frame 0). + * + * Determinism: same inputs → same outputs. No timers on the wall clock, + * no randomness in the state machine itself (only in event selection, + * which is seeded by Math.random — inject your own RNG if you need + * strict reproducibility). + */ + +import { imageSize } from "./animation.ts"; +import { matchSector, type CursorInfo, type CursorSector } from "./cursor.ts"; +import type { SpriteFrame } from "./entity.ts"; + +/* ------------------------------------------------------------------ */ +/* Types */ +/* ------------------------------------------------------------------ */ + +export interface AnimationClip { + frames: CanvasImageSource[]; + fps: number; + /** Default true. */ + loop?: boolean; +} + +export interface LookSector extends CursorSector { + clip: AnimationClip; +} + +export interface LookConfig { + pivot: { x: number; y: number }; + distance: { min: number; max: number }; + hysteresis: number; + sectors: LookSector[]; +} + +export interface ChatterCue { + /** Frame index or milliseconds into the event clip. */ + at: number; + unit: "frame" | "ms"; + /** One line or a pool to pick from. */ + text: string | string[]; + /** Optional typing speed override. */ + typeSpeed?: number; + /** Optional display duration override. */ + duration?: number; +} + +export interface EventDef { + name: string; + clip: AnimationClip; + /** Selection weight among eligible events at a boundary. Default 1. */ + weight?: number; + /** 0..1 chance per roll. Default 1. */ + chance?: number; + /** Seconds between roll attempts, randomized in [min, max]. */ + interval: [number, number]; + /** Seconds after firing during which this event can't fire again. Default 0. */ + cooldown?: number; + /** What to do when a state change arrives mid-play. Default 'cut'. */ + interrupt?: "cut" | "finish"; + /** Optional chatter cues fired during the event. */ + chatter?: ChatterCue[]; +} + +export interface EnterContext { + previousState: string; + impactSpeed?: number; + [key: string]: unknown; +} + +export interface BehaviorState { + /** Base clip. Required. Should loop. */ + base: AnimationClip; + /** Enter variant: static clip or a function that picks one. */ + enter?: AnimationClip | ((ctx: EnterContext) => AnimationClip | undefined); + /** Random event pool. */ + events?: EventDef[]; + /** Cursor look config. Omit to disable look for this state. */ + look?: LookConfig; +} + +export interface BehaviorBounds { + x: number; + y: number; + width: number; + height: number; +} + +export interface BehaviorContext { + /** State name from the app's resolver. */ + state: string; + /** World-space cursor position, or null. */ + cursor?: { x: number; y: number } | null; + /** World-space sprite bounding box, required when `cursor` is set. */ + bounds?: BehaviorBounds; + /** Impact speed for conditional enters. */ + impactSpeed?: number; + [key: string]: unknown; +} + +export interface BehaviorControllerConfig { + states: Record; + /** Called when a chatter cue or manual chatter fires. */ + onChatter?: (text: string, source: "event" | "manual") => void; + /** Injection point for deterministic tests. Default Math.random. */ + rng?: () => number; + /** Called with a human-readable message when the config is malformed. */ + onWarn?: (message: string) => void; +} + +export type TrackName = "base" | "enter" | "look" | "event"; + +export interface DebugSnapshot { + state: string; + track: TrackName; + clip: string; + frameIndex: number; + frameCount: number; + lookFolder: string | null; + cursor: CursorInfo | null; + matchedFolder: string | null; + queuedEvent: string | null; + activeEvent: string | null; + cooldowns: Record; + pendingState: string | null; +} + +/* ------------------------------------------------------------------ */ +/* BehaviorController */ +/* ------------------------------------------------------------------ */ + +export class BehaviorController { + private readonly states: Record; + private readonly onChatter: ((text: string, source: "event" | "manual") => void) | undefined; + private readonly rng: () => number; + private readonly onWarn: (message: string) => void; + + /* --- runtime --- */ + private _state = ""; + private activeClip: AnimationClip | null = null; + private track: TrackName = "base"; + private frameIndex = 0; + private frameTimer = 0; + private clipFinished = false; + private hitBoundary = false; + private trackTime = 0; + private pendingSectorSwap: LookSector | null = null; + + private lookFolder: string | null = null; + + private activeEvent: EventDef | null = null; + private queuedEvent: EventDef | null = null; + + /** Cooldown+roll state, keyed by `${state}:${event}`. Persists across state changes. */ + private eventTimers = new Map(); + + private now = 0; + private pendingState: string | null = null; + private pendingContext: BehaviorContext | null = null; + + private firedCues = new Set(); + private matchedSectorFolder: string | null = null; + + constructor(cfg: BehaviorControllerConfig) { + this.states = cfg.states; + this.onChatter = cfg.onChatter; + this.rng = cfg.rng ?? Math.random; + this.onWarn = cfg.onWarn ?? (msg => console.warn(`[shimejic behavior] ${msg}`)); + + this.validateConfig(); + } + + /* -------------------------------------------------------------- */ + /* Public API */ + /* -------------------------------------------------------------- */ + + update(dt: number, ctx: BehaviorContext): void { + this.now += dt; + + if (ctx.state !== this._state) { + this.handleStateChange(ctx); + } + + this.tickLook(ctx); + this.tickFrame(dt); + this.maybeFireEventCues(); + + if (this.hitBoundary) { + this.hitBoundary = false; + this.handleCycleBoundary(ctx); + } + + if (this.clipFinished) { + this.clipFinished = false; + if (this.pendingState !== null) { + this.applyPendingState(); + } else { + this.handleTrackCompletion(ctx); + } + } + } + + frame(): SpriteFrame | null { + const clip = this.activeClip; + if (clip === null || clip.frames.length === 0) return null; + const image = clip.frames[this.frameIndex]; + if (image === undefined) return null; + const size = imageSize(image); + return { image, width: size.width, height: size.height, sx: 0, sy: 0, sw: size.width, sh: size.height }; + } + + get state(): string { + return this._state; + } + + get activeTrack(): TrackName { + return this.track; + } + + get frameNumber(): number { + return this.frameIndex; + } + + get lookSector(): string | null { + return this.lookFolder; + } + + get queuedEventName(): string | null { + return this.queuedEvent?.name ?? null; + } + + get activeEventName(): string | null { + return this.activeEvent?.name ?? null; + } + + debugSnapshot(): DebugSnapshot { + const total = this.activeClip?.frames.length ?? 0; + const cooldowns: Record = {}; + for (const [key, t] of this.eventTimers) { + const remaining = t.cooldownUntil - this.now; + if (remaining > 0) cooldowns[key] = remaining; + } + return { + state: this._state, + track: this.track, + clip: this.activeClip === null ? "—" : `${this.activeClip.frames.length}f@${this.activeClip.fps}fps`, + frameIndex: this.frameIndex, + frameCount: total, + lookFolder: this.lookFolder, + cursor: null, + matchedFolder: this.matchedSectorFolder, + queuedEvent: this.queuedEvent?.name ?? null, + activeEvent: this.activeEvent?.name ?? null, + cooldowns, + pendingState: this.pendingState, + }; + } + + /** + * Manually queue an event. + * Returns true if the event was queued, false if rejected. + * Rejected when: state mismatch, queue occupied, event currently active, + * or event doesn't exist in the state's event list. + * Ignores cooldowns — manual pushes are intentional. + */ + pushEvent(stateName: string, eventName: string): boolean { + if (stateName !== this._state) return false; + if (this.queuedEvent !== null) return false; + if (this.activeEvent !== null) return false; + + const def = this.states[stateName]; + if (!def?.events) return false; + const event = def.events.find(e => e.name === eventName); + if (!event) return false; + + this.queuedEvent = event; + const key = `${stateName}:${eventName}`; + const timer = this.eventTimers.get(key); + if (timer) { + timer.cooldownUntil = this.now + (event.cooldown ?? 0); + timer.nextRoll = this.now + this.randomInterval(event); + } + return true; + } + + /** Push a raw chatter line, bypassing events. */ + pushChatter(text: string): void { + this.onChatter?.(text, "manual"); + } + + /* -------------------------------------------------------------- */ + /* State changes */ + /* -------------------------------------------------------------- */ + + private handleStateChange(ctx: BehaviorContext): void { + // If an event is active with 'finish' policy, defer. + if (this.activeEvent !== null && this.activeEvent.interrupt === "finish") { + this.pendingState = ctx.state; + this.pendingContext = ctx; + return; + } + + this.applyState(ctx); + } + + private applyState(ctx: BehaviorContext): void { + const previous = this._state; + const next = ctx.state; + const def = this.states[next]; + + this._state = next; + this.activeEvent = null; + this.queuedEvent = null; + this.lookFolder = null; + this.matchedSectorFolder = null; + this.firedCues.clear(); + this.pendingState = null; + this.pendingContext = null; + + if (def === undefined) { + this.onWarn(`Unknown state "${next}" — no clip will play`); + this.activeClip = null; + this.track = "base"; + this.frameIndex = 0; + this.frameTimer = 0; + return; + } + + // Enter variant? + let enterClip: AnimationClip | undefined; + if (def.enter !== undefined) { + if (typeof def.enter === "function") { + enterClip = def.enter({ + previousState: previous, + ...(ctx.impactSpeed !== undefined && { impactSpeed: ctx.impactSpeed }), + }); + } else { + enterClip = def.enter; + } + } + + if (enterClip !== undefined) { + this.activeClip = enterClip; + this.track = "enter"; + } else { + this.activeClip = def.base; + this.track = "base"; + } + + this.frameIndex = 0; + this.frameTimer = 0; + this.clipFinished = false; + this.hitBoundary = false; + this.trackTime = 0; + } + + private applyPendingState(): void { + if (this.pendingState === null) return; + const ctx = this.pendingContext ?? { state: this.pendingState }; + this.pendingState = null; + this.pendingContext = null; + this.applyState(ctx); + } + + /* -------------------------------------------------------------- */ + /* Frame advancing */ + /* -------------------------------------------------------------- */ + + private tickFrame(dt: number): void { + const clip = this.activeClip; + if (clip === null) return; + + this.trackTime += dt; + this.frameTimer += dt; + + const frameDuration = 1 / clip.fps; + while (this.frameTimer >= frameDuration) { + this.frameTimer -= frameDuration; + this.frameIndex += 1; + + if (this.frameIndex >= clip.frames.length) { + if (clip.loop !== false) { + this.frameIndex = 0; + this.hitBoundary = true; + break; + } else { + this.frameIndex = clip.frames.length - 1; + this.clipFinished = true; + break; + } + } + } + } + + /* -------------------------------------------------------------- */ + /* Look */ + /* -------------------------------------------------------------- */ + + private tickLook(ctx: BehaviorContext): void { + const def = this.states[this._state]; + const look = def?.look; + + const cursor = ctx.cursor; + const bounds = ctx.bounds; + + if ( + look === undefined || + this.activeEvent !== null || + cursor === undefined || + cursor === null || + bounds === undefined || + (this.track !== "base" && this.track !== "look") + ) { + if (this.lookFolder !== null) this.exitLook(); + return; + } + + const pivot = { + x: bounds.x + look.pivot.x * bounds.width, + y: bounds.y + look.pivot.y * bounds.height, + }; + const info: CursorInfo = { + angle: angleOf(pivot, cursor), + distance: distanceOf(pivot, cursor), + }; + + const match = matchSector(info, look, this.matchedSectorFolder); + this.matchedSectorFolder = match?.sector.folder ?? null; + + if (match === null) { + if (this.lookFolder !== null) this.exitLook(); + return; + } + + const targetSector = match.sector; + if (this.lookFolder === null) { + this.enterLook(targetSector); + } else if (this.lookFolder !== targetSector.folder) { + this.swapLook(targetSector); + } + } + + /** + * Swap the look clip mid-frame. The current frame's remaining duration + * plays in the new direction, then advances at the next boundary. Phase + * and timing are preserved; only the visual changes. + */ + private swapLook(sector: LookSector): void { + this.activeClip = sector.clip; + this.lookFolder = sector.folder; + // frameIndex, frameTimer, trackTime are all left unchanged. + } + + /** + * Enter look by swapping to the sector clip at the current phase. + * The current frame finishes its remaining duration in the new direction, + * then advances normally. + */ + private enterLook(sector: LookSector): void { + this.activeClip = sector.clip; + this.track = "look"; + this.lookFolder = sector.folder; + // frameIndex, frameTimer, trackTime are all preserved. + } + + /** + * Exit look by swapping back to the base clip at the current phase. + * Mirrors enterLook: same phase, same remaining frame duration. + */ + private exitLook(): void { + const def = this.states[this._state]; + if (def === undefined) { + this.lookFolder = null; + return; + } + this.activeClip = def.base; + this.track = "base"; + this.lookFolder = null; + // frameIndex, frameTimer, trackTime are all preserved. + } + + /* -------------------------------------------------------------- */ + /* Cycle boundary / event pool */ + /* -------------------------------------------------------------- */ + + private handleCycleBoundary(ctx: BehaviorContext): void { + // If look is active, events can't fire. Skip. + if (this.lookFolder !== null) return; + + // If an event is queued, play it now. + if (this.queuedEvent !== null) { + this.activateEvent(this.queuedEvent); + this.queuedEvent = null; + return; + } + + // If an event is active (shouldn't happen — active events don't loop), + // skip. + if (this.activeEvent !== null) return; + + // Roll for new events. + this.rollEvents(); + } + + private rollEvents(): void { + const def = this.states[this._state]; + if (def?.events === undefined || def.events.length === 0) return; + + const candidates: EventDef[] = []; + for (const event of def.events) { + const key = `${this._state}:${event.name}`; + const timer = this.eventTimers.get(key); + + // Initialize timer on first check + if (timer === undefined) { + this.eventTimers.set(key, { + nextRoll: this.now + this.randomInterval(event), + cooldownUntil: 0, + }); + continue; + } + + // Not ready yet? + if (this.now < timer.nextRoll) continue; + if (this.now < timer.cooldownUntil) continue; + + // Consume this roll opportunity regardless of outcome. + timer.nextRoll = this.now + this.randomInterval(event); + + // Roll chance + const chance = event.chance ?? 1; + if (this.rng() < chance) { + candidates.push(event); + } + } + + if (candidates.length === 0) return; + + // Weighted pick + const weights = candidates.map(e => e.weight ?? 1); + const totalWeight = weights.reduce((a, b) => a + b, 0); + let roll = this.rng() * totalWeight; + let picked = candidates[candidates.length - 1]!; + for (let i = 0; i < candidates.length; i++) { + roll -= weights[i] ?? 1; + if (roll <= 0) { + picked = candidates[i]!; + break; + } + } + + this.queuedEvent = picked; + } + + private activateEvent(event: EventDef): void { + this.activeEvent = event; + this.track = "event"; + this.activeClip = event.clip; + this.frameIndex = 0; + this.frameTimer = 0; + this.clipFinished = false; + this.hitBoundary = false; + this.trackTime = 0; + this.firedCues.clear(); + + // Set cooldown + const key = `${this._state}:${event.name}`; + const timer = this.eventTimers.get(key) ?? { nextRoll: 0, cooldownUntil: 0 }; + timer.cooldownUntil = this.now + (event.cooldown ?? 0); + this.eventTimers.set(key, timer); + } + + /* -------------------------------------------------------------- */ + /* Track completion */ + /* -------------------------------------------------------------- */ + + private handleTrackCompletion(ctx: BehaviorContext): void { + if (this.track === "enter") { + // Enter finished, hand off to base (or look if applicable). + const def = this.states[this._state]; + if (def === undefined) return; + this.activeClip = def.base; + this.track = "base"; + this.frameIndex = 0; + this.frameTimer = 0; + this.trackTime = 0; + return; + } + + if (this.track === "event") { + // Event finished, hand off to base at frame 0. + this.activeEvent = null; + const def = this.states[this._state]; + if (def === undefined) return; + this.activeClip = def.base; + this.track = "base"; + this.frameIndex = 0; + this.frameTimer = 0; + this.trackTime = 0; + this.firedCues.clear(); + + // If a pending state change was waiting, apply it. + if (this.pendingState !== null) { + this.applyPendingState(); + } + return; + } + + // Base or look clip finishing (non-looping): start over. + this.frameIndex = 0; + this.frameTimer = 0; + } + + /* -------------------------------------------------------------- */ + /* Chatter cues */ + /* -------------------------------------------------------------- */ + + private maybeFireEventCues(): void { + const event = this.activeEvent; + if (event === null || event.chatter === undefined) return; + + for (let i = 0; i < event.chatter.length; i++) { + if (this.firedCues.has(i)) continue; + const cue = event.chatter[i]; + if (cue === undefined) continue; + + const reached = cue.unit === "frame" ? this.frameIndex >= cue.at : this.trackTime * 1000 >= cue.at; + + if (!reached) continue; + + this.firedCues.add(i); + const text = Array.isArray(cue.text) + ? (cue.text[Math.floor(this.rng() * cue.text.length)] ?? cue.text[0] ?? "") + : cue.text; + this.onChatter?.(text, "event"); + } + } + + /* -------------------------------------------------------------- */ + /* Helpers */ + /* -------------------------------------------------------------- */ + + private randomInterval(event: EventDef): number { + const [min, max] = event.interval; + return min + this.rng() * (max - min); + } + + private validateConfig(): void { + for (const [stateName, def] of Object.entries(this.states)) { + if (def.look !== undefined) { + for (const sector of def.look.sectors) { + if (sector.clip.frames.length !== def.base.frames.length) { + this.onWarn( + `State "${stateName}": look sector "${sector.folder}" has ` + + `${sector.clip.frames.length} frames but base has ${def.base.frames.length}. ` + + `Look will not activate for this sector.`, + ); + } + } + } + } + } +} + +/* ------------------------------------------------------------------ */ +/* Local math (avoids importing cursor internals) */ +/* ------------------------------------------------------------------ */ + +function angleOf(pivot: { x: number; y: number }, point: { x: number; y: number }): number { + const dx = point.x - pivot.x; + const dy = point.y - pivot.y; + const rad = Math.atan2(dx, -dy); + const deg = (rad * 180) / Math.PI; + return ((deg % 360) + 360) % 360; +} + +function distanceOf(pivot: { x: number; y: number }, point: { x: number; y: number }): number { + const dx = point.x - pivot.x; + const dy = point.y - pivot.y; + return Math.sqrt(dx * dx + dy * dy); +} diff --git a/packages/shimejic/src/core/camera.ts b/packages/shimejic/src/core/camera.ts new file mode 100644 index 0000000..ae95b31 --- /dev/null +++ b/packages/shimejic/src/core/camera.ts @@ -0,0 +1,48 @@ +/** + * camera.ts — optional view transform. + * + * Identity by default: `toScreen` returns the input unchanged, `toWorld` + * is the inverse. Every world coordinate in the renderer is passed through + * `camera.toScreen()` before drawing, so the default path is a no-op + * multiply. + * + * Follow/target logic is not implemented in v1. The class exists so a + * camera can be introduced without a renderer change. + */ + +import type { Vec2 } from "./physics.ts"; + +export interface CameraConfig { + /** World coordinate of the viewport's top-left corner. Default {0,0}. */ + position?: Vec2; + /** Scale factor. Default 1. */ + zoom?: number; +} + +export class Camera { + position: Vec2; + zoom: number; + + constructor(cfg: CameraConfig = {}) { + this.position = { x: cfg.position?.x ?? 0, y: cfg.position?.y ?? 0 }; + this.zoom = cfg.zoom ?? 1; + } + + /** Identity when position is {0,0} and zoom is 1. */ + toScreen(world: Vec2): Vec2 { + return { + x: (world.x - this.position.x) * this.zoom, + y: (world.y - this.position.y) * this.zoom, + }; + } + + toWorld(screen: Vec2): Vec2 { + return { + x: screen.x / this.zoom + this.position.x, + y: screen.y / this.zoom + this.position.y, + }; + } + + /** Reserved for follow logic. No-op in v1. */ + update(_dt: number): void {} +} diff --git a/packages/shimejic/src/core/character-config.ts b/packages/shimejic/src/core/character-config.ts new file mode 100644 index 0000000..176d942 --- /dev/null +++ b/packages/shimejic/src/core/character-config.ts @@ -0,0 +1,369 @@ +export interface FrameRegion { + x: number; + y: number; + w: number; + h: number; + offsetX: number; + offsetY: number; + sourceW: number; + sourceH: number; +} + +export interface AtlasDefinition { + url: string; + width: number; + height: number; + frames: Record; +} + +export interface ClipDefinition { + atlas: string; + frames: string[]; + framerate: number; + loop?: boolean; +} + +export interface LookSectorDefinition { + minAngle: number; + maxAngle: number; + minDistance: number; + maxDistance: number; + atlas: string; + frames: string[]; +} + +export interface LookDefinition { + pivot: { x: number; y: number }; + distance: { min: number; max: number }; + hysteresis: number; + sectors: LookSectorDefinition[]; +} + +export interface EventDefinition { + name: string; + atlas: string; + frames: string[]; + framerate: number; + chance: number; + interval: [number, number]; + cooldown: number; + weight: number; + interrupt?: "cut" | "finish"; + chatter?: ChatterCueDefinition[]; +} + +export interface ChatterCueDefinition { + at: number; + unit: "frame" | "ms"; + text: string; +} + +export interface StateDefinition { + base: ClipDefinition; + enter?: ClipDefinition; + look?: LookDefinition; + events?: EventDefinition[]; +} + +export interface TextDefinition { + font: string; + color: string; + align: "left" | "center" | "right"; + padding: { top: number; right: number; bottom: number; left: number }; + lineHeight: number; + wrap: boolean; + wrapLongWords: boolean; + speed: number; + startFrame: number; +} + +export interface TimingDefinition { + duration?: number | "auto"; + holdLast: number; +} + +export interface BubbleDefinition { + atlas: string; + frames: string[]; + framerate?: number; + width: number; + height: number; + anchorX?: number; + anchorY?: number; + frameMode?: "loop" | "hold" | "reverse-on-dismiss"; + text?: Partial; +} + +export interface IconDefinition { + atlas: string; + frames: string[]; +} + +export interface VoiceDefinition { + basePitch?: number; + formatScale?: number; + noiseMix?: number; + volume?: number; +} + +export interface CharacterConfig { + ver: 1; + id: string; + initialState: string; + spawnState?: string; + atlases: Record; + states: Record; + bubbles: Record; + icons?: Record; + text?: Partial; + timing?: Partial; + voice?: VoiceDefinition; +} + +export interface ValidationError { + path: string; + message: string; +} + +export function validateConfig(config: unknown): ValidationError[] { + const errors: ValidationError[] = []; + + const push = (path: string, message: string): void => { + errors.push({ path, message }); + }; + + if (typeof config !== "object" || config === null) { + push("", "config must be an object"); + return errors; + } + + const c = config as Partial; + + if (c.ver !== 1) push("version", `expected 1, got ${c.ver}`); + if (typeof c.id !== "string" || c.id.length === 0) push("id", "must be a non-empty string"); + if (typeof c.initialState !== "string") push("initialState", "must be a string"); + + if (typeof c.atlases !== "object" || c.atlases === null) { + push("atlases", "must be an object"); + return errors; + } + if (typeof c.states !== "object" || c.states === null) { + push("states", "must be an object"); + return errors; + } + + for (const [name, atlas] of Object.entries(c.atlases)) { + validateAtlas(atlas, `atlases.${name}`, push); + } + + if (typeof c.initialState === "string" && !(c.initialState in c.states)) { + push("initialState", `references unknown state "${c.initialState}"`); + } + + if (c.spawnState !== undefined) { + if (!(c.spawnState in c.states)) { + push("spawnState", `references unknown state "${c.spawnState}"`); + } + } + + for (const [name, state] of Object.entries(c.states)) { + validateState(state, `states.${name}`, c.atlases, push); + } + + if (c.bubbles) { + for (const [name, bubble] of Object.entries(c.bubbles)) { + validateBubble(bubble, `bubbles.${name}`, c.atlases, push); + } + } + + if (c.icons) { + for (const [name, icon] of Object.entries(c.icons)) { + validateIcon(icon, `icons.${name}`, c.atlases, push); + } + } + + return errors; +} + +function validateAtlas(atlas: AtlasDefinition, path: string, push: (path: string, message: string) => void): void { + if (typeof atlas.url !== "string") push(`${path}.url`, "must be a string"); + if (typeof atlas.width !== "number" || atlas.width <= 0) { + push(`${path}.width`, "must be a positive number"); + } + if (typeof atlas.height !== "number" || atlas.height <= 0) { + push(`${path}.height`, "must be a positive number"); + } + if (typeof atlas.frames !== "object" || atlas.frames === null) { + push(`${path}.frames`, "must be an object"); + return; + } + for (const [frameName, region] of Object.entries(atlas.frames)) { + validateFrameRegion(region, `${path}.frames.${frameName}`, push); + } +} + +function validateFrameRegion(region: FrameRegion, path: string, push: (path: string, message: string) => void): void { + if (typeof region.x !== "number") push(`${path}.x`, "must be a number"); + if (typeof region.y !== "number") push(`${path}.y`, "must be a number"); + if (typeof region.w !== "number" || region.w <= 0) push(`${path}.w`, "must be a positive number"); + if (typeof region.h !== "number" || region.h <= 0) push(`${path}.h`, "must be a positive number"); +} + +function validateClip( + clip: ClipDefinition, + path: string, + atlases: Record, + push: (path: string, message: string) => void, +): void { + if (typeof clip.atlas !== "string") { + push(`${path}.atlas`, "must be a string"); + } else if (!(clip.atlas in atlases)) { + push(`${path}.atlas`, `references unknown atlas "${clip.atlas}"`); + } else if (Array.isArray(clip.frames)) { + const atlas = atlases[clip.atlas]; + if (atlas !== undefined) { + for (let i = 0; i < clip.frames.length; i++) { + const frameName = clip.frames[i]; + if (frameName !== undefined && !(frameName in atlas.frames)) { + push(`${path}.frames[${i}]`, `unknown frame "${frameName}" in atlas "${clip.atlas}"`); + } + } + } + } + + if (!Array.isArray(clip.frames) || clip.frames.length === 0) { + push(`${path}.frames`, "must be a non-empty array"); + } + if (typeof clip.framerate !== "number" || clip.framerate <= 0) { + push(`${path}.framerate`, "must be a positive number"); + } +} + +function validateState( + state: StateDefinition, + path: string, + atlases: Record, + push: (path: string, message: string) => void, +): void { + if (state.base === undefined) { + push(`${path}.base`, "is required"); + } else { + validateClip(state.base, `${path}.base`, atlases, push); + } + + if (state.enter !== undefined) { + validateClip(state.enter, `${path}.enter`, atlases, push); + } + + if (state.look !== undefined) { + validateLook(state.look, `${path}.look`, state.base, atlases, push); + } + + if (state.events !== undefined) { + for (let i = 0; i < state.events.length; i++) { + const ev = state.events[i]; + if (ev === undefined) continue; + const ep = `${path}.events[${i}]`; + // Event clip validation reuses validateClip + validateClip({ atlas: ev.atlas, frames: ev.frames, framerate: ev.framerate }, ep, atlases, push); + if (typeof ev.chance !== "number" || ev.chance < 0 || ev.chance > 1) { + push(`${ep}.chance`, "must be between 0 and 1"); + } + if (!Array.isArray(ev.interval) || ev.interval.length !== 2) { + push(`${ep}.interval`, "must be in the correct format [min, max]"); + } else if (ev.interval[0] > ev.interval[1]) { + push(`${ep}.interval`, "min must be <= max"); + } + if (typeof ev.cooldown !== "number" || ev.cooldown < 0) { + push(`${ep}.cooldown`, "must be >= 0"); + } + if (typeof ev.weight !== "number" || ev.weight < 0) { + push(`${ep}.weight`, "must be >= 0"); + } + } + } +} + +function validateLook( + look: LookDefinition, + path: string, + base: ClipDefinition, + atlases: Record, + push: (path: string, message: string) => void, +): void { + if (typeof look.pivot?.x !== "number" || typeof look.pivot?.y !== "number") { + push(`${path}.pivot`, "must have numeric x and y"); + } + if (typeof look.distance?.min !== "number" || typeof look.distance?.max !== "number") { + push(`${path}.distance`, "must have numeric min and max"); + } + if (typeof look.hysteresis !== "number" || look.hysteresis < 0) { + push(`${path}.hysteresis`, "must be >= 0"); + } + if (!Array.isArray(look.sectors)) { + push(`${path}.sectors`, "must be an array"); + return; + } + + const baseFrameCount = Array.isArray(base.frames) ? base.frames.length : 0; + + for (let i = 0; i < look.sectors.length; i++) { + const sector = look.sectors[i]; + if (sector === undefined) continue; + const sp = `${path}.sectors[${i}]`; + if (typeof sector.minAngle !== "number" || typeof sector.maxAngle !== "number") { + push(sp, "minAngle and maxAngle must be numbers"); + } + if (sector.minDistance !== undefined || sector.maxDistance !== undefined) { + push(sp, "minDistance and maxDistance must both be set or both be omitted"); + } else if (typeof sector.minDistance !== "number" || typeof sector.maxDistance !== "number") { + push(sp, "minDistance and maxDistance must be numbers"); + } else if (sector.minDistance > sector.maxDistance) { + push(sp, "minDistance must be <= maxDistance"); + } + if (typeof sector.atlas !== "string" || !(sector.atlas in atlases)) { + push(`${sp}.atlas`, `references unknown atlas "${sector.atlas}"`); + continue; + } + if (!Array.isArray(sector.frames)) { + push(`${sp}.frames`, "must be an array"); + continue; + } + const atlas = atlases[sector.atlas]; + if (atlas !== undefined) { + for (let j = 0; j < sector.frames.length; j++) { + const frameName = sector.frames[j]; + if (frameName !== undefined && !(frameName in atlas.frames)) { + push(`${sp}.frames[${j}]`, `unknown frame "${frameName}"`); + } + } + } + if (baseFrameCount > 0 && sector.frames.length !== baseFrameCount) { + push(`${sp}.frames`, `frame count ${sector.frames.length} doesn't match base count ${baseFrameCount}`); + } + } +} + +function validateBubble( + bubble: BubbleDefinition, + path: string, + atlases: Record, + push: (path: string, message: string) => void, +): void { + validateClip({ atlas: bubble.atlas, frames: bubble.frames, framerate: bubble.framerate ?? 8 }, path, atlases, push); + if (typeof bubble.width !== "number" || bubble.width <= 0) { + push(`${path}.width`, "must be a positive number"); + } + if (typeof bubble.height !== "number" || bubble.height <= 0) { + push(`${path}.height`, "must be a positive number"); + } +} + +function validateIcon( + icon: IconDefinition, + path: string, + atlases: Record, + push: (path: string, message: string) => void, +): void { + validateClip({ atlas: icon.atlas, frames: icon.frames, framerate: 1 }, path, atlases, push); +} diff --git a/packages/shimejic/src/core/chatter-overlay.ts b/packages/shimejic/src/core/chatter-overlay.ts new file mode 100644 index 0000000..6f386ed --- /dev/null +++ b/packages/shimejic/src/core/chatter-overlay.ts @@ -0,0 +1,554 @@ +/** + * chatter-overlay.ts — speech bubble rendering with typewriter reveal. + * + * Manages per-entity bubble state: current message, queue, elapsed time, + * bubble frame animation, typewriter reveal, and layout caching. + * + * Consumes the parser's token stream. Does not consume audio — mumble + * hooks in later via the same token stream. + * + * Usage: + * const overlay = new ChatterOverlay({ measure }); + * overlay.setConfig('cat', { bubble, text, timing }); + * overlay.registerIcon('fish', fishImage); + * overlay.say('cat', 'hello {pause 200} world'); + * // each frame: + * overlay.update(dt); + * // in render: + * const data = overlay.getRenderData('cat'); + * if (data) { drawBubble(ctx, x, y, data); } + */ + +import { parseMessage } from "./chatter-parser.ts"; +import type { BubbleRenderData, ChatterSlot, Layout, LayoutItem, ParsedMessage, VoiceConfig } from "./chatter-types.ts"; +import type { Mumble } from "./mumble"; + +/* ------------------------------------------------------------------ */ +/* Config */ +/* ------------------------------------------------------------------ */ + +export interface ChatterOverlayConfig { + /** + * Optional measurement function for tests. If omitted, uses an + * offscreen canvas. + */ + measure?: (text: string, font: string) => number; + mumble?: Mumble; + voice?: VoiceConfig; +} + +/* ------------------------------------------------------------------ */ +/* Runtime state */ +/* ------------------------------------------------------------------ */ + +interface QueuedMessage { + text: string; + priority: number; +} + +interface RuntimeState { + parsed: ParsedMessage; + layout: Layout; + config: ChatterSlot; + font: string; + color: string; + align: "left" | "center" | "right"; + wrapLongWords: boolean; + + /** Total time since the bubble appeared. */ + bubbleElapsed: number; + /** Time since typing began (bubbleElapsed - introDuration). */ + textElapsed: number; + /** Bubble animation intro duration before typing starts. */ + introDuration: number; + /** Total bubble duration (typing + hold, or explicit). */ + totalDuration: number; + + /** True after typing finishes. */ + typingComplete: boolean; + /** True after the bubble's total duration elapses (dismissing reverse anim). */ + dismissing: boolean; + /** Time since dismissing began. */ + dismissElapsed: number; + + queue: QueuedMessage[]; + currentText: string; +} + +/* ------------------------------------------------------------------ */ +/* Overlay */ +/* ------------------------------------------------------------------ */ + +export class ChatterOverlay { + private readonly measure: (text: string, font: string) => number; + private readonly mumble: Mumble | null; + private readonly voice: VoiceConfig | undefined; + private readonly configs = new Map(); + private readonly runtimes = new Map(); + private readonly icons = new Map(); + private ctx: CanvasRenderingContext2D | null = null; + + constructor(cfg: ChatterOverlayConfig = {}) { + this.measure = cfg.measure ?? ((text, font) => this.measureWithCanvas(text, font)); + this.mumble = cfg.mumble ?? null; + this.voice = cfg.voice; + } + + /* -------------------------------------------------------------- */ + /* Registration */ + /* -------------------------------------------------------------- */ + + setConfig(entityId: string, slot: ChatterSlot): void { + this.configs.set(entityId, slot); + } + + removeConfig(entityId: string): void { + this.configs.delete(entityId); + this.runtimes.delete(entityId); + } + + registerIcon(name: string, image: CanvasImageSource): void { + this.icons.set(name, image); + } + + unregisterIcon(name: string): void { + this.icons.delete(name); + } + + /* -------------------------------------------------------------- */ + /* Public API */ + /* -------------------------------------------------------------- */ + + /** + * Queue a message. Returns true if accepted into the queue. + * Returns false if: no config for entity, empty text, or the + * interrupt policy rejected it (see config.interrupt). + */ + say(entityId: string, text: string): boolean { + const config = this.configs.get(entityId); + if (!config) return false; + if (text.trim().length === 0) return false; + + const runtime = this.runtimes.get(entityId); + const interrupt = config.interrupt ?? "queue"; + + if (runtime && !runtime.dismissing) { + if (interrupt === "reject") return false; + if (interrupt === "replace") { + this.startNewMessage(entityId, text, config); + return true; + } + // queue + const priority = config.priority ?? 0; + const queued: QueuedMessage = { text, priority }; + runtime.queue.push(queued); + runtime.queue.sort((a, b) => b.priority - a.priority); + return true; + } + + this.startNewMessage(entityId, text, config); + return true; + } + + /** Force-clear the current bubble and all queued messages. */ + clear(entityId: string): void { + this.runtimes.delete(entityId); + this.mumble?.stop(entityId); + } + + /** Skip the typewriter effect — instantly complete the current text. */ + skip(entityId: string): void { + const rt = this.runtimes.get(entityId); + if (!rt) return; + if (rt.typingComplete) return; + rt.textElapsed = rt.parsed.totalDuration; + rt.typingComplete = true; + this.mumble?.stop(entityId); + } + + /** Dismiss the current bubble. If queued messages remain, plays the next. */ + dismiss(entityId: string): void { + const rt = this.runtimes.get(entityId); + if (!rt) return; + rt.dismissing = true; + rt.dismissElapsed = 0; + this.mumble?.stop(entityId); + } + + isActive(entityId: string): boolean { + return this.runtimes.has(entityId); + } + + /** 0..1 typing progress. */ + progress(entityId: string): number { + const rt = this.runtimes.get(entityId); + if (!rt) return 0; + if (rt.parsed.totalDuration === 0) return 1; + return Math.min(1, rt.textElapsed / rt.parsed.totalDuration); + } + + /* -------------------------------------------------------------- */ + /* Update */ + /* -------------------------------------------------------------- */ + + update(dt: number): void { + for (const [entityId, rt] of this.runtimes) { + rt.bubbleElapsed += dt; + + // Advance typing + rt.textElapsed = Math.max(0, rt.bubbleElapsed - rt.introDuration); + if (rt.textElapsed >= rt.parsed.totalDuration) { + rt.textElapsed = rt.parsed.totalDuration; + rt.typingComplete = true; + } + + // Advance dismiss animation + if (rt.dismissing) { + rt.dismissElapsed += dt; + const bubbleFps = this.bubbleFps(rt.config); + const reverseDuration = this.frameCount(rt.config) / bubbleFps; + if (rt.dismissElapsed >= reverseDuration) { + this.completeAndAdvance(entityId, rt); + } + continue; + } + + // Natural completion + if (rt.bubbleElapsed >= rt.totalDuration) { + const mode = rt.config.bubble.frameMode ?? "hold"; + if (mode === "reverse-on-dismiss") { + rt.dismissing = true; + rt.dismissElapsed = 0; + } else { + this.completeAndAdvance(entityId, rt); + } + } + } + } + + /* -------------------------------------------------------------- */ + /* Render data */ + /* -------------------------------------------------------------- */ + + getRenderData(entityId: string): BubbleRenderData | null { + const rt = this.runtimes.get(entityId); + if (!rt) return null; + + const image = this.currentBubbleFrame(rt); + if (image === null) return null; + + const charsShown = this.computeCharsShown(rt); + + return { + image, + width: rt.config.bubble.width, + height: rt.config.bubble.height, + alpha: rt.config.bubble.opacity ?? 1, + mirrored: false, + anchorX: rt.config.bubble.anchorX ?? 0, + anchorY: rt.config.bubble.anchorY ?? 4, + layout: rt.layout, + charsShown, + padding: rt.config.text.padding, + font: rt.font, + color: rt.color, + align: rt.align, + wrapLongWords: rt.wrapLongWords, + elapsed: rt.bubbleElapsed, + }; + } + + /* -------------------------------------------------------------- */ + /* Internal — start / complete */ + /* -------------------------------------------------------------- */ + + private startNewMessage(entityId: string, text: string, config: ChatterSlot): void { + const font = config.text.font ?? "11px monospace"; + const color = config.text.color ?? "#000"; + const align = config.text.align ?? "center"; + const wrapLongWords = config.text.wrapLongWords ?? false; + const speed = config.text.speed ?? 20; + + const parsed = parseMessage(text, { speed, color }); + const layout = this.buildLayout(parsed, config, font); + + const bubbleFps = this.bubbleFps(config); + const startFrame = config.text.startFrame ?? 0; + const introDuration = startFrame > 0 ? startFrame / bubbleFps : 0; + + const explicitDuration = config.timing?.duration; + const holdLast = config.timing?.holdLast ?? 1.5; + const bubbleCycle = this.frameCount(config) / bubbleFps; + const typingTotal = parsed.totalDuration + introDuration; + const autoDuration = Math.max(typingTotal, bubbleCycle) + holdLast; + const totalDuration = + explicitDuration !== undefined && explicitDuration !== "auto" ? explicitDuration : autoDuration; + + if (this.mumble !== null) { + const voice = config.voice ?? this.voice; + this.mumble.speak(entityId, parsed, voice); + } + + const state: RuntimeState = { + parsed, + layout, + config, + font, + color, + align, + wrapLongWords, + bubbleElapsed: 0, + textElapsed: 0, + introDuration, + totalDuration, + typingComplete: false, + dismissing: false, + dismissElapsed: 0, + queue: this.runtimes.get(entityId)?.queue ?? [], + currentText: text, + }; + + this.runtimes.set(entityId, state); + } + + private completeAndAdvance(entityId: string, rt: RuntimeState): void { + const onComplete = rt.config.onComplete; + if (onComplete) onComplete(entityId, rt.currentText); + + const next = rt.queue.shift(); + if (next) { + this.startNewMessage(entityId, next.text, rt.config); + } else { + this.runtimes.delete(entityId); + this.mumble?.stop(entityId); + } + } + + /* -------------------------------------------------------------- */ + /* Internal — bubble frame */ + /* -------------------------------------------------------------- */ + + private frameCount(config: ChatterSlot): number { + const img = config.bubble.image; + return Array.isArray(img) ? img.length : 1; + } + + private bubbleFps(config: ChatterSlot): number { + return config.bubble.fps ?? 8; + } + + private currentBubbleFrame(rt: RuntimeState): CanvasImageSource | null { + const img = rt.config.bubble.image; + if (!Array.isArray(img)) return img; + if (img.length === 0) return null; + + const fps = this.bubbleFps(rt.config); + + if (rt.dismissing) { + const idx = img.length - 1 - Math.floor(rt.dismissElapsed * fps); + return img[Math.max(0, Math.min(img.length - 1, idx))] ?? null; + } + + const idx = Math.floor(rt.bubbleElapsed * fps); + const mode = rt.config.bubble.frameMode ?? "hold"; + if (mode === "loop") return img[idx % img.length] ?? null; + return img[Math.min(idx, img.length - 1)] ?? null; + } + + /* -------------------------------------------------------------- */ + /* Internal — chars shown */ + /* -------------------------------------------------------------- */ + + private computeCharsShown(rt: RuntimeState): number { + if (rt.typingComplete) return rt.parsed.totalVisible; + + const elapsed = rt.textElapsed; + let accum = 0; + let visible = 0; + for (const token of rt.parsed.tokens) { + if (accum > elapsed) break; + accum += token.duration; + if (token.kind === "char" || token.kind === "icon") visible++; + } + return visible; + } + + /* -------------------------------------------------------------- */ + /* Internal — layout */ + /* -------------------------------------------------------------- */ + + private buildLayout(parsed: ParsedMessage, config: ChatterSlot, font: string): Layout { + const padding = config.text.padding; + const boxWidth = config.bubble.width - padding.left - padding.right; + const fontSize = this.parseFontSize(font); + const lineHeightMultiplier = config.text.lineHeight ?? 1.2; + const lineHeight = fontSize * lineHeightMultiplier; + const wrap = config.text.wrap ?? true; + const wrapLongWords = config.text.wrapLongWords ?? false; + + const items: LayoutItem[] = []; + const lineWidths: number[] = [0]; + let lineIndex = 0; + let cursorX = 0; + let visibleIndex = 0; + + const newLine = (): void => { + lineIndex++; + lineWidths[lineIndex] = 0; + cursorX = 0; + }; + + for (const token of parsed.tokens) { + if (token.kind === "char" || token.kind === "icon") { + let width: number; + let height: number; + let yOffset: number; + + if (token.kind === "char") { + width = this.measure(token.ch, font); + height = lineHeight; + yOffset = 0; + } else { + const icon = this.icons.get(token.name); + const iconSize = this.resolveIconSize(token, fontSize, icon, lineHeight); + width = iconSize.width; + height = iconSize.height; + yOffset = this.iconVerticalOffset(token.align, height, lineHeight); + } + + // Wrap logic + if (wrap && cursorX + width > boxWidth && cursorX > 0) { + if (token.kind === "char" && token.ch === " ") { + // Trailing space doesn't force a wrap + // Just skip it (drops the space at wrap point) + visibleIndex++; + continue; + } + if (!wrapLongWords || width <= boxWidth) { + newLine(); + } + } + + // Emit item + if (token.kind === "char") { + items.push({ + kind: "text", + text: token.ch, + x: cursorX, + y: lineIndex * lineHeight, + width, + height, + lineIndex, + visibleIndex, + style: token.style, + }); + } else { + items.push({ + kind: "icon", + name: token.name, + image: this.icons.get(token.name) ?? null, + x: cursorX, + y: lineIndex * lineHeight + yOffset, + width, + height, + lineIndex, + visibleIndex, + align: token.align, + style: token.style, + }); + } + + cursorX += width; + lineWidths[lineIndex] = Math.max(lineWidths[lineIndex] ?? 0, cursorX); + visibleIndex++; + } + } + + // Compute per-line alignment offsets + const align = config.text.align ?? "center"; + const lineOffsets = lineWidths.map(w => { + if (align === "left") return 0; + if (align === "right") return boxWidth - w; + return (boxWidth - w) / 2; + }); + + const totalHeight = (lineIndex + 1) * lineHeight; + const actualBoxWidth = boxWidth; + + return { items, lineHeight, totalHeight, boxWidth: actualBoxWidth, lineOffsets }; + } + + private resolveIconSize( + token: { size: "line" | "native" | number; multiplier?: number }, + fontSize: number, + icon: CanvasImageSource | undefined, + lineHeight: number, + ): { width: number; height: number } { + let baseWidth: number; + let baseHeight: number; + + if (token.size === "native") { + const size = icon ? this.iconNativeSize(icon) : { width: lineHeight, height: lineHeight }; + baseWidth = size.width; + baseHeight = size.height; + } else if (token.size === "line") { + baseWidth = lineHeight; + baseHeight = lineHeight; + } else { + baseWidth = token.size; + baseHeight = token.size; + } + + const mult = token.multiplier ?? 1; + const result = { width: baseWidth * mult, height: baseHeight * mult }; + return result; + } + + private iconNativeSize(icon: CanvasImageSource): { width: number; height: number } { + const any = icon as unknown as Record; + const nw = any.naturalWidth; + const nh = any.naturalHeight; + if (typeof nw === "number" && typeof nh === "number") { + return { width: nw, height: nh }; + } + const w = any.width; + const h = any.height; + if (typeof w === "number" && typeof h === "number") { + return { width: w, height: h }; + } + return { width: 0, height: 0 }; + } + + private iconVerticalOffset( + align: "baseline" | "middle" | "top" | "text-top", + iconHeight: number, + lineHeight: number, + ): number { + if (align === "top" || align === "text-top") return 0; + if (align === "middle") return (lineHeight - iconHeight) / 2; + // baseline: bottom of icon at text baseline (roughly 80% of line height) + const baselineY = lineHeight * 0.8; + return baselineY - iconHeight; + } + + /* -------------------------------------------------------------- */ + /* Internal — measurement */ + /* -------------------------------------------------------------- */ + + private measureWithCanvas(text: string, font: string): number { + if (!this.ctx) { + const canvas = document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + this.ctx = canvas.getContext("2d"); + } + if (!this.ctx) return text.length * 8; + this.ctx.font = font; + return this.ctx.measureText(text).width; + } + + private parseFontSize(font: string): number { + const match = /(\d+(?:\.\d+)?)px/.exec(font); + return match ? parseFloat(match[1]!) : 11; + } +} diff --git a/packages/shimejic/src/core/chatter-parser.ts b/packages/shimejic/src/core/chatter-parser.ts new file mode 100644 index 0000000..1765a66 --- /dev/null +++ b/packages/shimejic/src/core/chatter-parser.ts @@ -0,0 +1,475 @@ +/** + * chatter-parser.ts — converts raw message text into a token stream. + * + * Handles: + * - Escape sequences: {tag}, {tag value}, {/tag}, {{ literal + * - Vowel escape: {vowel X} or {vowel X ms} + * - Punctuation timing: . (6x), .. (9x), ... (12x), .... (15x) via 6+3(N-1) + * - Comma, semicolon, colon (3x); space, apostrophe, quotes, etc. (1x) + * - Sentence detection: . ? ! and 3+ dot runs (ellipsis) + * - Vowel detection: + * a, e, i, o, u → standard vowels + * oo (two adjacent o) → /u/ as in "boot" + * word-final y → /i/ as in "happy" + * - Uppercase (shout) + * - Style state tracking + * - Speed overrides + */ + +import { + DEFAULT_STYLE, + VOWEL_FORMANTS, + type CharToken, + type IconAlign, + type IconSize, + type IconToken, + type ParseOptions, + type ParsedMessage, + type PauseToken, + type SentenceInfo, + type SentenceType, + type TextStyle, + type Token, + type VoiceMood, + type VoiceToken, + type Vowel, + type VowelToken, +} from "./chatter-types.ts"; + +const VOWELS = new Set(["a", "e", "i", "o", "u"]); +const MOODS: ReadonlySet = new Set(["angry", "sleepy", "happy", "sad", "whisper"]); + +/** Multiplier for standard punctuation (relative to a normal character). */ +const PUNCT_MULTIPLIER: Record = { + ",": 3, + ";": 3, + ":": 3, + "?": 6, + "!": 6, +}; + +type VowelClassification = { isVowel: false } | { isVowel: true; vowel: Vowel }; + +function isVowelName(s: string): s is Vowel { + return s in VOWEL_FORMANTS; +} + +/** + * Classify the character at `index` as vowel or consonant in context. + * + * Standard vowels: a, e, i, o, u + * 'oo' — two adjacent o chars merge into /u/ + * Word-final y after a consonant → /i/ (happy, my, fly) + * Other y → consonant (yes, day, yellow, beyond) + */ +function classifyVowelAt(text: string, index: number): VowelClassification { + const ch = text[index]; + if (ch === undefined) return { isVowel: false }; + const lower = ch.toLowerCase(); + + // 'oo' detection: if either neighbor is 'o', this char is 'oo' + if (lower === "o") { + const prev = text[index - 1]?.toLowerCase(); + const next = text[index + 1]?.toLowerCase(); + if (prev === "o" || next === "o") { + return { isVowel: true, vowel: "oo" }; + } + } + + if (lower === "a" || lower === "e" || lower === "i" || lower === "o" || lower === "u") { + return { isVowel: true, vowel: lower as Vowel }; + } + + if (lower === "y") { + const next = text[index + 1]; + const nextIsLetter = next !== undefined && /[a-zA-Z]/.test(next); + if (nextIsLetter) return { isVowel: false }; + + const prev = text[index - 1]; + if (prev === undefined) return { isVowel: false }; + const prevLower = prev.toLowerCase(); + if (/[aeiou]/.test(prevLower) || prevLower === "y") return { isVowel: false }; + + return { isVowel: true, vowel: "i" }; + } + + return { isVowel: false }; +} + +export function parseMessage(text: string, opts: ParseOptions): ParsedMessage { + const tokens: Token[] = []; + const sentences: SentenceInfo[] = []; + + const initialCps = Math.max(0.01, opts.speed); + let currentCps = initialCps; + const baseStyle: TextStyle = { + ...DEFAULT_STYLE, + color: opts.color ?? DEFAULT_STYLE.color, + }; + let style: TextStyle = { ...baseStyle }; + + let i = 0; + let sentenceStart = 0; + let totalDuration = 0; + let totalVisible = 0; + let inDotRun = false; + + const pushToken = (token: Token): void => { + tokens.push(token); + totalDuration += token.duration; + if (token.kind === "char" || token.kind === "icon") { + totalVisible++; + } + }; + + while (i < text.length) { + const ch = text[i]!; + + /* ---------- literal escapes ---------- */ + if (ch === "{" && text[i + 1] === "{") { + pushToken(makeChar("{", currentCps, style)); + i += 2; + inDotRun = false; + continue; + } + + /* ---------- escape sequences ---------- */ + if (ch === "{") { + const close = text.indexOf("}", i + 1); + if (close === -1) { + pushToken(makeChar("{", currentCps, style)); + i += 1; + inDotRun = false; + continue; + } + const body = text.slice(i + 1, close); + i = close + 1; + inDotRun = false; + + const handled = handleEscape(body, { + tokens: pushToken, + styleRef: () => style, + setStyle: s => (style = s), + setSpeed: cps => (currentCps = cps), + getSpeed: () => currentCps, + initialCps, + baseStyle, + }); + if (handled) continue; + + // Unknown escape — render body as literal text + pushToken(makeChar("{", currentCps, style)); + for (const c of body) pushToken(makeChar(c, currentCps, style)); + pushToken(makeChar("}", currentCps, style)); + continue; + } + + /* ---------- punctuation with multipliers ---------- */ + if (ch === ".") { + let runLength = 1; + while (i + runLength < text.length && text[i + runLength] === ".") { + runLength++; + } + for (let d = 0; d < runLength; d++) { + const multiplier = d === 0 && !inDotRun ? 6 : 3; + pushToken(makeChar(".", currentCps, style, multiplier)); + } + if (runLength >= 3) { + endSentence(tokens.length - 1, "ellipsis"); + } else { + endSentence(tokens.length - 1, "statement"); + } + i += runLength; + inDotRun = false; + continue; + } + + if (ch === "?" || ch === "!" || ch === "," || ch === ";" || ch === ":") { + const multiplier = PUNCT_MULTIPLIER[ch] ?? 1; + pushToken(makeChar(ch, currentCps, style, multiplier)); + if (ch === "?" || ch === "!") { + endSentence(tokens.length - 1, ch === "?" ? "question" : "exclamation"); + } + i += 1; + inDotRun = false; + continue; + } + + /* ---------- regular character ---------- */ + const classification = classifyVowelAt(text, i); + pushToken(makeChar(ch, currentCps, style, 1, classification)); + i += 1; + inDotRun = ch === "."; + } + + if (sentenceStart < tokens.length) { + sentences.push({ + startToken: sentenceStart, + endToken: tokens.length - 1, + type: "fragment", + }); + } + + return { tokens, sentences, totalDuration, totalVisible }; + + function endSentence(endToken: number, type: SentenceType): void { + sentences.push({ startToken: sentenceStart, endToken, type }); + sentenceStart = endToken + 1; + } +} + +function makeChar( + ch: string, + cps: number, + style: TextStyle, + multiplier = 1, + classification?: VowelClassification, +): CharToken { + const lower = ch.toLowerCase(); + const cls: VowelClassification = + classification ?? (VOWELS.has(lower) ? { isVowel: true, vowel: lower as Vowel } : { isVowel: false }); + const shout = ch !== lower && ch.toUpperCase() === ch && ch !== ch.toLowerCase(); + const token: CharToken = { + kind: "char", + ch, + isVowel: cls.isVowel, + shout, + duration: multiplier / cps, + style: { ...style }, + }; + if (cls.isVowel) token.vowel = cls.vowel; + return token; +} + +interface EscapeContext { + tokens: (token: Token) => void; + styleRef: () => TextStyle; + setStyle: (s: TextStyle) => void; + setSpeed: (cps: number) => void; + getSpeed: () => number; + initialCps: number; + baseStyle: TextStyle; +} + +function handleEscape(body: string, ctx: EscapeContext): boolean { + const trimmed = body.trim(); + if (trimmed.length === 0) return false; + + // {/name} + if (trimmed.startsWith("/")) { + const name = trimmed.slice(1).trim(); + const current = ctx.styleRef(); + const restored: TextStyle = { ...current }; + if (name === "color") restored.color = ctx.baseStyle.color; + else if (name === "bold") restored.bold = false; + else if (name === "underline") restored.underline = false; + else if (name === "shake") restored.shake = false; + else if (name === "wobble") restored.wobble = false; + else if (name === "wave") restored.wave = false; + else return false; + ctx.setStyle(restored); + ctx.tokens({ kind: "style-close", name, duration: 0 }); + return true; + } + + // {pause N} + if (trimmed.startsWith("pause")) { + const match = /^pause\s+(\d+)/i.exec(trimmed); + if (!match) return false; + const ms = parseInt(match[1]!, 10); + const token: PauseToken = { kind: "pause", ms, duration: ms / 1000 }; + ctx.tokens(token); + return true; + } + + // {speed N} or {speed reset} + if (trimmed.startsWith("speed")) { + const rest = trimmed.slice(5).trim(); + if (rest === "reset") { + ctx.setSpeed(ctx.initialCps); + ctx.tokens({ kind: "speed", cps: ctx.initialCps, reset: true, duration: 0 }); + return true; + } + const num = parseFloat(rest); + if (!isNaN(num) && num > 0) { + ctx.setSpeed(num); + ctx.tokens({ kind: "speed", cps: num, reset: false, duration: 0 }); + return true; + } + return false; + } + + // {voice mood}, {voice pitch:N}, {voice volume:N} + if (trimmed.startsWith("voice")) { + const rest = trimmed.slice(5).trim(); + const voiceToken: VoiceToken = { kind: "voice", duration: 0 }; + let hasAny = false; + const parts = rest.split(/\s+/).filter(Boolean); + for (const tok of parts) { + if (MOODS.has(tok as VoiceMood)) { + voiceToken.mood = tok as VoiceMood; + hasAny = true; + continue; + } + const propMatch = /^(\w+):(\d+(?:\.\d+)?)$/.exec(tok); + if (propMatch) { + const key = propMatch[1]!; + const val = parseFloat(propMatch[2]!); + if (key === "pitch") { + voiceToken.pitch = val; + hasAny = true; + } else if (key === "volume") { + voiceToken.volume = val; + hasAny = true; + } + } + } + if (hasAny) { + ctx.tokens(voiceToken); + return true; + } + return false; + } + + // {vowel X} or {vowel X N} + if (trimmed.startsWith("vowel")) { + const rest = trimmed.slice(5).trim(); + const parts = rest.split(/\s+/).filter(Boolean); + if (parts.length === 0) return false; + const raw = parts[0]!; + const lower = raw.toLowerCase(); + if (!isVowelName(lower)) return false; + + const shout = raw === raw.toUpperCase() && raw !== lower; + let duration = 1 / ctx.getSpeed(); + if (parts[1] !== undefined) { + const ms = parseInt(parts[1]!, 10); + if (!isNaN(ms) && ms > 0) duration = ms / 1000; + } + + const token: VowelToken = { kind: "vowel", vowel: lower, shout, duration }; + ctx.tokens(token); + return true; + } + + // {icon ...} + if (trimmed.startsWith("icon")) { + const rest = trimmed.slice(4).trim(); + const parsed = parseIconSpec(rest); + if (!parsed) return false; + const current = ctx.styleRef(); + const token: IconToken = { + kind: "icon", + name: parsed.name, + size: parsed.size, + align: parsed.align, + duration: 1 / ctx.getSpeed(), + style: { ...current }, + }; + if (parsed.multiplier !== undefined) token.multiplier = parsed.multiplier; + ctx.tokens(token); + return true; + } + + // {color value} + if (trimmed.startsWith("color")) { + const value = trimmed.slice(5).trim(); + if (value.length === 0) return false; + const current = ctx.styleRef(); + ctx.setStyle({ ...current, color: value }); + ctx.tokens({ kind: "style-open", name: "color", value, duration: 0 }); + return true; + } + + // {bold}, {underline}, {shake}, {wobble}, {wave} + for (const tag of ["bold", "underline", "shake", "wobble", "wave"] as const) { + if (trimmed === tag) { + const current = ctx.styleRef(); + ctx.setStyle({ ...current, [tag]: true }); + ctx.tokens({ kind: "style-open", name: tag, duration: 0 }); + return true; + } + } + + return false; +} + +interface IconSpec { + name: string; + size: IconSize; + multiplier?: number; + align: IconAlign; +} + +/** + * Parses the body of an icon escape. + * + * Grammar: + * + * * + * @line | @native | @ + * @native* + * ^ (align modifier comes first) + */ +function parseIconSpec(spec: string): IconSpec | null { + let working = spec; + let align: IconAlign = "middle"; + + if (working.startsWith("^")) { + const spaceIdx = working.indexOf(" "); + if (spaceIdx === -1) return null; + const alignStr = working.slice(1, spaceIdx).toLowerCase(); + if (!isIconAlign(alignStr)) return null; + align = alignStr; + working = working.slice(spaceIdx + 1).trim(); + } + if (working.length === 0) return null; + + const sizeIdx = working.indexOf("@"); + const multIdx = working.indexOf("*"); + + let nameEnd = working.length; + if (sizeIdx >= 0) nameEnd = Math.min(nameEnd, sizeIdx); + if (multIdx >= 0) nameEnd = Math.min(nameEnd, multIdx); + + const name = working.slice(0, nameEnd).trim(); + if (name.length === 0) return null; + + let size: IconSize = "line"; + let multiplier: number | undefined; + + let rest = working.slice(nameEnd); + + if (rest.startsWith("@")) { + const afterAt = rest.slice(1); + const starInAfterAt = afterAt.indexOf("*"); + const sizeStr = starInAfterAt >= 0 ? afterAt.slice(0, starInAfterAt) : afterAt; + rest = starInAfterAt >= 0 ? afterAt.slice(starInAfterAt) : ""; + + const trimmedSize = sizeStr.trim().toLowerCase(); + if (trimmedSize === "line") size = "line"; + else if (trimmedSize === "native") size = "native"; + else { + const num = parseFloat(trimmedSize); + if (isNaN(num) || num <= 0) return null; + size = num; + } + } + + if (rest.startsWith("*")) { + const multStr = rest.slice(1).trim(); + const num = parseFloat(multStr); + if (isNaN(num) || num <= 0) return null; + multiplier = num; + } else if (rest.length > 0) { + return null; + } + + const result: IconSpec = { name, size, align }; + if (multiplier !== undefined) result.multiplier = multiplier; + return result; +} + +function isIconAlign(s: string): s is IconAlign { + return s === "baseline" || s === "middle" || s === "top" || s === "text-top"; +} diff --git a/packages/shimejic/src/core/chatter-types.ts b/packages/shimejic/src/core/chatter-types.ts new file mode 100644 index 0000000..8da7837 --- /dev/null +++ b/packages/shimejic/src/core/chatter-types.ts @@ -0,0 +1,340 @@ +/** + * chatter-types.ts — types for the chatter overlay system. + * + * A message is parsed into a token stream (parser) and then laid out + * into positioned items (overlay). The token stream is the shared + * representation: the overlay renders from it, and the mumble module + * (future) will consume it for vowel bursts and pitch contours. + */ + +/* ------------------------------------------------------------------ */ +/* Enumerations */ +/* ------------------------------------------------------------------ */ + +export type Vowel = "a" | "e" | "i" | "o" | "u" | "oo"; + +export interface VowelToken { + kind: "vowel"; + vowel: Vowel; + shout: boolean; + duration: number; +} + +export type SentenceType = "statement" | "question" | "exclamation" | "ellipsis" | "fragment"; + +export type VoiceMood = "angry" | "sleepy" | "happy" | "sad" | "whisper"; + +export type TailPosition = "left" | "bottom-left" | "bottom" | "bottom-right" | "right" | "top-right"; + +export type IconSize = "line" | "native" | number; + +export type IconAlign = "baseline" | "middle" | "top" | "text-top"; + +export type TextAlign = "left" | "center" | "right"; + +export type TextBaseline = "top" | "middle" | "bottom"; + +/* ------------------------------------------------------------------ */ +/* Style state */ +/* ------------------------------------------------------------------ */ + +export interface TextStyle { + color: string; + bold: boolean; + underline: boolean; + shake: boolean; + wobble: boolean; + wave: boolean; +} + +export const DEFAULT_STYLE: Readonly = { + color: "#000", + bold: false, + underline: false, + shake: false, + wobble: false, + wave: false, +}; + +/* ------------------------------------------------------------------ */ +/* Tokens */ +/* ------------------------------------------------------------------ */ + +export interface CharToken { + kind: "char"; + ch: string; + isVowel: boolean; + vowel?: Vowel; + shout: boolean; + /** Duration in seconds, including punctuation multiplier. */ + duration: number; + style: TextStyle; +} + +export interface PauseToken { + kind: "pause"; + ms: number; + /** Same as ms / 1000. Cached to avoid division per-frame. */ + duration: number; +} + +export interface SpeedToken { + kind: "speed"; + cps: number; + reset: boolean; + duration: 0; +} + +export interface VoiceToken { + kind: "voice"; + mood?: VoiceMood; + pitch?: number; + volume?: number; + duration: 0; +} + +export interface IconToken { + kind: "icon"; + name: string; + size: IconSize; + multiplier?: number; + align: IconAlign; + duration: number; + style: TextStyle; +} + +export interface StyleOpenToken { + kind: "style-open"; + name: string; + value?: string; + duration: 0; +} + +export interface StyleCloseToken { + kind: "style-close"; + name: string; + duration: 0; +} + +export type Token = + | VowelToken + | CharToken + | PauseToken + | SpeedToken + | VoiceToken + | IconToken + | StyleOpenToken + | StyleCloseToken; + +/* ------------------------------------------------------------------ */ +/* Parsed message */ +/* ------------------------------------------------------------------ */ + +export interface SentenceInfo { + /** Index into `tokens` where this sentence begins. */ + startToken: number; + /** Index of the terminal token (or last token if fragment). */ + endToken: number; + type: SentenceType; +} + +export interface ParsedMessage { + tokens: Token[]; + sentences: SentenceInfo[]; + /** Sum of all token durations, in seconds. */ + totalDuration: number; + /** Number of visible items (chars + icons). */ + totalVisible: number; +} + +/* ------------------------------------------------------------------ */ +/* Layout */ +/* ------------------------------------------------------------------ */ + +export interface LayoutTextItem { + kind: "text"; + text: string; + /** Position within the text box, before line-alignment offset. */ + x: number; + y: number; + width: number; + height: number; + lineIndex: number; + /** Position in the visible-item stream (0-based). */ + visibleIndex: number; + style: TextStyle; +} + +export interface LayoutIconItem { + kind: "icon"; + name: string; + image: CanvasImageSource | null; + x: number; + y: number; + width: number; + height: number; + lineIndex: number; + visibleIndex: number; + align: IconAlign; + style: TextStyle; +} + +export type LayoutItem = LayoutTextItem | LayoutIconItem; + +export interface Layout { + items: LayoutItem[]; + lineHeight: number; + totalHeight: number; + boxWidth: number; + /** X offset to apply per line for alignment. */ + lineOffsets: number[]; +} + +/* ------------------------------------------------------------------ */ +/* Config */ +/* ------------------------------------------------------------------ */ + +export interface BubbleConfig { + image: CanvasImageSource | CanvasImageSource[]; + fps?: number; + width: number; + height: number; + anchorX?: number; + anchorY?: number; + tail?: TailPosition; + scale?: number; + opacity?: number; + /** Frame behavior after typing completes. Default 'hold'. */ + frameMode?: "loop" | "hold" | "reverse-on-dismiss"; +} + +export interface TextConfig { + font?: string; + color?: string; + align?: TextAlign; + baseline?: TextBaseline; + padding: { top: number; right: number; bottom: number; left: number }; + lineHeight?: number; + wrap?: boolean; + wrapLongWords?: boolean; + /** Distance from text-box top to first line, in CSS px. */ + textTop?: number; + /** Bubble frame index at which typing begins. Default 0. */ + startFrame?: number; + /** Characters per second. Default 20. */ + speed?: number; +} + +export interface TimingConfig { + /** Explicit duration in seconds, or 'auto' to compute from typing + hold. */ + duration?: number | "auto"; + /** Seconds to hold after typing completes. Default 1.5. */ + holdLast?: number; +} + +/* ------------------------------------------------------------------ */ +/* Voice */ +/* ------------------------------------------------------------------ */ + +export interface EmotionConfig { + /** Pitch multiplier on top of base pitch. */ + pitch: number; + /** Additional noise mix added to base. E.g. whisper = 0.35. */ + noiseBonus?: number; +} + +export interface ContourConfig { + /** Pitch multiplier at the start of the sentence. */ + from: number; + /** Pitch multiplier at the end of the sentence. */ + to: number; + /** Easing shape. Default 'linear'. */ + ease?: "linear" | "ease-in" | "ease-out" | "ease-in-out"; +} + +export interface VoiceConfig { + /** Multiplier over 200 Hz reference. Default 1.0. */ + basePitch?: number; + /** Multiplier on formant frequencies. Default 1.0. */ + formantScale?: number; + /** Baseline breathiness, 0–1. Default 0.05. */ + noiseMix?: number; + /** Per-burst volume, 0–1. Default 0.5. */ + volume?: number; + /** Per-emotion overrides. Merged with defaults. */ + emotions?: Partial>; + /** Per-sentence-type contour overrides. Merged with defaults. */ + contours?: Partial>; +} + +export interface ChatterSlot { + bubble: BubbleConfig; + text: TextConfig; + timing?: TimingConfig; + voice?: VoiceConfig; + /** What to do when a new message arrives while one is active. Default 'queue'. */ + interrupt?: "queue" | "replace" | "reject"; + /** Priority for the queue. Higher = earlier. Default 0. */ + priority?: number; + /** Called when the bubble fully dismisses. */ + onComplete?: (entityId: string, text: string) => void; +} + +/* ------------------------------------------------------------------ */ +/* Runtime and render data */ +/* ------------------------------------------------------------------ */ + +export interface BubbleRenderData { + image: CanvasImageSource; + width: number; + height: number; + alpha: number; + mirrored: boolean; + anchorX: number; + anchorY: number; + layout: Layout; + charsShown: number; + padding: { top: number; right: number; bottom: number; left: number }; + font: string; + color: string; + align: TextAlign; + wrapLongWords: boolean; + elapsed: number; +} + +export interface ParseOptions { + /** Initial chars-per-second. `{speed N}` overrides per message. */ + speed: number; + /** Default text color. Default '#000'. */ + color?: string; +} + +export const DEFAULT_VOICE = { + basePitch: 1.0, + formantScale: 1.0, + noiseMix: 0.05, + volume: 0.5, + emotions: { + angry: { pitch: 1.15 }, + sleepy: { pitch: 0.85 }, + happy: { pitch: 1.1 }, + sad: { pitch: 0.9 }, + whisper: { pitch: 0.95, noiseBonus: 0.35 }, + } as Record, + contours: { + statement: { from: 1.05, to: 0.95, ease: "linear" }, + question: { from: 1.0, to: 1.2, ease: "ease-in" }, + exclamation: { from: 1.25, to: 1.05, ease: "linear" }, + ellipsis: { from: 1.3, to: 0.7, ease: "ease-out" }, + fragment: { from: 1.0, to: 1.0, ease: "linear" }, + } as Record, +}; + +export const VOWEL_FORMANTS: Record = { + a: { f1: 730, f2: 1090, f3: 2440 }, // 'ah' — father + e: { f1: 530, f2: 1840, f3: 2480 }, // 'eh' — bet + i: { f1: 270, f2: 2290, f3: 3010 }, // 'ee' — beet + o: { f1: 570, f2: 840, f3: 2410 }, // 'oh' — go + u: { f1: 640, f2: 1190, f3: 2390 }, // 'uh' — but + oo: { f1: 300, f2: 870, f3: 2240 }, // 'oo' — boot +}; diff --git a/packages/shimejic/src/core/cursor.ts b/packages/shimejic/src/core/cursor.ts new file mode 100644 index 0000000..1c82222 --- /dev/null +++ b/packages/shimejic/src/core/cursor.ts @@ -0,0 +1,188 @@ +/** + * cursor.ts — cursor angle, distance, and sector matching. + * + * Angle convention: 0° = up, 90° = right, 180° = down, 270° = left. + * All angles are normalized to [0, 360). + * + * Sectors are angular ranges that may wrap (minAngle > maxAngle). + * + * Hysteresis extends each sector by `hysteresis` degrees on each side. + * When the cursor falls in the overlap zone of two sectors, the sector + * you were already in wins. This prevents flicker from jitter at + * boundaries. Example: [0, 25] with hysteresis=1 becomes [359, 26] + * effective range. + * + * Distance is checked inclusively: [min, max]. Cursor must be inside + * the range for any sector to match. + */ + +export interface Vec2 { + x: number; + y: number; +} + +export interface CursorSector { + minAngle: number; + maxAngle: number; + folder: string; +} + +export interface CursorLookConfig extends SectorQuery { + /** + * Pivot point as a fraction of sprite dimensions. + * { x: 0.5, y: 0.2 } = 50% from left, 20% from top. + * The caller resolves this to world coordinates before querying. + */ + pivot: { x: number; y: number }; + /** Inclusive distance range. Cursor must be in [min, max]. */ + distance: { min: number; max: number }; + /** Degrees of extension on each side of each sector. Default 1. */ + hysteresis: number; + sectors: CursorSector[]; +} + +export interface CursorInfo { + angle: number; + distance: number; +} + +export interface SectorMatch { + sector: T; + angle: number; + distance: number; +} + +export interface SectorQuery { + distance: { min: number; max: number }; + hysteresis: number; + sectors: T[]; +} + +/* ------------------------------------------------------------------ */ +/* Pure math */ +/* ------------------------------------------------------------------ */ + +/** Angle from pivot to point. 0° = up, 90° = right, 180° = down, 270° = left. */ +export function angleFromPoint(pivot: Vec2, point: Vec2): number { + const dx = point.x - pivot.x; + const dy = point.y - pivot.y; + const rad = Math.atan2(dx, -dy); + const deg = (rad * 180) / Math.PI; + return ((deg % 360) + 360) % 360; +} + +/** Euclidean distance between two points. */ +export function distanceBetween(a: Vec2, b: Vec2): number { + const dx = a.x - b.x; + const dy = a.y - b.y; + return Math.sqrt(dx * dx + dy * dy); +} + +function normalize(deg: number): number { + return ((deg % 360) + 360) % 360; +} + +interface Arc { + start: number; + length: number; +} + +function sectorToArc(sector: CursorSector): Arc { + const start = normalize(sector.minAngle); + let length = sector.maxAngle - sector.minAngle; + if (length < 0) length += 360; + return { start, length }; +} + +function extendArc(arc: Arc, hysteresis: number): Arc { + const h = Math.max(0, hysteresis); + return { + start: normalize(arc.start - h), + length: Math.min(arc.length + 2 * h, 360), + }; +} + +function arcContains(arc: Arc, angle: number): boolean { + const a = normalize(angle); + const delta = normalize(a - arc.start); + return delta <= arc.length; +} + +function sectorContainsExtended(sector: CursorSector, angle: number, hysteresis: number): boolean { + return arcContains(extendArc(sectorToArc(sector), hysteresis), angle); +} + +/** + * Find the sector that matches the cursor. + * + * If `currentFolder` is provided and its extended range still contains the + * angle, that sector wins (hysteresis). Otherwise the first matching sector + * in array order is returned. + * + * Distance is checked first: outside [min, max], no sector matches. + */ +export function matchSector( + info: CursorInfo, + config: SectorQuery, + currentFolder: string | null, +): SectorMatch | null { + if (info.distance < config.distance.min || info.distance > config.distance.max) { + return null; + } + + if (currentFolder !== null) { + for (const sector of config.sectors) { + if (sector.folder !== currentFolder) continue; + if (sectorContainsExtended(sector, info.angle, config.hysteresis)) { + return { sector, angle: info.angle, distance: info.distance }; + } + break; + } + } + + for (const sector of config.sectors) { + if (sectorContainsExtended(sector, info.angle, config.hysteresis)) { + return { sector, angle: info.angle, distance: info.distance }; + } + } + + return null; +} + +/* ------------------------------------------------------------------ */ +/* Stateful service */ +/* ------------------------------------------------------------------ */ + +export class CursorService { + private _position: Vec2 | null = null; + + setCursor(x: number, y: number): void { + if (this._position === null) { + this._position = { x, y }; + } else { + this._position.x = x; + this._position.y = y; + } + } + + clearCursor(): void { + this._position = null; + } + + get position(): Readonly | null { + return this._position; + } + + get hasCursor(): boolean { + return this._position !== null; + } + + /** Angle and distance from a pivot. Returns null if no cursor is set. */ + query(pivot: Vec2): CursorInfo | null { + if (this._position === null) return null; + return { + angle: angleFromPoint(pivot, this._position), + distance: distanceBetween(pivot, this._position), + }; + } +} diff --git a/packages/shimejic/src/core/entity.ts b/packages/shimejic/src/core/entity.ts new file mode 100644 index 0000000..7d0f0c7 --- /dev/null +++ b/packages/shimejic/src/core/entity.ts @@ -0,0 +1,228 @@ +/** + * entity.ts — the entity model. + * + * An entity is a plain object with a transform and optional slots. Slots are + * self-contained interfaces — presence of a slot means the entity participates + * in that subsystem. There is no inheritance and no subclassing; composition + * happens by populating slots. + * + * Hierarchy is one-level in practice: a parent moves its children, children + * never move their parent. No deep trees. + */ + +import type { RigidBody, Vec2 } from "./physics.ts"; +import type { Anchor } from "./renderer.ts"; + +/* ------------------------------------------------------------------ */ +/* Transform */ +/* ------------------------------------------------------------------ */ + +export interface Transform { + /** Position relative to the parent (or world if no parent). */ + position: Vec2; + /** Anchor for the sprite, and rotation/scale pivot. */ + anchor: Anchor; + scaleX: number; + scaleY: number; + opacity: number; + /** Radians. Currently unused by the renderer; reserved. */ + rotation: number; +} + +export const DEFAULT_TRANSFORM: Readonly = { + position: { x: 0, y: 0 }, + anchor: "top-left", + scaleX: 1, + scaleY: 1, + opacity: 1, + rotation: 0, +}; + +/* ------------------------------------------------------------------ */ +/* Slots */ +/* ------------------------------------------------------------------ */ + +export interface SpriteFrame { + image: CanvasImageSource; + width: number; + height: number; + sx: number; + sy: number; + sw: number; + sh: number; +} + +export interface SpriteSlot { + /** Current frame, or null if nothing should be drawn. */ + frame(): SpriteFrame | null; + /** Optional per-frame update for animated sprites. */ + update?(dt: number): void; +} + +export interface BodySlot { + body: RigidBody; + /** + * If true (default), the body's position is copied into the entity's + * transform every frame by the physics system. + */ + syncTransform?: boolean; +} + +export interface ShadowSlot { + /** Horizontal radius as a fraction of sprite width. Default 0.4. */ + rx?: number; + /** Vertical radius as a fraction of sprite height. Default 0.08. */ + ry?: number; + color?: string; + alpha?: number; + /** Vertical squash per 100px of height. Default 0.5. */ + shrinkByHeight?: number; + /** Fade per 100px of height. Default 0.85. */ + fadeByHeight?: number; + /** Height at which the shadow disappears entirely. Default 200. */ + maxHeight?: number; +} + +export interface ReflectionSlot { + opacity?: number; + fade?: number; + /** Fade per 100px of height. */ + fadeByHeight?: number; + tint?: string; +} + +export interface BubbleTextConfig { + content: string; + font?: string; + color?: string; + align?: "left" | "center" | "right"; + padding?: { top: number; right: number; bottom: number; left: number }; + lineHeight?: number; + wrap?: boolean; + /** Typewriter reveal, 0..content.length. Omit for full text. */ + charsShown?: number; +} + +export interface BubbleSlot { + image: CanvasImageSource; + width: number; + height: number; + /** Offset from sprite top-center, in px. Default 0. */ + anchorX?: number; + /** Positive = above the head. Default 4. */ + anchorY?: number; + text?: BubbleTextConfig; +} + +export interface CustomSlot { + draw?: (ctx: CanvasRenderingContext2D, entity: Entity) => void; + update?: (entity: Entity, dt: number) => void; +} + +/* ------------------------------------------------------------------ */ +/* Entity */ +/* ------------------------------------------------------------------ */ + +export type SlotKey = "sprite" | "body" | "shadow" | "reflection" | "bubble" | "custom"; + +export interface Entity { + readonly id: string; + parent: Entity | null; + readonly children: Entity[]; + + visible: boolean; + destroyed: boolean; + + readonly transform: Transform; + + sprite?: SpriteSlot; + body?: BodySlot; + shadow?: ShadowSlot; + reflection?: ReflectionSlot; + bubble?: BubbleSlot; + custom?: CustomSlot; + + /** Arbitrary tags for filtering: `world.entitiesWith(...)` doesn't cover this. */ + readonly tags: Set; + /** Arbitrary user data. Feature systems (needs, chatter) store state here. */ + readonly data: Record; +} + +/* ------------------------------------------------------------------ */ +/* Factory */ +/* ------------------------------------------------------------------ */ + +export interface EntityOptions { + id?: string; + parent?: Entity; + visible?: boolean; + transform?: Partial; + sprite?: SpriteSlot; + body?: BodySlot; + shadow?: ShadowSlot; + reflection?: ReflectionSlot; + bubble?: BubbleSlot; + custom?: CustomSlot; + tags?: string[]; + data?: Record; +} + +let nextEntityId = 0; + +export function createEntity(opts: EntityOptions = {}): Entity { + const entity: Entity = { + id: opts.id ?? `entity-${nextEntityId++}`, + parent: opts.parent ?? null, + children: [], + visible: opts.visible ?? true, + destroyed: false, + transform: { + position: opts.transform?.position ?? { x: 0, y: 0 }, + anchor: opts.transform?.anchor ?? DEFAULT_TRANSFORM.anchor, + scaleX: opts.transform?.scaleX ?? DEFAULT_TRANSFORM.scaleX, + scaleY: opts.transform?.scaleY ?? DEFAULT_TRANSFORM.scaleY, + opacity: opts.transform?.opacity ?? DEFAULT_TRANSFORM.opacity, + rotation: opts.transform?.rotation ?? DEFAULT_TRANSFORM.rotation, + }, + tags: new Set(opts.tags ?? []), + data: opts.data ?? {}, + }; + + if (opts.sprite !== undefined) entity.sprite = opts.sprite; + if (opts.body !== undefined) entity.body = opts.body; + if (opts.shadow !== undefined) entity.shadow = opts.shadow; + if (opts.reflection !== undefined) entity.reflection = opts.reflection; + if (opts.bubble !== undefined) entity.bubble = opts.bubble; + if (opts.custom !== undefined) entity.custom = opts.custom; + + if (opts.parent !== undefined) opts.parent.children.push(entity); + + return entity; +} + +/* ------------------------------------------------------------------ */ +/* World transform */ +/* ------------------------------------------------------------------ */ + +/** + * Compose the transform of an entity with its ancestors. Recomputed on + * demand. For the shallow trees this library encourages, caching isn't + * worth the invalidation bookkeeping. + */ +export function getWorldTransform(entity: Entity): Transform { + if (entity.parent === null) return entity.transform; + + const parent = getWorldTransform(entity.parent); + + return { + position: { + x: parent.position.x + entity.transform.position.x, + y: parent.position.y + entity.transform.position.y, + }, + anchor: entity.transform.anchor, + scaleX: parent.scaleX * entity.transform.scaleX, + scaleY: parent.scaleY * entity.transform.scaleY, + opacity: parent.opacity * entity.transform.opacity, + rotation: parent.rotation + entity.transform.rotation, + }; +} diff --git a/packages/shimejic/src/core/index.ts b/packages/shimejic/src/core/index.ts new file mode 100644 index 0000000..b4439cf --- /dev/null +++ b/packages/shimejic/src/core/index.ts @@ -0,0 +1,126 @@ +export { anchorOffset, Canvas2DRenderer } from "./renderer.ts"; +export type { + Anchor, + ReflectionDraw, + Renderer, + RendererConfig, + RendererSize, + ShadowDraw, + SpriteDraw, + TextDraw, +} from "./renderer.ts"; + +export { PhysicsSolver, RigidBody } from "./physics.ts"; +export type { BodyConfig, BodyType, SolverConfig, Vec2 } from "./physics.ts"; + +export { createEntity, DEFAULT_TRANSFORM, getWorldTransform } from "./entity.ts"; +export type { + BodySlot, + BubbleSlot, + BubbleTextConfig, + CustomSlot, + Entity, + EntityOptions, + ReflectionSlot, + ShadowSlot, + SlotKey, + SpriteFrame, + SpriteSlot, + Transform, +} from "./entity.ts"; + +export type { System } from "./system.ts"; + +export { Camera } from "./camera.ts"; +export type { CameraConfig } from "./camera.ts"; + +export { World } from "./world.ts"; +export type { WorldConfig, WorldStats } from "./world.ts"; + +export { animatedSprite, Animator, imageSize, staticSprite } from "./animation.ts"; +export type { AnimatedSprite, AnimatedSpriteOptions, AnimationClip } from "./animation.ts"; + +export { AssetCache } from "./assets.ts"; +export type { AssetCacheConfig, CacheStats, ImageInfo, ImageManifest, LoadedImage } from "./assets.ts"; + +export { angleFromPoint, CursorService, distanceBetween, matchSector } from "./cursor.ts"; +export type { CursorInfo, CursorLookConfig, CursorSector, SectorMatch } from "./cursor.ts"; + +export { BehaviorController } from "./behavior.ts"; +export type { + AnimationClip as BehaviorAnimationClip, + BehaviorBounds, + BehaviorContext, + BehaviorControllerConfig, + BehaviorState, + ChatterCue, + DebugSnapshot, + EnterContext, + EventDef, + LookConfig, + LookSector, + TrackName, +} from "./behavior.ts"; + +export { DEFAULT_STYLE } from "./chatter-types.ts"; +export type { + BubbleConfig, + BubbleRenderData, + CharToken, + ChatterSlot, + IconAlign, + IconSize, + IconToken, + Layout, + LayoutIconItem, + LayoutItem, + LayoutTextItem, + ParsedMessage, + ParseOptions, + PauseToken, + SentenceInfo, + SentenceType, + SpeedToken, + StyleCloseToken, + StyleOpenToken, + TailPosition, + TextAlign, + TextBaseline, + TextConfig, + TextStyle, + TimingConfig, + Token, + VoiceMood, + VoiceToken, + Vowel, +} from "./chatter-types.ts"; + +export { parseMessage } from "./chatter-parser.ts"; + +export { ChatterOverlay } from "./chatter-overlay.ts"; +export type { ChatterOverlayConfig } from "./chatter-overlay.ts"; + +export { DEFAULT_VOICE, VOWEL_FORMANTS } from "./chatter-types.ts"; +export type { ContourConfig, EmotionConfig, VoiceConfig } from "./chatter-types.ts"; + +export { Mumble, planMumble, synthesizeVowel } from "./mumble.ts"; +export type { MumbleOptions, PlanMumbleOptions, ScheduledBurst } from "./mumble.ts"; + +export { validateConfig } from "./character-config.ts"; +export type { + AtlasDefinition, + BubbleDefinition, + CharacterConfig, + ChatterCueDefinition, + ClipDefinition, + EventDefinition, + FrameRegion, + IconDefinition, + LookDefinition, + LookSectorDefinition, + StateDefinition, + TextDefinition, + TimingDefinition, + ValidationError, + VoiceDefinition, +} from "./character-config.ts"; diff --git a/packages/shimejic/src/core/mumble.ts b/packages/shimejic/src/core/mumble.ts new file mode 100644 index 0000000..4602b00 --- /dev/null +++ b/packages/shimejic/src/core/mumble.ts @@ -0,0 +1,628 @@ +/** + * mumble.ts — procedural speech synthesis for chatter. + * + * Synthesizes vowel bursts using formant synthesis with a noise layer. + * Triggered per-vowel by the parser's token stream. Vowels are filtered + * through three resonant formants (F1, F2, F3); consonants are silent. + * A breath layer adds texture, more so for whisper. + * + * Pitch is driven by sentence contours (statement, question, exclamation, + * ellipsis) combined multiplicatively with emotion presets, uppercase + * shouting, and `{voice}` overrides. Per-vowel jitter adds organic variance. + * + * On-demand, main thread. No caching. No SFX — non-speech synthesis is a + * separate future module. + */ + +import type { ParsedMessage, SentenceType, VoiceMood, Vowel } from "./chatter-types.ts"; +import { + DEFAULT_VOICE, + VOWEL_FORMANTS, + type ContourConfig, + type EmotionConfig, + type VoiceConfig, +} from "./chatter-types.ts"; + +/* ------------------------------------------------------------------ */ +/* Constants */ +/* ------------------------------------------------------------------ */ + +const REFERENCE_F0 = 200; // Hz at basePitch = 1.0 +const MAX_BURST_DURATION = 0.2; // cap on per-burst length +const MIN_BURST_DURATION = 0.03; // floor on per-burst length +const BURST_DURATION_MULTIPLIER = 1.5; +const BURST_MIN_FILL_RATIO = 0.6; +const SCHEDULING_DELAY = 0.02; // 20ms ahead for scheduling safety +const SYNTHESIS_LEAD_TIME = 0.08; // 80ms lead for spreading CPU load +const SYNTHESIS_AMPLITUDE = 0.2; // per-burst base amplitude + +/* ------------------------------------------------------------------ */ +/* Types */ +/* ------------------------------------------------------------------ */ + +export interface ScheduledBurst { + /** Seconds from message start. */ + atTime: number; + /** Duration of the burst in seconds (already clamped and timeScale-adjusted). */ + burstDuration: number; + /** Target F0 in Hz after all multipliers. */ + pitch: number; + /** Formant frequency multiplier. */ + formantScale: number; + /** 0..1 noise mix. */ + noiseMix: number; + /** 0..1 volume. */ + volume: number; + /** Which vowel to synthesize. */ + vowel: Vowel; +} + +export interface PlanMumbleOptions { + rng?: () => number; + timeScale?: number; +} + +export interface MumbleOptions { + rng?: () => number; +} + +/* ------------------------------------------------------------------ */ +/* Plan (pure) */ +/* ------------------------------------------------------------------ */ + +/** + * Compute the full burst schedule for a parsed message. + * Pure — no audio context, no side effects, deterministic given the rng. + * Tests target this function. + */ +export function planMumble( + parsed: ParsedMessage, + voice: VoiceConfig, + options: PlanMumbleOptions = {}, +): ScheduledBurst[] { + const rng = options.rng ?? Math.random; + const timeScale = Math.max(0.01, options.timeScale ?? 1); + + const merged = mergeVoice(voice, DEFAULT_VOICE); + const basePitch = merged.basePitch; + const formantScale = merged.formantScale; + const baseNoise = merged.noiseMix; + const baseVolume = merged.volume; + + // Per-sentence start times and durations + const sentenceStarts: number[] = []; + const sentenceDurations: number[] = []; + let accum = 0; + for (const s of parsed.sentences) { + sentenceStarts.push(accum); + let dur = 0; + for (let i = s.startToken; i <= s.endToken; i++) { + const tok = parsed.tokens[i]; + if (tok) dur += tok.duration; + } + sentenceDurations.push(dur); + accum += dur; + } + + // Token -> sentence index + const sentenceOfToken: number[] = new Array(parsed.tokens.length).fill(0); + for (let s = 0; s < parsed.sentences.length; s++) { + const si = parsed.sentences[s]!; + for (let i = si.startToken; i <= si.endToken; i++) { + sentenceOfToken[i] = s; + } + } + + const lastWordBySentence: Array<{ + startToken: number; + startTime: number; + duration: number; + }> = []; + + for (let s = 0; s < parsed.sentences.length; s++) { + const sent = parsed.sentences[s]!; + let startToken = sent.startToken; + + for (let k = sent.endToken - 1; k >= sent.startToken; k--) { + const tok = parsed.tokens[k]; + if (!tok) continue; + const isBoundary = (tok.kind === "char" && (tok.ch === " " || tok.ch === "\t")) || tok.kind === "pause"; + if (isBoundary) { + startToken = k + 1; + break; + } + } + + let startTime = 0; + for (let k = sent.startToken; k < startToken; k++) { + const tok = parsed.tokens[k]; + if (tok) startTime += tok.duration; + } + + let duration = 0; + for (let k = startToken; k <= sent.endToken; k++) { + const tok = parsed.tokens[k]; + if (tok) duration += tok.duration; + } + + lastWordBySentence.push({ startToken, startTime, duration }); + } + + const result: ScheduledBurst[] = []; + let timeOffset = 0; + let currentPitchMult = 1; + let currentVolumeMult = 1; + let currentMood: VoiceMood | null = null; + + for (let i = 0; i < parsed.tokens.length; i++) { + const token = parsed.tokens[i]!; + + // Non-timed tokens — mutate voice state only + if (token.kind === "voice") { + if (token.mood !== undefined) currentMood = token.mood; + if (token.pitch !== undefined) currentPitchMult = token.pitch; + if (token.volume !== undefined) currentVolumeMult = token.volume; + continue; + } + if (token.kind === "speed") continue; + if (token.kind === "style-open" || token.kind === "style-close") continue; + + // Timed but silent + if (token.kind === "pause" || token.kind === "icon") { + timeOffset += token.duration; + continue; + } + + if (token.kind === "char") { + if (token.isVowel && token.vowel !== undefined) { + // Detect a run of adjacent vowels. Style tokens are transparent + // (they don't affect audio). Anything else breaks the run. + let runVowel: Vowel = token.vowel; + let runDuration = token.duration; + let runShout = token.shout; + + let j = i + 1; + while (j < parsed.tokens.length) { + const next = parsed.tokens[j]!; + + if (next.kind === "style-open" || next.kind === "style-close") { + j++; + continue; + } + if (next.kind === "char" && next.isVowel && next.vowel !== undefined) { + runDuration += next.duration; + runShout = runShout || next.shout; + j++; + continue; + } + break; + } + + const si = sentenceOfToken[i]!; + const sent = parsed.sentences[si]!; + const sentStart = sentenceStarts[si]!; + const sentDur = sentenceDurations[si]!; + const elapsedInSentence = timeOffset - sentStart; + const tNorm = sentDur > 0 ? Math.min(1, Math.max(0, elapsedInSentence / sentDur)) : 0; + + let contourMult: number; + if (sent.type === "question") { + const lw = lastWordBySentence[si]!; + if (i >= lw.startToken) { + // Inside the last word — rise + const tInWord = lw.duration > 0 ? (elapsedInSentence - lw.startTime) / lw.duration : 1; + const clampedT = Math.min(1, Math.max(0, tInWord)); + contourMult = computeContour(merged.contours.question, clampedT); + } else { + // Before the last word — flat + contourMult = 1.0; + } + } else { + const contourCfg = merged.contours[sent.type]; + contourMult = computeContour(contourCfg, tNorm); + } + + const emotionCfg: EmotionConfig | null = currentMood ? merged.emotions[currentMood] : null; + const emotionMult = emotionCfg?.pitch ?? 1; + const emotionNoise = emotionCfg?.noiseBonus ?? 0; + + const shoutMult = runShout ? 1.2 : 1; + const variation = 1 + (rng() - 0.5) * 0.04; + + const finalPitch = + REFERENCE_F0 * basePitch * contourMult * emotionMult * currentPitchMult * shoutMult * variation; + + const rawDur = runDuration * BURST_DURATION_MULTIPLIER; + const clampedDur = Math.min(MAX_BURST_DURATION, Math.max(MIN_BURST_DURATION, rawDur)); + const scaledDur = clampedDur / timeScale; + + const burst: ScheduledBurst = { + atTime: timeOffset / timeScale, + burstDuration: scaledDur, + pitch: finalPitch, + formantScale, + noiseMix: Math.min(1, baseNoise + emotionNoise), + volume: baseVolume * currentVolumeMult, + vowel: runVowel, + }; + result.push(burst); + + timeOffset += runDuration; + i = j - 1; // outer loop i++ lands on the token after the run + continue; + } + // Non-vowel char — silent, still advances time + timeOffset += token.duration; + } + } + + for (let k = 0; k < result.length - 1; k++) { + const current = result[k]!; + const next = result[k + 1]!; + const intervalToNext = next.atTime - current.atTime; + if (intervalToNext <= 0) continue; + + const minForFill = intervalToNext * BURST_MIN_FILL_RATIO; + if (minForFill > current.burstDuration) { + current.burstDuration = Math.min(MAX_BURST_DURATION, minForFill); + } + } + + return result; +} + +/* ------------------------------------------------------------------ */ +/* Synthesize (pure) */ +/* ------------------------------------------------------------------ */ + +/** + * Synthesize a single vowel burst to a Float32Array. + * + * Formant synthesis: a harmonic-rich source at F0 is filtered through + * three resonant filters (F1, F2, F3), then mixed with filtered noise + * for breathiness. An attack-sustain-release envelope shapes the result. + */ +export function synthesizeVowel( + vowel: Vowel, + pitch: number, + duration: number, + sampleRate: number, + noiseMix: number, + formantScale: number, + volume: number, + rng: () => number = Math.random, +): Float32Array { + const numSamples = Math.max(1, Math.floor(sampleRate * duration)); + const out = new Float32Array(numSamples); + + const formants = VOWEL_FORMANTS[vowel]; + const f1 = formants.f1 * formantScale; + const f2 = formants.f2 * formantScale; + const f3 = formants.f3 * formantScale; + + const bq1 = makeResonator(f1, sampleRate); + const bq2 = makeResonator(f2, sampleRate); + const bq3 = makeResonator(f3, sampleRate); + const noiseLP = makeLowpass(3500, sampleRate); + + const maxHarmonics = Math.min(10, Math.max(1, Math.floor(sampleRate / 2 / pitch))); + const phases = new Float32Array(maxHarmonics); + const phaseStep = (2 * Math.PI * pitch) / sampleRate; + const TWO_PI = Math.PI * 2; + + const attackSamples = Math.min(Math.floor(sampleRate * 0.012), Math.floor(numSamples * 0.2)); + const releaseSamples = Math.min(Math.floor(sampleRate * 0.03), Math.floor(numSamples * 0.4)); + const sustainEnd = numSamples - releaseSamples; + + for (let i = 0; i < numSamples; i++) { + // Source: additive harmonics + let source = 0; + for (let k = 0; k < maxHarmonics; k++) { + source += Math.sin(phases[k]!) / (k + 1); + phases[k] = (phases[k]! + phaseStep * (k + 1)) % TWO_PI; + } + + // Formant filters + const o1 = bq1.step(source); + const o2 = bq2.step(source); + const o3 = bq3.step(source); + const vowelSig = o1 * 1.0 + o2 * 0.55 + o3 * 0.25; + + // Noise + const noise = rng() * 2 - 1; + const noiseSig = noiseLP.step(noise); + const mixed = (1 - noiseMix) * vowelSig + noiseMix * noiseSig * 2.5; + + // Envelope + let env = 1; + if (i < attackSamples) env = i / attackSamples; + else if (i >= sustainEnd) { + env = Math.max(0, (numSamples - i) / releaseSamples); + } + + // Soft limit + volume + amplitude + const v = mixed * env * volume * SYNTHESIS_AMPLITUDE; + out[i] = Math.tanh(v); + } + + return out; +} + +/* ------------------------------------------------------------------ */ +/* Mumble */ +/* ------------------------------------------------------------------ */ + +export class Mumble { + private ctx: AudioContext | null = null; + private masterGain: GainNode | null = null; + + private muted = false; + private timeScale = 1; + private voiceDefaults: VoiceConfig = {}; + private readonly rng: () => number; + + /** Per-entity active sources, so one entity's speech doesn't stop another's. */ + private readonly sourcesByEntity = new Map>(); + /** Per-entity pending synthesis timers. */ + private readonly timersByEntity = new Map>>(); + + constructor(options: MumbleOptions = {}) { + this.rng = options.rng ?? Math.random; + } + + /* -------------------------------------------------------------- */ + /* Lifecycle */ + /* -------------------------------------------------------------- */ + + attach(ctx: AudioContext): void { + this.detach(); + this.ctx = ctx; + this.masterGain = ctx.createGain(); + this.masterGain.gain.value = 0.7; + this.masterGain.connect(ctx.destination); + } + + detach(): void { + this.stopAll(); + if (this.masterGain !== null) { + try { + this.masterGain.disconnect(); + } catch { + // Node already disconnected + } + } + this.ctx = null; + this.masterGain = null; + } + + isAvailable(): boolean { + return this.ctx !== null && this.masterGain !== null; + } + + /* -------------------------------------------------------------- */ + /* Config */ + /* -------------------------------------------------------------- */ + + setVoiceDefaults(voice: VoiceConfig): void { + this.voiceDefaults = voice; + } + + setMuted(muted: boolean): void { + this.muted = muted; + if (muted) this.stopAll(); + } + + isMuted(): boolean { + return this.muted; + } + + setTimeScale(scale: number): void { + this.timeScale = Math.max(0.01, scale); + // Existing sources keep their rate — new messages get the new scale. + // Changing mid-playback isn't supported cleanly without re-scheduling. + } + + /* -------------------------------------------------------------- */ + /* Speak */ + /* -------------------------------------------------------------- */ + + /** + * Speak a parsed message for an entity. + * Stops any previous speech for the same entity. + * No-op silently if no AudioContext or muted. + */ + speak(entityId: string, parsed: ParsedMessage, voice?: VoiceConfig): void { + if (!this.ctx || !this.masterGain) return; + if (this.muted) return; + if (this.ctx.state === "suspended") void this.ctx.resume(); + + this.stop(entityId); + + const merged = mergeVoice(voice ?? this.voiceDefaults, this.voiceDefaults); + const schedule = planMumble(parsed, merged, { + rng: this.rng, + timeScale: this.timeScale, + }); + + const now = this.ctx.currentTime; + const baseTime = now + SCHEDULING_DELAY; + + const sources = new Set(); + const timers = new Set>(); + this.sourcesByEntity.set(entityId, sources); + this.timersByEntity.set(entityId, timers); + + for (const burst of schedule) { + const playAt = baseTime + burst.atTime; + const delay = playAt - now; + + if (delay < SYNTHESIS_LEAD_TIME) { + this.playBurst(entityId, burst, playAt, sources); + } else { + const timer = setTimeout( + () => { + timers.delete(timer); + if (this.ctx && this.sourcesByEntity.get(entityId) === sources) { + this.playBurst(entityId, burst, playAt, sources); + } + }, + Math.max(0, (delay - SYNTHESIS_LEAD_TIME) * 1000), + ); + timers.add(timer); + } + } + } + + /** Stop speech for one entity. Clears its pending bursts and cuts active ones. */ + stop(entityId: string): void { + const sources = this.sourcesByEntity.get(entityId); + if (sources) { + for (const src of sources) { + try { + src.stop(); + } catch { + // Already stopped + } + } + sources.clear(); + } + const timers = this.timersByEntity.get(entityId); + if (timers) { + for (const t of timers) clearTimeout(t); + timers.clear(); + } + } + + /** Stop all speech across entities. */ + stopAll(): void { + for (const entityId of [...this.sourcesByEntity.keys()]) this.stop(entityId); + this.sourcesByEntity.clear(); + this.timersByEntity.clear(); + } + + /* -------------------------------------------------------------- */ + /* Playback */ + /* -------------------------------------------------------------- */ + + private playBurst( + entityId: string, + burst: ScheduledBurst, + playAt: number, + sources: Set, + ): void { + if (!this.ctx || !this.masterGain) return; + + const samples = synthesizeVowel( + burst.vowel, + burst.pitch, + burst.burstDuration, + this.ctx.sampleRate, + burst.noiseMix, + burst.formantScale, + burst.volume, + this.rng, + ); + + if (samples.length === 0) return; + + const buffer = this.ctx.createBuffer(1, samples.length, this.ctx.sampleRate); + buffer.copyToChannel(samples, 0); + + const source = this.ctx.createBufferSource(); + source.buffer = buffer; + source.connect(this.masterGain); + + source.onended = () => { + sources.delete(source); + try { + source.disconnect(); + } catch { + // Already disconnected + } + }; + + source.start(playAt); + sources.add(source); + } +} + +/* ------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------ */ + +interface Filter { + step(x: number): number; +} + +function makeResonator(freq: number, sampleRate: number, bandwidth = 100): Filter { + // Two-pole resonator with unity gain at resonance. + const r = Math.exp((-Math.PI * bandwidth) / sampleRate); + const theta = (2 * Math.PI * freq) / sampleRate; + const a1 = 2 * r * Math.cos(theta); + const a2 = -r * r; + const b0 = (1 - r) * Math.sqrt(1 - 2 * r * Math.cos(2 * theta) + r * r); + + let y1 = 0; + let y2 = 0; + return { + step(x: number): number { + const y = b0 * x + a1 * y1 + a2 * y2; + y2 = y1; + y1 = y; + return y; + }, + }; +} + +function makeLowpass(freq: number, sampleRate: number): Filter { + // One-pole lowpass for noise shaping. + const rc = 1 / (2 * Math.PI * freq); + const dt = 1 / sampleRate; + const alpha = dt / (rc + dt); + let prev = 0; + return { + step(x: number): number { + prev = prev + alpha * (x - prev); + return prev; + }, + }; +} + +function computeContour(cfg: ContourConfig, tNorm: number): number { + const eased = applyEase(tNorm, cfg.ease ?? "linear"); + return cfg.from + (cfg.to - cfg.from) * eased; +} + +function applyEase(t: number, ease: string): number { + switch (ease) { + case "ease-in": + return t * t; + case "ease-out": + return 1 - (1 - t) * (1 - t); + case "ease-in-out": + return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t); + default: + return t; + } +} + +function mergeVoice(override: VoiceConfig, fallback: VoiceConfig): typeof DEFAULT_VOICE { + const emotions: Record = { + ...DEFAULT_VOICE.emotions, + ...fallback.emotions, + ...override.emotions, + }; + const contours: Record = { + ...DEFAULT_VOICE.contours, + ...fallback.contours, + ...override.contours, + }; + return { + basePitch: override.basePitch ?? fallback.basePitch ?? DEFAULT_VOICE.basePitch, + formantScale: override.formantScale ?? fallback.formantScale ?? DEFAULT_VOICE.formantScale, + noiseMix: override.noiseMix ?? fallback.noiseMix ?? DEFAULT_VOICE.noiseMix, + volume: override.volume ?? fallback.volume ?? DEFAULT_VOICE.volume, + emotions, + contours, + }; +} diff --git a/packages/shimejic/src/core/physics.ts b/packages/shimejic/src/core/physics.ts new file mode 100644 index 0000000..442b890 --- /dev/null +++ b/packages/shimejic/src/core/physics.ts @@ -0,0 +1,296 @@ +/** + * physics.ts — rigid AABB bodies with world collisions. + * + * The solver: + * - integrates forces and velocity each step + * - resolves collisions against floor, ceiling, and side walls + * - applies restitution and Coulomb friction at contacts + * - never knows about entities, sprites, or rendering + * + * Coordinate system: + * - x grows right, y grows down + * - position is the top-left corner of the AABB + * - gravity is a positive-y acceleration + * - units: pixels, seconds + * + * Design notes: + * Bodies carry an `id` and a `type` tag so future constraint solvers can + * reference them. The solver has distinct integrate/collide phases so a + * constraint phase can be inserted between them later. + */ + +export interface Vec2 { + x: number; + y: number; +} + +export type BodyType = "box"; + +export interface BodyConfig { + /** Top-left corner. */ + position: Vec2; + width: number; + height: number; + /** Default 1. Set to 0 for a static (immovable) body. */ + mass?: number; + /** Bounciness, 0–1. Default 0.4. */ + restitution?: number; + /** Coulomb friction coefficient. Default 0.3. */ + friction?: number; + /** Fraction of velocity lost per second. Default 0 (no damping). */ + linearDamping?: number; +} + +export interface SolverConfig { + width: number; + height: number; + /** Thickness of the floor strip at the bottom, px. Default 0. */ + floorHeight?: number; + /** Default { x: 0, y: 1000 }. */ + gravity?: Vec2; + /** + * Vertical speed below which a ground contact snaps to rest instead of + * bouncing. Prevents jitter. Default 20. + */ + restVelocityThreshold?: number; +} + +let nextBodyId = 0; + +/* ------------------------------------------------------------------ */ +/* RigidBody */ +/* ------------------------------------------------------------------ */ + +export class RigidBody { + readonly id: number; + readonly type: BodyType = "box"; + + readonly position: Vec2; + readonly velocity: Vec2; + /** Force accumulator. Cleared after each step. */ + readonly force: Vec2; + + readonly width: number; + readonly height: number; + + readonly mass: number; + readonly inverseMass: number; + readonly restitution: number; + readonly friction: number; + readonly linearDamping: number; + + /** Contact flags, valid after step(). Cleared at the start of each step. */ + onGround = false; + onCeiling = false; + onLeftWall = false; + onRightWall = false; + + constructor(cfg: BodyConfig) { + this.id = nextBodyId++; + this.position = { x: cfg.position.x, y: cfg.position.y }; + this.velocity = { x: 0, y: 0 }; + this.force = { x: 0, y: 0 }; + this.width = cfg.width; + this.height = cfg.height; + this.mass = cfg.mass ?? 1; + this.inverseMass = this.mass > 0 ? 1 / this.mass : 0; + this.restitution = cfg.restitution ?? 0.4; + this.friction = cfg.friction ?? 0.3; + this.linearDamping = cfg.linearDamping ?? 0; + } + + get left(): number { + return this.position.x; + } + get right(): number { + return this.position.x + this.width; + } + get top(): number { + return this.position.y; + } + get bottom(): number { + return this.position.y + this.height; + } + get centerX(): number { + return this.position.x + this.width * 0.5; + } + get centerY(): number { + return this.position.y + this.height * 0.5; + } + + /** Add a continuous force. Accumulates until the next step. */ + applyForce(f: Vec2): void { + this.force.x += f.x; + this.force.y += f.y; + } + + /** Instantaneous velocity change. `v += impulse / mass`. */ + applyImpulse(i: Vec2): void { + this.velocity.x += i.x * this.inverseMass; + this.velocity.y += i.y * this.inverseMass; + } + + /** Overwrite velocity directly, bypassing mass. */ + setVelocity(v: Vec2): void { + this.velocity.x = v.x; + this.velocity.y = v.y; + } + + /** Zero the force accumulator. Called by the solver after each step. */ + clearForces(): void { + this.force.x = 0; + this.force.y = 0; + } +} + +/* ------------------------------------------------------------------ */ +/* PhysicsSolver */ +/* ------------------------------------------------------------------ */ + +export class PhysicsSolver { + gravity: Vec2; + width: number; + height: number; + floorHeight: number; + restVelocityThreshold: number; + + readonly bodies: RigidBody[] = []; + + constructor(cfg: SolverConfig) { + this.gravity = cfg.gravity ?? { x: 0, y: 1000 }; + this.width = cfg.width; + this.height = cfg.height; + this.floorHeight = cfg.floorHeight ?? 0; + this.restVelocityThreshold = cfg.restVelocityThreshold ?? 20; + } + + /** World-space Y of the floor surface. */ + get floorY(): number { + return this.height - this.floorHeight; + } + + addBody(body: RigidBody): RigidBody { + this.bodies.push(body); + return body; + } + + removeBody(body: RigidBody): void { + const i = this.bodies.indexOf(body); + if (i >= 0) this.bodies.splice(i, 1); + } + + /** Update world dimensions. Clamps any body that would be out of bounds. */ + resize(width: number, height: number, floorHeight?: number): void { + this.width = width; + this.height = height; + if (floorHeight !== undefined) this.floorHeight = floorHeight; + + for (const body of this.bodies) { + if (body.left < 0) body.position.x = 0; + if (body.right > this.width) body.position.x = this.width - body.width; + if (body.bottom > this.floorY) body.position.y = this.floorY - body.height; + } + } + + /** + * Advance by `dt` seconds. + * Each body is integrated, then its collisions against the world are + * resolved. Contact flags are cleared before integration. + */ + step(dt: number): void { + for (const body of this.bodies) { + body.onGround = false; + body.onCeiling = false; + body.onLeftWall = false; + body.onRightWall = false; + + this.integrate(body, dt); + this.resolveWorldCollisions(body, dt); + } + } + + /* -------------------------------------------------------------- */ + + private integrate(body: RigidBody, dt: number): void { + // Static bodies ignore gravity and integration. + if (body.inverseMass === 0) return; + + // Gravity as a force: F += m · g. This makes the acceleration + // mass-independent since a = F / m = g. + body.force.x += this.gravity.x * body.mass; + body.force.y += this.gravity.y * body.mass; + + // v += (F / m) · dt + body.velocity.x += body.force.x * body.inverseMass * dt; + body.velocity.y += body.force.y * body.inverseMass * dt; + + // Damping: multiplicative decay, frame-rate independent. + if (body.linearDamping > 0) { + const retain = Math.pow(1 - body.linearDamping, dt); + body.velocity.x *= retain; + body.velocity.y *= retain; + } + + // Semi-implicit Euler: use the just-updated velocity. + body.position.x += body.velocity.x * dt; + body.position.y += body.velocity.y * dt; + + body.clearForces(); + } + + private resolveWorldCollisions(body: RigidBody, dt: number): void { + const floorY = this.floorY; + + /* --- floor --- */ + if (body.bottom > floorY) { + body.position.y = floorY - body.height; + body.onGround = true; + + if (body.velocity.y > 0) { + if (body.velocity.y < this.restVelocityThreshold) { + body.velocity.y = 0; + } else { + body.velocity.y = -body.velocity.y * body.restitution; + } + } + + if (body.friction > 0 && body.velocity.x !== 0) { + // Coulomb friction: deceleration μ·|g| per second. + const frictionAccel = body.friction * Math.abs(this.gravity.y); + const dv = frictionAccel * dt; + if (Math.abs(body.velocity.x) <= dv) { + body.velocity.x = 0; + } else { + body.velocity.x -= Math.sign(body.velocity.x) * dv; + } + } + } + + /* --- ceiling --- */ + if (body.top < 0) { + body.position.y = 0; + body.onCeiling = true; + if (body.velocity.y < 0) { + body.velocity.y = -body.velocity.y * body.restitution; + } + } + + /* --- left wall --- */ + if (body.left < 0) { + body.position.x = 0; + body.onLeftWall = true; + if (body.velocity.x < 0) { + body.velocity.x = -body.velocity.x * body.restitution; + } + } + + /* --- right wall --- */ + if (body.right > this.width) { + body.position.x = this.width - body.width; + body.onRightWall = true; + if (body.velocity.x > 0) { + body.velocity.x = -body.velocity.x * body.restitution; + } + } + } +} diff --git a/packages/shimejic/src/core/render-primitives.ts b/packages/shimejic/src/core/render-primitives.ts new file mode 100644 index 0000000..e69de29 diff --git a/packages/shimejic/src/core/renderer.ts b/packages/shimejic/src/core/renderer.ts new file mode 100644 index 0000000..b88ec4d --- /dev/null +++ b/packages/shimejic/src/core/renderer.ts @@ -0,0 +1,415 @@ +/** + * renderer.ts — Canvas 2D renderer. + * + * The Renderer interface is backend-agnostic. Canvas2DRenderer is the only + * implementation shipped. Everything else in shimejic draws through this + * interface, never through `ctx` directly (except via the escape hatch). + * + * Pixel-art correctness: + * - imageSmoothingEnabled is disabled on every context that draws bitmaps + * - draw positions are rounded to integers when pixelArt is true + * - the canvas CSS property `image-rendering: pixelated` is expected to be + * set by the caller (or by a framework adapter); the renderer cannot set + * CSS from TypeScript + * + * DPI: + * The backing store is sized to cssSize × devicePixelRatio. A transform is + * set so all draw calls think in CSS pixels. Every primitive takes CSS + * pixel coordinates. + */ + +/* ------------------------------------------------------------------ */ +/* Public types */ +/* ------------------------------------------------------------------ */ + +export type Anchor = + | "top-left" + | "top-center" + | "top-right" + | "center-left" + | "center" + | "center-right" + | "bottom-left" + | "bottom-center" + | "bottom-right"; + +export interface RendererSize { + width: number; + height: number; + dpr: number; +} + +export interface RendererConfig { + canvas: HTMLCanvasElement; + /** Disable smoothing and round to integer positions. Default true. */ + pixelArt?: boolean; + /** Cap on devicePixelRatio. Default 3. */ + maxDpr?: number; + /** Override for testing. Default: window.devicePixelRatio || 1. */ + devicePixelRatio?: number; + /** Fill colour applied after clear. Omit for transparent. */ + backgroundColor?: string; + /** + * Factory for offscreen scratch canvases (used by reflections). + * Defaults to document.createElement('canvas'). Inject for tests. + */ + createCanvas?: () => HTMLCanvasElement; +} + +export interface SpriteDraw { + image: CanvasImageSource; + /** Anchor position in CSS pixels. Meaning depends on `anchor`. */ + x: number; + y: number; + width: number; + height: number; + /** Default 'top-left'. */ + anchor?: Anchor; + /** Flip horizontally. Default false. */ + mirrored?: boolean; + /** Overall alpha, 0–1. Default 1. */ + alpha?: number; + /** Additional x scale about the anchor. Default 1. */ + scaleX?: number; + /** Additional y scale about the anchor. Default 1. */ + scaleY?: number; + sx?: number; + sy?: number; + sw?: number; + sh?: number; +} + +export interface ShadowDraw { + cx: number; + cy: number; + rx: number; + ry: number; + color?: string; + alpha?: number; +} + +export interface ReflectionDraw { + image: CanvasImageSource; + x: number; + y: number; + width: number; + height: number; + anchor?: Anchor; + mirrored?: boolean; + alpha?: number; + /** Fade toward the far edge, 0–1. Default 0. */ + fade?: number; + /** Colour wash applied with source-atop. Omit for no tint. */ + tint?: string; + /** Which way the reflection fades. Default 'down'. */ + fadeDirection?: "down" | "up"; +} + +export interface TextDraw { + content: string; + x: number; + y: number; + width: number; + height: number; + /** Full CSS font string, e.g. "12px monospace". */ + font?: string; + color?: string; + align?: "left" | "center" | "right"; + baseline?: "top" | "middle" | "bottom"; + /** Multiplier over font size. Default 1.2. */ + lineHeight?: number; + /** Word-wrap to width. Default true. */ + wrap?: boolean; + /** Reveal only the first N characters (cumulative across lines). Default Infinity. */ + charsShown?: number; +} + +export interface Renderer { + resize(cssW: number, cssH: number): void; + clear(): void; + drawSprite(d: SpriteDraw): void; + drawShadow(s: ShadowDraw): void; + drawReflection(r: ReflectionDraw): void; + drawText(t: TextDraw): void; + readonly size: RendererSize; + /** Escape hatch. Prefer primitives. */ + readonly ctx: CanvasRenderingContext2D; +} + +/* ------------------------------------------------------------------ */ +/* Helpers */ +/* ------------------------------------------------------------------ */ + +function drawImageRect(ctx: CanvasRenderingContext2D, d: SpriteDraw, dx: number, dy: number): void { + if (d.sx !== undefined && d.sy !== undefined && d.sw !== undefined && d.sh !== undefined) { + ctx.drawImage(d.image, d.sx, d.sy, d.sw, d.sh, dx, dy, d.width, d.height); + } else { + ctx.drawImage(d.image, dx, dy, d.width, d.height); + } +} + +/** Offset from the anchor point to the image's top-left corner. */ +export function anchorOffset(anchor: Anchor, w: number, h: number): { ox: number; oy: number } { + const hx = anchor.includes("left") ? 0 : anchor.includes("right") ? -w : -w / 2; + const hy = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? -h : -h / 2; + return { ox: hx, oy: hy }; +} + +function parseFontSize(font: string | undefined): number { + if (!font) return 11; + const m = /(\d+(?:\.\d+)?)px/.exec(font); + return m?.[1] !== undefined ? parseFloat(m[1]) : 11; +} + +function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] { + const words = text.split(/\s+/).filter(Boolean); + const lines: string[] = []; + let line = ""; + for (const word of words) { + const candidate = line.length > 0 ? `${line} ${word}` : word; + if (ctx.measureText(candidate).width <= maxWidth) { + line = candidate; + } else { + if (line.length > 0) lines.push(line); + line = word; + } + } + if (line.length > 0) lines.push(line); + return lines; +} + +/* ------------------------------------------------------------------ */ +/* Canvas2DRenderer */ +/* ------------------------------------------------------------------ */ + +export class Canvas2DRenderer implements Renderer { + readonly ctx: CanvasRenderingContext2D; + readonly canvas: HTMLCanvasElement; + + private readonly pixelArt: boolean; + private readonly maxDpr: number; + private readonly dprOverride: number | undefined; + private readonly backgroundColor: string | undefined; + private readonly createCanvas: () => HTMLCanvasElement; + + private dpr = 1; + private cssW = 0; + private cssH = 0; + + private reflCanvas: HTMLCanvasElement | null = null; + private reflCtx: CanvasRenderingContext2D | null = null; + private reflW = 0; + private reflH = 0; + + constructor(cfg: RendererConfig) { + this.canvas = cfg.canvas; + const ctx = this.canvas.getContext("2d"); + if (!ctx) throw new Error("Canvas2DRenderer: could not acquire 2D context"); + this.ctx = ctx; + + this.pixelArt = cfg.pixelArt ?? true; + this.maxDpr = cfg.maxDpr ?? 3; + this.dprOverride = cfg.devicePixelRatio; + this.backgroundColor = cfg.backgroundColor; + this.createCanvas = cfg.createCanvas ?? (() => document.createElement("canvas")); + + // Sensible default transform so early draws aren't unscaled. + this.applyTransform(); + } + + get size(): RendererSize { + return { width: this.cssW, height: this.cssH, dpr: this.dpr }; + } + + resize(cssW: number, cssH: number): void { + const w = Math.max(1, cssW); + const h = Math.max(1, cssH); + const dpr = Math.min(this.dprOverride ?? window.devicePixelRatio ?? 1, this.maxDpr); + + if (w === this.cssW && h === this.cssH && dpr === this.dpr) return; + + this.cssW = w; + this.cssH = h; + this.dpr = dpr; + + this.canvas.width = Math.round(w * dpr); + this.canvas.height = Math.round(h * dpr); + this.applyTransform(); + } + + clear(): void { + this.ctx.clearRect(0, 0, this.cssW, this.cssH); + if (this.backgroundColor !== undefined) { + this.ctx.fillStyle = this.backgroundColor; + this.ctx.fillRect(0, 0, this.cssW, this.cssH); + } + } + + drawShadow(s: ShadowDraw): void { + const alpha = s.alpha ?? 0.3; + if (alpha <= 0) return; + + const ctx = this.ctx; + ctx.save(); + ctx.globalAlpha = alpha; + ctx.fillStyle = s.color ?? "#000"; + ctx.beginPath(); + ctx.ellipse(s.cx, s.cy, s.rx, s.ry, 0, 0, Math.PI * 2); + ctx.fill(); + ctx.restore(); + } + + drawSprite(d: SpriteDraw): void { + const alpha = d.alpha ?? 1; + if (alpha <= 0) return; + + const anchor = d.anchor ?? "top-left"; + const { ox, oy } = anchorOffset(anchor, d.width, d.height); + const ax = this.round(d.x); + const ay = this.round(d.y); + + const scaleX = (d.mirrored === true ? -1 : 1) * (d.scaleX ?? 1); + const scaleY = d.scaleY ?? 1; + + const ctx = this.ctx; + ctx.save(); + ctx.globalAlpha = alpha; + + if (scaleX !== 1 || scaleY !== 1) { + ctx.translate(ax, ay); + ctx.scale(scaleX, scaleY); + drawImageRect(ctx, d, ox, oy); + } else { + drawImageRect(ctx, d, ax + ox, ay + oy); + } + + ctx.restore(); + } + + drawReflection(r: ReflectionDraw): void { + const alpha = r.alpha ?? 1; + if (alpha <= 0.01) return; + + const pw = Math.max(1, Math.round(r.width * this.dpr)); + const ph = Math.max(1, Math.round(r.height * this.dpr)); + + if (this.reflW !== pw || this.reflH !== ph) { + if (this.reflCanvas === null) { + this.reflCanvas = this.createCanvas(); + } + this.reflCanvas.width = pw; + this.reflCanvas.height = ph; + this.reflW = pw; + this.reflH = ph; + } + + if (this.reflCtx === null) { + const c = this.reflCanvas?.getContext("2d"); + if (!c) return; + this.reflCtx = c; + } + const rc = this.reflCtx; + + rc.setTransform(1, 0, 0, 1, 0, 0); + rc.globalCompositeOperation = "source-over"; + rc.globalAlpha = 1; + rc.clearRect(0, 0, pw, ph); + rc.imageSmoothingEnabled = !this.pixelArt; + + // 1. Draw the image flipped vertically (and optionally horizontally). + rc.save(); + rc.translate(r.mirrored === true ? pw : 0, ph); + rc.scale(r.mirrored === true ? -1 : 1, -1); + rc.drawImage(r.image, 0, 0, pw, ph); + rc.restore(); + + // 2. Tint — paints only over existing pixels. + if (r.tint !== undefined) { + rc.globalCompositeOperation = "source-atop"; + rc.fillStyle = r.tint; + rc.fillRect(0, 0, pw, ph); + } + + // 3. Fade toward the far edge. + const fade = Math.min(Math.max(r.fade ?? 0, 0), 1); + if (fade > 0) { + rc.globalCompositeOperation = "destination-out"; + const grad = rc.createLinearGradient(0, 0, 0, ph); + const topA = r.fadeDirection === "up" ? fade : 0; + const botA = r.fadeDirection === "up" ? 0 : fade; + grad.addColorStop(0, `rgba(0,0,0,${topA})`); + grad.addColorStop(1, `rgba(0,0,0,${botA})`); + rc.fillStyle = grad; + rc.fillRect(0, 0, pw, ph); + } + rc.globalCompositeOperation = "source-over"; + + // 4. Composite to the main canvas. + const anchor = r.anchor ?? "top-left"; + const { ox, oy } = anchorOffset(anchor, r.width, r.height); + const x = this.round(r.x) + ox; + const y = this.round(r.y) + oy; + + const ctx = this.ctx; + ctx.save(); + ctx.globalAlpha = alpha; + ctx.drawImage(this.reflCanvas!, x, y, r.width, r.height); + ctx.restore(); + } + + drawText(t: TextDraw): void { + if (t.content.length === 0) return; + + const ctx = this.ctx; + const fontSize = parseFontSize(t.font); + const lineHeight = (t.lineHeight ?? 1.2) * fontSize; + const align = t.align ?? "center"; + const baseline = t.baseline ?? "top"; + const charsShown = t.charsShown ?? Infinity; + + ctx.save(); + ctx.font = t.font ?? "11px monospace"; + ctx.fillStyle = t.color ?? "#000"; + ctx.textBaseline = baseline === "middle" ? "middle" : baseline; + ctx.textAlign = align; + + const lines = t.wrap === false ? [t.content] : wrapText(ctx, t.content, t.width); + + const anchorX = align === "left" ? t.x : align === "right" ? t.x + t.width : t.x + t.width / 2; + + const baseY = baseline === "top" ? t.y : baseline === "bottom" ? t.y + t.height : t.y + t.height / 2; + + let cursor = 0; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (line === undefined) continue; + const visible = Math.max(0, Math.min(line.length, charsShown - cursor)); + if (visible <= 0) break; + + const yy = + baseline === "top" + ? baseY + i * lineHeight + : baseline === "bottom" + ? baseY - (lines.length - 1 - i) * lineHeight + : baseY - ((lines.length - 1) / 2 - i) * lineHeight; + + ctx.fillText(line.slice(0, visible), anchorX, yy); + + cursor += line.length; + if (visible < line.length) break; + } + + ctx.restore(); + } + + /* -------------------------------------------------------------- */ + + private applyTransform(): void { + this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0); + this.ctx.imageSmoothingEnabled = !this.pixelArt; + } + + private round(v: number): number { + return this.pixelArt ? Math.round(v) : v; + } +} diff --git a/packages/shimejic/src/core/system.ts b/packages/shimejic/src/core/system.ts new file mode 100644 index 0000000..68bc33f --- /dev/null +++ b/packages/shimejic/src/core/system.ts @@ -0,0 +1,27 @@ +/** + * system.ts — the system interface. + * + * A system is an object with an `update` method. Systems run in ascending + * `order`. `renderOnly` systems run during render() instead of update(), + * and are skipped by pause/timescale on the update side. + */ + +import type { World } from "./world.ts"; + +export interface System { + readonly name: string; + /** Sort key. Lower runs first. Default 0. */ + readonly order?: number; + /** + * When true, this system runs during World.render() with the last + * scaled dt, instead of during World.update(). + */ + readonly renderOnly?: boolean; + + update(world: World, dt: number): void; + + /** Called once when added to a world. */ + onAdd?(world: World): void; + /** Called once when removed from a world. */ + onRemove?(world: World): void; +} diff --git a/packages/shimejic/src/core/world.ts b/packages/shimejic/src/core/world.ts new file mode 100644 index 0000000..324a80a --- /dev/null +++ b/packages/shimejic/src/core/world.ts @@ -0,0 +1,204 @@ +/** + * world.ts — the top-level simulation container. + * + * Owns entities, systems, time state, and the optional camera. Provides + * safe add/remove during iteration via deferred queues flushed at the end + * of each update. + * + * The update loop: + * 1. Compute scaled dt (respects pause and timeScale). + * 2. Update camera. + * 3. Run each non-render system in order. + * 4. Flush pending adds and removes. + * + * The render loop: + * 1. Run each renderOnly system in order with the last scaled dt. + * + * Additions and removals are queued, not applied immediately. A system + * that adds an entity during update will not see it until the next frame. + */ + +import { Camera, type CameraConfig } from "./camera.ts"; +import { createEntity, type Entity, type EntityOptions, type SlotKey } from "./entity.ts"; +import type { System } from "./system.ts"; + +export interface WorldConfig { + width: number; + height: number; + /** Clamp on raw frame dt, seconds. Default 1/20. */ + maxDelta?: number; + camera?: CameraConfig; +} + +export interface WorldStats { + frameCount: number; + lastRawDt: number; + lastScaledDt: number; +} + +export class World { + width: number; + height: number; + timeScale = 1; + paused = false; + /** Scaled seconds elapsed since creation. */ + time = 0; + + readonly camera: Camera; + readonly maxDelta: number; + readonly stats: WorldStats = { + frameCount: 0, + lastRawDt: 0, + lastScaledDt: 0, + }; + + private readonly _entities: Entity[] = []; + private readonly _systems: System[] = []; + private readonly _pendingAdds: Entity[] = []; + private readonly _pendingRemoves: Entity[] = []; + private lastScaledDt = 0; + + constructor(cfg: WorldConfig) { + this.width = cfg.width; + this.height = cfg.height; + this.maxDelta = cfg.maxDelta ?? 1 / 20; + this.camera = new Camera(cfg.camera); + } + + /* -------------------------------------------------------------- */ + /* Accessors */ + /* -------------------------------------------------------------- */ + + get entities(): readonly Entity[] { + return this._entities; + } + + get systems(): readonly System[] { + return this._systems; + } + + /** Entities with no parent. Renderers iterate these and recurse. */ + get roots(): readonly Entity[] { + const result: Entity[] = []; + for (const e of this._entities) { + if (!e.destroyed && e.parent === null) result.push(e); + } + return result; + } + + /* -------------------------------------------------------------- */ + /* Entities */ + /* -------------------------------------------------------------- */ + + /** Create an entity and queue it for addition. */ + createEntity(opts: EntityOptions = {}): Entity { + const e = createEntity(opts); + this._pendingAdds.push(e); + return e; + } + + /** Queue an already-created entity for addition. */ + addEntity(entity: Entity): Entity { + this._pendingAdds.push(entity); + return entity; + } + + /** + * Mark an entity as destroyed and queue it for removal. + * Cascades to children. Idempotent. + */ + removeEntity(entity: Entity): void { + if (entity.destroyed) return; + entity.destroyed = true; + + // Detach from parent + if (entity.parent !== null) { + const i = entity.parent.children.indexOf(entity); + if (i >= 0) entity.parent.children.splice(i, 1); + entity.parent = null; + } + + // Cascade to children (copy the array first — removeEntity mutates it) + for (const child of [...entity.children]) { + this.removeEntity(child); + } + + this._pendingRemoves.push(entity); + } + + /** All live entities that have the given slot populated. */ + entitiesWith(slot: K): Entity[] { + const result: Entity[] = []; + for (const e of this._entities) { + if (e.destroyed) continue; + if (e[slot] !== undefined) result.push(e); + } + return result; + } + + /* -------------------------------------------------------------- */ + /* Systems */ + /* -------------------------------------------------------------- */ + + addSystem(system: System): System { + this._systems.push(system); + this._systems.sort((a, b) => (a.order ?? 0) - (b.order ?? 0)); + system.onAdd?.(this); + return system; + } + + removeSystem(system: System): void { + const i = this._systems.indexOf(system); + if (i < 0) return; + this._systems.splice(i, 1); + system.onRemove?.(this); + } + + /* -------------------------------------------------------------- */ + /* Main loop */ + /* -------------------------------------------------------------- */ + + update(rawDt: number): void { + this.stats.frameCount++; + this.stats.lastRawDt = rawDt; + + const clamped = Math.min(rawDt, this.maxDelta); + const scaledDt = this.paused ? 0 : clamped * this.timeScale; + + this.stats.lastScaledDt = scaledDt; + this.lastScaledDt = scaledDt; + this.time += scaledDt; + + this.camera.update(scaledDt); + + for (const sys of this._systems) { + if (sys.renderOnly === true) continue; + sys.update(this, scaledDt); + } + + this.flush(); + } + + render(): void { + for (const sys of this._systems) { + if (sys.renderOnly !== true) continue; + sys.update(this, this.lastScaledDt); + } + } + + /* -------------------------------------------------------------- */ + + private flush(): void { + if (this._pendingAdds.length > 0) { + for (const e of this._pendingAdds) this._entities.push(e); + this._pendingAdds.length = 0; + } + if (this._pendingRemoves.length > 0) { + for (const e of this._pendingRemoves) { + const i = this._entities.indexOf(e); + if (i >= 0) this._entities.splice(i, 1); + } + this._pendingRemoves.length = 0; + } + } +} diff --git a/packages/shimejic/src/features/index.ts b/packages/shimejic/src/features/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/packages/shimejic/src/index.ts b/packages/shimejic/src/index.ts index cb0ff5c..a71c9a1 100644 --- a/packages/shimejic/src/index.ts +++ b/packages/shimejic/src/index.ts @@ -1 +1,2 @@ -export {}; +export * from "./core/index"; +export * from "./systems/index"; diff --git a/packages/shimejic/src/systems/index.ts b/packages/shimejic/src/systems/index.ts new file mode 100644 index 0000000..6679178 --- /dev/null +++ b/packages/shimejic/src/systems/index.ts @@ -0,0 +1,3 @@ +export { PhysicsSystem } from "./physics-system"; +export { RenderSystem } from "./render-system"; +export type { RenderSystemConfig } from "./render-system"; diff --git a/packages/shimejic/src/systems/physics-system.ts b/packages/shimejic/src/systems/physics-system.ts new file mode 100644 index 0000000..874c573 --- /dev/null +++ b/packages/shimejic/src/systems/physics-system.ts @@ -0,0 +1,66 @@ +/** + * physics-system.ts — steps the solver and syncs bodies into transforms. + * + * The body's AABB drives the entity's transform. The transform position is + * set to the point on the AABB that corresponds to the entity's anchor: + * anchor 'bottom-center' → the AABB's bottom-center + * anchor 'top-left' → the AABB's top-left corner + * anchor 'center' → the AABB's center + * + * This keeps the rendered sprite aligned with its physics footprint + * regardless of where the anchor is. + */ + +import { getWorldTransform } from "../core/entity"; +import type { PhysicsSolver } from "../core/physics"; +import type { Anchor } from "../core/renderer"; +import type { System } from "../core/system"; +import type { World } from "../core/world"; + +function anchorPointOnBox( + left: number, + top: number, + width: number, + height: number, + anchor: Anchor, +): { x: number; y: number } { + const hx = anchor.includes("left") ? 0 : anchor.includes("right") ? width : width / 2; + const hy = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? height : height / 2; + return { x: left + hx, y: top + hy }; +} + +export class PhysicsSystem implements System { + readonly name = "physics"; + readonly order = 70; + + constructor(private readonly solver: PhysicsSolver) {} + + update(world: World, dt: number): void { + this.solver.step(dt); + + for (const entity of world.entities) { + const slot = entity.body; + if (slot === undefined || slot.syncTransform === false) continue; + + const body = slot.body; + const point = anchorPointOnBox( + body.position.x, + body.position.y, + body.width, + body.height, + entity.transform.anchor, + ); + + // Parent offset: if the entity has a parent, we want the local + // transform to reflect the world position minus the parent's. + if (entity.parent !== null) { + const parentWorld = getWorldTransform(entity.parent); + entity.transform.position.x = point.x - parentWorld.position.x; + entity.transform.position.y = point.y - parentWorld.position.y; + } else { + entity.transform.position.x = point.x; + entity.transform.position.y = point.y; + } + } + } +} diff --git a/packages/shimejic/src/systems/render-system.ts b/packages/shimejic/src/systems/render-system.ts new file mode 100644 index 0000000..9c1efea --- /dev/null +++ b/packages/shimejic/src/systems/render-system.ts @@ -0,0 +1,242 @@ +/** + * render-system.ts — walks entities and drives the renderer. + * + * Per entity, draws in a fixed order: + * shadow → reflection → sprite → bubble → custom → children + * + * The system knows nothing about what any slot means; it reads each slot's + * config and delegates to the renderer's primitives. + * + * Shadows and reflections use the sprite's current frame size. If there's + * no sprite slot or the slot returns null, they're skipped. + */ + +import type { BubbleTextConfig, Entity } from "../core/entity"; +import { getWorldTransform } from "../core/entity"; +import type { Renderer, TextDraw } from "../core/renderer"; +import { anchorOffset } from "../core/renderer"; +import type { System } from "../core/system"; +import type { World } from "../core/world"; + +export interface RenderSystemConfig { + renderer: Renderer; + /** + * World-space Y coordinate of the ground line. Shadows sit here; + * reflections are placed here and sink as the entity rises. + */ + groundY?: number; +} + +export class RenderSystem implements System { + readonly name = "render"; + readonly order = 1000; + readonly renderOnly = true; + + groundY: number; + + private readonly renderer: Renderer; + + constructor(cfg: RenderSystemConfig) { + this.renderer = cfg.renderer; + this.groundY = cfg.groundY ?? 0; + } + + update(world: World, _dt: number): void { + this.renderer.clear(); + for (const root of world.roots) { + this.drawEntity(root, world); + } + } + + /* -------------------------------------------------------------- */ + + private drawEntity(entity: Entity, world: World): void { + if (!entity.visible || entity.destroyed) return; + + const worldT = getWorldTransform(entity); + const screen = world.camera.toScreen(worldT.position); + + const frame = entity.sprite?.frame() ?? null; + if (frame !== null) { + const sx = worldT.scaleX; + const sy = worldT.scaleY; + + const { ox, oy } = anchorOffset(worldT.anchor, frame.width, frame.height); + const topLeftX = screen.x + ox * sx; + const topLeftY = screen.y + oy * sy; + const visualW = frame.width * sx; + const visualH = frame.height * sy; + const centerX = topLeftX + visualW / 2; + const topY = topLeftY; + const bottomY = topLeftY + visualH; + + const groundScreen = world.camera.toScreen({ x: 0, y: this.groundY }); + const heightAboveGround = Math.max(0, groundScreen.y - bottomY); + + if (entity.shadow !== undefined) { + this.drawShadow(entity, centerX, visualW, visualH, heightAboveGround, worldT.opacity); + } + + if (entity.reflection !== undefined) { + this.drawReflection( + entity, + frame.image, + centerX, + visualW, + visualH, + groundScreen.y, + heightAboveGround, + worldT.opacity, + worldT.scaleX < 0, + ); + } + + this.renderer.drawSprite({ + image: frame.image, + x: screen.x, + y: screen.y, + width: frame.width, + height: frame.height, + anchor: worldT.anchor, + alpha: worldT.opacity, + scaleX: worldT.scaleX, + scaleY: worldT.scaleY, + }); + + if (entity.bubble !== undefined) { + this.drawBubble(entity, centerX, topY, worldT.opacity); + } + } + + entity.custom?.draw?.(this.renderer.ctx, entity); + + for (const child of entity.children) { + this.drawEntity(child, world); + } + } + + private drawShadow( + entity: Entity, + centerX: number, + visualW: number, + _visualH: number, + heightAboveGround: number, + parentOpacity: number, + ): void { + const slot = entity.shadow; + if (slot === undefined) return; + + const maxHeight = slot.maxHeight ?? 200; + const t = Math.min(Math.max(heightAboveGround / maxHeight, 0), 1); + + const rx = visualW * (slot.rx ?? 0.4) * (1 - t * 0.5); + const ry = rx * (slot.ry ?? 0.25); + + const groundScreen = this.groundY; + const baseAlpha = slot.alpha ?? 0.32; + const fade = slot.fadeByHeight ?? 0.85; + const alpha = baseAlpha * (1 - t * fade) * parentOpacity; + + if (alpha <= 0) return; + + this.renderer.drawShadow({ + cx: centerX, + cy: groundScreen, + rx, + ry, + alpha, + ...(slot.color !== undefined && { color: slot.color }), + }); + } + + private drawReflection( + entity: Entity, + image: CanvasImageSource, + centerX: number, + visualW: number, + visualH: number, + groundScreenY: number, + heightAboveGround: number, + parentOpacity: number, + mirrored: boolean, + ): void { + const slot = entity.reflection; + if (slot === undefined) return; + + const baseOpacity = slot.opacity ?? 0.4; + const fadeByHeight = slot.fadeByHeight ?? 0.5; + const alpha = baseOpacity * (1 - (heightAboveGround * fadeByHeight) / 100) * parentOpacity; + if (alpha <= 0.01) return; + + // Sink the reflection into the floor as the entity rises. + const sinkY = groundScreenY + heightAboveGround * 0.5; + + this.renderer.drawReflection({ + image, + x: centerX, + y: sinkY, + width: visualW, + height: visualH, + anchor: "top-center", + mirrored, + alpha, + fade: slot.fade ?? 0.85, + ...(slot.tint !== undefined && { tint: slot.tint }), + }); + } + + private drawBubble(entity: Entity, centerX: number, topY: number, parentOpacity: number): void { + const slot = entity.bubble; + if (slot === undefined) return; + + const anchorX = slot.anchorX ?? 0; + const anchorY = slot.anchorY ?? 4; + + this.renderer.drawSprite({ + image: slot.image, + x: centerX + anchorX, + y: topY - anchorY, + width: slot.width, + height: slot.height, + anchor: "bottom-center", + alpha: parentOpacity, + }); + + if (slot.text !== undefined) { + this.drawBubbleText(slot.text, slot.width, slot.height, centerX + anchorX, topY - anchorY, parentOpacity); + } + } + + private drawBubbleText( + text: BubbleTextConfig, + bubbleW: number, + bubbleH: number, + anchorX: number, + anchorY: number, + parentOpacity: number, + ): void { + const pad = text.padding ?? { top: 8, right: 8, bottom: 8, left: 8 }; + const bx = anchorX - bubbleW / 2 + pad.left; + const by = anchorY - bubbleH + pad.top; + const bw = bubbleW - pad.left - pad.right; + const bh = bubbleH - pad.top - pad.bottom; + if (bw <= 0 || bh <= 0) return; + + const draw: TextDraw = { + content: text.content, + x: bx, + y: by, + width: bw, + height: bh, + baseline: "top", + }; + if (text.font !== undefined) draw.font = text.font; + if (text.color !== undefined) draw.color = text.color; + if (text.align !== undefined) draw.align = text.align; + if (text.lineHeight !== undefined) draw.lineHeight = text.lineHeight; + if (text.wrap !== undefined) draw.wrap = text.wrap; + if (text.charsShown !== undefined) draw.charsShown = text.charsShown; + + this.renderer.drawText(draw); + } +}