Add anatomical character customization at initial creation

This commit is contained in:
dingo
2026-09-12 16:00:15 -04:00
parent 90e33cbcd9
commit 4aca703b6f
25 changed files with 733 additions and 133 deletions
+12
View File
@@ -12,6 +12,18 @@
.appearance-swatches{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.appearance-swatches input[type=color]{width:100%;height:36px;padding:3px;border:1px solid #5e7576;border-radius:8px;background:#17272e;cursor:pointer}
.appearance-actions{display:flex;flex-wrap:wrap;gap:8px}.appearance-editor button{background:#38514e!important;color:#e7f1df!important;border:1px solid #638079!important;border-radius:8px;padding:9px 12px;font-size:12px;cursor:pointer}
.appearance-controls [hidden]{display:none!important}
.humanoid-controls{display:grid;gap:15px}.anatomy-region{margin:0;padding:14px;border:1px solid #5e75765c;border-radius:8px;display:grid;gap:14px;min-width:0}
.anatomy-region legend{color:#ddcfaa;padding:0 5px;font-size:12px}.anatomy-region label>span{display:flex;justify-content:space-between;gap:8px}.anatomy-region output{color:#b9d5c8;font-variant-numeric:tabular-nums}
.anatomy-region input[type=color]{width:100%;height:34px;padding:3px;background:#17272e;border:1px solid #5e7576}
.appearance-views{position:absolute;left:16px;right:16px;bottom:35px;display:flex;justify-content:center;gap:8px}
.appearance-views button{min-height:30px;padding:5px 12px;background:#17272ecc!important}
.arrival-creator{width:min(1040px,96vw);max-width:96vw;max-height:94dvh;overflow:auto;padding:24px}
.arrival-creator h1{font-size:29px;margin:8px 0}.arrival-creator #arrival-status{margin-bottom:14px}
.arrival-creator #join-form{display:block}.arrival-creator #join{width:100%;margin-top:0}
.arrival-creator .appearance-editor{margin:14px 0}.arrival-creator .appearance-controls{max-height:460px;overflow:auto;padding:20px}
.arrival-creator .appearance-stage{min-height:460px}.arrival-creator .appearance-editor button{margin-top:0;font-weight:400}
@media(max-width:640px){.arrival-creator{padding:16px}.arrival-creator .appearance-stage{min-height:250px}.arrival-creator .appearance-controls{max-height:250px;padding:14px}.arrival-creator .appearance-caption{top:12px;left:14px}.arrival-creator .appearance-caption strong{font-size:17px}}
.appearance-note,.appearance-status{font-size:11px;line-height:1.6;color:#a8bcb5;margin:0}.appearance-status:empty{display:none}
.appearance-dialog{box-sizing:border-box;width:min(920px,96vw)!important;max-width:96vw!important;max-height:94dvh;overflow:auto;background:#18272b!important;color:#f1eee2!important;padding:28px!important;border:1px solid #536b66!important;border-radius:22px!important;box-shadow:0 24px 100px #0008}
.appearance-dialog::backdrop{background:#071317b8;backdrop-filter:blur(7px)}
+23 -28
View File
@@ -3,7 +3,7 @@ import * as T from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { buildAppearance, defaultAppearance, disposeAppearance, forms } from './appearance-model';
import { registerMenu } from './menu-focus';
import { humanoidControls } from './humanoid-controls';
import type { Appearance, VisualPreset } from './generated';
const node = <K extends keyof HTMLElementTagNameMap>(tag: K, text = '', className = '') => {
@@ -11,27 +11,28 @@ const node = <K extends keyof HTMLElementTagNameMap>(tag: K, text = '', classNam
};
const button = (text: string, action: () => void) => { const b = node('button', text); b.type = 'button'; b.onclick = action; return b; };
export function createAppearanceEditor(families: string[], initial?: Appearance, library: VisualPreset[] = []) {
export function createAppearanceEditor(families: string[], initial?: Appearance, library: VisualPreset[] = [], creation = false) {
let value = structuredClone(initial ?? defaultAppearance(families[0]));
const root = node('section', '', 'appearance-editor');
const stage = node('div', '', 'appearance-stage'), canvas = node('canvas');
canvas.setAttribute('aria-label', '3D model preview. Drag to rotate and scroll to zoom.');
const caption = node('div', '', 'appearance-caption');
caption.append(node('span', 'AETERNALIS / CREATOR'), node('strong', 'A little life, shaped by you.'));
caption.append(node('span', 'AETERNALIS / CREATOR'), node('strong', 'Shape your traveler.'));
const hint = node('p', 'Drag to orbit · scroll to zoom', 'appearance-hint');
stage.append(canvas, caption, hint);
const panel = node('div', '', 'appearance-controls');
root.append(stage, panel);
const family = node('select'), variant = node('select'), presets = node('select');
for (const f of families) family.append(new Option(f === 'human' ? 'Character' : f[0].toUpperCase() + f.slice(1), f));
const field = (label: string, input: HTMLElement) => { const wrap = node('label', label); wrap.append(input); panel.append(wrap); };
const field = (label: string, input: HTMLElement) => { const wrap = node('label', label); wrap.append(input); panel.append(wrap); return wrap; };
if (families.length > 1) field('Create', family);
field('Form', variant);
const formField = field('Form', variant);
const legacyFields: HTMLElement[] = [];
const sliders = new Map<string, HTMLInputElement>(), colors = new Map<string, HTMLInputElement>();
const colorLabels = new Map<string, HTMLSpanElement>();
for (const [key, label, min, max] of [['height', 'Height', .75, 1.25], ['width', 'Build / fullness', .75, 1.25], ['detail', 'Feature size / foliage', 0, 1]] as const) {
const input = node('input'); input.type = 'range'; input.min = String(min); input.max = String(max); input.step = '.01';
sliders.set(key, input); field(label, input);
sliders.set(key, input); legacyFields.push(field(label, input));
}
const swatches = node('div', '', 'appearance-swatches');
for (const [key, label] of [['primary', 'Skin / main'], ['secondary', 'Hair / secondary'], ['accent', 'Clothes / accent']] as const) {
@@ -39,7 +40,8 @@ export function createAppearanceEditor(families: string[], initial?: Appearance,
}
panel.append(swatches);
const seed = node('input'); seed.type = 'number'; seed.min = '1'; seed.max = '65535'; seed.step = '1'; seed.required = true;
field('Variation seed', seed);
legacyFields.push(field('Variation seed', seed));
const anatomy = humanoidControls(() => value, next => { value = next; sync(); }); panel.append(anatomy.node);
presets.append(new Option('Choose a saved design…', ''));
for (const preset of library.filter(p => families.includes(p.appearance.family))) presets.append(new Option(preset.name, preset.id));
if (presets.options.length > 1) field('Start from the visual library', presets);
@@ -48,17 +50,23 @@ export function createAppearanceEditor(families: string[], initial?: Appearance,
const variation = crypto.getRandomValues(new Uint16Array(4));
value.seed = 1 + variation[0] % 65535;
value.variant = (value.variant + 1 + variation[1] % 3) % 4;
if (value.version === 2) { sync(); return; }
value.detail = Math.round(variation[2] / 65535 * 100) / 100;
value.width = .8 + (variation[3] % 41) / 100;
sync();
}));
const exportButton = button('Download GLB', () => void exportModel()); actions.append(exportButton); panel.append(actions);
actions.append(button('Reset all', () => { value = defaultAppearance(value.family); sync(); }));
const exportButton = button('Download GLB', () => void exportModel()); exportButton.hidden = creation; actions.append(exportButton); panel.append(actions);
const status = node('p', '', 'appearance-status'); status.setAttribute('role', 'status'); panel.append(status);
panel.append(node('p', 'Your look does not change your stats, movement, or reach.', 'appearance-note'));
panel.append(node('p', creation ? 'Your name and look are saved when you enter the world. Appearance changes will be available later.' : 'Your look does not change your stats, movement, or reach.', 'appearance-note'));
let renderer: T.WebGLRenderer | undefined, controls: OrbitControls | undefined, model: T.Group | undefined;
const scene = new T.Scene(); scene.background = new T.Color('#18262c');
const camera = new T.PerspectiveCamera(35, 1, .01, 100);
let viewAngle = -.30;
const views = node('div', '', 'appearance-views');
for (const [name, angle] of [['Front', 0], ['Side', Math.PI / 2], ['Back', Math.PI]] as const) views.append(button(name, () => { viewAngle = angle; framedForm = ''; rebuild(); }));
stage.append(views);
scene.add(new T.HemisphereLight('#f5f3e8', '#728382', 2.5));
const key = new T.DirectionalLight('#ffebd3', 3); key.position.set(-3, 6, -4); scene.add(key);
const rim = new T.DirectionalLight('#9cdbd9', 2); rim.position.set(3, 3, 2); scene.add(rim);
@@ -80,12 +88,16 @@ export function createAppearanceEditor(families: string[], initial?: Appearance,
const frameKey = value.family + ':' + value.variant;
if (framedForm !== frameKey) {
controls?.target.set(0, centerY, 0);
camera.position.set(height * .9, centerY + height * .45, -height * 2.3); camera.lookAt(0, centerY, 0);
camera.position.set(Math.sin(viewAngle) * height * 2.15, centerY + height * .12, -Math.cos(viewAngle) * height * 2.15); camera.lookAt(0, centerY, 0);
framedForm = frameKey;
}
controls?.update(); dirty = true;
}
function sync() {
const human = value.version === 2 && value.family === 'human';
for (const field of legacyFields) field.hidden = human;
anatomy.node.hidden = !human; anatomy.sync();
formField.firstChild!.textContent = human ? 'Hair style' : 'Form';
family.value = value.family; variant.replaceChildren(...forms[value.family].map((name, i) => new Option(name, String(i)))); variant.value = String(value.variant);
for (const [key, input] of sliders) input.value = String(value[key as 'height' | 'width' | 'detail']);
for (const [key, input] of colors) input.value = value[key as 'primary' | 'secondary' | 'accent'];
@@ -94,7 +106,7 @@ export function createAppearanceEditor(families: string[], initial?: Appearance,
seed.value = String(value.seed); rebuild();
}
function readInputs() {
value = { ...value, variant: Number(variant.value), seed: Number(seed.value), ...Object.fromEntries([...sliders].map(([k, i]) => [k, Number(i.value)])), ...Object.fromEntries([...colors].map(([k, i]) => [k, i.value])) };
value = { ...value, variant: Number(variant.value), ...(value.version === 2 ? {} : { seed: Number(seed.value), ...Object.fromEntries([...sliders].map(([k, i]) => [k, Number(i.value)])) }), ...Object.fromEntries([...colors].map(([k, i]) => [k, i.value])) };
if (seed.validity.valid && seed.value) rebuild();
}
family.onchange = () => { value = defaultAppearance(family.value); sync(); };
@@ -134,20 +146,3 @@ export function createAppearanceEditor(families: string[], initial?: Appearance,
sync(); frame = requestAnimationFrame(tick);
return { node: root, read: () => structuredClone(value), dispose };
}
export function showCharacterCreator(initial: Appearance | undefined, save: (appearance: Appearance) => Promise<void>) {
const dialog = node('dialog', '', 'appearance-dialog'), header = node('header'), editor = createAppearanceEditor(['human'], initial);
header.append(node('div', 'YOUR CHARACTER', 'appearance-eyebrow'), node('h2', 'Give your traveler a face.'));
const footer = node('footer'), error = node('p', '', 'error'), form = node('form');
let busy = false;
const menu = registerMenu(dialog, () => { if (!busy) { dialog.close(); editor.dispose(); dialog.remove(); menu.dispose(); } });
const cancel = button('Cancel', () => menu.close()), submit = node('button', 'Save appearance'); submit.type = 'submit';
footer.append(cancel, submit); form.append(editor.node, error, footer); dialog.append(header, form);
form.onsubmit = async event => {
event.preventDefault(); if (busy) return; busy = true; submit.disabled = cancel.disabled = true; editor.node.inert = true;
try { await save(editor.read()); busy = false; menu.close(); }
catch (e) { error.textContent = (e as Error).message; }
finally { busy = false; submit.disabled = cancel.disabled = false; editor.node.inert = false; }
};
const previous = document.activeElement; document.body.append(dialog); dialog.showModal(); menu.opened(previous);
}
+4
View File
@@ -1,6 +1,7 @@
import * as T from 'three';
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
import type { Appearance } from './generated';
import { buildHumanoid, defaultBody } from './humanoid-model';
export const forms: Record<string, string[]> = {
human: ['Tousled hair', 'Side swept', 'Rounded bob', 'Twin braids'],
@@ -11,6 +12,7 @@ export const forms: Record<string, string[]> = {
};
export function defaultAppearance(family = 'human'): Appearance {
if (family === 'human') return { version: 2, family, variant: 0, seed: 42, height: 1, width: 1, detail: .5, primary: '#c99573', secondary: '#392b28', accent: '#456c70', body: defaultBody() };
const colors: Record<string, string[]> = {
human: ['#d8a582', '#493947', '#578f8b'],
creature: ['#cd8959', '#fff0cf', '#607a67'],
@@ -27,6 +29,7 @@ export function defaultAppearance(family = 'human'): Appearance {
* draw per leaf. No collision or gameplay attributes are inferred from the mesh.
*/
export function buildAppearance(a: Appearance): T.Group {
if (a.family === 'human' && a.version === 2) return buildHumanoid(a);
const buckets = new Map<string, T.BufferGeometry[]>();
const transform = new T.Object3D();
let seed = a.seed;
@@ -174,6 +177,7 @@ export function buildAppearance(a: Appearance): T.Group {
export function disposeAppearance(root: T.Object3D) {
root.traverse(o => {
if (o instanceof T.SkinnedMesh) o.skeleton.dispose();
if (o instanceof T.Mesh) { o.geometry.dispose(); for (const m of Array.isArray(o.material) ? o.material : [o.material]) m.dispose(); }
});
}
+23
View File
@@ -114,6 +114,7 @@ export interface MobDefinition {
export interface Appearance {
accent: string;
body?: HumanoidBody;
detail: number;
family: string;
height: number;
@@ -125,6 +126,28 @@ export interface Appearance {
width: number;
}
export interface HumanoidBody {
armLength: number;
armWidth: number;
chest: string;
chestWidth: number;
eyeColor: string;
eyeHeight: number;
eyeSpacing: number;
eyebrows: string;
footSize: number;
headDepth: number;
headLength: number;
headWidth: number;
hipsWidth: number;
legLength: number;
legWidth: number;
mouthHeight: number;
mouthStyle: string;
noseHeight: number;
noseScale: number;
}
export interface MobSpawn {
biomes: string[];
count: number;
+60
View File
@@ -0,0 +1,60 @@
import type { Appearance, HumanoidBody } from './generated';
import { defaultBody } from './humanoid-model';
export function humanoidControls(read: () => Appearance, change: (next: Appearance) => void) {
const root = document.createElement('section'); root.className = 'humanoid-controls';
const label = document.createElement('label'); label.textContent = 'Customize region';
const region = document.createElement('select'); label.append(region); root.append(label);
const panels = new Map<string, HTMLElement>(), syncers: (() => void)[] = [];
const defaults = defaultBody();
const set = (key: keyof HumanoidBody, value: string | number) => change({ ...read(), body: { ...read().body!, [key]: value } });
function group(id: string, title: string) {
region.append(new Option(title, id));
const section = document.createElement('fieldset'); section.className = 'anatomy-region';
const legend = document.createElement('legend'); legend.textContent = title; section.append(legend);
panels.set(id, section); root.append(section); return section;
}
function range(parent: HTMLElement, key: keyof HumanoidBody | 'height', title: string, min: number, max: number, step = .01) {
const wrap = document.createElement('label'), caption = document.createElement('span'), output = document.createElement('output');
const input = document.createElement('input'); input.type = 'range'; input.min = String(min); input.max = String(max); input.step = String(step);
input.setAttribute('aria-label', title); caption.append(document.createTextNode(title), output); wrap.append(caption, input); parent.append(wrap);
input.oninput = () => key === 'height' ? change({ ...read(), height: Number(input.value) }) : set(key, Number(input.value));
syncers.push(() => { const value = key === 'height' ? read().height : read().body![key] as number; input.value = String(value); output.textContent = min < 0 ? `${value > 0 ? '+' : ''}${Math.round(value * 1000)}` : `${Math.round(value * 100)}%`; });
}
function select(parent: HTMLElement, key: keyof HumanoidBody, title: string, values: [string, string][]) {
const wrap = document.createElement('label'); wrap.textContent = title;
const input = document.createElement('select'); input.setAttribute('aria-label', title);
for (const [id, text] of values) input.append(new Option(text, id)); wrap.append(input); parent.append(wrap);
input.onchange = () => set(key, input.value); syncers.push(() => { input.value = String(read().body![key]); });
}
const head = group('head', 'Head');
range(head, 'headLength', 'Head length', .85, 1.15); range(head, 'headWidth', 'Head width', .85, 1.15); range(head, 'headDepth', 'Head depth', .85, 1.15);
const eyes = group('eyes', 'Eyes & eyebrows');
range(eyes, 'eyeSpacing', 'Eye spacing', .8, 1.2); range(eyes, 'eyeHeight', 'Eye height', -.035, .035, .001);
const colorLabel = document.createElement('label'); colorLabel.textContent = 'Eye color';
const eyeColor = document.createElement('input'); eyeColor.type = 'color'; colorLabel.append(eyeColor); eyes.append(colorLabel);
eyeColor.oninput = () => set('eyeColor', eyeColor.value); syncers.push(() => { eyeColor.value = read().body!.eyeColor; });
select(eyes, 'eyebrows', 'Eyebrows', [['none', 'None'], ['thin', 'Thin'], ['bushy', 'Bushy']]);
const nose = group('nose', 'Nose'); range(nose, 'noseHeight', 'Nose height', -.035, .035, .001); range(nose, 'noseScale', 'Nose scale', .75, 1.25);
const mouth = group('mouth', 'Mouth'); range(mouth, 'mouthHeight', 'Mouth height', -.025, .025, .001);
select(mouth, 'mouthStyle', 'Mouth style', [['neutral', 'Neutral'], ['smile', 'Soft smile'], ['stern', 'Stern']]);
const chest = group('chest', 'Chest & stature');
select(chest, 'chest', 'Chest form', [['male', 'Male'], ['female', 'Female']]);
range(chest, 'height', 'Overall height', .9, 1.1); range(chest, 'chestWidth', 'Chest width', .85, 1.15);
range(group('hips', 'Hips'), 'hipsWidth', 'Hip width', .85, 1.15);
const arms = group('arms', 'Arms'); range(arms, 'armLength', 'Arm length', .9, 1.1); range(arms, 'armWidth', 'Arm fullness', .8, 1.2);
const legs = group('legs', 'Legs'); range(legs, 'legLength', 'Leg length', .9, 1.1); range(legs, 'legWidth', 'Leg fullness', .8, 1.2);
range(group('feet', 'Feet'), 'footSize', 'Foot size', .85, 1.15);
const reset = document.createElement('button'); reset.type = 'button'; reset.textContent = 'Reset this region';
const keys: Record<string, (keyof HumanoidBody)[]> = { head: ['headLength', 'headWidth', 'headDepth'], eyes: ['eyeSpacing', 'eyeHeight', 'eyeColor', 'eyebrows'], nose: ['noseHeight', 'noseScale'], mouth: ['mouthHeight', 'mouthStyle'], chest: ['chest', 'chestWidth'], hips: ['hipsWidth'], arms: ['armLength', 'armWidth'], legs: ['legLength', 'legWidth'], feet: ['footSize'] };
reset.onclick = () => {
const next = structuredClone(read());
for (const key of keys[region.value]) Object.assign(next.body!, { [key]: defaults[key] });
if (region.value === 'chest') next.height = 1;
change(next);
};
root.append(reset);
region.onchange = () => { for (const [id, panel] of panels) panel.hidden = id !== region.value; };
region.value = 'head'; for (const [id, panel] of panels) panel.hidden = id !== 'head';
return { node: root, sync: () => { if (read().body) for (const update of syncers) update(); } };
}
+190
View File
@@ -0,0 +1,190 @@
import * as T from 'three';
import type { Appearance, HumanoidBody } from './generated';
export const defaultBody = (): HumanoidBody => ({
headLength: 1, headWidth: 1, headDepth: 1, eyeSpacing: 1, eyeHeight: 0,
eyeColor: '#547d75', eyebrows: 'thin', noseHeight: 0, noseScale: 1,
mouthHeight: 0, mouthStyle: 'neutral', chest: 'male', chestWidth: 1,
hipsWidth: 1, armLength: 1, armWidth: 1, legLength: 1, legWidth: 1, footSize: 1,
});
type Ring = [x: number, y: number, z: number, width: number, depth: number];
type Influence = [first: number, second: number, blend: number];
/** Version 2: shaped cross-sections with a stable bind-pose topology, paired
* proportions and named joints. Clothes are a fitted base outfit, not equipment.
* World peers still use the bind pose through the existing instancing path.
*/
export function buildHumanoid(a: Appearance): T.Group {
const b = a.body ?? defaultBody(), female = b.chest === 'female';
const root = new T.Group(); root.name = 'humanoid-v2';
root.userData.rigVersion = 1;
const bones: T.Bone[] = [], locations: T.Vector3[] = [];
function bone(name: string, parent: number | undefined, x: number, y: number, z = 0, limits = [-.6, .6, -.4, .4, -.4, .4]) {
const joint = new T.Bone(); joint.name = name;
const location = new T.Vector3(x, y, z).multiplyScalar(a.height);
joint.position.copy(location);
if (parent !== undefined) { joint.position.sub(locations[parent]); bones[parent].add(joint); }
else root.add(joint);
joint.userData.connection = { profile: name, rotationMin: [limits[0], limits[2], limits[4]], rotationMax: [limits[1], limits[3], limits[5]] };
locations.push(location); bones.push(joint); return bones.length - 1;
}
const hip = .98 * b.legLength, waist = hip + .15, chest = hip + .39, shoulder = hip + .51;
const neck = shoulder + .105, head = neck + .19 * b.headLength;
const pelvis = bone('pelvis', undefined, 0, hip), spine = bone('spine', pelvis, 0, waist);
const thorax = bone('chest', spine, 0, chest), neckBone = bone('neck', thorax, 0, neck);
const headBone = bone('head', neckBone, 0, head);
const positions: number[] = [], colors: number[] = [], indices: number[] = [], skinIndices: number[] = [], weights: number[] = [];
const tint = new T.Color();
function vertex(x: number, y: number, z: number, color: string, influence: Influence) {
const index = positions.length / 3;
positions.push(x * a.height, y * a.height, z * a.height);
tint.set(color); colors.push(tint.r, tint.g, tint.b);
skinIndices.push(influence[0], influence[1], 0, 0);
weights.push(1 - influence[2], influence[2], 0, 0);
return index;
}
const fixed = (id: number): Influence => [id, id, 0];
const blend = (y: number, pivot: number, first: number, second: number, width = .06): Influence =>
[first, second, T.MathUtils.clamp((y - pivot + width) / (2 * width), 0, 1)];
function tube(rings: Ring[], color: string, influence: (y: number) => Influence, sides = 12, shape?: (x: number, y: number, z: number, cosine: number) => number) {
const start = positions.length / 3;
for (const [cx, y, cz, rx, rz] of rings) {
for (let i = 0; i < sides; i++) {
const angle = i / sides * Math.PI * 2, cosine = Math.cos(angle), x = cx + Math.sin(angle) * rx;
const z = cz - cosine * rz;
vertex(x, y, shape ? shape(x, y, z, cosine) : z, color, influence(y));
}
}
for (let j = 0; j < rings.length - 1; j++) for (let i = 0; i < sides; i++) {
const p = start + j * sides + i, q = start + j * sides + (i + 1) % sides;
indices.push(p, p + sides, q, q, p + sides, q + sides);
}
for (const [j, reverse] of [[0, true], [rings.length - 1, false]] as const) {
const [x, y, z] = rings[j], center = vertex(x, y, z, color, influence(y));
for (let i = 0; i < sides; i++) {
const p = start + j * sides + i, q = start + j * sides + (i + 1) % sides;
indices.push(center, reverse ? p : q, reverse ? q : p);
}
}
}
function feature(geometry: T.BufferGeometry, color: string, x: number, y: number, z: number, sx: number, sy: number, sz: number, joint = headBone) {
const p = geometry.getAttribute('position'), offset = positions.length / 3;
for (let i = 0; i < p.count; i++) vertex(x + p.getX(i) * sx, y + p.getY(i) * sy, z + p.getZ(i) * sz, color, fixed(joint));
if (geometry.index) for (const n of geometry.index.array) indices.push(offset + n);
else for (let i = 0; i < p.count; i++) indices.push(offset + i);
geometry.dispose();
}
function anchor(name: string, joint: number, x = 0, y = 0, z = 0) {
const socket = new T.Object3D(); socket.name = `equipment:${name}`;
socket.position.set(x * a.height, y * a.height, z * a.height); bones[joint].add(socket);
}
const pants = '#333d49', boots = '#44372f';
const hipWidth = (female ? .215 : .19) * b.hipsWidth, chestWidth = .235 * b.chestWidth;
tube([[0, hip - .095, 0, hipWidth * .88, .125], [0, hip, 0, hipWidth, .14], [0, waist, 0, hipWidth * .84, .12],
[0, waist + .10, 0, chestWidth * .86, .13], [0, chest, 0, chestWidth, .155], [0, shoulder - .05, 0, chestWidth * 1.04, .14],
[0, shoulder + .015, 0, chestWidth * .9, .105], [0, neck - .025, 0, .072, .07]], a.accent,
y => y < waist ? blend(y, hip + .07, pelvis, spine) : blend(y, chest - .10, spine, thorax), 16,
(x, y, z, front) => z - (female && front > 0 ? .065 * Math.exp(-(((y - (chest - .015)) / .075) ** 2)) * Math.exp(-(((Math.abs(x) - chestWidth * .48) / .065) ** 2)) * front : 0));
const beltWidth = Math.max(hipWidth * .92, chestWidth * .86);
tube([[0, waist - .015, 0, beltWidth, .14], [0, waist + .025, 0, beltWidth, .14]], boots, () => fixed(spine), 16);
feature(new T.BoxGeometry(1, 1, 1), '#b99457', 0, waist + .005, -.145, .055, .035, .015, spine);
tube([[0, neck - .045, 0, .07, .066], [0, neck + .055, 0, .068, .068]], a.primary, () => fixed(neckBone));
for (const sign of [-1, 1]) {
const side = sign < 0 ? 'right' : 'left';
const legX = sign * hipWidth * .58, knee = .54 * b.legLength;
const thigh = bone(`${side}-thigh`, pelvis, legX, hip, 0, [-1.4, .7, -.5, .5, -.6, .6]);
const shin = bone(`${side}-shin`, thigh, legX, knee, 0, [0, 2.2, 0, 0, 0, 0]);
const foot = bone(`${side}-foot`, shin, legX, .14, 0, [-.5, .5, -.2, .2, -.2, .2]);
const legWeight = (y: number) => blend(y, knee, shin, thigh);
tube([[legX, .14, 0, .048 * b.legWidth, .05], [legX, .26 * b.legLength, .01, .057 * b.legWidth, .064],
[legX, .39 * b.legLength, .008, .072 * b.legWidth, .079], [legX, knee - .035, -.012, .059 * b.legWidth, .065],
[legX, knee + .035, -.012, .065 * b.legWidth, .073], [legX, .76 * b.legLength, 0, .088 * b.legWidth, .10],
[legX, hip - .045, 0, .104 * b.legWidth, .12], [legX, hip + .025, 0, .09 * b.legWidth, .10]], pants, legWeight);
tube([[legX, .025, -.055, .071 * b.footSize, .143 * b.footSize], [legX, .065, -.055, .075 * b.footSize, .146 * b.footSize],
[legX, .12, -.035, .07 * b.footSize, .118 * b.footSize], [legX, .18, 0, .054 * b.legWidth, .057],
[legX, .24, 0, .057 * b.legWidth, .06]], boots, () => fixed(foot));
const sx = sign * (chestWidth + .035), elbowY = shoulder - .27 * b.armLength;
const elbowX = sx + sign * .10, wristY = shoulder - .52 * b.armLength, wristX = sx + sign * .14;
const upper = bone(`${side}-upper-arm`, thorax, sx, shoulder - .04, 0, [-1.8, 1.4, -.8, .8, -1.6, 1.6]);
const lower = bone(`${side}-forearm`, upper, elbowX, elbowY, 0, [-2.2, 0, 0, 0, 0, 0]);
const hand = bone(`${side}-hand`, lower, wristX, wristY, 0);
const armWeight = (y: number) => blend(y, elbowY, lower, upper, .055);
tube([[wristX, wristY, 0, .039 * b.armWidth, .041], [wristX - sign * .018, wristY + .07 * b.armLength, 0, .046 * b.armWidth, .049],
[elbowX + sign * .012, elbowY - .06, 0, .059 * b.armWidth, .064], [elbowX, elbowY, 0, .05 * b.armWidth, .051],
[elbowX - sign * .02, elbowY + .075, 0, .059 * b.armWidth, .065], [sx, shoulder - .10, 0, .076 * b.armWidth, .078],
[sx - sign * .025, shoulder, 0, .065 * b.armWidth, .067]], a.primary, armWeight);
tube([[sx + sign * .04, shoulder - .16, 0, .078 * b.armWidth, .081], [sx, shoulder - .09, 0, .083 * b.armWidth, .085],
[sx - sign * .025, shoulder + .005, 0, .071 * b.armWidth, .071]], a.accent, () => fixed(upper));
tube([[wristX, wristY - .11, -.004, .041 * b.armWidth, .025], [wristX, wristY - .04, 0, .047 * b.armWidth, .029],
[wristX, wristY + .01, 0, .037 * b.armWidth, .032]], a.primary, () => fixed(hand), 10);
for (let finger = 0; finger < 4; finger++) {
const x = wristX + (finger - 1.5) * .021 * b.armWidth, bottom = wristY - .15 - (finger === 1 || finger === 2 ? .015 : 0);
tube([[x, bottom, -.002, .008, .010], [x, wristY - .085, 0, .009, .012]], a.primary, () => fixed(hand), 6);
}
tube([[wristX - sign * .065, wristY - .095, -.01, .012, .015], [wristX - sign * .035, wristY - .025, 0, .016, .021]], a.primary, () => fixed(hand), 8);
anchor(`${side}-glove`, hand); anchor(`${side}-boot`, foot); anchor(`${side}-shoulder`, upper);
anchor(sign < 0 ? 'weapon' : 'offhand', hand, 0, -.07, -.025);
for (let ring = 0; ring < 4; ring++) anchor(`ring${(sign < 0 ? 0 : 4) + ring + 1}`, hand, (ring - 1.5) * .021 * b.armWidth, -.10, 0);
}
const hw = .148 * b.headWidth, hd = .139 * b.headDepth, hy = (v: number) => head + v * b.headLength;
tube([[0, hy(-.18), -.009, hw * .42, hd * .60], [0, hy(-.145), 0, hw * .68, hd * .81],
[0, hy(-.09), .007, hw * .89, hd * .91], [0, hy(-.025), 0, hw, hd], [0, hy(.04), 0, hw * .96, hd * .99],
[0, hy(.11), .012, hw * .94, hd * .92], [0, hy(.165), .016, hw * .76, hd * .70],
[0, hy(.195), .014, hw * .25, hd * .22]], a.primary, () => fixed(headBone), 20);
const eyeY = hy(.018) + b.eyeHeight, ex = .060 * b.headWidth * b.eyeSpacing;
const faceDepth = (x: number) => -hd * Math.sqrt(Math.max(.1, 1 - (x / hw) ** 2));
for (const sign of [-1, 1]) {
feature(new T.SphereGeometry(1, 10, 6), a.primary, sign * hw * 1.015, hy(-.015), .01, .027, .049, .026);
const x = sign * ex, z = faceDepth(x);
feature(new T.SphereGeometry(1, 12, 8), '#e4dcd2', x, eyeY, z - .003, .027, .012, .009);
feature(new T.SphereGeometry(1, 12, 8), b.eyeColor, x, eyeY, z - .012, .010, .010, .003);
feature(new T.SphereGeometry(1, 10, 6), '#202429', x, eyeY, z - .015, .0045, .006, .002);
if (b.eyebrows !== 'none') {
feature(new T.BoxGeometry(1, 1, 1), a.secondary, x, eyeY + .027, z - .005, .055, b.eyebrows === 'bushy' ? .013 : .006, .008);
}
}
// A tapered bridge and triangular nose tip, rather than a spherical button.
const noseY = hy(-.03) + b.noseHeight, ns = b.noseScale;
const nose = new T.BufferGeometry();
nose.setAttribute('position', new T.Float32BufferAttribute([-.013,.05,0, .013,.05,0, -.025,-.025,0, .025,-.025,0, 0,-.017,-.044, 0,-.035,-.015], 3));
nose.setIndex([0,1,4, 0,4,2, 1,3,4, 2,4,5, 3,5,4, 2,5,3, 0,3,1, 0,2,3]);
feature(nose, a.primary, 0, noseY, -hd * .97, ns, ns, ns);
const mouthY = hy(-.105) + b.mouthHeight, lip = '#985e51';
for (const sign of [-1, 1]) {
const y = mouthY + (b.mouthStyle === 'smile' ? .004 : b.mouthStyle === 'stern' ? -.004 : 0);
feature(new T.SphereGeometry(1, 10, 6), lip, sign * .019, y, -hd * .89, .023, .005, .005);
}
// Four fitted hair silhouettes share the same head transform.
const hairRing = (y: number, width: number, depth: number): Ring => [0, hy(y), .018, hw * width, hd * depth];
tube([hairRing(.085, 1.015, 1.00), hairRing(.14, .91, .88), hairRing(.19, .66, .64), hairRing(.214, .16, .16)], a.secondary, () => fixed(headBone), 20);
if (a.variant === 0 || a.variant === 1) {
for (let i = 0; i < 5; i++) {
const x = (i - 2) * hw * .34, height = a.variant === 1 ? .043 + (i + 2) * .008 : .065 + (i % 2) * .012;
tube([[x - (a.variant === 1 ? .035 : 0), hy(height), -hd * .87, .019, .012],
[x, hy(.115), -hd * .80, .042, .035], [x * .75, hy(.177), -hd * .49, .026, .033]], a.secondary, () => fixed(headBone), 8);
}
}
for (const sign of [-1, 1]) {
if (a.variant === 2) tube([[sign * hw * .83, hy(-.15), .025, .041, hd * .89], [sign * hw * .95, hy(-.04), .03, .038, hd * .88], [sign * hw * .85, hy(.10), .025, .04, hd * .78]], a.secondary, () => fixed(headBone), 10);
if (a.variant === 3) {
const rows: Ring[] = [];
for (let i = 0; i < 7; i++) rows.push([sign * (hw + .015 + Math.sin(i * Math.PI / 2) * .01), hy(-.30 + i * .06), .06, .022 + i * .001, .026]);
tube(rows, a.secondary, () => fixed(headBone), 8);
feature(new T.BoxGeometry(1, 1, 1), a.accent, sign * (hw + .015), hy(-.27), .06, .046, .022, .05);
}
}
anchor('helmet', headBone, 0, .15 * b.headLength); anchor('mask', headBone, 0, -.04, -hd);
anchor('necklace', neckBone, 0, -.035, -.08); anchor('earrings', headBone, hw, -.035, 0);
anchor('chest', thorax, 0, 0, -.15); anchor('pants', pelvis); anchor('cape', thorax, 0, .05, .15); anchor('bag', spine, 0, 0, .17);
const geometry = new T.BufferGeometry();
geometry.setAttribute('position', new T.Float32BufferAttribute(positions, 3));
geometry.setAttribute('color', new T.Float32BufferAttribute(colors, 3));
geometry.setAttribute('skinIndex', new T.Uint16BufferAttribute(skinIndices, 4));
geometry.setAttribute('skinWeight', new T.Float32BufferAttribute(weights, 4));
geometry.setIndex(indices); geometry.computeVertexNormals();
const mesh = new T.SkinnedMesh(geometry, new T.MeshStandardMaterial({ vertexColors: true, roughness: .88 }));
mesh.name = 'humanoid-body'; mesh.castShadow = mesh.receiveShadow = true;
root.add(mesh); root.updateMatrixWorld(true); mesh.bind(new T.Skeleton(bones)); mesh.skeleton.update();
return root;
}
+9 -10
View File
@@ -1,7 +1,5 @@
import './style.css';
import { showCharacterCreator } from './appearance-editor';
import type { Appearance } from './generated';
let draftAppearance: Appearance | undefined;
import { createAppearanceEditor } from './appearance-editor';
import {createItemActions} from './item-actions';
import { showTravel } from './travel';
import { createHousingPanel } from './housing-panel';
@@ -357,15 +355,16 @@ async function boot() {
}
if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';}
}
const customize = document.createElement('button'); customize.type = 'button'; customize.textContent = 'Create your look';
customize.onclick = () => showCharacterCreator(draftAppearance, async appearance => { draftAppearance = appearance; customize.textContent = 'Edit your look'; });
$('join-form').insertBefore(customize, $('join'));
const restyle = document.createElement('button'); restyle.type = 'button'; restyle.textContent = 'Character appearance';
restyle.onclick = () => showCharacterCreator(snapshot?.self.entity.appearance, async appearance => { await api('/api/appearance', appearance); notice('Appearance saved.'); });
$('settings').append(restyle);
let characterEditor: ReturnType<typeof createAppearanceEditor> | undefined;
if (me && !me.character && !me.active && config.kind !== 'hub') {
characterEditor = createAppearanceEditor(['human'], undefined, [], true);
$('arrival').classList.add('arrival-creator');
$('arrival-status').textContent = 'Choose your name and appearance. This is who you will be in this life.';
$('join-form').insertBefore(characterEditor.node, $('join'));
}
$<HTMLFormElement>('join-form').onsubmit = async event => {
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '', appearance: draftAppearance }); $<HTMLDialogElement>('arrival').close(); connect(); }
try { await api('/api/join', { name: $<HTMLInputElement>('name').value, passage: '', appearance: characterEditor?.read() }); $<HTMLDialogElement>('arrival').close(); characterEditor?.dispose(); connect(); }
catch (e) { $('arrival-error').textContent = (e as Error).message; }
finally { button.disabled = false; }
};