Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(verse): first-person arms cut from the commander's own skinned body (#918)

Ruben Lütkef80c2138c37f
diff --git a/docs/verse/realtime.md b/docs/verse/realtime.md
index d3f1740969..6df97be432 100644
--- a/docs/verse/realtime.md
+++ b/docs/verse/realtime.md
@@ -263,19 +263,30 @@ mid-thigh up, the room at eye level in depth.
### First-person viewmodel
-In first person the commander sees their own arms: gloved hands at the
-bottom of the frame on the deck, and in a duel fought through the eyes the
-blaster in the right hand with the left supporting it. Code:
+In first person the commander sees their own arms, cut from their own body
+with its real skin weights: gloved hands at the bottom of the frame on the
+deck, and in a duel fought through the eyes the blaster in the right hand
+with the left supporting it. Code:
`src/components/society/verse/viewmodel/`.
| File | Role |
|---|---|
| `motion.ts` | Pure: who is drawn (`viewmodelVisibility`: arms in exactly where the third-person body goes out, past 30 % of the blend; the body also goes when a wall pushes the shoulder camera within 0.55 m), the walk bob (a dip per footfall, a sway per stride, scaled by ground speed / walk speed up to 1.7), idle breathing, look lag (the arms trail a turn by up to 0.07 rad and settle in ~0.1 s) and the recoil spring (a shot kicks the blaster back ~2 cm and the muzzle up ~2.5°, settling in ~0.25 s). prefers-reduced-motion drops bob, sway and lag and halves the recoil. |
-| `arms.ts` | The arms, procedural: sleeves in the commander's uniform colour (the rank tier's `M_Uniform`), a gauntleted glove (rounded palm, armoured knuckle plate, a panel in the uniform's trim, two-segment lathe-turned fingers and thumb), a hand pose (`HandPose`: the three outer fingers, the index finger and the thumb apart, so the right index rests on the trigger), two-bone IK from shoulder to wrist (`solveElbow`), the forearm turned so its back follows the back of the hand. The left forearm carries the shield emitter. |
-| `viewmodel.ts` | The rig, its own scene and camera, posed every frame in the camera's space; the layout (`VIEWMODEL`: poses, holds, hand poses, shoulders, field of view, light). |
-| `rigMesh.ts` | One draw for the whole rig: `RigBuilder` bakes every part into one skinned geometry on its bone, `RigPalette` holds every surface as a texel of three float textures under one material; `chamferBox` (44 triangles). |
+| `armMesh.ts` | The arms cut from the commander's own body (`cutArms`): the officer the deck and the duel draw for them (`SK_Officer_M`/`_F`, chosen by id), every triangle hanging at least half on an arm bone (upper arm to fingertips: sleeve, cuff, hand) with its painted atlas UVs, baked occlusion and the body's own skin weights. The shared skeleton has one bone for the four fingers and one for the thumb, so the cut re-rigs the hand from its geometry: finger vertices are sorted into index, middle, ring and little finger across the hand (1-D k-means), each finger's axis and length are measured, and the finger bone's weight is shared out along three phalanges (joints at 47 % and 75 % of the finger, blended over ±6.5 %), the thumb's along three bones of its own. The forearm gets a twist bone (its weight runs from the elbow's hinge to the wrist's twist), so turning the hand over rolls the forearm as a radius does. 19 bones per arm. |
+| `arms.ts` | One arm's bones (`ViewArm`): two-bone IK from shoulder to wrist with the body's own lengths (`solveElbow`; a wrist out of reach draws the shoulder after it, never the hand off the sleeve), the forearm's hinge in the elbow's plane and its twist following the back of the hand, and a hand pose (`HandPose`: the three outer fingers, the index finger and the thumb apart; each finger curls through all three joints, the end joint following the middle one). |
+| `viewmodel.ts` | The rig, its own scene and camera, posed every frame in the camera's space; the layout (`VIEWMODEL`: poses, holds, hand poses, gloves, shoulders, field of view, light). Holds say where the held part sits in the hand's frame; `solveHolds` closes the hands on the blaster by searching each hold's knuckle and middle joints so every finger's joints and tip rest a finger's thickness off the grip (a raked box) or the shroud (a cylinder), and rests the right index finger's pad on the trigger. |
+| `rigMesh.ts` | The blaster and the shield emitter as one skinned mesh: `RigBuilder` bakes every part into one geometry on its bone, `RigPalette` holds every surface as a texel of three float textures under one material; `chamferBox` (44 triangles). |
| `viewmodelPass.ts` | The draw: a pass in the eye view's post chain after the deck's render pass, into the same multisampled HDR target with depth cleared first (so the arms get the deck's anti-aliasing, bloom and AgX and never meet a wall); on the low tier the same draw straight to the screen. No full-screen pass of its own. |
-| `ViewmodelLayer.tsx` | Mounts the viewmodel on a stage with an eye-level view (`runtime.viewmodel`) and tells it each frame what to show: the deck's hands, the duel's blaster, or nothing. |
+| `ViewmodelLayer.tsx` | Mounts the viewmodel on a stage with an eye-level view (`runtime.viewmodel`), cuts the arms from the commander's body once the character library has it (`attachArms`; until then only the blaster shows), and tells it each frame what to show: the deck's hands, the duel's blaster, or nothing. |
+
+The arms wear the body's atlas under one material: the material colours
+multiply into the vertex colours over the baked occlusion (the sleeves in the
+rank tier's `M_Uniform`, repainted on a promotion; the cuff's trim band in
+the same cloth, because a hand's breadth from the eye its sawtooth edge
+would show as a change of tone, and lifted 1.8 mm off the sleeve it cuts
+through). The officer's bare hands are gloved (`VIEWMODEL.gloves`, dark
+leather multiplied into the hands' painted atlas, so knuckles and tendons
+keep their relief; `null` shows the skin).
The viewmodel camera takes the eye camera's orientation but sits at the
origin with its own near plane (1 cm) and a fixed horizontal field of view
@@ -301,20 +312,24 @@ dodge dips the arms. Each shot kicks the recoil spring and flashes at the
muzzle (a sprite and a short light on the hands); the world's own muzzle
flash and vent steam for the person are skipped in first person.
-Budget: both arms and the blaster are one skinned mesh (`rigMesh.ts`): every
-rigid part is baked into one geometry with each vertex bound at full weight
-to the bone it moves with (sleeves, forearm, gauntlet, hand, each finger
-segment, the blaster), and every surface is a texel of a small float palette
-(albedo, roughness and metalness, emission) under one material. The
-blaster's glowing parts copy its heat colours into the palette each frame;
-on the deck its vertices collapse to a point. That is one draw on the deck
-and two or three in a duel (the rig, the sight's reticle, the muzzle flash),
-about 2,900 triangles (chamfered boxes are 44 triangles each). The rig test
-holds it to 3 draws and 3,000 triangles.
+Budget: both arms are one skinned mesh under one material (about 3,070
+triangles from the officer body); the blaster and the shield emitter are a
+second (`rigMesh.ts`: every rigid part baked into one geometry at full weight
+on its bone, every surface a texel of a small float palette; about 1,100
+triangles). The blaster's glowing parts copy its heat colours into the
+palette each frame; on the deck its vertices collapse to a point. That is two
+draws on the deck and four in a duel (the arms, the blaster, the sight's
+reticle, the muzzle flash), about 4,200 triangles. The rig test holds it to
+4 draws and 6,000 triangles; the cut's tests hold every vertex to four
+normalised weights on its own arm, blended elbows, wrists and knuckles, three
+weighted phalanges per finger and thumb, the fingers sorted across the hand,
+the bind pose reproduced exactly, and a bent elbow with a closed fist that
+neither tears nor collapses a triangle.
Development handle (dev builds only): `window.__verseViewmodel = { layout,
-arm, motion, retune(), viewmodel }` tunes the layout live: change `layout`
-(or `arm`), then `retune()`.
+arm, cut, motion, retune(), viewmodel }` tunes the layout live: change
+`layout` (or `arm`), then `retune()` (it repaints and closes the hands
+again); `cut` takes effect when the arms are next cut.
QA hook (every build): `window.__verseView = { set(view), look(dx, dy),
zoom(factor), state() }` switches views, turns and zooms without a mouse
diff --git a/dodaios/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/dodaios/ui/web/frontend/src/components/layout/Sidebar.test.tsx
index fe4842b190..c4a17a3f1a 100644
--- a/dodaios/ui/web/frontend/src/components/layout/Sidebar.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/layout/Sidebar.test.tsx
@@ -64,18 +64,24 @@ test("IDE rail keeps workspace options and Dodaios Live reachable", () => {
test("IDE sidebar puts Projects first and returns to the normal chat navigation", async () => {
act(() => useEventStore.setState({ activeSection: "agentic-ide" }));
- renderSidebar();
- expect(await screen.findByTestId("ide-project-tree")).toBeDefined();
- // The agents list lives in the IDE's right-hand side panel now.
- expect(screen.queryByTestId("ide-workspace-agents")).toBeNull();
- expect(screen.queryByTestId("sidebar-new-chat")).toBeNull();
- expect(screen.queryByTestId("nav-row-agentic-ide")).toBeNull();
- // No "Back to Jarvis" row: the caption's back arrow leaves the IDE.
- expect(screen.queryByTestId("ide-back-to-jarvis")).toBeNull();
- act(() => useEventStore.setState({ activeSection: "chats" }));
- expect(screen.getByTestId("sidebar-new-chat")).toBeDefined();
- cleanup();
-});
+ try {
+ renderSidebar();
+ // The project tree is a lazy chunk: a cold CI runner can take longer than the default second to load it.
+ expect(await screen.findByTestId("ide-project-tree", undefined, { timeout: 10_000 })).toBeDefined();
+ // The agents list lives in the IDE's right-hand side panel now.
+ expect(screen.queryByTestId("ide-workspace-agents")).toBeNull();
+ expect(screen.queryByTestId("sidebar-new-chat")).toBeNull();
+ expect(screen.queryByTestId("nav-row-agentic-ide")).toBeNull();
+ // No "Back to Jarvis" row: the caption's back arrow leaves the IDE.
+ expect(screen.queryByTestId("ide-back-to-jarvis")).toBeNull();
+ act(() => useEventStore.setState({ activeSection: "chats" }));
+ expect(screen.getByTestId("sidebar-new-chat")).toBeDefined();
+ } finally {
+ // A failure here must not leave the IDE section and its sidebar behind for the next test.
+ cleanup();
+ act(() => useEventStore.setState({ activeSection: "chats" }));
+ }
+}, 20_000);
// The sidebar header avatar must mirror the chosen on-screen display style:
// the ghost mascot ONLY when the user explicitly picked "mascot"; the slim bar
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx
index 45d2893d5b..f6b32617da 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx
@@ -1,18 +1,23 @@
/**
- * Mounts the first-person viewmodel on a stage with an eye-level view: makes
- * the arms in the commander's uniform, hands them to the eye view
- * (`runtime.viewmodel`), and every frame tells them what to show: the deck's
- * empty hands while the commander walks in first person, the blaster while a
- * duel is fought through the eyes, nothing in third person or bird's-eye.
+ * Mounts the first-person viewmodel on a stage with an eye-level view: cuts
+ * the arms from the commander's own body (the officer the deck and the duel
+ * draw for them) once the character library has it, dresses them in the
+ * commander's uniform, hands them to the eye view (`runtime.viewmodel`), and
+ * every frame tells them what to show: the deck's empty hands while the
+ * commander walks in first person, the blaster while a duel is fought
+ * through the eyes, nothing in third person or bird's-eye.
*/
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useFrame } from "@react-three/fiber";
+import type { SkinnedMesh } from "three";
import type { Deck } from "../content/deck";
import type { StageRuntime } from "../runtime";
-import type { CharacterLibrary } from "../actors/characters";
+import { disposeInstance, type CharacterLibrary } from "../actors/characters";
import type { Look } from "../actors/look";
import type { DuelController } from "../duel/duelController";
import { OWN_ACCENT } from "../duel/DuelLayer";
+import { hash32 } from "../life/crew";
+import { CUT, cutArms } from "./armMesh";
import { ARM } from "./arms";
import { MOTION, viewmodelVisibility } from "./motion";
import { Viewmodel, VIEWMODEL, type ArmColours, type ViewmodelFrame } from "./viewmodel";
@@ -39,20 +44,39 @@ export function armColours(library: CharacterLibrary | null, look: Look): ArmCol
export function ViewmodelLayer({ runtime, duel, deck, library, commanderId, commanderLook }: Props) {
const { uniform, trim } = armColours(library, commanderLook);
const vmRef = useRef<Viewmodel | null>(null);
+ const [vm, setVm] = useState<Viewmodel | null>(null);
useEffect(() => {
- const vm = new Viewmodel(FALLBACK, OWN_ACCENT);
- vmRef.current = vm;
- runtime.viewmodel = vm;
+ const made = new Viewmodel(FALLBACK, OWN_ACCENT);
+ vmRef.current = made;
+ runtime.viewmodel = made;
+ setVm(made);
// Development handle: tune the layout live (edit `layout`, then `retune()`).
- if (import.meta.env.DEV) Object.assign(window, { __verseViewmodel: { layout: VIEWMODEL, arm: ARM, motion: MOTION, retune: () => vm.retune(), viewmodel: vm } });
+ if (import.meta.env.DEV) Object.assign(window, { __verseViewmodel: { layout: VIEWMODEL, arm: ARM, cut: CUT, motion: MOTION, retune: () => made.retune(), viewmodel: made } });
return () => {
- if (runtime.viewmodel === vm) runtime.viewmodel = null;
- if (vmRef.current === vm) vmRef.current = null;
- vm.dispose();
+ if (runtime.viewmodel === made) runtime.viewmodel = null;
+ if (vmRef.current === made) vmRef.current = null;
+ made.dispose();
};
}, [runtime]);
+ // The arms are the commander's own: the officer body the deck and the duel draw for them (same choice by id).
+ useEffect(() => {
+ if (!library || !vm) return;
+ const model = library.model("officer", undefined, hash32(commanderId));
+ if (!model) return;
+ let alive = true;
+ library.instantiate(model).then((instance) => {
+ try {
+ if (alive && vmRef.current === vm) vm.attachArms(cutArms(instance.meshes.filter((m): m is SkinnedMesh => (m as SkinnedMesh).isSkinnedMesh)));
+ } catch (error: unknown) {
+ console.warn("Verse first-person arms unavailable", error);
+ }
+ // The cut copied what it needs; the atlas it keeps is shared with the body.
+ disposeInstance(instance);
+ }, (error: unknown) => console.warn("Verse first-person arms unavailable", error));
+ return () => { alive = false; };
+ }, [vm, library, commanderId]);
// The sleeves wear the commander's uniform (a promotion repaints them).
- useEffect(() => { vmRef.current?.setColours({ uniform, trim }); }, [runtime, uniform, trim]);
+ useEffect(() => { vm?.setColours({ uniform, trim }); }, [vm, uniform, trim]);
const frame = useMemo<ViewmodelFrame>(() => ({
visibility: { arms: false, mode: "deck", hideOwnBody: false, raise: 0 },
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armFixture.test-util.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armFixture.test-util.ts
new file mode 100644
index 0000000000..9f7f60b2b4
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armFixture.test-util.ts
@@ -0,0 +1,52 @@
+/**
+ * Test-only: the commander's body (SK_Officer_M.glb) parsed from disk with its
+ * atlas images stripped (jsdom cannot decode them), as the skinned meshes the
+ * arm cut reads.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { SkinnedMesh } from "three";
+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+
+const CHARACTERS = join(__dirname, "../../../../../public/verse/characters");
+
+function stripImages(buf: Buffer): ArrayBuffer {
+ const len = buf.readUInt32LE(12);
+ const json = JSON.parse(buf.subarray(20, 20 + len).toString("utf8"));
+ for (const m of json.materials ?? []) {
+ if (m.pbrMetallicRoughness) {
+ delete m.pbrMetallicRoughness.baseColorTexture;
+ delete m.pbrMetallicRoughness.metallicRoughnessTexture;
+ }
+ delete m.normalTexture;
+ delete m.occlusionTexture;
+ delete m.emissiveTexture;
+ }
+ delete json.textures;
+ delete json.images;
+ delete json.samplers;
+ json.extensionsRequired = (json.extensionsRequired ?? []).filter((e: string) => e !== "EXT_texture_webp");
+ let text = Buffer.from(JSON.stringify(json), "utf8");
+ text = Buffer.concat([text, Buffer.alloc((4 - (text.length % 4)) % 4, 0x20)]);
+ const rest = buf.subarray(20 + len);
+ const head = Buffer.alloc(20);
+ head.writeUInt32LE(0x46546c67, 0);
+ head.writeUInt32LE(2, 4);
+ head.writeUInt32LE(20 + text.length + rest.length, 8);
+ head.writeUInt32LE(text.length, 12);
+ head.writeUInt32LE(0x4e4f534a, 16);
+ const out = Buffer.concat([head, text, rest]);
+ // A buffer of the test's own realm (jsdom's ArrayBuffer is not Node's).
+ const ab = new ArrayBuffer(out.byteLength);
+ new Uint8Array(ab).set(out);
+ return ab;
+}
+
+export async function loadBody(file = "SK_Officer_M.glb"): Promise<SkinnedMesh[]> {
+ const data = stripImages(readFileSync(join(CHARACTERS, file)));
+ const gltf = await new GLTFLoader().parseAsync(data, "");
+ gltf.scene.updateMatrixWorld(true);
+ const meshes: SkinnedMesh[] = [];
+ gltf.scene.traverse((o) => { if ((o as SkinnedMesh).isSkinnedMesh) meshes.push(o as SkinnedMesh); });
+ return meshes;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.test.ts
new file mode 100644
index 0000000000..9a32ec2bd9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.test.ts
@@ -0,0 +1,186 @@
+/**
+ * The first-person arms cut from the commander's body (SK_Officer_M.glb, read
+ * from disk): what the cut keeps, the weights it gives the re-rigged hand and
+ * forearm, and that posing the arm bends the surface smoothly (no torn or
+ * collapsed triangles at the elbow, the wrist or the knuckles).
+ */
+import { beforeAll, describe, expect, it } from "vitest";
+import { Bone, Matrix4, Quaternion, Skeleton, SkinnedMesh, Vector3, type BufferGeometry } from "three";
+import { B_FORE, B_HAND, B_THUMB, B_TWIST, B_UPPER, BONES, cutArms, fingerBone, kMeans1D, type ArmsSource } from "./armMesh";
+import { handPose, ViewArm } from "./arms";
+import { loadBody } from "./armFixture.test-util";
+
+let meshes: Awaited<ReturnType<typeof loadBody>>;
+beforeAll(async () => { meshes = await loadBody(); });
+
+/** Skinned positions of `geometry` for `bones` posed (bind inverses from the cut). */
+function skinned(geometry: BufferGeometry, bones: Bone[], inverses: Matrix4[]): Vector3[] {
+ const mesh = new SkinnedMesh(geometry);
+ for (const b of bones) if (!b.parent) mesh.add(b);
+ mesh.bind(new Skeleton(bones, inverses), new Matrix4());
+ mesh.updateMatrixWorld(true);
+ mesh.skeleton.update();
+ const out: Vector3[] = [];
+ for (let i = 0; i < geometry.getAttribute("position").count; i++) out.push(mesh.getVertexPosition(i, new Vector3()));
+ for (const b of bones) if (b.parent === mesh) mesh.remove(b);
+ return out;
+}
+
+/** The ratio of every edge's posed length to its bind length, worst stretch and worst squash. */
+function edgeRatios(geometry: BufferGeometry, posed: Vector3[]): { max: number; min: number } {
+ const pos = geometry.getAttribute("position");
+ const index = geometry.getIndex();
+ const bind = (i: number) => new Vector3().fromBufferAttribute(pos, i);
+ let max = 0;
+ let min = Infinity;
+ if (!index) return { max, min };
+ for (let t = 0; t < index.count; t += 3) {
+ for (let k = 0; k < 3; k++) {
+ const a = index.getX(t + k);
+ const b = index.getX(t + ((k + 1) % 3));
+ const rest = bind(a).distanceTo(bind(b));
+ if (rest < 1e-4) continue;
+ const r = posed[a].distanceTo(posed[b]) / rest;
+ max = Math.max(max, r);
+ min = Math.min(min, r);
+ }
+ }
+ return { max, min };
+}
+
+describe("arm cut", () => {
+ let src: ArmsSource;
+ beforeAll(() => { src = cutArms(meshes); });
+
+ it("keeps both arms from the upper arm to the fingertips, within the budget", () => {
+ expect(src.triangles).toBeGreaterThan(2000);
+ expect(src.triangles).toBeLessThanOrEqual(4500);
+ // The body's own proportions: an upper arm of ~29 cm and a forearm of ~24 cm.
+ for (const side of [src.right, src.left]) {
+ expect(side.upper).toBeGreaterThan(0.25);
+ expect(side.upper).toBeLessThan(0.34);
+ expect(side.fore).toBeGreaterThan(0.2);
+ expect(side.fore).toBeLessThan(0.3);
+ }
+ // Sleeves, cuffs and hands, all drawn with the body's atlas.
+ const kinds = new Set(src.slots);
+ expect(kinds.size).toBeGreaterThanOrEqual(3);
+ expect(src.geometry.getAttribute("uv")).toBeTruthy();
+ });
+
+ it("gives every vertex at most four normalised weights on its own arm's bones", () => {
+ const si = src.geometry.getAttribute("skinIndex");
+ const sw = src.geometry.getAttribute("skinWeight");
+ const pos = src.geometry.getAttribute("position");
+ for (let i = 0; i < si.count; i++) {
+ let sum = 0;
+ for (let j = 0; j < 4; j++) {
+ const w = sw.getComponent(i, j);
+ sum += w;
+ if (w > 0) {
+ // Right arm bones 0..18 (the character's right is −X), left 19..37.
+ const b = si.getComponent(i, j);
+ expect(b < BONES).toBe(pos.getX(i) < 0);
+ }
+ }
+ expect(sum).toBeCloseTo(1, 5);
+ }
+ });
+
+ it("blends the elbow and the wrist, and splits each finger into three phalanges", () => {
+ const si = src.geometry.getAttribute("skinIndex");
+ const sw = src.geometry.getAttribute("skinWeight");
+ const count = new Map<number, number>();
+ const blended = { elbow: 0, wrist: 0, knuckle: 0 };
+ for (let i = 0; i < si.count; i++) {
+ const bones = new Set<number>();
+ for (let j = 0; j < 4; j++) {
+ if (sw.getComponent(i, j) < 0.05) continue;
+ const b = si.getComponent(i, j) % BONES;
+ bones.add(b);
+ count.set(b, (count.get(b) ?? 0) + 1);
+ }
+ if (bones.has(B_UPPER) && (bones.has(B_FORE) || bones.has(B_TWIST))) blended.elbow++;
+ if (bones.has(B_HAND) && bones.has(B_TWIST)) blended.wrist++;
+ if (bones.has(B_HAND) && [0, 1, 2, 3].some((f) => bones.has(fingerBone(f)))) blended.knuckle++;
+ }
+ expect(blended.elbow).toBeGreaterThan(10);
+ expect(blended.wrist).toBeGreaterThan(10);
+ expect(blended.knuckle).toBeGreaterThan(10);
+ // Every phalanx of every finger, and of the thumb, carries vertices of its own.
+ for (let f = 0; f < 4; f++) for (let j = 0; j < 3; j++) expect(count.get(fingerBone(f) + j) ?? 0).toBeGreaterThan(4);
+ for (let j = 0; j < 3; j++) expect(count.get(B_THUMB + j) ?? 0).toBeGreaterThan(4);
+ });
+
+ it("sorts the fingers across the hand: the index next to the thumb, the little finger outside", () => {
+ for (const side of [src.right, src.left]) {
+ const toHand = side.bind[B_HAND].clone().invert();
+ const across = [0, 1, 2, 3].map((f) => new Vector3().setFromMatrixPosition(side.bind[fingerBone(f)]).applyMatrix4(toHand).x);
+ const thumb = new Vector3().setFromMatrixPosition(side.bind[B_THUMB]).applyMatrix4(toHand).x;
+ // The right hand's thumb is on +X, the left's (mirrored) on −X.
+ const s = side.side === "right" ? 1 : -1;
+ for (let f = 0; f < 3; f++) expect(s * across[f]).toBeGreaterThan(s * across[f + 1]);
+ expect(s * thumb).toBeGreaterThan(s * across[3]);
+ // Fingers 1.5–3.5 cm apart at the knuckles.
+ for (let f = 0; f < 3; f++) {
+ expect(Math.abs(across[f] - across[f + 1])).toBeGreaterThan(0.012);
+ expect(Math.abs(across[f] - across[f + 1])).toBeLessThan(0.035);
+ }
+ }
+ });
+
+ it("clusters values in one dimension", () => {
+ const c = kMeans1D([0, 0.1, 0.2, 1, 1.1, 2, 2.1, 3, 3.2], 4);
+ expect(c).toHaveLength(4);
+ expect(c[0]).toBeCloseTo(3.1, 6);
+ expect(c[3]).toBeCloseTo(0.1, 6);
+ });
+
+ it("bends the elbow, turns the wrist over and closes the fist without tearing the surface", () => {
+ const src2 = cutArms(meshes);
+ const right = new ViewArm(src2.right);
+ const left = new ViewArm(src2.left);
+ const bones = [...right.bones, ...left.bones];
+ const inverses = [...right.inverses(), ...left.inverses()];
+ // A held pose: the elbow bent ~90°, the hand palm-in ahead of the chest, a closed fist.
+ const shoulder = new Vector3(-0.17, 1.41, 0);
+ const wrist = new Vector3(-0.2, 1.2, 0.26);
+ const q = ViewArm.handFrame(new Vector3(0.2, 0.1, 1), new Vector3(-1, 0.3, 0), new Quaternion());
+ right.pose(shoulder, wrist, q, new Vector3(-0.3, -1, -0.4).normalize());
+ right.curl(handPose(1.5, 1.6, 0.9, [1.5, 1.6], 0.4));
+ left.pose(new Vector3(0.17, 1.41, 0), new Vector3(0.2, 0.92, 0.1), ViewArm.handFrame(new Vector3(0, -1, 0.1), new Vector3(1, 0, 0), new Quaternion()), new Vector3(0.3, -0.2, -1).normalize());
+ left.curl(handPose(0.3, 0.3, 0.2));
+ for (const g of [right.group, left.group]) g.updateMatrixWorld(true);
+ const posed = skinned(src2.geometry, bones, inverses);
+ const { max, min } = edgeRatios(src2.geometry, posed);
+ // A fist stretches the skin over the knuckles about twofold and folds the palm side; a vertex hung on the wrong
+ // finger, or a joint without a blend, would tear its triangles far wider or collapse them to a point.
+ expect(max).toBeLessThan(2.5);
+ expect(min).toBeGreaterThan(0.03);
+ // The hand ends at the wrist (the sleeve never parts from the glove).
+ expect(right.hand.position.distanceTo(wrist)).toBeLessThan(1e-9);
+ src2.geometry.dispose();
+ });
+
+ it("keeps the bind pose exactly when the bones sit at their bind frames", () => {
+ const src3 = cutArms(meshes);
+ const arm = new ViewArm(src3.right);
+ const other = new ViewArm(src3.left);
+ const bones = [...arm.bones, ...other.bones];
+ for (const [i, b] of bones.entries()) {
+ const side = i < BONES ? src3.right : src3.left;
+ if (b.parent && b.parent !== arm.group && b.parent !== other.group) continue;
+ side.bind[i % BONES].decompose(b.position, b.quaternion, b.scale);
+ }
+ // Chain bones keep their rest placement when uncurled.
+ arm.curl(handPose(0, 0, 0));
+ other.curl(handPose(0, 0, 0));
+ for (const g of [arm.group, other.group]) g.updateMatrixWorld(true);
+ const posed = skinned(src3.geometry, bones, [...arm.inverses(), ...other.inverses()]);
+ const pos = src3.geometry.getAttribute("position");
+ let worst = 0;
+ for (let i = 0; i < pos.count; i++) worst = Math.max(worst, posed[i].distanceTo(new Vector3().fromBufferAttribute(pos, i)));
+ expect(worst).toBeLessThan(1e-4);
+ src3.geometry.dispose();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.ts
new file mode 100644
index 0000000000..89580d996e
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/armMesh.ts
@@ -0,0 +1,518 @@
+/**
+ * The first-person arms cut from the commander's own body (docs/verse/realtime.md,
+ * "First-person viewmodel"): the triangles of the character's skinned mesh
+ * that hang on the arm bones (upper arm down to the fingertips), with their
+ * painted atlas, their baked ambient occlusion and their real skin weights,
+ * so elbows, wrists and knuckles bend the surface the way the body's do.
+ *
+ * The shared character skeleton has one bone for the four fingers and one for
+ * the thumb. The cut re-rigs the hand from its own geometry: the finger
+ * vertices are sorted into index, middle, ring and little finger by where
+ * they sit across the hand, each finger's axis and length are measured, and
+ * the finger bone's weight is shared out along three phalanges (and the
+ * thumb's along three bones of its own), blended over a few millimetres at
+ * each knuckle. The forearm gets a twist bone: the weight of the forearm runs
+ * from its hinge at the elbow to its twist at the wrist, so turning the hand
+ * over rolls the forearm as a radius does instead of wringing the elbow.
+ *
+ * Both arms come out as one indexed geometry whose bind space is the
+ * character's model space (metres, Y up, facing +Z) and one bone list per
+ * arm with its bind frames (`ArmRig`). The material colours (uniform, trim,
+ * skin) are multiplied into the vertex colours over the baked occlusion, so
+ * one material with the character's atlas draws everything: one draw call.
+ *
+ * Bone frames (bind and posed alike):
+ * - upper arm and forearm hinge: origin at the joint, +Y along the bone, +Z
+ * toward the point of the elbow (backward at rest);
+ * - forearm twist: origin at the elbow, +Y along the forearm, +Z toward the
+ * back of the hand;
+ * - hand: origin at the wrist, +Z to the knuckles, +Y the back of the hand,
+ * +X = Y × Z (the thumb's side on the right hand, the little finger's on
+ * the left: the left hand is the right one mirrored);
+ * - finger and thumb bones: origin at the joint, +Z along the finger, a
+ * positive turn about +X curls it toward the palm.
+ */
+import { BufferAttribute, BufferGeometry, Color, Matrix4, Vector3, type Material, type MeshStandardMaterial, type SkinnedMesh, type Texture } from "three";
+
+export type Side = "right" | "left";
+
+/** One arm's bones in bind space (model metres): where its joints are and how its bones are turned. */
+export interface ArmRig {
+ side: Side;
+ /** Joint positions at rest. */
+ shoulder: Vector3;
+ elbow: Vector3;
+ wrist: Vector3;
+ /** Bone lengths: shoulder to elbow, elbow to wrist. */
+ upper: number;
+ fore: number;
+ /** Bind frames (world = model space at rest) of the arm's bones, in `BONES` order. */
+ bind: Matrix4[];
+ /** Landmarks in the hand's bind frame: the knuckle line's middle on the back of the hand, the index finger's pad. */
+ knuckles: Vector3;
+ indexTip: Vector3;
+ /** Each finger's tip (index .. little), in its end bone's bind frame. */
+ tips: Vector3[];
+ /** Where on the forearm's back the shield emitter sits: share of the forearm from the elbow, height over its axis. */
+ emitterAt: number;
+ emitterLift: number;
+ /** The forearm's radius at the wrist (the cuff), metres. */
+ wristRadius: number;
+}
+
+/** Bones per arm, in order: upper arm, forearm hinge, forearm twist, hand, four fingers × three, thumb × three. */
+export const BONES = 19;
+export const B_UPPER = 0;
+export const B_FORE = 1;
+export const B_TWIST = 2;
+export const B_HAND = 3;
+/** First bone of finger `f` (0 index .. 3 little); its phalanges follow. */
+export const fingerBone = (f: number): number => 4 + f * 3;
+export const B_THUMB = 16;
+
+/** Material slots of the cut: their authored colours, unless the look repaints them. */
+export type ArmSlot = "uniform" | "trim" | "skin" | "other";
+
+export interface ArmsSource {
+ geometry: BufferGeometry;
+ right: ArmRig;
+ left: ArmRig;
+ /** The character's atlas (shared with the body: never disposed here). */
+ map: Texture | null;
+ normalMap: Texture | null;
+ roughnessMap: Texture | null;
+ normalScale: [number, number];
+ /** Per vertex: the baked occlusion (linear) and the slot whose colour multiplies it. */
+ occlusion: Float32Array;
+ slots: Uint8Array;
+ /** The authored colours of the slots (linear), before the look. */
+ authored: Record<ArmSlot, Color>;
+ /** The cut's triangles. */
+ triangles: number;
+}
+
+/** The layout of the cut: phalanx joints as shares of a finger's length from its knuckle, and blend widths. */
+export const CUT = {
+ /** A triangle stays when every corner hangs this much or more on its arm's bones. */
+ armWeight: 0.5,
+ /** Finger joints (PIP, DIP) as shares of the finger from the knuckle (MCP) to its tip. */
+ fingerJoints: [0.47, 0.75] as [number, number],
+ /** Thumb joints (MCP, IP) as shares from the thumb bone's root to its tip. */
+ thumbJoints: [0.42, 0.72] as [number, number],
+ /** Half-width of the blend across a finger joint, as a share of the finger. */
+ blend: 0.065,
+ /** The forearm's twist weight ramps in over this span of the forearm (shares from the elbow). */
+ twist: [0.2, 0.95] as [number, number],
+ /**
+ * The cuffs' trim band covers the sleeve's ragged end; its own edge toward the elbow is a sawtooth (unseen at the
+ * deck camera's distance, plain a hand's breadth from the eye). It is lifted off the cloth along its normals,
+ * metres, and the viewmodel paints it in the uniform's cloth so the sawtooth never shows as a change of tone.
+ */
+ trimLift: 0.0018,
+ /** The shield emitter's seat: share of the forearm from the elbow. */
+ emitterAt: 0.66,
+};
+
+const SLOT_CODES: ArmSlot[] = ["uniform", "trim", "skin", "other"];
+
+function slotOf(name: string): ArmSlot {
+ if (name === "M_Uniform" || name === "M_Undersuit") return "uniform";
+ if (name === "M_Trim") return "trim";
+ if (name === "M_Skin" || name === "M_Gloves") return "skin";
+ return "other";
+}
+
+function smoothstep(a: number, b: number, v: number): number {
+ const t = Math.min(1, Math.max(0, (v - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+}
+
+const SUFFIX: Record<Side, string> = { right: "_R", left: "_L" };
+const ARM_BONES = ["UpperArm", "ForeArm", "Hand", "Fingers", "Thumb"] as const;
+
+/** The bind frame with origin `o` and axes `x`, `y`, `z` (orthonormal). */
+function frame(o: Vector3, x: Vector3, y: Vector3, z: Vector3): Matrix4 {
+ return new Matrix4().makeBasis(x, y, z).setPosition(o);
+}
+
+/** A frame from its +Y axis and a hint for +Z (made perpendicular): X = Y × Z. */
+function frameYZ(o: Vector3, y: Vector3, zHint: Vector3): Matrix4 {
+ const Y = y.clone().normalize();
+ const Z = zHint.clone().addScaledVector(Y, -zHint.dot(Y)).normalize();
+ return frame(o, new Vector3().crossVectors(Y, Z), Y, Z);
+}
+
+/** A frame from its +Z axis and a hint for +Y (made perpendicular): X = Y × Z. */
+function frameZY(o: Vector3, z: Vector3, yHint: Vector3): Matrix4 {
+ const Z = z.clone().normalize();
+ const Y = yHint.clone().addScaledVector(Z, -yHint.dot(Z)).normalize();
+ return frame(o, new Vector3().crossVectors(Y, Z), Y, Z);
+}
+
+/** The principal direction of a point cloud (power iteration on its covariance). */
+function principal(points: Vector3[], hint: Vector3): Vector3 {
+ const c = new Vector3();
+ for (const p of points) c.add(p);
+ c.multiplyScalar(1 / Math.max(1, points.length));
+ const m = [0, 0, 0, 0, 0, 0];
+ for (const p of points) {
+ const x = p.x - c.x, y = p.y - c.y, z = p.z - c.z;
+ m[0] += x * x; m[1] += x * y; m[2] += x * z; m[3] += y * y; m[4] += y * z; m[5] += z * z;
+ }
+ const v = hint.clone().normalize();
+ for (let i = 0; i < 32; i++) {
+ const nx = m[0] * v.x + m[1] * v.y + m[2] * v.z;
+ const ny = m[1] * v.x + m[3] * v.y + m[4] * v.z;
+ const nz = m[2] * v.x + m[4] * v.y + m[5] * v.z;
+ v.set(nx, ny, nz);
+ const l = v.length();
+ if (l < 1e-12) return hint.clone().normalize();
+ v.multiplyScalar(1 / l);
+ }
+ return v.dot(hint) < 0 ? v.negate() : v;
+}
+
+/** 1-D k-means of `values` into `k` clusters (seeded at evenly spaced quantiles); the cluster centres, sorted descending. */
+export function kMeans1D(values: number[], k: number): number[] {
+ const sorted = [...values].sort((a, b) => a - b);
+ if (!sorted.length) return [];
+ const centres = Array.from({ length: k }, (_, i) => sorted[Math.min(sorted.length - 1, Math.floor(((i + 0.5) / k) * sorted.length))]);
+ for (let iter = 0; iter < 40; iter++) {
+ const sum = new Array(k).fill(0);
+ const n = new Array(k).fill(0);
+ for (const v of sorted) {
+ let best = 0;
+ for (let j = 1; j < k; j++) if (Math.abs(v - centres[j]) < Math.abs(v - centres[best])) best = j;
+ sum[best] += v;
+ n[best]++;
+ }
+ let moved = 0;
+ for (let j = 0; j < k; j++) {
+ if (!n[j]) continue;
+ const c = sum[j] / n[j];
+ moved = Math.max(moved, Math.abs(c - centres[j]));
+ centres[j] = c;
+ }
+ if (moved < 1e-7) break;
+ }
+ return centres.sort((a, b) => b - a);
+}
+
+interface SourceVertex {
+ p: Vector3;
+ n: Vector3;
+ uv: [number, number];
+ ao: number;
+ slot: number;
+ /** Weights by source bone name. */
+ w: Map<string, number>;
+}
+
+interface Finger { base: Vector3; dir: Vector3; length: number }
+
+/**
+ * Cut both arms out of a character's skinned meshes (the commander's body, in its bind pose). Throws when the body
+ * lacks the arm bones or the cut comes out empty.
+ */
+export function cutArms(meshes: readonly SkinnedMesh[]): ArmsSource {
+ const verts: SourceVertex[] = [];
+ const tris: number[] = [];
+ const sideOf: Side[] = [];
+ let atlas: MeshStandardMaterial | null = null;
+ const authored: Record<ArmSlot, Color> = { uniform: new Color(0.1, 0.1, 0.1), trim: new Color(0.08, 0.08, 0.08), skin: new Color(0.62, 0.38, 0.27), other: new Color(0.2, 0.2, 0.2) };
+ const boneBind = new Map<string, Matrix4>();
+ const normalM = new Matrix4();
+
+ for (const mesh of meshes) {
+ if (!mesh.isSkinnedMesh) continue;
+ const material = (Array.isArray(mesh.material) ? mesh.material[0] : mesh.material) as Material;
+ const std = material as MeshStandardMaterial;
+ const slot = slotOf(material.name);
+ const geo = mesh.geometry;
+ const pos = geo.getAttribute("position");
+ const nor = geo.getAttribute("normal");
+ const uv = geo.getAttribute("uv");
+ const col = geo.getAttribute("color");
+ const si = geo.getAttribute("skinIndex");
+ const sw = geo.getAttribute("skinWeight");
+ if (!pos || !si || !sw) continue;
+ const bones = mesh.skeleton.bones;
+ const names = bones.map((b) => b.name);
+ for (let i = 0; i < bones.length; i++) {
+ if (!boneBind.has(names[i])) boneBind.set(names[i], mesh.skeleton.boneInverses[i].clone().invert());
+ }
+ // Which side each vertex hangs on, and how much of it hangs on that arm.
+ const armOf = (v: number): { side: Side; weight: number } => {
+ let r = 0;
+ let l = 0;
+ for (let j = 0; j < 4; j++) {
+ const w = sw.getComponent(v, j);
+ if (w <= 0) continue;
+ const name = names[si.getComponent(v, j)];
+ for (const b of ARM_BONES) {
+ if (name === b + "_R") r += w;
+ else if (name === b + "_L") l += w;
+ }
+ }
+ return r >= l ? { side: "right", weight: r } : { side: "left", weight: l };
+ };
+ const index = geo.index;
+ const count = index ? index.count : pos.count;
+ const map = new Map<number, number>();
+ normalM.copy(mesh.bindMatrix);
+ for (let t = 0; t + 2 < count; t += 3) {
+ const corners = [0, 1, 2].map((k) => (index ? index.getX(t + k) : t + k));
+ const arms = corners.map(armOf);
+ if (slot === "other" || arms.some((a) => a.weight < CUT.armWeight || a.side !== arms[0].side)) continue;
+ // Every material of a character samples the same atlas: any of them lends it.
+ if (!atlas?.map && std.map) atlas = std;
+ for (const c of corners) {
+ let id = map.get(c);
+ if (id === undefined) {
+ id = verts.length;
+ map.set(c, id);
+ const w = new Map<string, number>();
+ for (let j = 0; j < 4; j++) {
+ const x = sw.getComponent(c, j);
+ if (x > 0) {
+ const name = names[si.getComponent(c, j)];
+ w.set(name, (w.get(name) ?? 0) + x);
+ }
+ }
+ verts.push({
+ p: new Vector3().fromBufferAttribute(pos, c).applyMatrix4(mesh.bindMatrix),
+ n: nor ? new Vector3().fromBufferAttribute(nor, c).transformDirection(normalM) : new Vector3(0, 1, 0),
+ uv: uv ? [uv.getX(c), uv.getY(c)] : [0, 0],
+ // The baked occlusion lives in the colour's red (grey: every channel the same).
+ ao: col ? col.getX(c) : 1,
+ slot: SLOT_CODES.indexOf(slot),
+ w,
+ });
+ }
+ tris.push(id);
+ }
+ sideOf.push(arms[0].side);
+ }
+ if (slot !== "other" && std.color) authored[slot].copy(std.color);
+ atlas ??= slot !== "other" ? std : null;
+ }
+ if (!tris.length) throw new Error("arm cut: no triangles hang on the arm bones");
+
+ const sides: Record<Side, ArmRig> = {
+ right: rigSide("right", verts, tris, sideOf, boneBind),
+ left: rigSide("left", verts, tris, sideOf, boneBind),
+ };
+
+ // The geometry: one bone list for both arms (right 0..18, left 19..37).
+ const n = verts.length;
+ const position = new Float32Array(n * 3);
+ const normal = new Float32Array(n * 3);
+ const uvs = new Float32Array(n * 2);
+ const occlusion = new Float32Array(n);
+ const slots = new Uint8Array(n);
+ const skinIndex = new Uint16Array(n * 4);
+ const skinWeight = new Float32Array(n * 4);
+ const vertSide = new Array<Side | null>(n).fill(null);
+ for (let t = 0; t < tris.length; t += 3) for (let k = 0; k < 3; k++) vertSide[tris[t + k]] = sideOf[t / 3];
+ const weights = new Map<Side, (v: SourceVertex) => Map<number, number>>([
+ ["right", (sides.right as RigWithWeights).weigh],
+ ["left", (sides.left as RigWithWeights).weigh],
+ ]);
+ for (let i = 0; i < n; i++) {
+ const v = verts[i];
+ if (SLOT_CODES[v.slot] === "trim") v.p.addScaledVector(v.n, CUT.trimLift);
+ position.set([v.p.x, v.p.y, v.p.z], i * 3);
+ normal.set([v.n.x, v.n.y, v.n.z], i * 3);
+ uvs.set(v.uv, i * 2);
+ occlusion[i] = v.ao;
+ slots[i] = v.slot;
+ const side = vertSide[i] ?? "right";
+ const offset = side === "right" ? 0 : BONES;
+ const w = [...(weights.get(side) as (v: SourceVertex) => Map<number, number>)(v).entries()].sort((a, b) => b[1] - a[1]).slice(0, 4);
+ const total = w.reduce((s, [, x]) => s + x, 0) || 1;
+ for (let j = 0; j < w.length; j++) {
+ skinIndex[i * 4 + j] = w[j][0] + offset;
+ skinWeight[i * 4 + j] = w[j][1] / total;
+ }
+ }
+ const geometry = new BufferGeometry();
+ geometry.name = "ViewmodelArms";
+ geometry.setAttribute("position", new BufferAttribute(position, 3));
+ geometry.setAttribute("normal", new BufferAttribute(normal, 3));
+ geometry.setAttribute("uv", new BufferAttribute(uvs, 2));
+ geometry.setAttribute("color", new BufferAttribute(new Float32Array(n * 3), 3));
+ geometry.setAttribute("skinIndex", new BufferAttribute(skinIndex, 4));
+ geometry.setAttribute("skinWeight", new BufferAttribute(skinWeight, 4));
+ geometry.setIndex(n > 65535 ? new BufferAttribute(new Uint32Array(tris), 1) : new BufferAttribute(new Uint16Array(tris), 1));
+ const ns = atlas?.normalScale;
+ return {
+ geometry,
+ right: sides.right,
+ left: sides.left,
+ map: atlas?.map ?? null,
+ normalMap: atlas?.normalMap ?? null,
+ roughnessMap: atlas?.roughnessMap ?? null,
+ normalScale: ns ? [ns.x, ns.y] : [1, 1],
+ occlusion,
+ slots,
+ authored,
+ triangles: tris.length / 3,
+ };
+}
+
+interface RigWithWeights extends ArmRig {
+ weigh: (v: SourceVertex) => Map<number, number>;
+}
+
+/** One arm: its joints and bind frames, and how a vertex's source weights map onto its bones. */
+function rigSide(side: Side, verts: SourceVertex[], tris: number[], sideOf: Side[], boneBind: Map<string, Matrix4>): RigWithWeights {
+ const sfx = SUFFIX[side];
+ const at = (name: string): Vector3 => {
+ const m = boneBind.get(name + sfx);
+ if (!m) throw new Error(`arm cut: the body has no bone ${name}${sfx}`);
+ return new Vector3().setFromMatrixPosition(m);
+ };
+ const shoulder = at("UpperArm");
+ const elbow = at("ForeArm");
+ const wrist = at("Hand");
+ const knuckle = at("Fingers");
+ const thumbRoot = at("Thumb");
+ const mine = new Set<number>();
+ for (let t = 0; t < tris.length; t += 3) if (sideOf[t / 3] === side) for (let k = 0; k < 3; k++) mine.add(tris[t + k]);
+ const pts = (bone: string, min = 0.5) => [...mine].filter((i) => (verts[i].w.get(bone + sfx) ?? 0) >= min).map((i) => verts[i].p);
+
+ // The hand's frame: knuckles from the wrist; across the hand from the spread of the fingers; the thumb's side.
+ const z = knuckle.clone().sub(wrist).normalize();
+ const fingerPts = pts("Fingers");
+ const thumbPts = pts("Thumb");
+ if (fingerPts.length < 16 || thumbPts.length < 4) throw new Error(`arm cut: the ${side} hand has too few finger vertices`);
+ const flat = fingerPts.map((p) => p.clone().sub(knuckle).addScaledVector(z, -p.clone().sub(knuckle).dot(z)));
+ const thumbC = thumbPts.reduce((s, p) => s.add(p), new Vector3()).multiplyScalar(1 / thumbPts.length);
+ const thumbSide = thumbC.clone().sub(wrist);
+ thumbSide.addScaledVector(z, -thumbSide.dot(z));
+ const across = principal(flat, thumbSide);
+ const X = side === "right" ? across.clone() : across.clone().negate();
+ const Y = new Vector3().crossVectors(z, X).normalize();
+ X.crossVectors(Y, z).normalize();
+ const handBind = frame(wrist, X, Y, z);
+
+ // Fingers: sorted across the hand (index on the thumb's side), each with its own axis and length.
+ const lateral = (p: Vector3) => p.clone().sub(knuckle).dot(across);
+ const along = (p: Vector3) => p.clone().sub(knuckle).dot(z);
+ const beyond = fingerPts.filter((p) => along(p) > 0.012);
+ const centres = kMeans1D(beyond.map(lateral), 4);
+ const fingerOf = (p: Vector3): number => {
+ const l = lateral(p);
+ let best = 0;
+ for (let j = 1; j < centres.length; j++) if (Math.abs(l - centres[j]) < Math.abs(l - centres[best])) best = j;
+ return best;
+ };
+ const fingers: Finger[] = [];
+ for (let f = 0; f < 4; f++) {
+ const own = beyond.filter((p) => fingerOf(p) === f);
+ const c = own.reduce((s, p) => s.add(p), new Vector3()).multiplyScalar(1 / Math.max(1, own.length));
+ const dir = principal(own, z);
+ // The knuckle joint: where the finger's axis crosses the knuckle plane.
+ const k = knuckle.clone().sub(c).dot(z) / Math.max(0.2, dir.dot(z));
+ const base = c.clone().addScaledVector(dir, k);
+ let length = 0;
+ for (const p of own) length = Math.max(length, p.clone().sub(base).dot(dir));
+ fingers.push({ base, dir, length: Math.max(0.03, length) });
+ }
+
+ // The thumb: from its bone's root to its farthest point.
+ let thumbTip = thumbRoot.clone();
+ for (const p of thumbPts) if (p.distanceToSquared(thumbRoot) > thumbTip.distanceToSquared(thumbRoot)) thumbTip = p;
+ const thumbDir = principal(thumbPts, thumbTip.clone().sub(thumbRoot));
+ let thumbLength = 0;
+ for (const p of thumbPts) thumbLength = Math.max(thumbLength, p.clone().sub(thumbRoot).dot(thumbDir));
+ thumbLength = Math.max(0.03, thumbLength);
+ // The thumb flexes toward the palm's middle (below the middle finger's root).
+ const palm = fingers[1].base.clone().lerp(wrist, 0.5).addScaledVector(Y, -0.02);
+ const thumbFlex = palm.sub(thumbRoot);
+ const thumbBack = thumbFlex.addScaledVector(thumbDir, -thumbFlex.dot(thumbDir)).normalize().negate();
+
+ // Bind frames. Elbows point backward at rest (the character faces +Z).
+ const back = new Vector3(0, 0, -1);
+ const bind: Matrix4[] = new Array(BONES);
+ bind[B_UPPER] = frameYZ(shoulder, elbow.clone().sub(shoulder), back);
+ bind[B_FORE] = frameYZ(elbow, wrist.clone().sub(elbow), back);
+ bind[B_TWIST] = frameYZ(elbow, wrist.clone().sub(elbow), Y);
+ bind[B_HAND] = handBind;
+ for (let f = 0; f < 4; f++) {
+ const { base, dir, length } = fingers[f];
+ const joints = [0, CUT.fingerJoints[0], CUT.fingerJoints[1]];
+ for (let j = 0; j < 3; j++) bind[fingerBone(f) + j] = frameZY(base.clone().addScaledVector(dir, joints[j] * length), dir, Y);
+ }
+ const tj = [0, CUT.thumbJoints[0], CUT.thumbJoints[1]];
+ for (let j = 0; j < 3; j++) bind[B_THUMB + j] = frameZY(thumbRoot.clone().addScaledVector(thumbDir, tj[j] * thumbLength), thumbDir, thumbBack);
+
+ // Landmarks in the hand's frame.
+ const toHand = handBind.clone().invert();
+ const knuckles = fingers[1].base.clone().lerp(fingers[2].base, 0.5).addScaledVector(Y, 0.012).applyMatrix4(toHand);
+ const idx = fingers[0];
+ const indexTip = idx.base.clone().addScaledVector(idx.dir, idx.length - 0.008).addScaledVector(Y, -0.006).applyMatrix4(toHand);
+ const tips = fingers.map((f, i) => f.base.clone().addScaledVector(f.dir, f.length - 0.005).applyMatrix4(bind[fingerBone(i) + 2].clone().invert()));
+
+ // The forearm's back for the emitter: how far the sleeve stands off the axis toward the back of the hand.
+ const foreAxis = wrist.clone().sub(elbow);
+ const foreLength = foreAxis.length();
+ foreAxis.multiplyScalar(1 / foreLength);
+ const twistZ = new Vector3().setFromMatrixColumn(bind[B_TWIST], 2);
+ const emitterAt = CUT.emitterAt;
+ let lift = 0.03;
+ let wristRadius = 0.03;
+ for (const i of mine) {
+ const v = verts[i];
+ const d = v.p.clone().sub(elbow);
+ const t = d.dot(foreAxis) / foreLength;
+ const radial = d.addScaledVector(foreAxis, -d.dot(foreAxis));
+ if (Math.abs(t - emitterAt) < 0.08) lift = Math.max(lift, radial.dot(twistZ));
+ if (Math.abs(t - 0.97) < 0.05) wristRadius = Math.max(wristRadius, radial.length());
+ }
+
+ const weigh = (v: SourceVertex): Map<number, number> => {
+ const out = new Map<number, number>();
+ const add = (bone: number, w: number) => { if (w > 0) out.set(bone, (out.get(bone) ?? 0) + w); };
+ for (const [name, w] of v.w) {
+ if (name === "ForeArm" + sfx) {
+ // The forearm's weight runs from its hinge at the elbow to its twist at the wrist.
+ const t = v.p.clone().sub(elbow).dot(foreAxis) / foreLength;
+ const s = smoothstep(CUT.twist[0], CUT.twist[1], t);
+ add(B_FORE, w * (1 - s));
+ add(B_TWIST, w * s);
+ } else if (name === "Hand" + sfx) {
+ add(B_HAND, w);
+ } else if (name === "Fingers" + sfx) {
+ const f = fingerOf(v.p);
+ const { base, dir, length } = fingers[f];
+ const u = v.p.clone().sub(base).dot(dir) / length;
+ const [j1, j2] = CUT.fingerJoints;
+ const h = CUT.blend;
+ const s2 = smoothstep(j1 - h, j1 + h, u);
+ const s3 = smoothstep(j2 - h, j2 + h, u);
+ add(fingerBone(f), w * (1 - s2));
+ add(fingerBone(f) + 1, w * (s2 - s3));
+ add(fingerBone(f) + 2, w * s3);
+ } else if (name === "Thumb" + sfx) {
+ const u = v.p.clone().sub(thumbRoot).dot(thumbDir) / thumbLength;
+ const [j1, j2] = CUT.thumbJoints;
+ const h = CUT.blend;
+ const s2 = smoothstep(j1 - h, j1 + h, u);
+ const s3 = smoothstep(j2 - h, j2 + h, u);
+ add(B_THUMB, w * (1 - s2));
+ add(B_THUMB + 1, w * (s2 - s3));
+ add(B_THUMB + 2, w * s3);
+ } else {
+ // The upper arm, and whatever of the shoulder and chest reaches into the sleeve's top.
+ add(B_UPPER, w);
+ }
+ }
+ return out;
+ };
+
+ return {
+ side, shoulder, elbow, wrist, upper: elbow.distanceTo(shoulder), fore: foreLength, bind, knuckles, indexTip, tips,
+ emitterAt, emitterLift: lift, wristRadius, weigh,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts
index 2d301ec7f8..f48fe9cc56 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts
@@ -1,66 +1,32 @@
/**
- * The commander's own arms for the first-person viewmodel, built
- * procedurally: an upper arm and a tapered forearm in the uniform's cloth, a
- * gauntlet with a strap in the uniform's trim, and a gloved hand (palm,
- * knuckle plate, four two-segment fingers and a two-segment thumb). The
- * index finger and the thumb pose apart from the other three fingers, so a
- * hand can hold a grip with the index on the trigger. The left forearm
- * carries the shield emitter.
+ * One of the commander's own arms in the first-person viewmodel: the bones
+ * that drive the arm cut from their body (`armMesh.ts`).
*
- * The arm is a chain of bones (Object3Ds); its parts are not meshes of their
- * own but go into the viewmodel's one skinned mesh (`RigBuilder`), each bound
- * to the bone it moves with, so the whole rig is one draw call.
+ * The bones are plain Bones in the viewmodel's rig, posed in the camera's
+ * space every frame; the arm's skinned vertices follow them with the body's
+ * own weights. Upper arm, forearm (a hinge at the elbow and a twist toward the
+ * wrist, so turning the hand over rolls the forearm), hand, three phalanges
+ * per finger and three thumb bones.
*
* Hand frame (the `hand` bone, origin at the wrist): +Z runs to the
* knuckles, +Y is the back of the hand, +X the thumb's side for the right
- * hand; the left hand is the same hand mirrored (thumb on −X: its parts are
- * baked mirrored and its finger bones placed mirrored). Fingers curl toward
- * −Y (the palm).
+ * hand; the left hand is the same hand mirrored (thumb on −X). Fingers curl
+ * toward −Y (the palm).
*
* `pose` places the arm for a frame: shoulder, wrist and the hand's frame
* given, the elbow is solved by two-bone IK toward a pole (it hangs down and
- * out, as an arm does), and the forearm turns about its axis so its back (and
- * the emitter) faces the way the back of the hand does.
+ * out, as an arm does) with the body's own bone lengths; a wrist out of reach
+ * draws the shoulder after it (the shoulder is never in view) rather than
+ * tearing the hand off the sleeve.
*/
-import {
- Bone, CylinderGeometry, Euler, Group, LatheGeometry, Matrix4, Object3D, Quaternion, SphereGeometry, TorusGeometry, Vector2, Vector3,
- type BufferGeometry,
-} from "three";
+import { Bone, Group, Matrix4, Object3D, Quaternion, Vector3 } from "three";
import { solveElbow } from "../duel/figure";
-import { chamferBox, type RigBuilder, type Slot } from "./rigMesh";
-
-/** The arm's surfaces in the rig's palette. */
-export interface ArmSlots {
- /** The uniform's cloth (sleeves). */
- sleeve: Slot;
- /** The uniform's trim (the gauntlet's strap, the panel on the back of the hand). */
- trim: Slot;
- /** Glove leather. */
- glove: Slot;
- /** Armour and the shield emitter's housing. */
- housing: Slot;
- /** The shield emitter's glowing strip and lens (left forearm only). */
- emitter: Slot;
-}
-
-export const ARM = {
- /** Upper arm and forearm lengths, metres (the upper arm is never in view; it is long enough that the hands reach the blaster). */
- upper: 0.36,
- fore: 0.3,
- /** Sleeve radii: shoulder, elbow, wrist. */
- rShoulder: 0.05,
- rElbow: 0.043,
- rWrist: 0.035,
- /** Finger segment lengths. */
- seg1: 0.042,
- seg2: 0.036,
- /** The forearm's sleeve stops this far short of the wrist, inside the glove's gauntlet. */
- sleeveShort: 0.06,
-};
+import { B_FORE, B_HAND, B_THUMB, B_TWIST, B_UPPER, BONES, fingerBone, type ArmRig } from "./armMesh";
/**
- * A hand's pose: the three outer fingers' two joints, the index finger's two joints (radians toward the palm), and
- * the thumb's bend (0 open .. 1 closed) and its swing across the palm (radians).
+ * A hand's pose: the three outer fingers' two joints (knuckle, middle joint; the end joint follows the middle one,
+ * as a real finger's does), the index finger's two joints (radians toward the palm), and the thumb's bend (0 open ..
+ * 1 closed) and its swing across the palm (radians).
*/
export interface HandPose {
fingers: [number, number];
@@ -93,165 +59,175 @@ export function copyHand(out: HandPose, from: HandPose): HandPose {
return out;
}
+export const ARM = {
+ /** The end joint of a finger bends this share of its middle joint. */
+ distal: 0.75,
+ /** Each finger from the index outward curls a little more, as a real grip does (a share of its curl per finger). */
+ spread: 0.04,
+ /** The thumb: how its three bones share the bend, and how far the swing carries it across the palm. */
+ thumbBend: [0.25, 0.55, 0.75] as [number, number, number],
+ thumbAcross: 1,
+ /** A wrist out of reach pulls the shoulder after it until the arm is this share of its full length. */
+ reach: 0.985,
+ /** The shield emitter's housing (half its thickness) clears the sleeve's cloth by this, metres. */
+ emitterClear: 0.009,
+};
+
const SCRATCH_X = new Vector3();
const SCRATCH_Y = new Vector3();
const SCRATCH_Z = new Vector3();
const SCRATCH_M = new Matrix4();
-const M_POS = new Vector3();
-const M_SCALE = new Vector3();
-const M_Q = new Quaternion();
-const M_E = new Euler();
+const FINGER_M = new Matrix4();
+const QX = new Quaternion();
+const QY = new Quaternion();
+const AXIS_X = new Vector3(1, 0, 0);
+const AXIS_Y = new Vector3(0, 1, 0);
-/** A part's placement in its bone's frame: translate, turn (XYZ Euler), scale. */
-function at(x: number, y: number, z: number, rx = 0, ry = 0, rz = 0, sx = 1, sy = 1, sz = 1): Matrix4 {
- return new Matrix4().compose(M_POS.set(x, y, z), M_Q.setFromEuler(M_E.set(rx, ry, rz)), M_SCALE.set(sx, sy, sz));
-}
-
-/**
- * A finger segment along +Z from the origin: a tube tapering from radius `r0`
- * to `r1` over `length`, both ends rounded (a lathe-turned profile). Pure.
- */
-export function fingerSegment(r0: number, r1: number, length: number, radial = 6): LatheGeometry {
- const profile = [
- new Vector2(0, 0), new Vector2(r0 * 0.8, r0 * 0.4), new Vector2(r0, r0 * 1.1),
- new Vector2(r1, length - r1 * 0.9), new Vector2(0, length),
- ];
- return new LatheGeometry(profile, radial).rotateX(Math.PI / 2);
-}
-
-/** A finger: two segments in a chain, the second hinged at the end of the first. */
-interface Finger { base: Bone; joint: Bone }
+/** A chain bone's rest placement relative to its parent (from the bind frames). */
+interface Rest { position: Vector3; quaternion: Quaternion }
export class ViewArm {
readonly group = new Group();
- /** The hand: place it with `pose`; its children are in the hand frame. */
- readonly hand = new Bone();
- /** The bones (unscaled, turned along shoulder → elbow and elbow → wrist). */
- readonly upper = new Bone();
- readonly fore = new Bone();
- /** Landmarks in the hand frame (for layout checks): the knuckle plate, and the index finger's tip. */
+ readonly side: "left" | "right";
+ /** The arm's bones in the cut's order (`armMesh.ts`): what the skinned mesh binds to. */
+ readonly bones: Bone[] = [];
+ readonly upper: Bone;
+ readonly fore: Bone;
+ readonly twist: Bone;
+ /** The hand: placed by `pose`; its children are in the hand frame. */
+ readonly hand: Bone;
+ /** Landmarks: the knuckles on the back of the hand, the index finger's pad, the shield emitter's seat on the forearm. */
readonly knuckles = new Object3D();
readonly indexTip = new Object3D();
- /** The sleeves (scaled along the bone to its length) and the gauntlet, at the wrist end of the forearm. */
- private readonly upperSleeve = new Bone();
- private readonly foreSleeve = new Bone();
- private readonly cuff = new Bone();
- private readonly housing: Bone | null = null;
- private readonly fingers: Finger[] = [];
- private readonly thumb: Finger;
+ readonly emitter = new Object3D();
+ /** Bone lengths, metres (the body's own). */
+ readonly upperLength: number;
+ readonly foreLength: number;
+ private readonly rest: Rest[] = [];
/** −1 for the left arm: the hand is mirrored. */
private readonly sx: number;
+ private readonly from = new Vector3();
private readonly elbow = new Vector3();
private readonly axis = new Vector3();
private readonly back = new Vector3();
private readonly across = new Vector3();
private readonly m4 = new Matrix4();
- constructor(readonly side: "left" | "right", rig: RigBuilder, slots: ArmSlots) {
- this.group.name = `ViewArm_${side}`;
- const sx = side === "left" ? -1 : 1;
- this.sx = sx;
- const mirror = sx < 0;
- // In the hand: placed for the right hand, mirrored for the left.
- const handPart = (geo: BufferGeometry, bone: Object3D, slot: Slot, m: Matrix4 | null = null) => rig.add(geo, bone, slot, m, mirror);
-
- // Sleeves: unit-height cylinders along +Y from the joint, scaled to the bone's length by `pose`.
- this.upper.add(this.upperSleeve);
- this.fore.add(this.foreSleeve);
- rig.add(new CylinderGeometry(ARM.rElbow, ARM.rShoulder, 1, 10, 1, true).translate(0, 0.5, 0), this.upperSleeve, slots.sleeve);
- rig.add(new CylinderGeometry(ARM.rWrist, ARM.rElbow, 1, 10, 1, true).translate(0, 0.5, 0), this.foreSleeve, slots.sleeve);
- // An elbow cap closes the joint between the two sleeves (at the forearm's start).
- rig.add(new SphereGeometry(ARM.rElbow * 0.98, 6, 4), this.fore, slots.sleeve);
- this.group.add(this.upper, this.fore, this.hand);
-
- // The glove's gauntlet rides on the forearm (it follows the arm, not the bent wrist): it flares over the sleeve's
- // end (the sleeve stops inside it) with a rolled rim and a strap in the trim. `pose` puts `cuff` at the wrist.
- this.fore.add(this.cuff);
- rig.add(new CylinderGeometry(0.036, 0.0415, 0.08, 12, 1, true), this.cuff, slots.glove, at(0, -0.04, 0, 0, 0, 0, 1.08, 1, 0.9));
- rig.add(new TorusGeometry(0.0415, 0.0042, 4, 12).rotateX(Math.PI / 2), this.cuff, slots.glove, at(0, -0.08, 0, 0, 0, 0, 1.08, 1, 0.9));
- rig.add(new CylinderGeometry(0.0408, 0.0418, 0.012, 12, 1, true), this.cuff, slots.trim, at(0, -0.058, 0, 0, 0, 0, 1.1, 1, 0.92));
-
- // The wrist: a rounded joint between the gauntlet and the palm. Palm: a chamfered slab; an armoured plate over the
- // knuckles and a panel in the trim on the back of the hand.
- handPart(new SphereGeometry(0.031, 8, 6), this.hand, slots.glove, at(0, -0.002, 0.006, 0, 0, 0, 1.12, 0.82, 1));
- handPart(chamferBox(0.08, 0.03, 0.084, 0.011, true), this.hand, slots.glove, at(0, 0, 0.05));
- handPart(chamferBox(0.07, 0.01, 0.026, 0.004), this.hand, slots.housing, at(0, 0.0145, 0.08, 0.12));
- handPart(chamferBox(0.052, 0.006, 0.038, 0.0025), this.hand, slots.trim, at(0, 0.0138, 0.042));
- this.knuckles.position.set(0, 0.0145, 0.08);
- this.hand.add(this.knuckles);
-
- // Fingers: two tapered, round-ended segments each; index on the thumb's side (+X), little finger outside.
- const lengths = [1, 1.08, 1.02, 0.84];
- const xs = [0.0265, 0.0088, -0.0088, -0.0262];
- for (let i = 0; i < 4; i++) {
- const base = new Bone();
- base.position.set(xs[i] * sx, -0.001, 0.086);
- const joint = new Bone();
- joint.position.set(0, 0, ARM.seg1 * lengths[i] - 0.008);
- base.add(joint);
- this.hand.add(base);
- handPart(fingerSegment(0.0098, 0.009, ARM.seg1), base, slots.glove, at(0, 0, 0, 0, 0, 0, 1, 1, lengths[i]));
- handPart(fingerSegment(0.009, 0.0078, ARM.seg2), joint, slots.glove, at(0, 0, 0, 0, 0, 0, 1, 1, lengths[i]));
- this.fingers.push({ base, joint });
+ constructor(readonly rig: ArmRig) {
+ this.side = rig.side;
+ this.sx = rig.side === "left" ? -1 : 1;
+ this.group.name = `ViewArm_${rig.side}`;
+ this.upperLength = rig.upper;
+ this.foreLength = rig.fore;
+ for (let i = 0; i < BONES; i++) {
+ const b = new Bone();
+ b.name = `${rig.side}_${i}`;
+ this.bones.push(b);
+ this.rest.push({ position: new Vector3(), quaternion: new Quaternion() });
}
- this.indexTip.position.set(0, -0.004, ARM.seg2 * lengths[0]);
- this.fingers[0].joint.add(this.indexTip);
- // Thumb: from the heel of the palm on the thumb's side, angled forward and in.
- const tb = new Bone();
- tb.position.set(0.034 * sx, -0.007, 0.028);
- const tj = new Bone();
- tj.position.set(0, 0, 0.034);
- tb.add(tj);
- this.hand.add(tb);
- handPart(fingerSegment(0.0118, 0.0105, 0.042), tb, slots.glove);
- handPart(fingerSegment(0.0105, 0.009, 0.036), tj, slots.glove);
- this.thumb = { base: tb, joint: tj };
+ this.upper = this.bones[B_UPPER];
+ this.fore = this.bones[B_FORE];
+ this.twist = this.bones[B_TWIST];
+ this.hand = this.bones[B_HAND];
+ this.group.add(this.upper, this.fore, this.twist, this.hand);
+ // Fingers and thumb hang from the hand in chains; their rest placements come from the bind frames.
+ const chain = (first: number) => {
+ for (let j = 0; j < 3; j++) {
+ const i = first + j;
+ const parent = j === 0 ? B_HAND : i - 1;
+ const local = SCRATCH_M.copy(rig.bind[parent]).invert().multiply(rig.bind[i]);
+ local.decompose(this.rest[i].position, this.rest[i].quaternion, SCRATCH_X);
+ this.bones[parent].add(this.bones[i]);
+ this.bones[i].position.copy(this.rest[i].position);
+ this.bones[i].quaternion.copy(this.rest[i].quaternion);
+ }
+ };
+ for (let f = 0; f < 4; f++) chain(fingerBone(f));
+ chain(B_THUMB);
+ this.knuckles.position.copy(rig.knuckles);
+ this.hand.add(this.knuckles);
+ // The index finger's pad, carried by its end bone.
+ const toEnd = SCRATCH_M.copy(rig.bind[fingerBone(0) + 2]).invert().multiply(rig.bind[B_HAND]);
+ this.indexTip.position.copy(rig.indexTip).applyMatrix4(toEnd);
+ this.bones[fingerBone(0) + 2].add(this.indexTip);
+ this.emitter.position.set(0, rig.emitterAt * rig.fore, rig.emitterLift + ARM.emitterClear);
+ this.twist.add(this.emitter);
+ this.curl(handPose(0.3, 0.3, 0.2));
+ }
- if (side === "left") {
- // The shield emitter: a flat housing along the back of the forearm with a glowing strip and a lens.
- const housing = new Bone();
- this.fore.add(housing);
- rig.add(chamferBox(0.052, 0.13, 0.02, 0.005), housing, slots.housing);
- rig.add(chamferBox(0.012, 0.1, 0.004, 0.0015), housing, slots.emitter, at(0, -0.005, 0.011));
- rig.add(new CylinderGeometry(0.011, 0.013, 0.006, 10).rotateX(Math.PI / 2), housing, slots.emitter, at(0, 0.05, 0.012));
- this.housing = housing;
- }
- this.curl(handPose(1.2, 1.1, 0.4));
+ /** The bind frames' inverses, in bone order (the skeleton's bone inverses). */
+ inverses(): Matrix4[] {
+ return this.rig.bind.map((m) => m.clone().invert());
}
/** Curl the fingers, the index finger and the thumb (see `HandPose`). */
curl(p: HandPose): void {
- for (let i = 0; i < this.fingers.length; i++) {
- const f = this.fingers[i];
- // The little finger curls a touch more, as a real grip does.
- const extra = i * 0.05;
- const c = i === 0 ? p.index : p.fingers;
- f.base.rotation.set(c[0] + extra, 0, 0);
- f.joint.rotation.set(c[1] + extra, 0, 0);
+ for (let f = 0; f < 4; f++) {
+ const c = f === 0 ? p.index : p.fingers;
+ const k = 1 + f * ARM.spread;
+ const angles = [c[0] * k, c[1] * k, c[1] * k * ARM.distal];
+ for (let j = 0; j < 3; j++) this.bend(fingerBone(f) + j, angles[j], 0);
}
- // The thumb turns about Y and Z too: mirrored for the left hand.
- const [bend, across] = p.thumb;
- this.thumb.base.rotation.set(0.35 + bend * 0.5, (-0.55 - bend * 0.25 - across) * this.sx, 0);
- this.thumb.joint.rotation.set(bend * 0.6, -0.2 * this.sx, 0);
+ // The thumb bends through its three bones; its root also swings across the palm (mirrored for the left hand).
+ const [bend, swing] = p.thumb;
+ for (let j = 0; j < 3; j++) this.bend(B_THUMB + j, bend * ARM.thumbBend[j], j === 0 ? swing * ARM.thumbAcross * this.sx : 0);
+ }
+
+ /**
+ * Points along finger `f` (0 index .. 3 little) for its current curl, in the hand's frame: the middle joint, the
+ * end joint, the middle of the end bone and the tip. Written into `out` (four vectors).
+ */
+ fingerPoints(f: number, out: Vector3[]): Vector3[] {
+ const m = FINGER_M.identity();
+ for (let j = 0; j < 3; j++) {
+ const bone = this.bones[fingerBone(f) + j];
+ bone.updateMatrix();
+ m.multiply(bone.matrix);
+ if (j === 1) out[0].setFromMatrixPosition(m);
+ }
+ out[1].setFromMatrixPosition(m);
+ const tip = this.rig.tips[f];
+ out[2].copy(tip).multiplyScalar(0.5).applyMatrix4(m);
+ out[3].copy(tip).applyMatrix4(m);
+ return out;
+ }
+
+ /** A chain bone at its rest placement, curled by `x` about its +X and swung by `y` about its +Y. */
+ private bend(i: number, x: number, y: number): void {
+ const b = this.bones[i];
+ b.quaternion.copy(this.rest[i].quaternion).multiply(QY.setFromAxisAngle(AXIS_Y, y)).multiply(QX.setFromAxisAngle(AXIS_X, x));
}
/**
* Place the arm (all in the parent's space): `shoulder`, the hand at
* `wrist` turned by `handQuat` (the hand frame), the elbow bending toward
- * `pole` (unit). The forearm's back follows the back of the hand.
+ * `pole` (unit). The forearm's twist follows the back of the hand.
*/
pose(shoulder: Vector3, wrist: Vector3, handQuat: Quaternion, pole: Vector3): void {
+ const a = this.upperLength;
+ const b = this.foreLength;
+ // Out of reach: the shoulder follows the wrist (never the hand off the sleeve).
+ const from = this.from.copy(shoulder);
+ const d = from.distanceTo(wrist);
+ const max = (a + b) * ARM.reach;
+ if (d > max) from.sub(wrist).multiplyScalar(max / d).add(wrist);
this.hand.position.copy(wrist);
this.hand.quaternion.copy(handQuat);
- const elbow = solveElbow(shoulder, wrist, ARM.upper, ARM.fore, pole, this.elbow);
- const upper = this.place(this.upper, shoulder, elbow, pole);
- this.upperSleeve.scale.set(1, Math.max(0.01, upper), 1);
+ const elbow = solveElbow(from, wrist, a, b, pole, this.elbow);
+ // Upper arm: along shoulder → elbow, +Z toward the point of the elbow.
+ this.place(this.upper, from, elbow, pole);
+ // Forearm hinge: the upper arm's hinge axis (+X), along elbow → wrist.
+ const hinge = SCRATCH_X.setFromMatrixColumn(this.m4.makeRotationFromQuaternion(this.upper.quaternion), 0);
+ const y = SCRATCH_Y.subVectors(wrist, elbow);
+ if (y.lengthSq() < 1e-10) y.set(0, -1, 0);
+ y.normalize();
+ hinge.addScaledVector(y, -hinge.dot(y)).normalize();
+ const z = SCRATCH_Z.crossVectors(hinge, y);
+ this.fore.quaternion.setFromRotationMatrix(this.m4.makeBasis(hinge, y, z));
+ this.fore.position.copy(elbow);
+ // Forearm twist: the same axis, its back toward the back of the hand.
this.back.set(0, 1, 0).applyQuaternion(handQuat);
- const length = this.place(this.fore, elbow, wrist, this.back);
- this.foreSleeve.scale.set(1, Math.max(0.01, length - ARM.sleeveShort), 1);
- // The emitter lies along the forearm's back, a hand's width short of the wrist.
- this.cuff.position.set(0, length, 0);
- if (this.housing) this.housing.position.set(0, Math.max(0, length - 0.15), ARM.rWrist + 0.008);
+ this.place(this.twist, elbow, wrist, this.back);
}
/** Turn `bone` along `a` → `b` (its +Y) with its +Z toward `up`. Returns the length. */
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts
index ed494b81db..51f27c9c39 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts
@@ -2,13 +2,16 @@
* The first-person viewmodel: who is drawn (arms in, own body out), the walk
* bob, idle sway, look lag and recoil maths, the arm's IK and hand frames,
* and the rig posed in the viewmodel camera's frustum on the deck and in a
- * duel (hip, sights, shield, a shot).
+ * duel (hip, sights, shield, vent, sprint, a shot), with the commander's own
+ * arms cut from their body (SK_Officer_M.glb, read from disk).
*/
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { Box3, Color, Frustum, Matrix4, Mesh, PerspectiveCamera, Quaternion, Sprite, Vector3 } from "three";
+import { Color, Frustum, Matrix4, Mesh, PerspectiveCamera, Quaternion, Sprite, Vector3, type SkinnedMesh } from "three";
import type { PlayerView } from "../combat/view";
-import { ARM, fingerSegment, handPose, ViewArm } from "./arms";
-import { chamferBox, RigBuilder } from "./rigMesh";
+import { cutArms } from "./armMesh";
+import { ARM, handPose, ViewArm } from "./arms";
+import { loadBody } from "./armFixture.test-util";
+import { chamferBox } from "./rigMesh";
import {
HIDE_BODY_BELOW_M, HIDE_BODY_FIRST_SHARE, idleSway, MOTION, springStep, turnBetween, ViewmodelMotion, viewmodelVisibility,
walkBob, zeroOffsets, type MotionInput,
@@ -159,18 +162,10 @@ describe("viewmodel motion", () => {
});
});
-describe("viewmodel arms", () => {
- it("turns finger segments along +Z, round at both ends", () => {
- const geo = fingerSegment(0.01, 0.008, 0.04);
- geo.computeBoundingBox();
- const box = geo.boundingBox as Box3;
- expect(box.min.z).toBeCloseTo(0, 6);
- expect(box.max.z).toBeCloseTo(0.04, 6);
- expect(box.max.x).toBeLessThanOrEqual(0.01);
- expect(box.max.x).toBeGreaterThan(0.008);
- geo.dispose();
- });
+let body: SkinnedMesh[] = [];
+beforeAll(async () => { body = await loadBody(); });
+describe("viewmodel arms", () => {
it("chamfers a box with 44 flat triangles", () => {
const geo = chamferBox(0.1, 0.04, 0.2, 0.01);
expect(geo.getAttribute("position").count / 3).toBe(44);
@@ -180,43 +175,57 @@ describe("viewmodel arms", () => {
geo.dispose();
});
- it("poses the index finger and the thumb apart from the other fingers", () => {
- const arm = new ViewArm("right", new RigBuilder(), SLOTS);
- const bones = arm as unknown as { fingers: { base: { rotation: { x: number } } }[]; thumb: { base: { rotation: { y: number } } } };
+ it("curls each finger through three joints, the index finger and the thumb apart from the rest", () => {
+ const src = cutArms(body);
+ const arm = new ViewArm(src.right);
+ arm.curl(handPose(0, 0, 0));
+ const rest = arm.bones.map((b) => b.quaternion.clone());
arm.curl(handPose(1.5, 1.4, 0.7, [0.3, 0.7], 0.2));
- expect(bones.fingers[0].base.rotation.x).toBeCloseTo(0.3, 6);
- expect(bones.fingers[1].base.rotation.x).toBeGreaterThan(1.5);
- const thumbY = bones.thumb.base.rotation.y;
- arm.curl(handPose(1.5, 1.4, 0.7, [0.3, 0.7], 0));
- expect(bones.thumb.base.rotation.y).not.toBeCloseTo(thumbY, 3);
- // The left hand is the right one mirrored: its thumb swings the other way.
- const left = new ViewArm("left", new RigBuilder(), SLOTS);
- left.curl(handPose(1.5, 1.4, 0.7, [0.3, 0.7], 0));
- expect((left as unknown as typeof bones).thumb.base.rotation.y).toBeCloseTo(-bones.thumb.base.rotation.y, 6);
+ const turned = (i: number) => arm.bones[i].quaternion.angleTo(rest[i]);
+ // Index (4..6): knuckle by 0.3; the middle finger (7..9) by 1.5 and more; every joint of a curled finger bends.
+ expect(turned(4)).toBeCloseTo(0.3, 6);
+ expect(turned(4)).toBeLessThan(turned(7));
+ for (const i of [7, 8, 9, 10, 11, 12, 13, 14, 15]) expect(turned(i)).toBeGreaterThan(0.5);
+ // The end joint follows the middle one.
+ expect(turned(9)).toBeCloseTo(1.4 * (1 + ARM.spread) * ARM.distal, 6);
+ // The thumb bends through its bones and swings across the palm, mirrored for the left hand.
+ expect(turned(17)).toBeGreaterThan(0.2);
+ const left = new ViewArm(src.left);
+ left.curl(handPose(0, 0, 0));
+ const leftRest = left.bones[16].quaternion.clone();
+ left.curl(handPose(1.5, 1.4, 0.7, [0.3, 0.7], 0.2));
+ expect(left.bones[16].quaternion.angleTo(leftRest)).toBeCloseTo(turned(16), 6);
+ src.geometry.dispose();
});
- it("reaches the wrist with a two-bone arm whose elbow bends toward the pole", () => {
- const arm = new ViewArm("right", new RigBuilder(), SLOTS);
- const shoulder = new Vector3(0.2, -0.38, 0);
- const wrist = new Vector3(0.12, -0.12, -0.4);
+ it("reaches the wrist with the body's own arm, the elbow bending toward the pole", () => {
+ const src = cutArms(body);
+ const arm = new ViewArm(src.right);
+ const shoulder = new Vector3(0.2, -0.3, 0);
+ const wrist = new Vector3(0.14, -0.2, -0.42);
const q = ViewArm.handFrame(new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Quaternion());
arm.pose(shoulder, wrist, q, new Vector3(1, -0.6, 0).normalize());
arm.group.updateMatrixWorld(true);
expect(arm.hand.position.distanceTo(wrist)).toBeLessThan(1e-9);
const elbow = arm.fore.position;
- expect(elbow.distanceTo(shoulder)).toBeCloseTo(ARM.upper, 6);
- expect(elbow.distanceTo(wrist)).toBeCloseTo(ARM.fore, 6);
+ expect(elbow.distanceTo(arm.upper.position)).toBeCloseTo(arm.upperLength, 6);
+ expect(elbow.distanceTo(wrist)).toBeCloseTo(arm.foreLength, 6);
// The elbow hangs out and down, as an arm does.
expect(elbow.x).toBeGreaterThan((shoulder.x + wrist.x) / 2);
- // The hand frame: knuckles ahead (−Z), back of the hand up.
- const knuckles = new Vector3(0, 0, 1).applyQuaternion(q);
- expect(knuckles.z).toBeCloseTo(-1, 6);
-
+ expect(elbow.y).toBeLessThan((shoulder.y + wrist.y) / 2);
+ // The forearm's twist follows the back of the hand; its hinge stays in the elbow's plane.
+ const twistBack = new Vector3(0, 0, 1).applyQuaternion(arm.twist.quaternion);
+ const foreAxis = wrist.clone().sub(elbow).normalize();
+ const handBack = new Vector3(0, 1, 0).applyQuaternion(q);
+ expect(twistBack.dot(handBack.addScaledVector(foreAxis, -handBack.dot(foreAxis)).normalize())).toBeCloseTo(1, 6);
+ // Out of reach, the shoulder follows: the hand stays on the sleeve.
+ const far = new Vector3(0.1, -0.1, -1.2);
+ arm.pose(shoulder, far, q, new Vector3(1, -0.6, 0).normalize());
+ expect(arm.fore.position.distanceTo(far)).toBeCloseTo(arm.foreLength, 6);
+ src.geometry.dispose();
});
});
-const SLOTS = { sleeve: 0, trim: 1, glove: 2, housing: 3, emitter: 4 };
-
function player(over: Partial<PlayerView> = {}): PlayerView {
return {
slot: 0, id: "a", local: true, side: 0, x: 0, z: 0, yaw: 0, pitch: 0, aimYaw: 0, aimPitch: 0, vx: 0, vz: 0, speed: 0,
@@ -246,6 +255,13 @@ describe("viewmodel rig", () => {
return c;
}
+ /** A viewmodel with the commander's arms attached. */
+ function made(): Viewmodel {
+ const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ vm.attachArms(cutArms(body));
+ return vm;
+ }
+
/** Whether a world point of the rig is in the viewmodel camera's view. */
function inView(vm: Viewmodel, p: Vector3): boolean {
const cam = vm.camera;
@@ -258,8 +274,10 @@ describe("viewmodel rig", () => {
return o.getWorldPosition(new Vector3());
}
+ const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
+
it("draws nothing until first person asks for the arms", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ const vm = made();
vm.prepare(eye(), 1 / 60, null);
expect(vm.visible).toBe(false);
vm.set(frameFor({ visibility: { arms: false, mode: "deck", hideOwnBody: false, raise: 0 } }));
@@ -268,17 +286,49 @@ describe("viewmodel rig", () => {
vm.dispose();
});
- it("puts both hands in the lower corners on the deck, the blaster away", () => {
+ it("holds the blaster before the body has loaded, and takes the arms when it has", () => {
const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ vm.set(duelFrame(player()));
+ for (let i = 0; i < 3; i++) vm.prepare(eye(), 1 / 60, null);
+ expect(vm.hasArms).toBe(false);
+ expect(vm.armsMesh).toBeNull();
+ vm.attachArms(cutArms(body));
+ vm.prepare(eye(), 1 / 60, null);
+ expect(vm.hasArms).toBe(true);
+ expect(vm.armsMesh?.isSkinnedMesh).toBe(true);
+ // Attaching again replaces the arms (one mesh in the scene).
+ vm.attachArms(cutArms(body));
+ expect(vm.scene.children.filter((o) => o.name === "ViewmodelArms")).toHaveLength(1);
+ vm.dispose();
+ });
+
+ it("dresses the sleeves in the uniform and the hands in gloves, over the body's occlusion", () => {
+ const vm = made();
+ const colours = vm.armsMesh?.geometry.getAttribute("color");
+ expect(colours).toBeTruthy();
+ const read = () => {
+ let max = 0;
+ for (let i = 0; i < (colours?.count ?? 0); i++) max = Math.max(max, colours?.getX(i) ?? 0);
+ return max;
+ };
+ const before = read();
+ vm.setColours({ uniform: "#e4e1d8", trim: "#d6d3c9" });
+ // The flag tier's white tunic lights the sleeves up.
+ expect(read()).toBeGreaterThan(before);
+ vm.dispose();
+ });
+
+ it("puts both hands in the lower corners on the deck, the blaster away", () => {
+ const vm = made();
vm.set(frameFor());
vm.prepare(eye(), 1 / 60, null);
expect(vm.visible).toBe(true);
- const parts = vm as unknown as { right: ViewArm; left: ViewArm; gun: { visible: boolean } };
- expect(parts.gun.visible).toBe(false);
+ const gun = (vm as unknown as { gun: { visible: boolean } }).gun;
+ expect(gun.visible).toBe(false);
vm.scene.updateMatrixWorld(true);
// The knuckles are in view; the right hand right of centre, the left hand left of it, both below the eye line.
- const r = world(parts.right.knuckles);
- const l = world(parts.left.knuckles);
+ const r = world(vm.right!.knuckles);
+ const l = world(vm.left!.knuckles);
expect(inView(vm, r)).toBe(true);
expect(inView(vm, l)).toBe(true);
const toCam = (p: Vector3) => p.clone().applyMatrix4(vm.camera.matrixWorldInverse);
@@ -289,18 +339,17 @@ describe("viewmodel rig", () => {
});
it("holds the blaster in a duel: muzzle and both hands in view at the hip; the sight on the eye line in the sights", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
- const parts = vm as unknown as { right: ViewArm; left: ViewArm; blaster: { group: { localToWorld(v: Vector3): Vector3 }; muzzle: Vector3; sight: Vector3 } };
- const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
+ const vm = made();
+ const parts = vm as unknown as { blaster: { group: { localToWorld(v: Vector3): Vector3 }; muzzle: Vector3; sight: Vector3 } };
const cam = eye();
vm.set(duelFrame(player()));
for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
vm.scene.updateMatrixWorld(true);
const muzzle = parts.blaster.group.localToWorld(parts.blaster.muzzle.clone());
expect(inView(vm, muzzle)).toBe(true);
- expect(inView(vm, world(parts.left.hand))).toBe(true);
+ expect(inView(vm, world(vm.left!.knuckles))).toBe(true);
// The right hand sits on the grip at the bottom right.
- const right = world(parts.right.hand).applyMatrix4(vm.camera.matrixWorldInverse);
+ const right = world(vm.right!.hand).applyMatrix4(vm.camera.matrixWorldInverse);
expect(right.x).toBeGreaterThan(0.08);
expect(right.y).toBeLessThan(-0.1);
// Aiming down the sights: the sight's window on the view axis at adsDistance.
@@ -314,22 +363,30 @@ describe("viewmodel rig", () => {
vm.dispose();
});
- it("raises the left forearm with the shield up and kicks with a shot", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
- const parts = vm as unknown as { left: ViewArm; gun: { position: Vector3 } };
+ it("raises the left forearm with the shield up, its emitter lit on the forearm, and kicks with a shot", () => {
+ const vm = made();
+ const parts = vm as unknown as { gun: { position: Vector3 }; housingBone: { getWorldPosition(v: Vector3): Vector3 } };
const cam = eye();
- const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
vm.set(duelFrame(player()));
for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
vm.scene.updateMatrixWorld(true);
- const restY = world(parts.left.hand).applyMatrix4(vm.camera.matrixWorldInverse).y;
+ const restY = world(vm.left!.hand).applyMatrix4(vm.camera.matrixWorldInverse).y;
const restZ = parts.gun.position.z;
vm.set(duelFrame(player({ shieldUp: true })));
for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
vm.scene.updateMatrixWorld(true);
- expect(world(parts.left.hand).applyMatrix4(vm.camera.matrixWorldInverse).y).toBeGreaterThan(restY + 0.03);
- // The emitter's strip lights.
+ expect(world(vm.left!.hand).applyMatrix4(vm.camera.matrixWorldInverse).y).toBeGreaterThan(restY + 0.03);
+ // The emitter's strip lights, and its housing rides on the left forearm between the elbow and the wrist.
expect(vm.emitterGlow).toBeGreaterThan(3);
+ const housing = world(parts.housingBone);
+ const elbow = world(vm.left!.fore);
+ const wrist = world(vm.left!.hand);
+ const axis = wrist.clone().sub(elbow);
+ const t = housing.clone().sub(elbow).dot(axis) / axis.lengthSq();
+ expect(t).toBeGreaterThan(0.3);
+ expect(t).toBeLessThan(0.95);
+ const off = housing.clone().sub(elbow).addScaledVector(axis, -t).length();
+ expect(off).toBeLessThan(0.08);
vm.set(duelFrame(player()));
for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
vm.shot(1, false);
@@ -339,26 +396,28 @@ describe("viewmodel rig", () => {
vm.dispose();
});
- /** The rig's skinned vertices in normalised device coordinates, split into the blaster's and the arms'. */
+ /** The skinned vertices in normalised device coordinates: the blaster's and the arms'. */
function screen(vm: Viewmodel): { gun: Vector3[]; arms: Vector3[] } {
vm.scene.updateMatrixWorld(true);
vm.camera.updateMatrixWorld();
- const mesh = vm.mesh;
- const gunBone = (vm as unknown as { gunBone: object }).gunBone;
- const gunIndex = mesh.skeleton.bones.indexOf(gunBone as never);
- const skin = mesh.geometry.getAttribute("skinIndex");
const out = { gun: [] as Vector3[], arms: [] as Vector3[] };
- for (let i = 0; i < skin.count; i += 3) {
- const p = mesh.getVertexPosition(i, new Vector3()).project(vm.camera);
- (skin.getX(i) === gunIndex ? out.gun : out.arms).push(p);
+ const rig = vm.mesh;
+ const gunBone = (vm as unknown as { gunBone: object }).gunBone;
+ const gunIndex = rig.skeleton.bones.indexOf(gunBone as never);
+ const skin = rig.geometry.getAttribute("skinIndex");
+ for (let i = 0; i < skin.count; i += 3) if (skin.getX(i) === gunIndex) out.gun.push(rig.getVertexPosition(i, new Vector3()).project(vm.camera));
+ const arms = vm.armsMesh;
+ if (arms) {
+ arms.skeleton.update();
+ const n = arms.geometry.getAttribute("position").count;
+ for (let i = 0; i < n; i += 2) out.arms.push(arms.getVertexPosition(i, new Vector3()).project(vm.camera));
}
return out;
}
const onScreen = (p: Vector3) => Math.abs(p.x) <= 1 && Math.abs(p.y) <= 1 && p.z < 1;
- const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
- it("draws the arms and the blaster as one skinned mesh within the budget", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ it("draws the arms in one draw and the blaster in another, within the budget", () => {
+ const vm = made();
vm.set(duelFrame(player()));
vm.shot(1, false);
vm.shot(2, false);
@@ -374,23 +433,25 @@ describe("viewmodel rig", () => {
draws++;
}
});
- // The rig, the sight's reticle and the muzzle flash.
- expect(draws).toBeLessThanOrEqual(3);
- expect(triangles).toBeLessThanOrEqual(3000);
+ // The arms, the blaster with the emitter, the sight's reticle and the muzzle flash.
+ expect(draws).toBeLessThanOrEqual(4);
+ expect(triangles).toBeLessThanOrEqual(6000);
+ expect(vm.armsMesh?.isSkinnedMesh).toBe(true);
expect(vm.mesh.isSkinnedMesh).toBe(true);
vm.dispose();
});
it("keeps the centre of the screen clear at the hip, the blaster low on the right", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ const vm = made();
vm.set(duelFrame(player()));
for (let i = 0; i < 30; i++) vm.prepare(eye(), 1 / 60, null);
const { gun, arms } = screen(vm);
- const all = [...gun, ...arms].filter(onScreen);
+ const all = [...gun.map((p) => ["gun", p] as const), ...arms.map((p) => ["arms", p] as const)].filter(([, p]) => onScreen(p));
+ const at = (list: typeof all) => list.map(([what, p]) => `${what} ${p.x.toFixed(3)},${p.y.toFixed(3)}`);
// Nothing of the rig around the crosshair: the middle fifth across, down to below the screen's middle.
- expect(all.filter((p) => Math.abs(p.x) < 0.12 && p.y > -0.2)).toHaveLength(0);
+ expect(at(all.filter(([, p]) => Math.abs(p.x) < 0.12 && p.y > -0.2))).toEqual([]);
// The left half of the screen stays clear above its bottom quarter (the support arm comes up from below).
- expect(all.filter((p) => p.x < -0.05 && p.y > -0.5)).toHaveLength(0);
+ expect(at(all.filter(([, p]) => p.x < -0.05 && p.y > -0.5))).toEqual([]);
// The blaster is right of centre and below the crosshair.
const seen = gun.filter(onScreen);
expect(seen.reduce((s, p) => s + p.x, 0) / seen.length).toBeGreaterThan(0.2);
@@ -399,7 +460,7 @@ describe("viewmodel rig", () => {
});
it("keeps the blaster in view, lowered and canted, in a sprint", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ const vm = made();
const parts = vm as unknown as { blaster: { group: { localToWorld(v: Vector3): Vector3 }; muzzle: Vector3 } };
vm.set(duelFrame(player({ sprinting: true, speed: 6 })));
for (let i = 0; i < 60; i++) vm.prepare(eye(), 1 / 60, null);
@@ -410,14 +471,33 @@ describe("viewmodel rig", () => {
vm.dispose();
});
- it("rests the right index finger on the trigger", () => {
- const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
- const parts = vm as unknown as { right: ViewArm };
+ it("rests the right index finger on the trigger and closes the other fingers round the grip", () => {
+ const vm = made();
vm.set(duelFrame(player()));
for (let i = 0; i < 30; i++) vm.prepare(eye(), 1 / 60, null);
vm.scene.updateMatrixWorld(true);
- const tip = world(parts.right.indexTip);
- expect(tip.distanceTo(world(vm.trigger))).toBeLessThan(0.012);
+ expect(vm.triggerReach).toBeLessThan(0.006);
+ expect(world(vm.right!.indexTip).distanceTo(world(vm.trigger))).toBeLessThan(0.008);
+ // The index finger is straighter than the fingers wrapped round the grip.
+ const hand = (vm as unknown as { gripHand: { fingers: number[]; index: number[] } }).gripHand;
+ expect(hand.fingers[0] + hand.fingers[1]).toBeGreaterThan(hand.index[0] + hand.index[1]);
+ vm.dispose();
+ });
+
+ it("slaps the receiver with the left hand while venting", () => {
+ const vm = made();
+ const cam = eye();
+ vm.set(duelFrame(player()));
+ for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ const rest = world(vm.left!.hand);
+ vm.set(duelFrame(player({ venting: true })));
+ for (let i = 0; i < 40; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ // The hand has left the shroud for the receiver, nearer the right hand on the grip.
+ const vent = world(vm.left!.hand);
+ expect(vent.distanceTo(rest)).toBeGreaterThan(0.03);
+ expect(vent.distanceTo(world(vm.right!.hand))).toBeLessThan(rest.distanceTo(world(vm.right!.hand)));
vm.dispose();
});
});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts
index 064bda54a8..e33790c1fc 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts
@@ -9,9 +9,14 @@
* field of view, and the pass clears depth before it draws, so the arms never
* sink into a wall and never stretch with a wide field-of-view setting.
*
- * Both arms and the blaster are one skinned mesh under one palette material
- * (`rigMesh.ts`): one draw call, plus the sight's reticle and the muzzle
- * flash in a duel.
+ * The arms are the commander's own, cut from their body (`armMesh.ts`): one
+ * skinned mesh under one material with the body's painted atlas, its sleeves
+ * in the rank tier's uniform, its real skin weights bending elbows, wrists and
+ * knuckles. They arrive once the body has loaded (`attachArms`); until then
+ * only the blaster shows. The blaster and the shield emitter on the left
+ * forearm are a second skinned mesh under a palette material (`rigMesh.ts`).
+ * Two draws on the deck; four in a duel with the sight's reticle and the
+ * muzzle flash.
*
* The rig is posed in the camera's space every frame (x right, y up, −z ahead):
* on the deck both hands hang loose low in the frame and swing with the walk;
@@ -25,8 +30,9 @@
* the muzzle and lights the hands. The frame path allocates nothing.
*/
import {
- AdditiveBlending, Bone, CanvasTexture, Color, DirectionalLight, Euler, Group, Matrix4, Mesh, MeshBasicMaterial, MeshStandardMaterial,
- PerspectiveCamera, PointLight, Quaternion, Scene, Sprite, SpriteMaterial, Vector3, type SkinnedMesh, type Texture,
+ AdditiveBlending, Bone, BufferAttribute, CanvasTexture, Color, CylinderGeometry, DirectionalLight, DoubleSide, Euler, Group, Matrix4, Mesh,
+ MeshBasicMaterial, MeshStandardMaterial, PerspectiveCamera, PointLight, Quaternion, Scene, Skeleton, SkinnedMesh, Sprite, SpriteMaterial,
+ Vector3, type Texture,
} from "three";
import type { Deck } from "../content/deck";
import { RoomLight } from "../actors/roomLight";
@@ -34,7 +40,8 @@ import type { PlayerView } from "../combat/view";
import { buildBlaster, type Blaster } from "../duel/blaster";
import { radialTexture } from "../duel/effects";
import { verticalFov } from "../engine/realtime/shoulderRig";
-import { copyHand, handPose, lerpHand, ViewArm, type ArmSlots, type HandPose } from "./arms";
+import { fingerBone, type ArmsSource, type ArmSlot } from "./armMesh";
+import { copyHand, handPose, lerpHand, ViewArm, type HandPose } from "./arms";
import { turnBetween, ViewmodelMotion, type Visibility } from "./motion";
import { chamferBox, RigBuilder, RigPalette, type Slot } from "./rigMesh";
@@ -46,12 +53,16 @@ export interface GunPose { x: number; y: number; z: number; pitch: number; yaw:
* (`window.__verseViewmodel` in development builds, then `retune()`).
*/
export const VIEWMODEL = {
+ /** Gloves over the body's hands (a CSS colour multiplied into the hands' painted atlas), or null for bare hands. */
+ gloves: "#1e1f23" as string | null,
/** Horizontal field of view of the viewmodel camera, degrees (fixed: the arms keep their shape whatever the person's setting). */
hfovDeg: 88,
/** ... and while aiming down the sights (the sight comes a little closer). */
adsHfovDeg: 76,
near: 0.01,
far: 4,
+ /** A gloved finger's half thickness: how far off a held surface the closed fingers' joints and tips rest, metres. */
+ fingerRadius: 0.0085,
/** The blaster's size in the hands, relative to the duel's model. */
gunScale: 0.6,
/** Distance from the eye to the sight's window when aiming down the sights, metres. */
@@ -67,7 +78,7 @@ export const VIEWMODEL = {
* A soft key light over the shoulder (in the view's frame, so the arms always read): divided by the deck's
* exposure, it lights the arms the same on every deck.
*/
- fill: 1.2,
+ fill: 0.9,
/**
* The blaster at the hip (low on the right, the muzzle toward the crosshair, the centre clear), lowered and canted
* in a sprint (still in view), lowered behind the shield, rolled over to vent, dropped when knocked out.
@@ -80,7 +91,7 @@ export const VIEWMODEL = {
/** The left wrist with the shield up, camera space. */
shieldWrist: { x: -0.13, y: -0.07, z: -0.42 },
/** The wrists on the deck (the left mirrors x), camera space. */
- deckWrist: { x: 0.2, y: -0.2, z: -0.42 },
+ deckWrist: { x: 0.19, y: -0.2, z: -0.47 },
/**
* Shoulders, below and behind the eyes, and the elbows' pull (down and out). The support arm's shoulder sits in
* toward the middle and low, so its forearm comes up from the bottom edge to the shroud instead of across the screen.
@@ -90,28 +101,33 @@ export const VIEWMODEL = {
poleR: new Vector3(1, -0.6, 0.1),
poleL: new Vector3(-0.4, -1, 0.2),
/**
- * The hands: the right hand's hold on the grip (along the grip, along the knuckles, out to the side), the left's
- * beside the shroud (out to its left, up, ahead), hand frames as knuckle and back-of-hand directions, and the hand
- * poses (`HandPose`: three fingers, the index finger, the thumb).
+ * The hands. Holds say where the held part sits in the hand's own frame (x toward the thumb on the right hand,
+ * y the back of the hand, z the knuckles; metres from the wrist): the grip's centre across the right palm, the
+ * shroud's axis over the left palm, the receiver's side under the slapping palm. Hand frames are knuckle and
+ * back-of-hand directions in the blaster's frame (+Z the muzzle, +X its left) or the camera's; hand poses are
+ * `HandPose` (three fingers, the index finger, the thumb). The right index finger's two joints are solved so its
+ * pad rests on the trigger.
*/
hands: {
- grip: [-0.03, -0.075, 0.036],
- /** The right hand on the grip: three fingers wrapped, the index finger straight along the guard onto the trigger, the thumb over the far side. */
- gripPose: handPose(1.5, 1.4, 0.75, [0, 1.5], 0.15),
- fore: [0.042, 0.012, -0.06],
- foreKnuckles: [-0.15, 0.25, 1],
- foreBack: [1, -0.15, 0],
- /** The left hand under the shroud: fingers curled round it, the thumb along its top. */
- forePose: handPose(1.25, 1.0, 0.35, [1.1, 0.9], -0.2),
+ grip: [0.056, -0.032, 0.072],
+ /** The right hand on the grip: three fingers wrapped round its front, the thumb over its far side. */
+ gripPose: handPose(1.45, 1.5, 0.7, [0.4, 1.0], 0.35),
+ fore: [-0.004, -0.04, 0.112],
+ /** The left hand under the shroud: the knuckles along the barrel, the back of the hand down and out. */
+ foreKnuckles: [0, 0.12, 1],
+ foreBack: [0.55, -0.85, 0],
+ /** The fingers curled up round the shroud's right side, the thumb along its left. */
+ forePose: handPose(1.1, 1.0, 0.45, [0.95, 0.85], 0.1),
+ vent: [0.0, -0.016, 0.07],
ventKnuckles: [0, 0.35, 1],
ventBack: [1, 0.1, 0],
/** The open hand slapping the receiver, and raised palm forward behind the shield. */
ventPose: handPose(0.35, 0.3, 0.1, [0.3, 0.25], -0.3),
shieldPose: handPose(0.15, 0.1, 0.2, [0.1, 0.05], -0.4),
- deckKnuckles: [-0.35, 0.25, -1],
- deckBack: [0.35, 1, 0.1],
+ deckKnuckles: [-0.25, 0.05, -1],
+ deckBack: [0.55, 0.85, 0],
/** Relaxed hands: the index a little straighter than the rest, the thumb resting along it. */
- deckPose: handPose(1.3, 1.15, 0.6, [1.05, 0.95], 0),
+ deckPose: handPose(0.35, 0.55, 0.3, [0.25, 0.4], 0),
shieldKnuckles: [0.15, 1, -0.2],
shieldBack: [0.2, 0.15, 1],
},
@@ -125,12 +141,24 @@ const SHOULDER_L = new Vector3();
const POLE_R = new Vector3();
const POLE_L = new Vector3();
-/** The person's colours for the arms: the uniform's cloth and trim (CSS colours). */
+/**
+ * The person's colours for the arms: the uniform's cloth and trim (CSS colours). Up close the sleeves and their cuffs
+ * wear the cloth; the trim is kept for the layer's contract.
+ */
export interface ArmColours {
uniform: string;
trim: string;
}
+/** The arms' own drawing: the bones of both arms, their skinned mesh and its material. */
+interface Arms {
+ right: ViewArm;
+ left: ViewArm;
+ mesh: SkinnedMesh;
+ material: MeshStandardMaterial;
+ source: ArmsSource;
+}
+
export interface ViewmodelFrame {
visibility: Visibility;
/** The duel's local player, or null on the deck. */
@@ -186,19 +214,22 @@ export class Viewmodel {
readonly camera: PerspectiveCamera;
/** Draw the pass this frame (set by `prepare`). */
visible = false;
- /** Both arms and the blaster: one skinned mesh. */
+ /** The blaster and the shield emitter: one skinned mesh under the palette. */
readonly mesh: SkinnedMesh;
private readonly rig = new Group();
- private readonly right: ViewArm;
- private readonly left: ViewArm;
+ /** The commander's arms, once their body has loaded. */
+ private arms: Arms | null = null;
private readonly blaster: Blaster;
private readonly gun = new Group();
/** The blaster's bone (inside its scaled group): collapsed to a point when the hands are empty. */
private readonly gunBone = new Bone();
+ /** The shield emitter's bone: on the left forearm once the arms are in, collapsed until then. */
+ private readonly housingBone = new Bone();
/** A landmark on the trigger, in the blaster's frame. */
readonly trigger = new Group();
private readonly palette = new RigPalette("M_View_Rig");
- private readonly slots: ArmSlots;
+ private readonly slots: { housing: Slot; emitter: Slot };
+ private colours: ArmColours;
private readonly glows: Glow[] = [];
private readonly reticle: MeshBasicMaterial;
private readonly flash: Sprite;
@@ -208,7 +239,6 @@ export class Viewmodel {
private readonly motion = new ViewmodelMotion();
private readonly textures: Texture[] = [];
private readonly emitterColour = new Color(0.35, 0.75, 1.6);
- private readonly tmpColour = new Color();
private frame: ViewmodelFrame | null = null;
private shots = 0;
private flashT = 0;
@@ -222,6 +252,11 @@ export class Viewmodel {
private readonly pose: GunPose = { ...VIEWMODEL.hip };
private readonly ads: GunPose = { ...VIEWMODEL.hip };
private readonly handL: HandPose = handPose(0, 0, 0);
+ /** The hands closed on the blaster (`solveHolds`): the right on the grip, its index on the trigger; the left on the shroud. */
+ private readonly gripHand: HandPose = handPose(0, 0, 0);
+ private readonly foreHand: HandPose = handPose(0, 0, 0);
+ /** How far the solved index finger's pad is from the trigger, metres (for checks). */
+ triggerReach = Infinity;
private readonly euler = new Euler(0, 0, 0, "YXZ");
private readonly qGun = new Quaternion();
private readonly qTmp = new Quaternion();
@@ -246,17 +281,17 @@ export class Viewmodel {
this.camera = new PerspectiveCamera(60, 1, VIEWMODEL.near, VIEWMODEL.far);
this.scene.name = "Viewmodel";
const pal = this.palette;
- this.slots = {
- sleeve: pal.slot("sleeve"), trim: pal.slot("trim"), glove: pal.slot("glove"), housing: pal.slot("housing"), emitter: pal.slot("emitter"),
- };
- pal.surface(this.slots.glove, new Color(0x2b2c31), 0.46, 0.05);
+ this.slots = { housing: pal.slot("housing"), emitter: pal.slot("emitter") };
pal.surface(this.slots.housing, new Color(0x2a2e34), 0.35, 0.85);
pal.surface(this.slots.emitter, new Color(0x050505), 0.4, 0);
- this.setColours(colours);
+ this.colours = { ...colours };
const rig = new RigBuilder();
- this.right = new ViewArm("right", rig, this.slots);
- this.left = new ViewArm("left", rig, this.slots);
+ // The shield emitter: a flat housing along the back of the left forearm with a glowing strip and a lens.
+ rig.add(chamferBox(0.046, 0.12, 0.016, 0.005), this.housingBone, this.slots.housing);
+ rig.add(chamferBox(0.011, 0.092, 0.004, 0.0015), this.housingBone, this.slots.emitter, new Matrix4().makeTranslation(0, -0.005, 0.009));
+ rig.add(new CylinderGeometry(0.01, 0.012, 0.006, 10).rotateX(Math.PI / 2), this.housingBone, this.slots.emitter, new Matrix4().makeTranslation(0, 0.046, 0.01));
+ this.housingBone.scale.setScalar(1e-5);
// The blaster: the duel's model (chamfered for the close view). Its parts are baked into the rig on the gun's
// bone; the stock stays out (it would hide the right hand); the sight's pane becomes a see-through reticle.
@@ -304,7 +339,7 @@ export class Viewmodel {
bg.add(this.flashLight);
this.flashLight.position.copy(this.blaster.muzzle);
- this.rig.add(this.right.group, this.left.group, this.gun, this.key, this.key.target);
+ this.rig.add(this.gun, this.housingBone, this.key, this.key.target);
this.key.position.set(-0.4, 1, 0.5);
this.mesh = rig.build(pal.material);
// The mesh stays at the origin: its vertices follow the bones in the rig.
@@ -321,8 +356,91 @@ export class Viewmodel {
/** The person's colours changed (a promotion): repaint the sleeves. */
setColours(colours: ArmColours): void {
- this.palette.surface(this.slots.sleeve, this.tmpColour.set(colours.uniform), 0.78, 0);
- this.palette.surface(this.slots.trim, this.tmpColour.set(colours.trim), 0.55, 0.2);
+ this.colours = { ...colours };
+ const arms = this.arms;
+ if (!arms) return;
+ // The atlas multiplies the material colour (as on the body): the uniform by the tier, the hands gloved (or the skin
+ // as authored), each over the body's baked occlusion. The cuff's trim band wears the cloth too: up close its
+ // sawtooth edge (`CUT.trimLift`) would show as a change of tone.
+ const src = arms.source;
+ const gloves = VIEWMODEL.gloves;
+ const cloth = new Color(colours.uniform);
+ const tint: Record<ArmSlot, Color> = {
+ uniform: cloth, trim: cloth, skin: gloves ? new Color(gloves) : src.authored.skin, other: src.authored.other,
+ };
+ const order: ArmSlot[] = ["uniform", "trim", "skin", "other"];
+ const attr = arms.mesh.geometry.getAttribute("color") as BufferAttribute;
+ const c = attr.array as Float32Array;
+ for (let i = 0; i < src.occlusion.length; i++) {
+ const t = tint[order[src.slots[i]]];
+ const ao = src.occlusion[i];
+ c[i * 3] = t.r * ao;
+ c[i * 3 + 1] = t.g * ao;
+ c[i * 3 + 2] = t.b * ao;
+ }
+ attr.needsUpdate = true;
+ }
+
+ /** The arms are in (the body has loaded). */
+ get hasArms(): boolean {
+ return this.arms !== null;
+ }
+
+ /** The bones of the right and left arm (null before the body has loaded). */
+ get right(): ViewArm | null {
+ return this.arms?.right ?? null;
+ }
+
+ get left(): ViewArm | null {
+ return this.arms?.left ?? null;
+ }
+
+ /** The arms' skinned mesh (null before the body has loaded). */
+ get armsMesh(): SkinnedMesh | null {
+ return this.arms?.mesh ?? null;
+ }
+
+ /**
+ * The commander's body has loaded: rig and draw the arms cut from it (`cutArms`). The cut's geometry is taken over
+ * (disposed with the viewmodel); its atlas stays the body's. Replaces arms attached before.
+ */
+ attachArms(source: ArmsSource): void {
+ this.detachArms();
+ const right = new ViewArm(source.right);
+ const left = new ViewArm(source.left);
+ const material = new MeshStandardMaterial({
+ name: "M_View_Arms", map: source.map, normalMap: source.normalMap, roughnessMap: source.roughnessMap,
+ vertexColors: true, roughness: 1, metalness: 0, side: DoubleSide,
+ });
+ material.normalScale.set(source.normalScale[0], source.normalScale[1]);
+ const mesh = new SkinnedMesh(source.geometry, material);
+ mesh.name = "ViewmodelArms";
+ mesh.frustumCulled = false;
+ const skeleton = new Skeleton([...right.bones, ...left.bones], [...right.inverses(), ...left.inverses()]);
+ mesh.bind(skeleton, new Matrix4());
+ this.rig.add(right.group, left.group);
+ this.rig.traverse((o) => { o.frustumCulled = false; });
+ this.scene.add(mesh);
+ // The emitter rides on the left forearm.
+ left.emitter.add(this.housingBone);
+ this.housingBone.scale.setScalar(1);
+ this.arms = { right, left, mesh, material, source };
+ this.light.attach([material]);
+ this.retune();
+ }
+
+ private detachArms(): void {
+ const arms = this.arms;
+ if (!arms) return;
+ this.rig.add(this.housingBone);
+ this.housingBone.scale.setScalar(1e-5);
+ this.housingBone.position.set(0, 0, 0);
+ this.rig.remove(arms.right.group, arms.left.group);
+ this.scene.remove(arms.mesh);
+ arms.mesh.geometry.dispose();
+ arms.mesh.skeleton.dispose();
+ arms.material.dispose();
+ this.arms = null;
}
/** This frame's state (the layer fills it before the eye view renders). */
@@ -345,33 +463,33 @@ export class Viewmodel {
retune(): void {
const s = VIEWMODEL.gunScale;
this.blaster.group.scale.setScalar(s);
+ this.setColours(this.colours);
SHOULDER_R.copy(VIEWMODEL.shoulderR);
SHOULDER_L.copy(VIEWMODEL.shoulderL);
POLE_R.copy(VIEWMODEL.poleR).normalize();
POLE_L.copy(VIEWMODEL.poleL).normalize();
- // Right hand: the grip's axis runs up and back (the grip rakes 0.28 rad); the back of the hand faces the
- // blaster's right (−X), the knuckles wrap the grip's front and the fingers curl round to its left side.
- const up = new Vector3(0, Math.cos(0.28), -Math.sin(0.28));
- const backR = new Vector3(-1, 0, 0);
- const knR = new Vector3().crossVectors(up, backR);
const h = VIEWMODEL.hands;
const vec = (a: readonly number[]) => new Vector3(a[0], a[1], a[2]);
- const grip = new Vector3(0, -0.06, -0.01).multiplyScalar(this.blasterScale() * s);
- this.holdR.at.copy(grip).addScaledVector(up, h.grip[0]).addScaledVector(knR, h.grip[1]).addScaledVector(backR, h.grip[2]);
- ViewArm.handFrame(knR, backR, this.holdR.q);
- // Left hand: a clamp on the shroud from its left, the thumb over the top, the knuckles along the barrel, the back
- // of the hand outward; the fingers curl in under the shroud.
- const fore = this.blaster.fore.clone().multiplyScalar(s);
- const knL = vec(h.foreKnuckles).normalize();
- const backL = vec(h.foreBack).normalize();
- this.holdL.at.set(fore.x + h.fore[0], fore.y + h.fore[1], fore.z + h.fore[2]).addScaledVector(knL, -0.05);
- ViewArm.handFrame(knL, backL, this.holdL.q);
+ const bs = this.blasterScale() * s;
+ // A hold: the wrist where the held point sits at `at` in the hand's frame `q`.
+ const hold = (out: { at: Vector3; q: Quaternion }, point: Vector3, at: readonly number[]) => {
+ out.at.copy(point).sub(vec(at).applyQuaternion(out.q));
+ };
+ // Right hand: the grip's axis runs up and back (the grip rakes 0.28 rad) along the hand's width (the thumb's side
+ // up); the back of the hand faces the blaster's right (−X), the knuckles wrap the grip's front and the fingers
+ // curl round to its left side.
+ const up = new Vector3(0, Math.cos(0.28), -Math.sin(0.28));
+ const backR = new Vector3(-1, 0, 0);
+ ViewArm.handFrame(new Vector3().crossVectors(up, backR), backR, this.holdR.q);
+ hold(this.holdR, new Vector3(0, -0.06, -0.01).multiplyScalar(bs), h.grip);
+ // Left hand: under the shroud, the knuckles along the barrel, the back of the hand down and out to the left; the
+ // fingers curl up round the shroud's right side, the thumb lies along its left.
+ ViewArm.handFrame(vec(h.foreKnuckles), vec(h.foreBack), this.holdL.q);
+ hold(this.holdL, new Vector3(0, 0.012 * this.blasterScale(), this.blaster.fore.z).multiplyScalar(s), h.fore);
// Venting: the left hand leaves the shroud and slaps the receiver's side, palm flat against it.
- const vents = new Vector3(0.05, 0.02, 0.12).multiplyScalar(this.blasterScale() * s);
- const knV = vec(h.ventKnuckles).normalize();
- const backV = vec(h.ventBack).normalize();
- this.ventL.at.copy(vents).addScaledVector(backV, 0.018).addScaledVector(knV, -0.05);
- ViewArm.handFrame(knV, backV, this.ventL.q);
+ ViewArm.handFrame(vec(h.ventKnuckles), vec(h.ventBack), this.ventL.q);
+ hold(this.ventL, new Vector3(0.03, 0.0, 0.07).multiplyScalar(bs), h.vent);
+ this.solveHolds();
// On the deck: relaxed hands, knuckles ahead, the backs of the hands up and out (the left mirrors the right).
const dk = vec(h.deckKnuckles);
const db = vec(h.deckBack);
@@ -390,6 +508,107 @@ export class Viewmodel {
this.ads.roll = 0;
}
+ /**
+ * Close the hands on the blaster (the holds are fixed in its frame, so this holds for every pose): a search over
+ * the knuckle and middle joints of the fingers, so each finger's joints and tip rest on the held part's surface
+ * without sinking in (the right hand's three outer fingers round the grip, the left hand's four round the shroud),
+ * and the right index finger's pad on the trigger. Without arms: the layout's hand poses.
+ */
+ private solveHolds(): void {
+ copyHand(this.gripHand, VIEWMODEL.hands.gripPose);
+ copyHand(this.foreHand, VIEWMODEL.hands.forePose);
+ const arms = this.arms;
+ if (!arms) return;
+ const bs = this.blasterScale() * VIEWMODEL.gunScale;
+ // The grip: a box raked back 0.28 rad. The shroud: a cylinder along the barrel.
+ const gripC = new Vector3(0, -0.06, -0.01).multiplyScalar(bs);
+ const gripH = new Vector3(0.017, 0.0525, 0.021).multiplyScalar(bs);
+ const unrake = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), 0.28);
+ const q = new Vector3();
+ const grip = (p: Vector3): number => {
+ q.subVectors(p, gripC).applyQuaternion(unrake);
+ const x = Math.abs(q.x) - gripH.x;
+ const y = Math.abs(q.y) - gripH.y;
+ const z = Math.abs(q.z) - gripH.z;
+ return Math.hypot(Math.max(x, 0), Math.max(y, 0), Math.max(z, 0)) + Math.min(Math.max(x, y, z), 0);
+ };
+ const shroudY = 0.012 * bs;
+ const shroudR = 0.028 * bs;
+ const shroud = (p: Vector3): number => Math.hypot(p.x, p.y - shroudY) - shroudR;
+ const right = arms.right;
+ this.wrap(right, this.holdR, this.gripHand.fingers, [1, 2, 3], grip);
+ this.wrap(arms.left, this.holdL, this.foreHand.fingers, [1, 2, 3], shroud);
+ this.wrap(arms.left, this.holdL, this.foreHand.index, [0], shroud);
+ // The right index finger onto the trigger.
+ const target = this.trigger.position.clone().multiplyScalar(VIEWMODEL.gunScale);
+ const hand = new Matrix4().compose(this.holdR.at, this.holdR.q, new Vector3(1, 1, 1));
+ const chain = [0, 1, 2].map((j) => right.bones[fingerBone(0) + j]);
+ const m = new Matrix4();
+ const tip = new Vector3();
+ let best = Infinity;
+ let ba = this.gripHand.index[0];
+ let bb = this.gripHand.index[1];
+ for (let a = 0; a <= 1.6; a += 0.02) {
+ for (let b = 0; b <= 1.8; b += 0.02) {
+ this.gripHand.index[0] = a;
+ this.gripHand.index[1] = b;
+ right.curl(this.gripHand);
+ // The finger's pad (`indexTip`, on its end bone) against the trigger.
+ m.copy(hand);
+ for (const bone of chain) {
+ bone.updateMatrix();
+ m.multiply(bone.matrix);
+ }
+ const d = tip.copy(right.indexTip.position).applyMatrix4(m).distanceTo(target);
+ if (d < best) {
+ best = d;
+ ba = a;
+ bb = b;
+ }
+ }
+ }
+ this.gripHand.index[0] = ba;
+ this.gripHand.index[1] = bb;
+ right.curl(this.gripHand);
+ this.triggerReach = best;
+ }
+
+ /**
+ * Curl `fingers` of `arm` (holding at `hold`, in the blaster's frame) by the shared knuckle and middle joint
+ * angles `out` that rest them on the surface `sdf` (signed distance, metres): each joint and the tip a finger's
+ * thickness off it, sinking in costing eight times a gap.
+ */
+ private wrap(arm: ViewArm, hold: { at: Vector3; q: Quaternion }, out: [number, number], fingers: number[], sdf: (p: Vector3) => number): void {
+ const hand = new Matrix4().compose(hold.at, hold.q, new Vector3(1, 1, 1));
+ const pose = handPose(0, 0, 0);
+ const pts = [new Vector3(), new Vector3(), new Vector3(), new Vector3()];
+ let best = Infinity;
+ let ba = out[0];
+ let bb = out[1];
+ for (let a = 0; a <= 1.7; a += 0.025) {
+ for (let b = 0; b <= 1.9; b += 0.025) {
+ pose.fingers[0] = pose.index[0] = a;
+ pose.fingers[1] = pose.index[1] = b;
+ arm.curl(pose);
+ let cost = 0;
+ for (const f of fingers) {
+ arm.fingerPoints(f, pts);
+ for (const p of pts) {
+ const gap = sdf(p.applyMatrix4(hand)) - VIEWMODEL.fingerRadius;
+ cost += gap < 0 ? 64 * gap * gap : gap * gap;
+ }
+ }
+ if (cost < best) {
+ best = cost;
+ ba = a;
+ bb = b;
+ }
+ }
+ }
+ out[0] = ba;
+ out[1] = bb;
+ }
+
/**
* Called by the eye view once its camera is placed for the frame: follow
* its orientation, step the motion, pose the rig. `dt` in seconds.
@@ -471,6 +690,7 @@ export class Viewmodel {
}
// The room's reflections: the deck's environment is captured in the open room, the hands are in the body's shade.
this.palette.material.envMapIntensity = VIEWMODEL.envGain;
+ if (this.arms) this.arms.material.envMapIntensity = VIEWMODEL.envGain;
if (f.deck) this.light.update(f.deck, f.x, f.y, f.z, step);
}
@@ -497,13 +717,14 @@ export class Viewmodel {
this.wristR.copy(this.holdR.at).applyQuaternion(this.qGun).add(this.gun.position);
this.qHandR.copy(this.qGun).multiply(this.holdR.q);
const h = VIEWMODEL.hands;
- this.right.curl(h.gripPose);
- this.right.pose(SHOULDER_R, this.wristR, this.qHandR, POLE_R);
+ const arms = this.arms;
+ arms?.right.curl(this.gripHand);
+ arms?.right.pose(SHOULDER_R, this.wristR, this.qHandR, POLE_R);
// Left hand: on the shroud, against the receiver while venting, up before the face behind the shield.
this.wristL.copy(this.holdL.at).applyQuaternion(this.qGun).add(this.gun.position);
this.qHandL.copy(this.qGun).multiply(this.holdL.q);
- const hand = copyHand(this.handL, h.forePose);
+ const hand = copyHand(this.handL, this.foreHand);
if (w.vent > 1e-3) {
// A slap: the hand swings out and in against the receiver in the first quarter second, then rests there.
const t = Math.min(1, this.ventT / 0.2);
@@ -522,26 +743,29 @@ export class Viewmodel {
lerpHand(hand, h.shieldPose, w.shield);
}
if (w.down > 1e-3) this.wristL.y -= w.down * 0.5;
- this.left.curl(hand);
- this.left.pose(SHOULDER_L, this.wristL, this.qHandL, POLE_L);
+ arms?.left.curl(hand);
+ arms?.left.pose(SHOULDER_L, this.wristL, this.qHandL, POLE_L);
}
private poseDeck(o: { x: number; y: number; z: number; pitch: number; yaw: number; roll: number }, dip: number): void {
// Loose hands low in the frame; while walking they swing against each other with the stride.
const swing = Math.sin(this.motion.phase) * 0.05 * Math.min(1, this.motion.bob);
const c = VIEWMODEL.hands.deckPose;
- this.right.curl(c);
- this.left.curl(c);
+ const arms = this.arms;
+ if (!arms) return;
+ arms.right.curl(c);
+ arms.left.curl(c);
const d = VIEWMODEL.deckWrist;
// The deck's arms hang from the shoulders' usual place (the duel's support shoulder sits in for the hold).
this.v.set(-VIEWMODEL.shoulderR.x, VIEWMODEL.shoulderR.y, VIEWMODEL.shoulderR.z);
this.wristR.set(d.x + o.x, d.y + o.y - dip + Math.abs(swing) * 0.2, d.z + o.z - swing);
this.wristL.set(-d.x + o.x, d.y + o.y - dip + Math.abs(swing) * 0.2, d.z + o.z + swing);
- this.right.pose(SHOULDER_R, this.wristR, this.qDeckR, POLE_R);
- this.left.pose(this.v, this.wristL, this.qDeckL, DECK_POLE_L.set(-POLE_R.x, POLE_R.y, POLE_R.z));
+ arms.right.pose(SHOULDER_R, this.wristR, this.qDeckR, POLE_R);
+ arms.left.pose(this.v, this.wristL, this.qDeckL, DECK_POLE_L.set(-POLE_R.x, POLE_R.y, POLE_R.z));
}
dispose(): void {
+ this.detachArms();
this.mesh.geometry.dispose();
this.mesh.skeleton.dispose();
this.palette.dispose();