Game · project 18 of 37
Fluffy Cat Kingdom.
A free 3D game a young player designed: chase fluffy orange cats through a candy kingdom, hatch tiny T-rexes, slide down Chocolate Mountain and care for your cats at home.
BeforeA child's drawing of fluffy orange cats, a list of rules in her words, and no game to play.
AfterHer own 3D game: ten fluffy cats to catch with one button, baby T-rexes, a chocolate slide and a home for her cats.
What it is worthA free game made from her own idea, with no ads, no accounts and nothing to buy. Instead of shop games full of ads, timers and things to buy.
How to use it
- Tap Play with the sound up (it plays even when an iPhone is on silent). The three paw buttons on the first screen set how fast the cats are: one paw is easiest.
- Move with the joystick on the left half of the screen, WASD or the arrow keys. Drag on the right half, or press Q and E, to turn the camera.
- Use the one big paw button or Space: tap to jump, hold it in the air to float down slowly, press it when the button turns gold to catch the cat with the heart ring. A sleeping or resting cat is caught just by running into it.
- Catch all ten cats (Golden Fluff comes last, on a cloud) to win the trophy. Look at the picture bubble over each princess for a small wish, and visit the T-rex eggs by the plaza.
- From the first screen or the trophy screen, pick a place: 🏡 Cat Home to pet your cats and spend candy on toys and outfits, 🍫 Chocolate Mountain to slide and catch cats, 🙈 Hide and Seek, or 🍭 Candy Hunt. The pause button has a 🏰 to come back to the kingdom from any of them.
- Two players: connect a second controller and press ✕ on it. A second catcher in a blue hoodie joins. Both can catch cats and pick up candy for the team, and the camera keeps both on screen.
Where it helps most
- A first 3D game for children of about four to eight, on a tablet, phone or computer, with no reading, no ads and nothing to buy.
- Parents who want to build a game from their own child's idea and keep changing it with her: the master prompt and the code show how.
- A short, happy shared game on the couch: the child plays, the grown-up cheers and helps find the last cat.
The idea
A young player described the game: lots of fluffy cats, orange on top, that run around and play tag; you chase and catch them; catching all of them means you win; the same button jumps and catches; a joystick; a Minecraft-like world; funny cats; candy; princesses; trophies. I wanted to take a child's idea seriously and build it properly for the iPad, and see how far a small AI studio could take it in one evening. After playing it, the young designer asked for changes: no dark rain clouds, trees that do not get in the way, and tiny friendly T-rexes that hatch from eggs, follow the cats and play with their own toys, with no biting and no fire. Those are in the game now.
The build
Claude ran it as a small studio: a lead that wrote the game code, a creative director agent that proposed concepts, challenged the plan and wrote the cat personalities, an audio agent that synthesized every sound and the music in code, and an independent QA agent that played each version and scored it against a weighted scorecard (6.8, then 7.3, 7.8, 8.1 and 8.4 out of 10, aiming for 8.5). It is TypeScript with Three.js and Vite, one page with no server. The cats are real shell-texture fur: each body part is drawn 9 to 14 times as stacked shells cut into strands by a shader, orange on top and cream below, so they look fluffy and not like spheres with ears. The world is a voxel grid with its own small physics (gravity, step-up, trampolines), and the cats, T-rexes and home cats run on small state machines (wander, flee, tease, tired, hide, sleep, statue, dance; egg, hatch, follow, play; sit, eat, petted, chase) with no AI calls at run time. Trees, cats and toys that come between the camera and the player fade away so a small child never loses sight of herself. Chocolate Mountain is a separate scene: a spiral half-pipe built on a smooth curve, with boost arrows, ramps and cats that drift into her lane. The princess wishes are picture bubbles with dots for progress, no words and no clock, and they cannot fail. All sound is made live with the Web Audio API and plays on an iPhone even in silent mode. Candy, owned toys, outfits, trophies and cat names stay on the device only: no ads, accounts, tracking or real money. Each version was played to the end at four screen sizes under the site's security rules. Limits: it has not been tested on a real iPhone or iPad by us, only by the family; old or slow phones get fewer fur layers and a lower resolution; the last QA score, 8.4, is just under the 8.5 target, and that last check did not re-test every mode. Two-player co-op (2026-11-27): the second controller drives a second catcher in a blue hoodie, made from the same Player class. It catches cats, picks up candy and floats like player 1; the camera frames both and pulls back as they spread out; player 2 pops back beside player 1 after a fall or when more than 22 m away. Each controller now has its own pause button state, so holding Options on one pad no longer flickers the pause screen.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: Fluffy Cat Kingdom
You lead a small AI game studio (lead engineer, creative director, audio director, independent QA). Build an original 3D web game from a six-year-old's idea: lots of fluffy cats, orange on top; they run around and play tag; the player chases and catches them; catching all of them wins; one button for jump and catch, including holding it; joystick controls; a voxel world of your own (no content from any other game); funny cats; everything fluffy; candy; princesses; trophies. Her later rules are fixed: no dark or rain clouds, trees never block her view, tiny friendly T-rexes hatch from eggs, follow the cats and play with their own toys, no biting, no fire, nothing scary.
Stack: TypeScript, Vite, Three.js, no backend, no runtime network calls, no AI calls at run time. Relative base path so it runs in any subfolder. Progress in localStorage, versioned (candy banked as it is picked up, trophies, cat names, owned toys, outfit, settings), merged with defaults on load.
World: a voxel island on a grid (1-unit soft chamfered blocks, frosting tops that drip down the sides, cookie sides), rolling hills, a checkered sugar plaza, a castle plateau with round towers and a rainbow arch, cupcake houses, about 18 candy and cotton-candy trees spaced away from the paths, giant cupcakes (hiding spots), marshmallow trampolines, a cotton-candy cloud sea at the edge, a pastel sky with only white clouds. Own kinematic physics: gravity, step up one block, walls, trampolines; a cloud catches her if she falls off. Any tree crown or trunk, friend cat or toy between the camera and the player is hidden; the camera tries a higher angle before it moves in.
Cats: shell-texture fur (each part drawn as stacked shells, strands cut by a 3D cell pattern, orange top, cream belly with varied belly, eye and stripe colours, fur that drifts with motion), big glossy eyes, blink, twitching ears, a six-segment tail, blob shadow. Poses: stand, sit, flop, butt-wiggle tease, dance, statue, sleep, spin. Ten personalities, each one rule and one gag: an easy tutorial cat; a huge slow one that bounces; a tiny one that hops like popcorn; a captain who hides in a cupcake; a princess who trips on her tail; a jittery one; a sleeper who snores, then gets the zoomies once; a sparkly one that leaves stars; a statue that sneezes, topples and rests; Golden Fluff who appears on a cloud after nine are caught. Cats play tag, bonk, dance, tease, flee and tire soon so every cat can be caught. On the easiest paw they never leave a hiding spot and hop low.
One button: tap = jump (coyote time, buffering, quick taps always count), hold in the air = slow float, press near a cat = catch. Generous range; the button turns gold and a heart ring marks the catchable cat; resting cats are caught by touch. A catch is a hug: a tiny freeze, a camera nudge, hearts, a fanfare, candy, and the cat joins a spaced parade that copies her jumps. Standing still gives purrs; after 8 seconds a cat boops her nose. Candy in a row makes a rising chime.
T-rexes: three eggs near the plaza wobble when she comes close, crack and hatch with a tiny rawr. Babies follow the nearest cats (or her), copy her jumps, sneeze rainbows and kick their own ball, which can bonk a cat but never hurts it.
Princesses: Sugarbell in the plaza and Mintly in the castle each show a picture bubble with one wish at a time (5 candies, bring a friend, bounce 3 times, visit the cupcake, visit the T-rex, catch 2 cats, jump 10 times), with dots for progress, no words, no clock, never failing. A finished wish glows until she walks back to the princess, who gives a gift and candy. Bubbles stay on screen and below the top bar.
Cat Home: a separate garden scene with a cottage where every caught cat lives. Cats wander, use toys, sit, sleep, eat, chase a feather wand, greet her. Pet (paw), treat (cookie) and rename (pencil, text cleaned) from a card for the nearest cat. A shop sells toys for candy (bed and yarn free; trampoline, wand, cat tower, slide, ball pit, fountain, rainbow) and a wardrobe of hood colours and hats (bow, flowers, party, tiara, wizard), with a short show-off camera after she wears something. A trophy shelf shows each trophy and a see-through one still to win. Three T-rexes live there too.
Chocolate Mountain: a separate scene, a spiral half-pipe slide built on a smooth curve. She rides a cookie sled after a 3-2-1 count; left and right steer, up and down go faster or slower. Candies, boost arrows and small ramps on the way; eight cats ride down and drift toward her lane when close; missed cats come back further down; on the easiest paw close cats are caught by themselves. A finish screen with Again and Home saves a mountain trophy.
Hide and Seek: the cats hide in shuffled spots on open ground around the village (never next to a wall, so no cat ends up on a roof) and giggle; she finds them one by one; after 30 seconds with no find the nearest hider peeks out in front of her. The pause menu has a castle button back to the title from every mode. Candy Hunt: 75 seconds of candy falling from the sky with a time bar and an end screen with Again.
Screens: a title with a picture how-to, three difficulty paws, Play, and a row of place buttons (home, mountain, hide and seek, candy hunt). Victory: trophy, fireworks, confetti, dancing cats, then Keep playing for a faster round, Home or Mountain. Pause on Escape. Toasts stack.
Controls: left-half floating joystick and a big round button on touch; WASD/arrows and Space; drag or Q/E for the camera; gamepad; F for the wand at home.
Sound: all synthesized with Web Audio (formant meows by mood, soft toy-like effects, rawr, egg wobble and crack, pet, treat, buy, wear, unlock, five music loops with a 0.6 s lookahead scheduler and few voices). iPhone silent mode: set navigator.audioSession.type to playback before creating the AudioContext, else loop a same-origin silent MP3; resume on every tap; a watchdog rebuilds a stuck context; a sound button.
Two players: the second connected controller plays a second catcher in a blue hoodie (same Player class). It catches cats and picks up candy for the team; one camera frames both and pulls back as they spread; player 2 pops back beside player 1 after a fall or when more than 22 m away. Keep each controller's pause state separate. Press ✕ on the second controller to join.
Finish: pastel sky dome, fog, soft lighting shared by every shader, adaptive resolution, fewer fur shells on touch devices. Test hooks on window for automated play. Stress test each version: play to the trophy and round 2, run the mountain to the end, find all hidden cats, finish a candy hunt, buy and wear in the Cat Home, at 320x568, 393x700, 740x360 and 1366x800 under a strict CSP (no inline scripts or styles, no outside fonts); mash the button, walk off the edge, resize; no console errors, no sideways scroll. An independent QA agent scores every version on a weighted scorecard; aim for 8.5 with no category under 7.
Get the code32 files, exactly as they run on this site · free under the MIT license
These are the source files. The site serves the built version at sghadimi.com/games/fluffy-cat-kingdom (public/games/fluffy-cat-kingdom: index.html, one JavaScript bundle and one stylesheet made by `npm run build`, and audio/silence.mp3 for iPhone silent mode). Three.js (MIT) is bundled. No images or sound files: everything is drawn and synthesized in code.
the page17 lines
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no" />
<title>Fluffy Cat Kingdom</title>
<meta name="description" content="A free 3D game for young children: chase fluffy orange cats in a candy voxel kingdom, collect candy and win a trophy. One button, no ads, no accounts.">
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
</head>
<body>
<canvas id="game"></canvas>
<div id="ui"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
main.ts707 lines
// Fluffy Cat Kingdom - boot, game loop, adventure mode, HUD and victory.
import './style.css';
import * as THREE from 'three';
import { setQuality, sharedLight, softMaterial } from './render/fur';
import { buildVillage } from './world/village';
import { makeSky } from './render/sky';
import { Input } from './input/input';
import { Player } from './player/player';
import { Cat, CAT_DEFS } from './cats/cats';
import type { CatWorld } from './cats/cats';
import { Particles } from './fx/particles';
import { Princess, makeTrophy } from './game/characters';
import { TinyRex } from './game/trex';
import { Sanctuary } from './game/sanctuary';
import { applyOutfit } from './game/wardrobe';
import { Quests } from './game/quests';
import { Mountain } from './game/mountain';
import { audio } from './audio';
import { angleDiff, clamp, damp, lerp } from './core/util';
import { loadSave, persist } from './save/save';
const isTouch = matchMedia('(pointer: coarse)').matches || 'ontouchstart' in window;
setQuality(isTouch);
const save = loadSave();
const canvas = document.getElementById('game') as HTMLCanvasElement;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: !isTouch, powerPreference: 'high-performance' });
let pixelRatio = Math.min(devicePixelRatio, isTouch ? 1.6 : 2);
renderer.setPixelRatio(pixelRatio);
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#ffd9ec');
const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 260);
function resize() { renderer.setSize(innerWidth, innerHeight, false); camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); }
addEventListener('resize', resize); resize();
const sky = makeSky();
scene.add(sky);
sharedLight.uFogColor.value.set('#ffe0f0');
const level = buildVillage(7);
scene.add(level.group);
const fx = new Particles(); scene.add(fx.mesh);
const input = new Input(canvas);
const player = new Player(level.world);
scene.add(player.root, player.shadowMesh);
applyOutfit(player, save.outfit);
player.body.pos.copy(level.spawn);
/* Player 2: a second catcher in a blue hoodie, played with a second controller (co-op on the same screen).
Press any face button on the second controller during play to join. Player 2 catches cats and picks up candy for
the team; one camera frames both, and player 2 pops back beside player 1 if they get too far apart. */
const player2 = new Player(level.world, '#2f8cff');
player2.setHood('#2f8cff', '#bfe3ff');
player2.root.traverse(o => { const m = (o as THREE.Mesh).material as THREE.ShaderMaterial | undefined; const u = m && m.uniforms && m.uniforms.uColor; if (u && (u.value as THREE.Color).getHexString() === '7b5cc4') (o as THREE.Mesh).material = softMaterial('#2f6fd6'); });
player2.root.visible = false; player2.shadowMesh.visible = false;
scene.add(player2.root, player2.shadowMesh);
let p2On = false;
function placeP2() {
const a = player.yaw + Math.PI / 2;
player2.body.pos.copy(player.body.pos).add(new THREE.Vector3(Math.sin(a) * 1.6, 0.6, Math.cos(a) * 1.6));
player2.body.vel.set(0, 0, 0); player2.yaw = player.yaw;
}
function setP2(on: boolean) {
if (on === p2On) return;
p2On = on; player2.root.visible = on; player2.shadowMesh.visible = on;
if (on) { placeP2(); fx.emit(player2.body.pos.clone().setY(player2.body.pos.y + 1), 30, { color: ['#7cc8ff', '#ffffff', '#b79bff'], speed: 3, up: 3, size: 0.1 }); audio.play('unlock'); toast('💙 Player 2 joined!'); }
else toast('Player 2 left. Press ✕ on the second controller to join again.');
}
const sugarbell = new Princess('#ff9cc9', '#ffc4de', '#ffcf7a');
// Princess Mintly waits in the castle yard with a gift
const mintly = new Princess('#9fe8cf', '#d4fff0', '#6fd3c8');
mintly.root.position.set(0, 5, -20.5); scene.add(mintly.root);
let mintlyGift = false;
// helper arrow: points at the nearest cat when none is close
const arrow = new THREE.Mesh(new THREE.ConeGeometry(0.28, 0.7, 12), new THREE.MeshBasicMaterial({ color: '#ffcf3f' }));
arrow.geometry.rotateX(Math.PI / 2); scene.add(arrow);
let cuddleT = 0;
let hitStop = 0, camPunch = 0, candyStreak = 0, candyStreakT = 0, boopT = 0;
const catName = (c: Cat) => save.names[c.def.id] || c.def.name;
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.75, 0.07, 8, 32), new THREE.MeshBasicMaterial({ color: '#ffcf3f' }));
ring.rotation.x = -Math.PI / 2; ring.geometry.rotateX(Math.PI / 2); scene.add(ring);
for (let i = 0; i < 6; i++) { const h = new THREE.Mesh(new THREE.SphereGeometry(0.09, 8, 6), new THREE.MeshBasicMaterial({ color: '#ff7fb0' })); const a = i / 6 * Math.PI * 2; h.position.set(Math.cos(a) * 0.75, 0.05, Math.sin(a) * 0.75); ring.add(h); }
sugarbell.root.position.copy(level.princessSpot); scene.add(sugarbell.root);
// candies
const candyGeo = (() => { const g = new THREE.SphereGeometry(0.22, 12, 8); return g; })();
const wrapGeo = new THREE.ConeGeometry(0.16, 0.28, 6);
const CANDY_COLORS = ['#ff5e9c', '#ffb648', '#7ee0a1', '#6cc6ff', '#c79bff', '#ffe25e'];
interface Candy { pos: THREE.Vector3; mesh: THREE.Group; taken: boolean; fly: number }
const candies: Candy[] = level.candySpots.map((p, i) => {
const g = new THREE.Group(); const col = CANDY_COLORS[i % CANDY_COLORS.length];
const m = new THREE.MeshLambertMaterial({ color: col, emissive: col, emissiveIntensity: 0.35 });
g.add(new THREE.Mesh(candyGeo, m));
for (const sx of [-1, 1]) { const w = new THREE.Mesh(wrapGeo, m); w.rotation.z = sx * Math.PI / 2; w.position.x = sx * 0.3; g.add(w); }
g.position.copy(p); scene.add(g);
return { pos: p.clone(), mesh: g, taken: false, fly: 0 };
});
// cats
const trail: THREE.Vector3[] = [];
const cw: CatWorld = { level, playerPos: player.body.pos, playerSpeed: 0, cats: [], fx, difficulty: save.settings.difficulty, bouncers: level.bouncers, trail, paused: false };
const cats = CAT_DEFS.map((d, i) => { const c = new Cat(d, cw, level.catSpots[i]); scene.add(c.rig.root); return c; });
cw.cats = cats;
// tutorial cat starts right in front of the player; the statue stands on the plaza pedestal
cats[0].body.pos.set(2, 3.5, 1); cats[0].home.set(2, 3, 1);
const statueCat = cats.find(c => c.def.special === 'statue')!;
statueCat.body.pos.set(4, 3.6, -3); statueCat.home.set(4, 3, -3);
// three tiny T-rex eggs by the plaza (they hatch when you walk up, or by themselves after a while)
const REX_LOOKS: [string, string, string, string, string][] = [
['#9be39b', '#fff4c9', '#fff4c9', '#8fd3ff', '#ff7fb0'],
['#b9a6ff', '#ffe6f2', '#ffe6f2', '#ffcf3f', '#7cc8ff'],
['#ffb37a', '#fff1d6', '#e6f7ff', '#ff9cc9', '#8fe39b'],
];
const REX_SPOTS = [new THREE.Vector3(6.5, 0, 6), new THREE.Vector3(-6.5, 0, 3.5), new THREE.Vector3(6, 0, 0)];
const rexes = REX_SPOTS.map((sp, i) => { const l = REX_LOOKS[i]; const r = new TinyRex(level.world, sp, l[0], l[1], l[2], l[3], l[4], i); scene.add(r.root, r.toy); return r; });
const golden = cats.find(c => c.def.special === 'golden')!;
const pedestal = new THREE.Mesh(new THREE.CylinderGeometry(0.8, 0.9, 0.6, 16), new THREE.MeshLambertMaterial({ color: '#e6d4ff' }));
pedestal.position.set(4, 3.3, -3); scene.add(pedestal);
level.bouncers.length; // pedestal is decorative
// lighting colours are in sharedLight; a hemisphere light for Lambert materials
scene.add(new THREE.HemisphereLight('#dfe9ff', '#ffc9d9', 1.6));
const sun = new THREE.DirectionalLight('#fff3e0', 1.6); sun.position.set(20, 40, 15); scene.add(sun);
// ---------------- UI ----------------
const ui = document.getElementById('ui')!;
const el = (h: string) => { const d = document.createElement('div'); d.innerHTML = h.trim(); return d.firstElementChild as HTMLElement; };
const hud = el(`<div class="hud" hidden><div class="pill cats" id="catrow"></div><div class="row"><div class="pill">🍬 <span id="candy">0</span></div><button class="iconbtn" id="snd" aria-label="Sound">🔊</button><button class="iconbtn" id="pause" aria-label="Pause">⏸</button></div></div>`);
ui.appendChild(hud);
const catRow = hud.querySelector('#catrow')!;
CAT_DEFS.forEach(d => { const i = document.createElement('i'); i.textContent = '🐱'; i.title = d.name; i.dataset.id = d.id; catRow.appendChild(i); });
const joy = el(`<div id="joy" hidden></div>`); ui.appendChild(joy);
const stick = el(`<div id="stick"><b></b></div>`); ui.appendChild(stick); input.stickEl = stick;
joy.addEventListener('pointerdown', e => canvas.dispatchEvent(new PointerEvent('pointerdown', e)));
const act = el(`<button id="act" aria-label="Jump and catch" hidden>🐾</button>`); ui.appendChild(act); input.bindButton(act);
const hint = el(`<div class="hint" hidden>👆</div>`); ui.appendChild(hint);
const keyHint = el(`<div class="pill keyhint" hidden>⌨️ WASD / arrows to run · Space to jump & catch</div>`); ui.appendChild(keyHint);
const candyEl = hud.querySelector('#candy')!;
const quests = new Quests(ui, [sugarbell, mintly]);
let candyCount = 0;
/** Candy counts for this play session and is banked in the save right away (it buys things in the Cat Home). */
function addCandy(n: number) { candyCount += n; candyEl.textContent = String(candyCount); save.candy += n; persist(save); }
function toast(t: string) { const n = ui.querySelectorAll('.toast').length; const d = el(`<div class="toast">${t}</div>`); if (n) d.style.top = `${22 + n * 9}%`; ui.appendChild(d); setTimeout(() => d.remove(), 1700); }
const title = el(`<div class="screen">
<h1 class="logo">Fluffy Cat<br>Kingdom</h1>
<p class="tag">Catch the fluff. Discover the magic.</p>
<button class="big" id="play" aria-label="Play">▶ Play</button>
<div class="row places"><button class="big alt" id="home" aria-label="Cat Home">🏡</button><button class="big alt" id="mtn" aria-label="Chocolate Mountain slide">🍫</button><button class="big alt" id="seek" aria-label="Hide and seek">🙈</button><button class="big alt" id="hunt" aria-label="Candy hunt">🍭</button></div>
<div class="row" id="diff" role="group" aria-label="Difficulty"></div>
<div class="howto" aria-label="How to play: move, tap the paw to jump, tap the paw next to a cat to catch it, walk to an egg to hatch a T-rex"><span>🕹️<b>🏃</b></span><span>🐾<b>🤸</b></span><span>🐾🐱<b>💖</b></span><span>🥚<b>🦖</b></span></div>
<p class="small">Grown-ups: joystick or WASD to move, one paw button or Space to jump and catch. No sound? Turn the volume up and tap once (works on silent too).</p>
</div>`);
ui.appendChild(title);
const diffRow = title.querySelector('#diff')!;
['🐾', '🐾🐾', '🐾🐾🐾'].forEach((lbl, i) => { const b = document.createElement('button'); b.className = 'big alt'; b.textContent = lbl; b.setAttribute('aria-label', ['Little Explorer', 'Royal Adventurer', 'Master Fluff Catcher'][i]); b.classList.toggle('sel', save.settings.difficulty === i); b.onclick = () => { save.settings.difficulty = i; cw.difficulty = i; persist(save); [...diffRow.children].forEach((c, j) => c.classList.toggle('sel', j === i)); audio.play('click'); }; diffRow.appendChild(b); });
let started = false;
type Mode = 'title' | 'intro' | 'play' | 'pause' | 'victory' | 'home' | 'mountain';
let round = 1;
let mode: Mode = 'title';
let introT = 0, playT = 0, victoryT = 0, idleT = 0;
let camYaw = 0, camPitch = 0.42, camDist = 7.5, manualCamT = 0;
const camPos = new THREE.Vector3(0, 12, 22), camLook = new THREE.Vector3();
let trophy: THREE.Group | null = null;
let caughtCount = 0;
title.querySelector('#play')!.addEventListener('click', () => {
audio.init(); audio.play('click'); audio.startMusic('village');
title.remove(); hud.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; }
if (started) { player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0); newRound(); return; }
started = true;
mode = 'intro'; introT = 0;
// the candy machine goes POP and cats scatter (the opening beat)
audio.play('firework');
fx.emit(new THREE.Vector3(0, 5, 3), 140, { color: CANDY_COLORS, speed: 9, up: 6, size: 0.16, life: 1.6, grav: 6 });
for (const c of cats) if (c.active && c.state === 'wander') { c.body.vel.set((Math.random() - 0.5) * 4, 8, (Math.random() - 0.5) * 4); }
});
const pauseScreen = el(`<div class="screen" hidden><h1 class="logo mid">Paused</h1><div class="row"><button class="big" id="resume">▶</button><button class="big alt" id="ptitle" aria-label="Back to the kingdom">🏰</button><button class="big alt" id="restart" aria-label="Start again">🔁</button></div><p class="small">Grown-ups: progress saves on this device only. No ads, no accounts, no tracking.</p></div>`);
ui.appendChild(pauseScreen);
const setPause = (p: boolean) => { if (mode === 'victory' || mode === 'title' || mode === 'home' || mode === 'mountain') return; mode = p ? 'pause' : 'play'; pauseScreen.hidden = !p; audio.play('click'); };
hud.querySelector('#pause')!.addEventListener('click', () => setPause(true));
let muted = false;
const sndBtn = hud.querySelector('#snd') as HTMLButtonElement;
sndBtn.addEventListener('click', () => {
if (!audio.isRunning()) { audio.kick(); muted = false; } else muted = !muted;
audio.setVolumes(muted ? 0 : 0.7, save.settings.music, save.settings.sfx);
sndBtn.textContent = muted ? '🔇' : '🔊'; audio.play('click');
});
pauseScreen.querySelector('#resume')!.addEventListener('click', () => setPause(false));
pauseScreen.querySelector('#ptitle')!.addEventListener('click', () => {
pauseScreen.hidden = true; seek.on = false; seekCover.hidden = true; endHunt(true); input.enabled = true;
hud.hidden = true; joy.hidden = true; act.hidden = true; quests.hideAll(); mode = 'title'; ui.appendChild(title); audio.play('click'); audio.startMusic('title');
});
pauseScreen.querySelector('#restart')!.addEventListener('click', () => location.reload());
function catchCat(c: Cat) {
const idx = cats.filter(k => k.caught).length;
c.startParade(idx);
caughtCount = idx + 1;
audio.play('catch'); audio.meow(c.def.voice, 'happy');
c.rig.pose = 'spin'; c.rig.flash('happy', 1.5);
player.hugT = 0.35; player.happyT = 1.2;
const p = c.pos.clone().setY(c.pos.y + 0.8);
fx.emit(p.setY(p.y + 0.6), 20, { color: ['#ff7fb0', '#ffd1e6', '#ffffff', '#ffe066'], speed: 3.5, up: 3, size: 0.09 });
addCandy(3);
fx.emit(p, 10, { color: CANDY_COLORS, speed: 3, up: 5, size: 0.12 });
const i = catRow.querySelector(`[data-id="${c.def.id}"]`); if (i) { i.className = 'got'; i.textContent = c.def.emoji; }
toast(`💖 ${catName(c)}!`); quests.notify('catch');
hitStop = 0.07; camPunch = 1;
save.caughtEver = Array.from(new Set([...save.caughtEver, c.def.id])); persist(save);
sugarbell.cheer = 1.5;
if (seek.on) { seek.found++; seek.lastT = seek.t; c.rig.flash('surprised', 0.6); audio.play('giggle'); if (seek.found === seek.cats.length) setTimeout(seekWin, 900); return; }
if (caughtCount === CAT_DEFS.length - 1 && !golden.active) {
// Golden Fluff arrives on a cloud
setTimeout(() => { golden.active = true; golden.rig.root.visible = true; golden.body.pos.set(0, 10, 4); golden.home.set(0, 3, 4); golden.state = 'wander'; audio.play('sparkle'); audio.play('trophy', { volume: 0.5 }); toast('🌟 Golden Fluff!'); fx.emit(new THREE.Vector3(0, 10, 4), 80, { color: ['#ffe066', '#ffffff'], speed: 5, size: 0.15 }); }, 1500);
}
if (caughtCount === CAT_DEFS.length) setTimeout(startVictory, 900);
}
/** Keep playing: friends run off for another game of tag, a bit faster each round. */
function newRound() {
round++; audio.play('click'); audio.startMusic('village');
if (trophy) { scene.remove(trophy); trophy = null; }
cw.difficulty = Math.min(2, save.settings.difficulty + (round - 1) * 0.5);
caughtCount = 0; trail.length = 0; input.enabled = true; mode = 'play'; playT = 0;
sugarbell.cheer = 0; sugarbell.root.position.copy(level.princessSpot);
catRow.querySelectorAll('i').forEach(i => { i.className = ''; i.textContent = '🐱'; (i as HTMLElement).hidden = false; });
seek.on = false; endHunt(true);
for (const c of cats) {
c.caught = false; c.wakes = 0; c.paradeIndex = -1; c.jumpQueue = []; c.fleeT = 0;
c.state = c.def.special === 'sleeper' ? 'sleep' : c.def.special === 'statue' ? 'statue' : 'flee';
if (c.def.special === 'golden') { c.active = false; c.rig.root.visible = false; continue; }
c.active = true; c.rig.root.visible = true;
c.home.copy(level.catSpots[Math.floor(Math.random() * level.catSpots.length)]);
c.body.vel.set((Math.random() - 0.5) * 8, 10, (Math.random() - 0.5) * 8);
}
statueCat.body.pos.set(4, 3.6, -3); statueCat.home.set(4, 3, -3);
for (const cd of candies) { cd.taken = false; cd.mesh.visible = true; cd.mesh.position.copy(cd.pos); }
fx.emit(player.body.pos.clone().setY(player.body.pos.y + 1), 50, { color: CANDY_COLORS, speed: 8, up: 5, size: 0.15 });
audio.play('firework'); toast(`Round ${round}! 🐾`);
}
function startVictory() {
mode = 'victory'; victoryT = 0; input.enabled = false;
audio.startMusic('victory'); audio.play('trophy');
trophy = makeTrophy(); trophy.position.copy(player.body.pos).add(new THREE.Vector3(0, 12, 0)); scene.add(trophy);
sugarbell.root.position.copy(player.body.pos).add(new THREE.Vector3(-1.8, 0, 1)); sugarbell.cheer = 99;
cats.forEach((c, i) => { c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3.2, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3.2); });
const won = { date: new Date().toISOString().slice(0, 10), seconds: Math.round(playT), candy: candyCount, difficulty: save.settings.difficulty };
save.trophies.push(won); persist(save);
setTimeout(() => {
const v = el(`<div class="screen"><div class="trophy">🏆</div><h1 class="logo win">You did it!</h1>
<p class="tag">All ${CAT_DEFS.length} cats are your friends. 🍬 ${candyCount} candies. ⏱ ${Math.floor(playT / 60)}:${String(Math.round(playT % 60)).padStart(2, '0')}</p>
<div class="row"><button class="big" id="again" aria-label="Keep playing">▶ Keep playing</button><button class="big alt" id="gohome" aria-label="Visit the Cat Home">🏡</button><button class="big alt" id="gomtn" aria-label="Chocolate Mountain slide">🍫</button></div><p class="small">Trophies won on this device: ${save.trophies.length} 🏆 The cats want to play again, a little faster each round!</p></div>`);
ui.appendChild(v); v.querySelector('#again')!.addEventListener('click', () => { v.remove(); newRound(); });
v.querySelector('#gohome')!.addEventListener('click', () => { v.remove(); goHome(); });
v.querySelector('#gomtn')!.addEventListener('click', () => { v.remove(); goMountain(); });
}, 6500);
}
// ---------------- Hide and Seek ----------------
// Five cats hide in safe spots around the village. Purrs get louder as she gets closer.
// After 20 s without a find, the helper arrow points the way. Cannot fail, no clock.
const seek = { on: false, t: 0, lastT: 0, found: 0, cats: [] as Cat[], purrT: 0, countT: 0 };
const seekCover = el(`<div class="screen seekcover" hidden><div class="seekeyes">🙈</div><h1 class="logo mid" id="seekn">3</h1></div>`); ui.appendChild(seekCover);
function shuffle<T>(a: T[]): T[] { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }
function seekSpots(): THREE.Vector3[] {
const s: THREE.Vector3[] = [];
const W = level.world;
// a hiding spot needs open ground around it (no wall within a block), so a hider can never end up on a roof
const open = (x: number, z: number, y: number) => { for (const ox of [-1.1, 0, 1.1]) for (const oz of [-1.1, 0, 1.1]) { if (W.solidAt(x + ox, y + 0.5, z + oz) || Math.abs(W.topAt(x + ox, z + oz) - y) > 1.1) return false; } return true; };
const add = (x: number, z: number) => { const y = W.topAt(x, z); if (y > 0 && Math.hypot(x, z - 6) > 9 && open(x, z, y)) s.push(new THREE.Vector3(x, y + 0.3, z)); };
for (const [hx, hz] of [[-14, 10], [14, 12], [-18, -4], [17, -6], [6, 22]]) { add(hx + 4.6, hz + 1); add(hx - 4.6, hz - 1); add(hx, hz + 4.6); }
for (const h of level.hideSpots) { add(h.x + 1.8, h.z + 1.8); add(h.x - 1.8, h.z - 1.2); }
for (const t of level.trees) add(t.pos.x + 0.7, t.pos.z + 0.7);
for (const [x, z] of [[-5, -24], [5, -24], [-5, -19.5], [5, -19.5], [1.5, 20.5]]) add(x, z);
return s;
}
function startSeek() {
audio.init(); audio.play('click'); audio.startMusic('garden');
quests.hideAll(); title.remove(); document.querySelectorAll('.screen.seekend').forEach(e => e.remove());
hud.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; }
started = true; mode = 'play'; input.enabled = false; playT = 0; caughtCount = 0; trail.length = 0;
if (trophy) { scene.remove(trophy); trophy = null; }
player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0);
const pool = shuffle(cats.filter(c => c.def.special !== 'golden')).slice(0, 5);
const spots = shuffle(seekSpots());
for (const c of cats) { c.caught = false; c.paradeIndex = -1; c.jumpQueue = []; c.active = false; c.rig.root.visible = false; }
pool.forEach((c, i) => { const sp = spots[i % spots.length]; c.active = true; c.rig.root.visible = true; c.state = 'seek'; c.body.pos.copy(sp); c.body.vel.set(0, 0, 0); c.home.copy(sp); c.meowT = 4 + i; });
catRow.querySelectorAll('i').forEach(i => { const on = pool.some(c => c.def.id === (i as HTMLElement).dataset.id); (i as HTMLElement).hidden = !on; i.className = ''; i.textContent = '🐱'; });
Object.assign(seek, { on: true, t: 0, lastT: 0, found: 0, cats: pool, purrT: 2, countT: 3 });
seekCover.hidden = false; (seekCover.querySelector('#seekn') as HTMLElement).textContent = '3';
}
function seekUpdate(dt: number) {
if (!seek.on) return;
if (seek.countT > 0) {
const before = Math.ceil(seek.countT); seek.countT -= dt; const now = Math.ceil(seek.countT);
if (now !== before) { audio.play('click'); (seekCover.querySelector('#seekn') as HTMLElement).textContent = now > 0 ? String(now) : '🐾'; }
if (seek.countT <= 0) { seekCover.hidden = true; input.enabled = true; toast('🙈 Ready or not!'); audio.play('whoosh'); }
return;
}
seek.t += dt; seek.purrT -= dt;
// hiders stay put (never climb anything)
for (const c of seek.cats) if (!c.caught && c.state === 'seek' && (Math.abs(c.pos.y - c.home.y) > 0.8 || Math.hypot(c.pos.x - c.home.x, c.pos.z - c.home.z) > 0.6)) { c.body.pos.copy(c.home); c.body.vel.set(0, 0, 0); }
// stuck for a while? the nearest hider gets curious and peeks out close to her
if (seek.t - seek.lastT > 30) {
let pc: Cat | null = null, pd = 1e9; for (const c of seek.cats) if (!c.caught) { const d = c.pos.distanceTo(player.body.pos); if (d < pd) { pd = d; pc = c; } }
const pp = player.body.pos;
if (pc && pd > 5) for (let k = 0; k < 12; k++) {
const a = Math.atan2(-Math.cos(camYaw), -Math.sin(camYaw)) + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * 0.5, x = pp.x + Math.cos(a) * 4.5, z = pp.z + Math.sin(a) * 4.5, y = level.world.topAt(x, z);
if (y > 0 && Math.abs(y - pp.y) < 1.2 && !level.world.solidAt(x, y + 0.5, z)) {
pc.body.pos.set(x, y + 0.3, z); pc.body.vel.set(0, 0, 0); pc.home.copy(pc.body.pos);
fx.emit(tmpV.set(x, y + 1, z), 24, { color: ['#ffe066', '#ffffff', '#ff7fb0'], speed: 3, up: 2, size: 0.12 }); audio.play('giggle'); pc.rig.flash('smug', 1.2);
break;
}
}
seek.lastT = seek.t - 12; // peek again later if she still needs help
}
// hot and cold: the nearest hidden cat purrs louder as she gets closer
let nd = 1e9; for (const c of seek.cats) if (!c.caught) nd = Math.min(nd, c.pos.distanceTo(player.body.pos));
if (seek.purrT <= 0 && nd < 1e8) { seek.purrT = nd < 6 ? 0.9 : 1.8; audio.play('purr', { volume: clamp(1.1 - nd / 18, 0.12, 1) }); }
}
function seekWin() {
mode = 'victory'; input.enabled = false; seek.on = false;
audio.startMusic('victory'); audio.play('trophy');
cats.forEach((c, i) => { if (!c.active) return; c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3); });
for (let k = 0; k < 4; k++) setTimeout(() => { fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 12, 8, (Math.random() - 0.5) * 12)), 50, { color: CANDY_COLORS, speed: 6, size: 0.13, life: 1.3, grav: 2 }); audio.play('firework', { volume: 0.6 }); }, k * 500);
addCandy(10);
setTimeout(() => {
const v = el(`<div class="screen seekend"><div class="trophy">🙈</div><h1 class="logo win">Found you!</h1><p class="tag">🐱 ${seek.cats.length} / ${seek.cats.length} · 🍬 +10</p><div class="row"><button class="big" data-s="again" aria-label="Play hide and seek again">🙈 Again</button><button class="big alt" data-s="title" aria-label="Back to the kingdom">🏰</button></div></div>`);
ui.appendChild(v);
v.addEventListener('click', e => { const a = (e.target as HTMLElement).closest('[data-s]')?.getAttribute('data-s'); if (a === 'again') { v.remove(); startSeek(); } if (a === 'title') { v.remove(); hud.hidden = true; joy.hidden = true; act.hidden = true; mode = 'title'; ui.appendChild(title); audio.startMusic('title'); } });
}, 3000);
}
// ---------------- Candy Hunt ----------------
// Candy rains on the island for a while. She grabs all she can; the cats grab some too (giggling).
// The run always ends with a party and every candy she got goes into her jar.
const HUNT_TIME = 75;
interface Drop { mesh: THREE.Mesh; vel: THREE.Vector3; alive: boolean; landed: boolean; age: number }
const hunt = { on: false, t: 0, got: 0, catsGot: 0, spawnT: 0, catT: 0, drops: [] as Drop[] };
const huntBar = el(`<div class="huntbar" hidden><b></b></div>`); ui.appendChild(huntBar);
const dropGeo = new THREE.OctahedronGeometry(0.3, 0);
for (let i = 0; i < 70; i++) { const m = new THREE.Mesh(dropGeo, softMaterial(CANDY_COLORS[i % CANDY_COLORS.length], 1, 0.25)); m.visible = false; scene.add(m); hunt.drops.push({ mesh: m, vel: new THREE.Vector3(), alive: false, landed: false, age: 0 }); }
function startHunt() {
audio.init(); audio.play('click'); audio.startMusic('garden');
quests.hideAll(); title.remove(); document.querySelectorAll('.screen.seekend').forEach(e => e.remove());
hud.hidden = false; huntBar.hidden = false; if (isTouch) { joy.hidden = false; act.hidden = false; }
started = true; seek.on = false; mode = 'play'; input.enabled = true; playT = 0; caughtCount = 0; trail.length = 0;
if (trophy) { scene.remove(trophy); trophy = null; }
player.body.pos.copy(level.spawn); player.body.vel.set(0, 0, 0);
for (const c of cats) { c.caught = false; c.paradeIndex = -1; c.jumpQueue = []; const g = c.def.special === 'golden'; c.active = !g; c.rig.root.visible = !g; if (!g) { c.state = 'wander'; c.body.pos.copy(c.home).y += 1; } }
catRow.querySelectorAll('i').forEach(i => { (i as HTMLElement).hidden = false; i.className = ''; i.textContent = '🐱'; });
for (const d of hunt.drops) { d.alive = false; d.mesh.visible = false; }
Object.assign(hunt, { on: true, t: 0, got: 0, catsGot: 0, spawnT: 0, catT: 0 });
toast('🍭 Candy rain!'); audio.play('firework');
}
function endHunt(silent = false) {
if (!hunt.on) return;
hunt.on = false; huntBar.hidden = true;
for (const d of hunt.drops) { d.alive = false; d.mesh.visible = false; }
if (silent) return;
mode = 'victory'; input.enabled = false;
audio.startMusic('victory'); audio.play('trophy');
cats.forEach((c, i) => { if (!c.active) return; c.state = 'dance'; const a = i / cats.length * Math.PI * 2; c.body.pos.set(player.body.pos.x + Math.cos(a) * 3.2, player.body.pos.y + 0.5, player.body.pos.z + Math.sin(a) * 3.2); });
for (let k = 0; k < 4; k++) setTimeout(() => { fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 12, 8, (Math.random() - 0.5) * 12)), 50, { color: CANDY_COLORS, speed: 6, size: 0.13, life: 1.3, grav: 2 }); audio.play('firework', { volume: 0.6 }); }, k * 500);
setTimeout(() => {
const v = el(`<div class="screen seekend"><div class="trophy">🍭</div><h1 class="logo win">Candy party!</h1><p class="tag">🍬 ${hunt.got}</p><div class="row"><button class="big" data-s="again" aria-label="Candy hunt again">🍭 Again</button><button class="big alt" data-s="title" aria-label="Back to the kingdom">🏰</button></div></div>`);
ui.appendChild(v);
v.addEventListener('click', e => { const a = (e.target as HTMLElement).closest('[data-s]')?.getAttribute('data-s'); if (a === 'again') { v.remove(); startHunt(); } if (a === 'title') { v.remove(); hud.hidden = true; joy.hidden = true; act.hidden = true; mode = 'title'; ui.appendChild(title); audio.startMusic('title'); } });
}, 3000);
}
function huntUpdate(dt: number) {
if (!hunt.on) return;
hunt.t += dt; hunt.spawnT -= dt; hunt.catT -= dt;
(huntBar.firstElementChild as HTMLElement).style.width = `${Math.max(0, 100 - hunt.t / HUNT_TIME * 100).toFixed(1)}%`;
const pp = player.body.pos;
// more candy falls near her, some further away so she explores
if (hunt.spawnT <= 0 && hunt.t < HUNT_TIME - 2) {
hunt.spawnT = 0.28;
const d = hunt.drops.find(k => !k.alive);
if (d) {
let x = 0, z = 0;
for (let tries = 0; tries < 8; tries++) { const nearHer = Math.random() < 0.55; const a = Math.random() * Math.PI * 2, r = nearHer ? 2 + Math.random() * 7 : Math.random() * 24; x = (nearHer ? pp.x : 0) + Math.cos(a) * r; z = (nearHer ? pp.z : 0) + Math.sin(a) * r; if (level.world.topAt(x, z) > 0 && Math.hypot(x, z) < 26) break; }
d.alive = true; d.landed = false; d.age = 0; d.mesh.visible = true; d.mesh.position.set(x, level.world.topAt(x, z) + 14, z); d.vel.set(0, -4, 0);
}
}
for (const d of hunt.drops) {
if (!d.alive) continue;
d.age += dt; const m = d.mesh;
if (!d.landed) { d.vel.y -= 14 * dt; m.position.addScaledVector(d.vel, dt); const g = level.world.topAt(m.position.x, m.position.z) + 0.35; if (m.position.y <= g) { m.position.y = g; d.landed = true; } }
else m.position.y += Math.sin(t * 5 + m.position.x) * 0.004;
m.rotation.y += dt * 3;
if (Math.hypot(m.position.x - pp.x, m.position.z - pp.z) < 1.3 && Math.abs(m.position.y - pp.y - 0.6) < 1.8) {
d.alive = false; m.visible = false; hunt.got++; addCandy(1); quests.notify('candy');
candyStreak = candyStreakT > 0 ? Math.min(candyStreak + 1, 10) : 0; candyStreakT = 1;
audio.play('candy', { pitch: 1 + candyStreak * 0.07 }); fx.emit(m.position, 6, { color: CANDY_COLORS, speed: 2, size: 0.07 });
continue;
}
if (d.age > 22) { d.alive = false; m.visible = false; }
}
// cats run for candy too
if (hunt.catT <= 0) {
hunt.catT = 0.8;
for (const c of cats) {
if (!c.active || c.state !== 'wander' && c.state !== 'idle') continue;
let best: Drop | null = null, bd = 9;
for (const d of hunt.drops) if (d.alive && d.landed) { const q = d.mesh.position.distanceTo(c.pos); if (q < bd) { bd = q; best = d; } }
if (best) { c.target.set(best.mesh.position.x, 0, best.mesh.position.z); c.state = 'wander'; c.timer = 2; }
}
}
for (const c of cats) {
if (!c.active) continue;
for (const d of hunt.drops) if (d.alive && d.landed && d.mesh.position.distanceTo(c.pos) < 0.9) { d.alive = false; d.mesh.visible = false; hunt.catsGot++; c.rig.flash('happy', 1); if (c.pos.distanceTo(pp) < 12) audio.play('giggle', { volume: 0.35 }); fx.emit(d.mesh.position, 5, { color: CANDY_COLORS, speed: 1.5, size: 0.06 }); }
}
if (hunt.t >= HUNT_TIME) endHunt();
}
// ---------------- Royal Cat Sanctuary ----------------
const home = new Sanctuary(save, ui, el, toast);
function goHome() {
audio.init(); audio.play('click');
quests.hideAll(); title.remove(); pauseScreen.hidden = true; hud.hidden = true; hint.hidden = true; keyHint.hidden = true; arrow.visible = false;
if (isTouch) { joy.hidden = false; act.hidden = false; }
input.enabled = true; mode = 'home'; home.enter();
}
home.onExit = () => {
applyOutfit(player, save.outfit);
mode = 'title'; hud.hidden = true; joy.hidden = true; act.hidden = true;
ui.appendChild(title); audio.startMusic('title');
};
title.querySelector('#home')!.addEventListener('click', goHome);
title.querySelector('#seek')!.addEventListener('click', startSeek);
title.querySelector('#hunt')!.addEventListener('click', startHunt);
// ---------------- Chocolate Mountain ----------------
const mountain = new Mountain(save, ui, el, toast);
function goMountain() {
audio.init(); audio.play('click');
quests.hideAll(); title.remove(); pauseScreen.hidden = true; hud.hidden = true; hint.hidden = true; keyHint.hidden = true; arrow.visible = false;
if (isTouch) { joy.hidden = false; act.hidden = false; }
input.enabled = true; mode = 'mountain'; mountain.enter();
}
mountain.onExit = () => { mode = 'title'; hud.hidden = true; joy.hidden = true; act.hidden = true; ui.appendChild(title); audio.startMusic('title'); };
title.querySelector('#mtn')!.addEventListener('click', goMountain);
// Trees never block the view: hide any candy tree between the camera and the player (or right next to the camera).
const treeM = new THREE.Matrix4(), zeroM = new THREE.Matrix4().makeScale(0, 0, 0);
function hideTrees() {
const ax = camera.position.x, az = camera.position.z, bx = camLook.x, bz = camLook.z;
const vx = bx - ax, vz = bz - az, vl = vx * vx + vz * vz || 1;
let dirty = false;
for (const tr of level.trees) {
const px = tr.pos.x - ax, pz = tr.pos.z - az;
const u = Math.max(0, Math.min(1, (px * vx + pz * vz) / vl));
const d = Math.hypot(px - vx * u, pz - vz * u);
const hide = mode !== 'title' && (d < 2.4 && u < 0.98 || Math.hypot(px, pz) < 2.6);
if (hide !== tr.hidden) {
tr.hidden = hide; tr.crown.visible = !hide; dirty = true;
level.trunks.setMatrixAt(tr.idx, hide ? zeroM : treeM.makeTranslation(tr.pos.x, tr.pos.y + 1.2, tr.pos.z));
}
}
if (dirty) level.trunks.instanceMatrix.needsUpdate = true;
for (const cup of level.cups) { const px = cup.position.x - ax, pz = cup.position.z - az, u = (px * vx + pz * vz) / vl; cup.visible = !(mode !== 'title' && ((u > -0.1 && u < 0.95 && Math.hypot(px - vx * u, pz - vz * u) < 2.6) || Math.hypot(px, pz) < 3)); }
}
// --------------- loop ----------------
const clock = new THREE.Clock();
let t = 0, frameAvg = 16, adaptT = 0, audioT = 0;
const tmpV = new THREE.Vector3(), tmpV2 = new THREE.Vector3();
function frame() {
requestAnimationFrame(frame);
const realDt = Math.min(clock.getDelta(), 0.5);
let dt = Math.min(realDt, 1 / 20);
if (hitStop > 0) { hitStop -= dt; dt *= 0.08; }
t += dt; sharedLight.uTime.value = t;
const inp = input.update();
if (inp.pausePressed) setPause(mode !== 'pause');
if (mode === 'mountain') {
mountain.update(dt, inp, camera); renderer.render(mountain.scene, camera);
audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); }
(window as unknown as { __fck: unknown }).__fck = { mode, candy: save.candy, fps: Math.round(1000 / frameAvg), mountain: mountain.debug() };
frameAvg = lerp(frameAvg, realDt * 1000, 0.05);
return;
}
if (mode === 'home') {
home.update(dt, inp, camera); renderer.render(home.scene, camera);
audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); }
(window as unknown as { __fck: unknown }).__fck = { mode, candy: save.candy, homeCats: home.cats.map(c => ({ id: c.def.id, state: c.state, x: c.pos.x, y: c.pos.y, z: c.pos.z })), player: home.player.body.pos };
return;
}
if (mode === 'pause') { (window as unknown as { __fck: { mode: string } }).__fck.mode = 'pause'; renderer.render(scene, camera); return; }
if (mode === 'intro') { introT += dt; if (introT > 0.6) { mode = 'play'; } }
const playing = mode === 'play';
if (playing) playT += dt;
const inp2 = input.p2;
if (!inp2 && p2On) setP2(false);
if (inp2 && !p2On && (playing || mode === 'intro') && inp2.actionPressed) setP2(true);
const two = p2On && !!inp2;
// catch check: nearest catchable cat in generous range
const range = 3.6 - cw.difficulty * 0.5;
let near: Cat | null = null, nd = 1e9;
for (const c of cats) {
if (!c.catchable || hunt.on) continue;
const d = Math.hypot(c.pos.x - player.body.pos.x, c.pos.z - player.body.pos.z);
const dy = Math.abs(c.pos.y - player.body.pos.y);
if (d < range && dy < (seek.on ? 4 : 2.4) && d < nd) { nd = d; near = c; }
}
act.classList.toggle('catch', !!near);
ring.visible = !!near && playing;
if (near) { ring.position.set(near.pos.x, near.pos.y + 0.08, near.pos.z); ring.rotation.z = t * 2; ring.scale.setScalar(near.rig.scale * (1 + Math.sin(t * 10) * 0.08)); }
// touch-catch: run into a resting cat to make friends, no button needed
if (playing && near && near.resting && nd < 1.3 && cw.difficulty < 1.5) { catchCat(near); near = null; }
let allowJump = true;
if (playing && near && inp.actionPressed) {
allowJump = false;
player.pounceT = 0.12; player.pounceDir.set(near.pos.x - player.body.pos.x, 0, near.pos.z - player.body.pos.z).normalize();
audio.play('pounce');
catchCat(near);
}
const speed = player.update(dt, playing ? inp : { ...inp, moveX: 0, moveY: 0, action: false, actionPressed: false }, camYaw, level.bouncers, allowJump && playing);
if (two && inp2) {
let near2: Cat | null = null, nd2 = 1e9;
for (const c of cats) {
if (!c.catchable || hunt.on) continue;
const d = Math.hypot(c.pos.x - player2.body.pos.x, c.pos.z - player2.body.pos.z);
if (d < range && Math.abs(c.pos.y - player2.body.pos.y) < (seek.on ? 4 : 2.4) && d < nd2) { nd2 = d; near2 = c; }
}
if (playing && near2 && near2.resting && nd2 < 1.3 && cw.difficulty < 1.5) { catchCat(near2); near2 = null; }
let allowJump2 = true;
if (playing && near2 && inp2.actionPressed) {
allowJump2 = false;
player2.pounceT = 0.12; player2.pounceDir.set(near2.pos.x - player2.body.pos.x, 0, near2.pos.z - player2.body.pos.z).normalize();
audio.play('pounce'); catchCat(near2); player2.happyT = 1.2;
}
player2.update(dt, playing ? inp2 : { ...inp2, moveX: 0, moveY: 0, action: false, actionPressed: false }, camYaw, level.bouncers, allowJump2 && playing);
if (player2.justJumped) audio.play('jump', { volume: 0.7 });
if (player2.body.bounced) audio.play('boing');
// fell off, or too far from player 1: pop back beside them
if (player2.body.pos.y < -6 || player2.body.pos.distanceTo(player.body.pos) > 22) { placeP2(); fx.emit(player2.body.pos.clone().setY(player2.body.pos.y + 0.6), 20, { color: ['#7cc8ff', '#ffffff'], speed: 2, up: 1, size: 0.12 }); }
}
cw.playerSpeed = speed;
if (player.justJumped) { audio.play('jump'); cats.filter(c => c.state === 'parade').forEach(c => c.jumpQueue.push(0.1 + c.paradeIndex * 0.12)); }
if (player.justLanded) { audio.play('land', { volume: 0.5 }); fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y + 0.1), 8, { color: '#ffffff', speed: 2, up: 0.5, size: 0.1, grav: 1 }); }
if (player.body.bounced) { audio.play('boing'); quests.notify('bounce'); }
if (player.justJumped && playing) quests.notify('jump');
// fell off the island: a fluffy white cloud catches her and boings her home
if (player.body.pos.y < -6) { player.body.pos.copy(player.body.lastSafe).y += 5; player.body.vel.set(0, 9, 0); audio.play('boing'); audio.play('giggle', { volume: 0.5 }); fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y - 0.5), 40, { color: ['#ffffff', '#f3ecff'], speed: 3, up: 1, size: 0.2, life: 1.2, grav: 1 }); toast('☁️ Wheee!'); }
// trail for the parade
const last = trail[0];
if (!last || last.distanceTo(player.body.pos) > 0.25) { trail.unshift(player.body.pos.clone()); if (trail.length > 80) trail.pop(); }
// idle hints for small hands
idleT = inp.moved || !playing ? 0 : idleT + dt;
candyStreakT -= dt; camPunch = Math.max(0, camPunch - dt * 3);
// stand still for a while and a friend sneaks up to boop your nose
if (idleT === 0) boopT = 0;
if (idleT > 8 && boopT === 0) { boopT = 1; const f = cats.find(c => c.caught); if (f) { f.rig.flash('happy', 1.5); audio.meow(f.def.voice, 'happy'); audio.play('pop', { volume: 0.4 }); player.happyT = 1.2; fx.emit(tmpV.copy(player.body.pos).setY(player.body.pos.y + 1.3), 8, { color: ['#ff7fb0', '#ff4d88'], speed: 0.8, up: 1.4, grav: 0, life: 1.4, size: 0.13 }); toast(`👃 Boop! ${catName(f)}`); } }
hint.hidden = !(playing && isTouch && playT < 8 && !inp.moved);
keyHint.hidden = !(playing && !isTouch && playT < 12);
for (const c of cats) c.update(dt);
seekUpdate(dt);
huntUpdate(dt);
// tiny T-rexes: hatch, follow a cat, then play with their toys
for (const r of rexes) { const ev = r.update(dt, player.body.pos, cats, playing, player.justJumped && playing); if (ev === 'hatch') { quests.notify('hatch'); audio.play('eggCrack'); audio.play('sparkle'); fx.emit(tmpV.copy(r.body.pos).setY(r.body.pos.y + 0.5), 40, { color: ['#fff4c9', '#c9f2b0', '#ffd1e6', '#ffffff'], speed: 3, up: 3, size: 0.1 }); toast('🦖 A tiny T-rex hatched!'); } else if (ev === 'rawr') audio.play('rawr', { volume: 0.7 }); else if (ev === 'sneeze') { audio.play('sneeze', { volume: 0.4, pitch: 1.8 }); fx.emit(tmpV.copy(r.body.pos).setY(r.body.pos.y + 0.8), 24, { color: ['#ff7a9c', '#ffb36b', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 2.5, up: 1, size: 0.09, life: 1 }); } else if (ev === 'ballhit' && r.lastHit) { const c = r.lastHit as Cat; if (!c.caught) { c.body.vel.y = 8; c.rig.flash('surprised', 0.8); } audio.play('boing', { volume: 0.5, pitch: 1.3 }); audio.play('giggle', { volume: 0.4 }); } else if (ev === 'wobble') audio.play('eggWobble', { volume: 0.6 }); }
for (const c of cats) {
const on = c === near;
c.highlight = lerp(c.highlight, on ? 1 : 0, damp(10, dt));
c.rig.root.scale.setScalar(c.rig.scale * (1 + c.highlight * 0.08 * (1 + Math.sin(t * 12))));
}
// candies
for (const cd of candies) {
if (cd.taken) continue;
cd.mesh.rotation.y += dt * 2; cd.mesh.position.y = cd.pos.y + Math.sin(t * 2.5 + cd.pos.x) * 0.15;
const d = cd.mesh.position.distanceTo(tmpV.copy(player.body.pos).setY(player.body.pos.y + 0.7));
if (d < 2.2) cd.mesh.position.lerp(tmpV, damp(8, dt));
const d2 = two ? cd.mesh.position.distanceTo(tmpV2.copy(player2.body.pos).setY(player2.body.pos.y + 0.7)) : 1e9;
if (d2 < 2.2 && d >= 2.2) cd.mesh.position.lerp(tmpV2, damp(8, dt));
if (d < 0.9 || d2 < 0.9) {
cd.taken = true; cd.mesh.visible = false; addCandy(1); quests.notify('candy');
candyStreak = candyStreakT > 0 ? Math.min(candyStreak + 1, 10) : 0; candyStreakT = 1;
audio.play('candy', { pitch: 1 + candyStreak * 0.07 }); fx.emit(cd.mesh.position, 10, { color: CANDY_COLORS, speed: 2, size: 0.08 });
}
}
// princess picture wishes
{
const pp = player.body.pos;
const res = quests.update(dt, camera, pp, {
friends: cats.filter(c => c.caught && c.pos.distanceTo(pp) < 7).length,
nearCupcake: level.hideSpots.some(h => Math.hypot(h.x - pp.x, h.z - pp.z) < 3.2),
nearRex: rexes.some(r => r.state !== 'egg' && r.state !== 'crack' && r.body.pos.distanceTo(pp) < 3),
}, playing && !seek.on && !hunt.on);
if (res) {
res.who.cheer = 2.5; addCandy(res.reward); audio.play('unlock'); audio.play('candy', { pitch: 1.5 });
fx.emit(tmpV.copy(res.who.root.position).setY(res.who.root.position.y + 2.2), 50, { color: CANDY_COLORS, speed: 4, up: 3, size: 0.12 });
toast(`${res.gift} +${res.reward} 🍬`); player.happyT = 1.5;
}
}
sugarbell.update(dt, player.body.pos);
mintly.update(dt, player.body.pos);
if (!mintlyGift && playing && player.body.pos.distanceTo(mintly.root.position) < 2.8) {
mintlyGift = true; mintly.cheer = 3;
const crown = new THREE.Group();
const band = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.05, 6, 20), new THREE.MeshLambertMaterial({ color: '#ffd34d', emissive: '#ffb300', emissiveIntensity: 0.4 }));
band.rotation.x = Math.PI / 2; crown.add(band);
['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'].forEach((c, i) => { const g = new THREE.Mesh(new THREE.OctahedronGeometry(0.07), new THREE.MeshLambertMaterial({ color: c, emissive: c, emissiveIntensity: 0.5 })); const a = i / 5 * Math.PI * 2; g.position.set(Math.cos(a) * 0.2, 0.08, Math.sin(a) * 0.2); crown.add(g); });
player.crownSlot.add(crown); player.happyT = 1.5;
addCandy(10);
audio.play('trophy', { volume: 0.6 }); toast('👑 A rainbow crown!');
fx.emit(player.body.pos.clone().setY(player.body.pos.y + 1.8), 60, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 4, size: 0.12 });
}
// arrow to the nearest free cat
let best: Cat | null = null, bd = 1e9;
for (const c of cats) { if (!c.catchable || hunt.on) continue; const d = c.pos.distanceTo(player.body.pos); if (d < bd) { bd = d; best = c; } }
arrow.visible = playing && !!best && (seek.on ? seek.t - seek.lastT > 20 : bd > 11);
if (best && arrow.visible) {
arrow.position.set(player.body.pos.x, player.body.pos.y + 2.4 + Math.sin(t * 4) * 0.1, player.body.pos.z);
arrow.lookAt(best.pos.x, player.body.pos.y + 2.4, best.pos.z);
}
// stand still with your friends for a cuddle: purrs and hearts
const friends = cats.filter(c => c.caught && c.pos.distanceTo(player.body.pos) < 2.4);
cuddleT = speed < 0.4 && friends.length && playing ? cuddleT + dt : 0;
if (cuddleT > 1.6) { cuddleT = -2.5; const f = friends[Math.floor(Math.random() * friends.length)]; audio.play('purr', { volume: 0.6 }); f.rig.flash('happy', 1.5); fx.emit(f.pos.clone().setY(f.pos.y + 1), 6, { color: ['#ff7fb0', '#ff4d88'], speed: 0.8, up: 1.4, grav: 0, life: 1.4, size: 0.13 }); }
for (const a of level.animated) a(t, dt);
fx.update(dt);
// victory choreography
if (mode === 'victory' && trophy) {
victoryT += dt;
const tgt = tmpV.copy(player.body.pos).add(new THREE.Vector3(0, 2.6, 0));
trophy.position.lerp(tgt, damp(1.5, dt)); trophy.rotation.y += dt * 1.5;
trophy.scale.setScalar(1 + Math.sin(t * 3) * 0.05);
if (Math.random() < dt * 2) { const p = player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 18, 8 + Math.random() * 6, (Math.random() - 0.5) * 18)); fx.emit(p, 45, { color: CANDY_COLORS, speed: 7, up: 0, size: 0.14, life: 1.4, grav: 2 }); audio.play('firework', { volume: 0.6 }); }
if (Math.random() < dt * 8) fx.emit(player.body.pos.clone().add(new THREE.Vector3((Math.random() - 0.5) * 10, 8, (Math.random() - 0.5) * 10)), 2, { color: CANDY_COLORS, speed: 0.5, up: -1, grav: 1, life: 3, size: 0.1 });
player.happyT = 1;
}
// camera: follows behind the player, drag to orbit, auto-recentre after a pause
if (Math.abs(inp.camX) + Math.abs(inp.camY) > 0) { manualCamT = 2; camYaw -= inp.camX * 0.006; camPitch = clamp(camPitch + inp.camY * 0.004, 0.12, 1.1); }
manualCamT -= dt;
if (manualCamT <= 0 && speed > 1 && playing) camYaw += angleDiff(camYaw, player.yaw + Math.PI) * damp(1.2, dt) * clamp(Math.abs(inp.moveX) + 0.25, 0, 1);
if (mode === 'title') { camYaw += dt * 0.12; }
let dist = mode === 'title' ? 16 : mode === 'victory' ? 9 : camDist - camPunch * 1.4;
const pitch = mode === 'title' ? 0.45 : camPitch;
const spread = two && mode !== 'title' ? Math.hypot(player.body.pos.x - player2.body.pos.x, player.body.pos.z - player2.body.pos.z) : 0;
const focus = mode === 'title' ? new THREE.Vector3(0, 3, 2) : two ? player.body.pos.clone().lerp(player2.body.pos, 0.5) : player.body.pos;
if (spread) dist += Math.min(10, spread * 0.55);
const want = new THREE.Vector3(focus.x + Math.sin(camYaw) * Math.cos(pitch) * dist, focus.y + 1.2 + Math.sin(pitch) * dist, focus.z + Math.cos(camYaw) * Math.cos(pitch) * dist);
// keep the camera out of hills and walls: slide it in towards the player until the view is clear
if (mode !== 'title') {
const fx0 = focus.x, fy0 = focus.y + 1.2, fz0 = focus.z;
const clearK = (w: THREE.Vector3) => { let k = 1; for (const oy of [-0.6, 0]) for (let i = 1; i <= 16; i++) { const f = i / 16; if (level.world.solidAt(fx0 + (w.x - fx0) * f, fy0 + oy + (w.y - fy0) * f, fz0 + (w.z - fz0) * f)) { k = Math.min(k, (i - 1.5) / 16); break; } } return k; };
let k = clearK(want);
// first try looking down from higher up (keeps her full size on screen), then move in as a last resort
for (const pp of [pitch + 0.35, pitch + 0.7, 1.15]) { if (k >= 1) break; const w2 = tmpV.set(focus.x + Math.sin(camYaw) * Math.cos(pp) * dist, focus.y + 1.2 + Math.sin(pp) * dist, focus.z + Math.cos(camYaw) * Math.cos(pp) * dist); const k2 = clearK(w2); if (k2 > k) { want.copy(w2); k = k2; } }
k = Math.max(0.5, k);
if (k < 1) want.set(fx0 + (want.x - fx0) * k, fy0 + (want.y - fy0) * k, fz0 + (want.z - fz0) * k);
}
const ground = level.world.topAt(want.x, want.z); if (want.y < ground + 1.2) want.y = ground + 1.2;
camPos.lerp(want, damp(mode === 'victory' ? 2 : 8, dt));
camLook.lerp(tmpV.copy(focus).setY(focus.y + 1), damp(12, dt));
camera.position.copy(camPos); camera.lookAt(camLook);
if (mode === 'victory') camYaw += dt * 0.4;
hideTrees();
// friends that wander between the camera and the player step out of the picture
{ const ax = camera.position.x, az = camera.position.z, vx = player.body.pos.x - ax, vz = player.body.pos.z - az, vl = vx * vx + vz * vz || 1;
for (const c of cats) { if (!c.caught) continue; const px = c.pos.x - ax, pz = c.pos.z - az, u = (px * vx + pz * vz) / vl; c.rig.root.visible = !(mode === 'play' && ((u > -0.2 && u < 0.85 && Math.hypot(px - vx * u, pz - vz * u) < 1.6) || c.pos.distanceTo(camera.position) < 3)); }
for (const r of rexes) { const px = r.body.pos.x - ax, pz = r.body.pos.z - az, u = (px * vx + pz * vz) / vl; r.root.visible = !(mode === 'play' && r.state !== 'egg' && ((u > -0.2 && u < 0.85 && Math.hypot(px - vx * u, pz - vz * u) < 1.4) || r.body.pos.distanceTo(camera.position) < 2.6)); } }
renderer.render(scene, camera);
// adaptive resolution keeps mobile smooth
frameAvg = lerp(frameAvg, realDt * 1000, 0.05); adaptT += dt;
audioT += dt; if (audioT > 1) { audioT = 0; audio.watchdog(); }
if (adaptT > 2) { adaptT = 0; const old = pixelRatio;
if (frameAvg > 24 && pixelRatio > 0.8) pixelRatio = Math.max(0.8, pixelRatio - 0.2);
else if (frameAvg < 15 && pixelRatio < Math.min(devicePixelRatio, 2)) pixelRatio = Math.min(Math.min(devicePixelRatio, 2), pixelRatio + 0.1);
if (old !== pixelRatio) { renderer.setPixelRatio(pixelRatio); resize(); } }
(window as unknown as { __fck: unknown }).__fck = { mode, caught: caughtCount, candy: candyCount, fps: Math.round(1000 / frameAvg), pr: pixelRatio, player: player.body.pos, p2: p2On ? player2.body.pos : null, cats: cats.map(c => ({ id: c.id, state: c.state, x: c.pos.x, y: c.pos.y, z: c.pos.z, caught: c.caught, active: c.active })) };
}
frame();
// Test hook for automated QA: move the player next to a cat (no effect on normal play).
(window as unknown as { __fckTest: unknown }).__fckTest = {
rexes() { return rexes.map(r => ({ state: r.state, x: r.body.pos.x, y: r.body.pos.y, z: r.body.pos.z })); },
trees() { return { total: level.trees.length, hidden: level.trees.filter(k => k.hidden).length }; },
home() { goHome(); return save.caughtEver.length; },
homeNear() { const c = home.cats[0]; if (!c) return null; home.player.body.pos.set(c.pos.x + 1, c.pos.y + 0.3, c.pos.z); return c.def.id; },
give(n: number) { save.candy += n; persist(save); return save.candy; },
wish(e: 'candy' | 'bounce' | 'jump' | 'catch', n: number) { for (let i = 0; i < n; i++) quests.notify(e); return true; },
toPrincess(k: number) { const r = (k ? mintly : sugarbell).root.position; player.body.pos.set(r.x + 1.5, r.y + 0.5, r.z + 1.5); player.body.vel.set(0, 0, 0); return true; },
slide(ds: number) { return mountain.skip(ds); },
seek() { startSeek(); return seek.cats.map(c => c.def.id); },
seekSpots() { return seekSpots().length; },
seekStuck() { seek.lastT = seek.t - 31; },
seekCats() { return seek.cats.map(c => ({ id: c.def.id, caught: c.caught, x: +c.pos.x.toFixed(1), y: +c.pos.y.toFixed(1), z: +c.pos.z.toFixed(1), home: +c.home.y.toFixed(1), d: +c.pos.distanceTo(player.body.pos).toFixed(1) })); },
seekNext() { const c = seek.cats.find(k => !k.caught); if (!c) return null; player.body.pos.set(c.pos.x + 1, c.pos.y + 0.2, c.pos.z); player.body.vel.set(0, 0, 0); return c.id; },
hunt() { startHunt(); return true; },
huntState() { return { on: hunt.on, t: Math.round(hunt.t), got: hunt.got, cats: hunt.catsGot, drops: hunt.drops.filter(d => d.alive).length }; },
huntSkip(t: number) { hunt.t += t; return hunt.t; },
hatch() { rexes.forEach(r => r.hatchNow()); return rexes.length; },
nextCat() { const c = cats.find(k => k.catchable); if (!c) return null; player.body.pos.set(c.pos.x + 1, c.pos.y + 0.2, c.pos.z); player.body.vel.set(0, 0, 0); return c.id; },
};
style.css116 lines
:root{ --bg:#ffd9ec; --ink:#5b2a58; --pink:#ff7fb0; --gold:#ffcf3f; --cream:#fff6ea; --glass:rgba(255,255,255,.78); color-scheme:light; --font:ui-rounded,'SF Pro Rounded','Arial Rounded MT Bold','Varela Round','Trebuchet MS',system-ui,sans-serif }
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink);font-family:var(--font);touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
[hidden]{display:none!important}
canvas#game{position:fixed;inset:0;width:100%;height:100%;display:block}
#ui{position:fixed;inset:0;pointer-events:none}
#ui *{pointer-events:auto}
.hud{position:absolute;top:calc(env(safe-area-inset-top,0px) + 10px);left:max(12px,env(safe-area-inset-left,0px));right:max(12px,env(safe-area-inset-right,0px));display:flex;gap:10px;align-items:center;justify-content:space-between;pointer-events:none}
.pill{background:var(--glass);border-radius:999px;padding:4px 14px;font-weight:800;font-size:22px;display:flex;align-items:center;gap:6px;box-shadow:0 3px 0 rgba(91,42,88,.15);pointer-events:none}
.cats{display:flex;gap:3px;flex-wrap:wrap}
.cats i{width:22px;height:22px;border-radius:50%;background:#e4d6ea;display:inline-block;font-style:normal;font-size:15px;line-height:22px;text-align:center;filter:grayscale(1);opacity:.55}
.cats i.got{background:#ffb347;filter:none;opacity:1;animation:pop .5s}
@keyframes pop{0%{transform:scale(.2)}60%{transform:scale(1.5)}100%{transform:scale(1)}}
.iconbtn{width:52px;height:52px;border-radius:50%;border:0;background:var(--glass);font-size:26px;box-shadow:0 3px 0 rgba(91,42,88,.2);cursor:pointer;color:var(--ink)}
.iconbtn:focus-visible,.big:focus-visible{outline:4px solid var(--pink)}
#joy{position:absolute;left:0;bottom:0;width:50%;height:65%}
#stick{position:absolute;width:130px;height:130px;border-radius:50%;background:rgba(255,255,255,.35);border:4px solid rgba(255,255,255,.8);transform:translate(-50%,-50%);display:none;pointer-events:none}
#stick b{position:absolute;left:50%;top:50%;width:58px;height:58px;margin:-29px;border-radius:50%;background:#fff;box-shadow:0 3px 0 rgba(91,42,88,.25)}
#act{position:absolute;right:max(22px,calc(env(safe-area-inset-right,0px) + 14px));bottom:calc(env(safe-area-inset-bottom,0px) + 22px);width:118px;height:118px;border-radius:50%;border:0;background:radial-gradient(circle at 40% 35%,#fff 0 18%,var(--pink) 60%);font-size:54px;box-shadow:0 6px 0 #c94f84;color:#fff;touch-action:none}
#act.catch{background:radial-gradient(circle at 40% 35%,#fff 0 18%,var(--gold) 60%);box-shadow:0 6px 0 #c99a17;animation:throb .6s infinite alternate}
#act:active{transform:translateY(4px);box-shadow:0 2px 0 #c94f84}
@keyframes throb{to{transform:scale(1.1)}}
.screen{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;background:radial-gradient(circle,rgba(255,240,250,.35),rgba(255,190,225,.6));padding-inline:max(16px,env(safe-area-inset-left,0px)) max(16px,env(safe-area-inset-right,0px));text-align:center}
.logo{font-size:clamp(40px,9vw,92px);line-height:.9;font-weight:800;color:#fff;text-shadow:0 5px 0 var(--pink),0 10px 0 #c94f84,0 14px 18px rgba(91,42,88,.4);margin:0;text-wrap:balance}
.tag{font-size:clamp(16px,3vw,24px);font-weight:600;margin:0;color:var(--ink)}
.big{border:0;border-radius:999px;background:var(--gold);color:var(--ink);font:800 34px var(--font);padding:10px 44px;box-shadow:0 7px 0 #c99a17;cursor:pointer}
.big:active{transform:translateY(5px);box-shadow:0 2px 0 #c99a17}
.big.alt{background:#fff;box-shadow:0 7px 0 #d9b8d6;font-size:26px}
.row{display:flex;gap:14px;flex-wrap:wrap;justify-content:center}
.trophy{font-size:120px;animation:spin 2.4s ease-in-out infinite;filter:drop-shadow(0 8px 10px rgba(201,154,23,.6))}
@keyframes spin{50%{transform:rotateY(180deg) scale(1.1)}}
.small{font-size:14px;max-width:34ch;opacity:.85}
.hint{position:absolute;left:50%;bottom:22%;transform:translateX(-50%);font-size:56px;animation:bob 1s infinite alternate;pointer-events:none}
@keyframes bob{to{transform:translate(-50%,-14px)}}
.toast{position:absolute;left:50%;top:22%;transform:translateX(-50%);font-size:38px;font-weight:800;color:#fff;text-shadow:0 3px 0 var(--pink),0 6px 8px rgba(91,42,88,.4);pointer-events:none;white-space:nowrap;animation:rise 1.6s forwards}
@keyframes rise{0%{opacity:0;transform:translate(-50%,20px) scale(.6)}15%{opacity:1;transform:translate(-50%,0) scale(1.1)}80%{opacity:1}100%{opacity:0;transform:translate(-50%,-30px)}}
@media (prefers-reduced-motion: reduce){*{animation:none!important}}
.hud .row{pointer-events:auto}
.keyhint{position:absolute;left:50%;bottom:calc(env(safe-area-inset-bottom,0px) + 18px);transform:translateX(-50%);font-size:18px;white-space:nowrap}
.logo.mid{font-size:56px}
.logo.win{font-size:clamp(40px,8vw,72px)}
@media (max-width:520px){.keyhint{font-size:14px}}
@media (max-width:420px){.cats i{width:17px;height:17px;font-size:12px;line-height:17px}.iconbtn{width:44px;height:44px;font-size:21px}.pill{font-size:18px;padding:3px 10px}.hud{gap:6px}#act{width:104px;height:104px;font-size:46px}}
/* short screens (phone held sideways): keep the title and the victory card inside the screen */
@media (max-height:480px){
.screen{gap:6px;justify-content:center;overflow:auto}
.logo{font-size:clamp(30px,11vh,52px)}
.logo.mid,.logo.win{font-size:clamp(28px,10vh,44px)}
.tag{font-size:15px}
.small{font-size:12px;max-width:60ch}
.big{font-size:24px;padding:6px 30px}
.big.alt{font-size:18px}
.trophy{font-size:64px}
.screen:has(.trophy){padding-top:56px}
}
/* ---------- Royal Cat Sanctuary ---------- */
#ui .home-ui { position: absolute; inset: 0; pointer-events: none; }
#ui .home-ui > .hud, #ui .home-ui > .hud > .row { pointer-events: none; }
.petcard { position: absolute; left: 50%; top: calc(74px + env(safe-area-inset-top)); transform: translateX(-50%); display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,.92); border-radius: 999px; padding: 6px 8px 6px 18px; box-shadow: 0 6px 18px rgba(160,80,130,.25); font-size: 20px; color: #7a3d63; white-space: nowrap; max-width: calc(100vw - 32px); }
.petcard .nm { overflow: hidden; text-overflow: ellipsis; max-width: 46vw; }
.wandbtn { position: absolute; right: max(44px, calc(env(safe-area-inset-right, 0px) + 36px)); bottom: calc(env(safe-area-inset-bottom, 0px) + 158px); width: 72px; height: 72px; border-radius: 50%; border: 0; font-size: 36px; background: radial-gradient(circle at 35% 30%, #ffffff, #d7c2ff); box-shadow: 0 6px 16px rgba(120,80,180,.3); touch-action: none; }
.nameinput { font: inherit; font-size: 26px; padding: 12px 18px; border-radius: 18px; border: 3px solid #ffb3d1; text-align: center; width: min(320px, 80vw); color: #7a3d63; background: #fff; }
.shop { overflow-y: auto; justify-content: flex-start; padding-top: 24px; padding-bottom: 24px; }
.shopgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; width: min(720px, calc(100vw - 32px)); margin: 8px 0 16px; }
.shopitem { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 12px 8px; border-radius: 20px; border: 0; background: #fff; box-shadow: 0 4px 12px rgba(160,80,130,.18); color: #7a3d63; font: inherit; }
.shopitem .em { font-size: 40px; line-height: 1.1; }
.shopitem b { font-size: 17px; }
.shopitem small { font-size: 13px; opacity: .8; min-height: 2.4em; }
.shopitem .price { font-size: 18px; font-weight: 700; background: #ffe6f2; border-radius: 999px; padding: 2px 12px; }
.shopitem.own { background: #eafff2; }
.shopitem.own .price { background: #c9f2d8; }
.shopitem.poor { opacity: .6; }
@media (max-width: 420px) { .wandbtn { right: 44px; bottom: 140px; width: 62px; height: 62px; font-size: 30px; } .shopgrid { grid-template-columns: 1fr 1fr; } }
#ui .home-ui.covered > .hud, #ui .home-ui.covered > .petcard, #ui .home-ui.covered > .wandbtn { visibility: hidden; }
.shophead { font-size: 22px; color: #7a3d63; margin: 10px 0 0; width: min(720px, calc(100vw - 32px)); text-align: left; }
.shopitem.wear { background: #fff6cf; box-shadow: 0 0 0 3px #ffd34d inset, 0 4px 12px rgba(160,80,130,.18); }
.shopitem.wear .price { background: #ffe680; }
/* v10: picture how-to for non-readers, clearer difficulty choice, one-line cat row on phones */
.howto { display: flex; gap: 10px; justify-content: center; flex-wrap: nowrap; margin: 6px 0; }
.howto span { display: flex; flex-direction: column; align-items: center; background: rgba(255,255,255,.85); border-radius: 18px; padding: 6px 10px; font-size: 26px; line-height: 1.2; box-shadow: 0 3px 10px rgba(160,80,130,.15); }
.howto b { font-size: 26px; font-weight: 400; }
#diff { flex-wrap: nowrap; }
#diff .big.alt { opacity: .75; padding-left: 14px; padding-right: 14px; }
#diff .big.alt.sel { opacity: 1; box-shadow: 0 0 0 4px #ffd34d, 0 6px 0 rgba(0,0,0,.12); transform: scale(1.06); }
@media (max-width:420px) { .cats { flex-wrap: nowrap; gap: 2px; } .cats i { width: 14px; height: 14px; font-size: 10px; line-height: 14px; } .howto span { font-size: 21px; padding: 5px 7px; } .howto b { font-size: 21px; } #diff .big.alt { font-size: 18px; padding: 10px 10px; } }
/* princess wish bubbles */
.wish { position: absolute; left: 0; top: 0; display: flex; flex-direction: column; align-items: center; background: #fff; border-radius: 20px; padding: 4px 10px 2px; box-shadow: 0 4px 12px rgba(160,80,130,.3); pointer-events: none !important; font-size: 30px; line-height: 1.1; will-change: transform; }
.wish::after { content: ''; position: absolute; bottom: -9px; left: 50%; margin-left: -9px; border: 9px solid transparent; border-bottom: 0; border-top-color: #fff; }
.wish i { font-style: normal; font-size: 12px; color: #ff6fae; letter-spacing: 2px; }
.wish.ready { animation: wishglow .5s infinite alternate; }
@keyframes wishglow { from { box-shadow: 0 0 0 3px #ffd34d, 0 4px 12px rgba(160,80,130,.3); } to { box-shadow: 0 0 0 8px rgba(255,211,77,.6), 0 4px 16px rgba(160,80,130,.3); } }
@media (max-width:420px) { .wish { font-size: 24px; } }
.places { flex-wrap: nowrap; }
.places .big { padding-left: 22px; padding-right: 22px; }
/* v11: phone top bar never wraps (cat row folds into two lines of five), shorter toasts on phones */
@media (max-width:420px) {
.hud .cats { display: grid; grid-template-columns: repeat(5, 16px); gap: 2px; }
.hud .cats i { width: 16px; height: 16px; font-size: 11px; line-height: 16px; }
.toast { font-size: 24px; white-space: normal; text-align: center; width: max-content; max-width: 88vw; }
}
/* hide and seek: she covers her eyes while the cats hide */
.seekcover { background: rgba(255, 214, 234, .96); }
.seekeyes { font-size: 120px; line-height: 1; animation: pop .6s infinite alternate; }
.screen{z-index:6}
.toast{z-index:7}
/* candy hunt: a shrinking rainbow bar instead of numbers */
.huntbar { position: absolute; left: 50%; top: calc(70px + env(safe-area-inset-top)); transform: translateX(-50%); width: min(300px, 60vw); height: 16px; border-radius: 999px; background: rgba(255,255,255,.85); box-shadow: 0 3px 10px rgba(160,80,130,.2); overflow: hidden; pointer-events: none !important; }
.huntbar b { display: block; height: 100%; width: 100%; background: linear-gradient(90deg, #ff7a9c, #ffe57a, #8fe39b, #7cc8ff, #b79bff); border-radius: 999px; }
fur.ts (src/render/fur.ts)185 lines
// Shell-texture fur. Each furred part is a normal mesh whose geometry holds N stacked
// copies of the base surface ("shells"). The shader pushes each shell out along the
// normal and cuts strands with a 3D cell pattern, so the cat looks genuinely fluffy.
import * as THREE from 'three';
export const quality = { shells: 14, low: false };
export function setQuality(low: boolean) { quality.low = low; quality.shells = low ? 9 : 14; }
const shellCache = new Map<string, THREE.BufferGeometry>();
export function shellGeometry(key: string, make: () => THREE.BufferGeometry): THREE.BufferGeometry {
const k = key + ':' + quality.shells;
const hit = shellCache.get(k);
if (hit) return hit;
const base = make().toNonIndexed();
base.computeVertexNormals();
const n = quality.shells;
const pos = base.getAttribute('position') as THREE.BufferAttribute;
const nor = base.getAttribute('normal') as THREE.BufferAttribute;
const vc = pos.count;
const P = new Float32Array(vc * 3 * n), N = new Float32Array(vc * 3 * n), S = new Float32Array(vc * n);
for (let s = 0; s < n; s++) {
P.set(pos.array as Float32Array, s * vc * 3);
N.set(nor.array as Float32Array, s * vc * 3);
S.fill(s / (n - 1), s * vc, (s + 1) * vc);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(P, 3));
g.setAttribute('normal', new THREE.BufferAttribute(N, 3));
g.setAttribute('aShell', new THREE.BufferAttribute(S, 1));
g.computeBoundingSphere();
if (g.boundingSphere) g.boundingSphere.radius *= 1.4;
shellCache.set(k, g);
base.dispose();
return g;
}
export const furSphere = () => shellGeometry('sphere', () => new THREE.SphereGeometry(1, quality.low ? 16 : 22, quality.low ? 12 : 16));
export const furCone = () => shellGeometry('cone', () => new THREE.ConeGeometry(1, 1.6, quality.low ? 10 : 14, 3));
/** Lighting + fog shared by all custom shaders. Updated once per frame by the scene. */
export const sharedLight = {
uSunDir: { value: new THREE.Vector3(0.4, 0.85, 0.35).normalize() },
uSunColor: { value: new THREE.Color(1.0, 0.95, 0.88) },
uSky: { value: new THREE.Color(0.75, 0.82, 1.0) },
uGround: { value: new THREE.Color(0.95, 0.75, 0.7) },
uFogColor: { value: new THREE.Color('#ffd9ec') },
uFogNear: { value: 40 },
uFogFar: { value: 120 },
uTime: { value: 0 },
};
export interface FurOptions {
top: THREE.ColorRepresentation;
bottom: THREE.ColorRepresentation;
axis?: THREE.Vector3; // local direction that gets the "top" color
split?: number; // -1..1 threshold along axis
stripes?: number; // tabby stripe strength 0..1
stripeAxis?: THREE.Vector3;
length?: number; // fur length in local units
density?: number; // strand density
drift?: { value: THREE.Vector3 }; // shared per-creature wind/gravity vector (world units)
glow?: number; // magic emissive (Golden Fluff, Sparkle)
}
const vert = /* glsl */`
attribute float aShell;
uniform float uLen; uniform vec3 uDrift; uniform float uTime;
varying vec3 vBase; varying vec3 vN; varying float vShell; varying vec3 vWorld; varying vec3 vLocalN;
void main(){
vShell = aShell;
vBase = position;
vLocalN = normal;
vec3 p = position + normal * aShell * uLen;
vec4 w = modelMatrix * vec4(p, 1.0);
float s2 = aShell * aShell;
w.xyz += uDrift * s2 + vec3(sin(uTime*2.3 + w.y*3.0), 0.0, cos(uTime*1.9 + w.x*3.0)) * 0.006 * s2;
vWorld = w.xyz;
vN = normalize(mat3(modelMatrix) * normal);
gl_Position = projectionMatrix * viewMatrix * w;
}`;
const frag = /* glsl */`
uniform vec3 uTop; uniform vec3 uBottom; uniform vec3 uAxis; uniform float uSplit;
uniform float uStripes; uniform vec3 uStripeAxis; uniform float uDensity; uniform float uGlow;
uniform vec3 uSunDir; uniform vec3 uSunColor; uniform vec3 uSky; uniform vec3 uGround;
uniform vec3 uFogColor; uniform float uFogNear; uniform float uFogFar; uniform float uTime;
varying vec3 vBase; varying vec3 vN; varying float vShell; varying vec3 vWorld; varying vec3 vLocalN;
float h31(vec3 p){ p = fract(p*0.3183099 + 0.1); p *= 17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
float strand(vec3 p, float shell){
vec3 c = floor(p); vec3 f = fract(p) - 0.5;
float r = h31(c);
float len = 0.55 + 0.45 * r; // strand length varies
if (shell > len) return 0.0;
float rad = (1.0 - shell/len) * 0.62 + 0.08;
return step(length(f.xy + vec2(r-0.5, h31(c+7.1)-0.5)*0.35) , rad);
}
void main(){
if (vShell > 0.001) {
vec3 p = vBase * uDensity;
float a = max(strand(p, vShell), strand(p*1.73 + 3.1, vShell*1.1));
if (a < 0.5) discard;
}
float t = dot(normalize(vLocalN), uAxis);
float m = smoothstep(uSplit - 0.18, uSplit + 0.18, t);
vec3 col = mix(uBottom, uTop, m);
// soft tabby stripes on the top colour only
float st = sin(dot(vBase, uStripeAxis) * 9.0 + sin(vBase.x*7.0)*0.8);
col *= 1.0 - uStripes * m * smoothstep(0.35, 0.95, st) * 0.28;
// fake ambient occlusion through the fur, brighter tips
col *= mix(0.58, 1.08, vShell);
vec3 N = normalize(vN);
float diff = clamp((dot(N, uSunDir) + 0.45) / 1.45, 0.0, 1.0);
vec3 amb = mix(uGround, uSky, N.y*0.5+0.5) * 0.55;
vec3 V = normalize(cameraPosition - vWorld);
float rim = pow(1.0 - clamp(dot(N, V), 0.0, 1.0), 2.5) * (0.25 + 0.5*vShell);
vec3 c = col * (amb + uSunColor * diff * 0.78) + rim * vec3(1.0, 0.92, 0.85) * 0.45;
c += uGlow * vec3(1.0, 0.85, 0.35) * (0.35 + 0.25*sin(uTime*4.0 + vBase.y*6.0));
float fog = smoothstep(uFogNear, uFogFar, length(cameraPosition - vWorld));
gl_FragColor = vec4(mix(c, uFogColor, fog), 1.0);
#include <colorspace_fragment>
}`;
export function furMaterial(o: FurOptions): THREE.ShaderMaterial {
return new THREE.ShaderMaterial({
vertexShader: vert,
fragmentShader: frag,
uniforms: {
...sharedLight,
uTop: { value: new THREE.Color(o.top) },
uBottom: { value: new THREE.Color(o.bottom) },
uAxis: { value: (o.axis ?? new THREE.Vector3(0, 1, 0)).clone().normalize() },
uSplit: { value: o.split ?? -0.1 },
uStripes: { value: o.stripes ?? 0 },
uStripeAxis: { value: (o.stripeAxis ?? new THREE.Vector3(0, 0, 1)).clone() },
uLen: { value: o.length ?? 0.22 },
uDensity: { value: o.density ?? 26 },
uDrift: o.drift ?? { value: new THREE.Vector3(0, -0.02, 0) },
uGlow: { value: o.glow ?? 0 },
},
});
}
/** Simple soft-lit material for non-fur parts that still matches the fur lighting. */
const softVert = /* glsl */`
varying vec3 vN; varying vec3 vWorld;
#ifdef USE_INSTANCING_COLOR
#endif
void main(){
vec4 w = modelMatrix * vec4(position,1.0);
vWorld = w.xyz; vN = normalize(mat3(modelMatrix)*normal);
gl_Position = projectionMatrix * viewMatrix * w;
}`;
const softFrag = /* glsl */`
uniform vec3 uColor; uniform float uGloss; uniform float uEmissive;
uniform vec3 uSunDir; uniform vec3 uSunColor; uniform vec3 uSky; uniform vec3 uGround;
uniform vec3 uFogColor; uniform float uFogNear; uniform float uFogFar;
varying vec3 vN; varying vec3 vWorld;
void main(){
vec3 N = normalize(vN); vec3 V = normalize(cameraPosition - vWorld);
float diff = clamp((dot(N,uSunDir)+0.4)/1.4,0.0,1.0);
vec3 amb = mix(uGround,uSky,N.y*0.5+0.5)*0.55;
vec3 c = uColor*(amb + uSunColor*diff*0.8);
vec3 H = normalize(uSunDir + V);
c += uGloss * pow(max(dot(N,H),0.0), 40.0) * vec3(1.0);
c += uGloss * 0.6 * step(0.985, max(dot(N, normalize(V + vec3(0.25,0.35,0.0))),0.0));
c += uColor * uEmissive;
float rim = pow(1.0 - clamp(dot(N,V),0.0,1.0), 3.0)*0.18;
c += rim;
float fog = smoothstep(uFogNear, uFogFar, length(cameraPosition - vWorld));
gl_FragColor = vec4(mix(c,uFogColor,fog),1.0);
#include <colorspace_fragment>
}`;
const softCache = new Map<string, THREE.ShaderMaterial>();
export function softMaterial(color: THREE.ColorRepresentation, gloss = 0, emissive = 0): THREE.ShaderMaterial {
const key = new THREE.Color(color).getHexString() + gloss + ':' + emissive;
const hit = softCache.get(key); if (hit) return hit;
const m = new THREE.ShaderMaterial({
vertexShader: softVert, fragmentShader: softFrag,
uniforms: { ...sharedLight, uColor: { value: new THREE.Color(color) }, uGloss: { value: gloss }, uEmissive: { value: emissive } },
});
softCache.set(key, m);
return m;
}
catModel.ts (src/cats/catModel.ts)289 lines
// Procedural fluffy cat: shell-fur parts in a small rig with expressive procedural animation.
import * as THREE from 'three';
import { furCone, furMaterial, furSphere, softMaterial } from '../render/fur';
import { clamp, damp, lerp, rand } from '../core/util';
export type Pose = 'stand' | 'sit' | 'flop' | 'wiggle' | 'dance' | 'statue' | 'sleep' | 'pancake' | 'spin' | 'eat' | 'roll';
export type Face = 'normal' | 'happy' | 'sleep' | 'surprised' | 'dizzy' | 'smug' | 'meow';
export type Accessory = 'leaf' | 'crown' | 'monocle' | 'hat' | 'nightcap' | 'bow' | 'star' | 'wings' | 'none' | 'tiny';
export interface CatLook {
top: string; bottom: string; scale: number; split?: number; stripes?: number;
accessory: Accessory; glow?: number; earSize?: number; furLen?: number; eye?: string;
}
const UP = new THREE.Vector3(0, 1, 0);
export class CatRig {
root = new THREE.Group();
private pivot = new THREE.Group();
private bodyMesh: THREE.Mesh;
private head = new THREE.Group();
private ears: THREE.Group[] = [];
private eyes: THREE.Group[] = [];
private paws: THREE.Mesh[] = [];
private tail: THREE.Group[] = [];
private mouthW: THREE.Group;
private mouthO: THREE.Mesh;
private blep: THREE.Mesh;
heartT = 0;
private shadow: THREE.Mesh;
private dizzy: THREE.Group;
private zzz: THREE.Group;
readonly drift = { value: new THREE.Vector3(0, -0.02, 0) };
readonly mats: THREE.ShaderMaterial[] = [];
scale: number;
// animation state
pose: Pose = 'stand';
face: Face = 'normal';
speed = 0; // horizontal speed (world units / s)
airborne = false;
vy = 0;
lookYaw = 0; lookPitch = 0;
wag = 1; // tail wag energy
private phase = rand() * 10;
private t = rand() * 10;
private blinkT = 2 + rand() * 3;
private blink = 0;
private squash = 0;
private earTwitch = [0, 0];
private poseW: Record<string, number> = {};
private spinA = 0;
private faceTimer = 0;
constructor(look: CatLook) {
this.scale = look.scale;
const s = look.scale;
this.root.scale.setScalar(s);
this.root.add(this.pivot);
this.pivot.position.y = 0.42;
const fl = look.furLen ?? 1;
const bodyMat = furMaterial({ top: look.top, bottom: look.bottom, split: look.split ?? -0.15, stripes: look.stripes ?? 0.8, stripeAxis: new THREE.Vector3(0, 0, 1), length: 0.24 * fl, density: 24, drift: this.drift, glow: look.glow });
const headMat = furMaterial({ top: look.top, bottom: look.bottom, axis: new THREE.Vector3(0, 0.75, -0.66), split: 0.05, stripes: (look.stripes ?? 0.8) * 0.6, stripeAxis: new THREE.Vector3(1.4, 0, 0), length: 0.2 * fl, density: 26, drift: this.drift, glow: look.glow });
const pawMat = furMaterial({ top: look.bottom, bottom: look.bottom, length: 0.25 * fl, density: 30, drift: this.drift, glow: (look.glow ?? 0) * 0.5 });
const earMat = furMaterial({ top: look.top, bottom: look.top, length: 0.18, density: 34, drift: this.drift, glow: look.glow });
const tailMat = furMaterial({ top: look.top, bottom: look.top, stripes: 0.9, stripeAxis: new THREE.Vector3(0, 1.6, 0), length: 0.42 * fl, density: 22, drift: this.drift, glow: look.glow });
const tipMat = furMaterial({ top: look.bottom, bottom: look.bottom, length: 0.45 * fl, density: 22, drift: this.drift, glow: look.glow });
this.mats.push(bodyMat, headMat, pawMat, earMat, tailMat, tipMat);
const sph = furSphere(), cone = furCone();
this.bodyMesh = new THREE.Mesh(sph, bodyMat);
this.bodyMesh.scale.set(0.4, 0.36, 0.5);
this.pivot.add(this.bodyMesh);
// chest fluff ruff gives the cat a fluffy silhouette
const ruff = new THREE.Mesh(sph, pawMat); ruff.scale.set(0.26, 0.24, 0.18); ruff.position.set(0, 0.06, 0.36); this.pivot.add(ruff);
this.head.position.set(0, 0.3, 0.42);
this.pivot.add(this.head);
const headMesh = new THREE.Mesh(sph, headMat); headMesh.scale.set(0.4, 0.35, 0.36); this.head.add(headMesh);
for (const sx of [-1, 1]) {
const cheek = new THREE.Mesh(sph, pawMat); cheek.scale.set(0.15, 0.13, 0.14); cheek.position.set(sx * 0.27, -0.12, 0.12); this.head.add(cheek);
const eg = new THREE.Group(); eg.position.set(sx * 0.27 * (look.earSize ?? 1) * 0.85, 0.27, -0.03);
eg.rotation.z = -sx * 0.32;
const es = look.earSize ?? 1;
const ear = new THREE.Mesh(cone, earMat); ear.scale.set(0.13 * es, 0.13 * es, 0.075 * es); ear.position.y = 0.08 * es; eg.add(ear);
const inner = new THREE.Mesh(new THREE.ConeGeometry(0.07 * es, 0.16 * es, 8), softMaterial('#ffb0c8')); inner.position.set(0, 0.07 * es, 0.045 * es); inner.scale.z = 0.4; eg.add(inner);
this.head.add(eg); this.ears.push(eg);
// big glossy eyes
const eye = new THREE.Group(); eye.position.set(sx * 0.155, 0.02, 0.3); eye.scale.setScalar(1.18);
const ball = new THREE.Mesh(new THREE.SphereGeometry(0.085, 16, 12), softMaterial(look.eye ?? '#2a1d3a', 1.2)); ball.scale.z = 0.55; eye.add(ball);
const hl = new THREE.Mesh(new THREE.SphereGeometry(0.026, 8, 6), softMaterial('#ffffff', 0, 2)); hl.position.set(sx * -0.025 + 0.012, 0.035, 0.04); eye.add(hl);
const hl2 = new THREE.Mesh(new THREE.SphereGeometry(0.012, 6, 4), softMaterial('#ffffff', 0, 2)); hl2.position.set(0.02 * sx, -0.03, 0.045); eye.add(hl2);
this.head.add(eye); this.eyes.push(eye);
const blush = new THREE.Mesh(new THREE.SphereGeometry(0.062, 10, 6), softMaterial('#ff8fb8', 0, 0.35)); blush.scale.set(1, 0.55, 0.3); blush.position.set(sx * 0.245, -0.085, 0.265); this.head.add(blush);
}
const nose = new THREE.Mesh(new THREE.SphereGeometry(0.04, 10, 6), softMaterial('#ff7fa6', 0.6)); nose.scale.set(1, 0.7, 0.6); nose.position.set(0, -0.04, 0.355); this.head.add(nose);
this.mouthW = new THREE.Group();
const arc = new THREE.TorusGeometry(0.028, 0.008, 5, 10, Math.PI);
for (const sx of [-1, 1]) { const a = new THREE.Mesh(arc, softMaterial('#5a3340')); a.rotation.z = Math.PI; a.position.set(sx * 0.028, -0.085, 0.345); this.mouthW.add(a); }
this.head.add(this.mouthW);
this.blep = new THREE.Mesh(new THREE.SphereGeometry(0.03, 10, 8), softMaterial('#ff6f9a', 0.6)); this.blep.scale.set(1, 0.7, 0.6); this.blep.position.set(0.012, -0.115, 0.345); this.blep.visible = false; this.head.add(this.blep);
this.mouthO = new THREE.Mesh(new THREE.SphereGeometry(0.04, 10, 8), softMaterial('#c44d6e')); this.mouthO.scale.set(1, 0.8, 0.4); this.mouthO.position.set(0, -0.11, 0.33); this.mouthO.visible = false; this.head.add(this.mouthO);
// whiskers
const wv: number[] = [];
for (const sx of [-1, 1]) for (const dy of [-0.02, 0.015]) wv.push(sx * 0.16, -0.06, 0.32, sx * 0.42, -0.06 + dy * 3, 0.3);
const wg = new THREE.BufferGeometry(); wg.setAttribute('position', new THREE.Float32BufferAttribute(wv, 3));
this.head.add(new THREE.LineSegments(wg, new THREE.LineBasicMaterial({ color: '#fff6ea' })));
for (const [x, z] of [[-0.2, 0.28], [0.2, 0.28], [-0.2, -0.3], [0.2, -0.3]]) {
const p = new THREE.Mesh(sph, pawMat); p.scale.set(0.11, 0.1, 0.13); p.position.set(x, -0.33, z); this.pivot.add(p); this.paws.push(p);
if (z > 0) { const bean = new THREE.Mesh(new THREE.SphereGeometry(0.4, 8, 6), softMaterial('#ff9ec0', 0.3)); bean.scale.set(0.55, 0.35, 0.3); bean.position.set(0, -0.35, 0.85); p.add(bean); }
}
let parent: THREE.Object3D = this.pivot;
for (let i = 0; i < 6; i++) {
const g = new THREE.Group();
if (i === 0) { g.position.set(0, 0.05, -0.45); g.rotation.x = -0.9; } else g.position.y = 0.12;
const r = 0.08 + i * 0.012;
const m = new THREE.Mesh(sph, i === 5 ? tipMat : tailMat); m.scale.setScalar(r); m.scale.y = r * 1.25; m.position.y = 0.06; g.add(m);
parent.add(g); this.tail.push(g); parent = g;
}
this.addAccessory(look.accessory);
// soft blob shadow
this.shadow = new THREE.Mesh(new THREE.CircleGeometry(0.5, 20), new THREE.MeshBasicMaterial({ color: '#7a4a6a', transparent: true, opacity: 0.22, depthWrite: false }));
this.shadow.rotation.x = -Math.PI / 2; this.shadow.position.y = 0.03; this.shadow.renderOrder = -1;
this.root.add(this.shadow);
// dizzy stars + zzz bubbles
this.dizzy = new THREE.Group();
for (let i = 0; i < 3; i++) { const st = new THREE.Mesh(starGeo(), softMaterial('#ffe066', 0, 0.8)); st.position.set(Math.cos(i * 2.1) * 0.3, 0, Math.sin(i * 2.1) * 0.3); st.scale.setScalar(0.12); this.dizzy.add(st); }
this.dizzy.position.set(0, 0.42, 0); this.dizzy.visible = false; this.head.add(this.dizzy);
this.zzz = new THREE.Group();
for (let i = 0; i < 3; i++) { const z = new THREE.Mesh(new THREE.SphereGeometry(0.06 + i * 0.03, 10, 8), new THREE.MeshBasicMaterial({ color: '#cfe8ff', transparent: true, opacity: 0.8 })); this.zzz.add(z); }
this.zzz.visible = false; this.head.add(this.zzz);
}
private addAccessory(a: Accessory) {
const h = this.head;
if (a === 'leaf') {
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.025, 0.035, 0.12, 6), softMaterial('#6bbf59')); stem.position.set(0, 0.4, 0); stem.rotation.z = 0.3; h.add(stem);
const leaf = new THREE.Mesh(new THREE.SphereGeometry(0.08, 8, 6), softMaterial('#8ee06e', 0.3)); leaf.scale.set(1, 0.3, 0.6); leaf.position.set(0.07, 0.44, 0); leaf.rotation.z = -0.5; h.add(leaf);
} else if (a === 'crown') {
const g = new THREE.Group(); g.position.set(0, 0.38, 0); g.rotation.z = 0.18;
const band = new THREE.Mesh(new THREE.CylinderGeometry(0.13, 0.14, 0.08, 14, 1, true), softMaterial('#ffd34d', 1.2, 0.2)); g.add(band);
for (let i = 0; i < 5; i++) { const sp = new THREE.Mesh(new THREE.ConeGeometry(0.035, 0.1, 5), softMaterial('#ffd34d', 1.2, 0.2)); const an = i / 5 * Math.PI * 2; sp.position.set(Math.cos(an) * 0.13, 0.08, Math.sin(an) * 0.13); g.add(sp);
const gem = new THREE.Mesh(new THREE.SphereGeometry(0.022, 6, 4), softMaterial(['#ff6fa8', '#6fd4ff', '#b07dff'][i % 3], 1.5, 0.3)); gem.position.set(Math.cos(an) * 0.14, 0.0, Math.sin(an) * 0.14); g.add(gem); }
h.add(g);
} else if (a === 'monocle') {
const m = new THREE.Mesh(new THREE.TorusGeometry(0.075, 0.012, 6, 16), softMaterial('#ffd34d', 1.5)); m.position.set(0.15, 0.03, 0.34); h.add(m);
const tash = new THREE.Group(); tash.position.set(0, -0.08, 0.36);
for (const sx of [-1, 1]) { const p = new THREE.Mesh(new THREE.SphereGeometry(0.06, 10, 6), softMaterial('#7a4a2a')); p.scale.set(1.4, 0.45, 0.5); p.position.x = sx * 0.07; p.rotation.z = sx * -0.3; tash.add(p);
const curl = new THREE.Mesh(new THREE.SphereGeometry(0.03, 8, 6), softMaterial('#7a4a2a')); curl.position.set(sx * 0.15, 0.03, 0); tash.add(curl); }
h.add(tash);
this.mouthW.visible = false;
} else if (a === 'hat') {
const hat = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.22, 0.14, 3), softMaterial('#3c5aa6', 0.4)); hat.position.set(0, 0.37, 0); hat.rotation.y = Math.PI; h.add(hat);
const feather = new THREE.Mesh(new THREE.SphereGeometry(0.06, 8, 6), softMaterial('#ff6fa8')); feather.scale.set(0.4, 1.4, 0.4); feather.position.set(0.1, 0.48, -0.05); feather.rotation.z = -0.5; h.add(feather);
} else if (a === 'nightcap') {
const cap = new THREE.Mesh(new THREE.ConeGeometry(0.2, 0.42, 12), softMaterial('#8fb8ff')); cap.position.set(0.05, 0.42, -0.02); cap.rotation.z = -0.6; h.add(cap);
const pom = new THREE.Mesh(new THREE.SphereGeometry(0.06, 10, 8), softMaterial('#ffffff')); pom.position.set(0.24, 0.53, -0.02); h.add(pom);
} else if (a === 'bow') {
const g = new THREE.Group(); g.position.set(0.18, 0.3, 0.05);
const cols = ['#ff5e7e', '#ffb648', '#7ee081', '#5ec8ff', '#b47dff'];
for (const sx of [-1, 1]) { const l = new THREE.Mesh(new THREE.ConeGeometry(0.07, 0.14, 4), softMaterial(cols[sx > 0 ? 3 : 0], 0.6)); l.rotation.z = sx * Math.PI / 2; l.position.x = sx * 0.07; g.add(l); }
g.add(new THREE.Mesh(new THREE.SphereGeometry(0.035, 8, 6), softMaterial(cols[1], 0.6)));
h.add(g);
} else if (a === 'star') {
const st = new THREE.Mesh(starGeo(), softMaterial('#fff07a', 0.5, 0.8)); st.scale.setScalar(0.16); st.position.y = 0.2; this.tail[5].add(st);
} else if (a === 'wings') {
for (const sx of [-1, 1]) { const w = new THREE.Mesh(furSphere(), this.mats[2]); w.scale.set(0.05, 0.18, 0.28); w.position.set(sx * 0.38, 0.22, -0.05); w.rotation.z = sx * 0.6; this.pivot.add(w); w.name = 'wing'; }
}
}
/** Brief expression override, e.g. 'meow' for half a second. */
flash(face: Face, seconds: number) { this.face = face; this.faceTimer = seconds; }
land(strength = 1) { this.squash = Math.max(this.squash, 0.6 * strength); }
update(dt: number) {
this.t += dt;
const sp = clamp(this.speed / 4, 0, 1.6);
this.phase += dt * (4 + this.speed * 3.2);
if (this.faceTimer > 0) { this.faceTimer -= dt; if (this.faceTimer <= 0) this.face = 'normal'; }
// pose blending weights
for (const p of ['sit', 'flop', 'wiggle', 'dance', 'statue', 'sleep', 'pancake', 'spin', 'eat', 'roll']) {
const target = this.pose === p ? 1 : 0;
this.poseW[p] = lerp(this.poseW[p] ?? 0, target, damp(9, dt));
}
const W = this.poseW;
const run = (1 - W.sit - W.flop - W.sleep - W.statue - W.pancake - W.eat) * sp;
const bob = Math.abs(Math.sin(this.phase)) * 0.11 * run;
this.squash = Math.max(0, this.squash - dt * 3);
const sq = Math.sin(this.squash * Math.PI) * 0.35 + W.pancake * 0.6;
const stretch = this.airborne ? clamp(this.vy * 0.04, -0.15, 0.2) : 0;
// body pose
const pv = this.pivot;
pv.position.y = 0.42 + bob + (this.airborne ? 0.05 : 0) - W.sit * 0.04 - W.flop * 0.12 - W.sleep * 0.16 - W.pancake * 0.25 + W.dance * Math.abs(Math.sin(this.t * 7)) * 0.25;
pv.rotation.x = -W.sit * 0.55 + Math.sin(this.phase * 2) * 0.06 * run - stretch * 0.6 + W.wiggle * 0.35 - W.eat * -0.3;
pv.rotation.z = W.flop * 1.35 + W.wiggle * Math.sin(this.t * 14) * 0.18 + W.dance * Math.sin(this.t * 7) * 0.2 + W.roll * Math.sin(this.t * 9) * 1.4;
this.spinA += dt * (W.spin * 14 + W.dance * 3);
pv.rotation.y = this.spinA * (W.spin + W.dance) + W.wiggle * Math.PI;
pv.scale.set(1 + sq * 0.6 - stretch * 0.4, 1 - sq + stretch, 1 + sq * 0.3);
if (W.wiggle > 0.01) { pv.position.y += W.wiggle * 0.05; }
// paws: trot cycle
const pa = this.phase;
const swing = [Math.sin(pa), Math.sin(pa + Math.PI), Math.sin(pa + Math.PI), Math.sin(pa)];
this.paws.forEach((p, i) => {
const front = i < 2;
const air = this.airborne ? (front ? 0.08 : -0.06) : 0;
p.position.z = (front ? 0.28 : -0.3) + swing[i] * 0.13 * run + air + W.sit * (front ? 0.06 : -0.02);
p.position.y = -0.33 + Math.max(0, -Math.cos(pa + (i === 0 || i === 3 ? 0 : Math.PI))) * 0.09 * run + W.sit * (front ? -0.02 : 0.05) + W.sleep * 0.1 + W.dance * (front ? 0.2 + Math.sin(this.t * 14 + i) * 0.08 : 0);
if (W.flop > 0.5 || W.roll > 0.5) p.position.y += Math.sin(this.t * 10 + i) * 0.03;
});
// tail: travelling wave; tease = straight up and wiggly
const wagSpeed = 3 + this.wag * 5 + W.wiggle * 8;
this.tail.forEach((g, i) => {
if (i === 0) {
g.rotation.x = lerp(-0.9 - run * 0.5, -0.15, W.wiggle + W.statue) + W.sleep * -0.6 + W.sit * 0.5;
g.rotation.z = Math.sin(this.t * wagSpeed) * (0.25 + this.wag * 0.2);
} else {
g.rotation.x = 0.28 - run * 0.12 - W.sleep * 0.1 + Math.sin(this.t * 2 + i) * 0.05 - W.statue * 0.25;
g.rotation.z = Math.sin(this.t * wagSpeed - i * 0.7) * (0.12 + this.wag * 0.12) * (1 - W.statue);
}
});
// head look + tilt
const h = this.head;
h.rotation.y = lerp(h.rotation.y, clamp(this.lookYaw, -0.9, 0.9) * (1 - W.sleep), damp(6, dt));
h.rotation.x = lerp(h.rotation.x, clamp(this.lookPitch, -0.4, 0.4) + W.sit * 0.45 + W.sleep * 0.3 + W.eat * 0.5 + W.wiggle * -0.4, damp(6, dt));
h.rotation.z = Math.sin(this.t * 1.3) * 0.08 + W.dance * Math.sin(this.t * 7 + 1) * 0.25 + (this.face === 'happy' ? 0.15 : 0);
// ears
this.earTwitch = this.earTwitch.map(v => Math.max(0, v - dt * 5));
if (rand() < dt * 0.4) this.earTwitch[rand() < 0.5 ? 0 : 1] = 1;
this.ears.forEach((e, i) => {
const sx = i === 0 ? -1 : 1;
const tw = Math.sin(this.earTwitch[i] * Math.PI) * 0.4;
e.rotation.z = -sx * (0.32 + (this.face === 'surprised' ? -0.15 : 0) + W.sleep * 0.4) - sx * tw;
e.rotation.x = -tw * 0.5 + (this.airborne ? -0.3 : 0) - run * 0.25;
});
// eyes: blink + expressions
this.blinkT -= dt;
if (this.blinkT < 0) { this.blink = 1; this.blinkT = 2 + rand() * 4; }
this.blink = Math.max(0, this.blink - dt * 8);
const f = this.face;
let ey = 1 - Math.sin(this.blink * Math.PI) * 0.9;
let es = 1;
if (f === 'happy' || f === 'smug') ey = 0.22;
if (f === 'sleep' || W.sleep > 0.5) ey = 0.08;
if (f === 'surprised') { es = 1.3; ey = 1.25; }
if (f === 'dizzy') ey = 0.5 + Math.sin(this.t * 12) * 0.4;
this.eyes.forEach((e, i) => {
e.scale.set(es, lerp(e.scale.y, ey * es, damp(20, dt)), es);
e.rotation.z = f === 'happy' ? (i ? -0.2 : 0.2) : 0;
});
const open = f === 'meow' || f === 'surprised';
this.mouthO.visible = open; if (this.mouthW.children.length && !this.mouthW.userData.hidden) this.mouthW.visible = !open;
this.mouthO.scale.y = 0.6 + Math.abs(Math.sin(this.t * 18)) * 0.5;
this.blep.visible = (f === 'happy' || f === 'smug') && !open && Math.sin(this.t * 0.7) > 0.2;
this.dizzy.visible = f === 'dizzy';
if (this.dizzy.visible) this.dizzy.rotation.y += dt * 5;
this.zzz.visible = W.sleep > 0.5;
if (this.zzz.visible) this.zzz.children.forEach((z, i) => { const k = (this.t * 0.6 + i / 3) % 1; z.position.set(0.25 + k * 0.3, 0.3 + k * 0.6, 0); z.scale.setScalar(0.4 + k); ((z as THREE.Mesh).material as THREE.MeshBasicMaterial).opacity = 0.9 * (1 - k); });
this.pivot.children.forEach(c => { if (c.name === 'wing') c.rotation.y = Math.sin(this.t * 16) * 0.5; });
// fur drift: gravity + lag behind motion
this.drift.value.set(0, -0.025 - (this.airborne ? this.vy * 0.004 : 0), 0);
this.shadow.scale.setScalar(1 - clamp((this.root.position.y - (this.root.userData.groundY ?? this.root.position.y)) * 0.2, 0, 0.6));
this.shadow.position.y = ((this.root.userData.groundY ?? this.root.position.y) - this.root.position.y) / this.scale + 0.03;
}
setMotionDrift(vx: number, vz: number) {
this.drift.value.x = -vx * 0.012; this.drift.value.z = -vz * 0.012;
}
}
let _star: THREE.BufferGeometry | null = null;
export function starGeo(): THREE.BufferGeometry {
if (_star) return _star;
const s = new THREE.Shape();
for (let i = 0; i < 10; i++) { const r = i % 2 ? 0.45 : 1; const a = i / 10 * Math.PI * 2 + Math.PI / 2; const x = Math.cos(a) * r, y = Math.sin(a) * r; i ? s.lineTo(x, y) : s.moveTo(x, y); }
_star = new THREE.ExtrudeGeometry(s, { depth: 0.35, bevelEnabled: true, bevelSize: 0.12, bevelThickness: 0.12, bevelSegments: 1 });
_star.center();
return _star;
}
export { UP };
cats.ts (src/cats/cats.ts)271 lines
// Cat personalities and the lightweight behaviour brain (deterministic + probabilistic, no runtime AI calls).
import * as THREE from 'three';
import { CatRig } from './catModel';
import type { CatLook, Pose } from './catModel';
import { Body } from '../physics/body';
import type { Bouncer } from '../physics/body';
import type { Level } from '../world/village';
import { angleLerp, clamp, damp, rand } from '../core/util';
import { audio } from '../audio';
import type { Particles } from '../fx/particles';
export type Special = 'tutorial' | 'bouncy' | 'popcorn' | 'hider' | 'tripper' | 'jitter' | 'sleeper' | 'sparkle' | 'statue' | 'golden';
export interface CatDef { id: string; name: string; emoji: string; look: CatLook; voice: number; speed: number; special: Special }
const O = '#ff9a3c', C = '#fff1dc';
export const CAT_DEFS: CatDef[] = [
{ id: 'pumpkin', name: 'Pumpkin', emoji: '🎃', voice: 0.6, speed: 0.6, special: 'tutorial', look: { top: O, bottom: C, scale: 1, accessory: 'leaf' } },
{ id: 'marshmallow', name: 'Marshmallow', emoji: '☁️', voice: 0.1, speed: 0.62, special: 'bouncy', look: { top: '#ffb15c', bottom: '#ffffff', eye: '#2b5a9a', scale: 1.55, split: 0.25, accessory: 'none', earSize: 0.75, furLen: 1.3 } },
{ id: 'popcorn', name: 'Popcorn', emoji: '🍿', voice: 1, speed: 0.8, special: 'popcorn', look: { top: '#ffb347', bottom: '#fff1a8', eye: '#6a4a1a', scale: 0.68, accessory: 'tiny', earSize: 1.2 } },
{ id: 'whiskers', name: 'Captain Whiskers', emoji: '🧁', voice: 0.45, speed: 0.72, special: 'hider', look: { top: '#f78b2e', bottom: '#dff7ee', stripes: 1, eye: '#2f7a4a', scale: 1.05, accessory: 'hat' } },
{ id: 'purr', name: 'Princess Purr', emoji: '👑', voice: 0.75, speed: 0.8, special: 'tripper', look: { top: '#ffa45e', bottom: '#ffd6e8', eye: '#7a3a8a', scale: 0.95, accessory: 'crown', furLen: 1.15 } },
{ id: 'jellybean', name: 'Jellybean', emoji: '🍬', voice: 0.85, speed: 0.82, special: 'jitter', look: { top: '#ff8f4a', bottom: '#dcefff', split: 0.1, eye: '#2b5a9a', scale: 0.85, accessory: 'bow' } },
{ id: 'cinnamon', name: 'Cinnamon', emoji: '💤', voice: 0.3, speed: 1.15, special: 'sleeper', look: { top: '#d9772f', bottom: '#ffe9cc', scale: 1.05, accessory: 'nightcap', stripes: 1 } },
{ id: 'sparkle', name: 'Sparkle', emoji: '✨', voice: 0.9, speed: 0.78, special: 'sparkle', look: { top: '#ffab52', bottom: '#eee2ff', eye: '#5a3a9a', scale: 0.9, accessory: 'star', glow: 0.18 } },
{ id: 'fluffington', name: 'Sir Fluffington', emoji: '🧐', voice: 0.2, speed: 0.75, special: 'statue', look: { top: '#f29240', bottom: C, stripes: 1, split: -0.3, scale: 1.2, accessory: 'monocle' } },
{ id: 'golden', name: 'Golden Fluff', emoji: '🌟', voice: 0.7, speed: 0.95, special: 'golden', look: { top: '#ffd23f', bottom: '#fffbe8', scale: 1.1, accessory: 'wings', glow: 0.35, furLen: 1.25, eye: '#2b3a7a' } },
];
export type CatState = 'wander' | 'idle' | 'flee' | 'tired' | 'sleep' | 'hide' | 'statue' | 'tease' | 'tag' | 'parade' | 'dance' | 'party' | 'bonk' | 'waiting' | 'seek';
export interface CatWorld {
level: Level; playerPos: THREE.Vector3; playerSpeed: number; cats: Cat[]; fx: Particles; difficulty: number;
bouncers: Bouncer[]; trail: THREE.Vector3[]; paused: boolean;
}
const tmp = new THREE.Vector3();
let lastMeow = 0;
export class Cat {
rig: CatRig; body: Body; state: CatState = 'wander'; timer = 0; fleeT = 0; caught = false;
home: THREE.Vector3; target = new THREE.Vector3(); yaw = rand() * 6.28; paradeIndex = -1;
tagTarget: Cat | null = null; braveT = 0; jumpQueue: number[] = []; specialT = 0; hideSpot: THREE.Vector3 | null = null;
highlight = 0; id: string; active = true; meowT = 2 + rand() * 6;
constructor(public def: CatDef, public world: CatWorld, spot: THREE.Vector3) {
this.id = def.id;
this.rig = new CatRig(def.look);
this.body = new Body(world.level.world);
this.body.radius = 0.3 * def.look.scale; this.body.height = 0.9 * def.look.scale;
this.body.pos.copy(spot).y += 0.5;
this.home = spot.clone();
this.target.copy(spot);
if (def.special === 'sleeper') this.state = 'sleep';
if (def.special === 'statue') this.state = 'statue';
if (def.special === 'golden') { this.active = false; this.rig.root.visible = false; }
}
get pos() { return this.body.pos; }
/** Resting cats are caught just by touching them (easy for small hands). */
get resting() { return ['tired', 'sleep', 'bonk', 'statue', 'hide', 'idle', 'party', 'seek'].includes(this.state); }
get catchable() { return this.active && !this.caught && this.state !== 'waiting'; }
private say(mood: 'happy' | 'tease' | 'sleepy' | 'surprised' | 'proud', vol = 1) {
const d = this.pos.distanceTo(this.world.playerPos);
const v = clamp(1 - d / 16, 0, 1) * vol;
const now = performance.now();
if (now - lastMeow < 450) return; // never stack meows: keeps the mix clean on phones
if (v > 0.08) { lastMeow = now; audio.meow(this.def.voice, mood, { volume: v * 0.8 }); this.rig.flash('meow', 0.4); }
}
private setState(s: CatState, t = 0) { this.state = s; this.timer = t; }
startParade(index: number) { this.caught = true; this.paradeIndex = index; this.setState('parade'); this.rig.root.visible = true; }
update(dt: number) {
if (!this.active) return;
const W = this.world, p = this.pos, pl = W.playerPos;
const dx = p.x - pl.x, dz = p.z - pl.z; const d = Math.hypot(dx, dz);
const diff = W.difficulty; // 0 easy, 1 medium, 2 hard
const fleeR = (this.braveT > 0 ? 3.2 : 6.5) + diff * 1.2;
const baseSpeed = 7.2 * this.def.speed * (0.68 + diff * 0.15);
this.timer -= dt; this.braveT -= dt; this.specialT -= dt; this.meowT -= dt;
let moveX = 0, moveZ = 0, speed = 0; let pose: Pose = 'stand';
const rig = this.rig;
const sp = this.def.special;
switch (this.state) {
case 'parade': {
const tr = W.trail; const idx = Math.min(tr.length - 1, 3 + (this.paradeIndex + 1) * 7);
const tgt = tr[idx] ?? pl;
tmp.set(tgt.x - p.x, 0, tgt.z - p.z); const l = tmp.length();
if (l > 0.4) { moveX = tmp.x / l; moveZ = tmp.z / l; speed = clamp(l * 3.2, 0, 10); }
if (l > 14) { p.copy(tgt); p.y += 0.5; }
if (this.jumpQueue.length && this.jumpQueue[0] <= 0) { this.jumpQueue.shift(); if (this.body.grounded) this.body.vel.y = 9; }
this.jumpQueue = this.jumpQueue.map(v => v - dt);
rig.face = 'happy'; rig.wag = 2;
if (W.playerSpeed < 0.3 && l < 1.5) pose = 'sit';
// never crowd the player: keep a little circle of space around her and between friends
if (d < 1.8) { moveX += dx / (d || 1) * 1.5; moveZ += dz / (d || 1) * 1.5; speed = Math.max(speed, 3); }
for (const o of W.cats) { if (o === this || o.state !== 'parade') continue; const ox = p.x - o.pos.x, oz = p.z - o.pos.z, od = Math.hypot(ox, oz); if (od < 1.1 && od > 0.001) { moveX += ox / od; moveZ += oz / od; speed = Math.max(speed, 2.5); } }
{ const ml = Math.hypot(moveX, moveZ); if (ml > 1) { moveX /= ml; moveZ /= ml; } }
break;
}
case 'dance': { pose = 'dance'; rig.face = 'happy'; break; }
case 'seek': { // hide and seek: sit very still in the hiding place, tail swishing, giggling now and then
pose = 'sit'; rig.face = d < 6 ? 'smug' : 'normal'; rig.wag = 2.5;
if (this.meowT <= 0) { if (d < 7) { audio.play('giggle', { volume: clamp(1 - d / 7, 0, 0.5) }); rig.flash('smug', 0.8); } this.meowT = 3 + rand() * 3; }
break;
}
case 'party': { // a surprise dance party: cats boogie together until the player comes close
pose = 'dance'; rig.face = 'happy'; rig.wag = 3;
if (this.specialT <= 0) { W.fx.emit(tmp.copy(p).setY(p.y + 1.3), 2, { color: ['#ff7fb0', '#7cc8ff', '#ffe066'], speed: 0.6, up: 1.5, grav: 0, life: 1.2, size: 0.12 }); this.specialT = 0.35; }
if (this.timer <= 0 || d < 3.4) { this.setState(d < 3.4 ? 'flee' : 'wander'); this.fleeT = 0; }
break;
}
case 'statue': {
pose = 'statue'; rig.face = 'smug';
if (d < 3.2) { // the statue sneezes and topples over
audio.play('sneeze', { volume: 0.9 }); W.fx.emit(tmp.copy(p).setY(p.y + 0.9), 24, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 4, size: 0.1 });
rig.flash('surprised', 0.8); this.setState('tired', 5);
}
break;
}
case 'sleep': {
pose = 'sleep'; rig.face = 'sleep';
if (this.specialT <= 0) { if (d < 10) audio.play('snore', { volume: clamp(1 - d / 10, 0, 1) * 0.6 }); this.specialT = 2.6; }
if (sp === 'sleeper' && d < 2.4 && this.wakes < 1) { // zoomies! (only once, then she stays sleepy and easy to catch)
this.wakes++;
rig.flash('surprised', 0.6); this.say('surprised'); this.setState('flee', 3); this.fleeT = 0; this.specialT = 99;
}
break;
}
case 'hide': {
pose = 'sit'; rig.face = 'smug';
if (this.hideSpot) { p.set(this.hideSpot.x, this.hideSpot.y + 2.6, this.hideSpot.z); this.body.vel.set(0, 0, 0); }
rig.wag = 3;
if ((diff > 0 && d < 2.2) || this.timer <= 0) { audio.play('boing'); this.body.vel.set(dx / (d || 1) * 4, 9, dz / (d || 1) * 4); this.say('tease'); this.setState('flee', 0); this.fleeT = 0; this.hideSpot = null; this.braveT = 0; }
break;
}
case 'tired': {
pose = 'flop'; rig.face = 'dizzy';
if (this.timer <= 0) { this.setState('wander'); this.braveT = 3.5; }
break;
}
case 'bonk': {
pose = 'flop'; rig.face = 'dizzy';
if (this.timer <= 0) { this.setState('flee'); this.fleeT = 0; }
break;
}
case 'tease': {
pose = 'wiggle'; rig.face = 'smug';
this.yaw = angleLerp(this.yaw, Math.atan2(-dx, -dz) + Math.PI, damp(8, dt));
if (this.timer <= 0 || d < 3.4) { this.setState('flee'); }
break;
}
case 'tag': {
const t = this.tagTarget;
if (!t || this.timer <= 0 || t.state !== 'flee' || t.caught) { this.setState('wander'); this.tagTarget = null; break; }
tmp.set(t.pos.x - p.x, 0, t.pos.z - p.z); const l = tmp.length();
moveX = tmp.x / (l || 1); moveZ = tmp.z / (l || 1); speed = baseSpeed * 0.85; rig.face = 'happy';
if (l < 0.9) { // tag! roles swap
audio.play('pop', { volume: clamp(1 - d / 18, 0, 0.6) }); W.fx.emit(tmp.copy(t.pos).setY(t.pos.y + 1), 10, { color: '#ffe066', size: 0.1 });
t.tagTarget = this; t.setState('tag', 3); this.setState('flee', 0); this.fleeT = 3; this.tagTarget = null;
}
if (d < fleeR) this.setState('flee');
break;
}
case 'flee': {
this.fleeT += dt;
// flee from player, or from a tagging cat
let ax = dx, az = dz;
const chaser = W.cats.find(c => c.state === 'tag' && c.tagTarget === this);
if (d > fleeR + 4 && chaser) { ax = p.x - chaser.pos.x; az = p.z - chaser.pos.z; }
const al = Math.hypot(ax, az) || 1;
let fx = ax / al, fz = az / al;
const r = Math.hypot(p.x, p.z);
if (r > 22) { fx -= p.x / r * (r - 22) * 0.5; fz -= p.z / r * (r - 22) * 0.5; } // stay on the island
if (sp === 'jitter' && this.specialT <= 0) { this.yaw += (rand() - 0.5) * 2.5; this.specialT = 0.7 + rand(); audio.play('giggle', { volume: clamp(1 - d / 16, 0, 0.6) }); }
const want = Math.atan2(fx, fz);
this.yaw = angleLerp(this.yaw, want, damp(sp === 'jitter' ? 2 : 4, dt));
moveX = Math.sin(this.yaw); moveZ = Math.cos(this.yaw);
speed = baseSpeed * (sp === 'sleeper' && this.timer > 0 ? 1.15 : 1);
rig.face = 'happy';
if (sp === 'popcorn' && this.body.grounded) { this.body.vel.y = diff > 0 ? 7 + rand() * 3 : 4 + rand() * 1.5; if (d < 9) audio.play('pop', { volume: clamp(1 - d / 9, 0, 0.4), pitch: 1.4 }); }
if (sp === 'tripper' && this.fleeT > 2.2 && this.specialT <= 0 && rand() < dt * 0.6) { this.specialT = 5; this.say('surprised'); audio.play('bump'); this.setState('bonk', 1.6); break; }
if (sp === 'sparkle' && this.specialT <= 0) { W.fx.emit(tmp.copy(p).setY(p.y + 0.4), 3, { color: ['#fff07a', '#ffffff', '#ffb3e6'], speed: 0.5, up: 0.6, grav: -0.3, life: 1.8, size: 0.09 }); this.specialT = 0.05; }
if (sp === 'hider' && this.fleeT > 1.2) {
const hs = W.level.hideSpots.find(h => Math.hypot(h.x - p.x, h.z - p.z) < 7 && Math.hypot(h.x - pl.x, h.z - pl.z) > 4);
if (hs) { tmp.set(hs.x - p.x, 0, hs.z - p.z); this.yaw = angleLerp(this.yaw, Math.atan2(tmp.x, tmp.z), damp(10, dt)); moveX = Math.sin(this.yaw); moveZ = Math.cos(this.yaw);
if (tmp.length() < 1.6) { this.hideSpot = hs; audio.play('pop'); this.setState('hide', 14); break; } }
}
if (sp === 'bouncy' && diff > 0 && d < 2.6 && this.body.grounded && this.specialT <= 0) { this.body.vel.y = 12; this.specialT = 3; audio.play('boing', { pitch: 0.7 }); }
if (this.meowT <= 0) { this.say(rand() < 0.5 ? 'tease' : 'happy', 0.8); this.meowT = 2.5 + rand() * 3; }
const tire = (sp === 'tutorial' ? 3 : 3.8 + diff * 1.4) + rand() * 0.5;
if (this.fleeT > tire || (sp === 'sleeper' && this.timer <= 0 && this.timer > -1 && this.fleeT > 2.5)) {
if (sp === 'sleeper') { this.setState('sleep'); this.specialT = 0.5; } else { this.setState('tired', 4.5 - diff); this.say('sleepy', 0.7); }
this.fleeT = 0; break;
}
if (d > fleeR + 6 && !chaser) { this.setState('wander'); this.fleeT = Math.max(0, this.fleeT - 2); }
break;
}
case 'idle':
case 'wander': default: {
if (this.state === 'idle') { pose = this.timer > 1.5 ? 'sit' : 'stand'; if (this.timer <= 0) this.setState('wander'); }
else {
tmp.set(this.target.x - p.x, 0, this.target.z - p.z); const l = tmp.length();
if (l < 0.6 || this.timer < -6) {
const a = rand() * Math.PI * 2, rr = 2 + rand() * 6;
this.target.set(this.home.x + Math.cos(a) * rr, 0, this.home.z + Math.sin(a) * rr);
if (Math.hypot(this.target.x, this.target.z) > 23) this.target.multiplyScalar(0.7);
this.setState(rand() < 0.5 ? 'idle' : 'wander', 2 + rand() * 2);
} else { moveX = tmp.x / l; moveZ = tmp.z / l; speed = 1.6 * (sp === 'popcorn' ? 1.5 : 1); if (sp === 'popcorn' && this.body.grounded && rand() < dt * 2) this.body.vel.y = 6; }
}
rig.face = 'normal';
// surprise dance party when three friends meet
if (rand() < dt * 0.05 && d > 8) {
const group = W.cats.filter(c => c.active && !c.caught && (c.state === 'wander' || c.state === 'idle') && c.pos.distanceTo(p) < 7);
if (group.length >= 3) { for (const c of group.slice(0, 4)) c.setState('party', 6); audio.play('sparkle', { volume: clamp(1 - d / 25, 0.15, 0.6) }); }
}
// play tag with friends
if (rand() < dt * 0.08) {
const other = W.cats.find(c => c !== this && c.active && !c.caught && (c.state === 'wander' || c.state === 'idle') && c.pos.distanceTo(p) < 6);
if (other) { this.tagTarget = other; this.setState('tag', 3.5); other.setState('flee', 0); other.fleeT = 4; audio.play('giggle', { volume: clamp(1 - d / 18, 0, 0.6) }); }
}
if (d < fleeR) {
if (d > 3.5 && rand() < 0.5) { this.say('tease'); this.setState('tease', 0.9 + rand() * 0.6); }
else { this.say('surprised', 0.7); this.setState('flee'); }
}
if (this.meowT <= 0) { this.say('happy', 0.5); this.meowT = 5 + rand() * 6; }
break;
}
}
// pile-up bonks between fleeing cats
if (this.state === 'flee') for (const o of W.cats) {
if (o === this || !o.active || o.caught || o.state !== 'flee') continue;
if (o.pos.distanceTo(p) < (this.body.radius + o.body.radius) * 1.3 && rand() < 0.5) {
audio.play('bump'); W.fx.emit(tmp.copy(p).lerp(o.pos, 0.5).setY(p.y + 1), 8, { color: '#ffe066' });
this.setState('bonk', 1.2); o.setState('bonk', 1.2); this.say('surprised'); break;
}
}
// movement & physics
const b = this.body;
const tx = moveX * speed, tz = moveZ * speed;
b.vel.x += (tx - b.vel.x) * damp(b.grounded ? 10 : 3, dt);
b.vel.z += (tz - b.vel.z) * damp(b.grounded ? 10 : 3, dt);
if (this.state === 'hide') b.vel.set(0, 0, 0);
const blocked = this.state === 'hide' ? false : b.step(dt, 24, W.bouncers);
if (b.bounced) { audio.play('boing', { volume: clamp(1 - d / 18, 0, 0.7) }); this.say('happy', 0.6); }
if (blocked && b.grounded && speed > 0.5) {
// try a jump over the obstacle, otherwise turn
const ahead = b.world.topAt(p.x + moveX * 0.8, p.z + moveZ * 0.8);
if (ahead - p.y <= 2.6 && rand() < 0.7) b.vel.y = 9.5; else { this.yaw += (rand() < 0.5 ? 1 : -1) * 1.4; this.target.copy(this.home); }
}
if (p.y < -6) { p.copy(this.home); p.y += 1; b.vel.set(0, 0, 0); }
if (speed > 0.3) this.yaw = angleLerp(this.yaw, Math.atan2(b.vel.x, b.vel.z), damp(10, dt));
if (this.state === 'tease') this.yaw = Math.atan2(-dx, -dz) + Math.PI;
rig.pose = pose; rig.speed = Math.hypot(b.vel.x, b.vel.z); rig.airborne = !b.grounded; rig.vy = b.vel.y;
rig.root.position.copy(p); rig.root.rotation.y = this.yaw;
rig.root.userData.groundY = isFinite(b.groundY) ? b.world.groundBelow(p.x, p.z, p.y + 0.1) : p.y;
// look at the player when near
const toP = Math.atan2(pl.x - p.x, pl.z - p.z);
rig.lookYaw = d < 9 ? ((toP - this.yaw + Math.PI * 3) % (Math.PI * 2)) - Math.PI : 0;
rig.setMotionDrift(b.vel.x, b.vel.z);
rig.update(dt);
if (b.grounded && rig.airborne === false && Math.abs(b.vel.y) < 0.01 && this.landed === false) { rig.land(); }
this.landed = b.grounded;
}
private landed = true;
wakes = 0;
}
voxels.ts (src/world/voxels.ts)160 lines
// Voxel grid world: storage, collision queries and an instanced soft-block mesh.
import * as THREE from 'three';
import { sharedLight } from '../render/fur';
export const enum B { AIR = 0, GRASS, PINK, CHOCO, SUGAR, CASTLE, PATH, COOKIE, MINT, CLOUD, GOLD, BERRY, LEMON }
/** [topColor, sideColor] for each block type. */
const COLORS: Record<number, [string, string]> = {
[B.GRASS]: ['#9fe6a0', '#e8b98a'],
[B.PINK]: ['#ffb3d1', '#f59bbd'],
[B.CHOCO]: ['#8a5a3c', '#734a31'],
[B.SUGAR]: ['#fff3d6', '#f5e2b8'],
[B.CASTLE]: ['#e6d4ff', '#d2bcf7'],
[B.PATH]: ['#fff0c9', '#f0d9a5'],
[B.COOKIE]: ['#e8b98a', '#d9a574'],
[B.MINT]: ['#bff5e4', '#a3e6d2'],
[B.CLOUD]: ['#ffffff', '#f3ecff'],
[B.GOLD]: ['#ffd95a', '#f2c23a'],
[B.BERRY]: ['#ff8fb1', '#ff7aa2'],
[B.LEMON]: ['#fff59a', '#f7e874'],
};
export class VoxelWorld {
readonly sx: number; readonly sy: number; readonly sz: number;
readonly data: Uint8Array;
/** Bounce strength per block type (trampolines are props, but blocks can bounce too). */
constructor(sx: number, sy: number, sz: number) {
this.sx = sx; this.sy = sy; this.sz = sz;
this.data = new Uint8Array(sx * sy * sz);
}
/** World x,z are centred: block (i,k) covers x in [i - sx/2, i - sx/2 + 1). */
get ox() { return this.sx / 2; }
get oz() { return this.sz / 2; }
idx(i: number, j: number, k: number) { return i + this.sx * (k + this.sz * j); }
get(i: number, j: number, k: number): number {
if (i < 0 || k < 0 || i >= this.sx || k >= this.sz || j >= this.sy) return 0;
if (j < 0) return B.COOKIE;
return this.data[this.idx(i, j, k)];
}
set(i: number, j: number, k: number, t: number) {
if (i < 0 || k < 0 || j < 0 || i >= this.sx || k >= this.sz || j >= this.sy) return;
this.data[this.idx(i, j, k)] = t;
}
solidAt(x: number, y: number, z: number): boolean {
return this.get(Math.floor(x + this.ox), Math.floor(y), Math.floor(z + this.oz)) !== 0;
}
/** Height of the highest solid top at or below y (search down). -Infinity if none. */
groundBelow(x: number, z: number, y: number): number {
const i = Math.floor(x + this.ox), k = Math.floor(z + this.oz);
if (i < 0 || k < 0 || i >= this.sx || k >= this.sz) return -Infinity;
let j = Math.min(this.sy - 1, Math.floor(y));
for (; j >= 0; j--) if (this.data[this.idx(i, j, k)] !== 0) return j + 1;
return -Infinity;
}
/** Top surface of the column (ignores overhangs). */
topAt(x: number, z: number): number { return this.groundBelow(x, z, this.sy); }
blockTop(x: number, z: number): number {
const i = Math.floor(x + this.ox), k = Math.floor(z + this.oz);
for (let j = this.sy - 1; j >= 0; j--) { const t = this.get(i, j, k); if (t) return t; }
return 0;
}
inside(x: number, z: number, margin = 0): boolean {
return x > -this.ox + margin && x < this.ox - margin && z > -this.oz + margin && z < this.oz - margin;
}
fillColumn(i: number, k: number, h: number, top: number, below = B.COOKIE) {
for (let j = 0; j < h; j++) this.set(i, j, k, j === h - 1 ? top : below);
}
box(i0: number, j0: number, k0: number, i1: number, j1: number, k1: number, t: number) {
for (let j = j0; j <= j1; j++) for (let k = k0; k <= k1; k++) for (let i = i0; i <= i1; i++) this.set(i, j, k, t);
}
/** Build one instanced mesh of all exposed blocks. Soft chamfered cubes, top/side colours. */
buildMesh(): THREE.InstancedMesh {
const exposed: number[] = [];
const { sx, sy, sz } = this;
for (let j = 0; j < sy; j++) for (let k = 0; k < sz; k++) for (let i = 0; i < sx; i++) {
const t = this.data[this.idx(i, j, k)];
if (!t) continue;
if (!this.get(i + 1, j, k) || !this.get(i - 1, j, k) || !this.get(i, j + 1, k) || (j > 0 && !this.get(i, j - 1, k)) || !this.get(i, j, k + 1) || !this.get(i, j, k - 1))
exposed.push(i, j, k, t);
}
const n = exposed.length / 4;
const geo = chamferBox(0.1);
const mat = blockMaterial();
const mesh = new THREE.InstancedMesh(geo, mat, n);
const m = new THREE.Matrix4();
const top = new Float32Array(n * 3), side = new Float32Array(n * 3), cover = new Float32Array(n);
const c = new THREE.Color();
for (let q = 0; q < n; q++) {
const i = exposed[q * 4], j = exposed[q * 4 + 1], k = exposed[q * 4 + 2], t = exposed[q * 4 + 3];
m.makeTranslation(i - this.ox + 0.5, j + 0.5, k - this.oz + 0.5);
mesh.setMatrixAt(q, m);
const [tc, sc] = COLORS[t] ?? ['#ff00ff', '#ff00ff'];
// tiny per-block variation keeps the voxels hand-made rather than flat
const v = 0.94 + ((i * 73856093 ^ j * 19349663 ^ k * 83492791) >>> 0) % 100 / 100 * 0.1;
c.set(tc).multiplyScalar(v); top.set([c.r, c.g, c.b], q * 3);
c.set(sc).multiplyScalar(v); side.set([c.r, c.g, c.b], q * 3);
cover[q] = this.get(i, j + 1, k) ? 1 : 0;
}
geo.setAttribute('aTop', new THREE.InstancedBufferAttribute(top, 3));
geo.setAttribute('aSide', new THREE.InstancedBufferAttribute(side, 3));
geo.setAttribute('aCover', new THREE.InstancedBufferAttribute(cover, 1));
mesh.instanceMatrix.needsUpdate = true;
mesh.frustumCulled = false;
return mesh;
}
}
function chamferBox(b: number): THREE.BufferGeometry {
// A cube with bevelled edges built from a low-poly rounded box.
const g = new THREE.BoxGeometry(1, 1, 1, 2, 2, 2);
const p = g.getAttribute('position') as THREE.BufferAttribute;
const v = new THREE.Vector3();
for (let i = 0; i < p.count; i++) {
v.fromBufferAttribute(p, i);
const ax = Math.abs(v.x), ay = Math.abs(v.y), az = Math.abs(v.z);
// pull mid-edge vertices in to bevel the corners
const edges = (ax > 0.49 ? 1 : 0) + (ay > 0.49 ? 1 : 0) + (az > 0.49 ? 1 : 0);
if (edges >= 2) v.multiplyScalar(1 - b * (edges === 3 ? 0.9 : 0.6));
p.setXYZ(i, v.x, v.y, v.z);
}
g.computeVertexNormals();
return g;
}
function blockMaterial(): THREE.ShaderMaterial {
return new THREE.ShaderMaterial({
uniforms: { ...sharedLight },
vertexShader: /* glsl */`
attribute vec3 aTop; attribute vec3 aSide; attribute float aCover;
varying vec3 vCol; varying vec3 vN; varying vec3 vWorld; varying vec3 vLocal;
void main(){
vec4 w = modelMatrix * instanceMatrix * vec4(position,1.0);
vWorld = w.xyz; vN = normalize(mat3(modelMatrix) * mat3(instanceMatrix) * normal);
vLocal = position;
float isTop = step(0.6, normal.y) * (1.0 - aCover);
// frosting drips: the top colour spills a little way down the sides
float drip = (1.0 - aCover) * step(0.32 + 0.1*sin(position.x*9.0 + position.z*7.0 + instanceMatrix[3].x*3.1), position.y);
vCol = mix(aSide, aTop, max(isTop, drip));
gl_Position = projectionMatrix * viewMatrix * w;
}`,
fragmentShader: /* glsl */`
uniform vec3 uSunDir; uniform vec3 uSunColor; uniform vec3 uSky; uniform vec3 uGround;
uniform vec3 uFogColor; uniform float uFogNear; uniform float uFogFar;
varying vec3 vCol; varying vec3 vN; varying vec3 vWorld; varying vec3 vLocal;
void main(){
vec3 N = normalize(vN);
float diff = clamp((dot(N,uSunDir)+0.35)/1.35,0.0,1.0);
vec3 amb = mix(uGround,uSky,N.y*0.5+0.5)*0.6;
// soft edge darkening gives each block a pillowy look
float edge = max(max(abs(vLocal.x),abs(vLocal.y)),abs(vLocal.z));
float e2 = (abs(vLocal.x)>0.44?1.0:0.0)+(abs(vLocal.y)>0.44?1.0:0.0)+(abs(vLocal.z)>0.44?1.0:0.0);
vec3 c = vCol * (amb + uSunColor*diff*0.75) * (1.0 - 0.07*step(1.5,e2));
float fog = smoothstep(uFogNear, uFogFar, length(cameraPosition - vWorld));
gl_FragColor = vec4(mix(c,uFogColor,fog),1.0);
#include <colorspace_fragment>
}`,
});
}
village.ts (src/world/village.ts)240 lines
// Cupcake Village: the first island. Pure data generation + prop meshes.
import * as THREE from 'three';
import { B, VoxelWorld } from './voxels';
import { mulberry32 } from '../core/util';
import { softMaterial, furMaterial, furSphere } from '../render/fur';
import type { Bouncer } from '../physics/body';
export interface Level {
world: VoxelWorld;
group: THREE.Group;
bouncers: Bouncer[];
trampolineMeshes: { mesh: THREE.Object3D; b: Bouncer }[];
candySpots: THREE.Vector3[];
catSpots: THREE.Vector3[];
hideSpots: THREE.Vector3[]; // giant cupcakes a cat can hide in
spawn: THREE.Vector3;
princessSpot: THREE.Vector3;
pedestal: THREE.Vector3;
castle: THREE.Vector3;
animated: ((t: number, dt: number) => void)[];
/** Candy trees: the game hides any tree that comes between the camera and the player. */
trees: { pos: THREE.Vector3; crown: THREE.Group; idx: number; hidden: boolean }[];
trunks: THREE.InstancedMesh;
/** Giant cupcakes: hidden like trees when they block the view. */
cups: THREE.Object3D[];
}
export function buildVillage(seed = 7): Level {
const SX = 76, SY = 18, SZ = 76;
const w = new VoxelWorld(SX, SY, SZ);
const r = mulberry32(seed);
const group = new THREE.Group();
const cx = SX / 2, cz = SZ / 2;
const heights: number[][] = [];
// rolling hills: sum of soft bumps, clipped by an island mask
const bumps = Array.from({ length: 14 }, () => ({ x: (r() - 0.5) * 56, z: (r() - 0.5) * 56, h: 1 + r() * 3.2, s: 5 + r() * 7 }));
for (let i = 0; i < SX; i++) {
heights[i] = [];
for (let k = 0; k < SZ; k++) {
const x = i - cx + 0.5, z = k - cz + 0.5;
const d = Math.hypot(x, z * 1.05) + Math.sin(Math.atan2(z, x) * 5) * 1.8;
let h = 0;
if (d < 33) {
h = 3;
for (const b of bumps) { const q = Math.hypot(x - b.x, z - b.z) / b.s; if (q < 1) h += b.h * (1 - q * q) * (1 - q * q); }
// keep the centre plaza flat and low; terraces become 1-block steps
const plaza = Math.hypot(x, z - 4);
if (plaza < 9) h = 3;
h = Math.round(h);
if (d > 30) h = Math.min(h, 2);
}
heights[i][k] = h;
}
}
// castle plateau to the north
const castle = new THREE.Vector3(0, 0, -21);
for (let i = 0; i < SX; i++) for (let k = 0; k < SZ; k++) {
const x = i - cx + 0.5, z = k - cz + 0.5;
if (Math.abs(x) < 9 && z > -28 && z < -15) heights[i][k] = Math.max(heights[i][k], 5);
}
for (let i = 0; i < SX; i++) for (let k = 0; k < SZ; k++) {
const h = heights[i][k]; if (!h) continue;
const x = i - cx + 0.5, z = k - cz + 0.5;
let top = B.GRASS;
const n = Math.sin(x * 0.35) + Math.cos(z * 0.3);
if (h >= 6) top = B.PINK; else if (n > 1.3) top = B.MINT;
if (Math.hypot(x, z - 4) < 8.5) top = (Math.floor(x) + Math.floor(z)) % 2 ? B.PATH : B.SUGAR;
if (Math.abs(x) < 1.6 && z > -15 && z < -4) top = B.PATH; // path to castle
if (Math.abs(x) < 9 && z > -28 && z < -15) top = B.SUGAR;
w.fillColumn(i, k, h, top, h <= 2 ? B.COOKIE : B.COOKIE);
}
// ramp of steps from plaza up to the castle plateau
for (let s = 0; s < 3; s++) for (let x = -2; x <= 1; x++) { const zi = Math.floor(-15 + s) + cz; w.fillColumn(x + cx, zi, 5 - s, B.PATH); }
// castle: walls, gate, towers
const ci = (x: number) => Math.floor(x + cx), ck = (z: number) => Math.floor(z + cz);
for (let x = -7; x <= 7; x++) for (const z of [-26, -18]) for (let y = 5; y < 8; y++) if (!(z === -18 && Math.abs(x) < 2)) w.set(ci(x), y, ck(z), B.CASTLE);
for (let z = -26; z <= -18; z++) for (const x of [-7, 7]) for (let y = 5; y < 8; y++) w.set(ci(x), y, ck(z), B.CASTLE);
for (let x = -7; x <= 7; x += 2) for (const z of [-26, -18]) if (!(z === -18 && Math.abs(x) < 2)) w.set(ci(x), 8, ck(z), B.CASTLE);
// keep inside
w.box(ci(-3), 5, ck(-25), ci(3), 9, ck(-22), B.CASTLE);
w.box(ci(-2), 10, ck(-24), ci(2), 10, ck(-23), B.BERRY);
// a few block structures: cupcake houses
const houses: [number, number, number][] = [[-14, 10, B.BERRY], [14, 12, B.LEMON], [-18, -4, B.MINT], [17, -6, B.BERRY], [6, 22, B.LEMON]];
for (const [hx, hz, roof] of houses) {
const g = w.topAt(hx, hz);
const base = Math.max(1, g);
w.box(ci(hx - 2), base, ck(hz - 2), ci(hx + 2), base + 2, ck(hz + 2), B.SUGAR);
w.box(ci(hx - 1), base, ck(hz + 2), ci(hx), base + 1, ck(hz + 2), 0); // door
w.box(ci(hx - 2), base + 3, ck(hz - 2), ci(hx + 2), base + 3, ck(hz + 2), roof);
w.box(ci(hx - 1), base + 4, ck(hz - 1), ci(hx + 1), base + 4, ck(hz + 1), roof);
}
// stepping-stone tower with candy on top (jump practice)
const steps: [number, number, number][] = [[-6, 14, 4], [-4, 16, 5], [-2, 18, 6], [0, 20, 7]];
for (const [x, z, h] of steps) w.box(ci(x), 0, ck(z), ci(x), h - 1, ck(z), B.LEMON);
const mesh = w.buildMesh();
group.add(mesh);
// --- props ---------------------------------------------------------------
const animated: ((t: number, dt: number) => void)[] = [];
const hideSpots: THREE.Vector3[] = [];
const bouncers: Bouncer[] = [];
const trampolineMeshes: { mesh: THREE.Object3D; b: Bouncer }[] = [];
const free = (x: number, z: number) => w.topAt(x, z) > 0 && Math.hypot(x, z - 4) > 12 && !(Math.abs(x) < 10 && z < -14 && z > -29) && !houses.some(([hx, hz]) => Math.abs(hx - x) < 4 && Math.abs(hz - z) < 4);
// candy trees (lollipops + cotton-candy puffs), instanced trunks
const treeSpots: THREE.Vector3[] = [];
for (let n = 0; n < 400 && treeSpots.length < 18; n++) {
const x = (r() - 0.5) * 58, z = (r() - 0.5) * 58;
if (!free(x, z) || Math.hypot(x, z) > 29) continue;
if (treeSpots.some(p => p.distanceTo(new THREE.Vector3(x, p.y, z)) < 6.5)) continue;
treeSpots.push(new THREE.Vector3(x, w.topAt(x, z), z));
}
const trunkGeo = new THREE.CylinderGeometry(0.16, 0.22, 2.4, 8);
const trunks = new THREE.InstancedMesh(trunkGeo, softMaterial('#fff4f0'), treeSpots.length);
const puffCols = ['#ffb3d9', '#b8e6ff', '#d7c2ff', '#fff1a6', '#b9f5d0'];
const puffGeo = new THREE.IcosahedronGeometry(1, 2);
const m4 = new THREE.Matrix4();
const trees: Level['trees'] = [];
treeSpots.forEach((p, idx) => {
m4.makeTranslation(p.x, p.y + 1.2, p.z); trunks.setMatrixAt(idx, m4);
const col = puffCols[idx % puffCols.length];
const lolli = idx % 3 === 0;
const crown = new THREE.Group(); crown.position.set(p.x, p.y + 2.6, p.z);
if (lolli) {
const disk = new THREE.Mesh(new THREE.CylinderGeometry(1.1, 1.1, 0.35, 24), softMaterial(col, 0.8));
disk.rotation.x = Math.PI / 2; crown.add(disk);
const sw = new THREE.Mesh(new THREE.TorusGeometry(0.62, 0.12, 6, 24), softMaterial('#ffffff', 0.6)); sw.position.z = 0.19; crown.add(sw);
const sw2 = sw.clone(); sw2.position.z = -0.19; crown.add(sw2);
crown.position.y += 0.3;
animated.push((t) => { crown.rotation.y = Math.sin(t * 0.5 + idx) * 0.6; });
} else {
for (let q = 0; q < 5; q++) {
const s = new THREE.Mesh(puffGeo, softMaterial(col, 0.2)); const a = q / 5 * Math.PI * 2;
s.position.set(Math.cos(a) * 0.7, (q % 2) * 0.4, Math.sin(a) * 0.7); s.scale.setScalar(0.85 + (q % 3) * 0.15); crown.add(s);
}
const topP = new THREE.Mesh(puffGeo, softMaterial(col, 0.2)); topP.position.y = 0.8; crown.add(topP);
animated.push((t) => { crown.scale.setScalar(1 + Math.sin(t * 1.5 + idx) * 0.03); });
}
group.add(crown); trees.push({ pos: p, crown, idx, hidden: false });
});
group.add(trunks);
// giant cupcakes: hiding spots
const cups: THREE.Object3D[] = [];
const cupSpots: [number, number][] = [[-22, 4], [21, 6], [-9, -10], [10, 18], [-12, 24]];
for (const [x, z] of cupSpots) {
const y = w.topAt(x, z);
const cup = makeCupcake(); cup.position.set(x, y, z); group.add(cup); cups.push(cup);
hideSpots.push(new THREE.Vector3(x, y, z));
}
// marshmallow trampolines
const trampSpots: [number, number][] = [[6, 9], [-8, 2], [-20, 15], [22, -14], [0, -12.5], [-24, -12]];
for (const [x, z] of trampSpots) {
const y = w.topAt(x, z);
const g = new THREE.Group(); g.position.set(x, y, z);
const base = new THREE.Mesh(new THREE.CylinderGeometry(1.1, 1.2, 0.5, 20), softMaterial('#fffaf5', 0.3)); base.position.y = 0.25; g.add(base);
const topM = new THREE.Mesh(new THREE.CylinderGeometry(1.05, 1.05, 0.12, 20), softMaterial('#ff9ccf', 0.5)); topM.position.y = 0.52; g.add(topM);
group.add(g);
const b: Bouncer = { x, z, r: 1.15, top: y + 0.55, power: 15, squash: 0 };
bouncers.push(b); trampolineMeshes.push({ mesh: g, b });
animated.push((_t, dt) => { b.squash = Math.max(0, b.squash - dt * 3); const s = Math.sin(b.squash * Math.PI * 2) * 0.25 * b.squash; g.scale.set(1 + s, 1 - s * 1.5, 1 + s); });
}
// castle towers
for (const [x, z] of [[-7, -26], [7, -26], [-7, -18], [7, -18]] as [number, number][]) {
const t = new THREE.Group(); t.position.set(x + 0.5, 5, z + 0.5);
const body = new THREE.Mesh(new THREE.CylinderGeometry(1.4, 1.5, 5, 16), softMaterial('#f1e4ff', 0.2)); body.position.y = 2.5; t.add(body);
const roof = new THREE.Mesh(new THREE.ConeGeometry(1.8, 2.8, 16), softMaterial('#ff8fc4', 0.5)); roof.position.y = 6.4; t.add(roof);
const flag = new THREE.Mesh(new THREE.PlaneGeometry(0.9, 0.5), softMaterial('#ffd34d', 0, 0.2)); flag.position.set(0.45, 8.1, 0); (flag.material as THREE.ShaderMaterial).side = THREE.DoubleSide; t.add(flag);
animated.push((tt) => { flag.rotation.y = Math.sin(tt * 3 + x) * 0.4; });
group.add(t);
}
// rainbow arch over the castle path
const cols = ['#ff7a9c', '#ffb36b', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'];
cols.forEach((c, i) => { const a = new THREE.Mesh(new THREE.TorusGeometry(6.5 - i * 0.35, 0.18, 8, 40, Math.PI), softMaterial(c, 0.3, 0.15)); a.position.set(0, 5, -15.5); group.add(a); });
// cotton-candy cloud sea + floating clouds
const cloudMat = softMaterial('#fff4fb', 0.1, 0.05);
const cloudGeo = new THREE.IcosahedronGeometry(1, 2);
const clouds = new THREE.InstancedMesh(cloudGeo, cloudMat, 140);
for (let q = 0; q < 140; q++) {
const a = q / 140 * Math.PI * 2 + r() * 0.1, d = 36 + r() * 14;
const s = 2.5 + r() * 3.5;
m4.compose(new THREE.Vector3(Math.cos(a) * d, -1.5 - r() * 2, Math.sin(a) * d), new THREE.Quaternion(), new THREE.Vector3(s * 1.3, s * 0.6, s));
clouds.setMatrixAt(q, m4);
}
group.add(clouds);
for (let q = 0; q < 9; q++) {
const c = new THREE.Group();
for (let p = 0; p < 5; p++) { const s = new THREE.Mesh(cloudGeo, cloudMat); s.position.set((p - 2) * 1.6, Math.sin(p) * 0.5, (r() - 0.5)); s.scale.setScalar(1.3 + r()); c.add(s); }
const a = r() * Math.PI * 2, d = 25 + r() * 30;
c.position.set(Math.cos(a) * d, 16 + r() * 10, Math.sin(a) * d);
group.add(c);
animated.push((t) => { c.position.x += Math.sin(t * 0.1 + q) * 0.004; });
}
// flowers: tiny instanced puffs on grass
const fl = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(0.16, 1), new THREE.MeshLambertMaterial({ color: '#ffffff', emissive: '#ff9fd0', emissiveIntensity: 0.25 }), 260);
const fc = new THREE.Color();
let fi = 0;
for (let n = 0; n < 2000 && fi < 260; n++) {
const x = (r() - 0.5) * 60, z = (r() - 0.5) * 60;
if (w.blockTop(x, z) !== B.GRASS && w.blockTop(x, z) !== B.MINT) continue;
m4.makeTranslation(x, w.topAt(x, z) + 0.12, z); fl.setMatrixAt(fi, m4);
fl.setColorAt(fi, fc.set(puffCols[fi % puffCols.length])); fi++;
}
fl.count = fi; group.add(fl);
// candies: lines and arcs that guide exploration
const candySpots: THREE.Vector3[] = [];
const addC = (x: number, z: number, lift = 0.8) => { if (!w.inside(x, z, 2)) return; const y = w.topAt(x, z); if (y <= 0) return; candySpots.push(new THREE.Vector3(x, y + lift, z)); };
for (let i = 0; i < 6; i++) addC(0, 1 - i * 2.2); // plaza -> castle
for (let i = 0; i < 8; i++) { const a = i / 8 * Math.PI * 2; addC(Math.cos(a) * 12, 4 + Math.sin(a) * 12); } // ring round plaza
for (const [x, z, h] of steps) candySpots.push(new THREE.Vector3(x + 0.5, h + 0.8, z + 0.5));
for (const [x, z] of trampSpots) { candySpots.push(new THREE.Vector3(x, w.topAt(x, z) + 4.5, z)); candySpots.push(new THREE.Vector3(x, w.topAt(x, z) + 6, z)); }
for (const [hx, hz] of houses) candySpots.push(new THREE.Vector3(hx + 0.5, w.topAt(hx, hz) + 0.8, hz + 0.5));
for (let i = 0; i < 5; i++) addC(-3 + i * 1.5, -22); // castle yard
for (let i = 0; i < 14; i++) { const a = r() * Math.PI * 2, d = 14 + r() * 14; addC(Math.cos(a) * d, Math.sin(a) * d); }
// cat starting spots spread around the island
const catSpots: THREE.Vector3[] = [];
const want: [number, number][] = [[3, 9], [-12, 5], [15, 2], [-6, -6], [18, 16], [-16, 18], [8, -10], [-20, -8], [0, -22], [22, -2], [-2, 26], [12, 24]];
for (const [x, z] of want) catSpots.push(new THREE.Vector3(x, w.topAt(x, z), z));
return {
world: w, group, bouncers, trampolineMeshes, candySpots, catSpots, hideSpots,
spawn: new THREE.Vector3(0, 3, 6), princessSpot: new THREE.Vector3(-3, 3, 1.5), pedestal: new THREE.Vector3(0, 3, 3), castle, animated, trees, trunks, cups,
};
}
export function makeCupcake(): THREE.Group {
const g = new THREE.Group();
const wrap = new THREE.Mesh(new THREE.CylinderGeometry(1.5, 1.1, 1.6, 18), softMaterial('#ff9fc9', 0.3)); wrap.position.y = 0.8; g.add(wrap);
for (let i = 0; i < 18; i++) { const rib = new THREE.Mesh(new THREE.BoxGeometry(0.08, 1.6, 0.08), softMaterial('#ffd1e6')); const a = i / 18 * Math.PI * 2; rib.position.set(Math.cos(a) * 1.32, 0.8, Math.sin(a) * 1.32); rib.rotation.z = Math.cos(a) * -0.24; rib.rotation.x = Math.sin(a) * 0.24; g.add(rib); }
const frost = furMaterial({ top: '#fff7fb', bottom: '#ffe3f0', length: 0.12, density: 12 });
for (let i = 0; i < 4; i++) { const t = new THREE.Mesh(furSphere(), frost); t.scale.set(1.6 - i * 0.38, 0.55, 1.6 - i * 0.38); t.position.y = 1.7 + i * 0.45; g.add(t); }
const cherry = new THREE.Mesh(new THREE.SphereGeometry(0.3, 14, 10), softMaterial('#ff3d6e', 1.2)); cherry.position.y = 3.3; g.add(cherry);
for (let i = 0; i < 14; i++) { const s = new THREE.Mesh(new THREE.CapsuleGeometry(0.04, 0.12, 2, 4), softMaterial(['#7cc8ff', '#ffe57a', '#8fe39b', '#b79bff'][i % 4], 0, 0.2)); const a = i * 2.4; s.position.set(Math.cos(a) * (0.5 + (i % 3) * 0.3), 2.3 + (i % 4) * 0.25, Math.sin(a) * (0.5 + (i % 3) * 0.3)); s.rotation.set(a, i, 0); g.add(s); }
return g;
}
body.ts (src/physics/body.ts)78 lines
// Kinematic character body that walks on the voxel world: gravity, auto-step, walls.
import * as THREE from 'three';
import type { VoxelWorld } from '../world/voxels';
export interface Bouncer { x: number; z: number; r: number; top: number; power: number; onBounce?: () => void; squash: number }
export class Body {
pos = new THREE.Vector3();
vel = new THREE.Vector3();
radius = 0.32;
height = 1.0;
grounded = false;
groundY = 0;
stepUp = 1.05; // can walk up one block (auto-hop) - forgiving for kids
lastSafe = new THREE.Vector3();
timeSinceGround = 0;
bounced = false;
wading = 0;
constructor(public world: VoxelWorld) {}
private blockedAt(x: number, z: number, feet: number): boolean {
const w = this.world, r = this.radius;
for (let y = feet + 0.05; y < feet + this.height; y += 0.45) {
if (w.solidAt(x + r, y, z) || w.solidAt(x - r, y, z) || w.solidAt(x, y, z + r) || w.solidAt(x, y, z - r)) return true;
}
return false;
}
private groundUnder(x: number, z: number, y: number): number {
const w = this.world, r = this.radius * 0.7;
return Math.max(w.groundBelow(x, z, y), w.groundBelow(x + r, z, y), w.groundBelow(x - r, z, y), w.groundBelow(x, z + r, y), w.groundBelow(x, z - r, y));
}
/** Move by velocity. Returns true when a wall stopped horizontal motion. */
step(dt: number, gravity: number, bouncers: Bouncer[] = []): boolean {
const p = this.pos, v = this.vel;
v.y -= gravity * dt;
if (v.y < -30) v.y = -30;
let hitWall = false;
const tryAxis = (dx: number, dz: number) => {
const nx = p.x + dx, nz = p.z + dz;
if (!this.world.inside(nx, nz, 0.5)) { hitWall = true; return; }
if (!this.blockedAt(nx, nz, p.y)) { p.x = nx; p.z = nz; return; }
// auto step: if the obstacle is low enough and we are on/near ground, climb it smoothly
const g = this.groundUnder(nx, nz, p.y + this.stepUp);
if ((this.grounded || this.timeSinceGround < 0.15) && g - p.y <= this.stepUp && !this.blockedAt(nx, nz, g)) {
p.y = Math.max(p.y, g); p.x = nx; p.z = nz; return;
}
hitWall = true;
};
const steps = Math.max(1, Math.ceil(Math.hypot(v.x, v.z) * dt / 0.2));
for (let s = 0; s < steps; s++) { tryAxis(v.x * dt / steps, 0); tryAxis(0, v.z * dt / steps); }
const ny = p.y + v.y * dt;
const g = this.groundUnder(p.x, p.z, p.y + 0.05);
this.bounced = false;
if (v.y <= 0 && ny <= g) {
p.y = g; v.y = 0;
if (!this.grounded) this.grounded = true;
this.groundY = g;
} else {
// head bump
if (v.y > 0 && this.blockedAt(p.x, p.z, ny + 0.02) && this.world.solidAt(p.x, ny + this.height, p.z)) { v.y = 0; }
else p.y = ny;
this.grounded = p.y <= g + 0.001;
}
// marshmallow trampolines
for (const b of bouncers) {
const dx = p.x - b.x, dz = p.z - b.z;
if (dx * dx + dz * dz < b.r * b.r && p.y <= b.top + 0.05 && p.y >= b.top - 0.6 && v.y <= 0) {
p.y = b.top; v.y = b.power; this.grounded = false; this.bounced = true; b.squash = 1; b.onBounce?.();
}
}
if (this.grounded) { this.timeSinceGround = 0; if (g > -5) this.lastSafe.copy(p); } else this.timeSinceGround += dt;
return hitWall;
}
}
player.ts (src/player/player.ts)135 lines
// The Royal Fluff Catcher: a chibi kid in a fluffy cat-ear hoodie, plus movement.
import * as THREE from 'three';
import { Body } from '../physics/body';
import type { Bouncer } from '../physics/body';
import type { VoxelWorld } from '../world/voxels';
import { furCone, furMaterial, furSphere, softMaterial } from '../render/fur';
import { angleLerp, clamp, damp, lerp } from '../core/util';
import type { InputState } from '../input/input';
export class Player {
root = new THREE.Group();
body: Body;
yaw = 0;
private pivot = new THREE.Group();
private head = new THREE.Group();
private legs: THREE.Mesh[] = [];
private arms: THREE.Group[] = [];
private eyes: THREE.Mesh[] = [];
private shadow: THREE.Mesh;
crownSlot = new THREE.Group();
hatSlot = new THREE.Group();
hood: THREE.ShaderMaterial;
drift = { value: new THREE.Vector3() };
private phase = 0; private t = 0;
private coyote = 0; private buffer = 0;
private squash = 0;
floating = false;
pounceT = 0; pounceDir = new THREE.Vector3();
hugT = 0;
happyT = 0;
speedMul = 1;
justLanded = false; justJumped = false;
private wasGrounded = true;
stepDist = 0;
constructor(world: VoxelWorld, hoodColor = '#c9a8ff') {
this.body = new Body(world);
this.body.radius = 0.34; this.body.height = 1.5;
this.root.add(this.pivot);
const hood = furMaterial({ top: hoodColor, bottom: '#fff2fb', axis: new THREE.Vector3(0, -1, 0), split: 0.6, length: 0.16, density: 26, drift: this.drift });
this.hood = hood;
const sph = furSphere();
const torso = new THREE.Mesh(sph, hood); torso.scale.set(0.36, 0.38, 0.32); torso.position.y = 0.6; this.pivot.add(torso);
const tummy = new THREE.Mesh(new THREE.SphereGeometry(0.2, 14, 10), softMaterial('#fff2fb')); tummy.scale.set(1, 1.1, 0.5); tummy.position.set(0, 0.55, 0.26); this.pivot.add(tummy);
this.head.position.y = 1.18; this.pivot.add(this.head);
const face = new THREE.Mesh(new THREE.SphereGeometry(0.34, 24, 18), softMaterial('#ffe2cf', 0.1)); face.scale.set(1, 0.95, 0.95); this.head.add(face);
const hoodBack = new THREE.Mesh(sph, hood); hoodBack.scale.set(0.42, 0.42, 0.4); hoodBack.position.set(0, 0.04, -0.07); this.head.add(hoodBack);
// trim the hood so the face shows: a cream fluffy rim
const rim = new THREE.Mesh(new THREE.TorusGeometry(0.3, 0.07, 8, 24), furMaterial({ top: '#fff7fd', bottom: '#fff7fd', length: 0.5, density: 40, drift: this.drift })); rim.position.z = 0.2; this.head.add(rim);
for (const sx of [-1, 1]) {
const ear = new THREE.Mesh(furCone(), hood); ear.scale.set(0.13, 0.15, 0.08); ear.position.set(sx * 0.26, 0.42, -0.04); ear.rotation.z = -sx * 0.35; this.head.add(ear);
const eye = new THREE.Mesh(new THREE.SphereGeometry(0.055, 12, 10), softMaterial('#3a2340', 1.2)); eye.scale.set(0.85, 1.15, 0.5); eye.position.set(sx * 0.11, 0.02, 0.31); this.head.add(eye); this.eyes.push(eye);
const hl = new THREE.Mesh(new THREE.SphereGeometry(0.018, 6, 4), softMaterial('#ffffff', 0, 2)); hl.position.set(sx * 0.11 + 0.015, 0.05, 0.345); this.head.add(hl);
const blush = new THREE.Mesh(new THREE.SphereGeometry(0.05, 10, 6), softMaterial('#ff9ec0', 0, 0.2)); blush.scale.set(1, 0.5, 0.3); blush.position.set(sx * 0.19, -0.07, 0.28); this.head.add(blush);
const leg = new THREE.Mesh(new THREE.CapsuleGeometry(0.1, 0.18, 4, 10), softMaterial('#7b5cc4')); leg.position.set(sx * 0.14, 0.17, 0); this.pivot.add(leg); this.legs.push(leg);
const arm = new THREE.Group(); arm.position.set(sx * 0.33, 0.78, 0); this.pivot.add(arm);
const a = new THREE.Mesh(sph, hood); a.scale.set(0.1, 0.2, 0.1); a.position.y = -0.17; arm.add(a);
const paw = new THREE.Mesh(new THREE.SphereGeometry(0.09, 10, 8), softMaterial('#fff2fb')); paw.position.y = -0.36; arm.add(paw);
arm.rotation.z = sx * 0.4; this.arms.push(arm);
}
const smile = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.014, 6, 12, Math.PI), softMaterial('#9a3d5c')); smile.rotation.z = Math.PI; smile.position.set(0, -0.08, 0.32); this.head.add(smile);
// fluffy tail on the hoodie
const tail = new THREE.Mesh(sph, hood); tail.scale.set(0.13, 0.13, 0.13); tail.position.set(0, 0.42, -0.34); this.pivot.add(tail);
this.crownSlot.position.y = 0.42; this.head.add(this.crownSlot);
this.hatSlot.position.y = 0.36; this.head.add(this.hatSlot);
this.shadow = new THREE.Mesh(new THREE.CircleGeometry(0.45, 20), new THREE.MeshBasicMaterial({ color: '#7a4a6a', transparent: true, opacity: 0.25, depthWrite: false }));
this.shadow.rotation.x = -Math.PI / 2;
}
/** Change the hoodie colours (wardrobe). */
setHood(top: string, bottom = '#fff2fb') { (this.hood.uniforms.uTop.value as THREE.Color).set(top); (this.hood.uniforms.uBottom.value as THREE.Color).set(bottom); }
setHat(hat: THREE.Object3D | null) { this.hatSlot.clear(); if (hat) this.hatSlot.add(hat); }
/** camYaw = camera yaw; moves relative to camera. Returns horizontal speed. */
update(dt: number, inp: InputState, camYaw: number, bouncers: Bouncer[], allowJump: boolean) {
this.t += dt;
const b = this.body;
this.justLanded = false; this.justJumped = false;
const fwdX = -Math.sin(camYaw), fwdZ = -Math.cos(camYaw);
const rgtX = Math.cos(camYaw), rgtZ = -Math.sin(camYaw);
let wx = fwdX * inp.moveY + rgtX * inp.moveX, wz = fwdZ * inp.moveY + rgtZ * inp.moveX;
const mag = Math.min(1, Math.hypot(wx, wz));
const maxSp = 7.2 * this.speedMul;
let tx = wx * maxSp, tz = wz * maxSp;
if (this.pounceT > 0) { this.pounceT -= dt; tx = this.pounceDir.x * 9; tz = this.pounceDir.z * 9; }
const accel = b.grounded ? 14 : 6;
b.vel.x = lerp(b.vel.x, tx, damp(accel, dt)); b.vel.z = lerp(b.vel.z, tz, damp(accel, dt));
if (this.hugT > 0) { this.hugT -= dt; b.vel.x *= 0.8; b.vel.z *= 0.8; }
if (mag > 0.1 && this.hugT <= 0) this.yaw = angleLerp(this.yaw, Math.atan2(wx, wz), damp(12, dt));
else if (this.pounceT > 0) this.yaw = angleLerp(this.yaw, Math.atan2(this.pounceDir.x, this.pounceDir.z), damp(16, dt));
// jump with coyote time + buffering; hold = fluffy float
this.coyote = b.grounded ? 0.13 : this.coyote - dt;
this.buffer = inp.actionPressed && allowJump ? 0.15 : this.buffer - dt;
if (this.buffer > 0 && this.coyote > 0) { b.vel.y = 10.5; this.coyote = 0; this.buffer = 0; b.grounded = false; this.justJumped = true; }
this.floating = !b.grounded && inp.action && b.vel.y < 0;
let grav = 27;
if (this.floating) { grav = 7; if (b.vel.y < -2.2) b.vel.y = lerp(b.vel.y, -2.2, damp(10, dt)); }
else if (b.vel.y > 0 && !inp.action) grav = 42; // short hop if released early
b.step(dt, grav, bouncers);
if (b.grounded && !this.wasGrounded) { this.justLanded = true; this.squash = 1; }
this.wasGrounded = b.grounded;
// animate
const sp = Math.hypot(b.vel.x, b.vel.z);
this.stepDist += sp * dt;
this.phase += dt * (3 + sp * 2.1);
const run = clamp(sp / 6, 0, 1) * (b.grounded ? 1 : 0.2);
this.squash = Math.max(0, this.squash - dt * 4);
const sq = Math.sin(this.squash * Math.PI) * 0.22;
this.root.position.copy(b.pos);
this.root.rotation.y = this.yaw;
this.pivot.position.y = Math.abs(Math.sin(this.phase)) * 0.12 * run;
const air = b.grounded ? 0 : clamp(b.vel.y * 0.03, -0.15, 0.18);
this.pivot.scale.set(1 + sq - air * 0.5, 1 - sq + air, 1 + sq);
this.pivot.rotation.x = run * 0.15 + (this.pounceT > 0 ? 0.5 : 0);
this.legs.forEach((l, i) => { l.position.z = Math.sin(this.phase + i * Math.PI) * 0.17 * run; l.position.y = 0.17 + Math.max(0, Math.sin(this.phase + i * Math.PI)) * 0.08 * run + (b.grounded ? 0 : 0.06); });
this.arms.forEach((a, i) => {
const sx = i ? 1 : -1;
a.rotation.x = -Math.sin(this.phase + i * Math.PI) * 0.8 * run + (this.floating ? 0 : 0) + (this.hugT > 0 ? -1.3 : 0) + (this.pounceT > 0 ? -1.6 : 0);
a.rotation.z = sx * (0.4 + (this.floating ? 1.9 + Math.sin(this.t * 18) * 0.25 : 0) + (!b.grounded && !this.floating ? 0.8 : 0) + (this.happyT > 0 ? 2.2 + Math.sin(this.t * 14) * 0.3 : 0)) - (this.hugT > 0 ? sx * 0.6 : 0);
});
this.happyT = Math.max(0, this.happyT - dt);
this.head.rotation.z = Math.sin(this.t * 1.7) * 0.05 + (this.happyT > 0 ? Math.sin(this.t * 10) * 0.15 : 0);
const blink = (this.t % 3.7) < 0.12 ? 0.15 : 1;
this.eyes.forEach(e => e.scale.y = (this.happyT > 0 ? 0.35 : 1.15) * blink);
this.drift.value.set(-b.vel.x * 0.012, -0.02 - (b.grounded ? 0 : b.vel.y * 0.004), -b.vel.z * 0.012);
const g = b.world.groundBelow(b.pos.x, b.pos.z, b.pos.y + 0.1);
this.shadow.position.set(b.pos.x, (isFinite(g) ? g : b.pos.y) + 0.03, b.pos.z);
this.shadow.scale.setScalar(clamp(1 - (b.pos.y - g) * 0.12, 0.3, 1));
return sp;
}
get shadowMesh() { return this.shadow; }
}
input.ts (src/input/input.ts)112 lines
// Unified input: keyboard, touch joystick + action button, mouse/touch camera drag, gamepad.
export interface InputState {
moveX: number; moveY: number; // -1..1, y = forward
camX: number; camY: number; // camera drag delta this frame (pixels) or stick
action: boolean; // jump/catch button held
actionPressed: boolean; // went down this frame
pausePressed: boolean;
usedTouch: boolean; moved: boolean;
}
export class Input {
s: InputState = { moveX: 0, moveY: 0, camX: 0, camY: 0, action: false, actionPressed: false, pausePressed: false, usedTouch: false, moved: false };
private keys = new Set<string>();
private joyId: number | null = null; private joyO = { x: 0, y: 0 }; private joyV = { x: 0, y: 0 };
private camId: number | null = null; private camLast = { x: 0, y: 0 }; private camAcc = { x: 0, y: 0 };
private btnDown = false; private prevAction = false; private pauseQ = false; private tapQ = false;
private prevPadPause: boolean[] = [];
/** Player 2: the second connected controller (null when there is none). */
p2: InputState | null = null;
private p2Prev = false;
stickEl: HTMLElement | null = null;
enabled = true;
constructor(private canvas: HTMLElement) {
addEventListener('keydown', e => {
if ((e.target as HTMLElement | null)?.tagName === 'INPUT') return; // typing a cat's name
if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.code)) e.preventDefault();
if (e.code === 'Escape' || e.code === 'KeyP') this.pauseQ = true;
if (!e.repeat && (e.code === 'Space' || e.code === 'Enter' || e.code === 'KeyJ')) this.tapQ = true;
this.keys.add(e.code);
});
addEventListener('keyup', e => this.keys.delete(e.code));
addEventListener('blur', () => { this.keys.clear(); this.btnDown = false; this.joyId = null; this.joyV = { x: 0, y: 0 }; });
canvas.addEventListener('pointerdown', e => {
if (e.pointerType === 'mouse') { this.camId = e.pointerId; this.camLast = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); return; }
this.s.usedTouch = true;
if (e.clientX < innerWidth * 0.5 && this.joyId === null) {
this.joyId = e.pointerId; this.joyO = { x: e.clientX, y: e.clientY }; this.joyV = { x: 0, y: 0 };
if (this.stickEl) { this.stickEl.style.display = 'block'; this.stickEl.style.left = e.clientX + 'px'; this.stickEl.style.top = e.clientY + 'px'; }
} else if (this.camId === null) { this.camId = e.pointerId; this.camLast = { x: e.clientX, y: e.clientY }; }
});
addEventListener('pointermove', e => {
if (e.pointerId === this.joyId) {
let dx = e.clientX - this.joyO.x, dy = e.clientY - this.joyO.y; const R = 55; const l = Math.hypot(dx, dy);
if (l > R) { // dragging far moves the stick base along (floating joystick)
this.joyO.x += dx - dx / l * R; this.joyO.y += dy - dy / l * R; dx = dx / l * R; dy = dy / l * R;
if (this.stickEl) { this.stickEl.style.left = this.joyO.x + 'px'; this.stickEl.style.top = this.joyO.y + 'px'; }
}
this.joyV = { x: dx / R, y: -dy / R };
const knob = this.stickEl?.firstElementChild as HTMLElement | null; if (knob) knob.style.transform = `translate(${dx}px,${dy}px)`;
} else if (e.pointerId === this.camId) {
this.camAcc.x += e.clientX - this.camLast.x; this.camAcc.y += e.clientY - this.camLast.y; this.camLast = { x: e.clientX, y: e.clientY };
}
});
const up = (e: PointerEvent) => {
if (e.pointerId === this.joyId) { this.joyId = null; this.joyV = { x: 0, y: 0 }; if (this.stickEl) this.stickEl.style.display = 'none'; }
if (e.pointerId === this.camId) this.camId = null;
};
addEventListener('pointerup', up); addEventListener('pointercancel', up);
}
bindButton(el: HTMLElement) {
el.addEventListener('pointerdown', e => { e.preventDefault(); e.stopPropagation(); this.btnDown = true; this.tapQ = true; this.s.usedTouch = e.pointerType !== 'mouse' || this.s.usedTouch; try { el.setPointerCapture(e.pointerId); } catch { /* ignore */ } });
const off = () => { this.btnDown = false; };
el.addEventListener('pointerup', off); el.addEventListener('pointercancel', off); el.addEventListener('lostpointercapture', off);
}
update(): InputState {
const s = this.s, k = this.keys;
let mx = (k.has('KeyD') || k.has('ArrowRight') ? 1 : 0) - (k.has('KeyA') || k.has('ArrowLeft') ? 1 : 0);
let my = (k.has('KeyW') || k.has('ArrowUp') ? 1 : 0) - (k.has('KeyS') || k.has('ArrowDown') ? 1 : 0);
let cx = this.camAcc.x + ((k.has('KeyE') ? 1 : 0) - (k.has('KeyQ') ? 1 : 0)) * 8, cy = this.camAcc.y;
this.camAcc = { x: 0, y: 0 };
let act = k.has('Space') || k.has('Enter') || k.has('KeyJ') || this.btnDown;
let pause = this.pauseQ; this.pauseQ = false;
const pads = navigator.getGamepads ? navigator.getGamepads() : [];
const dz = (v: number) => (Math.abs(v) < 0.18 ? 0 : v);
// the first controller plays player 1 (with the keyboard and touch); the second controller plays player 2
let n = 0, p2: InputState | null = null;
for (const p of pads) {
if (!p) continue;
n++;
const pp = !!p.buttons[9]?.pressed; if (pp && !this.prevPadPause[p.index]) pause = true; this.prevPadPause[p.index] = pp;
const b = [0, 1, 2, 3].some(i => p.buttons[i]?.pressed);
if (n === 2) {
let x = dz(p.axes[0] ?? 0), y = -dz(p.axes[1] ?? 0);
if (p.buttons[14]?.pressed) x -= 1; if (p.buttons[15]?.pressed) x += 1; if (p.buttons[12]?.pressed) y += 1; if (p.buttons[13]?.pressed) y -= 1;
const l2 = Math.hypot(x, y); if (l2 > 1) { x /= l2; y /= l2; }
if (!this.enabled) { x = 0; y = 0; }
const a = b && this.enabled;
p2 = { moveX: x, moveY: y, camX: 0, camY: 0, action: a, actionPressed: a && !this.p2Prev, pausePressed: false, usedTouch: false, moved: l2 > 0.2 };
this.p2Prev = a;
continue;
}
if (n > 2) continue;
mx += dz(p.axes[0] ?? 0); my -= dz(p.axes[1] ?? 0);
cx += dz(p.axes[2] ?? 0) * 14; cy += dz(p.axes[3] ?? 0) * 10;
if (p.buttons[14]?.pressed) mx -= 1; if (p.buttons[15]?.pressed) mx += 1; if (p.buttons[12]?.pressed) my += 1; if (p.buttons[13]?.pressed) my -= 1;
act = act || b;
}
if (!p2) this.p2Prev = false;
this.p2 = p2;
mx += this.joyV.x; my += this.joyV.y;
const l = Math.hypot(mx, my); if (l > 1) { mx /= l; my /= l; }
if (!this.enabled) { mx = 0; my = 0; act = false; }
s.moveX = mx; s.moveY = my; s.camX = cx; s.camY = cy;
// a tap that starts and ends between two frames still counts (slow devices)
s.actionPressed = (act && !this.prevAction) || (this.tapQ && this.enabled); s.action = act || (this.tapQ && this.enabled); this.prevAction = act; this.tapQ = false;
s.pausePressed = pause;
if (l > 0.2) s.moved = true;
return s;
}
}
particles.ts (src/fx/particles.ts)46 lines
// Pooled billboard-free particles (tiny meshes in one InstancedMesh): sparkles, hearts, confetti, fluff.
import * as THREE from 'three';
interface P { x: number; y: number; z: number; vx: number; vy: number; vz: number; life: number; max: number; size: number; grav: number; spin: number; r: number; g: number; b: number; drag: number }
export class Particles {
mesh: THREE.InstancedMesh;
private ps: P[] = [];
private m = new THREE.Matrix4(); private q = new THREE.Quaternion(); private e = new THREE.Euler(); private v = new THREE.Vector3(); private sc = new THREE.Vector3(); private c = new THREE.Color();
constructor(private max = 900) {
const geo = new THREE.OctahedronGeometry(1, 0);
this.mesh = new THREE.InstancedMesh(geo, new THREE.MeshBasicMaterial({ color: '#ffffff' }), max);
this.mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3);
this.mesh.frustumCulled = false; this.mesh.count = 0;
}
emit(pos: THREE.Vector3, n: number, o: { color?: string | string[]; speed?: number; up?: number; size?: number; life?: number; grav?: number; spread?: number; drag?: number } = {}) {
for (let i = 0; i < n && this.ps.length < this.max; i++) {
const cols = Array.isArray(o.color) ? o.color : [o.color ?? '#fff6a8'];
this.c.set(cols[(Math.random() * cols.length) | 0]);
const sp = (o.speed ?? 3) * (0.4 + Math.random() * 0.8); const a = Math.random() * Math.PI * 2; const el = (Math.random() - 0.2) * Math.PI * 0.6;
const life = (o.life ?? 1) * (0.6 + Math.random() * 0.6);
const sprd = o.spread ?? 0.2;
this.ps.push({ x: pos.x + (Math.random() - 0.5) * sprd, y: pos.y + (Math.random() - 0.5) * sprd, z: pos.z + (Math.random() - 0.5) * sprd,
vx: Math.cos(a) * Math.cos(el) * sp, vy: Math.sin(el) * sp + (o.up ?? 2), vz: Math.sin(a) * Math.cos(el) * sp,
life, max: life, size: (o.size ?? 0.12) * (0.6 + Math.random() * 0.8), grav: o.grav ?? 4, spin: Math.random() * 10, r: this.c.r, g: this.c.g, b: this.c.b, drag: o.drag ?? 0.5 });
}
}
update(dt: number) {
let n = 0;
for (let i = this.ps.length - 1; i >= 0; i--) {
const p = this.ps[i]; p.life -= dt;
if (p.life <= 0) { this.ps[i] = this.ps[this.ps.length - 1]; this.ps.pop(); continue; }
p.vy -= p.grav * dt; const d = Math.exp(-p.drag * dt); p.vx *= d; p.vz *= d; p.vy *= d;
p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt; p.spin += dt * 6;
}
for (const p of this.ps) {
const k = p.life / p.max; const s = p.size * Math.min(1, k * 3) * (k < 0.2 ? k * 5 : 1);
this.e.set(p.spin, p.spin * 0.7, 0); this.q.setFromEuler(this.e);
this.m.compose(this.v.set(p.x, p.y, p.z), this.q, this.sc.set(s, s, s));
this.mesh.setMatrixAt(n, this.m); this.mesh.setColorAt(n, this.c.setRGB(p.r, p.g, p.b)); n++;
}
this.mesh.count = n;
this.mesh.instanceMatrix.needsUpdate = true; if (this.mesh.instanceColor) this.mesh.instanceColor.needsUpdate = true;
}
}
characters.ts (src/game/characters.ts)59 lines
// Princess Sugarbell, Princess Mintly and the Royal Trophy (procedural models).
import * as THREE from 'three';
import { furMaterial, furSphere, softMaterial } from '../render/fur';
import { starGeo } from '../cats/catModel';
export class Princess {
root = new THREE.Group(); private arm = new THREE.Group(); private body = new THREE.Group(); private t = Math.random() * 5;
cheer = 0;
constructor(dress: string, dress2: string, hair: string) {
this.root.add(this.body);
for (let i = 0; i < 3; i++) {
const tier = new THREE.Mesh(new THREE.ConeGeometry(0.75 - i * 0.17, 0.55, 18, 1, true), softMaterial(i % 2 ? dress2 : dress, 0.3));
tier.position.y = 0.3 + i * 0.32; this.body.add(tier);
const ruffle = new THREE.Mesh(new THREE.TorusGeometry(0.72 - i * 0.17, 0.06, 6, 24), softMaterial('#ffffff', 0.2)); ruffle.rotation.x = Math.PI / 2; ruffle.position.y = 0.05 + i * 0.32; this.body.add(ruffle);
}
const torso = new THREE.Mesh(new THREE.SphereGeometry(0.24, 14, 10), softMaterial(dress, 0.3)); torso.scale.y = 1.2; torso.position.y = 1.12; this.body.add(torso);
const head = new THREE.Group(); head.position.y = 1.62; this.body.add(head);
head.add(new THREE.Mesh(new THREE.SphereGeometry(0.34, 22, 16), softMaterial('#ffe0cc', 0.1)));
const hairM = furMaterial({ top: hair, bottom: hair, length: 0.12, density: 28 });
const back = new THREE.Mesh(furSphere(), hairM); back.scale.set(0.38, 0.38, 0.36); back.position.set(0, 0.06, -0.08); head.add(back);
for (const sx of [-1, 1]) {
const bun = new THREE.Mesh(furSphere(), hairM); bun.scale.setScalar(0.17); bun.position.set(sx * 0.34, 0.2, -0.05); head.add(bun);
const eye = new THREE.Mesh(new THREE.SphereGeometry(0.055, 10, 8), softMaterial('#3a2340', 1.2)); eye.scale.set(0.85, 1.2, 0.5); eye.position.set(sx * 0.11, 0.0, 0.31); head.add(eye);
const hl = new THREE.Mesh(new THREE.SphereGeometry(0.018, 6, 4), softMaterial('#ffffff', 0, 2)); hl.position.set(sx * 0.11 + 0.015, 0.03, 0.345); head.add(hl);
const bl = new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 6), softMaterial('#ff9ec0', 0, 0.2)); bl.scale.set(1, 0.5, 0.3); bl.position.set(sx * 0.19, -0.09, 0.28); head.add(bl);
}
const smile = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.014, 6, 12, Math.PI), softMaterial('#9a3d5c')); smile.rotation.z = Math.PI; smile.position.set(0, -0.1, 0.32); head.add(smile);
const crown = new THREE.Group(); crown.position.y = 0.36; head.add(crown);
crown.add(new THREE.Mesh(new THREE.CylinderGeometry(0.16, 0.18, 0.1, 14, 1, true), softMaterial('#ffd34d', 1.4, 0.25)));
for (let i = 0; i < 5; i++) { const a = i / 5 * Math.PI * 2; const sp = new THREE.Mesh(new THREE.SphereGeometry(0.04, 6, 4), softMaterial('#ff6fa8', 1.5, 0.3)); sp.position.set(Math.cos(a) * 0.17, 0.08, Math.sin(a) * 0.17); crown.add(sp); }
this.arm.position.set(0.25, 1.2, 0); this.body.add(this.arm);
const a = new THREE.Mesh(new THREE.CapsuleGeometry(0.06, 0.3, 4, 8), softMaterial('#ffe0cc')); a.position.y = 0.18; this.arm.add(a);
const wand = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.5, 6), softMaterial('#ffffff', 1)); wand.position.y = 0.5; this.arm.add(wand);
const star = new THREE.Mesh(starGeo(), softMaterial('#ffe066', 1, 0.6)); star.scale.setScalar(0.14); star.position.y = 0.8; this.arm.add(star);
const la = new THREE.Mesh(new THREE.CapsuleGeometry(0.06, 0.3, 4, 8), softMaterial('#ffe0cc')); la.position.set(-0.27, 1.05, 0); la.rotation.z = 0.5; this.body.add(la);
}
update(dt: number, lookAt?: THREE.Vector3) {
this.t += dt; this.cheer = Math.max(0, this.cheer - dt);
const c = this.cheer > 0 ? 1 : 0;
this.body.position.y = Math.abs(Math.sin(this.t * (c ? 9 : 2))) * (c ? 0.35 : 0.06);
this.arm.rotation.z = -0.5 - Math.sin(this.t * (c ? 14 : 3)) * (c ? 0.6 : 0.35);
if (lookAt) { const a = Math.atan2(lookAt.x - this.root.position.x, lookAt.z - this.root.position.z); this.root.rotation.y += ((a - this.root.rotation.y + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 4); }
}
}
export function makeTrophy(): THREE.Group {
const g = new THREE.Group();
const gold = softMaterial('#ffcf3f', 1.6, 0.25);
const base = new THREE.Mesh(new THREE.CylinderGeometry(0.7, 0.8, 0.4, 20), softMaterial('#b07dff', 0.8)); base.position.y = 0.2; g.add(base);
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.15, 0.3, 0.7, 16), gold); stem.position.y = 0.75; g.add(stem);
const cup = new THREE.Mesh(new THREE.SphereGeometry(0.75, 24, 16, 0, Math.PI * 2, 0, Math.PI * 0.55), gold); cup.rotation.x = Math.PI; cup.position.y = 1.75; g.add(cup);
const lip = new THREE.Mesh(new THREE.TorusGeometry(0.72, 0.08, 8, 28), gold); lip.rotation.x = Math.PI / 2; lip.position.y = 1.78; g.add(lip);
for (const sx of [-1, 1]) { const h = new THREE.Mesh(new THREE.TorusGeometry(0.3, 0.07, 8, 16, Math.PI * 1.2), gold); h.position.set(sx * 0.75, 1.45, 0); h.rotation.z = sx > 0 ? -0.9 : Math.PI + 0.9; g.add(h); }
// cat ears on the trophy!
for (const sx of [-1, 1]) { const e = new THREE.Mesh(new THREE.ConeGeometry(0.2, 0.4, 4), gold); e.position.set(sx * 0.45, 2.0, 0); e.rotation.z = -sx * 0.3; g.add(e); }
const star = new THREE.Mesh(starGeo(), softMaterial('#fff5a8', 1, 0.8)); star.scale.setScalar(0.32); star.position.set(0, 1.3, 0.62); g.add(star);
return g;
}
trex.ts (src/game/trex.ts)180 lines
// Tiny T-rex friends: they wait in pastel eggs, hatch when you come near (or after a while),
// follow a cat around with little hops, then play with their own ball. No teeth, no fire, no biting.
import * as THREE from 'three';
import { softMaterial } from '../render/fur';
import { Body } from '../physics/body';
import type { VoxelWorld } from '../world/voxels';
import { angleDiff, damp } from '../core/util';
export type RexState = 'egg' | 'crack' | 'follow' | 'play';
export type RexEvent = 'hatch' | 'rawr' | 'wobble' | 'sneeze' | 'ballhit' | null;
interface CatLike { pos: THREE.Vector3; active: boolean }
const ball = new THREE.SphereGeometry(1, 16, 12);
function part(geo: THREE.BufferGeometry, color: string, gloss = 0.2) { return new THREE.Mesh(geo, softMaterial(color, gloss)); }
export class TinyRex {
root = new THREE.Group();
egg = new THREE.Group();
dino = new THREE.Group();
toy: THREE.Mesh;
body: Body;
state: RexState = 'egg';
private t = 0; private timer = 0; private rawrT = 3; private hop = 0; private yaw = 0;
private copyT = -1; private sneezeT = 12 + Math.random() * 10; private hitCool = 0;
/** The cat the ball just bumped (for a funny boing), set when update returns 'ballhit'. */
lastHit: CatLike | null = null;
private eggWait: number;
private target: CatLike | null = null;
private toyVel = new THREE.Vector3();
private head = new THREE.Group(); private mouth: THREE.Mesh; private tail: THREE.Mesh;
private armL: THREE.Mesh; private armR: THREE.Mesh; private shellBits: THREE.Mesh[] = [];
constructor(private world: VoxelWorld, public home: THREE.Vector3, body: string, belly: string, eggCol: string, spot: string, toyCol: string, private seed: number) {
this.body = new Body(world); this.body.radius = 0.25; this.body.height = 0.6;
this.eggWait = 22 + seed * 9;
// egg: pastel with polka spots
const shell = part(ball, eggCol, 0.7); shell.scale.set(0.42, 0.55, 0.42); shell.position.y = 0.55; this.egg.add(shell);
for (let i = 0; i < 6; i++) {
const s = part(ball, spot, 0.5); const a = i / 6 * Math.PI * 2, h = 0.4 + (i % 2) * 0.3;
s.scale.setScalar(0.08); s.position.set(Math.cos(a) * 0.38 * Math.sin(h * 2.2), 0.55 + (h - 0.55) * 0.6, Math.sin(a) * 0.38 * Math.sin(h * 2.2)); this.egg.add(s);
}
// little shell pieces that fly off when it hatches
for (let i = 0; i < 5; i++) { const b = part(ball, eggCol, 0.7); b.scale.set(0.14, 0.06, 0.14); b.visible = false; this.root.add(b); this.shellBits.push(b); }
// dino: round body, cream belly, big head, glossy eyes, tiny arms, little tail, pastel back bumps
const d = this.dino;
const torso = part(ball, body); torso.scale.set(0.3, 0.3, 0.36); torso.position.y = 0.42; d.add(torso);
const bel = part(ball, belly); bel.scale.set(0.22, 0.24, 0.2); bel.position.set(0, 0.4, 0.17); d.add(bel);
this.head.position.set(0, 0.78, 0.18); d.add(this.head);
const hd = part(ball, body); hd.scale.set(0.27, 0.25, 0.3); this.head.add(hd);
const snout = part(ball, body); snout.scale.set(0.2, 0.15, 0.18); snout.position.set(0, -0.05, 0.22); this.head.add(snout);
for (const sx of [-1, 1]) {
const eye = part(ball, '#2b2340', 0.9); eye.scale.setScalar(0.085); eye.position.set(sx * 0.13, 0.06, 0.22); this.head.add(eye);
const hl = new THREE.Mesh(ball, new THREE.MeshBasicMaterial({ color: '#ffffff' })); hl.scale.setScalar(0.03); hl.position.set(sx * 0.13 + 0.025, 0.1, 0.295); this.head.add(hl);
const blush = part(ball, '#ff9cc0'); blush.scale.set(0.05, 0.03, 0.02); blush.position.set(sx * 0.17, -0.05, 0.26); this.head.add(blush);
const leg = part(ball, body); leg.scale.set(0.1, 0.13, 0.12); leg.position.set(sx * 0.15, 0.13, 0.02); d.add(leg);
const foot = part(ball, belly); foot.scale.set(0.08, 0.04, 0.1); foot.position.set(sx * 0.15, 0.03, 0.09); d.add(foot);
}
this.mouth = part(ball, '#c2477a'); this.mouth.scale.set(0.07, 0.035, 0.03); this.mouth.position.set(0, -0.12, 0.39); this.head.add(this.mouth);
this.armL = part(ball, body); this.armL.scale.set(0.04, 0.08, 0.04); this.armL.position.set(-0.14, 0.52, 0.3); d.add(this.armL);
this.armR = this.armL.clone(); this.armR.position.x = 0.14; d.add(this.armR);
this.tail = part(new THREE.ConeGeometry(0.15, 0.55, 10), body); this.tail.rotation.x = -Math.PI / 2 + 0.35; this.tail.position.set(0, 0.36, -0.42); d.add(this.tail);
const spikeGeo = new THREE.ConeGeometry(0.06, 0.12, 6);
for (let i = 0; i < 4; i++) { const s = part(spikeGeo, i % 2 ? '#ffb3d9' : '#fff1a6', 0.5); s.position.set(0, 0.7 - i * 0.1, 0.05 - i * 0.14); s.rotation.x = -0.4 - i * 0.2; d.add(s); }
d.scale.setScalar(1.1); d.visible = false;
this.root.add(this.egg, d);
this.toy = part(ball, toyCol, 0.8); this.toy.scale.setScalar(0.2); this.toy.visible = false;
const stripe = new THREE.Mesh(new THREE.TorusGeometry(1.0, 0.18, 6, 20), softMaterial('#ffffff', 0.6)); this.toy.add(stripe);
this.reset();
}
reset() {
this.state = 'egg'; this.t = 0; this.timer = 0; this.target = null;
this.body.pos.copy(this.home); this.body.pos.y = this.world.topAt(this.home.x, this.home.z); this.body.vel.set(0, 0, 0);
this.egg.visible = true; this.egg.scale.setScalar(1); this.dino.visible = false; this.toy.visible = false;
this.shellBits.forEach(b => (b.visible = false));
}
hatchNow() { if (this.state === 'egg') { this.state = 'crack'; this.timer = 0; } }
/** Returns 'hatch' when the dino pops out, 'rawr' for a cute squeak, 'wobble' while the egg rocks, else null. */
update(dt: number, playerPos: THREE.Vector3, cats: CatLike[], playing: boolean, playerJumped = false): RexEvent {
this.t += dt; this.timer += dt;
let ev: RexEvent = null;
const p = this.body.pos;
if (this.state === 'egg') {
const near = Math.hypot(playerPos.x - p.x, playerPos.z - p.z) < 3;
this.egg.rotation.z = Math.sin(this.t * 3 + this.seed) * 0.06;
if (playing && (near || this.timer > this.eggWait)) { this.state = 'crack'; this.timer = 0; }
} else if (this.state === 'crack') {
this.egg.rotation.z = Math.sin(this.timer * 30) * 0.25 * (0.4 + this.timer);
this.egg.position.y = Math.abs(Math.sin(this.timer * 14)) * 0.1;
if (Math.floor(this.timer * 3) !== Math.floor((this.timer - dt) * 3)) ev = 'wobble';
if (this.timer > 1) {
this.egg.visible = false; this.dino.visible = true; this.body.vel.y = 6;
this.shellBits.forEach((b, i) => { b.visible = true; const a = i / 5 * Math.PI * 2; b.position.set(Math.cos(a) * 0.3, 0.6, Math.sin(a) * 0.3); b.userData.v = new THREE.Vector3(Math.cos(a) * 2, 3 + i * 0.3, Math.sin(a) * 2); });
this.state = 'follow'; this.timer = 0; this.target = null; ev = 'hatch';
}
} else {
// move: follow a cat, or chase and bump the toy ball
let gx = p.x, gz = p.z, speed = 0;
if (this.state === 'follow') {
if (!this.target || !this.target.active || this.timer < dt || this.target.pos.distanceTo(playerPos) > 9) {
const pool = cats.filter(c => c.active && c.pos.distanceTo(playerPos) < 7);
this.target = pool.sort((a, b) => a.pos.distanceTo(p) - b.pos.distanceTo(p))[Math.floor(Math.random() * Math.min(3, pool.length))] || null;
}
if (!this.target) { // no cat nearby: stay close to the player instead
const dx = p.x - playerPos.x, dz = p.z - playerPos.z, l = Math.hypot(dx, dz) || 1;
gx = playerPos.x + dx / l * 2.4; gz = playerPos.z + dz / l * 2.4; speed = l > 3 ? Math.min(6, 2.4 + l * 0.3) : 0;
if (l > 25) { p.set(gx, this.world.topAt(gx, gz) + 1, gz); }
}
if (this.target) {
const tp = this.target.pos, dx = p.x - tp.x, dz = p.z - tp.z, l = Math.hypot(dx, dz) || 1;
gx = tp.x + dx / l * 1.3; gz = tp.z + dz / l * 1.3; speed = l > 1.6 ? Math.min(5.5, 2.4 + l * 0.25) : 0;
}
if (this.timer > 9 + (this.seed % 3) * 1.5) {
this.state = 'play'; this.timer = 0;
this.toy.visible = true; this.toy.position.set(p.x + Math.sin(this.yaw) * 0.8, p.y + 0.6, p.z + Math.cos(this.yaw) * 0.8); this.toyVel.set(0, 2, 0);
ev = 'rawr';
}
} else {
const tp = this.toy.position, l = Math.hypot(tp.x - p.x, tp.z - p.z);
gx = tp.x; gz = tp.z; speed = l > 0.5 ? 2.6 : 0;
if (l < 0.55 && this.toyVel.lengthSq() < 0.5) {
// bump the ball with the nose
const a = this.yaw + (Math.random() - 0.5) * 1.2; this.toyVel.set(Math.sin(a) * 3, 2.5, Math.cos(a) * 3);
this.hop = 1; this.armL.rotation.x = this.armR.rotation.x = -1;
}
// ball physics: bounce on the ground, roll and slow down
this.toyVel.y -= 14 * dt; tp.addScaledVector(this.toyVel, dt);
const g = this.world.topAt(tp.x, tp.z) + 0.2;
if (tp.y < g) { tp.y = g; this.toyVel.y = Math.abs(this.toyVel.y) * 0.35; this.toyVel.x *= 0.92; this.toyVel.z *= 0.92; if (this.toyVel.y < 0.4) this.toyVel.y = 0; }
this.toyVel.x *= 1 - dt * 1.2; this.toyVel.z *= 1 - dt * 1.2;
// the rolling ball can bonk into a cat: boing!
this.hitCool -= dt;
if (this.hitCool <= 0 && Math.hypot(this.toyVel.x, this.toyVel.z) > 1.2) {
const c = cats.find(k => k.active && Math.hypot(k.pos.x - tp.x, k.pos.z - tp.z) < 0.8 && Math.abs(k.pos.y + 0.4 - tp.y) < 1.2);
if (c) { this.lastHit = c; this.hitCool = 2; this.toyVel.x *= -0.6; this.toyVel.z *= -0.6; this.toyVel.y = 3; ev = 'ballhit'; }
}
if (tp.distanceTo(this.home) > 24) { tp.copy(p); tp.y += 0.6; this.toyVel.set(0, 0, 0); }
this.toy.rotation.x += this.toyVel.z * dt * 4; this.toy.rotation.z -= this.toyVel.x * dt * 4;
if (this.timer > 7) { this.state = 'follow'; this.timer = 0; this.toy.visible = false; this.target = null; }
}
const dx = gx - p.x, dz = gz - p.z, l = Math.hypot(dx, dz);
if (speed > 0 && l > 0.05) {
this.body.vel.x = dx / l * speed; this.body.vel.z = dz / l * speed;
this.yaw += angleDiff(this.yaw, Math.atan2(dx, dz)) * damp(8, dt);
if (this.body.grounded && Math.random() < dt * 2.5) this.body.vel.y = 3.2; // happy little hops
} else { this.body.vel.x *= 0.8; this.body.vel.z *= 0.8; }
if (this.body.step(dt, 20) && this.body.grounded) this.body.vel.y = 6; // hop over a block
if (p.y < -6) p.copy(this.home).setY(this.world.topAt(this.home.x, this.home.z) + 1);
// squeaky rawr now and then, when the player is close enough to see it
// copy the player's jumps, a tiny moment later
if (playerJumped && playerPos.distanceTo(p) < 9) this.copyT = 0.22 + this.seed * 0.08;
if (this.copyT > 0) { this.copyT -= dt; if (this.copyT <= 0 && this.body.grounded) { this.body.vel.y = 6.5; this.hop = 1; } }
// a tiny rainbow sneeze now and then
this.sneezeT -= dt;
if (this.sneezeT < 0) { this.sneezeT = 14 + Math.random() * 12; if (playerPos.distanceTo(p) < 12) { ev = 'sneeze'; this.hop = 1; } }
this.rawrT -= dt;
if (this.rawrT < 0) { this.rawrT = 4 + Math.random() * 5; if (playerPos.distanceTo(p) < 12) { ev = ev ?? 'rawr'; this.hop = 1; } }
}
// animate
this.hop = Math.max(0, this.hop - dt * 2.5);
const walk = Math.hypot(this.body.vel.x, this.body.vel.z);
this.dino.rotation.y = this.yaw;
this.dino.rotation.z = Math.sin(this.t * 12) * 0.08 * Math.min(1, walk / 2);
this.tail.rotation.y = Math.sin(this.t * 7) * 0.4;
this.head.rotation.x = -this.hop * 0.5;
this.mouth.scale.y = 0.035 + this.hop * 0.06;
const flap = Math.sin(this.t * 18) * 0.5 * (this.hop + 0.2);
this.armL.rotation.x = this.armL.rotation.x * 0.9 + flap * 0.1; this.armR.rotation.x = this.armR.rotation.x * 0.9 - flap * 0.1;
this.root.position.copy(p);
for (const b of this.shellBits) {
if (!b.visible) continue; const v = b.userData.v as THREE.Vector3;
v.y -= 12 * dt; b.position.addScaledVector(v, dt); b.rotation.x += dt * 6;
if (b.position.y < -0.5) b.visible = false;
}
return ev;
}
}
sanctuary.ts, the Cat Home (src/game/sanctuary.ts)552 lines
// The Royal Cat Sanctuary: a cozy garden where every cat you have befriended lives.
// Pet them, give them treats, rename them, and buy toys and playground pieces with candy.
// No hunger meters, no neglect, no timers: cats are always happy to see you.
import * as THREE from 'three';
import { VoxelWorld, B } from '../world/voxels';
import { Body } from '../physics/body';
import type { Bouncer } from '../physics/body';
import { Player } from '../player/player';
import type { InputState } from '../input/input';
import { CatRig } from '../cats/catModel';
import type { Pose } from '../cats/catModel';
import { CAT_DEFS } from '../cats/cats';
import type { CatDef } from '../cats/cats';
import { Particles } from '../fx/particles';
import { softMaterial } from '../render/fur';
import { makeSky } from '../render/sky';
import { audio } from '../audio';
import type { SaveV1 } from '../save/save';
import { persist } from '../save/save';
import { makeTrophy } from './characters';
import { HATS, HOODS, applyOutfit } from './wardrobe';
import { TinyRex } from './trex';
import { angleDiff, angleLerp, clamp, damp, lerp } from '../core/util';
type Kind = 'bed' | 'yarn' | 'trampoline' | 'tower' | 'slide' | 'pit' | 'fountain' | 'rainbow' | 'wand';
export interface DecoDef { id: Kind; name: string; emoji: string; price: number; about: string }
export const DECOS: DecoDef[] = [
{ id: 'bed', name: 'Cloud bed', emoji: '🛏️', price: 0, about: 'A puffy bed for nap time.' },
{ id: 'yarn', name: 'Yarn ball', emoji: '🧶', price: 0, about: 'Cats roll it around.' },
{ id: 'trampoline', name: 'Trampoline', emoji: '🤸', price: 15, about: 'Boing! Cats and you can bounce.' },
{ id: 'wand', name: 'Feather wand', emoji: '🪶', price: 20, about: 'Hold 🪶 and the cats chase you.' },
{ id: 'tower', name: 'Cat tower', emoji: '🗼', price: 25, about: 'Cats climb to the top and nap.' },
{ id: 'slide', name: 'Rainbow slide', emoji: '🛝', price: 30, about: 'Wheee! Cats slide down.' },
{ id: 'pit', name: 'Candy ball pit', emoji: '🎈', price: 35, about: 'Cats dive in and pop out.' },
{ id: 'fountain', name: 'Fish fountain', emoji: '⛲', price: 40, about: 'Sparkly water to watch.' },
{ id: 'rainbow', name: 'Rainbow arch', emoji: '🌈', price: 50, about: 'A magic rainbow over the garden.' },
];
interface Deco { def: DecoDef; group: THREE.Group; spot: THREE.Vector3; users: number; anim?: (t: number, dt: number) => void; bouncer?: Bouncer }
type HState = 'wander' | 'goto' | 'use' | 'sit' | 'sleep' | 'eat' | 'petted' | 'chase' | 'boop' | 'hello';
class HomeCat {
rig: CatRig; body: Body; state: HState = 'wander'; timer = 0; yaw = Math.random() * 6.28;
target = new THREE.Vector3(); deco: Deco | null = null; pal: HomeCat | null = null;
// scripted moves (climb, slide, dive) ignore physics
path: THREE.Vector3[] = []; pathT = 0; pathPose: Pose = 'stand'; petCount = 0; treatT = 0;
constructor(public def: CatDef, world: VoxelWorld, at: THREE.Vector3) {
this.rig = new CatRig(def.look);
this.body = new Body(world); this.body.radius = 0.3 * def.look.scale; this.body.height = 0.9 * def.look.scale;
this.body.pos.copy(at); this.target.copy(at);
}
get pos() { return this.body.pos; }
active = true;
}
const DECO_SPOTS: [number, number][] = [[-6, -2], [6, -2], [-9, 5], [9, 5], [-10, -4], [10, -4], [-7, -9], [7, -9], [0, -4.6]];
const KIND_ORDER: Kind[] = ['bed', 'yarn', 'trampoline', 'wand', 'tower', 'slide', 'pit', 'fountain', 'rainbow'];
export class Sanctuary {
scene = new THREE.Scene();
world: VoxelWorld;
player: Player;
fx = new Particles(500);
cats: HomeCat[] = [];
decos = new Map<Kind, Deco>();
bouncers: Bouncer[] = [];
private t = 0;
private camYaw = 0; private camPitch = 0.5; private manualCamT = 0;
private camPos = new THREE.Vector3(0, 10, 16); private camLook = new THREE.Vector3();
private near: HomeCat | null = null;
private ui: HTMLElement; private bar: HTMLElement; private card: HTMLElement; private candyEl: HTMLElement; private wandBtn: HTMLElement;
private wandHeld = false;
private overlay: HTMLElement | null = null;
private sign: THREE.Group;
private tmp = new THREE.Vector3();
private trophies: { g: THREE.Group; spin: number; i: number }[] = [];
private ghost: THREE.Group | null = null;
private rexes: TinyRex[] = [];
private showOffT = 0;
onExit: () => void = () => {};
active = false;
constructor(private save: SaveV1, root: HTMLElement, private el: (h: string) => HTMLElement, private toast: (t: string) => void) {
this.scene.background = new THREE.Color('#ffe6f2');
this.scene.add(makeSky('0.7,0.84,1.0', '1.0,0.9,0.95'));
this.scene.add(new THREE.HemisphereLight('#dfe9ff', '#ffc9d9', 1.6));
const sun = new THREE.DirectionalLight('#fff3e0', 1.6); sun.position.set(20, 40, 15); this.scene.add(sun);
this.world = this.buildGarden();
this.scene.add(this.world.buildMesh());
// a grass sheet just under the block tops hides the hairline gaps between soft blocks
const under = new THREE.Mesh(new THREE.CircleGeometry(13.6, 40), softMaterial('#9fe6a0', 0)); under.rotation.x = -Math.PI / 2; under.position.y = 1.9; this.scene.add(under);
this.scene.add(this.fx.mesh);
this.player = new Player(this.world);
applyOutfit(this.player, save.outfit);
this.scene.add(this.player.root, this.player.shadowMesh);
this.sign = this.makeSign(); this.scene.add(this.sign);
// the tiny T-rex friends have a nest here too, and play with the cats
const looks: [string, string, string, string, string][] = [['#9be39b', '#fff4c9', '#fff4c9', '#8fd3ff', '#ff7fb0'], ['#b9a6ff', '#ffe6f2', '#ffe6f2', '#ffcf3f', '#7cc8ff'], ['#ffb37a', '#fff1d6', '#e6f7ff', '#ff9cc9', '#8fe39b']];
looks.forEach((l, i) => { const r = new TinyRex(this.world, new THREE.Vector3(-2 + i * 2, 0, 2), l[0], l[1], l[2], l[3], l[4], i); r.hatchNow(); this.scene.add(r.root, r.toy); this.rexes.push(r); });
// UI (hidden until the player comes home)
this.ui = el(`<div class="home-ui" hidden></div>`); root.appendChild(this.ui);
this.bar = el(`<div class="hud"><div class="pill">🏡 Cat Home</div><div class="row"><div class="pill">🍬 <span class="hc">0</span></div><button class="iconbtn" data-a="shop" aria-label="Candy shop">🛍️</button><button class="iconbtn" data-a="exit" aria-label="Back to the kingdom">🏰</button></div></div>`);
this.ui.appendChild(this.bar);
this.candyEl = this.bar.querySelector('.hc') as HTMLElement;
this.card = el(`<div class="petcard" hidden><b class="nm"></b><button class="iconbtn" data-a="name" aria-label="Rename">✏️</button><button class="iconbtn" data-a="treat" aria-label="Give a treat">🍪</button></div>`);
this.ui.appendChild(this.card);
this.wandBtn = el(`<button class="wandbtn" aria-label="Wave the feather wand" hidden>🪶</button>`); this.ui.appendChild(this.wandBtn);
const wandOn = (e: Event) => { e.preventDefault(); e.stopPropagation(); this.wandHeld = true; };
const wandOff = () => { this.wandHeld = false; };
this.wandBtn.addEventListener('pointerdown', wandOn); this.wandBtn.addEventListener('pointerup', wandOff); this.wandBtn.addEventListener('pointercancel', wandOff); this.wandBtn.addEventListener('pointerleave', wandOff);
addEventListener('keydown', e => { if (this.active && e.code === 'KeyF' && !this.overlay) this.wandHeld = true; if (this.active && e.code === 'KeyT' && !this.overlay) this.treat(); });
addEventListener('keyup', e => { if (e.code === 'KeyF') this.wandHeld = false; });
this.ui.addEventListener('click', e => {
const a = (e.target as HTMLElement).closest('[data-a]')?.getAttribute('data-a');
if (a === 'exit') { audio.play('click'); this.leave(); }
if (a === 'shop') this.openShop();
if (a === 'name') this.openRename();
if (a === 'treat') this.treat();
});
}
// ---------- world ----------
private buildGarden(): VoxelWorld {
const S = 40, w = new VoxelWorld(S, 12, S), c = S / 2;
for (let i = 0; i < S; i++) for (let k = 0; k < S; k++) {
const x = i - c + 0.5, z = k - c + 0.5, d = Math.hypot(x, z) + Math.sin(Math.atan2(z, x) * 6) * 0.8;
if (d > 16) continue;
let h = 2; if (d > 14) h = 1;
const ring = Math.abs(Math.hypot(x, z) - 4.5) < 0.8;
const top = Math.hypot(x, z) < 3 ? ((Math.floor(x) + Math.floor(z)) % 2 ? B.SUGAR : B.PATH) : ring ? B.PATH : (Math.sin(x * 0.5) + Math.cos(z * 0.4) > 1.2 ? B.MINT : B.GRASS);
w.fillColumn(i, k, h, top, B.COOKIE);
}
// the cats' cottage at the back
const ci = (x: number) => Math.floor(x + c), ck = (z: number) => Math.floor(z + c);
w.box(ci(-4), 2, ck(-14), ci(4), 5, ck(-11), B.SUGAR);
// a solid backing inside the cottage hides the hairline gaps between its soft blocks
{ const back = new THREE.Mesh(new THREE.BoxGeometry(8.6, 3.6, 3.6), softMaterial("#f5e2b8", 0)); back.position.set(0.5, 4.0, -12); this.scene.add(back); }
for (const [w2, d2, y2, col] of [[10.6, 5.6, 6.5, '#ff7aa2'], [8.6, 3.6, 7.5, '#ff7aa2'], [4.6, 1.6, 8.5, '#f59bbd']] as [number, number, number, string][]) { const r = new THREE.Mesh(new THREE.BoxGeometry(w2, 0.6, d2), softMaterial(col, 0)); r.position.set(0.5, y2, -12); this.scene.add(r); }
w.box(ci(-1), 2, ck(-11), ci(0), 3, ck(-11), 0);
w.box(ci(-5), 6, ck(-15), ci(5), 6, ck(-10), B.BERRY);
w.box(ci(-4), 7, ck(-14), ci(4), 7, ck(-11), B.BERRY);
w.box(ci(-2), 8, ck(-13), ci(2), 8, ck(-12), B.PINK);
// candy-cane fence posts around the edge
for (let a = 0; a < 28; a++) { const ang = a / 28 * Math.PI * 2; const x = Math.cos(ang) * 14.5, z = Math.sin(ang) * 14.5; if (z < -9 && Math.abs(x) < 6) continue; w.box(ci(x), 2, ck(z), ci(x), 2, ck(z), a % 2 ? B.BERRY : B.CLOUD); }
// flowers
const fcols = ['#ff7fb0', '#ffe066', '#b79bff', '#7cc8ff', '#ffffff'];
const fgeo = new THREE.IcosahedronGeometry(0.16, 0);
for (let n = 0; n < 70; n++) {
const a = Math.random() * Math.PI * 2, r = 5.5 + Math.random() * 8.5, x = Math.cos(a) * r, z = Math.sin(a) * r;
const f = new THREE.Mesh(fgeo, softMaterial(fcols[n % fcols.length], 0.3)); f.position.set(x, w.topAt(x, z) + 0.15, z); this.scene.add(f);
}
return w;
}
private makeSign(): THREE.Group {
// a friendly wooden sign that shows when no cats live here yet
const g = new THREE.Group();
const post = new THREE.Mesh(new THREE.BoxGeometry(0.2, 1.4, 0.2), softMaterial('#e8b98a')); post.position.y = 0.7; g.add(post);
const board = new THREE.Mesh(new THREE.BoxGeometry(2.2, 0.9, 0.15), softMaterial('#fff3d6', 0.3)); board.position.y = 1.5; g.add(board);
const heart = new THREE.Mesh(new THREE.SphereGeometry(0.22, 12, 8), softMaterial('#ff7fb0', 0.6)); heart.position.set(0, 1.5, 0.12); heart.scale.set(1, 0.9, 0.4); g.add(heart);
g.position.set(0, 2, -4);
return g;
}
private buildDeco(kind: Kind, spot: THREE.Vector3): Deco {
const def = DECOS.find(d => d.id === kind)!;
const g = new THREE.Group(); g.position.copy(spot);
const d: Deco = { def, group: g, spot, users: 0 };
const M = (geo: THREE.BufferGeometry, col: string, gloss = 0.3) => new THREE.Mesh(geo, softMaterial(col, gloss));
if (kind === 'bed') {
const base = M(new THREE.CylinderGeometry(1.1, 1.2, 0.35, 24), '#c9b6ff'); base.position.y = 0.18; g.add(base);
const rim = M(new THREE.TorusGeometry(1.0, 0.28, 10, 28), '#ffffff', 0.2); rim.rotation.x = Math.PI / 2; rim.position.y = 0.4; g.add(rim);
const pillow = M(new THREE.SphereGeometry(0.35, 12, 8), '#ffd1e6'); pillow.scale.set(1.2, 0.5, 0.8); pillow.position.set(0, 0.45, -0.55); g.add(pillow);
} else if (kind === 'yarn') {
const ball = M(new THREE.SphereGeometry(0.4, 16, 12), '#ff7fb0', 0.2); ball.position.y = 0.4; g.add(ball);
for (let i = 0; i < 3; i++) { const r = M(new THREE.TorusGeometry(0.4, 0.035, 6, 24), '#ffb3d1'); r.rotation.set(i, i * 1.3, 0); r.position.y = 0.4; g.add(r); }
d.anim = (t) => { ball.rotation.z = Math.sin(t * 0.7) * 0.6; };
} else if (kind === 'trampoline') {
const frame = M(new THREE.TorusGeometry(1.1, 0.14, 8, 28), '#7cc8ff'); frame.rotation.x = Math.PI / 2; frame.position.y = 0.5; g.add(frame);
const mat = M(new THREE.CylinderGeometry(1.05, 1.05, 0.08, 28), '#ffe066', 0.5); mat.position.y = 0.5; g.add(mat);
for (let i = 0; i < 4; i++) { const leg = M(new THREE.CylinderGeometry(0.06, 0.06, 0.5, 6), '#ffffff'); const a = i / 4 * Math.PI * 2 + 0.4; leg.position.set(Math.cos(a), 0.25, Math.sin(a)); g.add(leg); }
d.bouncer = { x: spot.x, z: spot.z, r: 1.1, top: spot.y + 0.55, power: 15, squash: 0 };
this.bouncers.push(d.bouncer);
const b = d.bouncer;
d.anim = (_t, dt) => { b.squash = Math.max(0, b.squash - dt * 4); mat.scale.y = 1 - b.squash * 0.6; mat.position.y = 0.5 - b.squash * 0.15; };
} else if (kind === 'tower') {
const post = M(new THREE.CylinderGeometry(0.22, 0.26, 3.2, 10), '#f5e2b8'); post.position.y = 1.6; g.add(post);
[0.9, 1.9, 2.9].forEach((h, i) => { const p = M(new THREE.CylinderGeometry(0.75 - i * 0.1, 0.75 - i * 0.1, 0.2, 18), ['#ffb3d1', '#b8e6ff', '#d7c2ff'][i]); p.position.set(i === 1 ? 0.35 : -0.2, h, 0); g.add(p); });
const top = M(new THREE.SphereGeometry(0.6, 14, 10), '#fff1a6'); top.scale.y = 0.35; top.position.y = 3.15; g.add(top);
} else if (kind === 'slide') {
const ladder = M(new THREE.BoxGeometry(0.9, 2.6, 0.3), '#ffffff'); ladder.position.set(0, 1.3, -1.4); g.add(ladder);
const deck = M(new THREE.BoxGeometry(1.2, 0.2, 1.0), '#ffe066'); deck.position.set(0, 2.6, -1.0); g.add(deck);
const ramp = new THREE.Group(); ramp.position.set(0, 2.6, -0.5);
const cols = ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'];
cols.forEach((c, i) => { const s = M(new THREE.BoxGeometry(1.0 - 0.05, 0.08, 0.66), c, 0.6); s.position.set(0, -i * 0.5, 0.33 + i * 0.66); ramp.add(s); });
ramp.rotation.x = 0; g.add(ramp);
// make the ramp a smooth incline
ramp.children.forEach((s, i) => { s.position.y = -i * 0.5 - 0.1; });
} else if (kind === 'pit') {
const tub = M(new THREE.CylinderGeometry(1.3, 1.2, 0.7, 24, 1, true), '#ffb3d1'); tub.position.y = 0.35; g.add(tub);
const rim = M(new THREE.TorusGeometry(1.3, 0.12, 8, 28), '#ffffff'); rim.rotation.x = Math.PI / 2; rim.position.y = 0.7; g.add(rim);
const cols = ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'];
const bg = new THREE.SphereGeometry(0.16, 8, 6);
for (let i = 0; i < 46; i++) { const b = M(bg, cols[i % 5], 0.7); const a = Math.random() * 6.28, r = Math.random() * 1.1; b.position.set(Math.cos(a) * r, 0.45 + Math.random() * 0.2, Math.sin(a) * r); g.add(b); }
} else if (kind === 'fountain') {
const bowl = M(new THREE.CylinderGeometry(1.3, 1.0, 0.5, 24), '#e6d4ff'); bowl.position.y = 0.25; g.add(bowl);
const water = M(new THREE.CylinderGeometry(1.15, 1.15, 0.05, 24), '#9fdcff', 0.9); water.position.y = 0.5; g.add(water);
const col = M(new THREE.CylinderGeometry(0.16, 0.2, 1.0, 10), '#e6d4ff'); col.position.y = 1.0; g.add(col);
const fish = M(new THREE.SphereGeometry(0.28, 12, 8), '#ff9a3c', 0.5); fish.scale.set(0.8, 1, 0.6); fish.position.y = 1.65; g.add(fish);
const tail = M(new THREE.ConeGeometry(0.18, 0.3, 8), '#ff9a3c'); tail.position.y = 1.95; g.add(tail);
const at = spot.clone().setY(spot.y + 2);
d.anim = (t, dt) => { water.rotation.y = t * 0.3; fish.rotation.y = Math.sin(t) * 0.3; if (Math.random() < dt * 20) this.fx.emit(at, 1, { color: ['#9fdcff', '#ffffff'], speed: 1.2, up: 2.5, grav: 6, life: 0.8, size: 0.06 }); };
} else if (kind === 'rainbow') {
const cols = ['#ff7a9c', '#ffb36b', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'];
cols.forEach((c, i) => { const a = M(new THREE.TorusGeometry(3.2 - i * 0.22, 0.12, 8, 40, Math.PI), c, 0.4); a.position.y = 0.1; g.add(a); });
d.anim = (t, dt) => { if (Math.random() < dt * 4) this.fx.emit(this.tmp.set(spot.x + (Math.random() - 0.5) * 6, spot.y + 3, spot.z), 1, { color: cols, speed: 0.3, up: 0.5, grav: 0.5, life: 2, size: 0.08 }); };
}
if (kind !== 'wand') this.scene.add(g);
return d;
}
private placeDecos() {
for (const kind of KIND_ORDER) {
if (!this.save.owned.includes(kind) || this.decos.has(kind)) continue;
const i = KIND_ORDER.indexOf(kind), [x, z] = DECO_SPOTS[i];
const spot = new THREE.Vector3(x, this.world.topAt(x, z), z);
const d = this.buildDeco(kind, spot);
if (kind === 'slide' || kind === 'rainbow') d.group.rotation.y = Math.atan2(-x, -z) + Math.PI;
this.decos.set(kind, d);
}
}
// ---------- coming and going ----------
enter() {
this.active = true; this.ui.hidden = false;
this.placeDecos();
// every befriended cat moves in (and stays forever)
for (const id of this.save.caughtEver) {
if (this.cats.some(c => c.def.id === id)) continue;
const def = CAT_DEFS.find(d => d.id === id); if (!def) continue;
const a = Math.random() * Math.PI * 2, r = 3 + Math.random() * 6;
const at = new THREE.Vector3(Math.cos(a) * r, 2.5, Math.sin(a) * r);
const c = new HomeCat(def, this.world, at); this.cats.push(c); this.scene.add(c.rig.root);
}
this.buildTrophies();
this.sign.visible = this.cats.length === 0;
this.player.body.pos.set(0, 2.2, 6); this.player.body.vel.set(0, 0, 0); this.player.yaw = Math.PI;
this.camYaw = 0; this.camPos.set(0, 9, 16);
this.wandBtn.hidden = !this.save.owned.includes('wand');
this.refreshCandy();
audio.startMusic('home');
// everyone runs over to say hello
for (const c of this.cats) { c.state = 'hello'; c.timer = 2.5 + Math.random(); }
this.toast(this.cats.length ? '🏡 Welcome home!' : '🏡 Catch cats in the kingdom and they come to live here!');
}
/** Trophy shelf in front of the cottage: one trophy per win, plus a see-through one for the next win. */
private buildTrophies() {
const n = this.save.trophies.length;
const bases = ['#b07dff', '#ff7fb0', '#7cc8ff', '#8fe39b', '#ffb36b'];
const slot = (i: number) => { const row = Math.floor(i / 7), col = i % 7; const x = -4.5 + col * 1.5, z = -8.6 + row * 1.6; return new THREE.Vector3(x, this.world.topAt(x, z), z); };
while (this.trophies.length < Math.min(n, 21)) {
const i = this.trophies.length, g = makeTrophy(); g.scale.setScalar(0.5); g.position.copy(slot(i));
const base = g.children[0] as THREE.Mesh; base.material = softMaterial(bases[i % bases.length], 0.8);
this.scene.add(g); this.trophies.push({ g, spin: 0, i });
}
if (this.ghost) this.scene.remove(this.ghost);
if (n < 21) {
const g = makeTrophy(); g.scale.setScalar(0.5); g.position.copy(slot(n));
const glass = new THREE.MeshBasicMaterial({ color: '#ffffff', transparent: true, opacity: 0.35, depthWrite: false });
g.traverse(o => { if ((o as THREE.Mesh).isMesh) (o as THREE.Mesh).material = glass; });
this.ghost = g; this.scene.add(g);
}
}
private celebrate(tr: { g: THREE.Group; spin: number; i: number }) {
tr.spin = 1.4; audio.play('trophy', { volume: 0.7 });
const w = this.save.trophies[tr.i];
this.fx.emit(this.tmp.copy(tr.g.position).setY(tr.g.position.y + 1.4), 70, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff', '#ffffff'], speed: 5, up: 4, size: 0.12, life: 1.5 });
if (w) this.toast(`🏆 #${tr.i + 1} · ⏱ ${Math.floor(w.seconds / 60)}:${String(w.seconds % 60).padStart(2, '0')} · 🍬 ${w.candy}`);
this.player.happyT = 1.5;
}
leave() { this.active = false; this.ui.hidden = true; this.closeOverlay(); this.onExit(); }
private refreshCandy() { this.candyEl.textContent = String(this.save.candy); }
nameOf(def: CatDef) { return this.save.names[def.id] || def.name; }
// ---------- interactions ----------
private pet(c: HomeCat) {
c.petCount++;
const poses: Pose[] = ['roll', 'flop', 'wiggle', 'spin', 'pancake'];
c.state = 'petted'; c.timer = 1.6; c.pathPose = poses[c.petCount % poses.length];
c.rig.flash('happy', 1.8);
audio.play('pet'); audio.play('purr', { volume: 0.7 });
if (c.petCount % 3 === 0) audio.meow(c.def.voice, 'happy');
this.player.hugT = 0.4; this.player.happyT = 1.2;
this.fx.emit(this.tmp.copy(c.pos).setY(c.pos.y + 1), 10, { color: ['#ff7fb0', '#ff4d88', '#ffd1e6'], speed: 1.2, up: 1.6, grav: 0, life: 1.3, size: 0.13 });
}
treat() {
const c = this.near; if (!c || c.treatT > 0) return;
c.treatT = 2.5; c.state = 'eat'; c.timer = 2.2; c.rig.flash('happy', 2.4);
audio.play('treat');
this.fx.emit(this.tmp.copy(c.pos).setY(c.pos.y + 0.6), 14, { color: ['#e8b98a', '#ffe066', '#ffffff'], speed: 1.5, up: 2, size: 0.08 });
setTimeout(() => { audio.meow(c.def.voice, 'happy'); this.fx.emit(this.tmp.copy(c.pos).setY(c.pos.y + 1.2), 8, { color: ['#ff7fb0', '#ff4d88'], speed: 0.8, up: 1.4, grav: 0, life: 1.4, size: 0.13 }); }, 1500);
}
private closeOverlay() { if (this.overlay) { this.overlay.remove(); this.overlay = null; } this.ui.classList.remove('covered'); }
private openRename() {
const c = this.near; if (!c) return;
audio.play('click'); this.closeOverlay();
const o = this.el(`<div class="screen"><h1 class="logo mid">${c.def.emoji} New name</h1><input class="nameinput" maxlength="14" aria-label="Cat name" autocomplete="off"><div class="row"><button class="big" data-x="ok" aria-label="Save name">✔</button><button class="big alt" data-x="no" aria-label="Cancel">✖</button></div></div>`);
const inp = o.querySelector('input') as HTMLInputElement; inp.value = this.nameOf(c.def);
o.addEventListener('click', e => {
const x = (e.target as HTMLElement).closest('[data-x]')?.getAttribute('data-x');
if (x === 'ok') { const v = inp.value.replace(/[<>&"]/g, '').trim().slice(0, 14); if (v) { this.save.names[c.def.id] = v; persist(this.save); (this.card.querySelector('.nm') as HTMLElement).textContent = `${c.def.emoji} ${v}`; this.toast(`💖 Hello, ${v}!`); audio.meow(c.def.voice, 'happy'); } this.closeOverlay(); }
if (x === 'no') this.closeOverlay();
});
inp.addEventListener('keydown', e => { if (e.key === 'Enter') (o.querySelector('[data-x="ok"]') as HTMLElement).click(); });
this.ui.appendChild(o); this.overlay = o; this.ui.classList.add('covered'); setTimeout(() => inp.focus(), 50);
}
private openShop() {
audio.play('click'); this.closeOverlay();
const card = (key: string, emoji: string, name: string, about: string, price: number, own: boolean, wearing = false) =>
`<button class="shopitem${wearing ? ' wear' : own ? ' own' : this.save.candy >= price ? '' : ' poor'}" data-buy="${key}" aria-label="${name}"><span class="em">${emoji}</span><b>${name}</b>${about ? `<small>${about}</small>` : ''}<span class="price">${wearing ? '✨ Wearing' : own ? (key.includes(':') ? '👆 Wear' : '✔ Yours') : '🍬 ' + price}</span></button>`;
const home = DECOS.filter(d => d.price > 0).map(d => card(d.id, d.emoji, d.name, d.about, d.price, this.save.owned.includes(d.id))).join('');
const hoods = HOODS.map(h => card('hood:' + h.id, h.emoji, h.name, '', h.price, h.price === 0 || this.save.owned.includes('hood:' + h.id), this.save.outfit.hood === h.id)).join('');
const hats = HATS.map(h => card('hat:' + h.id, h.emoji, h.name, '', h.price, h.price === 0 || this.save.owned.includes('hat:' + h.id), this.save.outfit.hat === h.id)).join('');
const o = this.el(`<div class="screen shop"><h1 class="logo mid">Candy Shop</h1><p class="tag">You have 🍬 ${this.save.candy}</p>
<h2 class="shophead">🏡 For the cats</h2><div class="shopgrid">${home}</div>
<h2 class="shophead">👗 For you</h2><div class="shopgrid">${hoods}${hats}</div>
<button class="big" data-buy="close" aria-label="Close shop">✔</button></div>`);
o.addEventListener('click', e => {
const id = (e.target as HTMLElement).closest('[data-buy]')?.getAttribute('data-buy');
if (!id) return;
if (id === 'close') { audio.play('click'); this.closeOverlay(); return; }
if (id.includes(':')) { this.wardrobe(id); return; }
const d = DECOS.find(k => k.id === id)!;
if (this.save.owned.includes(d.id)) return;
if (this.save.candy < d.price) { audio.play('bump'); this.toast(`🍬 ${d.price - this.save.candy} more candy!`); return; }
this.save.candy -= d.price; this.save.owned.push(d.id); persist(this.save);
audio.play('buy'); audio.play('unlock');
this.closeOverlay(); this.placeDecos(); this.refreshCandy();
this.wandBtn.hidden = !this.save.owned.includes('wand');
const deco = this.decos.get(d.id);
if (deco && d.id !== 'wand') { this.fx.emit(this.tmp.copy(deco.spot).setY(deco.spot.y + 1.5), 80, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 5, up: 3, size: 0.13 }); }
this.toast(`${d.emoji} ${d.name}!`);
// a curious cat comes to try it right away
const c = this.cats.find(k => k.state !== 'use'); if (c && deco && d.id !== 'wand') this.sendTo(c, deco);
});
this.ui.appendChild(o); this.overlay = o; this.ui.classList.add('covered');
}
/** Buy or put on a hoodie or hat. */
private wardrobe(key: string) {
const [kind, id] = key.split(':');
const item = kind === 'hood' ? HOODS.find(h => h.id === id) : HATS.find(h => h.id === id);
if (!item) return;
const own = item.price === 0 || this.save.owned.includes(key);
if (!own) {
if (this.save.candy < item.price) { audio.play('bump'); this.toast(`🍬 ${item.price - this.save.candy} more candy!`); return; }
this.save.candy -= item.price; this.save.owned.push(key); audio.play('buy');
}
if (kind === 'hood') this.save.outfit.hood = id; else this.save.outfit.hat = id;
persist(this.save); applyOutfit(this.player, this.save.outfit); this.refreshCandy();
audio.play('wear'); this.player.happyT = 2; this.showOffT = 3;
this.fx.emit(this.tmp.copy(this.player.body.pos).setY(this.player.body.pos.y + 1.2), 40, { color: ['#ffffff', '#ffe066', '#ff7fb0', '#b8e6ff'], speed: 3, up: 2, size: 0.1 });
this.toast(`${item.emoji} ${item.name}!`);
this.closeOverlay();
}
private sendTo(c: HomeCat, d: Deco) { c.deco = d; c.state = 'goto'; c.timer = 12; c.target.copy(d.spot); d.users++; }
private freeDeco(c: HomeCat) { if (c.deco) { c.deco.users = Math.max(0, c.deco.users - 1); c.deco = null; } }
/** Begin using a decoration: physical (trampoline) or a scripted path (tower, slide, ball pit). */
private use(c: HomeCat, d: Deco) {
c.state = 'use'; c.path = []; c.pathT = 0;
const s = d.spot, k = d.def.id;
const v = (x: number, y: number, z: number) => new THREE.Vector3(s.x + x, s.y + y, s.z + z);
if (k === 'bed') { c.timer = 7 + Math.random() * 5; c.pathPose = 'sleep'; c.path = [v((Math.random() - 0.5) * 0.6, 0.35, (Math.random() - 0.5) * 0.6)]; }
else if (k === 'yarn') { c.timer = 5; c.pathPose = 'roll'; }
else if (k === 'fountain' || k === 'rainbow') { c.timer = 5; c.pathPose = 'sit'; }
else if (k === 'trampoline') { c.timer = 5; c.pathPose = 'stand'; c.target.copy(s); }
else if (k === 'tower') { c.timer = 8; c.pathPose = 'sit'; c.path = [v(-0.2, 1.0, 0.4), v(0.35, 2.0, 0.3), v(0, 3.25, 0)]; }
else if (k === 'slide') {
const r = d.group.rotation.y, rot = (x: number, y: number, z: number) => { const p = new THREE.Vector3(x, y, z).applyAxisAngle(new THREE.Vector3(0, 1, 0), r); return p.add(s); };
c.timer = 3.6; c.pathPose = 'pancake'; c.path = [rot(0, 0, -1.7), rot(0, 2.7, -1.2), rot(0, 2.6, -0.3), rot(0, 1.4, 1.2), rot(0, 0.2, 3.3)];
} else if (k === 'pit') { c.timer = 3.2; c.pathPose = 'roll'; c.path = [v(0, 1.6, 0), v(0, 0.1, 0), v(0, 0.1, 0), v(0.3, 1.8, 0.3), v(1.8, 0, 1.8)]; }
}
// ---------- frame ----------
update(dt: number, inp: InputState, camera: THREE.PerspectiveCamera) {
this.t += dt; const t = this.t;
const overlay = !!this.overlay;
const pin = overlay ? { ...inp, moveX: 0, moveY: 0, action: false, actionPressed: false } : inp;
// nearest cat for petting
const pp = this.player.body.pos;
let near: HomeCat | null = null, nd = 2.4;
const cur = this.near;
if (cur && cur.path.length === 0 && Math.hypot(cur.pos.x - pp.x, cur.pos.z - pp.z) < 3.0) { near = cur; nd = -1; }
for (const c of this.cats) { const d = Math.hypot(c.pos.x - pp.x, c.pos.z - pp.z); if (d < nd && Math.abs(c.pos.y - pp.y) < 2.5 && c.path.length === 0) { nd = d; near = c; } }
// a cat next to you stops to say hello, so pets, treats and names go to the cat you see on the card
if (near && (near.state === 'wander' || near.state === 'goto' || near.state === 'boop')) { this.freeDeco(near); near.state = 'hello'; near.timer = 3; }
if (near !== this.near) {
this.near = near; this.card.hidden = !near;
if (near) (this.card.querySelector('.nm') as HTMLElement).textContent = `${near.def.emoji} ${this.nameOf(near.def)}`;
}
let allowJump = true;
if (near && pin.actionPressed) { allowJump = false; this.pet(near); }
else if (pin.actionPressed) {
const tr = this.trophies.find(k => Math.hypot(k.g.position.x - pp.x, k.g.position.z - pp.z) < 1.3);
if (tr) { allowJump = false; this.celebrate(tr); }
}
for (const tr of this.trophies) { tr.spin = Math.max(0, tr.spin - dt); tr.g.rotation.y += dt * (0.4 + tr.spin * 9); tr.g.position.y = this.world.topAt(tr.g.position.x, tr.g.position.z) + Math.sin(Math.min(1, tr.spin / 1.4) * Math.PI) * 0.8; }
if (this.ghost) this.ghost.rotation.y += dt * 0.4;
this.player.update(dt, pin, this.camYaw, this.bouncers, allowJump);
if (this.player.justJumped) audio.play('jump');
if (this.player.body.bounced) audio.play('boing');
if (pp.y < -4) { pp.set(0, 3, 6); this.player.body.vel.set(0, 0, 0); }
const wand = this.wandHeld && this.save.owned.includes('wand') && !overlay;
if (wand && Math.random() < dt * 10) this.fx.emit(this.tmp.copy(pp).setY(pp.y + 1.6), 1, { color: ['#ffffff', '#ffd1e6', '#b8e6ff'], speed: 0.6, up: 0.4, grav: 1, life: 0.9, size: 0.07 });
for (const c of this.cats) this.updateCat(c, dt, wand);
for (const d of this.decos.values()) d.anim?.(t, dt);
for (const r of this.rexes) { const ev = r.update(dt, pp, this.cats, true, this.player.justJumped); if (ev === 'rawr') audio.play('rawr', { volume: 0.5 }); else if (ev === 'hatch') { r.root.visible = true; } }
if (this.sign.visible) this.sign.rotation.y = Math.sin(t) * 0.1;
this.fx.update(dt);
// camera: same feel as the kingdom
if (Math.abs(inp.camX) + Math.abs(inp.camY) > 0) { this.manualCamT = 2; this.camYaw -= inp.camX * 0.006; this.camPitch = clamp(this.camPitch + inp.camY * 0.004, 0.15, 1.1); }
this.manualCamT -= dt;
const speed = Math.hypot(this.player.body.vel.x, this.player.body.vel.z);
if (this.manualCamT <= 0 && speed > 1) this.camYaw += angleDiff(this.camYaw, this.player.yaw + Math.PI) * damp(1.0, dt) * clamp(Math.abs(inp.moveX) + 0.25, 0, 1);
this.showOffT -= dt;
if (this.showOffT > 0) { this.player.yaw = this.camYaw; this.player.root.rotation.y = this.camYaw; }
const dist = this.showOffT > 0 ? 4.2 : 8.5, p = this.showOffT > 0 ? 0.3 : this.camPitch;
const want = this.tmp.set(pp.x + Math.sin(this.camYaw) * Math.cos(p) * dist, pp.y + 1.2 + Math.sin(p) * dist, pp.z + Math.cos(this.camYaw) * Math.cos(p) * dist);
this.camPos.lerp(want, damp(6, dt));
this.camLook.lerp(this.tmp.copy(pp).setY(pp.y + 1), damp(10, dt));
camera.position.copy(this.camPos); camera.lookAt(this.camLook);
const ax = this.camPos.x, az = this.camPos.z, vx = pp.x - ax, vz = pp.z - az, vl = vx * vx + vz * vz || 1;
for (const d of this.decos.values()) {
const px = d.spot.x - ax, pz = d.spot.z - az, u = (px * vx + pz * vz) / vl;
const r = d.def.id === 'rainbow' ? 3.6 : 1.8;
d.group.visible = !(u > 0 && u < 0.95 && Math.hypot(px - vx * u, pz - vz * u) < r);
}
for (const c of this.cats) { const px = c.pos.x - ax, pz = c.pos.z - az, u = (px * vx + pz * vz) / vl; c.rig.root.visible = !(u > 0 && u < 0.85 && Math.hypot(px - vx * u, pz - vz * u) < 1.3); }
}
private updateCat(c: HomeCat, dt: number, wand: boolean) {
const b = c.body, p = b.pos, rig = c.rig, pp = this.player.body.pos;
c.timer -= dt; c.treatT -= dt;
let pose: Pose = 'stand', speed = 0;
const dPlayer = Math.hypot(pp.x - p.x, pp.z - p.z);
// the feather wand wins over everything except a scripted move
if (wand && c.path.length === 0 && dPlayer < 14 && c.state !== 'chase') { this.freeDeco(c); c.state = 'chase'; }
if (!wand && c.state === 'chase') { c.state = 'sit'; c.timer = 1.5; rig.flash('happy', 1); }
switch (c.state) {
case 'hello': { const n = this.cats.length, ha = this.camYaw + Math.PI + (n > 1 ? (this.cats.indexOf(c) / (n - 1) - 0.5) : 0) * 2.6; c.target.set(pp.x + Math.sin(ha) * 2.3, 0, pp.z + Math.cos(ha) * 2.3); } speed = Math.hypot(c.target.x - p.x, c.target.z - p.z) > 0.5 ? 4 : 0; if (speed === 0) this.yawTo(c, pp.x, pp.z, dt); if (speed === 0) { pose = 'sit'; rig.wag = 2; } if (c.timer < 0) { c.state = 'wander'; c.timer = 1; } break;
case 'chase': {
// run in playful circles around the player, pouncing at the feather
const a = this.t * 1.5 + c.def.voice * 6;
c.target.set(pp.x + Math.cos(a) * 1.8, 0, pp.z + Math.sin(a) * 1.8); speed = 5.5;
if (b.grounded && Math.random() < dt * 1.2) { b.vel.y = 7; rig.flash('happy', 0.6); }
break;
}
case 'wander':
speed = Math.hypot(c.target.x - p.x, c.target.z - p.z) > 0.6 ? 2 : 0;
if (c.timer < 0) this.decide(c);
break;
case 'goto':
speed = 3.2;
if (c.deco && Math.hypot(c.target.x - p.x, c.target.z - p.z) < (c.deco.def.id === 'trampoline' ? 0.6 : 1.4)) this.use(c, c.deco);
else if (c.timer < 0) { this.freeDeco(c); c.state = 'wander'; c.timer = 1; }
break;
case 'use': {
const k = c.deco?.def.id;
pose = c.pathPose;
if (k === 'trampoline') { c.target.copy(c.deco!.spot); speed = 1.2; pose = b.grounded ? 'stand' : 'wiggle'; if (b.bounced) { rig.flash('happy', 0.8); if (Math.random() < 0.3) audio.play('boing', { volume: 0.35 }); } }
if (k === 'yarn' && c.deco) { const s = c.deco.spot; const a = this.t * 2; c.target.set(s.x + Math.cos(a) * 0.9, 0, s.z + Math.sin(a) * 0.9); speed = 1.5; pose = Math.sin(this.t * 3) > 0 ? 'roll' : 'wiggle'; }
if ((k === 'fountain' || k === 'rainbow') && c.deco) { const s = c.deco.spot; this.yawTo(c, s.x, s.z, dt); }
if (c.timer < 0 && c.path.length === 0) { this.freeDeco(c); c.state = 'wander'; c.timer = 1 + Math.random() * 2; this.pickWander(c); }
break;
}
case 'sit': pose = 'sit'; if (c.timer < 0) this.decide(c); break;
case 'sleep': pose = 'sleep'; rig.face = 'sleep'; if (c.timer < 0) this.decide(c); break;
case 'eat': pose = 'eat'; this.yawTo(c, pp.x, pp.z, dt); if (c.timer < 0) { c.state = 'sit'; c.timer = 1.5; } break;
case 'petted': pose = c.pathPose; if (c.timer < 0) { c.state = 'sit'; c.timer = 2; this.yawTo(c, pp.x, pp.z, 1); } break;
case 'boop': {
const pal = c.pal; if (!pal) { c.state = 'wander'; break; }
c.target.copy(pal.pos); const d = Math.hypot(pal.pos.x - p.x, pal.pos.z - p.z);
speed = d > 0.9 ? 2.6 : 0;
if (d <= 0.9) { pose = 'sit'; this.yawTo(c, pal.pos.x, pal.pos.z, dt); if (c.timer > 0.5 && c.timer < 0.6) { this.fx.emit(this.tmp.copy(p).lerp(pal.pos, 0.5).setY(p.y + 1), 6, { color: ['#ff7fb0', '#ff4d88'], speed: 0.6, up: 1.2, grav: 0, life: 1.2, size: 0.12 }); c.rig.flash('happy', 1.2); pal.rig.flash('happy', 1.2); } }
if (c.timer < 0) { c.pal = null; c.state = 'wander'; c.timer = 1; this.pickWander(c); }
break;
}
}
if (c.path.length) {
// scripted move along a path (climb, slide, dive)
const seg = c.deco?.def.id === 'slide' ? 0.55 : 0.7;
c.pathT += dt / seg;
const i = Math.min(Math.floor(c.pathT), c.path.length - 1);
const from = i === 0 ? (c.path.length > 1 ? c.path[0] : p.clone()) : c.path[i - 1];
const to = c.path[i], f = clamp(c.pathT - i, 0, 1);
if (c.path.length === 1) { p.lerp(to, damp(6, dt)); }
else {
const hop = Math.sin(f * Math.PI) * (c.deco?.def.id === 'slide' && i >= 3 ? 0 : 0.5);
p.lerpVectors(from, to, f).y += hop;
if (to.x !== from.x || to.z !== from.z) this.yawTo(c, to.x + (to.x - from.x), to.z + (to.z - from.z), dt);
}
pose = c.pathPose;
if (c.deco?.def.id === 'slide' && i >= 3) { pose = 'pancake'; rig.flash('happy', 0.3); if (Math.random() < dt * 30) this.fx.emit(this.tmp.copy(p).setY(p.y + 0.3), 1, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff'], speed: 1, size: 0.08 }); }
if (c.deco?.def.id === 'pit' && i === 2 && f < 0.1) { audio.play('pop', { volume: 0.5 }); this.fx.emit(this.tmp.copy(p).setY(p.y + 0.7), 20, { color: ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'], speed: 3, up: 4, size: 0.15 }); }
const last = c.path.length === 1 ? c.timer < 0 : c.pathT >= c.path.length - (c.deco?.def.id === 'tower' ? 0 : 0);
if (c.deco?.def.id === 'tower' && c.pathT >= c.path.length) { pose = 'sit'; if (c.timer < 0) { c.path = [p.clone(), c.deco.spot.clone().add(new THREE.Vector3(1.3, 0, 1.3))]; c.pathT = 0; c.timer = 99; c.deco = (this.freeDeco(c), null); c.pathPose = 'wiggle'; } }
else if (last && c.pathT >= c.path.length) { c.path = []; b.vel.set(0, 0, 0); if (c.state === 'use' && c.deco?.def.id !== 'bed') { this.freeDeco(c); c.state = 'wander'; c.timer = 1.5; this.pickWander(c); } else if (!c.deco) { c.state = 'wander'; c.timer = 1; } }
else if (c.path.length === 1 && c.timer < 0) { c.path = []; }
b.vel.set(0, 0, 0);
} else {
const dx = c.target.x - p.x, dz = c.target.z - p.z, l = Math.hypot(dx, dz) || 1;
const mx = speed > 0 ? dx / l : 0, mz = speed > 0 ? dz / l : 0;
b.vel.x += (mx * speed - b.vel.x) * damp(b.grounded ? 10 : 3, dt);
b.vel.z += (mz * speed - b.vel.z) * damp(b.grounded ? 10 : 3, dt);
const blocked = b.step(dt, 24, this.bouncers);
if (blocked && b.grounded && speed > 0.5) b.vel.y = 8;
if (speed > 0.3) c.yaw = angleLerp(c.yaw, Math.atan2(b.vel.x, b.vel.z), damp(10, dt));
if (p.y < -4) p.set(0, 3, 0);
}
rig.pose = pose; rig.speed = c.path.length ? 0 : Math.hypot(b.vel.x, b.vel.z); rig.airborne = c.path.length ? false : !b.grounded; rig.vy = b.vel.y;
rig.root.position.copy(p); rig.root.rotation.y = c.yaw;
rig.root.userData.groundY = this.world.groundBelow(p.x, p.z, p.y + 0.1);
const toP = Math.atan2(pp.x - p.x, pp.z - p.z);
rig.lookYaw = dPlayer < 7 && pose !== 'sleep' ? ((toP - c.yaw + Math.PI * 3) % (Math.PI * 2)) - Math.PI : 0;
rig.setMotionDrift(b.vel.x, b.vel.z);
rig.update(dt);
if (c === this.near) rig.root.scale.setScalar(c.rig.scale * (1 + Math.sin(this.t * 10) * 0.03));
else rig.root.scale.setScalar(c.rig.scale);
}
private yawTo(c: HomeCat, x: number, z: number, dt: number) { c.yaw = angleLerp(c.yaw, Math.atan2(x - c.pos.x, z - c.pos.z), clamp(damp(8, dt), 0, 1)); }
private pickWander(c: HomeCat) { const a = Math.random() * Math.PI * 2, r = 2 + Math.random() * 9; c.target.set(Math.cos(a) * r, 0, Math.sin(a) * r); }
private decide(c: HomeCat) {
const r = Math.random();
const decos = [...this.decos.values()].filter(d => d.def.id !== 'wand' && d.users < (d.def.id === 'bed' || d.def.id === 'pit' || d.def.id === 'tower' ? 2 : 3));
if (r < 0.55 && decos.length) { this.sendTo(c, decos[Math.floor(Math.random() * decos.length)]); return; }
if (r < 0.7 && this.cats.length > 1) { const pal = this.cats.filter(k => k !== c && k.path.length === 0)[0 | (Math.random() * (this.cats.length - 1))]; if (pal) { c.pal = pal; c.state = 'boop'; c.timer = 4; return; } }
if (r < 0.82) { c.state = 'sit'; c.timer = 2 + Math.random() * 3; return; }
if (r < 0.9) { c.state = 'sleep'; c.timer = 4 + Math.random() * 4; return; }
c.state = 'wander'; c.timer = 3 + Math.random() * 3; this.pickWander(c);
}
}
export { lerp };
mountain.ts, Chocolate Mountain (src/game/mountain.ts)335 lines
// Chocolate Mountain: a gentle slide run around a chocolate mountain.
// She rides a cookie sled down a railed slide (she cannot fall off), steers left and right,
// and catches cats that slide along with her. A missed cat just pops up ahead again: no fail state.
import * as THREE from 'three';
import { Player } from '../player/player';
import type { InputState } from '../input/input';
import { VoxelWorld } from '../world/voxels';
import { CatRig } from '../cats/catModel';
import { CAT_DEFS } from '../cats/cats';
import type { CatDef } from '../cats/cats';
import { Particles } from '../fx/particles';
import { softMaterial } from '../render/fur';
import { makeSky } from '../render/sky';
import { makeTrophy } from './characters';
import { applyOutfit } from './wardrobe';
import { audio } from '../audio';
import type { SaveV1 } from '../save/save';
import { persist } from '../save/save';
import { clamp, damp, lerp } from '../core/util';
const HALF = 2.4; // half width of the slide floor
const BOWL = 2.9; // radius of the half-pipe cross-section
const N = 700; // samples along the slide
const CANDY_COLORS = ['#ff7a9c', '#ffe57a', '#8fe39b', '#7cc8ff', '#b79bff'];
interface SlideCat { def: CatDef; rig: CatRig; s: number; x: number; h: number; vh: number; phase: number; caught: boolean; order: number; sx: number }
interface Pickup { s: number; x: number; mesh: THREE.Object3D; taken: boolean; kind: 'candy' | 'boost' | 'ramp' }
export class Mountain {
scene = new THREE.Scene();
player: Player;
fx = new Particles(600);
active = false;
onExit: () => void = () => {};
private curve: THREE.CatmullRomCurve3;
private pts: THREE.Vector3[] = []; private tans: THREE.Vector3[] = []; private rights: THREE.Vector3[] = [];
private L = 0;
private s = 0; private x = 0; private h = 0; private vh = 0; private v = 0;
private cats: SlideCat[] = [];
private pickups: Pickup[] = [];
private sled: THREE.Group;
private ring: THREE.Mesh;
private phase: 'count' | 'ride' | 'finish' = 'count';
private countT = 0; private t = 0; private boostT = 0; private runCandy = 0; private runT = 0;
private camPos = new THREE.Vector3(); private camLook = new THREE.Vector3();
private ui: HTMLElement; private catRow: HTMLElement; private candyEl: HTMLElement;
private endScreen: HTMLElement | null = null;
private trophy: THREE.Group | null = null;
private tmp = new THREE.Vector3(); private tmp2 = new THREE.Vector3();
constructor(private save: SaveV1, root: HTMLElement, private el: (h: string) => HTMLElement, private toast: (t: string) => void) {
this.scene.background = new THREE.Color('#ffe9d6');
this.scene.add(makeSky('0.68,0.83,1.0', '1.0,0.88,0.8'));
this.scene.add(new THREE.HemisphereLight('#e8f0ff', '#ffd1b0', 1.6));
const sun = new THREE.DirectionalLight('#fff3e0', 1.6); sun.position.set(30, 60, 20); this.scene.add(sun);
this.scene.add(this.fx.mesh);
// spiral path: two turns around the mountain, from the top down to the candy meadow
const ctl: THREE.Vector3[] = [];
for (let i = 0; i <= 40; i++) {
const t = i / 40, a = t * Math.PI * 4 + 0.6, r = 13 + 21 * t, y = 58 * (1 - t) + 2;
ctl.push(new THREE.Vector3(Math.cos(a) * r, y, Math.sin(a) * r));
}
// flat run-out into the finish meadow
const last = ctl[ctl.length - 1], dir = ctl[ctl.length - 1].clone().sub(ctl[ctl.length - 2]).setY(0).normalize();
for (let k = 1; k <= 3; k++) ctl.push(last.clone().addScaledVector(dir, k * 6).setY(2));
this.curve = new THREE.CatmullRomCurve3(ctl);
this.L = this.curve.getLength();
const up = new THREE.Vector3(0, 1, 0);
for (let i = 0; i <= N; i++) {
const u = i / N;
const p = this.curve.getPointAt(u), tn = this.curve.getTangentAt(u);
this.pts.push(p); this.tans.push(tn); this.rights.push(new THREE.Vector3().crossVectors(tn, up).normalize());
}
this.buildSlide();
this.buildScenery();
this.player = new Player(new VoxelWorld(4, 4, 4));
this.scene.add(this.player.root);
this.sled = this.makeSled(); this.scene.add(this.sled);
this.ring = new THREE.Mesh(new THREE.TorusGeometry(0.75, 0.08, 8, 32), new THREE.MeshBasicMaterial({ color: '#ffcf3f' }));
this.ring.rotation.x = -Math.PI / 2; this.scene.add(this.ring);
// UI
this.ui = el(`<div class="home-ui" hidden></div>`); root.appendChild(this.ui);
const bar = el(`<div class="hud"><div class="pill cats mt"></div><div class="row"><div class="pill">🍬 <span class="hc">0</span></div><button class="iconbtn" data-a="exit" aria-label="Back to the kingdom">🏰</button></div></div>`);
this.ui.appendChild(bar);
this.catRow = bar.querySelector('.mt') as HTMLElement; this.candyEl = bar.querySelector('.hc') as HTMLElement;
this.ui.addEventListener('click', e => {
const a = (e.target as HTMLElement).closest('[data-a]')?.getAttribute('data-a');
if (a === 'exit') { audio.play('click'); this.leave(); }
if (a === 'again') { audio.play('click'); this.start(); }
});
}
// ---------- building ----------
private frameAt(s: number) {
const f = clamp(s / this.L, 0, 1) * N, i = Math.min(N - 1, Math.floor(f)), k = f - i;
const p = this.tmp.copy(this.pts[i]).lerp(this.pts[i + 1], k);
const r = this.tmp2.copy(this.rights[i]).lerp(this.rights[i + 1], k).normalize();
return { p, r, tn: this.tans[i] };
}
/** Height of the bowl floor at sideways offset x. */
private bowlY(x: number) { const q = clamp(x / BOWL, -0.95, 0.95); return (1 - Math.cos(Math.asin(q))) * BOWL * 0.75; }
private posAt(s: number, x: number, h: number, out: THREE.Vector3) {
const { p, r } = this.frameAt(s);
return out.copy(p).addScaledVector(r, x).setY(p.y + this.bowlY(x) + h);
}
private buildSlide() {
const SEC = 13, verts: number[] = [], cols: number[] = [], idx: number[] = [];
const choc = new THREE.Color('#8a5a3c'), choc2 = new THREE.Color('#a06a44'), cara = new THREE.Color('#f2b86b');
for (let i = 0; i <= N; i++) {
const p = this.pts[i], r = this.rights[i];
const stripe = Math.floor((i / N) * this.L / 3) % 2 === 0;
for (let j = 0; j <= SEC; j++) {
const x = -BOWL * 0.97 + (j / SEC) * BOWL * 1.94;
const y = this.bowlY(x);
verts.push(p.x + r.x * x, p.y + y - 0.02, p.z + r.z * x);
const c = j === 0 || j === SEC ? cara : stripe ? choc : choc2;
cols.push(c.r, c.g, c.b);
}
}
for (let i = 0; i < N; i++) for (let j = 0; j < SEC; j++) {
const a = i * (SEC + 1) + j, b = a + SEC + 1;
idx.push(a, b, a + 1, a + 1, b, b + 1);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
g.setAttribute('color', new THREE.Float32BufferAttribute(cols, 3));
g.setIndex(idx); g.computeVertexNormals();
const m = new THREE.Mesh(g, new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.DoubleSide }));
this.scene.add(m);
// candy-cane rails on both sides
for (const side of [-1, 1]) {
const rp: THREE.Vector3[] = [];
for (let i = 0; i <= N; i += 4) { const x = side * BOWL * 0.97; rp.push(this.pts[i].clone().addScaledVector(this.rights[i], x).setY(this.pts[i].y + this.bowlY(x) + 0.35)); }
const rail = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(rp), 600, 0.16, 8), softMaterial(side < 0 ? '#ff8fb8' : '#ffffff', 0.6));
this.scene.add(rail);
// posts
const postGeo = new THREE.CylinderGeometry(0.08, 0.08, 0.6, 6);
const posts = new THREE.InstancedMesh(postGeo, softMaterial('#fff3d6'), Math.floor(N / 10) + 1);
const m4 = new THREE.Matrix4(); let k = 0;
for (let i = 0; i <= N; i += 10) { const q = rp[Math.min(rp.length - 1, Math.round(i / 4))]; m4.makeTranslation(q.x, q.y - 0.3, q.z); posts.setMatrixAt(k++, m4); }
posts.count = k; this.scene.add(posts);
}
}
private buildScenery() {
// the chocolate mountain with frosting on top
const mtn = new THREE.Mesh(new THREE.ConeGeometry(24, 66, 40, 6), softMaterial('#7a4a2c', 0.15));
mtn.position.y = 30; this.scene.add(mtn);
const frost = new THREE.Mesh(new THREE.ConeGeometry(9.2, 25, 40, 2, true), softMaterial('#fff6fb', 0.4));
frost.position.y = 53; this.scene.add(frost);
for (let i = 0; i < 9; i++) { const d = new THREE.Mesh(new THREE.SphereGeometry(0.9, 10, 8), softMaterial('#fff6fb', 0.4)); const a = i / 9 * Math.PI * 2; d.scale.set(1, 1.8, 1); d.position.set(Math.cos(a) * 8.7, 41.5, Math.sin(a) * 8.7); this.scene.add(d); }
const cherry = new THREE.Mesh(new THREE.SphereGeometry(1.6, 16, 12), softMaterial('#ff4d6d', 1.2)); cherry.position.y = 66; this.scene.add(cherry);
// candy meadow floor
const ground = new THREE.Mesh(new THREE.CircleGeometry(90, 48), softMaterial('#a8e6a1', 0.05)); ground.rotation.x = -Math.PI / 2; ground.position.y = 0; this.scene.add(ground);
// lollipop trees and gumdrops around the meadow (far from the slide)
const cols = ['#ffb3d9', '#b8e6ff', '#d7c2ff', '#fff1a6', '#b9f5d0'];
for (let n = 0; n < 40; n++) {
const a = Math.random() * Math.PI * 2, r = 42 + Math.random() * 40, x = Math.cos(a) * r, z = Math.sin(a) * r;
if (n % 2) { const stick = new THREE.Mesh(new THREE.CylinderGeometry(0.15, 0.15, 4, 6), softMaterial('#ffffff')); stick.position.set(x, 2, z); this.scene.add(stick); const top = new THREE.Mesh(new THREE.SphereGeometry(1.6, 14, 10), softMaterial(cols[n % 5], 0.8)); top.position.set(x, 4.6, z); this.scene.add(top); }
else { const gd = new THREE.Mesh(new THREE.SphereGeometry(1.4, 14, 10, 0, Math.PI * 2, 0, Math.PI / 2), softMaterial(cols[n % 5], 1)); gd.position.set(x, 0, z); this.scene.add(gd); }
}
}
private makeSled() {
const g = new THREE.Group();
const cookie = new THREE.Mesh(new THREE.CylinderGeometry(0.75, 0.75, 0.16, 24), softMaterial('#e3a55f', 0.2)); cookie.scale.z = 1.35; g.add(cookie);
const chips = new THREE.SphereGeometry(0.08, 6, 4);
for (let i = 0; i < 9; i++) { const c = new THREE.Mesh(chips, softMaterial('#5a3420')); const a = i * 2.4, r = 0.2 + (i % 3) * 0.17; c.position.set(Math.cos(a) * r, 0.09, Math.sin(a) * r * 1.3); g.add(c); }
return g;
}
// ---------- run ----------
debug() { return { phase: this.phase, s: Math.round(this.s), L: Math.round(this.L), caught: this.cats.filter(c => c.caught).length, candy: this.runCandy }; }
/** Test hook: jump ahead along the slide and put the next free cat right next to the player. */
skip(ds: number) { this.s = Math.min(this.L - 9, this.s + ds); const c = this.cats.find(k => !k.caught); if (c) { c.s = this.s + 1; c.x = this.x; } return this.debug(); }
enter() { this.active = true; this.ui.hidden = false; applyOutfit(this.player, this.save.outfit); this.start(); }
leave() { this.active = false; this.ui.hidden = true; if (this.endScreen) { this.endScreen.remove(); this.endScreen = null; } this.onExit(); }
start() {
if (this.endScreen) { this.endScreen.remove(); this.endScreen = null; }
if (this.trophy) { this.scene.remove(this.trophy); this.trophy = null; }
this.s = 9; this.x = 0; this.h = 0; this.vh = 0; this.v = 0; this.phase = 'count'; this.countT = 0; this.runCandy = 0; this.runT = 0; this.boostT = 0;
this.candyEl.textContent = '0';
// cats
for (const c of this.cats) this.scene.remove(c.rig.root);
this.cats = [];
const defs = CAT_DEFS.filter(d => d.special !== 'golden' && d.special !== 'statue').slice(0, 8);
defs.forEach((def, i) => {
const rig = new CatRig({ ...def.look, scale: def.look.scale * 1.15 }); this.scene.add(rig.root);
this.cats.push({ def, rig, s: 30 + i * ((this.L - 60) / defs.length) + Math.random() * 8, x: (Math.random() - 0.5) * 3, h: 0, vh: 0, phase: Math.random() * 6, caught: false, order: -1, sx: 0.6 + Math.random() * 0.5 });
});
this.catRow.innerHTML = defs.map(d => `<i data-id="${d.id}">🐱</i>`).join('');
// candies in little lines, rainbow boost arrows and a few jump ramps
for (const p of this.pickups) this.scene.remove(p.mesh);
this.pickups = [];
const candyGeo = new THREE.OctahedronGeometry(0.28, 0);
for (let s = 20; s < this.L - 25; s += 9) {
const lane = Math.sin(s * 0.05) * 1.6;
for (let k = 0; k < 3; k++) { const m = new THREE.Mesh(candyGeo, softMaterial(CANDY_COLORS[(s + k) % 5 | 0], 1, 0.2)); this.scene.add(m); this.pickups.push({ s: s + k * 1.4, x: lane, mesh: m, taken: false, kind: 'candy' }); }
}
for (let s = 60; s < this.L - 40; s += 55) {
const boost = new THREE.Group();
for (let k = 0; k < 3; k++) { const ch = new THREE.Mesh(new THREE.ConeGeometry(0.5, 0.6, 3), softMaterial(CANDY_COLORS[k + 1], 0.8, 0.5)); ch.rotation.x = Math.PI / 2; ch.position.z = k * 0.55; boost.add(ch); }
const x = (Math.random() - 0.5) * 2.4;
this.scene.add(boost); this.pickups.push({ s, x, mesh: boost, taken: false, kind: 'boost' });
}
for (let s = 95; s < this.L - 40; s += 70) {
const ramp = new THREE.Mesh(new THREE.BoxGeometry(HALF * 1.6, 0.25, 1.6), softMaterial('#ffe066', 0.6)); ramp.rotation.x = -0.25;
this.scene.add(ramp); this.pickups.push({ s, x: 0, mesh: ramp, taken: false, kind: 'ramp' });
}
for (const p of this.pickups) {
const pos = this.posAt(p.s, p.x, p.kind === 'candy' ? 0.7 : 0.08, new THREE.Vector3());
p.mesh.position.copy(pos);
const { tn } = this.frameAt(p.s); p.mesh.rotation.y = Math.atan2(tn.x, tn.z);
p.mesh.visible = true;
}
audio.startMusic('garden');
this.toast('🍫 3');
}
private catchCat(c: SlideCat) {
c.caught = true; c.order = this.cats.filter(k => k.caught).length - 1;
audio.play('catch'); audio.meow(c.def.voice, 'happy'); c.rig.flash('happy', 1.5);
this.player.happyT = 1.2;
this.fx.emit(this.tmp.copy(c.rig.root.position).setY(c.rig.root.position.y + 0.8), 24, { color: ['#ff7fb0', '#ffd1e6', '#ffffff', '#ffe066'], speed: 4, up: 3, size: 0.13 });
const i = this.catRow.querySelector(`[data-id="${c.def.id}"]`); if (i) { i.className = 'got'; i.textContent = c.def.emoji; }
this.toast(`💖 ${this.save.names[c.def.id] || c.def.name}!`);
if (!this.save.caughtEver.includes(c.def.id)) { this.save.caughtEver.push(c.def.id); }
this.addCandy(3);
}
private addCandy(n: number) { this.runCandy += n; this.save.candy += n; persist(this.save); this.candyEl.textContent = String(this.runCandy); }
private finish() {
this.phase = 'finish';
const got = this.cats.filter(c => c.caught).length;
audio.startMusic('victory'); audio.play('trophy');
this.trophy = makeTrophy(); this.trophy.scale.setScalar(0.8);
this.posAt(this.s + 3, 0, 1.5, this.trophy.position); this.scene.add(this.trophy);
this.save.trophies.push({ date: new Date().toISOString().slice(0, 10), seconds: Math.round(this.runT), candy: this.runCandy, difficulty: this.save.settings.difficulty });
persist(this.save);
setTimeout(() => {
if (!this.active) return;
this.endScreen = this.el(`<div class="screen"><div class="trophy">🏆</div><h1 class="logo win">Wheee!</h1><p class="tag">🐱 ${got} / ${this.cats.length} · 🍬 ${this.runCandy}</p><div class="row"><button class="big" data-a="again" aria-label="Slide again">🍫 Again</button><button class="big alt" data-a="exit" aria-label="Back to the kingdom">🏰</button></div></div>`);
this.ui.appendChild(this.endScreen);
}, 3500);
}
update(dt: number, inp: InputState, camera: THREE.PerspectiveCamera) {
this.t += dt; const t = this.t;
if (this.phase === 'count') {
const before = Math.ceil(2.4 - this.countT);
this.countT += dt;
const now = Math.ceil(2.4 - this.countT);
if (now !== before && now > 0) { this.toast(['', '1', '2', '3'][now] ?? ''); audio.play('click'); }
if (this.countT > 2.4) { this.phase = 'ride'; this.toast('🐾 Go!'); audio.play('whoosh'); }
}
const riding = this.phase === 'ride';
if (riding) this.runT += dt;
// speed: gentle gravity along the slide, faster with joystick up, slower with down; boosts add a burst
const target = this.phase === 'finish' ? 0 : riding ? 9.5 + inp.moveY * 3 + (this.boostT > 0 ? 6 : 0) : 0;
this.v = lerp(this.v, target, damp(this.phase === 'finish' ? 2 : 1.6, dt));
this.boostT -= dt;
this.s = Math.min(this.L - 1, this.s + this.v * dt);
this.x = clamp(this.x + inp.moveX * 5.5 * dt * (riding ? 1 : 0), -HALF, HALF);
// jump (button) when no cat is close; landing is always safe on the slide
let near: SlideCat | null = null, nd = 1e9;
for (const c of this.cats) {
if (c.caught) continue;
const ds = Math.abs(c.s - this.s), dx = Math.abs(c.x - this.x);
if (ds < 3.4 && dx < 2.6 && ds + dx < nd) { nd = ds + dx; near = c; }
}
if (riding && near && (inp.actionPressed || (this.save.settings.difficulty === 0 && nd < 1.8))) { this.catchCat(near); near = null; }
else if (riding && inp.actionPressed && this.h <= 0.01) { this.vh = 7; audio.play('jump'); }
this.vh -= 22 * dt; this.h = Math.max(0, this.h + this.vh * dt); if (this.h === 0 && this.vh < 0) { if (this.vh < -4) audio.play('land', { volume: 0.4 }); this.vh = 0; }
// pickups
for (const p of this.pickups) {
if (p.taken) continue;
if (p.kind === 'candy') p.mesh.rotation.y += dt * 3;
if (Math.abs(p.s - this.s) > 1.1 || Math.abs(p.x - this.x) > (p.kind === 'ramp' ? HALF : 1.1)) continue;
if (p.kind === 'candy' && this.h < 1.8) { p.taken = true; p.mesh.visible = false; this.addCandy(1); audio.play('candy', { pitch: 1 + (this.runCandy % 8) * 0.06 }); this.fx.emit(p.mesh.position, 8, { color: CANDY_COLORS, speed: 2, size: 0.08 }); }
if (p.kind === 'boost' && this.h < 0.5) { p.taken = true; this.boostT = 1.6; audio.play('whoosh'); audio.play('sparkle'); this.toast('🌈 Zoom!'); }
if (p.kind === 'ramp' && this.h < 0.3) { p.taken = true; this.vh = 9; audio.play('boing'); this.toast('Wheee!'); }
}
// cats slide along (slower than her); a missed cat pops up again further down
let k = 0;
for (const c of this.cats) {
if (c.caught) {
// the two newest friends ride right behind her; the others ride further back, out of the camera's way
const newest = this.cats.filter(k => k.caught).length - 1 - c.order;
c.rig.root.visible = newest < 2 || this.phase === 'finish';
c.s = lerp(c.s, this.s - 1.5 * (newest + 1), damp(6, dt)); c.x = lerp(c.x, this.x + (newest % 2 ? 0.9 : -0.9), damp(3, dt));
c.h = this.h > 0 ? this.h * 0.8 : 0; c.rig.pose = 'sit'; c.rig.face = 'happy';
} else {
c.phase += dt;
if (riding) c.s += this.v * c.sx * 0.72 * dt;
const close = c.s - this.s < 10 && c.s > this.s - 2;
c.x = close ? lerp(c.x, this.x + Math.sin(c.phase * 2) * 0.6, damp(1.5, dt)) : clamp(Math.sin(c.phase * 0.9) * 2, -HALF, HALF);
if (c.s < this.s - 8 && this.s < this.L - 60) { c.s = this.s + 40 + Math.random() * 30; c.x = (Math.random() - 0.5) * 3; this.toast(`😹 ${this.save.names[c.def.id] || c.def.name}!`); }
c.s = Math.min(c.s, this.L - 6 - k * 1.2);
c.vh -= 22 * dt; c.h = Math.max(0, c.h + c.vh * dt); if (c.h === 0 && Math.random() < dt * 0.6) c.vh = 5;
c.rig.pose = c.h > 0 ? 'wiggle' : 'pancake'; c.rig.face = Math.abs(c.s - this.s) < 6 ? 'smug' : 'happy';
k++;
}
const pos = this.posAt(c.s, c.x, c.h + 0.05, c.rig.root.position);
const { tn } = this.frameAt(c.s);
c.rig.root.rotation.y = Math.atan2(tn.x, tn.z);
c.rig.root.userData.groundY = pos.y - c.h;
c.rig.speed = 3; c.rig.airborne = c.h > 0.05; c.rig.vy = c.vh; c.rig.update(dt);
}
this.ring.visible = !!near && riding;
if (near) { this.ring.position.copy(near.rig.root.position).setY(near.rig.root.position.y + 0.08); this.ring.scale.setScalar(1 + Math.sin(t * 10) * 0.08); }
// player on her cookie sled
const pp = this.posAt(this.s, this.x, this.h + 0.12, this.player.root.position);
const { tn } = this.frameAt(this.s);
const yaw = Math.atan2(tn.x, tn.z);
this.player.root.rotation.set(0, yaw, -inp.moveX * 0.25);
this.player.root.position.y += 0.1;
this.sled.position.copy(pp); this.sled.rotation.set(0, yaw, -inp.moveX * 0.2);
this.player.happyT = Math.max(this.player.happyT, this.boostT > 0 || this.h > 0.5 ? 0.2 : 0);
if (riding && this.v > 8 && Math.random() < dt * 20) this.fx.emit(this.tmp.copy(pp).addScaledVector(tn, -0.8), 1, { color: ['#c58b5a', '#f2b86b', '#ffffff'], speed: 1, up: 1, grav: 4, life: 0.5, size: 0.08 });
if (this.phase !== 'finish' && this.s >= this.L - 8) this.finish();
if (this.trophy) { this.trophy.rotation.y += dt * 1.5; if (Math.random() < dt * 2) this.fx.emit(this.tmp.copy(this.trophy.position).add(new THREE.Vector3((Math.random() - 0.5) * 10, 5 + Math.random() * 4, (Math.random() - 0.5) * 10)), 40, { color: CANDY_COLORS, speed: 6, size: 0.13, life: 1.3, grav: 2 }); }
for (const c of this.cats) if (this.phase === 'finish' && c.caught) c.rig.pose = 'dance';
this.fx.update(dt);
// camera behind and above, looking down the slide
const look = this.posAt(this.s + 6, this.x * 0.5, 0.8, new THREE.Vector3());
const want = this.posAt(Math.max(0, this.s - 7), this.x * 0.4, 4.6, new THREE.Vector3());
if (this.phase === 'finish') { want.copy(pp).add(new THREE.Vector3(Math.sin(t * 0.3) * 7, 4, Math.cos(t * 0.3) * 7)); look.copy(pp).setY(pp.y + 1); }
if (this.camPos.lengthSq() === 0 || this.camPos.distanceTo(want) > 30) this.camPos.copy(want);
this.camPos.lerp(want, damp(5, dt)); this.camLook.lerp(look, damp(8, dt));
camera.position.copy(this.camPos); camera.lookAt(this.camLook);
}
}
quests.ts, princess wishes (src/game/quests.ts)73 lines
// Princess picture quests: each princess shows a picture bubble with one small wish.
// No words needed, no clock, cannot fail. Walking away never cancels a wish.
import * as THREE from 'three';
import { clamp } from '../core/util';
export type QuestEvent = 'candy' | 'bounce' | 'hatch' | 'catch' | 'jump';
interface Wish { icon: string; need: number; done: (s: QuestState) => boolean; progress?: (s: QuestState) => number; reward: number; gift: string }
export interface QuestState { counts: Record<QuestEvent, number>; friends: number; nearCupcake: boolean; nearRex: boolean; atPrincess: boolean }
// "need" counts are measured from the moment the wish starts
const WISHES: Wish[] = [
{ icon: '🍬', need: 5, done: s => s.counts.candy >= 5, progress: s => s.counts.candy, reward: 8, gift: '🍭' },
{ icon: '🐱', need: 1, done: s => s.friends >= 1 && s.atPrincess, reward: 6, gift: '💖' },
{ icon: '🤸', need: 3, done: s => s.counts.bounce >= 3, progress: s => s.counts.bounce, reward: 8, gift: '⭐' },
{ icon: '🧁', need: 1, done: s => s.nearCupcake, reward: 6, gift: '🧁' },
{ icon: '🦖', need: 1, done: s => s.nearRex, reward: 6, gift: '🥚' },
{ icon: '🐾', need: 2, done: s => s.counts.catch >= 2, progress: s => s.counts.catch, reward: 10, gift: '🎀' },
{ icon: '🦘', need: 10, done: s => s.counts.jump >= 10, progress: s => s.counts.jump, reward: 6, gift: '🌈' },
];
export interface Asker { root: THREE.Object3D; cheer: number }
class PrincessWish {
bubble: HTMLElement; wish: Wish; counts: Record<QuestEvent, number> = { candy: 0, bounce: 0, hatch: 0, catch: 0, jump: 0 };
doneT = 0; delivered = false;
constructor(public who: Asker, ui: HTMLElement, public order: number[], public i = 0) {
this.bubble = document.createElement('div'); this.bubble.className = 'wish'; ui.appendChild(this.bubble);
this.wish = WISHES[order[0]]; this.render();
}
render() {
if (this.delivered) { this.bubble.innerHTML = `<span>💖</span>`; return; }
const w = this.wish, p = w.progress ? Math.min(w.need, w.progress({ counts: this.counts } as QuestState)) : 0;
this.bubble.innerHTML = `<span>${w.icon}</span>${w.need > 1 ? `<i>${'●'.repeat(p)}${'○'.repeat(w.need - p)}</i>` : ''}`;
}
next() { this.i = (this.i + 1) % this.order.length; this.wish = WISHES[this.order[this.i]]; this.counts = { candy: 0, bounce: 0, hatch: 0, catch: 0, jump: 0 }; this.delivered = false; this.render(); }
}
export class Quests {
private wishes: PrincessWish[] = [];
private v = new THREE.Vector3();
visible = true;
constructor(ui: HTMLElement, askers: Asker[]) {
const orders = [[0, 1, 3, 6], [2, 4, 5, 1]];
askers.forEach((a, k) => this.wishes.push(new PrincessWish(a, ui, orders[k % orders.length])));
}
hideAll() { for (const w of this.wishes) w.bubble.hidden = true; }
notify(e: QuestEvent) { for (const w of this.wishes) if (!w.delivered) { w.counts[e]++; if (w.wish.progress) w.render(); } }
reset() { for (const w of this.wishes) { w.counts = { candy: 0, bounce: 0, hatch: 0, catch: 0, jump: 0 }; w.delivered = false; w.render(); } }
/** Returns a finished wish (to pay its reward) when the player brings it to the princess. */
update(dt: number, camera: THREE.Camera, playerPos: THREE.Vector3, ctx: { friends: number; nearCupcake: boolean; nearRex: boolean }, show: boolean): { gift: string; reward: number; who: Asker } | null {
let out: { gift: string; reward: number; who: Asker } | null = null;
for (const w of this.wishes) {
const pr = w.who.root.position;
const atPrincess = Math.hypot(pr.x - playerPos.x, pr.z - playerPos.z) < 3 && Math.abs(pr.y - playerPos.y) < 3;
const st: QuestState = { counts: w.counts, friends: ctx.friends, nearCupcake: ctx.nearCupcake, nearRex: ctx.nearRex, atPrincess };
if (!w.delivered && w.wish.done(st)) {
// wishes that happen far away are "ready": the bubble glows until she visits the princess
w.bubble.classList.add('ready');
if (atPrincess) { w.delivered = true; w.doneT = 5; w.bubble.classList.remove('ready'); w.render(); out = { gift: w.wish.gift, reward: w.wish.reward, who: w.who }; }
}
if (w.delivered) { w.doneT -= dt; if (w.doneT <= 0) w.next(); }
// place the bubble over the princess's head
this.v.copy(pr).setY(pr.y + 2.6).project(camera);
const on = show && this.visible && this.v.z < 1 && Math.abs(this.v.x) < 1.1 && Math.abs(this.v.y) < 1.1;
w.bubble.hidden = !on;
// keep the bubble fully on screen and below the top bar
if (on) { const x = clamp((this.v.x + 1) / 2 * innerWidth, 40, innerWidth - 40), y = clamp((1 - this.v.y) / 2 * innerHeight, 150, innerHeight - 20); w.bubble.style.transform = `translate(${x.toFixed(0)}px, ${y.toFixed(0)}px) translate(-50%, -100%)`; }
}
return out;
}
}
wardrobe.ts (src/game/wardrobe.ts)60 lines
// Wardrobe: hoodie colours and hats bought with candy. Cosmetic only, always earned by playing.
import * as THREE from 'three';
import { softMaterial } from '../render/fur';
import { starGeo } from '../cats/catModel';
export interface Hood { id: string; name: string; emoji: string; price: number; top: string; bottom: string }
export interface Hat { id: string; name: string; emoji: string; price: number }
export const HOODS: Hood[] = [
{ id: 'lilac', name: 'Lilac hoodie', emoji: '💜', price: 0, top: '#b58cff', bottom: '#e6d8ff' },
{ id: 'pink', name: 'Bubblegum hoodie', emoji: '🩷', price: 10, top: '#ff7fb8', bottom: '#ffd3e7' },
{ id: 'mint', name: 'Mint hoodie', emoji: '💚', price: 10, top: '#5fd6aa', bottom: '#cdf5e5' },
{ id: 'sky', name: 'Sky hoodie', emoji: '💙', price: 10, top: '#6fb4ff', bottom: '#d3e8ff' },
{ id: 'orange', name: 'Orange cat hoodie', emoji: '🧡', price: 20, top: '#ff8a1f', bottom: '#ffd6a8' },
];
export const HATS: Hat[] = [
{ id: 'none', name: 'No hat', emoji: '🙂', price: 0 },
{ id: 'bow', name: 'Big bow', emoji: '🎀', price: 10 },
{ id: 'flowers', name: 'Flower crown', emoji: '🌸', price: 15 },
{ id: 'party', name: 'Party hat', emoji: '🥳', price: 15 },
{ id: 'tiara', name: 'Princess tiara', emoji: '👸', price: 25 },
{ id: 'wizard', name: 'Star wizard hat', emoji: '🧙', price: 30 },
];
export function makeHat(id: string): THREE.Group | null {
const g = new THREE.Group();
const M = (geo: THREE.BufferGeometry, c: string, gloss = 0.4, em = 0) => new THREE.Mesh(geo, softMaterial(c, gloss, em));
if (id === 'bow') {
for (const sx of [-1, 1]) { const w = M(new THREE.SphereGeometry(0.13, 12, 8), '#ff5c9d'); w.scale.set(1.2, 0.8, 0.5); w.position.set(sx * 0.13, 0.02, 0.02); w.rotation.z = sx * 0.4; g.add(w); }
const k = M(new THREE.SphereGeometry(0.06, 10, 8), '#ff8fbf'); k.position.z = 0.05; g.add(k);
g.position.set(0.12, 0.02, 0.05); g.rotation.z = -0.3;
} else if (id === 'flowers') {
const cols = ['#ff8fbf', '#ffe066', '#ffffff', '#b79bff', '#8fd3ff'];
for (let i = 0; i < 9; i++) { const a = i / 9 * Math.PI * 2; const f = M(new THREE.IcosahedronGeometry(0.075, 1), cols[i % 5], 0.3); f.position.set(Math.cos(a) * 0.3, -0.06, Math.sin(a) * 0.3); g.add(f); }
const band = M(new THREE.TorusGeometry(0.3, 0.025, 6, 24), '#8fe39b'); band.rotation.x = Math.PI / 2; band.position.y = -0.06; g.add(band);
} else if (id === 'party') {
const cone = M(new THREE.ConeGeometry(0.16, 0.42, 16), '#7cc8ff', 0.6); cone.position.y = 0.2; g.add(cone);
for (let i = 0; i < 3; i++) { const d = M(new THREE.SphereGeometry(0.035, 8, 6), ['#ffe066', '#ff7fb0', '#ffffff'][i]); d.position.set(Math.sin(i * 2.1) * 0.1, 0.1 + i * 0.09, Math.cos(i * 2.1) * 0.1); g.add(d); }
const pom = M(new THREE.SphereGeometry(0.07, 10, 8), '#ffffff'); pom.position.y = 0.43; g.add(pom);
g.rotation.z = 0.15;
} else if (id === 'tiara') {
const gold = '#ffd34d';
const band = M(new THREE.TorusGeometry(0.24, 0.03, 6, 24, Math.PI), gold, 1.2, 0.2); band.rotation.y = 0; band.position.set(0, -0.02, 0.06); band.rotation.x = -0.2; g.add(band);
for (let i = -2; i <= 2; i++) { const p = M(new THREE.ConeGeometry(0.035, 0.12 - Math.abs(i) * 0.02, 6), gold, 1.2, 0.2); const a = Math.PI / 2 + i * 0.45; p.position.set(Math.cos(a) * 0.24, 0.05, Math.sin(a) * 0.24 * 0.4 + 0.12); g.add(p); }
const gem = M(new THREE.OctahedronGeometry(0.05), '#ff7fb0', 1, 0.6); gem.position.set(0, 0.05, 0.25); g.add(gem);
} else if (id === 'wizard') {
const cone = M(new THREE.ConeGeometry(0.26, 0.6, 18), '#9d7bff', 0.4); cone.position.y = 0.28; cone.rotation.z = 0.2; g.add(cone);
const brim = M(new THREE.CylinderGeometry(0.4, 0.4, 0.04, 24), '#9d7bff'); g.add(brim);
for (let i = 0; i < 3; i++) { const st = new THREE.Mesh(starGeo(), softMaterial('#fff5a8', 1, 0.8)); st.scale.setScalar(0.07); st.position.set(Math.sin(i * 2) * 0.17, 0.15 + i * 0.12, Math.cos(i * 2) * 0.17); g.add(st); }
} else return null;
return g;
}
/** Dress a player in the saved outfit. */
export function applyOutfit(p: { setHood(top: string, bottom?: string): void; setHat(h: THREE.Object3D | null): void }, outfit: { hood: string; hat: string }) {
const h = HOODS.find(k => k.id === outfit.hood) ?? HOODS[0];
p.setHood(h.top, h.bottom); p.setHat(makeHat(outfit.hat));
}
sky.ts (src/render/sky.ts)9 lines
// Pastel sky dome (pink horizon to soft blue), shared by every scene.
import * as THREE from 'three';
export function makeSky(top = '0.62,0.8,1.0', bottom = '1.0,0.85,0.93'): THREE.Mesh {
return new THREE.Mesh(new THREE.SphereGeometry(200, 24, 12), new THREE.ShaderMaterial({ side: THREE.BackSide, depthWrite: false,
vertexShader: 'varying vec3 vP; void main(){ vP = position; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }',
fragmentShader: `varying vec3 vP; void main(){ float h = normalize(vP).y; vec3 a = vec3(${bottom}); vec3 b = vec3(${top}); vec3 c = mix(a,b,smoothstep(-0.05,0.55,h)); gl_FragColor = vec4(c,1.0);\n#include <colorspace_fragment>\n}` }));
}
save.ts (src/save/save.ts)24 lines
// Versioned local save. Never leaves the device.
export interface SaveV1 {
v: 1; candy: number; caughtEver: string[];
trophies: { date: string; seconds: number; candy: number; difficulty: number }[];
names: Record<string, string>;
/** Cat home decorations and wardrobe items the player has bought with candy. */
owned: string[];
/** What the player is wearing: hoodie colour id, hat id. */
outfit: { hood: string; hat: string };
settings: { difficulty: number; music: number; sfx: number; reducedMotion: boolean };
}
const KEY = 'fck-save-v1';
export function fresh(): SaveV1 { return { v: 1, candy: 0, caughtEver: [], trophies: [], names: {}, owned: ['bed', 'yarn'], outfit: { hood: 'lilac', hat: 'none' }, settings: { difficulty: 0, music: 0.7, sfx: 1, reducedMotion: false } }; }
export function loadSave(): SaveV1 {
try {
const raw = localStorage.getItem(KEY); if (!raw) return fresh();
const s = JSON.parse(raw) as Partial<SaveV1>;
if (s.v !== 1) return fresh();
const f = fresh();
return { ...f, ...s, settings: { ...f.settings, ...(s.settings ?? {}) }, outfit: { ...f.outfit, ...(s.outfit ?? {}) }, owned: Array.isArray(s.owned) ? s.owned : f.owned } as SaveV1;
} catch { return fresh(); }
}
export function persist(s: SaveV1) { try { localStorage.setItem(KEY, JSON.stringify(s)); } catch { /* storage blocked: play on */ } }
util.ts (src/core/util.ts)31 lines
// Small math + random helpers shared by all modules.
export function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export const clamp = (v: number, a: number, b: number) => (v < a ? a : v > b ? b : v);
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
/** Frame-rate independent smoothing factor. */
export const damp = (rate: number, dt: number) => 1 - Math.exp(-rate * dt);
export function angleLerp(a: number, b: number, t: number): number {
let d = ((b - a + Math.PI) % (Math.PI * 2)) - Math.PI;
if (d < -Math.PI) d += Math.PI * 2;
return a + d * t;
}
export function angleDiff(a: number, b: number): number {
let d = ((b - a + Math.PI) % (Math.PI * 2)) - Math.PI;
if (d < -Math.PI) d += Math.PI * 2;
return d;
}
export const easeOutBack = (t: number) => { const c = 1.7; return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2); };
export const easeInOut = (t: number) => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2);
/** Global random used for cosmetic randomness. Gameplay uses seeded rngs. */
export const rand = Math.random;
export const pick = <T>(arr: readonly T[], r: () => number = rand): T => arr[Math.floor(r() * arr.length)];
index.ts (src/audio/index.ts)73 lines
// Public audio API. Everything is a safe no-op until init() is called from a user gesture.
import { createContext, dropContext, getCtx, setBusVolumes } from './context';
import { iosUnlock, installUnlockListeners, primeContext } from './unlock';
import { playSfx } from './sfx';
import { playMeow } from './meow';
import { resetMusic, startMusic, stopMusic, syncMusic } from './music';
import type { Sfx, Mood, Track, PlayOpts } from './types';
export type { Sfx, Mood, Track, PlayOpts } from './types';
let stuck = 0, needRebuild = false;
function rebuildOnGesture(): void {
const c = getCtx();
if (!needRebuild || !c || c.state === 'running') { needRebuild = false; return; }
needRebuild = false; stuck = 0;
try { dropContext(); iosUnlock(); if (createContext()) { primeContext(); resetMusic(); } } catch { /* ignore */ }
}
if (typeof window !== 'undefined') for (const ev of ['pointerdown', 'touchend', 'keydown']) window.addEventListener(ev, rebuildOnGesture, { capture: true, passive: true });
export const audio = {
init(): void {
try {
const fresh = !getCtx();
iosUnlock(); // set the iOS playback session BEFORE the context exists (changing it later can interrupt audio)
if (!createContext()) return;
if (fresh) primeContext();
installUnlockListeners();
syncMusic();
} catch { /* audio must never break the game */ }
},
play(name: Sfx, opts?: PlayOpts): void {
try { playSfx(name, opts); } catch { /* ignore */ }
},
meow(voice: number, mood?: Mood, opts?: PlayOpts): void {
try { playMeow(voice, mood, opts); } catch { /* ignore */ }
},
startMusic(track: Track): void {
try { startMusic(track); } catch { /* ignore */ }
},
stopMusic(): void {
try { stopMusic(); } catch { /* ignore */ }
},
setVolumes(master: number, music: number, sfx: number): void {
setBusVolumes(master, music, sfx);
},
/** Call about once a second: recovers audio that iOS or the browser stopped. */
watchdog(): void {
const c = getCtx(); if (!c || document.hidden) { stuck = 0; return; }
if (c.state === 'running') { stuck = 0; return; }
try { void c.resume().catch(() => undefined); } catch { /* ignore */ }
stuck++;
if (c.state === 'closed' || stuck > 3) needRebuild = true; // rebuilt on the next tap (iOS needs a gesture)
},
/** Sound button: restart audio from scratch inside the tap. */
kick(): void {
const c = getCtx();
if (!c) { this.init(); return; }
if (c.state === 'running') return;
needRebuild = true; rebuildOnGesture();
},
isRunning(): boolean {
return getCtx()?.state === 'running';
},
};
if (typeof window !== 'undefined') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).__fckAudio = {
get ctx() { return getCtx(); },
iosUnlock,
};
}
context.ts (src/audio/context.ts)163 lines
// Shared AudioContext, bus graph and tiny synth primitives (tone / noise).
let ctx: AudioContext | null = null;
let master: GainNode | null = null;
let sfxBus: GainNode | null = null;
let musicBus: GainNode | null = null;
let noiseBuf: AudioBuffer | null = null;
// Voice limit by end time: a voice can never leak, even if onended does not fire.
const voiceEnds: number[] = [];
const MAX_VOICES = 14;
const vols = { master: 0.7, music: 0.7, sfx: 0.8 };
export const getCtx = (): AudioContext | null => ctx;
export const getSfxBus = (): GainNode | null => sfxBus;
export const getMusicBus = (): GainNode | null => musicBus;
export const canPlay = (): boolean => {
if (!ctx) return false;
const now = ctx.currentTime;
for (let i = voiceEnds.length - 1; i >= 0; i--) if (voiceEnds[i] < now) voiceEnds.splice(i, 1);
return voiceEnds.length < MAX_VOICES;
};
/** Throw away a broken context (iOS can leave one stuck after an interruption). */
export function dropContext(): void {
try { if (ctx && ctx.state !== 'closed') void ctx.close().catch(() => undefined); } catch { /* ignore */ }
ctx = null; master = null; sfxBus = null; musicBus = null; noiseBuf = null; voiceEnds.length = 0;
}
export const rnd = (a: number, b: number): number => a + Math.random() * (b - a);
export const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x));
export const midi = (m: number): number => 440 * Math.pow(2, (m - 69) / 12);
/** Create context + graph (master -> compressor -> destination). Only call from init(). */
export function createContext(): AudioContext | null {
if (ctx) return ctx;
const AC = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
if (!AC) return null;
try { ctx = new AC({ latencyHint: 'playback' }); } catch { try { ctx = new AC(); } catch { return null; } }
master = ctx.createGain();
const comp = ctx.createDynamicsCompressor();
comp.threshold.value = -20; comp.knee.value = 18; comp.ratio.value = 6;
comp.attack.value = 0.006; comp.release.value = 0.2;
sfxBus = ctx.createGain();
musicBus = ctx.createGain();
sfxBus.connect(master); musicBus.connect(master);
master.connect(comp); comp.connect(ctx.destination);
master.gain.value = vols.master; musicBus.gain.value = vols.music; sfxBus.gain.value = vols.sfx;
noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
const d = noiseBuf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
return ctx;
}
export function setBusVolumes(m: number, mu: number, s: number): void {
vols.master = clamp(m, 0, 1); vols.music = clamp(mu, 0, 1); vols.sfx = clamp(s, 0, 1);
if (!ctx || !master || !musicBus || !sfxBus) return;
const t = ctx.currentTime;
master.gain.setTargetAtTime(vols.master, t, 0.04);
musicBus.gain.setTargetAtTime(vols.music, t, 0.04);
sfxBus.gain.setTargetAtTime(vols.sfx, t, 0.04);
}
/** Count a source as an active voice and free its nodes when it ends. */
export function trackVoice(src: AudioScheduledSourceNode, nodes: AudioNode[], counted = true): void {
if (counted && ctx) voiceEnds.push(ctx.currentTime + 2);
src.onended = () => {
src.disconnect();
for (const n of nodes) n.disconnect();
};
}
export interface Mod { rate: number; depth: number }
interface Common {
t?: number; dur: number; vol?: number; atk?: number; pan?: number;
am?: Mod; music?: boolean; dest?: AudioNode;
}
export interface ToneOpts extends Common {
f: number; f2?: number; sweep?: number; rel?: number; type?: OscillatorType;
detune?: number; lp?: number; vib?: Mod;
}
export interface NoiseOpts extends Common {
f: number; f2?: number; q?: number; type?: BiquadFilterType;
}
function envelope(c: AudioContext, g: GainNode, t: number, o: Common & { rel?: number }): void {
const vol = o.vol ?? 0.3, atk = o.atk ?? 0.005;
g.gain.setValueAtTime(0.0001, t);
g.gain.linearRampToValueAtTime(vol, t + atk);
if (o.rel !== undefined && o.dur - o.rel > atk) g.gain.setValueAtTime(vol, t + o.dur - o.rel);
g.gain.exponentialRampToValueAtTime(0.0001, t + o.dur);
void c;
}
/** Wire (optional AM) -> envelope gain -> (optional pan) -> bus. Returns the first node to feed. */
function output(c: AudioContext, t: number, o: Common & { rel?: number }, extra: AudioNode[]): { input: AudioNode; lfo: OscillatorNode | null } {
const g = c.createGain();
envelope(c, g, t, o);
extra.push(g);
let input: AudioNode = g;
let lfo: OscillatorNode | null = null;
if (o.am) {
const amG = c.createGain();
amG.gain.value = 1 - o.am.depth;
lfo = c.createOscillator(); lfo.frequency.value = o.am.rate;
const lg = c.createGain(); lg.gain.value = o.am.depth;
lfo.connect(lg); lg.connect(amG.gain); amG.connect(g);
extra.push(amG, lg, lfo);
input = amG;
}
let tail: AudioNode = g;
if (o.pan && typeof c.createStereoPanner === 'function') {
const p = c.createStereoPanner(); p.pan.value = clamp(o.pan, -1, 1);
g.connect(p); extra.push(p); tail = p;
}
const dest = o.dest ?? (o.music ? musicBus : sfxBus);
if (dest) tail.connect(dest);
return { input, lfo };
}
export function tone(o: ToneOpts): void {
const c = ctx; if (!c) return;
const t = Math.max(o.t ?? c.currentTime, c.currentTime);
const osc = c.createOscillator();
osc.type = o.type ?? 'sine';
osc.frequency.setValueAtTime(o.f, t);
if (o.f2 !== undefined) osc.frequency.exponentialRampToValueAtTime(Math.max(1, o.f2), t + o.dur * (o.sweep ?? 1));
if (o.detune) osc.detune.value = o.detune;
const nodes: AudioNode[] = [];
const out = output(c, t, o, nodes);
let head: AudioNode = osc;
if (o.lp) {
const lp = c.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = o.lp;
osc.connect(lp); head = lp; nodes.push(lp);
}
head.connect(out.input);
const end = t + o.dur + 0.05;
if (o.vib) {
const l = c.createOscillator(); l.frequency.value = o.vib.rate;
const lg = c.createGain(); lg.gain.value = o.vib.depth;
l.connect(lg); lg.connect(osc.detune); l.start(t); l.stop(end); nodes.push(l, lg);
}
if (out.lfo) { out.lfo.start(t); out.lfo.stop(end); }
trackVoice(osc, nodes, !o.music);
osc.start(t); osc.stop(end);
}
export function noise(o: NoiseOpts): void {
const c = ctx; if (!c || !noiseBuf) return;
const t = Math.max(o.t ?? c.currentTime, c.currentTime);
const src = c.createBufferSource();
src.buffer = noiseBuf; src.loop = true;
const f = c.createBiquadFilter();
f.type = o.type ?? 'bandpass'; f.Q.value = o.q ?? 1;
f.frequency.setValueAtTime(o.f, t);
if (o.f2 !== undefined) f.frequency.exponentialRampToValueAtTime(Math.max(20, o.f2), t + o.dur);
const nodes: AudioNode[] = [f];
const out = output(c, t, o, nodes);
src.connect(f); f.connect(out.input);
const end = t + o.dur + 0.05;
if (out.lfo) { out.lfo.start(t); out.lfo.stop(end); }
trackVoice(src, nodes, !o.music);
src.start(t, Math.random() * 1.5); src.stop(end);
}
export function getNoiseBuffer(): AudioBuffer | null { return noiseBuf; }
unlock.ts (src/audio/unlock.ts)53 lines
// iOS silent-mode unlock + resume handling.
import { getCtx } from './context';
type SessionNav = Navigator & { audioSession?: { type: string } };
let silent: HTMLAudioElement | null = null;
let listening = false;
function ensureSilentAudio(): void {
if (!silent) {
silent = document.createElement('audio');
silent.src = './audio/silence.mp3';
silent.loop = true;
silent.preload = 'auto';
silent.setAttribute('playsinline', '');
silent.setAttribute('webkit-playsinline', '');
}
if (silent.paused) void silent.play().catch(() => undefined);
}
export function iosUnlock(): void {
try {
const nav = navigator as SessionNav;
if (nav.audioSession) nav.audioSession.type = 'playback';
else ensureSilentAudio();
} catch { /* ignore */ }
const c = getCtx();
if (c && c.state !== 'running') {
try { void c.resume().catch(() => undefined); } catch { /* ignore */ }
}
}
/** Play a one-sample silent buffer (helps older iOS start the context). */
export function primeContext(): void {
const c = getCtx(); if (!c) return;
try {
const s = c.createBufferSource();
s.buffer = c.createBuffer(1, 1, 22050);
s.connect(c.destination); s.start(0);
} catch { /* ignore */ }
}
export function installUnlockListeners(): void {
if (listening) return;
listening = true;
const handler = (): void => {
const c = getCtx();
if (!c || c.state !== 'running') iosUnlock();
};
const opts: AddEventListenerOptions = { capture: true, passive: true };
for (const ev of ['pointerdown', 'touchend', 'click', 'keydown']) window.addEventListener(ev, handler, opts);
document.addEventListener('visibilitychange', () => { if (!document.hidden) handler(); }, opts);
}
sfx.ts (src/audio/sfx.ts)174 lines
// Short synthesized sound effects: soft, round, toy-like.
import { getCtx, tone, noise, rnd, canPlay, clamp } from './context';
import type { ToneOpts, NoiseOpts } from './context';
import type { Sfx, PlayOpts } from './types';
interface C { p: number; v: number; pan: number }
type TO = Omit<ToneOpts, 't'> & { at?: number };
type NO = Omit<NoiseOpts, 't'> & { at?: number };
let base = 0;
const T = (c: C, o: TO): void => tone({
...o, t: base + (o.at ?? 0), f: o.f * c.p, f2: o.f2 !== undefined ? o.f2 * c.p : undefined,
vol: (o.vol ?? 0.3) * c.v, pan: c.pan,
});
const N = (c: C, o: NO): void => noise({ ...o, t: base + (o.at ?? 0), vol: (o.vol ?? 0.3) * c.v, pan: c.pan });
/** Round bell: fundamental + soft inharmonic partial. */
const bell = (c: C, f: number, at: number, dur: number, vol: number): void => {
T(c, { f, at, dur, vol, atk: 0.004 });
T(c, { f: f * 2.76, at, dur: dur * 0.4, vol: vol * 0.25, atk: 0.003 });
};
const PENTA = [523, 659, 784, 1047, 1319, 1568, 2093];
const FX: Record<Sfx, (c: C) => void> = {
jump: (c) => {
T(c, { f: 330, f2: 640, dur: 0.17, vol: 0.28, atk: 0.01 });
T(c, { f: 660, f2: 1280, dur: 0.12, vol: 0.06, type: 'triangle' });
},
land: (c) => {
N(c, { f: 600, f2: 150, type: 'lowpass', dur: 0.14, vol: 0.28, atk: 0.008 });
T(c, { f: 150, f2: 70, dur: 0.12, vol: 0.28 });
},
catch: (c) => {
PENTA.slice(0, 6).forEach((f, i) => bell(c, f, i * 0.07, 0.32, 0.26));
[1047, 1319, 1568].forEach((f) => bell(c, f, 0.44, 0.5, 0.2));
T(c, { f: 262, at: 0.44, dur: 0.45, vol: 0.18, type: 'triangle' });
for (let i = 0; i < 6; i++) T(c, { f: rnd(3000, 5200), at: 0.3 + i * 0.07, dur: 0.18, vol: 0.05 });
},
candy: (c) => {
T(c, { f: 988, dur: 0.28, vol: 0.28, atk: 0.003 });
T(c, { f: 1976, dur: 0.14, vol: 0.08 });
T(c, { f: 2960, dur: 0.07, vol: 0.05 });
},
boing: (c) => {
T(c, { f: 160, f2: 420, dur: 0.09, vol: 0.28 });
T(c, { f: 420, f2: 170, at: 0.08, dur: 0.5, vol: 0.3, vib: { rate: 21, depth: 380 } });
T(c, { f: 840, f2: 340, at: 0.08, dur: 0.3, vol: 0.05, type: 'triangle', vib: { rate: 21, depth: 380 } });
},
snore: (c) => {
T(c, { f: 85, f2: 120, dur: 0.55, vol: 0.2, atk: 0.3, type: 'sawtooth', lp: 500, vib: { rate: 34, depth: 260 } });
N(c, { f: 700, q: 5, dur: 0.55, vol: 0.12, atk: 0.3 });
T(c, { f: 120, f2: 70, at: 0.65, dur: 0.7, vol: 0.2, atk: 0.12, type: 'sawtooth', lp: 400, vib: { rate: 28, depth: 300 } });
N(c, { f: 500, q: 5, at: 0.65, dur: 0.6, vol: 0.1, atk: 0.12 });
},
sneeze: (c) => {
T(c, { f: 520, f2: 760, dur: 0.14, vol: 0.2, atk: 0.04, type: 'triangle' });
T(c, { f: 600, f2: 860, at: 0.2, dur: 0.14, vol: 0.22, atk: 0.04, type: 'triangle' });
N(c, { f: 3200, f2: 1400, at: 0.42, dur: 0.16, vol: 0.3, q: 0.8, atk: 0.01 });
T(c, { f: 420, f2: 200, at: 0.42, dur: 0.16, vol: 0.18, type: 'triangle' });
[1568, 2093, 2637, 3136].forEach((f, i) => bell(c, f, 0.62 + i * 0.06, 0.3, 0.12));
},
pounce: (c) => {
N(c, { f: 400, f2: 2600, q: 1.5, dur: 0.22, vol: 0.2, atk: 0.1 });
T(c, { f: 420, f2: 140, at: 0.2, dur: 0.1, vol: 0.3 });
},
firework: (c) => {
T(c, { f: 500, f2: 2200, dur: 0.5, vol: 0.1, atk: 0.06, sweep: 1 });
N(c, { f: 3500, q: 0.7, at: 0.5, dur: 0.35, vol: 0.1, atk: 0.01 });
for (let i = 0; i < 6; i++) bell(c, rnd(1500, 3600), 0.5 + i * 0.05, 0.3, 0.09);
},
click: (c) => {
T(c, { f: 1500, f2: 900, dur: 0.05, vol: 0.2, atk: 0.002 });
T(c, { f: 3000, dur: 0.02, vol: 0.05, type: 'triangle' });
},
purr: (c) => {
N(c, { f: 180, q: 1.2, type: 'bandpass', dur: 1.05, vol: 0.4, atk: 0.2, am: { rate: 25, depth: 0.85 } });
T(c, { f: 50, dur: 1.05, vol: 0.22, atk: 0.2, type: 'triangle', am: { rate: 25, depth: 0.85 } });
},
whoosh: (c) => { N(c, { f: 300, f2: 1800, q: 1.2, dur: 0.35, vol: 0.2, atk: 0.14 }); },
poof: (c) => {
N(c, { f: 1400, f2: 300, type: 'lowpass', dur: 0.28, vol: 0.28, atk: 0.01 });
T(c, { f: 220, f2: 90, dur: 0.15, vol: 0.1 });
},
chest: (c) => {
T(c, { f: 130, f2: 280, dur: 0.38, vol: 0.12, atk: 0.05, type: 'sawtooth', lp: 700, vib: { rate: 15, depth: 150 } });
T(c, { f: 260, f2: 160, at: 0.2, dur: 0.2, vol: 0.08, atk: 0.03, type: 'sawtooth', lp: 600 });
[1047, 1319, 1568, 2093].forEach((f, i) => bell(c, f, 0.42 + i * 0.07, 0.5, 0.18));
},
step: (c) => {
const j = rnd(0.9, 1.15);
N(c, { f: 900 * j, q: 1, dur: 0.04, vol: 0.05, atk: 0.003 });
T(c, { f: 180 * j, f2: 120 * j, dur: 0.05, vol: 0.05, atk: 0.002 });
},
giggle: (c) => {
for (let i = 0; i < 5; i++) {
const f = rnd(850, 1150) + (i % 2) * 250;
T(c, { f, f2: f * 1.4, at: i * 0.075, dur: 0.065, vol: 0.16, atk: 0.008, type: 'triangle' });
}
},
pop: (c) => {
T(c, { f: 320, f2: 1000, dur: 0.07, vol: 0.3, atk: 0.003 });
N(c, { f: 4000, type: 'highpass', dur: 0.03, vol: 0.06, atk: 0.001 });
},
sparkle: (c) => {
for (let i = 0; i < 9; i++) bell(c, rnd(2000, 4600), i * 0.05, 0.3, 0.1);
},
trophy: (c) => {
[262, 330, 392, 523, 659, 784].forEach((f) => T(c, { f, dur: 1.6, vol: 0.12, atk: 0.28, rel: 0.7, type: 'triangle' }));
T(c, { f: 131, dur: 1.6, vol: 0.2, atk: 0.2, rel: 0.7 });
PENTA.slice(0, 5).forEach((f, i) => bell(c, f, 0.25 + i * 0.09, 0.5, 0.2));
[1047, 1319, 1568, 2093].forEach((f) => bell(c, f, 0.8, 0.8, 0.16));
for (let i = 0; i < 6; i++) bell(c, rnd(2500, 4800), 0.9 + i * 0.07, 0.3, 0.07);
},
bump: (c) => {
T(c, { f: 125, f2: 60, dur: 0.16, vol: 0.4 });
N(c, { f: 300, type: 'lowpass', dur: 0.08, vol: 0.15, atk: 0.003 });
},
// ---- sanctuary / egg / shop sounds (each uses few voices: iPad breaks up with too many) ----
rawr: (c) => { // tiny toy dino: rising chirp, then a falling squeak with a little growl wobble
T(c, { f: 620, f2: 1050, dur: 0.13, vol: 0.2, atk: 0.015, type: 'triangle', vib: { rate: 30, depth: 70 } });
T(c, { f: 1050, f2: 560, at: 0.11, dur: 0.26, vol: 0.2, atk: 0.02, type: 'sawtooth', lp: 1800,
vib: { rate: 32, depth: 90 }, am: { rate: 30, depth: 0.35 } });
T(c, { f: 2100, f2: 1200, at: 0.11, dur: 0.16, vol: 0.04 });
},
eggWobble: (c) => { // soft wooden tok-tok
T(c, { f: 880, f2: 620, dur: 0.06, vol: 0.17, atk: 0.002, type: 'triangle' });
N(c, { f: 2500, q: 3, dur: 0.025, vol: 0.04, atk: 0.001 });
T(c, { f: 760, f2: 540, at: 0.14, dur: 0.06, vol: 0.16, atk: 0.002, type: 'triangle' });
N(c, { f: 2200, q: 3, at: 0.14, dur: 0.025, vol: 0.03, atk: 0.001 });
},
eggCrack: (c) => { // gentle crackle, then a bright pop
N(c, { f: 3000, q: 2, dur: 0.03, vol: 0.08, atk: 0.001 });
N(c, { f: 2200, q: 2, at: 0.05, dur: 0.04, vol: 0.09, atk: 0.001 });
T(c, { f: 360, f2: 1100, at: 0.14, dur: 0.08, vol: 0.15, atk: 0.003 });
bell(c, 1568, 0.18, 0.35, 0.07);
},
pet: (c) => { // soft fluffy brush stroke
N(c, { f: 900, f2: 2200, q: 0.7, dur: 0.32, vol: 0.24, atk: 0.12 });
N(c, { f: 700, type: 'lowpass', dur: 0.3, vol: 0.1, atk: 0.1 });
},
treat: (c) => { // crunchy nom-nom: two little bites
for (const at of [0, 0.17]) {
N(c, { f: 1800, q: 1.2, at, dur: 0.05, vol: 0.2, atk: 0.002, am: { rate: 90, depth: 0.6 } });
T(c, { f: 300, f2: 220, at: at + 0.01, dur: 0.09, vol: 0.16, atk: 0.01, type: 'triangle' });
}
},
buy: (c) => { // cheerful bell "ka-ching"
N(c, { f: 5000, type: 'highpass', dur: 0.02, vol: 0.04, atk: 0.001 });
bell(c, 1319, 0, 0.15, 0.1);
bell(c, 2093, 0.08, 0.6, 0.11);
T(c, { f: 2637, at: 0.08, dur: 0.5, vol: 0.06, atk: 0.003 });
T(c, { f: 3136, at: 0.11, dur: 0.4, vol: 0.03, atk: 0.003 });
},
wear: (c) => { // sparkly whoosh
N(c, { f: 500, f2: 3000, q: 1.1, dur: 0.4, vol: 0.22, atk: 0.15 });
for (let i = 0; i < 3; i++) T(c, { f: rnd(2400, 4000), at: 0.2 + i * 0.06, dur: 0.25, vol: 0.1, atk: 0.003 });
},
unlock: (c) => { // small rising arpeggio fanfare
[523, 659, 784, 1047].forEach((f, i) => T(c, { f, at: i * 0.09, dur: 0.3, vol: 0.12, atk: 0.004 }));
T(c, { f: 523, at: 0.38, dur: 0.45, vol: 0.07, atk: 0.01, type: 'triangle' });
bell(c, 1568, 0.38, 0.42, 0.11);
T(c, { f: 2093, at: 0.4, dur: 0.38, vol: 0.04, atk: 0.003 });
},
};
const PRIORITY = new Set<Sfx>(['catch', 'trophy', 'click']);
export function playSfx(name: Sfx, o: PlayOpts = {}): void {
const ctx = getCtx();
if (!ctx || ctx.state !== 'running') return;
if (!PRIORITY.has(name) && !canPlay()) return;
base = ctx.currentTime + 0.005;
FX[name]({ p: clamp(o.pitch ?? 1, 0.25, 4), v: clamp(o.volume ?? 1, 0, 1), pan: clamp(o.pan ?? 0, -1, 1) });
}
meow.ts (src/audio/meow.ts)89 lines
// Formant-synthesized cute meow: saw + breath noise through gliding bandpass formants.
import { getCtx, getSfxBus, getNoiseBuffer, trackVoice, canPlay, rnd, clamp } from './context';
import type { Mood, PlayOpts } from './types';
interface Unit {
at: number; dur: number; gain: number;
contour: [number, number][]; // [relative time 0..1, pitch multiplier]
f1: [number, number]; f2: [number, number];
}
const MOODS: Record<Mood, Unit[]> = {
happy: [{ at: 0, dur: 0.55, gain: 1, contour: [[0, 0.85], [0.3, 1.25], [0.7, 1.05], [1, 0.8]], f1: [380, 800], f2: [2300, 1200] }],
tease: [
{ at: 0, dur: 0.2, gain: 0.9, contour: [[0, 0.95], [0.5, 1.2], [1, 1.05]], f1: [450, 650], f2: [1800, 1500] },
{ at: 0.27, dur: 0.22, gain: 0.85, contour: [[0, 1], [0.5, 1.3], [1, 1.1]], f1: [450, 650], f2: [1800, 1500] },
],
sleepy: [{ at: 0, dur: 1.05, gain: 0.8, contour: [[0, 0.8], [0.35, 1], [1, 0.55]], f1: [350, 650], f2: [1900, 1000] }],
surprised: [{ at: 0, dur: 0.3, gain: 1.1, contour: [[0, 1], [1, 1.9]], f1: [450, 750], f2: [2400, 1900] }],
proud: [{ at: 0, dur: 0.95, gain: 0.95, contour: [[0, 0.85], [0.45, 1.1], [1, 0.9]], f1: [400, 850], f2: [2200, 1100] }],
};
function playUnit(f0: number, size: number, vol: number, pan: number, u: Unit): void {
const c = getCtx(), bus = getSfxBus(), nb = getNoiseBuffer();
if (!c || !bus || !nb) return;
const t = c.currentTime + 0.005 + u.at;
const end = t + u.dur + 0.05;
const nodes: AudioNode[] = [];
const osc = c.createOscillator(); osc.type = 'sawtooth';
osc.frequency.setValueAtTime(f0 * u.contour[0][1], t);
for (let i = 1; i < u.contour.length; i++) osc.frequency.linearRampToValueAtTime(f0 * u.contour[i][1], t + u.dur * u.contour[i][0]);
const vib = c.createOscillator(); vib.frequency.value = rnd(5, 6.5);
const vg = c.createGain(); vg.gain.value = 14;
vib.connect(vg); vg.connect(osc.detune);
const nz = c.createBufferSource(); nz.buffer = nb; nz.loop = true;
const ng = c.createGain(); ng.gain.value = 0.12;
nz.connect(ng);
const src = c.createGain();
osc.connect(src); ng.connect(src);
const sum = c.createGain();
const peak = 0.6 * vol * u.gain;
sum.gain.setValueAtTime(0.0001, t);
sum.gain.linearRampToValueAtTime(peak, t + Math.min(0.05, u.dur * 0.2));
sum.gain.linearRampToValueAtTime(peak * 0.7, t + u.dur * 0.75);
sum.gain.exponentialRampToValueAtTime(0.0001, t + u.dur);
const formants: [number, number, number, number][] = [
[u.f1[0] * size, u.f1[1] * size, 6, 1],
[u.f2[0] * size, u.f2[1] * size, 8, 0.7],
[2900 * size, 2900 * size, 10, 0.3],
];
for (const [a, b, q, g] of formants) {
const bp = c.createBiquadFilter(); bp.type = 'bandpass'; bp.Q.value = q;
bp.frequency.setValueAtTime(a, t);
bp.frequency.linearRampToValueAtTime(b, t + u.dur * 0.85);
const bg = c.createGain(); bg.gain.value = g;
src.connect(bp); bp.connect(bg); bg.connect(sum);
nodes.push(bp, bg);
}
let tail: AudioNode = sum;
if (pan && typeof c.createStereoPanner === 'function') {
const p = c.createStereoPanner(); p.pan.value = pan; sum.connect(p); tail = p; nodes.push(p);
}
tail.connect(bus);
nodes.push(vg, ng, src, sum);
trackVoice(nz, [], true);
trackVoice(vib, [], true);
trackVoice(osc, nodes, true);
vib.start(t); nz.start(t, Math.random()); osc.start(t);
vib.stop(end); nz.stop(end); osc.stop(end);
}
/** voice 0..1: 0 = big low cat (~300 Hz), 1 = tiny kitten (~900 Hz). */
export function playMeow(voice: number, mood: Mood = 'happy', o: PlayOpts = {}): void {
const ctx = getCtx();
if (!ctx || ctx.state !== 'running' || !canPlay()) return;
const v = clamp(voice, 0, 1);
const f0 = 300 * Math.pow(3, v) * (o.pitch ?? 1) * (1 + (Math.random() - 0.5) * 0.06);
const size = 0.9 + 0.3 * v;
const vol = 0.8 * clamp(o.volume ?? 1, 0, 1);
const pan = clamp(o.pan ?? 0, -1, 1);
const stretch = 1 + (Math.random() - 0.5) * 0.1;
for (const u of MOODS[mood]) playUnit(f0, size, vol, pan, { ...u, dur: u.dur * stretch, at: u.at * stretch });
}
music.ts (src/audio/music.ts)84 lines
// Lookahead scheduler (setInterval + ctx.currentTime) with crossfades between tracks.
import { getCtx, getMusicBus } from './context';
import { TRACKS } from './tracks';
import type { TrackDef } from './tracks';
import type { Track } from './types';
interface Active { def: TrackDef; out: GainNode; step: number; next: number; sd: number; fadeEnd: number }
const LOOKAHEAD = 0.6; // long lookahead: music keeps playing smoothly when the phone's main thread is busy
const BACKLOG = 1.2;
const FADE = 0.8;
let want: Track | null = null;
let playing: Track | null = null;
let cur: Active | null = null;
let fading: Active[] = [];
let timer: number | null = null;
function run(a: Active, now: number): void {
if (a.next < now - BACKLOG) { // tab was hidden / main thread stalled: skip, don't pile up notes
const skip = Math.ceil((now - a.next) / a.sd);
a.step += skip; a.next += skip * a.sd;
}
while (a.next < now + LOOKAHEAD) {
a.def.step(a.step, a.next, a.out);
a.step++; a.next += a.sd;
}
}
function tick(): void {
const ctx = getCtx();
if (!ctx) return;
const now = ctx.currentTime;
if (cur) run(cur, now);
fading = fading.filter((a) => {
if (now <= a.fadeEnd) return true;
a.out.disconnect();
return false;
});
if (!cur && !fading.length && timer !== null) { window.clearInterval(timer); timer = null; }
}
function fadeOut(a: Active, now: number, dur: number): void {
a.out.gain.cancelScheduledValues(now);
a.out.gain.setValueAtTime(a.out.gain.value, now);
a.out.gain.linearRampToValueAtTime(0, now + dur);
a.fadeEnd = now + dur + 0.1;
fading.push(a);
}
/** Make the playing track match the wanted one. Safe before init (waits for context). */
export function syncMusic(): void {
const ctx = getCtx(), bus = getMusicBus();
if (!ctx || !bus || playing === want) return;
const now = ctx.currentTime;
if (cur) { fadeOut(cur, now, want ? FADE : 0.5); cur = null; }
playing = want;
if (want) {
const def = TRACKS[want];
const out = ctx.createGain();
out.gain.setValueAtTime(0, now);
out.gain.linearRampToValueAtTime(def.level, now + FADE);
out.connect(bus);
cur = { def, out, step: 0, next: now + 0.06, sd: 60 / def.bpm / def.spb, fadeEnd: 0 };
}
if (timer === null && (cur || fading.length)) timer = window.setInterval(tick, 60);
tick();
}
/** After the context was rebuilt: forget old nodes and start the wanted track again. */
export function resetMusic(): void {
cur = null; fading = []; playing = null;
if (timer !== null) { window.clearInterval(timer); timer = null; }
syncMusic();
}
export function startMusic(name: Track): void {
if (name === want) return;
want = name; syncMusic();
}
export function stopMusic(): void {
want = null; syncMusic();
}
tracks.ts (src/audio/tracks.ts)156 lines
// Composed track definitions. Each track yields notes for a global step index.
import { midi } from './context';
import { kalimba, marimba, musicBox, bell, bass, pad, horn, shaker, kick, clap } from './instruments';
import type { Track } from './types';
export interface TrackDef {
bpm: number; spb: number; level: number;
step(i: number, t: number, out: GainNode): void;
}
interface Note { d: number; len: number }
const SCALE = [0, 2, 4, 7, 9]; // major pentatonic; degree 0 = C4
const degFreq = (d: number): number => midi(60 + 12 * Math.floor(d / 5) + SCALE[((d % 5) + 5) % 5]);
/** Tokens: number = scale degree, '.' = rest, '_' = hold previous note, '|' ignored. */
function parse(s: string, steps: number): (Note | null)[] {
const toks = s.replace(/\|/g, ' ').trim().split(/\s+/);
const out: (Note | null)[] = new Array<Note | null>(steps).fill(null);
let last: Note | null = null;
for (let i = 0; i < Math.min(steps, toks.length); i++) {
const tk = toks[i];
if (tk === '.') last = null;
else if (tk === '_') { if (last) last.len++; }
else { last = { d: Number(tk), len: 1 }; out[i] = last; }
}
return out;
}
// ---- village: bouncy, 112 bpm, 8th-note steps, 8-bar phrases, form A A B A ----
const VA = parse(`2 . 3 2 0 . 1 . | 2 . . 3 4 . 3 . | 5 . 4 3 2 . 3 . | 1 . . . 0 . 1 .
| 2 . 3 5 4 . 3 . | 2 3 4 . 3 2 1 . | 1 . 2 1 0 . -1 . | 0 . . . . . . .`, 64);
const VB = parse(`5 . 6 5 4 . 3 . | 4 . 5 . 7 . . . | 8 . 7 6 5 . 4 . | 3 . . 4 3 . 1 .
| 5 . 6 5 4 . 3 . | 4 5 7 . 8 . 7 . | 6 . 5 4 3 . 1 . | 2 . 3 . 1 . . .`, 64);
const VFORM = [VA, VA, VB, VA];
const VROOT = [48, 41, 48, 43, 48, 41, 43, 48];
const village: TrackDef = {
bpm: 112, spb: 2, level: 0.35,
step(i, t, out) {
const n = VFORM[Math.floor(i / 64) % 4][i % 64];
if (n) (Math.floor(i / 64) % 4 === 2 ? marimba : kalimba)(out, t, degFreq(n.d), 0.3);
const s = i % 8, r = VROOT[Math.floor(i / 8) % 8];
if (s === 0 || s === 3) bass(out, t, midi(r), 0.4);
if (s === 4) bass(out, t, midi(r + 7), 0.3);
shaker(out, t, s % 2 ? 0.06 : 0.03);
},
};
// ---- title: music box waltz, 3/4, 6 eighth-steps per bar, 16 bars ----
const TA = parse(`4 . 3 . 2 . | 3 . 2 . 0 . | 4 . 5 . 4 . | 3 . . . 2 . | 5 . 4 . 3 . | 4 . 3 . 2 . | 1 . 2 . 3 . | 0 . . . . .`, 48);
const TB = parse(`7 . 6 . 5 . | 6 . 5 . 3 . | 4 . 5 . 6 . | 5 . . . 3 . | 7 . 6 . 5 . | 6 . 5 . 4 . | 3 . 1 . 2 . | 0 . . . . .`, 48);
const TCH: [number, number[]][] = [
[48, [60, 64, 67]], [45, [57, 60, 64]], [41, [57, 60, 65]], [48, [60, 64, 67]],
[41, [57, 60, 65]], [48, [60, 64, 67]], [43, [59, 62, 67]], [48, [60, 64, 67]],
];
const titleTrack: TrackDef = {
bpm: 100, spb: 2, level: 0.4,
step(i, t, out) {
const n = (Math.floor(i / 48) % 2 ? TB : TA)[i % 48];
if (n) musicBox(out, t, degFreq(n.d), 0.26);
const s = i % 6, [root, triad] = TCH[Math.floor(i / 6) % 8];
if (s === 0) musicBox(out, t, midi(root), 0.2);
if (s === 2 || s === 4) for (const m of triad) musicBox(out, t, midi(m), 0.06);
},
};
// ---- garden: calm 72 bpm, warm pads + bells, 4 chords x 2 bars ----
const GCH: [number, number[]][] = [
[48, [48, 55, 59, 64]], [45, [45, 52, 57, 60, 64]], [41, [41, 48, 57, 64]], [43, [43, 50, 55, 59, 62]],
];
const GBELL = [
parse('2 . . 4 . . 3 . . . 1 . . . . .', 16),
parse('4 . . 5 . . 4 . . 2 . . 3 . . .', 16),
parse('5 . . 7 . . 5 . . 4 . . 3 . . .', 16),
parse('6 . . 5 . . 3 . . 1 . . 2 . . 0', 16),
];
const garden: TrackDef = {
bpm: 72, spb: 2, level: 0.4,
step(i, t, out) {
const c = Math.floor(i / 16) % 4, s = i % 16, [root, tones] = GCH[c];
const sd = 60 / 72 / 2;
if (s === 0) pad(out, t, tones.map(midi), 16 * sd + 1.2, 0.05);
if (s === 0 || s === 8) bass(out, t, midi(root), 0.22);
const n = GBELL[c][s];
if (n) bell(out, t, degFreq(n.d + 5), 0.16);
},
};
// ---- victory: 8-bar fanfare, then a happy dance groove loop (120 bpm) ----
const FAN = parse(`3 . 3 . 3 . 5 _ | _ _ _ . 4 . 5 . | 7 _ . 7 . 8 . 7 | 5 _ _ _ . . 3 .
| 5 . 5 . 5 . 7 _ | _ _ _ . 6 . 7 . | 8 _ 7 _ 6 _ 5 _ | 5 _ _ _ . . . .`, 64);
const FROOT = [48, 48, 41, 48, 48, 45, 43, 48];
const TRI: Record<number, number[]> = { 48: [60, 64, 67], 41: [57, 60, 65], 45: [57, 60, 64], 43: [59, 62, 67] };
const GRV = parse(`5 . 4 3 . 4 5 . | 3 . 2 . 3 . . . | 4 . 5 . 7 . 5 . | 6 . 5 . 3 . 1 .
| 5 . 4 3 . 4 5 . | 3 . 2 . 3 . 5 . | 7 . 5 . 4 . 3 . | 1 . 2 . 3 . 1 .`, 64);
const GROOT = [48, 45, 41, 43, 48, 45, 41, 43];
const victory: TrackDef = {
bpm: 120, spb: 2, level: 0.4,
step(i, t, out) {
const sd = 60 / 120 / 2;
if (i < 64) {
const s = i % 8, r = FROOT[Math.floor(i / 8)];
const n = FAN[i];
if (n) {
horn(out, t, degFreq(n.d), n.len * sd * 0.95);
bell(out, t, degFreq(n.d + 5), 0.07);
}
if (s === 0 || s === 4) {
bass(out, t, midi(r), 0.4);
for (const m of TRI[r]) marimba(out, t, midi(m), 0.09);
}
if (s === 0) kick(out, t, 0.25);
return;
}
const j = (i - 64) % 64, s = j % 8, r = GROOT[Math.floor(j / 8)];
const n = GRV[j];
if (n) (j >= 32 ? marimba : kalimba)(out, t, degFreq(n.d), 0.3);
if (s === 0 || s === 3 || s === 6) bass(out, t, midi(r), 0.4);
if (s === 4) bass(out, t, midi(r + 7), 0.3);
if (s === 0 || s === 4) kick(out, t, 0.28);
if (s === 2 || s === 6) clap(out, t, 0.1);
shaker(out, t, s % 2 ? 0.07 : 0.035);
},
};
// ---- home: cozy sanctuary lullaby, F major, 80 bpm, 8th-note steps, form A A B A ----
const MAJ = [0, 2, 4, 5, 7, 9, 11]; // major scale; degree 0 = F4
const majFreq = (d: number): number => midi(65 + 12 * Math.floor(d / 7) + MAJ[((d % 7) + 7) % 7]);
const HA = parse(`2 _ 4 . 3 _ 2 . | 1 _ 2 . 5 _ _ . | 3 _ 5 . 4 _ 3 . | 4 _ _ _ . . . .
| 2 _ 4 . 7 _ 6 . | 5 _ 3 . 5 _ 4 . | 3 _ 2 . 1 _ 4 . | 2 _ _ _ 0 _ _ .`, 64);
const HB = parse(`5 _ 4 . 3 _ 5 . | 4 _ 2 . 0 _ 2 . | 3 _ 4 . 5 _ 3 . | 4 _ _ _ 6 _ _ .
| 6 _ 4 . 2 _ 4 . | 5 _ 7 . 5 _ 2 . | 3 _ 1 . 4 _ 6 . | 7 _ _ _ _ _ . .`, 64);
const HCH: Record<string, [number, number[]]> = {
F: [41, [57, 60, 65]], Dm: [38, [57, 62, 65]], Bb: [46, [58, 62, 65]], C: [48, [55, 60, 64]],
Gm: [43, [55, 58, 62]], Am: [45, [57, 60, 64]],
};
// one chord per half bar
const HCA = 'F F Dm Dm Bb Bb C C F F Bb Bb C C F F'.split(' ');
const HCB = 'Bb Bb F F Gm Gm C C Am Am Dm Dm Gm C F F'.split(' ');
const HFORM: [(Note | null)[], string[]][] = [[HA, HCA], [HA, HCA], [HB, HCB], [HA, HCA]];
const home: TrackDef = {
bpm: 80, spb: 2, level: 0.4,
step(i, t, out) {
const [mel, chords] = HFORM[Math.floor(i / 64) % 4], j = i % 64, s = j % 8;
const n = mel[j];
if (n) musicBox(out, t, majFreq(n.d), 0.24);
const [root, tri] = HCH[chords[Math.floor(j / 4)]];
if (s === 0) bass(out, t, midi(root), 0.2);
if (s === 4) bass(out, t, midi(root + 7), 0.12);
if (s === 2) marimba(out, t, midi(tri[0]), 0.07);
if (s === 3 || s === 7) marimba(out, t, midi(tri[1]), 0.06);
if (s === 6) marimba(out, t, midi(tri[2]), 0.07);
},
};
export const TRACKS: Record<Track, TrackDef> = { title: titleTrack, village, garden, victory, home };
instruments.ts (src/audio/instruments.ts)45 lines
// Soft music instruments (all routed to a track output gain, never counted as sfx voices).
import { tone, noise } from './context';
type Out = GainNode;
const M = (out: Out) => ({ music: true as const, dest: out });
export const kalimba = (out: Out, t: number, f: number, v = 0.3): void => {
tone({ ...M(out), f, t, dur: 0.9, vol: v, atk: 0.003 });
tone({ ...M(out), f: f * 5.4, t, dur: 0.07, vol: v * 0.2, atk: 0.002 });
};
export const marimba = (out: Out, t: number, f: number, v = 0.3): void => {
tone({ ...M(out), f, t, dur: 0.5, vol: v, atk: 0.003 });
tone({ ...M(out), f: f * 4, t, dur: 0.09, vol: v * 0.3, atk: 0.002 });
};
export const musicBox = (out: Out, t: number, f: number, v = 0.25): void => {
tone({ ...M(out), f, t, dur: 1.4, vol: v, atk: 0.003 });
tone({ ...M(out), f: f * 3, t, dur: 0.2, vol: v * 0.2, atk: 0.002 });
};
export const bell = (out: Out, t: number, f: number, v = 0.2): void => {
tone({ ...M(out), f, t, dur: 2, vol: v, atk: 0.004 });
tone({ ...M(out), f: f * 2.76, t, dur: 0.8, vol: v * 0.25, atk: 0.003 });
};
export const bass = (out: Out, t: number, f: number, v = 0.4): void => {
tone({ ...M(out), f, t, dur: 0.35, vol: v, atk: 0.006 });
tone({ ...M(out), f, t, dur: 0.25, vol: v * 0.4, atk: 0.006, type: 'triangle', lp: 500 });
};
export const pad = (out: Out, t: number, freqs: number[], dur: number, v = 0.05): void => {
for (const f of freqs) {
for (const d of [-7, 7]) tone({ ...M(out), f, t, dur, vol: v, atk: 1.4, rel: 1.8, type: 'triangle', detune: d, lp: 900 });
}
};
export const horn = (out: Out, t: number, f: number, dur: number, v = 0.14): void => {
tone({ ...M(out), f, t, dur: dur + 0.1, vol: v, atk: 0.03, rel: 0.12, type: 'sawtooth', lp: 1300 });
tone({ ...M(out), f, t, dur: dur + 0.1, vol: v * 0.8, atk: 0.03, rel: 0.12 });
};
export const shaker = (out: Out, t: number, v = 0.06): void => {
noise({ ...M(out), t, f: 6500, type: 'highpass', dur: 0.05, vol: v, atk: 0.002 });
};
export const kick = (out: Out, t: number, v = 0.3): void => {
tone({ ...M(out), f: 130, f2: 45, t, dur: 0.2, vol: v, atk: 0.002 });
};
export const clap = (out: Out, t: number, v = 0.12): void => {
noise({ ...M(out), t, f: 1800, q: 0.8, dur: 0.1, vol: v, atk: 0.002 });
};
types.ts (src/audio/types.ts)7 lines
export type Sfx = 'jump'|'land'|'catch'|'candy'|'boing'|'snore'|'sneeze'|'pounce'|'firework'
|'click'|'purr'|'whoosh'|'poof'|'chest'|'step'|'giggle'|'pop'|'sparkle'|'trophy'|'bump'
|'rawr'|'eggWobble'|'eggCrack'|'pet'|'treat'|'buy'|'wear'|'unlock';
export type Mood = 'happy'|'tease'|'sleepy'|'surprised'|'proud';
export type Track = 'title'|'village'|'garden'|'victory'|'home';
export interface PlayOpts { volume?: number; pitch?: number; pan?: number } // volume 0..1, pitch multiplier, pan -1..1
vite.config.ts10 lines
import { defineConfig } from 'vite';
import { viteSingleFile } from 'vite-plugin-singlefile';
// Normal build: dist/ with hashed assets, relative base so it works under any subfolder.
// Single-file build (SINGLE=1): one self-contained index.html for previews.
export default defineConfig(({ mode }) => ({
base: './',
build: { target: 'es2020', outDir: mode === 'single' ? 'dist-single' : 'dist', chunkSizeWarningLimit: 1200 },
plugins: mode === 'single' ? [viteSingleFile()] : [],
}));
package.json27 lines
{
"name": "fluffy-cat-kingdom",
"version": "1.0.0",
"description": "",
"scripts": {
"dev": "vite --host",
"build": "tsc -p . && vite build",
"build:single": "vite build --mode single",
"preview": "vite preview --host --port 4173",
"typecheck": "tsc -p .",
"test": "node tests/smoke.mjs"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"three": "0.170.0"
},
"devDependencies": {
"@types/three": "0.170.0",
"typescript": "5.7.2",
"vite": "6.0.7",
"vite-plugin-singlefile": "2.1.0"
},
"private": true,
"type": "module"
}
Need an interactive piece for your business or audience?
A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.