Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea/character's anatomy (bones, organs, pieces, hits) and its test
shinyobjectz90b2621d5bad
diff --git a/sdk/character/src/anatomy/bones.ts b/sdk/character/src/anatomy/bones.tsnew file mode 100644index 00000000..40ef37fd--- /dev/null+++ b/sdk/character/src/anatomy/bones.ts@@ -0,0 +1,182 @@+// The skeleton as bones, made from the body's own frame (frame.ts): the spine's 24 vertebrae and their discs, the+// sacrum, twelve pairs of ribs with their cartilages, the sternum, the clavicles and shoulder blades, the hip bones,+// the skull and jaw, and the long bones of the arms and legs. Shapes are simple (tubes, blobs), proportions an adult's+// (Gray's Anatomy, 1918, public domain: the ribs' slope, the sternum's levels, the vertebrae's sizes by region).+// Not yet: the bones of the hands and feet, the hyoid, the teeth.+import { frameOf, interp, type Frame } from "./frame";+import { blob, merge, smoothPath, tube, v, type Geo, type V3 } from "./mesh";+import { COLORS, piece, type Piece } from "./piece";++const I3: [V3, V3, V3] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];+const ball = (c: V3, r: V3, n = 16): Geo => blob(c, I3, r, () => 1, n, Math.round(n * 0.6));+const sides = [["Left", 1], ["Right", -1]] as const;++function spine(F: Frame): Piece[] {+ const k = F.k, out: Piece[] = [];+ for (const [i, vt] of F.vertebrae.entries()) {+ const reg = vt.name[0] as "C" | "T" | "L", c = F.spine(vt.y), h = vt.h;+ const [bx, bz] = reg === "L" ? [0.021, 0.016] : reg === "T" ? [0.0135, 0.0125] : [0.009, 0.008];+ const W = (r: number) => r * k * (reg === "T" ? 1 + 0.25 * (+vt.name.slice(1) / 12) : 1);+ const parts: Geo[] = [tube([v.add(c, [0, -0.36 * h, 0]), v.add(c, [0, 0.36 * h, 0])], () => [W(bx), W(bz)], 12, [1, 0, 0])];+ // the arch round the canal, its spinous process back (and down in the chest) and the transverse processes+ const canal = W(reg === "C" ? 0.007 : 0.008), cz = c[2] - W(bz) - canal - 0.002 * k;+ const arch: V3[] = [[canal * 1.1, c[1], c[2] - W(bz) * 0.6]];+ for (let a = 0; a <= 8; a++) { const t = Math.PI * (a / 8); arch.push([canal * 1.1 * Math.cos(t), c[1], cz - canal * Math.sin(t)]); }+ arch.push([-canal * 1.1, c[1], c[2] - W(bz) * 0.6]);+ parts.push(tube(arch, () => [0.0035 * k, 0.0035 * k], 6));+ const back = cz - canal, room = back - (F.skin(vt.y).back + 0.012 * k);+ const sp = reg === "L" ? [0.03, -0.004] : reg === "T" ? [0.03, -0.022] : [0.016, -0.006];+ const len = Math.min(sp[0] * k, Math.max(0.006 * k, room));+ parts.push(tube([[0, c[1], back], [0, c[1] + (sp[1] * k * len) / (sp[0] * k), back - len]], (t) => [0.006 * k * (1 - 0.4 * t), 0.0025 * k], 6, [0, 1, 0]));+ const tp = (reg === "L" ? 0.034 : reg === "T" ? 0.026 : 0.017) * k;+ for (const s of [1, -1]) parts.push(tube([[s * canal, c[1], cz], [s * (canal + tp), c[1] + (reg === "T" ? 0.004 * k : 0), cz - (reg === "T" ? 0.012 * k : 0.002 * k)]], (t) => [0.0045 * k * (1 - 0.3 * t), 0.003 * k], 6));+ const joint = reg === "C" ? (+vt.name.slice(1) <= 4 ? "Neck2" : "Neck1") : reg === "T" ? (+vt.name.slice(1) <= 10 ? "Chest" : "Spine2") : (+vt.name.slice(1) <= 2 ? "Spine2" : "Spine1");+ out.push(piece(F, `vertebra-${vt.name}`, "bone", joint, merge(...parts), COLORS.bone, 0.55));+ // the disc under it+ const next = F.vertebrae[i + 1];+ if (next && vt.name !== "C1") {+ const d = F.spine(vt.y - 0.5 * h);+ out.push(piece(F, `disc-${vt.name}-${next.name}`, "cartilage", joint, tube([v.add(d, [0, -0.13 * h, 0]), v.add(d, [0, 0.13 * h, 0])], () => [W(bx) * 0.92, W(bz) * 0.92], 12, [1, 0, 0]), COLORS.cartilage, 0.4));+ }+ }+ // the sacrum and coccyx: curving back and down from L5, narrowing+ const s0 = F.spine(F.y.L5), path = smoothPath([s0, v.add(s0, [0, -0.04 * k, -0.012 * k]), v.add(s0, [0, -0.08 * k, -0.03 * k]), v.add(s0, [0, -0.115 * k, -0.052 * k])], 14);+ out.push(piece(F, "sacrum", "bone", "Hips", tube(path, (t) => [interp([0, 0.4, 0.7, 1], [0.05, 0.042, 0.022, 0.008], t) * k, interp([0, 1], [0.013, 0.005], t) * k], 12, [1, 0, 0]), COLORS.bone, 0.55));+ return out;+}++/** where each true rib meets the sternum, as a fraction of the way from the jugular notch to the xiphisternal joint */+const STERNAL = [0.08, 0.32, 0.5, 0.65, 0.79, 0.92, 1.0];+/** how far each true rib's cartilage climbs from its rib's end to the sternum */+const RISE = [0, 0, 0.005, 0.012, 0.02, 0.03, 0.045];+/** where each rib's bone ends round its loop (pi at the front's middle) */+const BONY_END = [0.8, 0.82, 0.8, 0.78, 0.76, 0.74, 0.72, 0.72, 0.7, 0.68, 0.58, 0.45];+const RIB_R = [0.0048, 0.0058, 0.0062, 0.0065, 0.0066, 0.0066, 0.0065, 0.0063, 0.006, 0.0056, 0.005, 0.0045];++function sternum(F: Frame) {+ const k = F.k, j = F.y.jug, x = F.y.xiph;+ const ys = [j, j - 0.25 * (j - x), x, F.y.xtip];+ const half = (y: number) => interp([F.y.xtip, x, j - 0.27 * (j - x), j - 0.2 * (j - x), j], [0.006, 0.014, 0.017, 0.014, 0.026], y) * k;+ const at = (y: number): V3 => [0, y, F.cage(y).front - 0.002 * k];+ return { half, at, geo: tube(smoothPath(ys.map(at), 16), (t) => [half(interp([0, 1], [j, F.y.xtip], t)), 0.0055 * k], 12, [1, 0, 0]) };+}++function ribs(F: Frame): Piece[] {+ const k = F.k, out: Piece[] = [], st = sternum(F), dT = F.vertebrae.find((q) => q.name === "T1")!.h;+ out.push(piece(F, "sternum", "bone", "Chest", st.geo, COLORS.bone, 0.55));+ const joinAt: Record<number, V3> = {};+ for (const [side, s] of sides) {+ for (let i = 1; i <= 12; i++) {+ const yh = F.y.T1 - (i - 0.5) * dT, sp = F.spine(yh);+ const ys = i <= 7 ? F.y.jug - STERNAL[i - 1] * (F.y.jug - F.y.xiph) : F.y.xiph - (i - 7) * 0.026 * k;+ const yEnd = ys - (i <= 7 ? RISE[i - 1] : 0.045) * k;+ const pe = BONY_END[i - 1] * Math.PI, w = F.cage(yh - 0.4 * (yh - yEnd)).half * (i >= 11 ? 0.94 : 1);+ // the bony rib: from its head on the vertebra back and out to its angle, round the side and down to its end+ const yOf = (phi: number) => yh - (yh - yEnd) * Math.pow(phi / pe, 1.5);+ const loop: V3[] = [];+ for (let q = 0; q <= 14; q++) { const phi = 0.1 * Math.PI + (pe - 0.1 * Math.PI) * (q / 14); loop.push(F.wall(yOf(phi), phi, s, w)); }+ const path = smoothPath([[s * 0.016 * k, yh, sp[2]], [s * 0.03 * k, yh, sp[2] - 0.012 * k], ...loop], 40);+ const r = RIB_R[i - 1] * k, joint = i <= 9 ? "Chest" : "Spine2";+ out.push(piece(F, `rib-${i}-${side.toLowerCase()}`, "bone", joint, tube(path, (t) => [r * (t < 0.08 ? 0.7 : 1) * (1 - 0.2 * t * t), r * 0.45], 8), COLORS.bone, 0.55));+ // its cartilage: a true rib's to the sternum's edge, rising; ribs 8 to 10's up to the cartilage over them+ const end = path[path.length - 1];+ let to: V3 | undefined;+ if (i <= 7) to = [s * st.half(ys) * 0.95, ys, st.at(ys)[2]];+ else if (i <= 10) to = joinAt[s * 100 + i - 1];+ if (to) {+ const mid: V3 = v.lerp(end, to, 0.5);+ const cp = smoothPath([end, [mid[0] * 1.04, mid[1] - (i <= 7 ? 0.004 * k : 0.008 * k), mid[2] + 0.004 * k], to], 14);+ out.push(piece(F, `cartilage-${i}-${side.toLowerCase()}`, "cartilage", "Chest", tube(cp, () => [r * 0.85, r * 0.5], 8), COLORS.cartilage, 0.4));+ joinAt[s * 100 + i] = cp[Math.round(cp.length * 0.45)];+ }+ }+ }+ return out;+}++function girdle(F: Frame): Piece[] {+ const k = F.k, out: Piece[] = [], dT = F.vertebrae.find((q) => q.name === "T1")!.h;+ for (const [side, s] of sides) {+ const arm = F.joint(`${side}Arm`), j = F.y.jug, f = F.cage(j).front;+ const acromion: V3 = [arm[0] - s * 0.012 * k, arm[1] + 0.035 * k, arm[2] + 0.004 * k];+ const clav = smoothPath([[s * 0.022 * k, j + 0.006 * k, f - 0.004 * k], [s * 0.06 * k, j + 0.012 * k, f - 0.004 * k], [s * 0.11 * k, j + 0.02 * k, f - 0.018 * k], acromion], 24);+ out.push(piece(F, `clavicle-${side.toLowerCase()}`, "bone", `${side}Shoulder`, tube(clav, (t) => [0.0068 * k * (1 + 0.3 * t), 0.0055 * k], 8), COLORS.bone, 0.55));+ // the shoulder blade: a triangular blade on the back of the ribs from its upper angle to its lower, its spine up+ // to the acromion and its neck out to the socket under it+ const yTop = F.y.T1 - 1.5 * dT, yLow = F.y.T1 - 7 * dT;+ const onBack = (x: number, y: number): V3 => [x, y, F.cage(y).back - 0.006 * k + (Math.abs(x) - 0.06 * k) * 0.45];+ const blade: V3[] = Array.from({ length: 9 }, (_, q) => { const t = q / 8, y = yTop + (yLow - yTop) * t, hw = interp([0, 0.3, 1], [0.042, 0.048, 0.004], t) * k; return onBack(s * (0.068 * k + hw * 0.9), y); });+ const bw = (t: number) => interp([0, 0.3, 1], [0.042, 0.048, 0.006], t) * k;+ const geo = merge(+ tube(blade, (t) => [bw(t), 0.0035 * k], 10, [s, 0, 0.35]),+ tube(smoothPath([onBack(s * 0.07 * k, F.y.T1 - 2.4 * dT), onBack(s * 0.12 * k, F.y.T1 - 2.0 * dT), [acromion[0], acromion[1] - 0.006 * k, acromion[2] - 0.012 * k]], 12), () => [0.0075 * k, 0.004 * k], 8),+ tube([onBack(s * 0.13 * k, F.y.T1 - 2.8 * dT), [arm[0] - s * 0.024 * k, arm[1] - 0.004 * k, arm[2] - 0.008 * k]], (t) => [0.011 * k * (1 + 0.6 * t), 0.01 * k], 10),+ );+ out.push(piece(F, `scapula-${side.toLowerCase()}`, "bone", `${side}Shoulder`, geo, COLORS.bone, 0.55));+ }+ return out;+}++function pelvis(F: Frame): Piece[] {+ const k = F.k, out: Piece[] = [], L5 = F.y.L5, sp = F.spine(L5);+ for (const [side, s] of sides) {+ const H = F.joint(`${side}Leg`), front = (y: number) => F.skin(y).front;+ const crest: V3[] = [[s * 0.042 * k, L5 + 0.02 * k, sp[2] - 0.035 * k], [s * 0.09 * k, L5 + 0.045 * k, sp[2] - 0.022 * k], [s * 0.125 * k, L5 + 0.05 * k, sp[2] + 0.015 * k], [s * 0.118 * k, H[1] + 0.07 * k, front(H[1] + 0.07 * k) - 0.022 * k]];+ const wing = smoothPath(crest.map((p, q) => [p[0] * (q === 3 ? 0.98 : 0.97), p[1] - 0.032 * k, p[2] + (q === 0 ? 0.008 * k : 0)] as V3), 20);+ const sym: V3 = [s * 0.011 * k, H[1] - 0.03 * k, front(H[1] - 0.04 * k) - 0.035 * k];+ const tub: V3 = [s * 0.055 * k, H[1] - 0.075 * k, H[2] - 0.035 * k];+ const sock = Array.from({ length: 13 }, (_, q) => { const a = (2 * Math.PI * q) / 12; return [H[0] + s * 0.012 * k, H[1] + 0.027 * k * Math.cos(a), H[2] + 0.027 * k * Math.sin(a)] as V3; });+ const geo = merge(+ tube(wing, (t) => [interp([0, 0.5, 1], [0.03, 0.04, 0.022], t) * k, 0.0045 * k], 10, [0, 1, 0]),+ tube(smoothPath([wing[10], v.lerp(wing[10], H, 0.55), [H[0] + s * 0.004 * k, H[1] + 0.02 * k, H[2]]], 10), () => [0.016 * k, 0.008 * k], 10, [0, 0, 1]),+ tube(sock, () => [0.006 * k, 0.006 * k], 8, [s, 0, 0]),+ tube(smoothPath([[H[0] - s * 0.01 * k, H[1] - 0.012 * k, H[2] + 0.022 * k], v.lerp([H[0], H[1], H[2] + 0.03 * k], sym, 0.5), sym], 10), () => [0.008 * k, 0.006 * k], 8),+ tube(smoothPath([[H[0] - s * 0.004 * k, H[1] - 0.026 * k, H[2] - 0.012 * k], tub, [s * 0.03 * k, H[1] - 0.07 * k, sym[2] - 0.03 * k], [sym[0], sym[1] - 0.022 * k, sym[2] - 0.004 * k]], 16), (t) => [interp([0, 0.3, 1], [0.011, 0.013, 0.006], t) * k, 0.008 * k], 8),+ tube([[s * 0.04 * k, L5 - 0.01 * k, sp[2] - 0.03 * k], wing[2]], () => [0.012 * k, 0.008 * k], 8),+ );+ out.push(piece(F, `hip-bone-${side.toLowerCase()}`, "bone", "Hips", geo, COLORS.bone, 0.55));+ }+ return out;+}++function skull(F: Frame): Piece[] {+ const k = F.k, l = F.joint("LeftEye"), r = F.joint("RightEye"), e = v.lerp(l, r, 0.5);+ // (measured on gb-sentry's fitted head, 11-17: the crown 1.761 over the eyes' 1.649, the back of the head 18.8 cm behind+ // them: the cranium 8 mm under the crown and 1 cm inside the back)+ const cranium = blob(v.add(e, [0, 0.03 * k, -0.08 * k]), I3, [0.071 * k, 0.074 * k, 0.098 * k], (u) => 1 - 0.1 * Math.max(0, -u[1]) - 0.04 * Math.max(0, u[2]) * Math.max(0, -u[1]), 32, 22);+ // (a face 10 cm across under the cranium read as a snowman's second ball, 11-17: as wide as the cheekbones, set back+ // into the cranium and narrowing to the upper jaw, with the cheekbones' arches back to the ears)+ const face = blob(v.add(e, [0, -0.03 * k, -0.03 * k]), I3, [0.058 * k, 0.05 * k, 0.05 * k], (u) => (1 - 0.3 * Math.max(0, -u[1])) * (1 - 0.12 * Math.max(0, -u[2])), 26, 18);+ const arches = [1, -1].map((s) => tube(smoothPath([v.add(e, [s * 0.048 * k, -0.022 * k, -0.012 * k]), v.add(e, [s * 0.062 * k, -0.024 * k, -0.04 * k]), v.add(e, [s * 0.064 * k, -0.026 * k, -0.065 * k])], 10), () => [0.007 * k, 0.004 * k], 8));+ // the upper jaw and its teeth, between the face and the lower jaw+ const maxilla = blob(v.add(e, [0, -0.078 * k, -0.004 * k]), I3, [0.031 * k, 0.017 * k, 0.03 * k], (u) => 1 - 0.2 * Math.max(0, -u[2]), 20, 12);+ const pieces = [piece(F, "skull", "bone", "Head", merge(cranium, face, maxilla, ...arches), COLORS.bone, 0.5)];+ const jaw = smoothPath([[0.05 * k, -0.035 * k, -0.07 * k], [0.048 * k, -0.087 * k, -0.058 * k], [0.034 * k, -0.105 * k, -0.012 * k], [0, -0.114 * k, 0.012 * k], [-0.034 * k, -0.105 * k, -0.012 * k], [-0.048 * k, -0.087 * k, -0.058 * k], [-0.05 * k, -0.035 * k, -0.07 * k]].map((p) => v.add(e, p as V3)), 30);+ const hasJaw = (() => { try { F.joint("Jaw"); return true; } catch { return false; } })();+ pieces.push(piece(F, "mandible", "bone", hasJaw ? "Jaw" : "Head", tube(jaw, (t) => [interp([0, 0.15, 0.5, 0.85, 1], [0.016, 0.013, 0.011, 0.013, 0.016], t) * k, 0.0045 * k], 8, [0, 1, 0]), COLORS.bone, 0.5));+ return pieces;+}++function limbs(F: Frame): Piece[] {+ const k = F.k, out: Piece[] = [];+ const shaft = (a: V3, b: V3, r: number, ends: [number, number], n = 12): Geo => tube(smoothPath([a, v.lerp(a, b, 0.5), b], n), (t) => { const q = r * (1 + ends[0] * Math.max(0, 1 - t / 0.12) ** 2 + ends[1] * Math.max(0, (t - 0.88) / 0.12) ** 2); return [q, q]; }, 10);+ const off = (a: V3, b: V3, d: number): V3 => { const ax = v.norm(v.sub(b, a)); return v.mul(v.norm(v.cross(ax, Math.abs(ax[1]) > 0.9 ? [1, 0, 0] : [0, 1, 0])), d); };+ for (const [side, s] of sides) {+ const L = side.toLowerCase(), arm = F.joint(`${side}Arm`), fore = F.joint(`${side}ForeArm`), hand = F.joint(`${side}Hand`);+ out.push(piece(F, `humerus-${L}`, "bone", `${side}Arm`, merge(ball(v.add(arm, [-s * 0.004 * k, 0.004 * k, -0.003 * k]), [0.023 * k, 0.023 * k, 0.023 * k]), shaft(arm, fore, 0.0105 * k, [0.6, 0.9])), COLORS.bone, 0.55));+ const o = off(fore, hand, 0.009 * k);+ out.push(piece(F, `radius-${L}`, "bone", `${side}ForeArm`, shaft(v.add(fore, o), v.add(hand, v.mul(o, 1.3)), 0.0068 * k, [0.4, 1.1]), COLORS.bone, 0.55));+ out.push(piece(F, `ulna-${L}`, "bone", `${side}ForeArm`, shaft(v.sub(fore, o), v.sub(hand, v.mul(o, 0.7)), 0.0062 * k, [1.0, 0.3]), COLORS.bone, 0.55));+ const hip = F.joint(`${side}Leg`), knee = F.joint(`${side}Shin`), ankle = F.joint(`${side}Foot`);+ const troch: V3 = [hip[0] + s * 0.045 * k, hip[1] - 0.02 * k, hip[2] - 0.004 * k];+ out.push(piece(F, `femur-${L}`, "bone", `${side}Leg`, merge(ball(hip, [0.024 * k, 0.024 * k, 0.024 * k]), tube([hip, troch], () => [0.014 * k, 0.012 * k], 10), shaft(troch, v.add(knee, [0, 0.012 * k, 0]), 0.0135 * k, [0.4, 1.0])), COLORS.bone, 0.55));+ out.push(piece(F, `patella-${L}`, "bone", `${side}Shin`, blob(v.add(knee, [0, 0.012 * k, 0.04 * k]), I3, [0.021 * k, 0.023 * k, 0.009 * k], () => 1, 16, 10), COLORS.bone, 0.55));+ out.push(piece(F, `tibia-${L}`, "bone", `${side}Shin`, merge(blob(v.add(knee, [0, -0.012 * k, 0]), I3, [0.036 * k, 0.012 * k, 0.028 * k], () => 1, 18, 10), shaft(v.add(knee, [0, -0.012 * k, 0]), v.add(ankle, [-s * 0.004 * k, 0.012 * k, 0]), 0.012 * k, [0.5, 0.6])), COLORS.bone, 0.55));+ out.push(piece(F, `fibula-${L}`, "bone", `${side}Shin`, shaft(v.add(knee, [s * 0.03 * k, -0.022 * k, -0.012 * k]), v.add(ankle, [s * 0.028 * k, -0.008 * k, -0.008 * k]), 0.006 * k, [0.6, 0.6]), COLORS.bone, 0.55));+ }+ return out;+}++export function bonesOf(skel: Parameters<typeof frameOf>[0], F: Frame = frameOf(skel)): Piece[] {+ return [...spine(F), ...ribs(F), ...girdle(F), ...pelvis(F), ...skull(F), ...limbs(F)];+}diff --git a/sdk/character/src/anatomy/draw.tsx b/sdk/character/src/anatomy/draw.tsxnew file mode 100644index 00000000..fb870ce6--- /dev/null+++ b/sdk/character/src/anatomy/draw.tsx@@ -0,0 +1,141 @@+// Drawing a body's anatomy where its pose puts it, and the X-ray that shows it: the skin and what the body wears made+// translucent over bright bone and tinted organs, the path of a shot through them, and the wounds where it went in+// and out.+//+// const A = anatomyOf(sentrySkel), shot = hits(sentrySkel, pose, A, muzzle, dir);+// <Character body=... pose={pose} ghost={xrayGhost(t)} parts={xrayParts(parts, t)} />+// <Anatomy skel={sentrySkel} pose={pose} anatomy={A} name="sentry" xray={t} />+// <ShotPath from={muzzle} to={shot.at(-1)!.exit} name="sentry" /> <Wounds hits={shot} name="sentry" />+import { Fragment } from "react";+import { pose as posed, qmul, qyaw, skinJoints, toScene, type CharacterGhost, type CharacterPart, type Placement, type Pose, type Skeleton } from "../character/all";+import { BufferMesh } from "@raea/render/3d";+import { LinearRgba, Mesh3d, Srgba, StandardMaterial, Transform } from "@raea/render/bevy3d";+import type { Hit } from "./hits";+import { blob, tube, type V3 } from "./mesh";+import type { Piece } from "./piece";++const mix = (a: number, b: number, t: number) => a + (b - a) * t;+const glow = (hex: string, s: number) => LinearRgba.from(Srgba.hex(hex)).mul(s);++/** what an X-ray shows of each kind: bone near white and bright, organs in their colour, dimmer */+const XRAY: Record<string, { color: string; glow: number }> = {+ bone: { color: "#f2f6ff", glow: 2.2 }, cartilage: { color: "#b9d4e6", glow: 1.0 }, organ: { color: "", glow: 0.9 }, vessel: { color: "", glow: 1.1 }, airway: { color: "#cfe3f2", glow: 0.8 },+};++export interface AnatomyProps {+ skel: Skeleton;+ pose: Pose;+ anatomy: { pieces: Piece[] };+ /** where the body stands (the same as its <Character>'s) */+ at?: Placement;+ /** names its meshes: `${name}-anatomy-${piece}` */+ name: string;+ /** which pieces to draw (all by default) */+ show?: (p: Piece) => boolean;+ /** 0 as the pieces are, 1 as an X-ray shows them (lit from within); between, a fade */+ xray?: number;+ /** the pieces a shot has gone through so far (their names, as hits() gives them), drawn flushed red and glowing */+ struck?: string[];+}++const STRUCK = "#ff3b2f";++export function Anatomy({ skel, pose, anatomy, at = {}, name, show, xray = 0, struck = [] }: AnatomyProps) {+ const hit = new Set(struck);+ const J = new Map(skinJoints(skel, posed(skel, pose)).map((j) => [j.name, j]));+ const turn = qyaw(at.yaw ?? 0), k = at.scale ?? 1;+ return (+ <>+ {anatomy.pieces.filter((p) => (show ? show(p) : true)).map((p) => {+ const j = J.get(p.joint);+ if (!j) return null;+ const x = XRAY[p.kind], plain = xray > 0 && x.color ? x.color : p.color, struckNow = hit.has(p.name);+ const color = struckNow ? STRUCK : plain;+ return (+ // (organs press on each other and the aorta leaves the heart: the pieces of a body touch by nature)+ <Mesh3d key={p.name} name={`${name}-anatomy-${p.name}`} allowOverlap transform={Transform.fromTranslation(toScene(at, j.pos) as V3).withRotation(qmul(turn, j.rot)).withScale(k)}>+ <BufferMesh positions={p.geo.positions} normals={p.geo.normals} indices={p.geo.indices} />+ <StandardMaterial base_color={color} perceptual_roughness={mix(p.roughness, 0.9, xray)} {...(struckNow ? { emissive: glow(STRUCK, 1.5 + 2.5 * xray) } : xray > 0 ? { emissive: glow(color, x.glow * xray) } : {})} />+ </Mesh3d>+ );+ })}+ </>+ );+}++/** the skin as an X-ray shows it: a pale translucent film over what is inside, more see-through as `t` goes to 1+ * (undefined at 0: the skin as it is) */+export function xrayGhost(t: number, color = "#9cc6e4"): CharacterGhost | undefined {+ if (t <= 0) return undefined;+ return { color, opacity: mix(0.55, 0.1, t), emissive: "#1d3a52", emissiveIntensity: t, unlit: true };+}++/** what the body wears (and its head and hair) made translucent the same way */+export function xrayParts(parts: CharacterPart[], t: number, color = "#a9cde6"): CharacterPart[] {+ if (t <= 0) return parts;+ // (lit, not unlit: a <Model> takes an unlit material only drawn flat, as the ghost's body is, and a part is not)+ return parts.map((p) => ({ ...p, children: <StandardMaterial base_color_texture={null} base_color={Srgba.hex(color).with_alpha(mix(0.45, 0.07, t))} alpha_mode="Blend" perceptual_roughness={0.9} emissive={glow("#1d3a52", 1.5 * t)} /> }));+}++/** the path of a shot as a thin glowing line, from where it was fired to where it stops */+export function ShotPath({ from, to, name, color = "#ffb347", radius = 0.0025 }: { from: V3; to: V3; name: string; color?: string; radius?: number }) {+ const g = tube([from, to], () => [radius, radius], 8);+ return (+ <Mesh3d name={`${name}-shot-path`}>+ <BufferMesh positions={g.positions} normals={g.normals} indices={g.indices} />+ <StandardMaterial base_color={color} emissive={glow(color, 6)} unlit />+ </Mesh3d>+ );+}++/** the wounds a shot leaves: a small dark hole where it went into the skin and a larger torn one where it came out,+ * each laid on the skin square to the path (a garment over the skin is marked `cloth` metres further out). With+ * `travelled` (metres the bullet has gone from the shot's origin, as hits()'s t0 and t1 count), each appears only once+ * the bullet is past it. */+export function Wounds({ hits, name, cloth = 0, travelled = Infinity }: { hits: Hit[]; name: string; cloth?: number; travelled?: number }) {+ const skin = hits.find((h) => h.part === "skin");+ if (!skin || travelled < skin.t0 - cloth) return null;+ const d = ((a: V3, b: V3) => { const v: V3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], l = Math.hypot(...v) || 1; return [v[0] / l, v[1] / l, v[2] / l] as V3; })(skin.entry, skin.exit);+ const mark = (at: V3, r: number, out: number) => {+ const p: V3 = [at[0] + d[0] * out, at[1] + d[1] * out, at[2] + d[2] * out];+ const a0: V3 = Math.abs(d[1]) < 0.9 ? [d[2], 0, -d[0]] : [1, 0, 0], l = Math.hypot(...a0), u: V3 = [a0[0] / l, a0[1] / l, a0[2] / l];+ const w: V3 = [d[1] * u[2] - d[2] * u[1], d[2] * u[0] - d[0] * u[2], d[0] * u[1] - d[1] * u[0]];+ return blob(p, [u, w, d], [r, r, r * 0.25], (q) => 1 + (r > 0.008 ? 0.18 * Math.sin(7 * Math.atan2(q[1], q[0])) : 0), 18, 8);+ };+ const out = travelled >= skin.t1;+ const marks = [+ { key: "entry", g: mark(skin.entry, 0.0045, -0.001), c: "#1a0605" },+ ...(out ? [{ key: "exit", g: mark(skin.exit, 0.012, 0.001), c: "#3a0907" }] : []),+ ...(cloth > 0 ? [{ key: "entry-cloth", g: mark(skin.entry, 0.005, -cloth), c: "#0d0806" }, ...(travelled >= skin.t1 + cloth ? [{ key: "exit-cloth", g: mark(skin.exit, 0.014, cloth), c: "#160b08" }] : [])] : []),+ ];+ return (+ <>+ {marks.map((m) => (+ <Fragment key={m.key}>+ <Mesh3d name={`${name}-wound-${m.key}`}>+ <BufferMesh positions={m.g.positions} normals={m.g.normals} indices={m.g.indices} />+ <StandardMaterial base_color={m.c} perceptual_roughness={0.35} />+ </Mesh3d>+ </Fragment>+ ))}+ </>+ );+}++/** The bullet itself, at `at` heading along `dir`: a spitzer (pointed) round, by default the German S-Patrone's 7.92 mm+ * across and 28 mm long, cupro-nickel jacketed; `glow` lights it (an X-ray shows metal brightest of all). */+export function Round({ at, dir, name, caliber = 0.00792, length = 0.028, glow: g = 0 }: { at: V3; dir: V3; name: string; caliber?: number; length?: number; glow?: number }) {+ const l = Math.hypot(...dir) || 1, d: V3 = [dir[0] / l, dir[1] / l, dir[2] / l];+ // (its body a cylinder, then the ogive narrowing to a point over the front 45%, as the spitzer's does)+ const R = caliber / 2, tail: V3 = [at[0] - d[0] * length / 2, at[1] - d[1] * length / 2, at[2] - d[2] * length / 2];+ const path = Array.from({ length: 16 }, (_, i) => [tail[0] + d[0] * length * i / 15, tail[1] + d[1] * length * i / 15, tail[2] + d[2] * length * i / 15] as V3);+ const r = (t: number) => { const x = t < 0.55 ? (t < 0.06 ? 0.86 + 2.3 * t : 1) : Math.sqrt(Math.max(0, 1 - ((t - 0.55) / 0.45) ** 2)); return [R * Math.max(x, 0.02), R * Math.max(x, 0.02)] as [number, number]; };+ const geo = tube(path, r, 14);+ const c = "#b9a27a";+ return (+ <Mesh3d name={`${name}-round`} allowOverlap>+ <BufferMesh positions={geo.positions} normals={geo.normals} indices={geo.indices} />+ <StandardMaterial base_color={c} metallic={0.9} perceptual_roughness={0.3} {...(g > 0 ? { emissive: glow("#ffe6b0", 4 * g) } : {})} />+ </Mesh3d>+ );+}diff --git a/sdk/character/src/anatomy/frame.ts b/sdk/character/src/anatomy/frame.tsnew file mode 100644index 00000000..7f6e084b--- /dev/null+++ b/sdk/character/src/anatomy/frame.ts@@ -0,0 +1,102 @@+// Where the inside of a body is, read off its own skeleton and skin (skeleton.json's joints and `surface` samples):+// the spine's levels between its joints, the line its vertebrae stand on, and the rib cage's inner wall at any height,+// so a short broad body gets a short broad rib cage. Metres in the body's frame at rest (+z ahead, +y up, left +x).+import type { Skeleton } from "../character/all";+import type { V3 } from "./mesh";++export interface Frame {+ /** how big the body is against SOMA's 1.75 m man (the trunk's length between Hips and Neck1) */+ k: number;+ joint: (name: string) => V3;+ /** heights: the top of T1, the jugular notch, the sternum's xiphisternal joint and the xiphoid's tip, the bottom of+ * T12 and of L5; each vertebra's middle (C1..C7, T1..T12, L1..L5 in order) and height */+ y: { T1: number; jug: number; xiph: number; xtip: number; T12: number; L5: number };+ vertebrae: { name: string; y: number; h: number }[];+ /** the skin's front and back at the midline and its half-width, at a height (smoothed from the samples) */+ skin: (y: number) => { front: number; back: number; half: number };+ /** a vertebral body's middle at a height (x 0) */+ spine: (y: number) => V3;+ /** the rib cage's inner wall at a height: its back (behind the ribs' angles), front (behind the sternum), the depth+ * its widest point is at, and its half-width there (`w`, the rib's own when given) */+ cage: (y: number, w?: number) => { back: number; front: number; mid: number; half: number };+ /** a point on the cage's wall: phi 0 at the back's midline, pi/2 at the side, pi at the front; side +1 left, -1 right */+ wall: (y: number, phi: number, side: number, w?: number, inset?: number) => V3;+}++const TRUNK = /^(chest|torso|waist|hips|neck)$/;+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;++/** a curve through (x, y) knots, linear between them and flat past the ends */+export function interp(xs: number[], ys: number[], x: number): number {+ if (x <= xs[0]) return ys[0];+ for (let i = 1; i < xs.length; i++) if (x <= xs[i]) return lerp(ys[i - 1], ys[i], (x - xs[i - 1]) / (xs[i] - xs[i - 1]));+ return ys[ys.length - 1];+}++export function frameOf(skel: Skeleton): Frame {+ const J = new Map(skel.joints.map((j) => [j.name, j.head as V3]));+ const joint = (n: string): V3 => {+ const h = J.get(n);+ if (!h) throw new Error(`anatomy: ${skel.name} has no joint ${n} (a SOMA body's skeleton is needed)`);+ return h;+ };+ const hips = joint("Hips"), sp1 = joint("Spine1"), sp2 = joint("Spine2"), chest = joint("Chest"), n1 = joint("Neck1"), n2 = joint("Neck2"), head = joint("Head");+ const k = (n1[1] - hips[1]) / 0.459;++ // the levels: T1's top at Neck1, T12's bottom a little under Chest, L5's under Hips; C1 to C7 up to the skull+ const T1 = n1[1], T12 = chest[1] - 0.02 * k, L5 = hips[1] + 0.02 * k;+ const dT = (T1 - T12) / 12, dL = (T12 - L5) / 5, dC = (head[1] - 0.004 * k - T1) / 7;+ const vertebrae: Frame["vertebrae"] = [];+ for (let i = 0; i < 7; i++) vertebrae.push({ name: `C${i + 1}`, y: head[1] - 0.004 * k - (i + 0.5) * dC, h: dC });+ for (let i = 0; i < 12; i++) vertebrae.push({ name: `T${i + 1}`, y: T1 - (i + 0.5) * dT, h: dT });+ for (let i = 0; i < 5; i++) vertebrae.push({ name: `L${i + 1}`, y: T12 - (i + 0.5) * dL, h: dL });+ const y = { T1, jug: T1 - 2.5 * dT, xiph: T1 - 8.5 * dT, xtip: T1 - 8.5 * dT - 0.035 * k, T12, L5 };++ // the skin in bands 2 cm apart: the front and back near the midline, the half-width; gaps filled, then smoothed+ const pts: V3[] = [];+ for (const x of skel.surface ?? []) if (TRUNK.test(x.part)) { const h = skel.joints[x.j[0]].head; pts.push([h[0] + x.o[0], h[1] + x.o[1], h[2] + x.o[2]]); }+ if (pts.length < 50) throw new Error(`anatomy: ${skel.name}'s skeleton.json has too few skin samples of the trunk (${pts.length})`);+ const y0 = hips[1] - 0.14 * k, y1 = n1[1] + 0.06 * k, step = 0.02, nb = Math.ceil((y1 - y0) / step) + 1;+ const ys = Array.from({ length: nb }, (_, i) => y0 + i * step);+ const band = (f: (p: V3[]) => number) => ys.map((yy) => { const q = pts.filter((p) => Math.abs(p[1] - yy) < 0.03); return q.length >= 3 ? f(q) : NaN; });+ const mid = (q: V3[]) => q.filter((p) => Math.abs(p[0]) < 0.06 * k);+ let front = band((q) => { const m = mid(q); return m.length ? Math.max(...m.map((p) => p[2])) : NaN; });+ let back = band((q) => { const m = mid(q); return m.length ? Math.min(...m.map((p) => p[2])) : NaN; });+ let half = band((q) => { const a = q.map((p) => Math.abs(p[0])).sort((s, t) => s - t); return a[Math.floor(0.92 * (a.length - 1))]; });+ // (a band whose midline samples lie all on one side reads its front and back as one: kept only when 12 cm apart)+ back = back.map((b, i) => (Number.isFinite(b) && Number.isFinite(front[i]) && front[i] - b > 0.12 * k ? b : NaN));+ front = front.map((f, i) => (Number.isFinite(back[i]) ? f : NaN));+ const fill = (a: number[]) => {+ const ok = a.map((x, i) => [i, x] as const).filter(([, x]) => Number.isFinite(x));+ if (!ok.length) throw new Error(`anatomy: ${skel.name}'s trunk could not be measured`);+ const filled = a.map((x, i) => (Number.isFinite(x) ? x : interp(ok.map(([j]) => j), ok.map(([, z]) => z), i)));+ return filled.map((_, i) => { const w = filled.slice(Math.max(0, i - 2), i + 3); return w.reduce((s, t) => s + t, 0) / w.length; });+ };+ front = fill(front); back = fill(back); half = fill(half);+ const skin = (yy: number) => ({ front: interp(ys, front, yy), back: interp(ys, back, yy), half: interp(ys, half, yy) });++ // the spine: through the trunk's joints, set back over the thoracic curve, and never nearer the back than 5.5 cm+ const knots = [hips, sp1, sp2, chest, n1, n2, head];+ const thor = T1 - 5 * dT;+ const spine = (yy: number): V3 => {+ const z = interp(knots.map((p) => p[1]), knots.map((p) => p[2]), yy) - 0.026 * k * Math.exp(-(((yy - thor) / (4 * dT)) ** 2));+ return [0, yy, yy < T1 + 0.01 ? Math.max(z, skin(yy).back + 0.055 * k) : z];+ };++ // the rib cage's wall: its back behind the ribs' angles (3.2 cm in from the back's skin, the muscles there), its+ // front behind the sternum (1.3 cm in), its widest a little behind the middle; its half-width from the chest's+ // skin under the arms (2 cm of muscle at the side), narrowing to the top as ribs 1 to 3 do+ const chestHalf = Math.max(...ys.filter((yy) => yy > y.xiph && yy < T1 - 4 * dT).map((yy) => skin(yy).half)) - 0.02 * k;+ const cage = (yy: number, w?: number) => {+ const s = skin(yy), b = s.back + 0.032 * k, f = s.front - 0.013 * k;+ const profile = interp([T12 - 3 * dL, T12 - dT, T1 - 8 * dT, T1 - 4 * dT, T1 - 1.5 * dT], [0.8, 0.97, 1, 0.86, 0.5], yy);+ return { back: b, front: f, mid: lerp(b, f, 0.45), half: w ?? chestHalf * profile };+ };+ const wall = (yy: number, phi: number, side: number, w?: number, inset = 0): V3 => {+ const c = cage(yy, w), s = Math.sin(phi), co = Math.cos(phi);+ const x = side * Math.max(0, c.half - inset) * Math.pow(Math.abs(s), 0.85);+ const z = co >= 0 ? c.mid - (c.mid - c.back - inset) * Math.pow(co, 1.15) : c.mid + (c.front - c.mid - inset) * Math.pow(-co, 1.15);+ return [x, yy, z];+ };+ return { k, joint, y, vertebrae, skin, spine, cage, wall };+}diff --git a/sdk/character/src/anatomy/hits.ts b/sdk/character/src/anatomy/hits.tsnew file mode 100644index 00000000..2c46d9de--- /dev/null+++ b/sdk/character/src/anatomy/hits.ts@@ -0,0 +1,93 @@+// What a straight path through a posed body passes through: each piece of its anatomy (anatomyOf) the ray goes in and+// out of, in order along it, and where it enters and leaves the skin (the body's surface samples, skeleton.json's+// `surface`, nearest the ray). For a bullet's path in a kill cam, its wounds, and what the shot hit.+import { pose as posed, qinv, qrot, qyaw, skinJoints, surface, toBody, toScene, type Placement, type Pose, type Skeleton } from "../character/all";+import type { V3 } from "./mesh";+import type { Kind, Piece } from "./piece";++export interface Hit {+ /** the piece's name ("rib-5-left", "lung-left", "heart"), or "skin" */+ part: string;+ kind: Kind | "skin";+ /** where the path goes into it and out of it, in the scene */+ entry: V3;+ exit: V3;+ /** how far along the path each is, metres in the scene */+ t0: number;+ t1: number;+}++const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];++const bounds = new WeakMap<Piece, { c: V3; r: number }>();+function boundOf(p: Piece) {+ let b = bounds.get(p);+ if (!b) {+ const P = p.geo.positions, n = P.length / 3, c: V3 = [0, 0, 0];+ for (let i = 0; i < n; i++) { c[0] += P[3 * i] / n; c[1] += P[3 * i + 1] / n; c[2] += P[3 * i + 2] / n; }+ let r = 0;+ for (let i = 0; i < n; i++) r = Math.max(r, Math.hypot(P[3 * i] - c[0], P[3 * i + 1] - c[1], P[3 * i + 2] - c[2]));+ bounds.set(p, (b = { c, r }));+ }+ return b;+}++/** each crossing of a ray with a closed mesh: its distance along the ray and whether it goes in (the face looks back) */+function crossings(p: Piece, o: V3, d: V3): { t: number; inward: boolean }[] {+ const b = boundOf(p), oc = sub(b.c, o), tc = dot(oc, d);+ if (dot(oc, oc) - tc * tc > b.r * b.r) return [];+ const P = p.geo.positions, I = p.geo.indices, out: { t: number; inward: boolean }[] = [];+ const at = (k: number): V3 => [P[3 * k], P[3 * k + 1], P[3 * k + 2]];+ for (let i = 0; i < I.length; i += 3) {+ const a = at(I[i]), e1 = sub(at(I[i + 1]), a), e2 = sub(at(I[i + 2]), a), h = cross(d, e2), det = dot(e1, h);+ if (Math.abs(det) < 1e-12) continue;+ const f = 1 / det, s = sub(o, a), u = f * dot(s, h);+ if (u < 0 || u > 1) continue;+ const q = cross(s, e1), w = f * dot(d, q);+ if (w < 0 || u + w > 1) continue;+ const t = f * dot(e2, q);+ if (t > 0) out.push({ t, inward: dot(cross(e1, e2), d) < 0 });+ }+ return out.sort((x, y) => x.t - y.t);+}++/**+ * The pieces of `anatomy` a ray from `origin` along `dir` (in the scene) passes through on the body posed `pose` and+ * placed `at`, and the skin it enters and leaves, in order along the ray. A piece the ray crosses twice (a rib's both+ * sides, a lung in and out and in again) is listed once each time through.+ */+export function hits(skel: Skeleton, pose: Pose, anatomy: { pieces: Piece[] }, origin: V3, dir: V3, at: Placement = {}): Hit[] {+ const k = at.scale ?? 1, yaw = qyaw(-(at.yaw ?? 0));+ const o = toBody(at, origin) as V3, dl = Math.hypot(...dir), d = qrot(yaw, [dir[0] / dl, dir[1] / dl, dir[2] / dl]) as V3;+ const w = posed(skel, pose), J = new Map(skinJoints(skel, w).map((j) => [j.name, j]));+ const scene = (t: number): V3 => toScene(at, [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t]) as V3;+ const out: Hit[] = [];+ for (const p of anatomy.pieces) {+ const j = J.get(p.joint);+ if (!j) continue;+ const inv = qinv(j.rot), ol = qrot(inv, sub(o, j.pos as V3)) as V3, dl_ = qrot(inv, d) as V3;+ let open: number | null = null;+ for (const c of crossings(p, ol, dl_)) {+ if (c.inward) { if (open === null) open = c.t; }+ else {+ const t0 = open ?? 0;+ out.push({ part: p.name, kind: p.kind, entry: scene(t0), exit: scene(c.t), t0: t0 * k, t1: c.t * k });+ open = null;+ }+ }+ }+ // the skin: its samples near the ray, the first facing back along it and the last facing on+ const near = surface(skel, w).map((s) => ({ s, t: dot(sub(s.at as V3, o), d) })).filter(({ s, t }) => {+ const q = sub(s.at as V3, [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t]);+ return t > 0 && dot(q, q) < 0.035 * 0.035;+ });+ const into = near.filter(({ s }) => dot(s.normal as V3, d) < 0).sort((a, b) => a.t - b.t)[0];+ const outOf = near.filter(({ s }) => dot(s.normal as V3, d) > 0).sort((a, b) => b.t - a.t)[0];+ if (into || outOf) {+ const t0 = into?.t ?? Math.min(...out.map((h) => h.t0 / k)), t1 = outOf?.t ?? Math.max(...out.map((h) => h.t1 / k));+ if (Number.isFinite(t0) && Number.isFinite(t1)) out.push({ part: "skin", kind: "skin", entry: scene(t0), exit: scene(t1), t0: t0 * k, t1: t1 * k });+ }+ return out.sort((a, b) => a.t0 - b.t0);+}diff --git a/sdk/character/src/anatomy/index.ts b/sdk/character/src/anatomy/index.tsnew file mode 100644index 00000000..01467727--- /dev/null+++ b/sdk/character/src/anatomy/index.ts@@ -0,0 +1,36 @@+// A body's anatomy for an X-ray and a shot's path through it (docs/character.feature CH50): its skeleton as bones and+// its chest and belly's organs, made from the body's own skeleton.json (its joints and its skin's samples) so they fit+// any registered SOMA body, each piece riding its joint as the body is posed. All of it is made here in code: no+// anatomy data is downloaded (the open atlases are share-alike).+//+// const A = anatomyOf(skel); // once per body+// hits(skel, pose, A, muzzle, dir, at) // what a shot passes through, in order: [{ part, entry, exit }]+// <Anatomy skel={skel} pose={pose} anatomy={A} name="sentry" xray={1} />+import type { Skeleton } from "../character/all";+import { bonesOf } from "./bones";+import { frameOf, type Frame } from "./frame";+import { organsOf } from "./organs";+import type { Piece } from "./piece";++export interface AnatomyOf {+ body: string;+ frame: Frame;+ pieces: Piece[];+}++const made = new WeakMap<Skeleton, AnatomyOf>();++/** the body's anatomy (made once per skeleton): its bones and organs, each a mesh on the joint it rides */+export function anatomyOf(skel: Skeleton): AnatomyOf {+ let a = made.get(skel);+ if (!a) {+ const F = frameOf(skel);+ made.set(skel, (a = { body: skel.name, frame: F, pieces: [...bonesOf(skel, F), ...organsOf(skel, F)] }));+ }+ return a;+}++export { hits, type Hit } from "./hits";+export { Anatomy, Round, ShotPath, Wounds, xrayGhost, xrayParts, type AnatomyProps } from "./draw";+export type { Piece, Kind } from "./piece";+export type { Frame } from "./frame";diff --git a/sdk/character/src/anatomy/mesh.ts b/sdk/character/src/anatomy/mesh.tsnew file mode 100644index 00000000..564c7224--- /dev/null+++ b/sdk/character/src/anatomy/mesh.ts@@ -0,0 +1,161 @@+// The shapes anatomy is made of, as triangle meshes in plain arrays (a <BufferMesh>'s positions, normals and indices):+// a tube along a path with an oval section (a rib, a long bone, a vessel, a blade of bone), a blob (an ellipsoid shaped+// by a function of direction: an organ), and a loft through closed rings (a lung that fills the rib cage).+export type V3 = [number, number, number];+export interface Geo { positions: number[]; normals: number[]; indices: number[] }++export const v = {+ add: (a: V3, b: V3): V3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]],+ sub: (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],+ mul: (a: V3, s: number): V3 => [a[0] * s, a[1] * s, a[2] * s],+ dot: (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],+ cross: (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]],+ len: (a: V3) => Math.hypot(a[0], a[1], a[2]),+ norm: (a: V3): V3 => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; },+ lerp: (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t],+};++/** each vertex's normal from the faces round it (area-weighted), outward for a mesh wound counter-clockwise */+export function withNormals(positions: number[], indices: number[]): Geo {+ const n = new Array(positions.length).fill(0);+ for (let i = 0; i < indices.length; i += 3) {+ const [a, b, c] = [indices[i], indices[i + 1], indices[i + 2]];+ const p = (k: number): V3 => [positions[3 * k], positions[3 * k + 1], positions[3 * k + 2]];+ const f = v.cross(v.sub(p(b), p(a)), v.sub(p(c), p(a)));+ for (const k of [a, b, c]) for (let d = 0; d < 3; d++) n[3 * k + d] += f[d];+ }+ for (let k = 0; k < n.length; k += 3) {+ const l = Math.hypot(n[k], n[k + 1], n[k + 2]) || 1;+ n[k] /= l; n[k + 1] /= l; n[k + 2] /= l;+ }+ return { positions, normals: n, indices };+}++export function merge(...gs: Geo[]): Geo {+ const out: Geo = { positions: [], normals: [], indices: [] };+ for (const g of gs) {+ const o = out.positions.length / 3;+ out.positions.push(...g.positions); out.normals.push(...g.normals);+ for (const i of g.indices) out.indices.push(i + o);+ }+ return out;+}++/** a path through points, smooth (Catmull-Rom), `n` points evenly in its parameter */+export function smoothPath(pts: V3[], n: number): V3[] {+ if (pts.length < 3) return Array.from({ length: n }, (_, i) => v.lerp(pts[0], pts[pts.length - 1], i / (n - 1)));+ const out: V3[] = [];+ for (let i = 0; i < n; i++) {+ const t = (i / (n - 1)) * (pts.length - 1), k = Math.min(pts.length - 2, Math.floor(t)), u = t - k;+ const p0 = pts[Math.max(0, k - 1)], p1 = pts[k], p2 = pts[k + 1], p3 = pts[Math.min(pts.length - 1, k + 2)];+ const c = (a: number, b: number, c_: number, d: number) => 0.5 * (2 * b + (-a + c_) * u + (2 * a - 5 * b + 4 * c_ - d) * u * u + (-a + 3 * b - 3 * c_ + d) * u * u * u);+ out.push([c(p0[0], p1[0], p2[0], p3[0]), c(p0[1], p1[1], p2[1], p3[1]), c(p0[2], p1[2], p2[2], p3[2])]);+ }+ return out;+}++/**+ * A tube along `path` with an oval section: `r(t)` gives its two half-widths at t (0 at the start, 1 at the end), the+ * first along `hint` (laid square to the path: up for a rib, so its section stands tall) and the second across it.+ * Its ends are closed.+ */+export function tube(path: V3[], r: (t: number) => [number, number], sides = 10, hint: V3 = [0, 1, 0]): Geo {+ const P: number[] = [], I: number[] = [], n = path.length;+ let prevN: V3 | null = null;+ for (let i = 0; i < n; i++) {+ const T = v.norm(v.sub(path[Math.min(n - 1, i + 1)], path[Math.max(0, i - 1)]));+ let N = v.sub(hint, v.mul(T, v.dot(hint, T)));+ if (v.len(N) < 1e-4) N = prevN ?? v.cross(T, Math.abs(T[0]) < 0.9 ? [1, 0, 0] : [0, 0, 1]);+ N = v.norm(N);+ if (prevN && v.dot(N, prevN) < 0) N = v.mul(N, -1);+ prevN = N;+ const B = v.cross(T, N), [ra, rb] = r(i / (n - 1));+ for (let s = 0; s < sides; s++) {+ const a = (2 * Math.PI * s) / sides;+ P.push(...v.add(path[i], v.add(v.mul(N, ra * Math.cos(a)), v.mul(B, rb * Math.sin(a)))));+ }+ }+ for (let i = 0; i < n - 1; i++)+ for (let s = 0; s < sides; s++) {+ const a = i * sides + s, b = i * sides + ((s + 1) % sides), c = a + sides, d = b + sides;+ I.push(a, b, c, b, d, c);+ }+ const body = withNormals(P, I);+ // the ends, each a fan of its own vertices (so the side's normals stay round)+ const cap = (i: number, out: number): Geo => {+ const ps: number[] = [...path[i], ...P.slice(i * sides * 3, (i + 1) * sides * 3)], ix: number[] = [];+ for (let s = 0; s < sides; s++) out > 0 ? ix.push(0, 1 + s, 1 + ((s + 1) % sides)) : ix.push(0, 1 + ((s + 1) % sides), 1 + s);+ return withNormals(ps, ix);+ };+ return outward(merge(body, cap(0, -1), cap(n - 1, 1)));+}++/**+ * A blob: an ellipsoid at `c` with axes `ax` (three directions) and half-lengths `rad`, each direction's radius+ * scaled by `shape(u)` (u the unit direction in the axes' own frame: u[2] along the third axis, the poles').+ */+export function blob(c: V3, ax: [V3, V3, V3], rad: V3, shape: (u: V3) => number = () => 1, nu = 28, nv = 18): Geo {+ const P: number[] = [], I: number[] = [];+ for (let j = 0; j <= nv; j++) {+ const th = (Math.PI * j) / nv;+ for (let i = 0; i < nu; i++) {+ const ph = (2 * Math.PI * i) / nu;+ const u: V3 = [Math.sin(th) * Math.cos(ph), Math.sin(th) * Math.sin(ph), Math.cos(th)];+ const s = shape(u);+ let p = c;+ for (let k = 0; k < 3; k++) p = v.add(p, v.mul(ax[k], rad[k] * u[k] * s));+ P.push(...p);+ }+ }+ for (let j = 0; j < nv; j++)+ for (let i = 0; i < nu; i++) {+ const a = j * nu + i, b = j * nu + ((i + 1) % nu), c_ = a + nu, d = b + nu;+ I.push(a, c_, b, b, c_, d);+ }+ return outward(withNormals(P, I));+}++/** a loft through closed rings of the same count (each ring in order round its loop), its two ends closed (each+ * end's fan meeting at its ring's middle, or at the point given) */+export function loft(rings: V3[][], ends: [V3?, V3?] = [undefined, undefined]): Geo {+ const m = rings[0].length, P: number[] = [], I: number[] = [];+ for (const r of rings) for (const p of r) P.push(...p);+ for (let k = 0; k < rings.length - 1; k++)+ for (let s = 0; s < m; s++) {+ const a = k * m + s, b = k * m + ((s + 1) % m), c = a + m, d = b + m;+ I.push(a, c, b, b, c, d);+ }+ const side = withNormals(P, I);+ const cap = (k: number, out: number): Geo => {+ const r = rings[k], c = ends[k === 0 ? 0 : 1] ?? v.mul(r.reduce((s, p) => v.add(s, p), [0, 0, 0] as V3), 1 / m), ps: number[] = [...c], ix: number[] = [];+ for (const p of r) ps.push(...p);+ for (let s = 0; s < m; s++) out > 0 ? ix.push(0, 1 + ((s + 1) % m), 1 + s) : ix.push(0, 1 + s, 1 + ((s + 1) % m));+ return withNormals(ps, ix);+ };+ return outward(merge(side, cap(0, -1), cap(rings.length - 1, 1)));+}++/** a closed mesh turned to face out, if its faces were wound in (its signed volume negative) */+export function outward(g: Geo): Geo {+ let vol = 0;+ const P = g.positions, I = g.indices;+ for (let i = 0; i < I.length; i += 3) {+ const a = 3 * I[i], b = 3 * I[i + 1], c = 3 * I[i + 2];+ vol += P[a] * (P[b + 1] * P[c + 2] - P[b + 2] * P[c + 1]) - P[a + 1] * (P[b] * P[c + 2] - P[b + 2] * P[c]) + P[a + 2] * (P[b] * P[c + 1] - P[b + 1] * P[c]);+ }+ return vol < 0 ? flip(g) : g;+}++/** its faces turned the other way (and its normals) */+export function flip(g: Geo): Geo {+ for (let i = 0; i < g.indices.length; i += 3) [g.indices[i + 1], g.indices[i + 2]] = [g.indices[i + 2], g.indices[i + 1]];+ for (let k = 0; k < g.normals.length; k++) g.normals[k] = -g.normals[k];+ return g;+}++/** the mesh moved by -o (into a joint's frame at rest, its head at o) */+export function shifted(g: Geo, o: V3): Geo {+ const P = g.positions.slice();+ for (let k = 0; k < P.length; k += 3) { P[k] -= o[0]; P[k + 1] -= o[1]; P[k + 2] -= o[2]; }+ return { positions: P, normals: g.normals, indices: g.indices };+}diff --git a/sdk/character/src/anatomy/organs.ts b/sdk/character/src/anatomy/organs.tsnew file mode 100644index 00000000..ae95ea4e--- /dev/null+++ b/sdk/character/src/anatomy/organs.ts@@ -0,0 +1,117 @@+// The organs of the chest and belly, placed in the body's own frame (frame.ts): the lungs filling each side of the rib+// cage down to the diaphragm's dome (the left with the heart's notch), the heart turned down, left and forward, the+// aorta and the pulmonary trunk, the windpipe and its bronchi; under the diaphragm the liver, stomach, spleen and+// kidneys, and the bowel. Their places and sizes are an adult's (Gray's Anatomy, 1918, public domain), scaled by the+// body; their shapes simple. Not yet: the oesophagus, the pancreas, the bladder, the great veins.+import { frameOf, interp, type Frame } from "./frame";+import { blob, loft, smoothPath, tube, v, type V3 } from "./mesh";+import { COLORS, piece, type Piece } from "./piece";++const I3: [V3, V3, V3] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];++/** the heart's shape: its base right of the middle behind the sternum, its apex down, left and forward */+function heartShape(F: Frame) {+ const k = F.k, j = F.y.jug, x = F.y.xiph;+ const base: V3 = [0.004 * k, j - 0.5 * (j - x), F.cage(j - 0.5 * (j - x)).mid + 0.005 * k];+ const apex: V3 = [0.078 * k, x - 0.004 * k, F.cage(x).front - 0.026 * k];+ const a2 = v.norm(v.sub(apex, base)), a0 = v.norm(v.cross([0, 1, 0], a2)), a1 = v.cross(a2, a0);+ const ax: [V3, V3, V3] = [a0, a1, a2], rad: V3 = [0.046 * k, 0.037 * k, 0.064 * k], c = v.lerp(base, apex, 0.45);+ const shape = (u: V3) => 1 - 0.3 * Math.max(0, u[2]) ** 1.5 + 0.06 * Math.max(0, -u[2]);+ // a point inside it (with a margin) moved out to its surface along its own direction from the middle+ const outOf = (p: V3, margin = 1.14): V3 => {+ const d = v.sub(p, c), u: V3 = [v.dot(d, a0) / rad[0], v.dot(d, a1) / rad[1], v.dot(d, a2) / rad[2]], r = v.len(u);+ if (r < 1e-6) return p;+ const n: V3 = [u[0] / r, u[1] / r, u[2] / r], lim = shape(n) * margin;+ if (r >= lim) return p;+ let q = c;+ for (let i = 0; i < 3; i++) q = v.add(q, v.mul(ax[i], rad[i] * n[i] * lim));+ return q;+ };+ return { base, apex, ax, rad, c, shape, outOf };+}++function lungs(F: Frame): Piece[] {+ const k = F.k, dT = F.vertebrae.find((q) => q.name === "T1")!.h, out: Piece[] = [], H = heartShape(F);+ const apex = F.y.jug + 0.035 * k, low = F.y.T1 - 11 * dT;+ const heartY = [F.y.xiph - 0.01 * k, F.y.jug - 0.45 * (F.y.jug - F.y.xiph), F.y.jug - 0.2 * (F.y.jug - F.y.xiph)];+ for (const [side, s] of [["left", 1], ["right", -1]] as const) {+ // the diaphragm under it: a dome, highest under the lung's middle (the right's higher, over the liver), its edges+ // falling to the recesses behind and at the side+ const top = F.y.xiph + (s < 0 ? 0.016 : 0.004) * k;+ const dome = (p: V3) => {+ const c = F.cage(top), cx = s * c.half * 0.45, cz = c.mid + 0.01 * k;+ const rho = Math.min(1.3, Math.hypot((p[0] - cx) / (c.half * 0.62), (p[2] - cz) / ((c.front - c.back) * 0.5)));+ const edge = interp([-1, 0, 1], [low, top - 0.05 * k, top - 0.03 * k], (p[2] - cz) / ((c.front - c.back) * 0.5));+ return top - (top - edge) * Math.min(1, rho * rho);+ };+ const rings: V3[][] = [];+ const N = 22;+ for (let q = 0; q <= N; q++) {+ const y = apex - (apex - low) * (q / N), taper = Math.min(1, Math.sqrt(Math.max(0.02, (apex - y) / (0.05 * k))));+ // the mediastinum's side: the heart pushes the left lung out at its levels (the cardiac notch)+ const heart = Math.max(0, 1 - Math.abs(y - heartY[1]) / (heartY[2] - heartY[0]) * 1.6);+ const xm = s > 0 ? (0.028 + 0.05 * heart) * k : (0.026 + 0.012 * heart) * k;+ const pb = (s > 0 ? 0.88 - 0.16 * heart : 0.93) * Math.PI;+ const ring: V3[] = [];+ for (let a = 0; a <= 16; a++) { const phi = 0.13 * Math.PI + (pb - 0.13 * Math.PI) * (a / 16); ring.push(F.wall(y, phi, s, undefined, 0.006 * k)); }+ const zf = ring[ring.length - 1][2], zb = ring[0][2];+ for (let a = 1; a <= 7; a++) ring.push([s * xm, y, zf + (zb - zf) * (a / 8)]);+ // (narrowed to its apex round its own middle)+ const c = v.mul(ring.reduce((t, p) => v.add(t, p), [0, 0, 0] as V3), 1 / ring.length);+ // (over the dome, and clear of the heart: its cardiac impression)+ rings.push(ring.map((p) => { const t = v.add(c, v.mul(v.sub(p, c), taper)); return H.outOf([t[0], Math.max(y, dome(t)), t[2]]); }));+ }+ const c0 = F.cage(top);+ out.push(piece(F, `lung-${side}`, "organ", "Chest", loft(rings, [[s * 0.05 * k, apex + 0.004 * k, F.cage(apex).mid], [s * c0.half * 0.45, top, c0.mid + 0.01 * k]]), COLORS.lung, 0.5));+ }+ return out;+}++function heart(F: Frame): Piece[] {+ const k = F.k, j = F.y.jug, H = heartShape(F), base = H.base;+ const out = [piece(F, "heart", "organ", "Chest", blob(H.c, H.ax, H.rad, H.shape, 28, 20), COLORS.heart, 0.45)];+ const sp = (y: number) => F.spine(y)[2];+ const aorta = smoothPath([v.add(base, [0, 0.02 * k, 0.005 * k]), [0.0, j - 0.022 * k, F.cage(j).mid], [0.012 * k, j - 0.028 * k, sp(j) + 0.03 * k], [0.018 * k, j - 0.07 * k, sp(j - 0.07 * k) + 0.028 * k], [0.014 * k, F.y.T12 - 0.02 * k, sp(F.y.T12) + 0.028 * k]], 40);+ out.push(piece(F, "aorta", "vessel", "Chest", tube(aorta, (t) => [interp([0, 0.3, 1], [0.0135, 0.012, 0.011], t) * k, interp([0, 0.3, 1], [0.0135, 0.012, 0.011], t) * k], 12), COLORS.aorta, 0.4));+ const pt = smoothPath([v.add(base, [0.012 * k, 0.004 * k, 0.025 * k]), [0.014 * k, j - 0.06 * k, F.cage(j).mid + 0.012 * k], [0.002 * k, j - 0.075 * k, F.cage(j).mid - 0.008 * k]], 16);+ out.push(piece(F, "pulmonary-trunk", "vessel", "Chest", tube(pt, () => [0.012 * k, 0.012 * k], 12), "#6f3a5a", 0.4));+ // the windpipe from the neck to its fork, and the two bronchi+ const top: V3 = [0, F.y.T1 + 0.05 * k, sp(F.y.T1 + 0.05 * k) + 0.034 * k], fork: V3 = [0, j - 0.06 * k, sp(j - 0.06 * k) + 0.036 * k];+ out.push(piece(F, "trachea", "airway", "Chest", tube(smoothPath([top, v.lerp(top, fork, 0.5), fork], 12), () => [0.009 * k, 0.009 * k], 12), COLORS.airway, 0.5));+ for (const s of [1, -1]) out.push(piece(F, `bronchus-${s > 0 ? "left" : "right"}`, "airway", "Chest", tube([fork, [s * 0.052 * k, fork[1] - (s > 0 ? 0.035 : 0.025) * k, fork[2] - 0.012 * k]], () => [0.0065 * k, 0.0065 * k], 10), COLORS.airway, 0.5));+ return out;+}++function belly(F: Frame): Piece[] {+ const k = F.k, x = F.y.xiph, out: Piece[] = [];+ const at = (y: number) => F.cage(y);+ // the liver: under the right dome, from the right wall across past the middle, thinning to the left+ const ly = x - 0.045 * k, lc = at(ly), right = -lc.half + 0.008 * k, left = 0.06 * k;+ out.push(piece(F, "liver", "organ", "Spine2", blob([(right + left) / 2, ly, lc.mid + 0.008 * k], I3, [(left - right) / 2, 0.062 * k, (lc.front - lc.back) * 0.4], (u) => (1 - 0.42 * Math.max(0, u[0]) ** 1.4) * (1 - 0.22 * Math.max(0, -u[1])) * (1 - 0.45 * Math.max(0, -u[2]) * Math.max(0, u[0] + 0.25)), 30, 20), COLORS.liver, 0.4));+ // the stomach: a J down the left from its top under the heart to the pylorus right of the middle+ const m = (y: number) => at(y).mid + 0.012 * k;+ const st = smoothPath([[0.025 * k, x - 0.03 * k, m(x) - 0.012 * k], [0.065 * k, x - 0.026 * k, m(x) - 0.01 * k], [0.082 * k, x - 0.05 * k, m(x) + 0.012 * k], [0.06 * k, x - 0.09 * k, m(x) + 0.03 * k], [0.015 * k, x - 0.096 * k, m(x) + 0.034 * k], [-0.022 * k, x - 0.08 * k, m(x) + 0.024 * k]], 40);+ out.push(piece(F, "stomach", "organ", "Spine2", tube(st, (t) => { const r = interp([0, 0.15, 0.4, 0.65, 0.85, 1], [0.018, 0.034, 0.037, 0.03, 0.02, 0.011], t) * k; return [r, r * 0.85]; }, 14), COLORS.stomach, 0.45));+ out.push(piece(F, "spleen", "organ", "Spine2", blob([0.088 * k, x - 0.062 * k, at(x).back + 0.04 * k], I3, [0.021 * k, 0.045 * k, 0.032 * k], () => 1, 18, 12), COLORS.spleen, 0.45));+ for (const s of [1, -1]) {+ const y = F.y.T12 - (s > 0 ? 0.012 : 0.034) * k;+ out.push(piece(F, `kidney-${s > 0 ? "left" : "right"}`, "organ", "Spine2", blob([s * 0.058 * k, y, F.spine(y)[2] - 0.004 * k], I3, [0.027 * k, 0.052 * k, 0.02 * k], (u) => 1 - 0.28 * Math.max(0, -s * u[0]) ** 3, 18, 14), COLORS.kidney, 0.45));+ }+ // the bowel: the small intestine coiled in the middle of the belly, framed by the colon+ const y0 = F.y.L5 - 0.025 * k, y1 = F.y.T12 - 0.055 * k, ym = (y0 + y1) / 2;+ const zc = (y: number) => (F.skin(y).front + F.spine(y)[2]) / 2 + 0.012 * k, zf = (y: number) => F.skin(y).front - 0.022 * k;+ const coil: V3[] = [];+ for (let q = 0; q <= 260; q++) {+ const t = q / 260, y = ym - 0.006 * k + (y1 - y0) * 0.34 * Math.sin(2 * Math.PI * (3.1 * t) + 0.4) * (0.75 + 0.25 * Math.cos(2 * Math.PI * 11 * t));+ const z = zc(y) + (zf(y) - zc(y)) * (0.45 + 0.42 * Math.sin(2 * Math.PI * 7.7 * t + 1));+ coil.push([0.05 * k * Math.sin(2 * Math.PI * 5.3 * t + 0.3) * (0.8 + 0.2 * Math.sin(2 * Math.PI * 2.3 * t)), y, z]);+ }+ out.push(piece(F, "small-intestine", "organ", "Spine1", tube(smoothPath(coil, 520), () => [0.0105 * k, 0.0105 * k], 8), COLORS.bowel, 0.5));+ const colon = smoothPath([[-0.072 * k, y0 + 0.005 * k, zc(y0)], [-0.086 * k, y1 - 0.01 * k, zc(y1) - 0.012 * k], [-0.07 * k, y1 + 0.012 * k, zc(y1)], [0, y1 - 0.012 * k, zf(y1) - 0.006 * k], [0.08 * k, y1 + 0.022 * k, zc(y1) - 0.012 * k], [0.09 * k, y0 + 0.01 * k, zc(y0) - 0.016 * k], [0.04 * k, y0 - 0.035 * k, zc(y0)], [0.004 * k, y0 - 0.06 * k, F.spine(F.y.L5)[2] + 0.01 * k]], 90);+ out.push(piece(F, "colon", "organ", "Spine1", tube(colon, (t) => { const r = interp([0, 0.15, 0.5, 0.8, 1], [0.025, 0.022, 0.02, 0.017, 0.016], t) * k; return [r, r]; }, 12), COLORS.colon, 0.5));+ return out;+}++export function organsOf(skel: Parameters<typeof frameOf>[0], F: Frame = frameOf(skel)): Piece[] {+ return [...lungs(F), ...heart(F), ...belly(F)];+}diff --git a/sdk/character/src/anatomy/piece.ts b/sdk/character/src/anatomy/piece.tsnew file mode 100644index 00000000..f8f24d5c--- /dev/null+++ b/sdk/character/src/anatomy/piece.ts@@ -0,0 +1,27 @@+// A piece of the anatomy: one bone, cartilage, organ or vessel, its mesh in its joint's frame at rest (the joint's head+// at the origin), so the joint's turn carries it as the body is posed (character/drawing.tsx onJoint).+import type { Frame } from "./frame";+import { shifted, type Geo } from "./mesh";++export type Kind = "bone" | "cartilage" | "organ" | "vessel" | "airway";++export interface Piece {+ /** what it is ("rib-5-left", "lung-right", "heart") */+ name: string;+ kind: Kind;+ /** the joint it rides */+ joint: string;+ geo: Geo;+ /** its colour as it is (sRGB hex), and how rough */+ color: string;+ roughness: number;+}++export const COLORS = {+ bone: "#e6dcc6", cartilage: "#cdd6d2", lung: "#d79a96", heart: "#8a2c2a", liver: "#6b2b20", stomach: "#c4897a",+ bowel: "#d3a089", colon: "#c49378", kidney: "#7a302b", spleen: "#5e2734", aorta: "#a8383a", airway: "#d6cdbd",+};++export function piece(F: Frame, name: string, kind: Kind, joint: string, geo: Geo, color: string, roughness = 0.6): Piece {+ return { name, kind, joint, geo: shifted(geo, F.joint(joint)), color, roughness };+}diff --git a/sdk/character/src/character.tsx b/sdk/character/src/character.tsxindex 62a6e175..ca7e76da 100644--- a/sdk/character/src/character.tsx+++ b/sdk/character/src/character.tsx@@ -20,6 +20,9 @@ export type { Quat, Joint, Skeleton, Pose, Posed, Side, Finger, HandShape, Closi// a character takes a thing with its hands, with no capture of the action (docs/hands.feature)export { take, fetch, fitPose, handShape, placedPose, walkUp } from "./take";export type { TakeThing, TakeSpec, Taken, Mark } from "./take";+// a body's anatomy: its bones and organs made from its own skeleton, an X-ray of them, and a shot's path through them+export { anatomyOf, hits, Anatomy, Round, ShotPath, Wounds, xrayGhost, xrayParts } from "./anatomy";+export type { AnatomyOf, Hit, AnatomyProps, Piece, Kind, Frame } from "./anatomy";// motion on SOMA's skeleton (NVIDIA's motion models and datasets) played on a raea bodyexport { readSomaUsda, somaPose, turnsPose, withTwists } from "./soma";export type { SomaClip, TurnsClip } from "./soma";diff --git a/sdk/character/test/anatomy.test.ts b/sdk/character/test/anatomy.test.tsnew file mode 100644index 00000000..b142150c--- /dev/null+++ b/sdk/character/test/anatomy.test.ts@@ -0,0 +1,63 @@+// A body's anatomy made from its skeleton (src/anatomy): its pieces, inside its skin, and a shot's path through them.+// The body here is made up: a SOMA man's joints (gb-sentry's, 1.75 m) and an oval trunk of skin samples round them.+import { expect, test } from "bun:test";+import { anatomyOf, hits } from "../src/anatomy";+import { rest, type Skeleton } from "../src/character/all";++type V3 = [number, number, number];+const JOINTS: [string, number, V3][] = [+ ["Hips", -1, [0, 0.998, -0.049]], ["Spine1", 0, [0, 1.049, -0.05]], ["Spine2", 1, [0, 1.121, -0.051]], ["Chest", 2, [0, 1.194, -0.058]],+ ["Neck1", 3, [0, 1.457, -0.059]], ["Neck2", 4, [0, 1.532, -0.035]], ["Head", 5, [0, 1.596, -0.016]], ["Jaw", 6, [0, 1.6, 0.0]],+ ["LeftEye", 6, [0.032, 1.66, 0.07]], ["RightEye", 6, [-0.032, 1.66, 0.07]],+ ["LeftShoulder", 3, [0.016, 1.428, -0.008]], ["LeftArm", 10, [0.161, 1.401, -0.063]], ["LeftForeArm", 11, [0.34, 1.18, -0.07]], ["LeftHand", 12, [0.47, 0.98, -0.05]],+ ["RightShoulder", 3, [-0.016, 1.428, -0.008]], ["RightArm", 14, [-0.161, 1.401, -0.063]], ["RightForeArm", 15, [-0.34, 1.18, -0.07]], ["RightHand", 16, [-0.47, 0.98, -0.05]],+ ["LeftLeg", 0, [0.1, 0.915, -0.027]], ["LeftShin", 18, [0.11, 0.5, -0.03]], ["LeftFoot", 19, [0.12, 0.08, -0.05]],+ ["RightLeg", 0, [-0.1, 0.915, -0.027]], ["RightShin", 21, [-0.11, 0.5, -0.03]], ["RightFoot", 22, [-0.12, 0.08, -0.05]],+];+// the trunk's skin: an oval 30 cm across and 21 cm deep (its middle 4 cm behind the hips' joint), from the hips to the neck+const FRONT = 0.065, BACK = -0.145, HALF = 0.15;+const surface: Skeleton["surface"] = [];+for (let y = 0.86; y <= 1.52; y += 0.012)+ for (let a = 0; a < 48; a++) {+ const t = (2 * Math.PI * a) / 48, x = HALF * Math.sin(t), z = Math.cos(t) >= 0 ? (FRONT + BACK) / 2 + ((FRONT - BACK) / 2) * Math.cos(t) : (FRONT + BACK) / 2 + ((FRONT - BACK) / 2) * Math.cos(t);+ surface.push({ part: y > 1.2 ? "chest" : y > 1.0 ? "torso" : "hips", side: "", j: [0], w: [1], o: [x, y - 0.998, z + 0.049], n: [Math.sin(t), 0, Math.cos(t)] });+ }+const skel = { name: "anatomy-test", height: 1.75, landmarks: { eyes: [0, 1.66, 0.07] }, surface, joints: JOINTS.map(([name, parent, head]) => ({ name, parent, head, tail: [head[0], head[1] + 0.02, head[2]] })) } as unknown as Skeleton;+const A = anatomyOf(skel);++test("it has the spine's 24 vertebrae, 24 ribs, the sternum, both lungs, the heart and the belly's organs", () => {+ const names = new Set(A.pieces.map((p) => p.name));+ expect(A.pieces.filter((p) => p.name.startsWith("vertebra-")).length).toBe(24);+ expect(A.pieces.filter((p) => /^rib-\d+-(left|right)$/.test(p.name)).length).toBe(24);+ for (const n of ["sternum", "lung-left", "lung-right", "heart", "aorta", "liver", "stomach", "kidney-left", "kidney-right", "skull", "femur-left"]) expect(names.has(n)).toBe(true);+});++test("the chest's pieces stay inside the trunk's skin", () => {+ const head = new Map(skel.joints.map((j) => [j.name, j.head as V3]));+ for (const p of A.pieces.filter((q) => /^(rib|lung|heart|liver|stomach|sternum|vertebra-T)/.test(q.name))) {+ const o = head.get(p.joint)!, P = p.geo.positions;+ for (let i = 0; i < P.length; i += 3) {+ const x = P[i] + o[0], z = P[i + 2] + o[2];+ const r = (x / HALF) ** 2 + ((z - (FRONT + BACK) / 2) / ((FRONT - BACK) / 2)) ** 2;+ if (r >= 1) throw new Error(`${p.name} reaches outside the skin at ${x.toFixed(3)}, ${(P[i + 1] + o[1]).toFixed(3)}, ${z.toFixed(3)}`);+ }+ }+});++test("a shot straight through the left chest goes in through the skin, then the heart and lung, in order", () => {+ const H = hits(skel, rest(skel), A, [0.06, 1.3, 5], [0, 0, -1]);+ expect(H[0].part).toBe("skin");+ expect(H[0].entry[2]).toBeCloseTo(FRONT, 1);+ const parts = H.map((h) => h.part);+ expect(parts.some((p) => p === "heart" || p === "lung-left")).toBe(true);+ for (let i = 1; i < H.length; i++) expect(H[i].t0).toBeGreaterThanOrEqual(H[i - 1].t0);+ for (const h of H) expect(h.t1).toBeGreaterThan(h.t0);+});++test("the shot finds the same pieces when the body is moved and turned, the shot with it", () => {+ const base = hits(skel, rest(skel), A, [0.06, 1.3, 5], [0, 0, -1]).map((h) => h.part);+ // the body turned a quarter left and moved: its front faces +x, so the same shot comes from +x+ const at = { position: [3, 0, -2] as V3, yaw: Math.PI / 2 };+ const turned = hits(skel, rest(skel), A, [3 + 5, 1.3, -2 - 0.06], [-1, 0, 0], at).map((h) => h.part);+ expect(turned).toEqual(base);+});