CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
55.5 kB
// People: a procedural humanoid, so a scene can have believable people without a model or an
// animation file.
//
// createHumanoid() returns a stylised mannequin with human proportions: one skinned mesh generated
// in code (about 2.7k triangles) on a 22-bone skeleton with Mixamo-style bone names, and a procedural
// animator. The game moves `humanoid.root` (feet at y = 0, facing -z) and says how fast it is going;
// update(dt) does the rest: stride length and cadence follow the speed and the leg length, the
// stance foot is held on the ground by two-bone IK while the pelvis bobs over it, the arms
// counter-swing, the spine twists and leans, and standing still breathes and shifts weight.
// Upper-body and whole-body actions (talk, wave, point, aim, crouch, sit, hit, fall) blend in and
// out. Nothing here is a likeness of anyone: appearance is height, build, colours and two or three
// clothing/hair shapes.
//
// The animation is a pure function of the sequence of set() and update(dt) calls: no random
// numbers and no wall clock, so a fixed-step replay shows the same motion every time.
//
// Conventions: metres, +Y up, the character faces -Z, its right hand is at +X. The bind pose is a
// T-pose with every bone axis-aligned, so the bone names match Mixamo but a Mixamo clip needs
// retargeting (SkeletonUtils.retargetClip) rather than playing directly. See README.md.
import * as THREE from './three.js';
const TAU = Math.PI * 2;
const HALF_PI = Math.PI / 2;
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
const fract = (x) => x - Math.floor(x);
const approach = (rate, dt) => 1 - Math.exp(-rate * dt);
// ---------------------------------------------------------------- skeleton
const PREFIX = 'mixamorig';
const SHOULDER_X = 0.098, ARM_Y = 0.794, UPPER_ARM = 0.165, FORE_ARM = 0.145; // the shoulder joint, a little under the shoulder's top
// [name, parent, x, y, z] as fractions of the height; the left side is at -x.
const JOINTS = [
['Hips', null, 0, 0.555, 0], ['Spine', 'Hips', 0, 0.605, 0], ['Spine1', 'Spine', 0, 0.665, 0],
['Spine2', 'Spine1', 0, 0.73, 0], ['Neck', 'Spine2', 0, 0.845, 0], ['Head', 'Neck', 0, 0.89, 0],
];
for (const [side, s] of [['Left', -1], ['Right', 1]]) {
JOINTS.push([`${side}Shoulder`, 'Spine2', s * 0.035, 0.806, 0], [`${side}Arm`, `${side}Shoulder`, s * SHOULDER_X, ARM_Y, 0],
[`${side}ForeArm`, `${side}Arm`, s * (SHOULDER_X + UPPER_ARM), ARM_Y, 0], [`${side}Hand`, `${side}ForeArm`, s * (SHOULDER_X + UPPER_ARM + FORE_ARM), ARM_Y, 0]);
}
for (const [side, s] of [['Left', -1], ['Right', 1]]) {
JOINTS.push([`${side}UpLeg`, 'Hips', s * 0.052, 0.525, 0], [`${side}Leg`, `${side}UpLeg`, s * 0.052, 0.285, 0],
[`${side}Foot`, `${side}Leg`, s * 0.052, 0.045, 0], [`${side}ToeBase`, `${side}Foot`, s * 0.052, 0.012, -0.075]);
}
const INDEX = Object.fromEntries(JOINTS.map(([name], i) => [name, i]));
/** The skeleton's bone names, in skeleton order. */
export const BONE_NAMES = JOINTS.map(([name]) => PREFIX + name);
// Body measures as fractions of the height.
const HIP_X = 0.052, HIP_DROP = 0.03, THIGH = 0.24, SHANK = 0.24, ANKLE = 0.045;
const TOE_Y = 0.012, TOE_FWD = 0.075, TOE_LEN = 0.04, HEEL_PIVOT = 0.024, HEEL_END = 0.034;
const SHOULDER_UP = ARM_Y - 0.73; // shoulder above Spine2
const STAND = 0.5545; // hips height standing: knees a touch off straight
// ---------------------------------------------------------------- gait
const GAIT_SPEED = [0, 0.5, 1.0, 1.4, 2.0, 2.6, 3.5, 6.0, 8.0, 10.0]; // m/s for a 1.75 m person
const GAIT_STEPS = [1.0, 1.25, 1.62, 1.89, 2.2, 2.55, 2.75, 3.1, 3.6, 4.2]; // steps per second
const GAIT_DUTY = [0.72, 0.68, 0.65, 0.62, 0.56, 0.44, 0.36, 0.26, 0.22, 0.2]; // share of a cycle a foot is down
function table(xs, ys, x) {
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];
}
/**
* The gait a person of `height` uses at ground `speed` (m/s): { strideLength (m, two steps),
* stepLength (m), cadence (steps per second), duty (share of the cycle each foot is down),
* run (0 walking .. 1 running) }. speed = stepLength * cadence. Taller people take longer,
* slower steps (speeds and times scale with the square root of the height).
*/
export function gaitFor(speed, height = 1.75) {
const k = Math.sqrt(Math.max(0.5, height) / 1.75), v = Math.abs(speed) / k;
const cadence = table(GAIT_SPEED, GAIT_STEPS, v) / k;
const stepLength = Math.abs(speed) / cadence;
return { strideLength: 2 * stepLength, stepLength, cadence, duty: table(GAIT_SPEED, GAIT_DUTY, v), run: smooth(2.0, 2.9, v) };
}
// ---------------------------------------------------------------- geometry
const SKIN = 0, HAIR = 1, TOP = 2, BOTTOM = 3, SHOES = 4;
const PARTS = ['skin', 'hair', 'top', 'bottom', 'shoes'];
// Head outline from chin (t = 0) to crown (t = 1): [t, half width, front z, back z].
const HEAD_Y0 = 0.868, HEAD_H = 0.132, HEAD_ZC = -0.005;
const HEAD = [
[0.03, 0.016, -0.050, -0.008], [0.10, 0.029, -0.0585, 0.012], [0.22, 0.037, -0.061, 0.030],
[0.36, 0.0415, -0.062, 0.043], [0.50, 0.0438, -0.061, 0.050], [0.64, 0.0445, -0.0615, 0.053],
[0.77, 0.043, -0.057, 0.051], [0.88, 0.036, -0.045, 0.041], [0.96, 0.022, -0.026, 0.024],
];
function headAt(t) {
if (t <= HEAD[0][0]) return HEAD[0];
for (let i = 1; i < HEAD.length; i++) {
if (t <= HEAD[i][0]) {
const a = HEAD[i - 1], b = HEAD[i], f = (t - a[0]) / (b[0] - a[0]);
return [t, lerp(a[1], b[1], f), lerp(a[2], b[2], f), lerp(a[3], b[3], f)];
}
}
return HEAD[HEAD.length - 1];
}
const FACE_SQUARE = 2.5;
/** z of the face surface at head height t and sideways offset x. */
function faceZ(t, x) {
const [, rx, front] = headAt(t);
const depth = HEAD_ZC - front, f = clamp(Math.abs(x) / rx, 0, 1);
return HEAD_ZC - depth * (1 - f ** FACE_SQUARE) ** (1 / FACE_SQUARE);
}
// A closed outline of n points around c in the plane of the unit axes u and v: half size ru
// along u, rvPos along +v and rvNeg along -v; e > 2 squares the outline (2 is an ellipse).
function ring(n, c, u, v, ru, rvPos, rvNeg = rvPos, ePos = 2, eNeg = ePos, start = HALF_PI) {
const out = [];
for (let k = 0; k < n; k++) {
const a = start + (k / n) * TAU, cs = Math.cos(a), sn = Math.sin(a), e = sn >= 0 ? ePos : eNeg;
const pu = Math.sign(cs) * Math.abs(cs) ** (2 / e) * ru;
const pv = Math.sign(sn) * Math.abs(sn) ** (2 / e) * (sn >= 0 ? rvPos : rvNeg);
out.push([c[0] + u[0] * pu + v[0] * pv, c[1] + u[1] * pu + v[1] * pv, c[2] + u[2] * pu + v[2] * pv]);
}
return out;
}
const AX = [1, 0, 0], AY = [0, 1, 0], AZ = [0, 0, 1], FRONT = [0, 0, -1];
function buildGeometry(height, build, hair, sleeves) {
const positions = [], shades = [], weights = [];
const triangles = PARTS.map(() => []);
const add = (p, w, shade = 1) => { positions.push(p[0], p[1], p[2]); weights.push(w); shades.push(shade); return weights.length - 1; };
const tri = (a, b, c, mat) => triangles[mat].push(a, b, c);
const B = (name) => INDEX[name];
// rows: [{ pts, mat, shade, gap }]: consecutive rows are joined by quads in the later row's
// material unless it has gap (a coincident copy, for a hard edge). start/end: cap points.
function loft(rows, weightOf, { start = null, end = null } = {}) {
const n = rows[0].pts.length;
const ids = rows.map((row) => row.pts.map((p) => add(p, weightOf(p), typeof row.shade === 'function' ? row.shade(p) : row.shade ?? 1)));
const centres = rows.map((row) => row.pts.reduce((sum, p) => [sum[0] + p[0] / n, sum[1] + p[1] / n, sum[2] + p[2] / n], [0, 0, 0]));
let outward = 0;
for (let i = 0; i + 1 < rows.length; i++) {
if (rows[i + 1].gap) continue;
for (let k = 0; k < n; k++) {
const a = rows[i].pts[k], b = rows[i].pts[(k + 1) % n], c = rows[i + 1].pts[k], o = centres[i];
const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2], vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
outward += (uy * vz - uz * vy) * (a[0] - o[0]) + (uz * vx - ux * vz) * (a[1] - o[1]) + (ux * vy - uy * vx) * (a[2] - o[2]);
}
}
const put = (a, b, c, mat) => (outward >= 0 ? tri(a, b, c, mat) : tri(a, c, b, mat));
for (let i = 0; i + 1 < rows.length; i++) {
if (rows[i + 1].gap) continue;
for (let k = 0; k < n; k++) {
const k1 = (k + 1) % n;
put(ids[i][k], ids[i][k1], ids[i + 1][k], rows[i + 1].mat);
put(ids[i][k1], ids[i + 1][k1], ids[i + 1][k], rows[i + 1].mat);
}
}
if (start) {
const tip = add(start, weightOf(start), typeof rows[0].shade === 'function' ? rows[0].shade(start) : rows[0].shade ?? 1);
for (let k = 0; k < n; k++) put(tip, ids[0][(k + 1) % n], ids[0][k], rows[0].mat ?? rows[1].mat);
}
if (end) {
const last = rows.length - 1;
const tip = add(end, weightOf(end), typeof rows[last].shade === 'function' ? rows[last].shade(end) : rows[last].shade ?? 1);
for (let k = 0; k < n; k++) put(ids[last][k], ids[last][(k + 1) % n], tip, rows[last].mat);
}
}
// A triangle facing the given direction.
const facing = (a, b, c, mat, dir) => {
const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3), pc = positions.slice(c * 3, c * 3 + 3);
const ux = pb[0] - pa[0], uy = pb[1] - pa[1], uz = pb[2] - pa[2], vx = pc[0] - pa[0], vy = pc[1] - pa[1], vz = pc[2] - pa[2];
const d = (uy * vz - uz * vy) * dir[0] + (uz * vx - ux * vz) * dir[1] + (ux * vy - uy * vx) * dir[2];
if (d >= 0) tri(a, b, c, mat); else tri(a, c, b, mat);
};
const girthW = lerp(0.9, 1.16, build), girthD = lerp(0.86, 1.3, build), girthL = lerp(0.87, 1.22, build);
const belly = Math.max(0, build - 0.45) * 0.09;
// ---- torso and neck
const spine = [['Spine', 0.605, 0.025], ['Spine1', 0.665, 0.03], ['Spine2', 0.73, 0.03], ['Neck', 0.845, 0.018], ['Head', 0.89, 0.014]];
const spineWeights = (y) => {
let bone = B('Hips');
for (const [name, at, half] of spine) {
const t = smooth(at - half, at + half, y);
if (t <= 0) break;
if (t < 1) return [[bone, 1 - t], [B(name), t]];
bone = B(name);
}
return [[bone, 1]];
};
const torsoWeights = (p) => {
const base = spineWeights(p[1]);
const s = smooth(0.04, 0.08, Math.abs(p[0])) * smooth(0.765, 0.8, p[1]) * (1 - smooth(0.835, 0.85, p[1])) * 0.7;
if (s <= 0) return base;
return [...base.map(([bone, w]) => [bone, w * (1 - s)]), [B(p[0] < 0 ? 'LeftShoulder' : 'RightShoulder'), s]];
};
// y, half width, front, back, squareness, material
const TORSO = [
[0.49, 0.044, 0.034, 0.042, 2.2, BOTTOM], [0.506, 0.086, 0.049, 0.06, 2.4, BOTTOM], [0.532, 0.097, 0.059, 0.068, 2.5, BOTTOM],
[0.552, 0.095, 0.060, 0.064, 2.5, BOTTOM],
[0.536, 0.1, 0.0625, 0.071, 2.5, TOP, 'hem'], [0.563, 0.096, 0.063, 0.065, 2.5, TOP], [0.59, 0.088, 0.061, 0.056, 2.4, TOP],
[0.62, 0.082, 0.058, 0.051, 2.4, TOP], [0.67, 0.084, 0.060, 0.053, 2.5, TOP],
[0.72, 0.087, 0.066, 0.057, 2.6, TOP], [0.765, 0.088, 0.067, 0.061, 2.6, TOP], [0.80, 0.091, 0.059, 0.059, 2.5, TOP],
[0.826, 0.081, 0.043, 0.05, 2.3, TOP], [0.846, 0.043, 0.037, 0.041, 2, TOP],
[0.849, 0.034, 0.033, 0.035, 2, SKIN, 'collar'], [0.87, 0.031, 0.031, 0.034, 2, SKIN], [0.897, 0.030, 0.030, 0.033, 2, SKIN],
];
const torsoRows = [];
for (const [y, rx, front, back, e, mat, edge] of TORSO) {
const shoulders = smooth(0.75, 0.8, y), neck = smooth(0.84, 0.85, y);
const w = lerp(lerp(girthW, lerp(0.97, 1.05, build), shoulders), lerp(0.95, 1.1, build), neck);
const d = lerp(girthD, lerp(0.95, 1.12, build), neck);
const bulge = belly * Math.exp(-(((y - 0.635) / 0.065) ** 2));
const zc = y > 0.846 ? -0.006 * smooth(0.846, 0.897, y) : 0;
const row = { pts: ring(14, [0, y, zc], AX, FRONT, rx * w, front * d + bulge, back * d + bulge * 0.15, e), mat };
if (edge) torsoRows.push({ ...torsoRows[torsoRows.length - 1], gap: true }, { ...row }, { ...row, gap: true });
else torsoRows.push(row);
}
loft(torsoRows, torsoWeights, { start: [0, 0.484, 0], end: [0, 0.9, -0.006] });
for (const s of [-1, 1]) {
const side = s < 0 ? 'Left' : 'Right';
// ---- leg: a ball at the hip inside the pelvis, a smooth knee, a hem inside the shoe
const LEG = [
[0.572, 0.020, 0.022, 0.024], [0.553, 0.039, 0.043, 0.047], [0.525, 0.047, 0.053, 0.057], [0.49, 0.0485, 0.054, 0.057],
[0.455, 0.0475, 0.053, 0.053], [0.40, 0.044, 0.049, 0.048], [0.345, 0.039, 0.043, 0.041],
[0.315, 0.0345, 0.038, 0.037], [0.30, 0.0335, 0.038, 0.036], [0.285, 0.033, 0.0385, 0.035], [0.27, 0.0325, 0.036, 0.035],
[0.255, 0.0325, 0.034, 0.037], [0.215, 0.033, 0.031, 0.041], [0.15, 0.029, 0.028, 0.034], [0.09, 0.0265, 0.026, 0.028],
[0.052, 0.0255, 0.025, 0.026],
];
const legWeights = (p) => {
const t = smooth(0.317, 0.253, p[1]);
return t <= 0 ? [[B(`${side}UpLeg`), 1]] : t >= 1 ? [[B(`${side}Leg`), 1]] : [[B(`${side}UpLeg`), 1 - t], [B(`${side}Leg`), t]];
};
loft(LEG.map(([y, rx, front, back]) => ({ pts: ring(10, [s * HIP_X, y, 0], AX, FRONT, rx * girthL, front * girthL, back * girthL), mat: BOTTOM })),
legWeights, { start: [s * HIP_X, 0.578, 0], end: [s * HIP_X, 0.05, 0] });
// ---- shoe: flat sole, a mound round the ankle, toes on their own bone
const SHOE = [
[0.036, 0.014, 0.040, 0.011], [0.028, 0.0235, 0.060, 0.016], [0.012, 0.0285, 0.074, 0.016], [-0.006, 0.030, 0.076, 0.016],
[-0.024, 0.031, 0.066, 0.016], [-0.045, 0.032, 0.050, 0.016], [-0.062, 0.033, 0.040, 0.016], [-0.075, 0.033, 0.035, 0.016],
[-0.090, 0.032, 0.031, 0.016], [-0.105, 0.027, 0.027, 0.015], [-0.114, 0.017, 0.022, 0.010],
];
const shoeScale = 1 + 0.08 * (build - 0.5);
const shoeWeights = (p) => {
const t = smooth(-0.062, -0.088, p[2]);
return t <= 0 ? [[B(`${side}Foot`), 1]] : t >= 1 ? [[B(`${side}ToeBase`), 1]] : [[B(`${side}Foot`), 1 - t], [B(`${side}ToeBase`), t]];
};
const soleShade = (p) => (p[1] < 0.0085 ? 0.5 : 1);
loft(SHOE.map(([z, rx, top, mid]) => ({ pts: ring(10, [s * HIP_X, mid, z], AX, AY, rx * shoeScale, top - mid, mid, 2.2, 5), mat: SHOES, shade: soleShade })),
shoeWeights, { start: [s * HIP_X, 0.022, 0.0395], end: [s * HIP_X, 0.012, -0.118] });
// ---- arm: a ball at the shoulder, a smooth elbow, an optional short sleeve
const short = sleeves === 'short';
const ARM = [ // distance from the shoulder joint, half height, half depth
[-0.025, 0.017, 0.017], [-0.014, 0.026, 0.026], [0, 0.030, 0.0305], [0.02, 0.0295, 0.030], [0.055, 0.0275, 0.0285],
[0.095, 0.0255, 0.0265], [0.13, 0.0235, 0.0245], [0.145, 0.0225, 0.0232], [0.155, 0.022, 0.0225], [0.165, 0.022, 0.0222],
[0.175, 0.022, 0.0225], [0.185, 0.0225, 0.0235], [0.215, 0.022, 0.0245], [0.265, 0.018, 0.0205], [0.298, 0.0135, 0.017],
].map(([x, ry, rz]) => [SHOULDER_X + x, ry, rz]);
const sleeveEnd = SHOULDER_X + (short ? 0.095 : 0.265);
const armRows = [];
for (const [x, ry, rz] of ARM) {
const clothed = x <= sleeveEnd + 1e-6;
const fat = girthL * (clothed ? (short ? 1.1 : 1.07) : 1);
const row = { pts: ring(8, [s * x, ARM_Y, 0], AZ, AY, rz * fat, ry * fat), mat: clothed ? TOP : SKIN };
armRows.push(row);
if (Math.abs(x - sleeveEnd) < 1e-6) {
const bare = { pts: ring(8, [s * x, ARM_Y, 0], AZ, AY, rz * girthL * 0.98, ry * girthL * 0.98), mat: TOP };
armRows.push({ ...row, gap: true }, bare, { ...bare, gap: true, mat: SKIN });
}
}
const armWeights = (p) => {
const x = Math.abs(p[0]) - SHOULDER_X, t = smooth(0.143, 0.187, x);
return t <= 0 ? [[B(`${side}Arm`), 1]] : t >= 1 ? [[B(`${side}ForeArm`), 1]] : [[B(`${side}Arm`), 1 - t], [B(`${side}ForeArm`), t]];
};
loft(armRows, armWeights, { start: [s * (SHOULDER_X - 0.031), ARM_Y, 0] });
// ---- hand: a mitt with a thumb, fingers slightly curled
const handScale = 1 + 0.12 * (build - 0.5);
const WRIST = SHOULDER_X + UPPER_ARM + FORE_ARM;
const HAND = [ // distance from the wrist, half thickness, half width, drop
[-0.012, 0.0125, 0.016, 0], [0.005, 0.012, 0.018, 0], [0.025, 0.012, 0.024, -0.001], [0.05, 0.011, 0.0255, -0.002],
[0.073, 0.009, 0.0238, -0.005], [0.088, 0.0072, 0.021, -0.01], [0.097, 0.0045, 0.015, -0.015],
].map(([x, ...rest]) => [WRIST + x, ...rest]);
const handWeights = (p) => {
const t = smooth(-0.017, 0.01, Math.abs(p[0]) - WRIST);
return t >= 1 ? [[B(`${side}Hand`), 1]] : [[B(`${side}ForeArm`), 1 - t], [B(`${side}Hand`), t]];
};
loft(HAND.map(([x, ry, rz, drop]) => ({ pts: ring(8, [s * x, ARM_Y + drop, 0], AZ, AY, rz * handScale, ry * handScale, ry * handScale, 2.6, 2.6), mat: SKIN })),
handWeights, { end: [s * (WRIST + 0.101), ARM_Y - 0.017, 0] });
const thumbA = [s * (WRIST + 0.017), ARM_Y - 0.003, -0.019], thumbB = [s * (WRIST + 0.065), ARM_Y - 0.013, -0.044];
const axis = [thumbB[0] - thumbA[0], thumbB[1] - thumbA[1], thumbB[2] - thumbA[2]];
const len = Math.hypot(...axis), dir = axis.map((x) => x / len);
const side1 = [0, 1, 0], side2 = [dir[1] * side1[2] - dir[2] * side1[1], dir[2] * side1[0] - dir[0] * side1[2], dir[0] * side1[1] - dir[1] * side1[0]];
const n2 = Math.hypot(...side2), u2 = side2.map((x) => x / n2);
loft([0, 0.5, 0.92].map((f, i) => ({ pts: ring(5, thumbA.map((x, j) => x + axis[j] * f), u2, side1, [0.0085, 0.008, 0.0055][i] * handScale, [0.0075, 0.007, 0.005][i] * handScale), mat: SKIN })),
() => [[B(`${side}Hand`), 1]], { start: thumbA.map((x, j) => x - dir[j] * 0.004), end: thumbB });
}
// ---- head: a flattened face plane, nose, ears, eyes, brows and mouth
const head = [[B('Head'), 1]];
const headY = (t) => HEAD_Y0 + HEAD_H * t;
const headRing = (t, grow = 1, lift = 0, n = 14) => {
const [, rx, front, back] = headAt(t);
const flat = lerp(2, FACE_SQUARE, smooth(0.08, 0.3, t) * (1 - smooth(0.7, 0.92, t)));
return ring(n, [0, headY(t) + lift, HEAD_ZC], AX, FRONT, rx * grow, (HEAD_ZC - front) * grow, (back - HEAD_ZC) * grow, flat, 2);
};
loft(HEAD.map(([t]) => ({ pts: headRing(t), mat: SKIN })), () => head, { start: [0, HEAD_Y0 - 0.002, -0.03], end: [0, headY(1), -0.004] });
const facePoint = (x, t, out = 0.0012) => add([x, headY(t), faceZ(t, x) - out], head);
const patch = (x, t, halfW, halfT, mat, shade, out = 0.0014) => {
const ids = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([i, j]) => add([x + i * halfW, headY(t + j * halfT), faceZ(t + j * halfT, x + i * halfW) - out], head, shade));
facing(ids[0], ids[1], ids[2], mat, FRONT); facing(ids[0], ids[2], ids[3], mat, FRONT);
};
const browMat = hair === 'none' ? SKIN : HAIR, browShade = hair === 'none' ? [0.42, 0.36, 0.34] : 1;
for (const s of [-1, 1]) {
patch(s * 0.0172, 0.535, 0.0066, 0.022, SKIN, [0.1, 0.09, 0.09]);
patch(s * 0.0175, 0.625, 0.0095, 0.014, browMat, browShade);
const [, rx] = headAt(0.47);
const ear = [[0, 0.56, -0.004], [0, 0.47, -0.011], [0, 0.375, -0.003], [0, 0.47, 0.007]].map(([, t, z]) => add([s * headAt(t)[1] * 0.97, headY(t), HEAD_ZC + 0.012 + z], head));
const tip = add([s * (rx + 0.0055), headY(0.47), HEAD_ZC + 0.019], head);
for (let k = 0; k < 4; k++) facing(ear[k], ear[(k + 1) % 4], tip, SKIN, [s, 0, k < 2 ? -0.6 : 0.6]);
}
patch(0, 0.2, 0.0125, 0.012, SKIN, [0.62, 0.36, 0.34]);
const bridge = facePoint(0, 0.57, 0.002), tipN = add([0, headY(0.37), faceZ(0.37, 0) - 0.0165], head);
const wingL = facePoint(-0.0095, 0.335, 0.0005), wingR = facePoint(0.0095, 0.335, 0.0005), under = facePoint(0, 0.31, 0.001);
facing(bridge, wingL, tipN, SKIN, [-0.7, 0.2, -0.6]); facing(bridge, tipN, wingR, SKIN, [0.7, 0.2, -0.6]);
facing(tipN, wingL, under, SKIN, [-0.3, -1, -0.3]); facing(tipN, under, wingR, SKIN, [0.3, -1, -0.3]);
// ---- hair: a cap over the skull, longer at the back for 'long'
if (hair !== 'none') {
const long = hair === 'long';
const n = 14, rowsCount = long ? 8 : 5, nape = long ? -0.5 : 0.14, temple = long ? 0.42 : 0.5;
const hairline = (a) => {
const sn = Math.sin(a);
return sn >= 0 ? lerp(temple, 0.775, smooth(0.05, 0.8, sn)) : lerp(temple, nape, smooth(0, long ? 0.4 : 0.75, -sn));
};
const hairRows = [];
for (let j = 1; j <= rowsCount; j++) {
const pts = [];
for (let k = 0; k < n; k++) {
const a = HALF_PI + (k / n) * TAU;
const t = j === 1 ? 0.94 : lerp(0.86, hairline(a), (j - 2) / (rowsCount - 2));
const at = Math.max(t, 0.26), grow = 1.085 + 0.28 * (at - t), p = headRing(at, grow, 0, n)[k];
pts.push([p[0], headY(t) + 0.0065 * smooth(0.5, 1, t), p[2] + 0.012 * (at - t)]);
}
hairRows.push({ pts, mat: HAIR });
}
const hairWeights = (p) => {
const t = (p[1] - HEAD_Y0) / HEAD_H, w = 0.2 + 0.8 * smooth(-0.5, 0.05, t);
return w >= 1 ? head : [[B('Head'), w], [B('Spine2'), 1 - w]];
};
loft(hairRows, hairWeights, { start: [0, headY(1) + 0.0075, -0.004] });
}
// ---- buffers
const count = weights.length;
const position = new Float32Array(count * 3), color = new Float32Array(count * 3);
const skinIndex = new Uint16Array(count * 4), skinWeight = new Float32Array(count * 4);
for (let i = 0; i < count; i++) {
for (let j = 0; j < 3; j++) position[i * 3 + j] = positions[i * 3 + j] * height;
const shade = shades[i];
color.set(typeof shade === 'number' ? [shade, shade, shade] : shade, i * 3);
const list = weights[i].filter(([, w]) => w > 1e-4).sort((a, b) => b[1] - a[1]).slice(0, 4);
const total = list.reduce((sum, [, w]) => sum + w, 0);
list.forEach(([bone, w], j) => { skinIndex[i * 4 + j] = bone; skinWeight[i * 4 + j] = w / total; });
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(position, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(color, 3));
geometry.setAttribute('skinIndex', new THREE.BufferAttribute(skinIndex, 4));
geometry.setAttribute('skinWeight', new THREE.BufferAttribute(skinWeight, 4));
const index = [];
triangles.forEach((list, mat) => {
if (!list.length) return;
geometry.addGroup(index.length, list.length, mat);
for (const i of list) index.push(i);
});
geometry.setIndex(index);
geometry.computeVertexNormals();
// Poses reach well outside the bind pose (a fall lies a body length behind the root).
geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, height * 0.5, height * 0.2), height * 1.15);
geometry.boundingBox = new THREE.Box3(new THREE.Vector3(-height, -0.1, -height), new THREE.Vector3(height, height * 1.25, height * 1.3));
geometry.userData.triangles = index.length / 3;
return geometry;
}
const geometryCache = new Map(); // key -> { geometry, users }
const materialCache = new Map(); // key -> { material, users }
function acquireGeometry(height, build, hair, sleeves) {
const key = `${height.toFixed(3)}|${build.toFixed(2)}|${hair}|${sleeves}`;
let entry = geometryCache.get(key);
if (!entry) { entry = { geometry: buildGeometry(height, build, hair, sleeves), users: 0 }; geometryCache.set(key, entry); }
entry.users++;
return [key, entry.geometry];
}
const ROUGHNESS = { skin: 0.62, hair: 0.55, top: 0.88, bottom: 0.9, shoes: 0.5 };
function acquireMaterial(part, color, doubleSided) {
const hex = new THREE.Color(color).getHexString();
const key = `${part}|${hex}|${doubleSided ? 2 : 1}`;
let entry = materialCache.get(key);
if (!entry) {
const material = new THREE.MeshStandardMaterial({ color: new THREE.Color(color), roughness: ROUGHNESS[part], metalness: 0, vertexColors: true,
side: doubleSided ? THREE.DoubleSide : THREE.FrontSide });
// look.adopt() reads this: cloth for clothes, plain for the rest; a moving thing.
material.userData = { surface: part === 'top' || part === 'bottom' ? 'fabric' : 'generic', dynamic: true, humanoid: part };
entry = { material, users: 0 };
materialCache.set(key, entry);
}
entry.users++;
return [key, entry.material];
}
// ---------------------------------------------------------------- animation
const ACTIONS = ['talk', 'wave', 'point', 'aim', 'crouch', 'sit', 'hit', 'fall'];
const ACTION_RATE = { talk: 6, wave: 7, point: 9, aim: 9, crouch: 6, sit: 3.2, hit: 30 };
const DEFAULT_COLORS = { skin: 0xc58c66, hair: 0x2a1d15, top: 0x4b6b8c, bottom: 0x2f3542, shoes: 0x1d1d20 };
function mulberry(seed) {
let a = (seed >>> 0) || 1;
return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const _e = new THREE.Euler(0, 0, 0, 'YXZ');
const _m = new THREE.Matrix4();
const _v1 = new THREE.Vector3(), _v2 = new THREE.Vector3(), _v3 = new THREE.Vector3(), _v4 = new THREE.Vector3();
const _vx = new THREE.Vector3(), _vy = new THREE.Vector3(), _vz = new THREE.Vector3();
const _q1 = new THREE.Quaternion(), _q2 = new THREE.Quaternion(), _q3 = new THREE.Quaternion(), _q4 = new THREE.Quaternion();
const _qPelvis = new THREE.Quaternion(), _qChest = new THREE.Quaternion(), _qInv = new THREE.Quaternion();
const _qUpper = new THREE.Quaternion(), _qLower = new THREE.Quaternion(), _qUpperIk = new THREE.Quaternion(), _qLowerIk = new THREE.Quaternion();
const _hip = new THREE.Vector3(), _ankle = [new THREE.Vector3(), new THREE.Vector3()], _pelvis = new THREE.Vector3();
const IDENTITY = new THREE.Quaternion();
/** Rotation from pitch (about x, up positive), yaw (about y, left positive) and roll (about z). */
const euler = (q, pitch, yaw, roll) => q.setFromEuler(_e.set(pitch, yaw, roll, 'YXZ'));
const basis = (q, x, y, z) => q.setFromRotationMatrix(_m.makeBasis(x, y, z));
class Humanoid {
constructor(options = {}) {
const colors = { ...DEFAULT_COLORS, ...(options.colours || {}), ...(options.colors || {}) };
this.height = clamp(Number(options.height) || 1.75, 0.8, 2.3);
this.build = clamp(options.build ?? 0.5, 0, 1);
this.hair = ['none', 'short', 'long'].includes(options.hair) ? options.hair : 'short';
this.sleeves = options.sleeves === 'short' ? 'short' : 'long';
this.seed = options.seed ?? 1;
const H = this.height;
this.root = new THREE.Group();
this.root.name = 'humanoid';
const bones = JOINTS.map(([name]) => { const bone = new THREE.Bone(); bone.name = PREFIX + name; return bone; });
const inverses = [];
JOINTS.forEach(([, parent, x, y, z], i) => {
const from = parent ? JOINTS[INDEX[parent]] : [0, 0, 0, 0, 0];
bones[i].position.set((x - from[2]) * H, (y - from[3]) * H, (z - from[4]) * H);
if (parent) bones[INDEX[parent]].add(bones[i]);
inverses.push(new THREE.Matrix4().makeTranslation(-x * H, -y * H, -z * H));
});
this.bones = Object.fromEntries(JOINTS.map(([name], i) => [name, bones[i]]));
this._rest = bones.map((bone) => bone.position.clone());
this.skeleton = new THREE.Skeleton(bones, inverses);
const [geometryKey, geometry] = acquireGeometry(H, this.build, this.hair, this.sleeves);
this._geometryKey = geometryKey;
this._materialKeys = [];
const materials = PARTS.map((part) => {
const [key, material] = acquireMaterial(part, colors[part], part === 'hair' && this.hair === 'long');
this._materialKeys.push(key);
return material;
});
this.mesh = new THREE.SkinnedMesh(geometry, materials);
this.mesh.name = 'humanoid-body';
this.mesh.castShadow = true;
this.mesh.receiveShadow = true;
this.mesh.userData.dynamic = true;
this.mesh.boundingSphere = geometry.boundingSphere.clone();
this.mesh.boundingBox = geometry.boundingBox.clone();
this.root.add(bones[0], this.mesh);
this.mesh.bind(this.skeleton, new THREE.Matrix4());
this.triangles = geometry.userData.triangles;
const random = mulberry(Math.imul((this.seed | 0) + 17, 2654435761));
this._offsets = [random() * TAU, random() * TAU, random() * TAU, random() * TAU, random() * TAU];
this._time = random() * 40;
this._lead = random() < 0.5 ? 0 : 1; // which foot stays down when setting off
this._phase = this._lead * 0.5 + 0.1;
this._stepping = false;
this._rise = 0;
this._height = STAND * H;
this._step = 1;
this._speed = 0; this._turn = 0; this._action = 'none'; this._aimPitch = 0; this._lookAt = null; this._seat = null;
this._vs = 0; this._ws = 0;
this._w = Object.fromEntries(ACTIONS.map((name) => [name, 0]));
this._actionTime = 0; this._hitTime = 10; this._fall = 0;
this._headYaw = 0; this._headPitch = 0;
this._style = {};
this._feet = [-1, 1].map((side) => ({ side, planted: true, x: side * H * 0.058, z: H * 0.01, yaw: -side * 0.14, pitch: 0, lift: 0, toeFlat: 1,
x0: 0, z0: 0, yaw0: 0, pitch0: 0, from: 0.7, last: 0, tau: 0 }));
/** Which feet are on the ground (for footstep sounds and tests). */
this.footDown = { left: true, right: true };
/** Gait phase 0..1: the left foot lands at 0, the right at 0.5. */
this.phase = this._phase;
this._updateStyle();
this._pose();
}
/**
* Say what the person is doing. Any subset of: speed (m/s along its facing, negative backs up),
* turn (rad/s, the rate of root.rotation.y: positive turns left), action ('none', 'talk', 'wave',
* 'point', 'aim', 'crouch', 'sit', 'hit', 'fall'), aimPitch (rad, up positive, for point and aim),
* lookAt (world Vector3 for the head and for point, or null), seat (m, the chair height for sit).
*/
set(state = {}) {
if (Number.isFinite(state.speed)) this._speed = state.speed;
if (Number.isFinite(state.turn)) this._turn = state.turn;
if (Number.isFinite(state.aimPitch)) this._aimPitch = clamp(state.aimPitch, -1.2, 1.2);
if (state.seat !== undefined) this._seat = Number.isFinite(state.seat) ? state.seat : null;
if (state.lookAt !== undefined) {
if (!state.lookAt) this._lookAt = null;
else (this._lookAt || (this._lookAt = new THREE.Vector3())).copy(state.lookAt);
}
if (state.action !== undefined) {
const action = ACTIONS.includes(state.action) ? state.action : 'none';
if (action !== this._action) {
this._action = action;
this._actionTime = 0;
if (action === 'hit') this._hitTime = 0;
}
}
return this;
}
/** Advance the animation by dt seconds and pose the skeleton. Call after moving `root`. */
update(dt) {
const step = Number.isFinite(dt) && dt > 0 ? Math.min(dt, 1) : 0;
const count = Math.max(1, Math.ceil(step * 30 - 1e-9));
for (let i = 0; i < count; i++) this._advance(step / count);
this._step = step;
this._pose();
return this;
}
dispose() {
this.root.removeFromParent();
this.skeleton.dispose();
const geometry = geometryCache.get(this._geometryKey);
if (geometry && --geometry.users <= 0) { geometry.geometry.dispose(); geometryCache.delete(this._geometryKey); }
for (const key of this._materialKeys) {
const entry = materialCache.get(key);
if (entry && --entry.users <= 0) { entry.material.dispose(); materialCache.delete(key); }
}
this._materialKeys = [];
}
// The numbers that shape the gait at the current (smoothed) speed.
_updateStyle() {
const H = this.height, k = Math.sqrt(H / 1.75), s = this._style, w = this._w;
const still = Math.max(w.sit, this._fallBlend());
const veff = Math.max(Math.abs(this._vs), Math.abs(this._ws) * 0.7 * k);
const gait = gaitFor(veff, H), run = gait.run;
const a = Math.abs(this._vs) / k, sp = Math.min(1.45, a / 1.4), back = this._vs < -0.02, fast = Math.max(0, sp - 1);
s.veff = veff; s.run = run; s.duty = gait.duty; s.back = back;
s.cadence = gait.cadence * (1 + 0.8 * w.crouch) * (back ? 1.4 : 1); // crouched and backward steps are short and quick
s.move = smooth(0.03, 0.45, veff / k) * (1 - still);
s.strike = back ? -0.2 * Math.min(1, a) * s.move : 0.3 * Math.min(1, a / 1.1) * (1 - 0.85 * run) * s.move;
s.toeOff = (back ? 0.15 : lerp(0.2 + 0.75 * Math.min(1, a / 1.2), 1.2, run)) * s.move;
s.flat = lerp(0.16, 0.08, run); s.heelOff = lerp(0.48, 0.28, run);
s.swingLift = H * lerp(0.028 + 0.014 * Math.min(1, sp), 0.13 + 0.07 * clamp((a - 2.5) / 3.5, 0, 1.6), run);
s.liftPow = lerp(0.82, 0.62, run);
s.carry = lerp(0.55, 0.22, run); // how much of the ground's speed the foot keeps as it leaves and lands
s.drop = H * lerp(0.003 + 0.019 * Math.min(1, sp) ** 1.5 + 0.045 * fast, 0.052, run) * s.move + H * (0.2 - 0.06 * s.move) * w.crouch;
s.bob = H * lerp(0.014 * Math.min(1, sp) ** 1.3, -0.026, run) * s.move;
s.pelvisYaw = lerp(0.085 * sp + 0.12 * fast, 0.12, run) * s.move;
s.pelvisRoll = lerp(0.05 * Math.min(1.1, sp), 0.045, run) * s.move;
s.sway = H * lerp(0.016 - 0.005 * Math.min(1, sp), 0.007, run) * s.move;
s.chestYaw = lerp(0.075 * sp, 0.17, run) * s.move;
s.lean = (0.015 + 0.03 * Math.min(1, sp) + (0.1 + 0.012 * Math.max(0, a - 3.5)) * run) * s.move * (back ? -0.3 : 1)
+ clamp((this._speed - this._vs) * 0.05, -0.12, 0.15) * (1 - still);
s.armFwd = lerp(0.44 * sp ** 0.9, 0.78, run) * s.move;
s.armBack = lerp(0.34 * sp ** 0.9, 0.8, run) * s.move;
s.width = H * lerp(lerp(0.058, 0.04, Math.min(1, sp)), 0.02, run);
s.reach = back ? -0.5 : lerp(0.4, 0.36, run);
}
_fallBlend() { return this._fall ** 1.8; }
_advance(dt) {
const H = this.height, w = this._w, s = this._style;
this._time += dt;
this._actionTime += dt;
this._hitTime += dt;
this._vs += (this._speed - this._vs) * approach(7, dt);
this._ws += (this._turn - this._ws) * approach(6, dt);
for (const name of ACTIONS) if (name !== 'fall') w[name] += ((this._action === name ? 1 : 0) - w[name]) * approach(ACTION_RATE[name], dt);
this._fall = clamp(this._fall + (this._action === 'fall' ? dt / 0.8 : -dt / 1.3), 0, 1);
w.fall = this._fallBlend();
this._updateStyle();
const hold = this._action === 'sit' || this._action === 'fall' || w.fall > 0.02;
const v = hold ? 0 : this._speed, turn = hold ? 0 : this._turn;
const moving = !hold && (Math.abs(v) > 0.03 || Math.abs(turn) > 0.1);
const feet = this._feet, homeZ = H * 0.01, toeOut = 0.14;
let stepping = moving;
if (!moving) {
for (const foot of feet) {
const away = Math.abs(foot.x - foot.side * s.width) > H * 0.045 || Math.abs(foot.z - homeZ) > H * 0.035 || Math.abs(foot.yaw + foot.side * toeOut) > 0.3;
if (!foot.planted || (!hold && away)) stepping = true;
}
}
// The phase follows the distance covered, so a stance never carries a foot further than the
// stride at the smoothed speed, however abruptly the speed changes.
const k = Math.sqrt(H / 1.75), rawEff = Math.max(Math.abs(v), Math.abs(turn) * 0.7 * k);
const cadence = moving ? s.cadence * clamp(rawEff / Math.max(s.veff, 0.05), 0, 4) : Math.max(s.cadence, 1.75);
const duty = s.duty, stance = duty * 2 / s.cadence, swing = (1 - duty) * 2 / Math.max(cadence, 0.5);
if (moving && !this._stepping) { // setting off: one foot leaves at once, the other is mid-stance
this._lead = 1 - this._lead;
this._phase = this._lead * 0.5 + 0.36 * duty;
for (const foot of feet) foot.last = fract(this._phase + (foot.side < 0 ? 0 : 0.5));
}
const travel = Math.abs(this._vs) * stance, sign = s.back ? -1 : 1;
// Keep the phase in step with where the planted feet really are: a foot further through its
// stance than the phase says (the pace just changed) hurries the cycle, and the reverse.
let hurry = 0;
if (moving && travel > H * 0.08) {
let error = 0, count = 0;
for (const foot of feet) {
if (!foot.planted) continue;
const pf = fract(this._phase + (foot.side < 0 ? 0 : 0.5));
error += clamp(sign * (foot.z - homeZ) / travel + s.reach * sign - pf / duty, -0.5, 1); count++;
}
if (count) hurry = 5 * duty * error / count;
}
if (stepping) this._phase = fract(this._phase + Math.max(0, cadence / 2 + hurry) * dt);
this._stepping = stepping;
for (let i = 0; i < 2; i++) {
const foot = feet[i], prev = foot.last, pf = fract(this._phase + (foot.side < 0 ? 0 : 0.5));
foot.last = pf;
// A leg that has run out of reach (the pace dropped mid-stance) lifts early.
const spent = foot.planted && moving && sign * (foot.z - homeZ) > Math.min(travel * (1 - Math.abs(s.reach)) + H * 0.025, H * 0.42);
// Where the foot should land so that the middle of the next stance is under the hip.
const half = turn * stance * 0.5, hx = foot.side * s.width, hz = homeZ - travel * s.reach;
const tx = hx * Math.cos(half) + hz * Math.sin(half), tz = -hx * Math.sin(half) + hz * Math.cos(half), tyaw = -foot.side * toeOut + half;
// The part of this step the foot spends on the ground: landings and lift-offs fall inside a
// step, and the foot must not ride the ground before the one or after the other.
let share = 1;
if (!foot.planted && (!stepping || pf < prev - 0.5)) {
foot.planted = true; foot.lift = 0; foot.x = tx; foot.z = tz; foot.yaw = tyaw;
share = stepping ? pf / Math.max(pf + 1 - prev, 1e-6) : 0;
}
const leaving = foot.planted && stepping && (pf >= duty || spent);
if (leaving) share = prev < duty && pf > prev && pf >= duty ? (duty - prev) / (pf - prev) : 0;
let goal;
if (foot.planted) {
// The ground moves under the root: round at its yaw rate, then back at its speed (the
// order of `root.rotation.y += turn * dt; root.translateZ(-speed * dt)`).
const angle = turn * dt * share, x = foot.x, z = foot.z;
foot.x = x * Math.cos(angle) - z * Math.sin(angle);
foot.z = x * Math.sin(angle) + z * Math.cos(angle) + v * dt * share;
foot.yaw -= angle;
}
if (foot.planted && !leaving) {
const u = stepping ? pf / duty : 0.3;
if (s.back) goal = s.strike * (1 - smooth(0, 0.25, u)) + s.toeOff * smooth(0.8, 1, u);
else if (u < s.flat) goal = s.strike * (1 - smooth(0, s.flat, u));
else if (u > s.heelOff) goal = -s.toeOff * ((u - s.heelOff) / (1 - s.heelOff)) ** 1.5;
else goal = 0;
foot.toeFlat = 1;
} else {
if (foot.planted) {
foot.planted = false; foot.from = Math.min(share > 0 ? duty : pf, 0.95);
foot.x0 = foot.x; foot.z0 = foot.z; foot.yaw0 = foot.yaw; foot.pitch0 = share > 0 ? (s.back ? s.toeOff : -s.toeOff) : foot.pitch;
}
const tau = foot.tau = clamp((pf - foot.from) / (1 - foot.from), 0, 1);
const t2 = tau * tau, t3 = t2 * tau, h01 = -2 * t3 + 3 * t2, h00 = 1 - h01, tangents = t3 - 2 * t2 + tau + t3 - t2;
foot.x = h00 * foot.x0 + h01 * tx;
foot.z = h00 * foot.z0 + h01 * tz + tangents * s.carry * v * swing; // leave and meet the ground near its speed
foot.yaw = lerp(foot.yaw0, tyaw, smooth(0, 1, tau));
goal = foot.pitch0 * (1 - smooth(0.05, 0.7, tau)) + s.strike * smooth(0.55, 1, tau);
foot.lift = s.swingLift * Math.sin(Math.PI * tau ** s.liftPow);
foot.toeFlat = 1 - smooth(0, 0.4, tau);
}
foot.pitch += clamp(goal - foot.pitch, -30 * dt, 30 * dt);
}
// The pelvis rides up and down with the stride; eased so a sudden change of pace does not jolt it.
const rise = s.bob * Math.cos(2 * TAU * (this._phase - duty / 2)) - s.drop;
this._rise += (rise - this._rise) * approach(26, dt);
this.footDown.left = feet[0].planted;
this.footDown.right = feet[1].planted;
this.phase = this._phase;
// Head: towards the target, else a little into the turn.
let yaw = clamp(this._ws * 0.22, -0.5, 0.5), pitch = this._action === 'aim' || this._action === 'point' ? this._aimPitch * 0.6 : 0;
if (this._lookAt) {
this.root.updateWorldMatrix(true, false);
const d = _v1.copy(this._lookAt);
this.root.worldToLocal(d);
d.y -= H * 0.93;
const flat = Math.hypot(d.x, d.z);
if (flat + Math.abs(d.y) > 1e-4) { yaw = clamp(Math.atan2(-d.x, -d.z), -1.25, 1.25); pitch = clamp(Math.atan2(d.y, flat), -0.7, 0.7); }
}
const rate = approach(7, dt);
this._headYaw += (yaw - this._headYaw) * rate;
this._headPitch += (pitch - this._headPitch) * rate;
}
// Ankle position (root space) and foot rotation for a foot whose sole origin is at (x, lift, z).
_footPose(foot, pitch, yaw, toeFlat, lift, ankle, quat) {
const H = this.height, ank = ANKLE * H;
const sin = Math.sin(pitch), cos = Math.cos(pitch);
let dy, dz;
if (pitch >= 0) { // rocking on the heel, toes up
const hb = HEEL_PIVOT * H;
dy = ank * cos + hb * sin; dz = hb * (1 - cos) + ank * sin;
} else { // rolling over the ball of the foot, heel up
const ry = (ANKLE - TOE_Y) * H, rz = TOE_FWD * H;
dy = TOE_Y * H + ry * cos - rz * sin; dz = -rz + ry * sin + rz * cos;
}
const toe = Math.max(0, -pitch) * toeFlat;
if (lift > 0) {
// Keep heel, ball and toe tip clear of the ground while the foot is in the air.
const heel = dy - ank * cos - HEEL_END * H * sin, ball = dy - ank * cos + TOE_FWD * H * sin;
const joint = dy + (TOE_Y - ANKLE) * H * cos + TOE_FWD * H * sin, tilt = pitch + toe;
const tip = joint - TOE_Y * H * Math.cos(tilt) + TOE_LEN * H * Math.sin(tilt);
const low = Math.min(heel, ball, tip) + lift;
if (low < 0.004) lift += 0.004 - low;
}
ankle.set(foot.x + Math.sin(yaw) * dz, lift + dy, foot.z + Math.cos(yaw) * dz);
euler(quat, pitch, yaw, 0);
return toe;
}
// Two-bone leg: thigh and shank rotations (root space) that put the ankle on the target, knee towards the pole.
_solveLimb(origin, target, pole, l1, l2, slack) {
const n = _v1.subVectors(target, origin);
const d = n.length(), dc = clamp(d, Math.abs(l1 - l2) + 1e-4, (l1 + l2) * slack);
n.multiplyScalar(1 / Math.max(d, 1e-6));
const cosA = clamp((l1 * l1 + dc * dc - l2 * l2) / (2 * l1 * dc), -1, 1), sinA = Math.sqrt(1 - cosA * cosA);
const f = _v2.copy(pole).addScaledVector(n, -pole.dot(n));
if (f.lengthSq() < 1e-8) f.set(0, 1, 0).addScaledVector(n, -n.y);
f.normalize();
const first = _v3.copy(n).multiplyScalar(cosA).addScaledVector(f, sinA); // origin -> middle joint
const second = _v4.copy(n).multiplyScalar(dc).addScaledVector(first, -l1).normalize(); // middle joint -> end
return [first, second, f, n];
}
_pose() {
const H = this.height, s = this._style, w = this._w, t = this._time, bones = this.bones, o = this._offsets;
const phase = this._phase, duty = s.duty, move = s.move, run = s.run, fall = w.fall;
const mid = TAU * (phase - duty / 2); // 0 at the middle of the left foot's stance
const cycle = Math.cos(TAU * phase); // 1 when the left foot lands
const idle = (1 - move) * (1 - Math.max(w.sit * 0.6, fall));
const hitT = this._hitTime, hit = (hitT < 0.07 ? hitT / 0.07 : Math.exp(-(hitT - 0.07) / 0.22)) * w.hit;
const breathRate = lerp(0.24, 0.55, run * move), breath = Math.sin(TAU * breathRate * t + o[4]);
const turnLean = clamp(this._vs * this._ws / 9.81, -0.32, 0.32) * 0.75;
// ---- pelvis (root space)
let yaw = -s.pelvisYaw * cycle + idle * 0.025 * Math.sin(t * 0.31 + o[2]) + hit * 0.22 + w.aim * 0.18;
let roll = -s.pelvisRoll * Math.cos(mid) + idle * 0.02 * Math.sin(t * 0.83 + o[0]) + turnLean * 0.5;
let pitch = -(s.lean * 0.3 + w.crouch * 0.22) + hit * 0.1 + w.sit * 0.12;
let px = -s.sway * Math.cos(mid) - idle * H * (0.009 * Math.sin(t * 0.83 + o[0]) + 0.004 * Math.sin(t * 0.37 + o[1])) - turnLean * H * 0.04;
let py = STAND * H + this._rise - idle * H * 0.0015 * breath - hit * H * 0.035;
let pz = w.crouch * H * 0.06 + hit * H * 0.03;
if (w.sit > 0) {
const seat = this._seat ?? H * 0.26;
px = lerp(px, 0, w.sit); py = lerp(py, seat + H * 0.085, w.sit); pz = lerp(pz, 0, w.sit);
yaw *= 1 - w.sit; roll *= 1 - w.sit;
}
if (fall > 0) {
const lie = H * 0.066 * lerp(0.86, 1.3, this.build);
px = lerp(px, 0, fall); py = lerp(py, lie, smooth(0, 1, fall) * 0.4 + fall * 0.6); pz = lerp(pz, H * 0.4, fall);
pitch = lerp(pitch, HALF_PI, fall); yaw *= 1 - fall; roll *= 1 - fall;
}
euler(_qPelvis, pitch, yaw, roll);
// ---- feet: ankle targets, then the pelvis may not be higher than the legs can reach
const feet = this._feet, reach = (THIGH + SHANK) * H * 0.999, footQuat = [_q3, _q4], toes = [0, 0];
for (let i = 0; i < 2; i++) {
const foot = feet[i];
let fp = foot.pitch, fy = foot.yaw, toeFlat = foot.toeFlat, lift = foot.planted ? 0 : foot.lift;
const ankle = _ankle[i];
if (fall > 0) { fp = lerp(fp, 0.95, fall); fy = lerp(fy, -foot.side * 0.35, fall); }
toes[i] = this._footPose(foot, fp, fy, toeFlat, lift, ankle, footQuat[i]);
if (fall > 0) { ankle.z -= fall * H * (i ? 0.1 : 0.2); ankle.x += foot.side * fall * H * 0.05; }
if (w.sit > 0) {
ankle.lerp(_v1.set(foot.side * H * 0.08, ANKLE * H, -H * 0.225), w.sit);
footQuat[i].slerp(euler(_q1, 0, -foot.side * 0.1, 0), w.sit);
toes[i] *= 1 - w.sit;
}
const offset = _v2.set(foot.side * HIP_X * H, -HIP_DROP * H, 0).applyQuaternion(_qPelvis);
const flat = Math.hypot(px + offset.x - ankle.x, pz + offset.z - ankle.z);
const top = ankle.y - offset.y + Math.sqrt(Math.max(0, reach * reach - flat * flat));
const firm = foot.planted ? 1 : Math.max(smooth(0.75, 1, foot.tau), 1 - smooth(0, 0.3, foot.tau));
if (top < py) py = lerp(py, Math.max(top, py - H * 0.1), firm);
}
// A change of pace may ask the pelvis to jump; let it move no faster than a body does.
const limit = (this._fall > 0 ? 6 : 1.1) * H / 1.75 * this._step;
py = this._height = clamp(py, this._height - limit, this._height + limit);
_pelvis.set(px, py, pz);
bones.Hips.position.copy(_pelvis);
bones.Hips.quaternion.copy(_qPelvis);
// ---- legs
const forward = _vz.set(0, 0, -1).applyQuaternion(_qPelvis);
for (let i = 0; i < 2; i++) {
const foot = feet[i], side = foot.side, name = side < 0 ? 'Left' : 'Right';
_hip.set(side * HIP_X * H, -HIP_DROP * H, 0).applyQuaternion(_qPelvis).add(_pelvis);
const spread = w.crouch * 0.3 + w.sit * 0.12 + fall * 0.25;
const pole = _vx.set(-Math.sin(foot.yaw * 0.6), 0, -Math.cos(foot.yaw * 0.6)).lerp(forward, 0.5 + 0.5 * Math.max(fall, w.sit));
pole.x += side * spread; pole.y += 0.25 * Math.max(fall, w.sit, w.crouch);
const [thigh, shank, bend] = this._solveLimb(_hip, _ankle[i], pole, THIGH * H, SHANK * H, 0.9995);
// Bone frames: y up the bone, x the knee's hinge.
const hinge = _vx.crossVectors(thigh, bend).normalize();
if (hinge.lengthSq() < 0.5) hinge.set(1, 0, 0);
basis(_qUpper, hinge, _vy.copy(thigh).negate(), _v1.crossVectors(hinge, _vy));
basis(_qLower, hinge, _vy.copy(shank).negate(), _v1.crossVectors(hinge, _vy));
bones[`${name}UpLeg`].quaternion.copy(_qInv.copy(_qPelvis).invert()).multiply(_qUpper);
bones[`${name}Leg`].quaternion.copy(_qInv.copy(_qUpper).invert()).multiply(_qLower);
bones[`${name}Foot`].quaternion.copy(_qInv.copy(_qLower).invert()).multiply(footQuat[i]);
euler(bones[`${name}ToeBase`].quaternion, toes[i], 0, 0);
}
// ---- spine: lean, counter-twist against the pelvis, level the shoulders
const aimPitch = this._aimPitch * Math.max(w.aim, w.point * 0.5);
const trunkPitch = -(s.lean * 0.7 + w.crouch * 0.42) + hit * 0.3 - w.sit * 0.16 + aimPitch * 0.3 - Math.sin(Math.PI * fall) * 0.5 - fall * 0.0
+ idle * 0.012 * Math.sin(t * 0.53 + o[3]);
const chestYaw = s.chestYaw * cycle + this._headYaw * 0.22 + w.talk * 0.05 * Math.sin(t * 1.1 + o[1]);
const trunkYaw = (chestYaw - (yaw - hit * 0.1)) * (1 - fall), trunkRoll = (-roll * 1.25 + turnLean * 0.5) * (1 - fall) * (1 - w.sit * 0.5);
euler(bones.Spine.quaternion, trunkPitch * 0.3, trunkYaw * 0.3, trunkRoll * 0.35);
euler(bones.Spine1.quaternion, trunkPitch * 0.35 + breath * 0.008, trunkYaw * 0.35, trunkRoll * 0.35);
euler(bones.Spine2.quaternion, trunkPitch * 0.35 + breath * 0.006, trunkYaw * 0.35, trunkRoll * 0.3);
_qChest.copy(_qPelvis).multiply(bones.Spine.quaternion).multiply(bones.Spine1.quaternion).multiply(bones.Spine2.quaternion);
const chestPitch = pitch + trunkPitch;
// ---- head: steady over the body, towards what it looks at
const nod = w.talk * 0.05 * Math.sin(t * 2.7 + o[0]) + hit * 0.35 - w.crouch * 0.1;
const headGoal = euler(_q1, this._headPitch + chestPitch * 0.3 + nod, this._headYaw + (yaw + trunkYaw) * 0.2 + w.wave * 0.12,
(roll + trunkRoll) * 0.3 + w.wave * 0.06 + w.talk * 0.04 * Math.sin(t * 0.9 + o[2]));
if (fall > 0) headGoal.slerp(_q2.copy(_qChest).multiply(euler(_q3, 0.12, 0.3, 0)), fall);
const neckTurn = _q2.copy(_qChest).invert().multiply(headGoal);
bones.Neck.quaternion.copy(IDENTITY).slerp(neckTurn, 0.45);
bones.Head.quaternion.copy(bones.Neck.quaternion).invert().multiply(neckTurn);
// ---- arms (chest space)
const swingPhase = Math.cos(TAU * (phase - 0.03));
for (const side of [-1, 1]) {
const name = side < 0 ? 'Left' : 'Right', right = side > 0;
const c = -side * swingPhase; // 1 with this arm forward: opposite to its leg
// angles: forward flexion, abduction away from the body, inward twist, elbow bend
let flex = (c > 0 ? s.armFwd : s.armBack) * c + idle * (0.03 + 0.012 * Math.sin(t * 0.7 + o[right ? 1 : 3]));
let abd = lerp(0.11, 0.17, run * move) + idle * 0.01 * breath;
let twist = lerp(0.12, 0.45 + 0.25 * Math.max(c, 0), run * move);
let elbow = lerp(0.2 + 0.32 * Math.max(c, 0) * Math.min(1, s.armFwd * 2.5), 1.55 + 0.22 * c, run * move);
let wrist = 0.08, grip = 0;
const blend = (weight, f, a, tw, e) => { flex = lerp(flex, f, weight); abd = lerp(abd, a, weight); twist = lerp(twist, tw, weight); elbow = lerp(elbow, e, weight); };
blend(w.crouch, 0.8, 0.2, 0.5, 1.05);
blend(w.sit, 0.3, 0.09, 0.25, 0.85);
if (right) blend(w.talk, 0.38 + 0.12 * Math.sin(t * 2.1 + o[0]), 0.2, 0.55 + 0.2 * Math.sin(t * 1.3 + o[1]), 1.5 + 0.25 * Math.sin(t * 4.4 + o[2]));
else blend(w.talk, 0.2 + 0.08 * Math.sin(t * 1.7 + o[3]), 0.15, 0.5, 1.2 + 0.2 * Math.sin(t * 3.1 + o[4]));
if (right) blend(w.wave, 0.3, 1.5, -1.45, 1.4 + 0.42 * Math.sin(TAU * 2.1 * this._actionTime));
blend(hit, -0.3, 0.65, 0, 1.0);
blend(fall, 0.04 + 0.8 * Math.sin(Math.PI * fall), 0.8 + 0.35 * Math.sin(Math.PI * fall), right ? -1.35 : 1.3, right ? 0.9 : 0.4);
euler(_qUpper, flex, 0, 0).multiply(_q1.setFromAxisAngle(_v1.set(0, 0, 1), -side * (HALF_PI - abd)))
.multiply(_q1.setFromAxisAngle(_v1.set(1, 0, 0), -twist));
_qLower.copy(_qUpper).multiply(_q1.setFromAxisAngle(_v1.set(0, 1, 0), side * elbow));
// Reaching poses come from where the hand should be.
const reachWeight = Math.max(w.aim, right ? w.point : 0);
if (reachWeight > 0.001) {
const shoulder = _hip.set(side * SHOULDER_X * H, SHOULDER_UP * H, 0);
let target, pole;
const p = this._aimPitch - chestPitch;
if (w.aim >= (right ? w.point : 0)) {
grip = w.aim;
const along = right ? 0.262 : 0.25;
target = _v3.set(side * 0.02 * H, (SHOULDER_UP + 0.025) * H, 0)
.add(_v4.set(0, Math.sin(p), -Math.cos(p)).multiplyScalar(along * H));
if (!right) target.y -= 0.022 * H * Math.cos(p);
pole = _vx.set(side * 0.9, -1, 0.1);
} else {
const dir = _v4.set(0, Math.sin(p), -Math.cos(p));
if (this._lookAt) {
const local = _vy.copy(this._lookAt);
this.root.worldToLocal(local);
local.sub(_v1.copy(shoulder).add(_v2.set(0, 0.73 * H, 0))).applyQuaternion(_qInv.copy(_qChest).invert());
if (local.lengthSq() > 1e-6) {
const flat = Math.hypot(local.x, local.z), bearing = clamp(Math.atan2(-local.x, -local.z), -1.7, 0.7), rise = clamp(Math.atan2(local.y, flat), -1.3, 1.3);
dir.set(-Math.sin(bearing) * Math.cos(rise), Math.sin(rise), -Math.cos(bearing) * Math.cos(rise));
}
}
target = _v3.copy(shoulder).addScaledVector(dir, (UPPER_ARM + FORE_ARM) * H * 0.992);
pole = _vx.set(-side * 0.5, -0.7, 0.3);
}
const [upper, lower, bend] = this._solveLimb(shoulder, target, pole, UPPER_ARM * H, FORE_ARM * H, 0.999);
// Bone frames: x along the bone away from the body, the elbow closes towards -z.
const zAxis = _vz.copy(upper).multiplyScalar(upper.dot(lower)).sub(lower);
if (zAxis.lengthSq() < 1e-6) zAxis.copy(bend); else zAxis.normalize();
const xUpper = _v1.copy(upper).multiplyScalar(side), hingeAxis = _vy.crossVectors(zAxis, xUpper).normalize();
basis(_qUpperIk, xUpper, hingeAxis, _v2.crossVectors(xUpper, hingeAxis));
const xLower = _v1.copy(lower).multiplyScalar(side);
basis(_qLowerIk, xLower, hingeAxis, _v2.crossVectors(xLower, hingeAxis));
_qUpper.slerp(_qUpperIk, reachWeight);
_qLower.slerp(_qLowerIk, reachWeight);
wrist = lerp(wrist, 0, reachWeight);
}
const lift = Math.max(0, abd - 0.6) * 0.22 + w.aim * 0.08 + hit * 0.15 + breath * 0.012 * (1 + run);
const clavicle = bones[`${name}Shoulder`].quaternion.setFromAxisAngle(_v1.set(0, 0, 1), side * lift);
bones[`${name}Arm`].quaternion.copy(_qInv.copy(clavicle).invert()).multiply(_qUpper);
bones[`${name}ForeArm`].quaternion.copy(_qInv.copy(_qUpper).invert()).multiply(_qLower);
const hand = bones[`${name}Hand`].quaternion.setFromAxisAngle(_v1.set(0, 0, 1), -side * wrist);
if (grip > 0.001) {
// Both hands along the aim, palms together.
const p = this._aimPitch - chestPitch, along = _v1.set(0, Math.sin(p), -Math.cos(p)).multiplyScalar(side);
const across = _v2.set(side, 0, 0);
basis(_q1, along, across, _v3.crossVectors(along, across));
hand.slerp(_q2.copy(_qLower).invert().multiply(_q1), grip);
}
}
}
}
/**
* A person. options: height (m, 1.75), build (0 slim .. 1 heavy, 0.5), colors { skin, hair, top,
* bottom, shoes }, hair ('none' | 'short' | 'long'), sleeves ('long' | 'short'), seed (decorrelates
* idle motion and which foot leads). Returns { root, mesh, skeleton, bones, set(state), update(dt),
* dispose(), footDown, phase, triangles }. Humanoids with the same height, build, hair and sleeves
* share one geometry; each has its own skeleton.
*/
export function createHumanoid(options = {}) {
return new Humanoid(options);
}
export { Humanoid };