@hackbuild/avatar-host 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +211 -2
- package/dist/avatar-host.iife.js +13454 -0
- package/dist/body.d.ts +78 -0
- package/dist/body.js +191 -0
- package/dist/drop.d.ts +20 -0
- package/dist/drop.js +44 -0
- package/dist/element.d.ts +9 -0
- package/dist/element.js +77 -0
- package/dist/environment.d.ts +35 -0
- package/dist/environment.js +59 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +25 -0
- package/dist/follow.d.ts +42 -0
- package/dist/follow.js +97 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +88 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -0
- package/dist/load.d.ts +21 -0
- package/dist/load.js +79 -0
- package/dist/loop.d.ts +50 -0
- package/dist/loop.js +102 -0
- package/dist/placeholder.d.ts +11 -0
- package/dist/placeholder.js +90 -0
- package/dist/single.d.ts +2 -0
- package/dist/single.js +4 -0
- package/dist/source.d.ts +35 -0
- package/dist/source.js +83 -0
- package/dist/stage.d.ts +167 -0
- package/dist/stage.js +436 -0
- package/dist/three.d.ts +7 -0
- package/dist/three.js +10 -0
- package/package.json +52 -4
package/dist/source.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// What a stage shows: a model by URL, bytes or a File, with a resolver for
|
|
2
|
+
// the files it references when it came from a drop. Textures are found by
|
|
3
|
+
// their path below the model's folder, then by file name anywhere in the
|
|
4
|
+
// drop, ignoring case (models made on Windows often differ in case).
|
|
5
|
+
const EXT = { vrm: "vrm", glb: "glb", gltf: "gltf", fbx: "fbx" };
|
|
6
|
+
const extOf = (name) => name.toLowerCase().replace(/[?#].*$/, "").split(".").pop() ?? "";
|
|
7
|
+
/** The body kind a file name says, or null. */
|
|
8
|
+
export function kindOf(name) {
|
|
9
|
+
return EXT[extOf(name)] ?? null;
|
|
10
|
+
}
|
|
11
|
+
/** A model by URL; the kind comes from the name, glb when it says nothing. */
|
|
12
|
+
export function sourceFromUrl(url, name = url.split("/").pop() ?? "model") {
|
|
13
|
+
return { kind: kindOf(name) ?? "glb", data: url, name: decodeURIComponent(name.replace(/[?#].*$/, "")) };
|
|
14
|
+
}
|
|
15
|
+
const pathOf = (f) => (f.webkitRelativePath || f.name).replace(/\\/g, "/").toLowerCase();
|
|
16
|
+
const dirOf = (p) => p.slice(0, p.lastIndexOf("/") + 1);
|
|
17
|
+
/** Lower case, forward slashes, no leading ./ and no URL escapes. */
|
|
18
|
+
export function normalizeRef(ref) {
|
|
19
|
+
let r = ref.replace(/\\/g, "/");
|
|
20
|
+
try {
|
|
21
|
+
r = decodeURIComponent(r);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// a stray % stays as it is
|
|
25
|
+
}
|
|
26
|
+
return r.replace(/^(\.\/)+/, "").toLowerCase();
|
|
27
|
+
}
|
|
28
|
+
const browserUrls = { create: (b) => URL.createObjectURL(b), revoke: (u) => URL.revokeObjectURL(u) };
|
|
29
|
+
// Picked in this order when a drop holds several models.
|
|
30
|
+
const ORDER = ["vrm", "glb", "gltf", "fbx"];
|
|
31
|
+
/**
|
|
32
|
+
* A source from dropped or picked files: the first .vrm, .glb, .gltf or .fbx,
|
|
33
|
+
* with every other file reachable through `resolve`. Throws with the copy
|
|
34
|
+
* for the person when the drop holds no model the stage reads.
|
|
35
|
+
*/
|
|
36
|
+
export function sourceFromFiles(files, urls = browserUrls) {
|
|
37
|
+
let model;
|
|
38
|
+
for (const k of ORDER)
|
|
39
|
+
if ((model = files.find((f) => kindOf(f.name) === k)))
|
|
40
|
+
break;
|
|
41
|
+
if (!model) {
|
|
42
|
+
const ext = files.map((f) => extOf(f.name)).find((e) => e === "pmx" || e === "pmd" || e === "vrma" || e === "bvh");
|
|
43
|
+
if (ext === "pmx" || ext === "pmd")
|
|
44
|
+
throw new Error(`this file is a ${ext}. convert it to vrm or glb.`);
|
|
45
|
+
if (ext)
|
|
46
|
+
throw new Error(`a ${ext} file is an animation. drop a body: a .vrm, .glb, .gltf or .fbx.`);
|
|
47
|
+
throw new Error("this drop has no model. drop a .vrm, .glb, .gltf or .fbx file.");
|
|
48
|
+
}
|
|
49
|
+
const dir = dirOf(pathOf(model));
|
|
50
|
+
const byPath = new Map(files.map((f) => [pathOf(f), f]));
|
|
51
|
+
const byName = new Map();
|
|
52
|
+
for (const f of files)
|
|
53
|
+
if (!byName.has(f.name.toLowerCase()))
|
|
54
|
+
byName.set(f.name.toLowerCase(), f);
|
|
55
|
+
const made = new Map();
|
|
56
|
+
const misses = [];
|
|
57
|
+
let released = false;
|
|
58
|
+
const urlOf = (f) => {
|
|
59
|
+
let u = made.get(f);
|
|
60
|
+
if (!u) {
|
|
61
|
+
u = urls.create(f);
|
|
62
|
+
made.set(f, u);
|
|
63
|
+
}
|
|
64
|
+
return u;
|
|
65
|
+
};
|
|
66
|
+
const resolve = (ref) => {
|
|
67
|
+
const low = normalizeRef(ref);
|
|
68
|
+
const f = byPath.get(dir + low) ?? byPath.get(low) ?? byName.get(low.slice(low.lastIndexOf("/") + 1));
|
|
69
|
+
if (f && !released)
|
|
70
|
+
return urlOf(f);
|
|
71
|
+
misses.push(ref);
|
|
72
|
+
return null;
|
|
73
|
+
};
|
|
74
|
+
const release = () => {
|
|
75
|
+
if (released)
|
|
76
|
+
return;
|
|
77
|
+
released = true;
|
|
78
|
+
for (const u of made.values())
|
|
79
|
+
urls.revoke(u);
|
|
80
|
+
made.clear();
|
|
81
|
+
};
|
|
82
|
+
return { kind: kindOf(model.name), data: model, name: model.name, resolve, misses, release };
|
|
83
|
+
}
|
package/dist/stage.d.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { type Light, PerspectiveCamera, Scene, Vector2, WebGLRenderer } from "three";
|
|
2
|
+
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
|
3
|
+
import { type Rng } from "@hackbuild/organic";
|
|
4
|
+
import { type Avatar } from "@hackbuild/avatar/three";
|
|
5
|
+
import { StageLoop, type PauseReason } from "./loop.js";
|
|
6
|
+
import { type BodySource, type DroppedFile } from "./source.js";
|
|
7
|
+
import { Body, type BodyCaps, type BodyOptions } from "./body.js";
|
|
8
|
+
import { FollowCamera, type FollowOptions } from "./follow.js";
|
|
9
|
+
import { type BodyLoadOptions } from "./load.js";
|
|
10
|
+
import { type PlaceholderOptions } from "./placeholder.js";
|
|
11
|
+
import { EnvironmentSlot, type EnvironmentRequest } from "./environment.js";
|
|
12
|
+
import type { LoadedEnvironment } from "@hackbuild/environment/three";
|
|
13
|
+
export declare const LOST_COPY = "the 3d view was lost. press to restore.";
|
|
14
|
+
export interface StageOptions extends BodyLoadOptions {
|
|
15
|
+
/** A canvas to draw on; by default the stage makes one and appends it to the container. */
|
|
16
|
+
canvas?: HTMLCanvasElement;
|
|
17
|
+
/** Seeded randomness for gaze and blinks. Default seededRng("avatar-host"). */
|
|
18
|
+
rng?: Rng;
|
|
19
|
+
/** Device pixels per CSS pixel, at most. Default 2 (proposed); a lit scene caps it at 1.5 (vendor). */
|
|
20
|
+
maxPixelRatio?: number;
|
|
21
|
+
/** Scene background; null leaves the canvas transparent. Default null. */
|
|
22
|
+
background?: number | null;
|
|
23
|
+
/** The plain lights; false when the page brings its own. Default true. */
|
|
24
|
+
lights?: boolean;
|
|
25
|
+
follow?: FollowOptions;
|
|
26
|
+
body?: Omit<BodyOptions, "rng">;
|
|
27
|
+
/** Seconds between stats events. Default 1. */
|
|
28
|
+
statsEvery?: number;
|
|
29
|
+
/** A button with the restore line over a lost context. Default true. */
|
|
30
|
+
restoreButton?: boolean;
|
|
31
|
+
/** A scene to show from the start, as `setEnvironment` takes it. */
|
|
32
|
+
environment?: EnvironmentRequest | string;
|
|
33
|
+
}
|
|
34
|
+
export interface StageStats {
|
|
35
|
+
/** Frames per second over the last window (measured from the loop clock). */
|
|
36
|
+
fps: number;
|
|
37
|
+
frames: number;
|
|
38
|
+
/** Draw calls and triangles of the last frame (three.js renderer info). */
|
|
39
|
+
calls: number;
|
|
40
|
+
triangles: number;
|
|
41
|
+
/** Drawing buffer size in device pixels. */
|
|
42
|
+
width: number;
|
|
43
|
+
height: number;
|
|
44
|
+
pixelRatio: number;
|
|
45
|
+
}
|
|
46
|
+
export type StageEvent = {
|
|
47
|
+
type: "loaded";
|
|
48
|
+
body: Body;
|
|
49
|
+
name: string;
|
|
50
|
+
caps: BodyCaps;
|
|
51
|
+
warnings: string[];
|
|
52
|
+
placeholder: boolean;
|
|
53
|
+
} | {
|
|
54
|
+
type: "failed";
|
|
55
|
+
message: string;
|
|
56
|
+
cause: unknown;
|
|
57
|
+
} | {
|
|
58
|
+
type: "stats";
|
|
59
|
+
stats: StageStats;
|
|
60
|
+
} | {
|
|
61
|
+
type: "state";
|
|
62
|
+
running: boolean;
|
|
63
|
+
reasons: PauseReason[];
|
|
64
|
+
} | {
|
|
65
|
+
type: "lost";
|
|
66
|
+
} | {
|
|
67
|
+
type: "restored";
|
|
68
|
+
};
|
|
69
|
+
type Of<K extends StageEvent["type"]> = Extract<StageEvent, {
|
|
70
|
+
type: K;
|
|
71
|
+
}>;
|
|
72
|
+
export declare class AvatarStage {
|
|
73
|
+
readonly container: HTMLElement;
|
|
74
|
+
private readonly opts;
|
|
75
|
+
readonly scene: Scene<import("three").Object3DEventMap>;
|
|
76
|
+
readonly camera: PerspectiveCamera;
|
|
77
|
+
readonly renderer: WebGLRenderer;
|
|
78
|
+
readonly canvas: HTMLCanvasElement;
|
|
79
|
+
readonly controls: OrbitControls;
|
|
80
|
+
readonly follow: FollowCamera;
|
|
81
|
+
readonly loop: StageLoop;
|
|
82
|
+
readonly lights: Light[];
|
|
83
|
+
/** The body on stage, or null. */
|
|
84
|
+
body: Body | null;
|
|
85
|
+
/** The lit scene around the body: `stage.environment.set("studio")`. */
|
|
86
|
+
readonly environment: EnvironmentSlot;
|
|
87
|
+
private scenery;
|
|
88
|
+
private background;
|
|
89
|
+
/** Normalized pointer over the canvas, -1 to 1, for gaze. */
|
|
90
|
+
readonly pointer: Vector2;
|
|
91
|
+
private pointerAt;
|
|
92
|
+
private viewLook;
|
|
93
|
+
private readonly host;
|
|
94
|
+
private readonly listeners;
|
|
95
|
+
private readonly input;
|
|
96
|
+
private readonly observers;
|
|
97
|
+
private readonly ownCanvas;
|
|
98
|
+
private readonly rng;
|
|
99
|
+
private readonly box;
|
|
100
|
+
private readonly look;
|
|
101
|
+
private readonly v;
|
|
102
|
+
private restoreEl;
|
|
103
|
+
private readonly loseExt;
|
|
104
|
+
private interacting;
|
|
105
|
+
private startDistance;
|
|
106
|
+
private reduced;
|
|
107
|
+
private statT;
|
|
108
|
+
private statFrames;
|
|
109
|
+
private disposed;
|
|
110
|
+
constructor(container: HTMLElement, opts?: StageOptions);
|
|
111
|
+
/** Subscribes to one event type; returns the unsubscribe. */
|
|
112
|
+
on<K extends StageEvent["type"]>(type: K, fn: (e: Of<K>) => void): () => void;
|
|
113
|
+
private emit;
|
|
114
|
+
/**
|
|
115
|
+
* Shows a body from a source, a URL, or dropped files. Resolves to the
|
|
116
|
+
* body, or null when a later show superseded it or it failed; a failure
|
|
117
|
+
* emits `failed` with copy for the person and keeps the current body.
|
|
118
|
+
*/
|
|
119
|
+
show(source: BodySource | string | readonly DroppedFile[] | Promise<BodySource>): Promise<Body | null>;
|
|
120
|
+
/** Shows the placeholder body and supersedes any load in flight. */
|
|
121
|
+
showPlaceholder(opts?: PlaceholderOptions): Body;
|
|
122
|
+
/** Shows an Avatar loaded elsewhere; the stage owns it from here and disposes it on the next swap. */
|
|
123
|
+
showAvatar(avatar: Avatar, name?: string): Body;
|
|
124
|
+
/**
|
|
125
|
+
* Shows a lit scene by preset id or request, or the plain stage for null.
|
|
126
|
+
* Resolves true when that scene shows; a missing file emits `failed` with the
|
|
127
|
+
* environment copy and keeps the current scene.
|
|
128
|
+
*/
|
|
129
|
+
showEnvironment(req: EnvironmentRequest | string | null): Promise<boolean>;
|
|
130
|
+
/** The swap the environment slot calls: old scene out first, new one in, shadows and lights to match. */
|
|
131
|
+
setEnvironment(env: LoadedEnvironment | null): void;
|
|
132
|
+
private castShadows;
|
|
133
|
+
private mount;
|
|
134
|
+
private unmount;
|
|
135
|
+
/** Starts the loop after a pause by hand. */
|
|
136
|
+
play(): void;
|
|
137
|
+
/** Stops the loop by hand; other reasons still apply after play(). */
|
|
138
|
+
pause(): void;
|
|
139
|
+
/** The tool's route is (in)active. */
|
|
140
|
+
setActive(on: boolean): void;
|
|
141
|
+
/** A sheet or a modal covers the stage fully. */
|
|
142
|
+
setCovered(on: boolean): void;
|
|
143
|
+
/** factor above 1 moves closer. */
|
|
144
|
+
zoomBy(factor: number): void;
|
|
145
|
+
/** Frames the body again and forgets the person's pan and zoom. */
|
|
146
|
+
resetView(): void;
|
|
147
|
+
/** Gaze at a point in view coordinates (-1 to 1, +y up), or null to hand gaze back to the pointer and camera. */
|
|
148
|
+
lookAtView(p: {
|
|
149
|
+
x: number;
|
|
150
|
+
y: number;
|
|
151
|
+
} | null): void;
|
|
152
|
+
resize(): void;
|
|
153
|
+
/** One frame rendered now and read in the same task, as a PNG. */
|
|
154
|
+
snapshot(type?: string): Promise<Blob | null>;
|
|
155
|
+
/** After a lost context: asks the browser for the context back. A loss the browser caused comes back by itself when it can. */
|
|
156
|
+
restore(): void;
|
|
157
|
+
private frame;
|
|
158
|
+
private gazeTarget;
|
|
159
|
+
private stats;
|
|
160
|
+
private offscreen;
|
|
161
|
+
private wireInput;
|
|
162
|
+
private wireObservers;
|
|
163
|
+
private showRestore;
|
|
164
|
+
/** Stops the loop, frees the body, the renderer and its context, and removes what the stage added. */
|
|
165
|
+
dispose(): void;
|
|
166
|
+
}
|
|
167
|
+
export {};
|
package/dist/stage.js
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// The avatar stage: a three.js renderer that sizes to its container, an
|
|
2
|
+
// orbit camera that follows the posed body, plain lights, the body frame
|
|
3
|
+
// order, and the stage loop with its pause rules. Loads go through the
|
|
4
|
+
// ticketed host, so fast switching never shows a stale body. Events carry
|
|
5
|
+
// what the stage chrome needs: loaded with the capability list, failed with
|
|
6
|
+
// copy for the person, frame stats, the loop state and a lost context.
|
|
7
|
+
import { Box3, Color, DirectionalLight, HemisphereLight, PCFSoftShadowMap, PerspectiveCamera, Scene, SRGBColorSpace, TOUCH, Vector2, Vector3, WebGLRenderer } from "three";
|
|
8
|
+
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
|
9
|
+
import { seededRng } from "@hackbuild/organic";
|
|
10
|
+
import { posedBounds } from "@hackbuild/avatar/three";
|
|
11
|
+
import { AvatarHost } from "./host.js";
|
|
12
|
+
import { StageLoop } from "./loop.js";
|
|
13
|
+
import { sourceFromFiles, sourceFromUrl } from "./source.js";
|
|
14
|
+
import { bodyError } from "./errors.js";
|
|
15
|
+
import { Body } from "./body.js";
|
|
16
|
+
import { FollowCamera } from "./follow.js";
|
|
17
|
+
import { bodyAdapters } from "./load.js";
|
|
18
|
+
import { placeholderBody } from "./placeholder.js";
|
|
19
|
+
import { EnvironmentSlot, stagePixelRatio } from "./environment.js";
|
|
20
|
+
export const LOST_COPY = "the 3d view was lost. press to restore.";
|
|
21
|
+
/** Pointer moves count as attention for this long, seconds (vendor). */
|
|
22
|
+
const POINTER_WINDOW = 2;
|
|
23
|
+
export class AvatarStage {
|
|
24
|
+
container;
|
|
25
|
+
opts;
|
|
26
|
+
scene = new Scene();
|
|
27
|
+
camera = new PerspectiveCamera(30, 1, 0.05, 200);
|
|
28
|
+
renderer;
|
|
29
|
+
canvas;
|
|
30
|
+
controls;
|
|
31
|
+
follow;
|
|
32
|
+
loop;
|
|
33
|
+
lights = [];
|
|
34
|
+
/** The body on stage, or null. */
|
|
35
|
+
body = null;
|
|
36
|
+
/** The lit scene around the body: `stage.environment.set("studio")`. */
|
|
37
|
+
environment;
|
|
38
|
+
scenery = null;
|
|
39
|
+
background;
|
|
40
|
+
/** Normalized pointer over the canvas, -1 to 1, for gaze. */
|
|
41
|
+
pointer = new Vector2();
|
|
42
|
+
pointerAt = -Infinity;
|
|
43
|
+
viewLook = null;
|
|
44
|
+
host;
|
|
45
|
+
listeners = new Map();
|
|
46
|
+
input = new AbortController();
|
|
47
|
+
observers = [];
|
|
48
|
+
ownCanvas;
|
|
49
|
+
rng;
|
|
50
|
+
box = new Box3();
|
|
51
|
+
look = new Vector3();
|
|
52
|
+
v = new Vector3();
|
|
53
|
+
restoreEl = null;
|
|
54
|
+
loseExt;
|
|
55
|
+
interacting = false;
|
|
56
|
+
startDistance = 0;
|
|
57
|
+
reduced = false;
|
|
58
|
+
statT = 0;
|
|
59
|
+
statFrames = 0;
|
|
60
|
+
disposed = false;
|
|
61
|
+
constructor(container, opts = {}) {
|
|
62
|
+
this.container = container;
|
|
63
|
+
this.opts = opts;
|
|
64
|
+
this.rng = opts.rng ?? seededRng("avatar-host");
|
|
65
|
+
this.ownCanvas = !opts.canvas;
|
|
66
|
+
this.canvas = opts.canvas ?? container.ownerDocument.createElement("canvas");
|
|
67
|
+
if (this.ownCanvas) {
|
|
68
|
+
this.canvas.style.cssText = "display:block;width:100%;height:100%;touch-action:none";
|
|
69
|
+
container.append(this.canvas);
|
|
70
|
+
}
|
|
71
|
+
// no preserveDrawingBuffer: snapshot() renders and reads in one task
|
|
72
|
+
this.renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
|
|
73
|
+
this.renderer.outputColorSpace = SRGBColorSpace;
|
|
74
|
+
this.loseExt = this.renderer.getContext().getExtension("WEBGL_lose_context");
|
|
75
|
+
this.background = opts.background == null ? null : new Color(opts.background);
|
|
76
|
+
this.scene.background = this.background;
|
|
77
|
+
this.renderer.shadowMap.type = PCFSoftShadowMap;
|
|
78
|
+
this.environment = new EnvironmentSlot(this);
|
|
79
|
+
if (opts.lights !== false) {
|
|
80
|
+
const key = new DirectionalLight(0xffffff, 3);
|
|
81
|
+
key.position.set(1.2, 1.8, 2.2);
|
|
82
|
+
const rim = new DirectionalLight(0xbcd0ff, 1.1);
|
|
83
|
+
rim.position.set(-2, 1.2, -1.8);
|
|
84
|
+
this.lights.push(key, rim, new HemisphereLight(0xffffff, 0x404048, 1.5));
|
|
85
|
+
this.scene.add(...this.lights);
|
|
86
|
+
}
|
|
87
|
+
this.camera.position.set(0, 1.3, 3);
|
|
88
|
+
this.controls = new OrbitControls(this.camera, this.canvas);
|
|
89
|
+
this.controls.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
|
|
90
|
+
this.controls.target.set(0, 1, 0);
|
|
91
|
+
this.controls.minDistance = 0.2;
|
|
92
|
+
this.controls.maxDistance = 50;
|
|
93
|
+
this.follow = new FollowCamera(this.camera, this.controls.target, opts.follow);
|
|
94
|
+
this.host = new AvatarHost({ adapters: bodyAdapters(opts), exclusive: false, discard: (a) => a.dispose() });
|
|
95
|
+
this.loop = new StageLoop({
|
|
96
|
+
driver: this.renderer,
|
|
97
|
+
frame: (dt, t) => this.frame(dt, t),
|
|
98
|
+
busy: () => this.interacting || (this.body?.moving() ?? false),
|
|
99
|
+
onState: (running, reasons) => this.emit({ type: "state", running, reasons }),
|
|
100
|
+
});
|
|
101
|
+
this.wireInput();
|
|
102
|
+
this.wireObservers();
|
|
103
|
+
this.resize();
|
|
104
|
+
if (opts.environment)
|
|
105
|
+
void this.showEnvironment(opts.environment);
|
|
106
|
+
}
|
|
107
|
+
/** Subscribes to one event type; returns the unsubscribe. */
|
|
108
|
+
on(type, fn) {
|
|
109
|
+
let set = this.listeners.get(type);
|
|
110
|
+
if (!set)
|
|
111
|
+
this.listeners.set(type, (set = new Set()));
|
|
112
|
+
const f = fn;
|
|
113
|
+
set.add(f);
|
|
114
|
+
return () => set.delete(f);
|
|
115
|
+
}
|
|
116
|
+
emit(e) {
|
|
117
|
+
for (const f of this.listeners.get(e.type) ?? [])
|
|
118
|
+
f(e);
|
|
119
|
+
}
|
|
120
|
+
// ------------------------------------------------------------- bodies
|
|
121
|
+
/**
|
|
122
|
+
* Shows a body from a source, a URL, or dropped files. Resolves to the
|
|
123
|
+
* body, or null when a later show superseded it or it failed; a failure
|
|
124
|
+
* emits `failed` with copy for the person and keeps the current body.
|
|
125
|
+
*/
|
|
126
|
+
async show(source) {
|
|
127
|
+
let src;
|
|
128
|
+
try {
|
|
129
|
+
src = typeof source === "string" ? sourceFromUrl(source) : Array.isArray(source) ? sourceFromFiles(source) : source;
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
this.emit({ type: "failed", message: bodyError(e), cause: e });
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const avatar = await this.host.show(src);
|
|
137
|
+
if (!avatar || this.disposed)
|
|
138
|
+
return null;
|
|
139
|
+
const name = (await src).name;
|
|
140
|
+
return this.mount(avatar, name.replace(/\.[^.]+$/, ""), false);
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
this.emit({ type: "failed", message: bodyError(e), cause: e });
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Shows the placeholder body and supersedes any load in flight. */
|
|
148
|
+
showPlaceholder(opts = {}) {
|
|
149
|
+
void this.host.show(Promise.reject(new Error("superseded"))).catch(() => undefined);
|
|
150
|
+
return this.mount(placeholderBody(opts), "placeholder", true);
|
|
151
|
+
}
|
|
152
|
+
/** Shows an Avatar loaded elsewhere; the stage owns it from here and disposes it on the next swap. */
|
|
153
|
+
showAvatar(avatar, name = avatar.root.name || "body") {
|
|
154
|
+
return this.mount(avatar, name, false);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Shows a lit scene by preset id or request, or the plain stage for null.
|
|
158
|
+
* Resolves true when that scene shows; a missing file emits `failed` with the
|
|
159
|
+
* environment copy and keeps the current scene.
|
|
160
|
+
*/
|
|
161
|
+
async showEnvironment(req) {
|
|
162
|
+
try {
|
|
163
|
+
await this.environment.set(req);
|
|
164
|
+
const id = req === null ? null : typeof req === "string" ? req : typeof req.preset === "string" ? req.preset : req.preset.id;
|
|
165
|
+
return this.environment.current === id;
|
|
166
|
+
}
|
|
167
|
+
catch (e) {
|
|
168
|
+
this.emit({ type: "failed", message: e instanceof Error ? e.message : String(e), cause: e });
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The swap the environment slot calls: old scene out first, new one in, shadows and lights to match. */
|
|
173
|
+
setEnvironment(env) {
|
|
174
|
+
if (this.disposed) {
|
|
175
|
+
env?.dispose();
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.scenery?.dispose();
|
|
179
|
+
this.scenery = env;
|
|
180
|
+
if (env)
|
|
181
|
+
env.attach();
|
|
182
|
+
else
|
|
183
|
+
this.scene.background = this.background;
|
|
184
|
+
const shadows = !!env?.shadows;
|
|
185
|
+
this.renderer.shadowMap.enabled = shadows;
|
|
186
|
+
for (const l of this.lights)
|
|
187
|
+
l.visible = !env;
|
|
188
|
+
if (this.body)
|
|
189
|
+
this.castShadows(this.body.avatar.root, shadows);
|
|
190
|
+
// materials compile again with or without shadow maps
|
|
191
|
+
this.scene.traverse((o) => {
|
|
192
|
+
const m = o.material;
|
|
193
|
+
if (m)
|
|
194
|
+
for (const x of Array.isArray(m) ? m : [m])
|
|
195
|
+
x.needsUpdate = true;
|
|
196
|
+
});
|
|
197
|
+
this.resize();
|
|
198
|
+
}
|
|
199
|
+
castShadows(root, on) {
|
|
200
|
+
root.traverse((o) => (o.castShadow = on));
|
|
201
|
+
}
|
|
202
|
+
mount(avatar, name, placeholder) {
|
|
203
|
+
this.unmount();
|
|
204
|
+
avatar.root.traverse((o) => (o.frustumCulled = false));
|
|
205
|
+
this.castShadows(avatar.root, !!this.scenery?.shadows);
|
|
206
|
+
this.scene.add(avatar.root);
|
|
207
|
+
const body = new Body(avatar, { rng: this.rng, ...this.opts.body });
|
|
208
|
+
this.body = body;
|
|
209
|
+
avatar.root.updateMatrixWorld(true);
|
|
210
|
+
this.follow.frame(posedBounds(avatar.bones));
|
|
211
|
+
this.controls.update();
|
|
212
|
+
this.loop.invalidate();
|
|
213
|
+
this.emit({ type: "loaded", body, name, caps: body.caps, warnings: avatar.warnings, placeholder });
|
|
214
|
+
return body;
|
|
215
|
+
}
|
|
216
|
+
unmount() {
|
|
217
|
+
if (!this.body)
|
|
218
|
+
return;
|
|
219
|
+
this.body.dispose();
|
|
220
|
+
this.body = null;
|
|
221
|
+
}
|
|
222
|
+
// ------------------------------------------------------------- view surface
|
|
223
|
+
/** Starts the loop after a pause by hand. */
|
|
224
|
+
play() {
|
|
225
|
+
this.loop.resume("paused");
|
|
226
|
+
}
|
|
227
|
+
/** Stops the loop by hand; other reasons still apply after play(). */
|
|
228
|
+
pause() {
|
|
229
|
+
this.loop.pause("paused");
|
|
230
|
+
}
|
|
231
|
+
/** The tool's route is (in)active. */
|
|
232
|
+
setActive(on) {
|
|
233
|
+
this.loop.hold("inactive", !on);
|
|
234
|
+
}
|
|
235
|
+
/** A sheet or a modal covers the stage fully. */
|
|
236
|
+
setCovered(on) {
|
|
237
|
+
this.loop.hold("covered", on);
|
|
238
|
+
}
|
|
239
|
+
/** factor above 1 moves closer. */
|
|
240
|
+
zoomBy(factor) {
|
|
241
|
+
this.follow.zoomBy(factor, this.controls.minDistance, this.controls.maxDistance);
|
|
242
|
+
this.controls.update();
|
|
243
|
+
this.loop.invalidate();
|
|
244
|
+
}
|
|
245
|
+
/** Frames the body again and forgets the person's pan and zoom. */
|
|
246
|
+
resetView() {
|
|
247
|
+
if (!this.body)
|
|
248
|
+
return;
|
|
249
|
+
this.body.avatar.root.updateMatrixWorld(true);
|
|
250
|
+
this.follow.frame(posedBounds(this.body.avatar.bones));
|
|
251
|
+
this.controls.update();
|
|
252
|
+
this.loop.invalidate();
|
|
253
|
+
}
|
|
254
|
+
/** Gaze at a point in view coordinates (-1 to 1, +y up), or null to hand gaze back to the pointer and camera. */
|
|
255
|
+
lookAtView(p) {
|
|
256
|
+
this.viewLook = p ? (this.viewLook ?? new Vector2()).set(p.x, p.y) : null;
|
|
257
|
+
}
|
|
258
|
+
resize() {
|
|
259
|
+
const w = this.container.clientWidth;
|
|
260
|
+
const h = this.container.clientHeight;
|
|
261
|
+
const ratio = stagePixelRatio(globalThis.devicePixelRatio || 1, this.opts.maxPixelRatio ?? 2, this.scenery !== null);
|
|
262
|
+
this.renderer.setPixelRatio(ratio);
|
|
263
|
+
this.renderer.setSize(Math.max(1, w), Math.max(1, h), false);
|
|
264
|
+
this.camera.aspect = Math.max(w, 1) / Math.max(h, 1);
|
|
265
|
+
this.camera.updateProjectionMatrix();
|
|
266
|
+
this.loop.hold("offscreen", w === 0 || h === 0 || this.offscreen);
|
|
267
|
+
this.loop.invalidate();
|
|
268
|
+
}
|
|
269
|
+
/** One frame rendered now and read in the same task, as a PNG. */
|
|
270
|
+
snapshot(type = "image/png") {
|
|
271
|
+
// step first: a hidden tab runs no frames, and the body would still be at rest
|
|
272
|
+
this.frame(0, this.loop.time);
|
|
273
|
+
return new Promise((ok) => this.canvas.toBlob((b) => ok(b), type));
|
|
274
|
+
}
|
|
275
|
+
/** After a lost context: asks the browser for the context back. A loss the browser caused comes back by itself when it can. */
|
|
276
|
+
restore() {
|
|
277
|
+
// the extension is taken while the context lives: a lost context hands out none
|
|
278
|
+
this.loseExt?.restoreContext();
|
|
279
|
+
}
|
|
280
|
+
// ------------------------------------------------------------- frame
|
|
281
|
+
frame(dt, t) {
|
|
282
|
+
const body = this.body;
|
|
283
|
+
if (body) {
|
|
284
|
+
body.update(dt, this.gazeTarget(body, t), this.reduced, t);
|
|
285
|
+
if (!this.interacting) {
|
|
286
|
+
body.avatar.root.updateMatrixWorld(true);
|
|
287
|
+
this.box.copy(posedBounds(body.avatar.bones));
|
|
288
|
+
this.follow.step(this.box, dt);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
this.controls.update(dt);
|
|
292
|
+
this.renderer.render(this.scene, this.camera);
|
|
293
|
+
this.stats(dt);
|
|
294
|
+
}
|
|
295
|
+
// what the eyes follow: a point the page set, else the pointer while it
|
|
296
|
+
// moves over the stage, else the viewer
|
|
297
|
+
gazeTarget(body, t) {
|
|
298
|
+
const view = this.viewLook ?? (t - this.pointerAt < POINTER_WINDOW ? this.pointer : null);
|
|
299
|
+
if (!view)
|
|
300
|
+
return this.camera.getWorldPosition(this.look);
|
|
301
|
+
const eye = body.eyePosition(this.v);
|
|
302
|
+
const d = this.camera.position.distanceTo(eye);
|
|
303
|
+
this.look.set(view.x, view.y, 0.5).unproject(this.camera).sub(this.camera.position).setLength(d);
|
|
304
|
+
return this.look.add(this.camera.position);
|
|
305
|
+
}
|
|
306
|
+
stats(dt) {
|
|
307
|
+
this.statT += dt;
|
|
308
|
+
this.statFrames++;
|
|
309
|
+
const every = this.opts.statsEvery ?? 1;
|
|
310
|
+
if (this.statT < every)
|
|
311
|
+
return;
|
|
312
|
+
const size = this.renderer.getDrawingBufferSize(new Vector2());
|
|
313
|
+
const info = this.renderer.info.render;
|
|
314
|
+
this.emit({
|
|
315
|
+
type: "stats",
|
|
316
|
+
stats: { fps: this.statFrames / this.statT, frames: this.loop.frames, calls: info.calls, triangles: info.triangles, width: size.x, height: size.y, pixelRatio: this.renderer.getPixelRatio() },
|
|
317
|
+
});
|
|
318
|
+
this.statT = 0;
|
|
319
|
+
this.statFrames = 0;
|
|
320
|
+
}
|
|
321
|
+
// ------------------------------------------------------------- wiring
|
|
322
|
+
offscreen = false;
|
|
323
|
+
wireInput() {
|
|
324
|
+
const signal = this.input.signal;
|
|
325
|
+
this.canvas.addEventListener("pointermove", (e) => {
|
|
326
|
+
const r = this.canvas.getBoundingClientRect();
|
|
327
|
+
const clamp = (x) => Math.max(-1, Math.min(1, x));
|
|
328
|
+
this.pointer.set(clamp(((e.clientX - r.left) / Math.max(1, r.width)) * 2 - 1), clamp(-(((e.clientY - r.top) / Math.max(1, r.height)) * 2 - 1)));
|
|
329
|
+
this.pointerAt = this.loop.time;
|
|
330
|
+
}, { signal });
|
|
331
|
+
this.canvas.addEventListener("pointerleave", () => (this.pointerAt = -Infinity), { signal });
|
|
332
|
+
this.canvas.addEventListener("dblclick", () => this.resetView(), { signal });
|
|
333
|
+
this.controls.addEventListener("start", () => {
|
|
334
|
+
this.interacting = true;
|
|
335
|
+
this.startDistance = this.follow.distance();
|
|
336
|
+
this.loop.sync();
|
|
337
|
+
});
|
|
338
|
+
this.controls.addEventListener("end", () => {
|
|
339
|
+
this.interacting = false;
|
|
340
|
+
const body = this.body;
|
|
341
|
+
if (body)
|
|
342
|
+
body.avatar.root.updateMatrixWorld(true);
|
|
343
|
+
this.follow.released(body ? posedBounds(body.avatar.bones) : null, this.startDistance);
|
|
344
|
+
this.loop.invalidate();
|
|
345
|
+
});
|
|
346
|
+
this.controls.addEventListener("change", () => this.loop.invalidate());
|
|
347
|
+
this.canvas.addEventListener("webglcontextlost", () => {
|
|
348
|
+
this.loop.hold("lost", true);
|
|
349
|
+
this.showRestore(true);
|
|
350
|
+
this.emit({ type: "lost" });
|
|
351
|
+
}, { signal });
|
|
352
|
+
this.canvas.addEventListener("webglcontextrestored", () => {
|
|
353
|
+
this.showRestore(false);
|
|
354
|
+
this.loop.hold("lost", false);
|
|
355
|
+
this.emit({ type: "restored" });
|
|
356
|
+
}, { signal });
|
|
357
|
+
}
|
|
358
|
+
wireObservers() {
|
|
359
|
+
const doc = this.container.ownerDocument;
|
|
360
|
+
const win = doc.defaultView;
|
|
361
|
+
const signal = this.input.signal;
|
|
362
|
+
doc.addEventListener("visibilitychange", () => this.loop.hold("hidden", doc.hidden), { signal });
|
|
363
|
+
this.loop.hold("hidden", doc.hidden);
|
|
364
|
+
if (win && "ResizeObserver" in win) {
|
|
365
|
+
const ro = new win.ResizeObserver(() => this.resize());
|
|
366
|
+
ro.observe(this.container);
|
|
367
|
+
this.observers.push(ro);
|
|
368
|
+
}
|
|
369
|
+
if (win && "IntersectionObserver" in win) {
|
|
370
|
+
const io = new win.IntersectionObserver((entries) => {
|
|
371
|
+
const e = entries[entries.length - 1];
|
|
372
|
+
if (!e)
|
|
373
|
+
return;
|
|
374
|
+
this.offscreen = !e.isIntersecting || e.boundingClientRect.width === 0 || e.boundingClientRect.height === 0;
|
|
375
|
+
this.loop.hold("offscreen", this.offscreen || this.container.clientWidth === 0 || this.container.clientHeight === 0);
|
|
376
|
+
});
|
|
377
|
+
io.observe(this.container);
|
|
378
|
+
this.observers.push(io);
|
|
379
|
+
}
|
|
380
|
+
const mq = win?.matchMedia?.("(prefers-reduced-motion: reduce)");
|
|
381
|
+
if (mq) {
|
|
382
|
+
const apply = () => {
|
|
383
|
+
this.reduced = mq.matches;
|
|
384
|
+
this.controls.enableDamping = !mq.matches;
|
|
385
|
+
this.loop.reducedMotion = mq.matches;
|
|
386
|
+
};
|
|
387
|
+
mq.addEventListener("change", apply, { signal });
|
|
388
|
+
apply();
|
|
389
|
+
}
|
|
390
|
+
else
|
|
391
|
+
this.controls.enableDamping = true;
|
|
392
|
+
}
|
|
393
|
+
showRestore(on) {
|
|
394
|
+
if (this.opts.restoreButton === false)
|
|
395
|
+
return;
|
|
396
|
+
if (on && !this.restoreEl) {
|
|
397
|
+
const doc = this.container.ownerDocument;
|
|
398
|
+
const b = doc.createElement("button");
|
|
399
|
+
b.type = "button";
|
|
400
|
+
b.className = "hb-btn hb-stage-restore";
|
|
401
|
+
b.textContent = LOST_COPY;
|
|
402
|
+
b.style.cssText = "position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);max-width:calc(100% - 32px)";
|
|
403
|
+
b.addEventListener("click", () => this.restore());
|
|
404
|
+
if (doc.defaultView?.getComputedStyle(this.container).position === "static")
|
|
405
|
+
this.container.style.position = "relative";
|
|
406
|
+
this.container.append(b);
|
|
407
|
+
this.restoreEl = b;
|
|
408
|
+
}
|
|
409
|
+
else if (!on && this.restoreEl) {
|
|
410
|
+
this.restoreEl.remove();
|
|
411
|
+
this.restoreEl = null;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/** Stops the loop, frees the body, the renderer and its context, and removes what the stage added. */
|
|
415
|
+
dispose() {
|
|
416
|
+
if (this.disposed)
|
|
417
|
+
return;
|
|
418
|
+
this.disposed = true;
|
|
419
|
+
this.loop.dispose();
|
|
420
|
+
this.host.destroy();
|
|
421
|
+
this.input.abort();
|
|
422
|
+
for (const o of this.observers)
|
|
423
|
+
o.disconnect();
|
|
424
|
+
this.unmount();
|
|
425
|
+
this.environment.cancel();
|
|
426
|
+
this.scenery?.dispose();
|
|
427
|
+
this.scenery = null;
|
|
428
|
+
this.controls.dispose();
|
|
429
|
+
this.renderer.dispose();
|
|
430
|
+
this.loseExt?.loseContext();
|
|
431
|
+
this.restoreEl?.remove();
|
|
432
|
+
if (this.ownCanvas)
|
|
433
|
+
this.canvas.remove();
|
|
434
|
+
this.listeners.clear();
|
|
435
|
+
}
|
|
436
|
+
}
|