Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(city): player-rig math module + articulated cyber-runner avatar

[._.]/ Adam Eivy676137773fb6
diff --git a/client/src/components/city/PlayerAvatar.jsx b/client/src/components/city/PlayerAvatar.jsx
index c2fc0d6458..f633cbf7d9 100644
--- a/client/src/components/city/PlayerAvatar.jsx
+++ b/client/src/components/city/PlayerAvatar.jsx
@@ -1,157 +1,227 @@
-import { useRef, useMemo } from 'react';
+import { useRef, useMemo, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
-
-const BODY_COLOR = '#0c0c24';
-const NEON_COLOR = '#06b6d4';
-const VISOR_COLOR = '#06b6d4';
-const EYE_COLOR = '#ff3366';
-
-export default function PlayerAvatar({ isMovingRef, facingAngleRef }) {
- const groupRef = useRef();
- const leftArmRef = useRef();
- const rightArmRef = useRef();
- const leftLegRef = useRef();
- const rightLegRef = useRef();
- const walkPhaseRef = useRef(0);
-
- const torsoEdges = useMemo(() => {
- const geom = new THREE.BoxGeometry(0.3, 0.4, 0.2);
- return new THREE.EdgesGeometry(geom);
- }, []);
-
- useFrame((_, delta) => {
- if (!groupRef.current) return;
-
- // Facing direction
- groupRef.current.rotation.y = facingAngleRef.current;
-
- // Idle bob
- const t = performance.now() / 1000;
- const bob = Math.sin(t * 2) * 0.03;
- groupRef.current.position.y = bob;
-
- // Walk animation
- if (isMovingRef.current) {
- walkPhaseRef.current += delta * 12;
+import { useCityPalette } from './CityPaletteContext';
+import { dampFactor, dampAngle } from '../../utils/cityPlayerRig';
+
+// The exploration-mode cyber-runner: a stylized articulated character (~1.7 units tall)
+// rendered in third person. Reads the PlayerController's mutable rig every frame — no
+// React state on the hot path — and animates by rig.state:
+// idle — soft bob, visor breathing, slow head scan
+// walk — opposing hip/shoulder swing with elbow/knee follow-through
+// run — faster phase, bigger amplitude, torso pitched into the sprint
+// hover — flyover: legs tuck, jet vents flare, glow disc brightens (a flying runner,
+// not a mid-air walker)
+// Body color tracks the theme's structural dark; visor/trim/soles glow the theme accent.
+// Geometry is shared at module scope; materials are per-mount (theme-tinted).
+
+const EYE_COLOR = '#ff3366'; // semantic sensor red — not themed
+
+const GEO = {
+ helmet: new THREE.IcosahedronGeometry(0.16, 1),
+ visor: new THREE.BoxGeometry(0.26, 0.07, 0.08),
+ sensor: new THREE.BoxGeometry(0.05, 0.02, 0.02),
+ torso: new THREE.BoxGeometry(0.42, 0.5, 0.26),
+ core: new THREE.CylinderGeometry(0.09, 0.09, 0.03, 6),
+ pauldron: new THREE.OctahedronGeometry(0.12, 0),
+ upperArm: new THREE.CylinderGeometry(0.05, 0.045, 0.28, 6),
+ forearm: new THREE.CylinderGeometry(0.045, 0.04, 0.26, 6),
+ fist: new THREE.SphereGeometry(0.055, 6, 6),
+ pelvis: new THREE.BoxGeometry(0.3, 0.16, 0.2),
+ thigh: new THREE.CylinderGeometry(0.06, 0.055, 0.32, 6),
+ shin: new THREE.CylinderGeometry(0.05, 0.045, 0.3, 6),
+ boot: new THREE.BoxGeometry(0.11, 0.08, 0.22),
+ sole: new THREE.BoxGeometry(0.11, 0.02, 0.22),
+ backUnit: new THREE.BoxGeometry(0.22, 0.28, 0.1),
+ vent: new THREE.CylinderGeometry(0.035, 0.05, 0.1, 6),
+ disc: new THREE.CircleGeometry(0.45, 18),
+};
+GEO.helmet.computeVertexNormals();
+
+// Joint heights (feet at 0): knee 0.31, hip 0.76, torso center 1.08, shoulder 1.3, head 1.55.
+const HIP_Y = 0.76;
+const SHOULDER_Y = 1.3;
+
+export default function PlayerAvatar({ rigRef, eyeHeight = 1.6 }) {
+ const { accent, buildingBody, tintStructure } = useCityPalette();
+
+ // Theme-tinted materials. Trim/visor glow the accent; the animated ones (visor, vents,
+ // disc) are separate instances so per-frame intensity writes don't bleed across parts.
+ const mats = useMemo(() => {
+ const body = new THREE.MeshStandardMaterial({
+ color: buildingBody, roughness: 0.45, metalness: 0.5, flatShading: true,
+ });
+ const dark = new THREE.MeshStandardMaterial({
+ color: tintStructure('#0b101e'), roughness: 0.6, metalness: 0.4,
+ });
+ const trim = new THREE.MeshStandardMaterial({
+ color: accent, emissive: accent, emissiveIntensity: 0.55, toneMapped: false,
+ roughness: 0.3, metalness: 0.3,
+ });
+ const visor = trim.clone();
+ const vents = new THREE.MeshStandardMaterial({
+ color: accent, emissive: accent, emissiveIntensity: 0.0, toneMapped: false,
+ });
+ const sensor = new THREE.MeshBasicMaterial({ color: EYE_COLOR, toneMapped: false });
+ const disc = new THREE.MeshBasicMaterial({
+ color: accent, transparent: true, opacity: 0.16,
+ blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide,
+ });
+ return { body, dark, trim, visor, vents, sensor, disc };
+ }, [accent, buildingBody, tintStructure]);
+
+ // R3F doesn't dispose materials handed in via the `material` prop — free the prior
+ // set when a theme switch rebuilds them, and on unmount.
+ useEffect(() => () => { Object.values(mats).forEach((m) => m.dispose()); }, [mats]);
+
+ const rootRef = useRef();
+ const headRef = useRef();
+ const torsoRef = useRef();
+ const hipL = useRef();
+ const hipR = useRef();
+ const kneeL = useRef();
+ const kneeR = useRef();
+ const shoulderL = useRef();
+ const shoulderR = useRef();
+ const elbowL = useRef();
+ const elbowR = useRef();
+ const phaseRef = useRef(0);
+ const groundOffsetRef = useRef(-eyeHeight);
+
+ useFrame(({ clock }, delta) => {
+ const root = rootRef.current;
+ const rig = rigRef?.current;
+ if (!root || !rig) return;
+ const t = clock.getElapsedTime();
+ const f = dampFactor(8, delta);
+ const state = rig.state;
+ const hovering = state === 'hover';
+ const running = state === 'run';
+ const moving = state === 'walk' || running;
+
+ // Root follows the rig: feet on the ground normally; in hover the body floats
+ // closer to the camera anchor with legs tucked.
+ const targetOffset = hovering ? -1.05 : -eyeHeight;
+ groundOffsetRef.current += (targetOffset - groundOffsetRef.current) * f;
+ const bob = state === 'idle' ? Math.sin(t * 1.6) * 0.03 : hovering ? Math.sin(t * 2.2) * 0.06 : 0;
+ root.position.set(rig.position.x, rig.position.y + groundOffsetRef.current + bob, rig.position.z);
+ root.rotation.y = rig.facing;
+ root.rotation.z = rig.bank;
+
+ // Gait phase advances while moving, settles to neutral at rest.
+ if (moving) phaseRef.current += delta * (running ? 14 : 9);
+ else phaseRef.current *= 1 - Math.min(1, f * 1.4);
+ const amp = running ? 0.9 : 0.55;
+ const swing = moving ? Math.sin(phaseRef.current) * amp : 0;
+ const counter = -swing;
+
+ const lerpRot = (ref, x) => {
+ if (ref.current) ref.current.rotation.x += (x - ref.current.rotation.x) * f;
+ };
+
+ if (hovering) {
+ // Tuck: thighs forward, knees folded, arms slightly out and back.
+ lerpRot(hipL, 0.65);
+ lerpRot(hipR, 0.65);
+ lerpRot(kneeL, -1.2);
+ lerpRot(kneeR, -1.2);
+ lerpRot(shoulderL, -0.35);
+ lerpRot(shoulderR, -0.35);
+ lerpRot(elbowL, -0.5);
+ lerpRot(elbowR, -0.5);
} else {
- // Damp walk phase toward zero
- walkPhaseRef.current *= 0.85;
+ // Gait: hips/shoulders oppose; knees and elbows follow through a half-beat later.
+ const follow = moving ? Math.max(0, Math.sin(phaseRef.current + 0.5)) * amp * 0.9 : 0;
+ const followR = moving ? Math.max(0, Math.sin(phaseRef.current + Math.PI + 0.5)) * amp * 0.9 : 0;
+ const elbowBase = running ? -0.8 : moving ? -0.3 : -0.12;
+ lerpRot(hipL, swing);
+ lerpRot(hipR, counter);
+ lerpRot(kneeL, -follow);
+ lerpRot(kneeR, -followR);
+ lerpRot(shoulderL, counter * 0.8);
+ lerpRot(shoulderR, swing * 0.8);
+ lerpRot(elbowL, elbowBase - Math.max(0, counter) * 0.4);
+ lerpRot(elbowR, elbowBase - Math.max(0, swing) * 0.4);
}
- const swing = Math.sin(walkPhaseRef.current) * 0.6;
+ // Torso pitches into a sprint; head scans slowly at idle.
+ if (torsoRef.current) {
+ torsoRef.current.rotation.x += ((running ? 0.18 : hovering ? -0.1 : 0) - torsoRef.current.rotation.x) * f;
+ }
+ if (headRef.current) {
+ const scan = state === 'idle' ? Math.sin(t * 0.4) * 0.22 : 0;
+ headRef.current.rotation.y = dampAngle(headRef.current.rotation.y, scan, f);
+ }
- if (leftArmRef.current) leftArmRef.current.rotation.x = swing;
- if (rightArmRef.current) rightArmRef.current.rotation.x = -swing;
- if (leftLegRef.current) leftLegRef.current.rotation.x = -swing;
- if (rightLegRef.current) rightLegRef.current.rotation.x = swing;
+ // Emissive life: visor breathes at idle, vents flare in hover, disc brightens in hover.
+ mats.visor.emissiveIntensity = 0.55 + (state === 'idle' ? (Math.sin(t * 1.8) + 1) * 0.12 : 0.15);
+ const ventTarget = hovering ? 0.9 + (Math.sin(t * 6) + 1) * 0.25 : moving ? 0.25 : 0.05;
+ mats.vents.emissiveIntensity += (ventTarget - mats.vents.emissiveIntensity) * f;
+ mats.disc.opacity = hovering ? 0.3 : 0.16;
});
- // Foot bottom = hip(0.55) - footOffset(0.32) - halfFootHeight(0.02) = 0.21
- // Shift body down by 0.18 so feet rest at Y=0.03, just above ground
- const bodyOffset = -0.18;
-
return (
- <group ref={groupRef}>
- {/* Body group offset so feet touch ground */}
- <group position={[0, bodyOffset, 0]}>
- {/* Head - wireframe icosahedron */}
- <group position={[0, 1.05, 0]}>
- <mesh>
- <icosahedronGeometry args={[0.12, 0]} />
- <meshBasicMaterial color={NEON_COLOR} wireframe transparent opacity={0.7} />
- </mesh>
- {/* Visor */}
- <mesh position={[0, 0, 0.08]}>
- <boxGeometry args={[0.18, 0.05, 0.04]} />
- <meshBasicMaterial color={VISOR_COLOR} transparent opacity={0.8} />
- </mesh>
- {/* Eyes */}
- <mesh position={[-0.04, 0, 0.11]}>
- <boxGeometry args={[0.03, 0.02, 0.01]} />
- <meshBasicMaterial color={EYE_COLOR} />
- </mesh>
- <mesh position={[0.04, 0, 0.11]}>
- <boxGeometry args={[0.03, 0.02, 0.01]} />
- <meshBasicMaterial color={EYE_COLOR} />
- </mesh>
+ <group ref={rootRef}>
+ <group ref={torsoRef} position={[0, HIP_Y + 0.08, 0]}>
+ {/* Torso + chest core */}
+ <mesh geometry={GEO.torso} material={mats.body} position={[0, 0.26, 0]} />
+ <mesh geometry={GEO.core} material={mats.trim} rotation={[Math.PI / 2, 0, 0]} position={[0, 0.3, 0.14]} />
+ {/* Back unit + jet vents */}
+ <mesh geometry={GEO.backUnit} material={mats.dark} position={[0, 0.28, -0.17]} />
+ <mesh geometry={GEO.vent} material={mats.vents} position={[-0.07, 0.12, -0.18]} />
+ <mesh geometry={GEO.vent} material={mats.vents} position={[0.07, 0.12, -0.18]} />
+
+ {/* Head */}
+ <group ref={headRef} position={[0, SHOULDER_Y - HIP_Y + 0.17, 0]}>
+ <mesh geometry={GEO.helmet} material={mats.body} />
+ <mesh geometry={GEO.visor} material={mats.visor} position={[0, 0.01, 0.12]} />
+ <mesh geometry={GEO.sensor} material={mats.sensor} position={[0, -0.07, 0.14]} />
</group>
- {/* Torso */}
- <group position={[0, 0.75, 0]}>
- <mesh>
- <boxGeometry args={[0.3, 0.4, 0.2]} />
- <meshBasicMaterial color={BODY_COLOR} transparent opacity={0.9} />
- </mesh>
- {/* Neon wireframe edges */}
- <lineSegments geometry={torsoEdges}>
- <lineBasicMaterial color={NEON_COLOR} transparent opacity={0.8} />
- </lineSegments>
- </group>
+ {/* Pauldrons */}
+ <mesh geometry={GEO.pauldron} material={mats.trim} position={[-0.27, 0.48, 0]} scale={[1, 0.7, 1]} />
+ <mesh geometry={GEO.pauldron} material={mats.trim} position={[0.27, 0.48, 0]} scale={[1, 0.7, 1]} />
- {/* Left arm - pivoted at shoulder */}
- <group position={[-0.22, 0.9, 0]}>
- <group ref={leftArmRef}>
- <mesh position={[0, -0.125, 0]}>
- <cylinderGeometry args={[0.04, 0.04, 0.25, 6]} />
- <meshBasicMaterial color={BODY_COLOR} transparent opacity={0.9} />
- </mesh>
+ {/* Arms: shoulder → elbow, two segments each */}
+ <group ref={shoulderL} position={[-0.3, 0.44, 0]}>
+ <mesh geometry={GEO.upperArm} material={mats.body} position={[0, -0.14, 0]} />
+ <group ref={elbowL} position={[0, -0.28, 0]}>
+ <mesh geometry={GEO.forearm} material={mats.dark} position={[0, -0.13, 0]} />
+ <mesh geometry={GEO.fist} material={mats.dark} position={[0, -0.28, 0]} />
</group>
</group>
-
- {/* Right arm - pivoted at shoulder */}
- <group position={[0.22, 0.9, 0]}>
- <group ref={rightArmRef}>
- <mesh position={[0, -0.125, 0]}>
- <cylinderGeometry args={[0.04, 0.04, 0.25, 6]} />
- <meshBasicMaterial color={BODY_COLOR} transparent opacity={0.9} />
- </mesh>
+ <group ref={shoulderR} position={[0.3, 0.44, 0]}>
+ <mesh geometry={GEO.upperArm} material={mats.body} position={[0, -0.14, 0]} />
+ <group ref={elbowR} position={[0, -0.28, 0]}>
+ <mesh geometry={GEO.forearm} material={mats.dark} position={[0, -0.13, 0]} />
+ <mesh geometry={GEO.fist} material={mats.dark} position={[0, -0.28, 0]} />
</group>
</group>
+ </group>
- {/* Left leg - pivoted at hip */}
- <group position={[-0.08, 0.55, 0]}>
- <group ref={leftLegRef}>
- <mesh position={[0, -0.15, 0]}>
- <cylinderGeometry args={[0.05, 0.05, 0.3, 6]} />
- <meshBasicMaterial color={BODY_COLOR} transparent opacity={0.9} />
- </mesh>
- {/* Foot */}
- <mesh position={[0, -0.32, 0.03]}>
- <boxGeometry args={[0.07, 0.04, 0.12]} />
- <meshBasicMaterial color={NEON_COLOR} transparent opacity={0.6} />
- </mesh>
- </group>
- </group>
+ {/* Pelvis */}
+ <mesh geometry={GEO.pelvis} material={mats.dark} position={[0, HIP_Y, 0]} />
- {/* Right leg - pivoted at hip */}
- <group position={[0.08, 0.55, 0]}>
- <group ref={rightLegRef}>
- <mesh position={[0, -0.15, 0]}>
- <cylinderGeometry args={[0.05, 0.05, 0.3, 6]} />
- <meshBasicMaterial color={BODY_COLOR} transparent opacity={0.9} />
- </mesh>
- {/* Foot */}
- <mesh position={[0, -0.32, 0.03]}>
- <boxGeometry args={[0.07, 0.04, 0.12]} />
- <meshBasicMaterial color={NEON_COLOR} transparent opacity={0.6} />
- </mesh>
- </group>
+ {/* Legs: hip → knee, two segments each, boots with glowing soles */}
+ <group ref={hipL} position={[-0.1, HIP_Y - 0.04, 0]}>
+ <mesh geometry={GEO.thigh} material={mats.body} position={[0, -0.16, 0]} />
+ <group ref={kneeL} position={[0, -0.32, 0]}>
+ <mesh geometry={GEO.shin} material={mats.dark} position={[0, -0.15, 0]} />
+ <mesh geometry={GEO.boot} material={mats.dark} position={[0, -0.32, 0.04]} />
+ <mesh geometry={GEO.sole} material={mats.trim} position={[0, -0.37, 0.04]} />
+ </group>
+ </group>
+ <group ref={hipR} position={[0.1, HIP_Y - 0.04, 0]}>
+ <mesh geometry={GEO.thigh} material={mats.body} position={[0, -0.16, 0]} />
+ <group ref={kneeR} position={[0, -0.32, 0]}>
+ <mesh geometry={GEO.shin} material={mats.dark} position={[0, -0.15, 0]} />
+ <mesh geometry={GEO.boot} material={mats.dark} position={[0, -0.32, 0.04]} />
+ <mesh geometry={GEO.sole} material={mats.trim} position={[0, -0.37, 0.04]} />
</group>
</group>
- {/* Glow disc at ground level (outside body offset) */}
- <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.03, 0]}>
- <circleGeometry args={[0.4, 16]} />
- <meshBasicMaterial
- color={NEON_COLOR}
- transparent
- opacity={0.15}
- side={THREE.DoubleSide}
- blending={THREE.AdditiveBlending}
- depthWrite={false}
- />
- </mesh>
+ {/* Ground glow disc */}
+ <mesh geometry={GEO.disc} material={mats.disc} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, 0]} />
</group>
);
}
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index b5c4953aea..25755ec5d3 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -84,6 +84,7 @@ its tunable constants and placement helpers.
| `cityMiniMap` | Mini-map projection of building positions into 2D bounds (`computeMiniMap`, `projectPoint`). |
| `cityPhotoMode` | Photo-mode camera presets, the demand-loop fly stepper, postcard stats, and screenshot filename (`getPreset`, `cyclePreset`, `stepFly`). |
| `cityPlan` | Master town plan: district parcels, shoreline/bay, plaza, transit loop, street network (`PARCELS`, `WORLD`, `computeStreets`, `computeStreetProps`, `isInWater`). |
+| `cityPlayerRig` | Exploration player-rig math: third-person follow camera, boom collision, damping, facing, avatar state (`thirdPersonCamera`, `resolveBoomT`, `dampAngle`, `moveFacing`, `avatarState`). |
| `cityRooftops` | Deterministic rooftop fixture kits (antenna/tank/AC/dish) per app name (`computeRooftopKit`). |
| `cityProductivity` | Productivity monument from streak/velocity tiers (`computeProductivityMonument`). |
| `citySeasonalDecor` | Season/holiday resolution → seasonal decoration placements (`computeSeasonalDecor`). |
diff --git a/client/src/utils/cityPlan.js b/client/src/utils/cityPlan.js
index e4c314cace..275f59e9ab 100644
--- a/client/src/utils/cityPlan.js
+++ b/client/src/utils/cityPlan.js
@@ -98,6 +98,16 @@ export const TRANSIT = {
// players on land). `margin` extends the water zone toward land (positive = stricter).
export const isInWater = (x, z, margin = 0) => z < WORLD.shorelineZ + margin;
+// True where a ground-level player may stand: any land, plus the Data Harbor's piers —
+// the one parcel built over the water (reached by the avenue gangway). Flying players
+// (above rooftop height) ignore this entirely.
+export const isWalkable = (x, z) => {
+ if (!isInWater(x, z)) return true;
+ const harbor = PARCELS.dataHarbor;
+ return Math.abs(x - harbor.anchor[0]) <= harbor.w / 2
+ && z >= harbor.anchor[2] - harbor.d / 2;
+};
+
// ---------------------------------------------------------------------------
// Streets: ring road + spokes + the harbor avenue, as flat rotated rectangles.
// ---------------------------------------------------------------------------
diff --git a/client/src/utils/cityPlan.test.js b/client/src/utils/cityPlan.test.js
index 94ffeb78b6..42deb91fed 100644
--- a/client/src/utils/cityPlan.test.js
+++ b/client/src/utils/cityPlan.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
- WORLD, PARCELS, PLAZA, TRANSIT, isInWater, computeStreets, computeStreetProps,
+ WORLD, PARCELS, PLAZA, TRANSIT, isInWater, isWalkable, computeStreets, computeStreetProps,
} from './cityPlan';
const staticParcels = Object.entries(PARCELS).filter(([, p]) => !p.dynamic);
@@ -65,6 +65,17 @@ describe('isInWater', () => {
});
});
+describe('isWalkable', () => {
+ it('allows all land, blocks open water, but keeps the harbor piers reachable', () => {
+ expect(isWalkable(0, 0)).toBe(true); // downtown
+ expect(isWalkable(50, WORLD.shorelineZ - 5)).toBe(false); // open bay
+ const harbor = PARCELS.dataHarbor;
+ expect(isWalkable(harbor.anchor[0], harbor.anchor[2])).toBe(true); // on the pier
+ expect(isWalkable(0, WORLD.shorelineZ - 2)).toBe(true); // the gangway off the avenue
+ expect(isWalkable(harbor.anchor[0] + harbor.w, harbor.anchor[2])).toBe(false); // beside the pier
+ });
+});
+
describe('TRANSIT', () => {
it('keeps the loop track on land, above the streets, below rooftop scale', () => {
expect(TRANSIT.y).toBeGreaterThan(6);
diff --git a/client/src/utils/cityPlayerRig.js b/client/src/utils/cityPlayerRig.js
new file mode 100644
index 0000000000..327d037e0e
--- /dev/null
+++ b/client/src/utils/cityPlayerRig.js
@@ -0,0 +1,113 @@
+// Pure math for CyberCity's exploration-mode player rig: the third-person follow camera
+// (spherical boom behind the character with building-aware shortening), frame-rate-
+// independent damping, shortest-arc facing, and the avatar's animation-state classifier.
+// PlayerController owns the THREE.Vector3 plumbing; every formula lives here on plain
+// `{x, y, z}` objects so the whole rig is node-testable (no three.js / React imports).
+
+// Convention (matches PlayerController): forward at yaw is (-sin(yaw), 0, -cos(yaw));
+// the camera hangs BEHIND the character at (+sin(yaw), 0, +cos(yaw)) scaled by the boom.
+
+export const THIRD_PERSON = {
+ boom: 6.5, // camera distance behind the character
+ shoulder: 0.6, // lateral over-the-shoulder offset (positive = right)
+ height: 2.4, // camera rise above the character's feet at pitch 0
+ minPitch: -0.45, // looking up from under the character — floor-limited
+ maxPitch: 1.15, // looking down over the character
+ minCamY: 0.6, // the camera never dips into the pavement
+ lookAhead: 2, // lookAt leads the character so the view reads forward
+ lookHeight: 1.4, // aim at the chest, not the feet
+ camDampRate: 8, // camera position smoothing (lower = floatier)
+ lookDampRate: 12, // aim smoothing (tighter than position so aim stays crisp)
+};
+
+export const clampPitch = (pitch) =>
+ Math.min(THIRD_PERSON.maxPitch, Math.max(THIRD_PERSON.minPitch, pitch));
+
+// Desired third-person camera + aim point for a rig pose. Pure — collision is applied
+// separately via resolveBoomT so callers can damp toward the resolved point.
+export function thirdPersonCamera({ pos, yaw, pitch, boom = THIRD_PERSON.boom }) {
+ const p = clampPitch(pitch);
+ const back = boom * Math.cos(p);
+ const sinYaw = Math.sin(yaw);
+ const cosYaw = Math.cos(yaw);
+ // Right vector at this yaw (for the shoulder offset).
+ const rightX = cosYaw;
+ const rightZ = -sinYaw;
+ return {
+ camera: {
+ x: pos.x + sinYaw * back + rightX * THIRD_PERSON.shoulder,
+ y: Math.max(THIRD_PERSON.minCamY, pos.y + THIRD_PERSON.height + boom * Math.sin(p)),
+ z: pos.z + cosYaw * back + rightZ * THIRD_PERSON.shoulder,
+ },
+ lookAt: {
+ x: pos.x - sinYaw * THIRD_PERSON.lookAhead,
+ y: pos.y + THIRD_PERSON.lookHeight,
+ z: pos.z - cosYaw * THIRD_PERSON.lookAhead,
+ },
+ };
+}
+
+// True when a camera point lands inside a building cylinder (the same cylinder model
+// PlayerController uses for walking collision). Above a building's roof the point is
+// clear — flyover camera angles stay unclipped.
+const insideBuilding = (point, building, radius) =>
+ point.y < (building.height ?? 4) + 0.5
+ && Math.hypot(point.x - building.x, point.z - building.z) < radius;
+
+// Boom-shortening fraction in (0, 1]: walk the camera in toward the aim anchor until it
+// clears every building cylinder. "Collision-aware enough" — a sampled pull-in, not a
+// raycast. `buildings` is any iterable of { x, z, height }.
+export function resolveBoomT({ anchor, camera, buildings, radius = 3.5 }) {
+ const list = buildings ? [...buildings] : [];
+ if (list.length === 0) return 1;
+ const steps = [1, 0.85, 0.7, 0.55, 0.4, 0.3];
+ for (const t of steps) {
+ const point = {
+ x: anchor.x + (camera.x - anchor.x) * t,
+ y: anchor.y + (camera.y - anchor.y) * t,
+ z: anchor.z + (camera.z - anchor.z) * t,
+ };
+ if (!list.some((b) => insideBuilding(point, b, radius))) return t;
+ }
+ return 0.25;
+}
+
+// Frame-rate-independent damping factor: lerp by this each frame and the closure rate
+// stays constant whether the frame took 4ms or 40ms.
+export const dampFactor = (rate, delta) => 1 - Math.exp(-rate * Math.max(0, delta));
+
+// Shortest-arc angular lerp — never spins the long way around ±π.
+export function dampAngle(current, target, factor) {
+ let diff = (target - current) % (Math.PI * 2);
+ if (diff > Math.PI) diff -= Math.PI * 2;
+ if (diff < -Math.PI) diff += Math.PI * 2;
+ return current + diff * factor;
+}
+
+// The facing angle of the character for a local movement input: `forward` is +1 for W /
+// -1 for S, `strafe` is +1 for D / -1 for A. The camera yaw stays mouse-driven; the
+// character turns toward where it's actually going (strafe = quarter-turn run, S = run
+// toward the camera).
+export function moveFacing(yaw, { forward = 0, strafe = 0 }) {
+ if (forward === 0 && strafe === 0) return yaw;
+ // World-space movement direction.
+ const sinYaw = Math.sin(yaw);
+ const cosYaw = Math.cos(yaw);
+ const dx = -sinYaw * forward + cosYaw * strafe;
+ const dz = -cosYaw * forward - sinYaw * strafe;
+ // Character forward is (-sin θ, -cos θ): solve θ so it aligns with (dx, dz).
+ return Math.atan2(-dx, -dz);
+}
+
+// The avatar's animation state for the current rig pose.
+export function avatarState({ moving = false, sprinting = false, airborne = false }) {
+ if (airborne) return 'hover';
+ if (!moving) return 'idle';
+ return sprinting ? 'run' : 'walk';
+}
+
+// Banking target from yaw angular velocity (rad/s): lean into turns, clamped so the
+// character never keels over. Callers damp toward this.
+export function bankAngle(yawRate, max = 0.25, gain = 0.08) {
+ return Math.min(max, Math.max(-max, -yawRate * gain));
+}
diff --git a/client/src/utils/cityPlayerRig.test.js b/client/src/utils/cityPlayerRig.test.js
new file mode 100644
index 0000000000..6fbdcdb2c7
--- /dev/null
+++ b/client/src/utils/cityPlayerRig.test.js
@@ -0,0 +1,146 @@
+import { describe, it, expect } from 'vitest';
+import {
+ THIRD_PERSON, clampPitch, thirdPersonCamera, resolveBoomT,
+ dampFactor, dampAngle, moveFacing, avatarState, bankAngle,
+} from './cityPlayerRig';
+
+const pos = { x: 0, y: 1.6, z: 0 };
+
+describe('thirdPersonCamera', () => {
+ it('hangs the camera behind the character at yaw 0 (facing -Z → camera at +Z)', () => {
+ const { camera, lookAt } = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
+ expect(camera.z).toBeGreaterThan(pos.z + THIRD_PERSON.boom * 0.9);
+ expect(camera.x).toBeCloseTo(THIRD_PERSON.shoulder, 5); // right vector at yaw 0 is +X
+ expect(camera.y).toBeCloseTo(pos.y + THIRD_PERSON.height, 5);
+ // Aim leads the character forward (-Z) at chest height.
+ expect(lookAt.z).toBeCloseTo(-THIRD_PERSON.lookAhead, 5);
+ expect(lookAt.y).toBeCloseTo(pos.y + THIRD_PERSON.lookHeight, 5);
+ });
+
+ it('tracks yaw — at yaw π/2 (facing -X) the camera sits at +X', () => {
+ const { camera } = thirdPersonCamera({ pos, yaw: Math.PI / 2, pitch: 0 });
+ expect(camera.x).toBeGreaterThan(THIRD_PERSON.boom * 0.9);
+ expect(Math.abs(camera.z)).toBeLessThan(1.5); // just the shoulder offset
+ });
+
+ it('raises the camera with positive pitch and clamps both ends', () => {
+ const level = thirdPersonCamera({ pos, yaw: 0, pitch: 0 });
+ const high = thirdPersonCamera({ pos, yaw: 0, pitch: 0.8 });
+ expect(high.camera.y).toBeGreaterThan(level.camera.y);
+ // Clamped: an absurd pitch matches the clamp boundary exactly.
+ const over = thirdPersonCamera({ pos, yaw: 0, pitch: 9 });
+ const atMax = thirdPersonCamera({ pos, yaw: 0, pitch: THIRD_PERSON.maxPitch });
+ expect(over.camera.y).toBeCloseTo(atMax.camera.y, 6);
+ expect(clampPitch(-9)).toBe(THIRD_PERSON.minPitch);
+ });
+
+ it('never dips the camera into the pavement', () => {
+ const { camera } = thirdPersonCamera({ pos: { x: 0, y: 1.6, z: 0 }, yaw: 0, pitch: -0.45 });
+ expect(camera.y).toBeGreaterThanOrEqual(THIRD_PERSON.minCamY);
+ });
+});
+
+describe('resolveBoomT', () => {
+ const anchor = { x: 0, y: 2, z: 0 };
+
+ it('keeps the full boom with no obstructions', () => {
+ expect(resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: [] })).toBe(1);
+ expect(resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: null })).toBe(1);
+ });
+
+ it('shortens the boom when the camera lands inside a building cylinder', () => {
+ const buildings = [{ x: 0, z: 7, height: 10 }];
+ const t = resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings });
+ expect(t).toBeLessThan(1);
+ // The resolved point actually clears the cylinder.
+ const z = anchor.z + (7 - anchor.z) * t;
+ expect(Math.abs(z - 7)).toBeGreaterThanOrEqual(3.5);
+ });
+
+ it('ignores buildings the camera clears above (flyover)', () => {
+ const buildings = [{ x: 0, z: 7, height: 4 }];
+ const t = resolveBoomT({ anchor, camera: { x: 0, y: 12, z: 7 }, buildings });
+ expect(t).toBe(1);
+ });
+
+ it('accepts any iterable (e.g. Map.values())', () => {
+ const map = new Map([['a', { x: 0, z: 7, height: 10 }]]);
+ const t = resolveBoomT({ anchor, camera: { x: 0, y: 3, z: 7 }, buildings: map.values() });
+ expect(t).toBeLessThan(1);
+ });
+});
+
+describe('dampFactor', () => {
+ it('is monotonic in delta and bounded to [0, 1)', () => {
+ const a = dampFactor(8, 0.004);
+ const b = dampFactor(8, 0.016);
+ const c = dampFactor(8, 0.1);
+ expect(a).toBeLessThan(b);
+ expect(b).toBeLessThan(c);
+ expect(c).toBeLessThan(1);
+ expect(dampFactor(8, 0)).toBe(0);
+ expect(dampFactor(8, -1)).toBe(0); // negative delta can't overshoot backward
+ });
+
+ it('two small steps ≈ one big step (frame-rate independence)', () => {
+ const one = dampFactor(8, 0.032);
+ const half = dampFactor(8, 0.016);
+ const twoStep = half + (1 - half) * half;
+ expect(twoStep).toBeCloseTo(one, 6);
+ });
+});
+
+describe('dampAngle', () => {
+ it('moves toward the target', () => {
+ expect(dampAngle(0, 1, 0.5)).toBeCloseTo(0.5, 6);
+ });
+
+ it('takes the shortest arc across ±π', () => {
+ // From just below π to just above -π is a tiny step, not a full spin.
+ const next = dampAngle(Math.PI - 0.1, -Math.PI + 0.1, 0.5);
+ expect(next).toBeGreaterThan(Math.PI - 0.1); // continues past π, not backward
+ expect(next - (Math.PI - 0.1)).toBeCloseTo(0.1, 5);
+ });
+});
+
+describe('moveFacing', () => {
+ it('faces the camera yaw when moving forward', () => {
+ expect(moveFacing(0.3, { forward: 1, strafe: 0 })).toBeCloseTo(0.3, 6);
+ });
+
+ it('quarter-turns for a pure strafe', () => {
+ const right = moveFacing(0, { forward: 0, strafe: 1 });
+ // Strafing right at yaw 0 moves along +X; the character faces +X → θ = -π/2.
+ expect(right).toBeCloseTo(-Math.PI / 2, 6);
+ const left = moveFacing(0, { forward: 0, strafe: -1 });
+ expect(left).toBeCloseTo(Math.PI / 2, 6);
+ });
+
+ it('faces the camera when backpedaling', () => {
+ const back = moveFacing(0, { forward: -1, strafe: 0 });
+ expect(Math.abs(back)).toBeCloseTo(Math.PI, 6);
+ });
+
+ it('keeps the current yaw with no input', () => {
+ expect(moveFacing(0.7, { forward: 0, strafe: 0 })).toBe(0.7);
+ });
+});
+
+describe('avatarState', () => {
+ it('classifies the four states with airborne taking priority', () => {
+ expect(avatarState({ moving: false })).toBe('idle');
+ expect(avatarState({ moving: true })).toBe('walk');
+ expect(avatarState({ moving: true, sprinting: true })).toBe('run');
+ expect(avatarState({ moving: true, sprinting: true, airborne: true })).toBe('hover');
+ });
+});
+
+describe('bankAngle', () => {
+ it('leans opposite the yaw rate and clamps', () => {
+ expect(bankAngle(1)).toBeLessThan(0);
+ expect(bankAngle(-1)).toBeGreaterThan(0);
+ expect(bankAngle(100)).toBe(-0.25);
+ expect(bankAngle(-100)).toBe(0.25);
+ expect(bankAngle(0)).toBeCloseTo(0, 10);
+ });
+});
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 17c132b25d..ed8b18bded 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -53,6 +53,7 @@ export * from './cityMemoryDistrict.js';
export * from './cityMiniMap.js';
export * from './cityPhotoMode.js';
export * from './cityPlan.js';
+export * from './cityPlayerRig.js';
export * from './cityRooftops.js';
export * from './cityProductivity.js';
export * from './citySeasonalDecor.js';