Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

duoViewer.ts

566 lines21.5 KB

1// @effect-diagnostics globalTimers:off - Native display handoff has a bounded acknowledgement window.
2import {
3 AmbientLight,
4 Box3,
5 CanvasTexture,
6 DirectionalLight,
7 Euler,
8 LinearFilter,
9 PerspectiveCamera,
10 PMREMGenerator,
11 Quaternion,
12 Scene,
13 SRGBColorSpace,
14 Vector3,
15 WebGLRenderer,
16} from "three";
17import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
18import {
19 createDuoScene,
20 duoDisplayKey,
21 duoFrameMatches,
22 type DuoPanelId,
23 type DuoHingeLeaf,
24} from "./duoScene.ts";
25import { loadDeviceModel } from "./modelScene.ts";
26import { createDeviceModelSlot, type DeviceModelSource } from "./model.ts";
27import { createDeviceFraming } from "./deviceFraming.ts";
28import { createDeviceMotion } from "./deviceMotion.ts";
29import { duoViewSnaps, nearestDuoView, type DuoRestFace } from "./duoSnap.ts";
30import { createRenderScheduler } from "./renderScheduler.ts";
31import type { DeviceScreenSize } from "./stream.ts";
32import type { DuoPose } from "./duoControl.ts";
33​
34export interface DuoViewer {
35 readonly setScreen: (screen: DeviceScreenSize | null) => void;
36 readonly setHingePreview: (angle: number | null) => void;
37 readonly setInteractionActive: (active: boolean, mode?: "touch" | "orbit") => void;
38 readonly rejectOrientation: () => void;
39 readonly frameUpdated: (panel: DuoPanelId, primary?: HTMLCanvasElement) => void;
40 readonly resize: (width: number, height: number, pixelRatio: number) => void;
41 readonly screenPoint: (
42 x: number,
43 y: number,
44 captured?: boolean,
45 ) => { x: number; y: number } | null;
46 readonly orbit: (x: number, y: number) => void;
47 readonly beginHinge: (x: number, y: number) => boolean;
48 readonly resetPose: () => void;
49 readonly cancelInput: () => void;
50 readonly dispose: () => void;
52​
53/** On-demand renderer for the articulated body. One inner framebuffer spans both leaves; HID belongs to the stream. */
54export function createDuoViewer(options: {
55 canvas: HTMLCanvasElement;
56 sources: Record<DuoPanelId, HTMLCanvasElement>;
57 model: DeviceModelSource;
58 onUnavailable: () => void;
59 onModelError?: (cause: unknown) => void;
60 onPanelRequested?: (panel: DuoPanelId) => void;
61 onOrientationRequested?: (orientation: DeviceScreenSize["orientation"]) => void;
62}): DuoViewer {
63 const surfaces = ([1, 3] as const)
64 .map((id) => {
65 const canvas = document.createElement("canvas");
66 canvas.width = id === 1 ? 784 : 1600;
67 canvas.height = id === 1 ? 1140 : 1125;
68 const context = canvas.getContext("2d", { alpha: false });
69 if (!context) throw new Error("Duo display canvas is unavailable");
70 context.fillStyle = "#080a10";
71 context.fillRect(0, 0, canvas.width, canvas.height);
72 return { id, canvas, context };
73 })
74 .map(({ id, canvas, context }) => {
75 const texture = new CanvasTexture(canvas);
76 texture.colorSpace = SRGBColorSpace;
77 texture.minFilter = texture.magFilter = LinearFilter;
78 texture.generateMipmaps = false;
79 return { id, canvas, context, texture };
80 });
81 const renderer = new WebGLRenderer({
82 canvas: options.canvas,
83 alpha: true,
84 antialias: true,
85 powerPreference: "low-power",
86 });
87 renderer.outputColorSpace = SRGBColorSpace;
88 const scene = new Scene();
89 const environment = (() => {
90 const generator = new PMREMGenerator(renderer);
91 const room = new RoomEnvironment();
92 try {
93 return generator.fromScene(room, 0.04);
94 } catch (cause) {
95 for (const surface of surfaces) surface.texture.dispose();
96 renderer.dispose();
97 renderer.forceContextLoss();
98 throw cause;
99 } finally {
100 room.dispose();
101 generator.dispose();
102 }
103 })();
104 scene.environment = environment.texture;
105 const camera = new PerspectiveCamera(36, 1, 0.1, 150);
106 const key = new DirectionalLight(0xffffff, 4);
107 key.position.set(-6, 10, 14);
108 const fill = new DirectionalLight(0xc7dcff, 2);
109 fill.position.set(8, -3, -5);
110 scene.add(new AmbientLight(0xffffff, 2.4), key, fill);
111 let model: ReturnType<typeof createDuoScene> | null = null;
112 let screen: DeviceScreenSize | null = null;
113 let readyKey = "";
114 let primaryKey = "";
115 let activationAt = 0;
116 let disposed = false;
117 let viewport = { width: 0, height: 0, ratio: 1 };
118 let buffer = { width: 0, height: 0, ratio: 0 };
119 let restFace: DuoRestFace = "inside";
120 let requestedOrientation: DeviceScreenSize["orientation"] | null = null;
121 let viewOrientation: DeviceScreenSize["orientation"] | null = null;
122 const pivot = new Vector3();
123 const targetPivot = new Vector3();
124 let requestedPanel: DuoPanelId | null = null;
125 let handoffTimer: ReturnType<typeof setTimeout> | null = null;
126 const clearHandoff = () => {
127 if (handoffTimer) clearTimeout(handoffTimer);
128 handoffTimer = null;
129 requestedPanel = null;
130 };
131 const activeSnaps = () =>
132 model
133 ? duoViewSnaps(
134 model.restFrames(screen?.screenId === 1 ? 1 : 3),
135 screen?.screenId === 1 ? 1 : 3,
136 )
137 : [];
138 const snaps = () => {
139 if (!model || !screen?.supportsPhysicalOrientation || !options.onPanelRequested)
140 return activeSnaps();
141 const cover = duoViewSnaps(model.restFrames(1), 1);
142 // A shut inner display is occluded and cannot become a useful rest view.
143 return angle > 20 && angle < 180
144 ? [...duoViewSnaps(model.restFrames(3), 3), ...cover]
145 : activeSnaps();
146 };
147 const orbit = createDeviceMotion({
148 choose(rotation) {
149 const snap = nearestDuoView(rotation, snaps());
150 if (!snap) return rotation;
151 restFace = snap.face;
152 const panel = snap.face === "cover" ? 1 : 3;
153 if (screen && panel !== (requestedPanel ?? screen.screenId) && options.onPanelRequested) {
154 clearHandoff();
155 requestedPanel = panel;
156 model?.cancelInput();
157 options.onPanelRequested(panel);
158 handoffTimer = setTimeout(() => {
159 clearHandoff();
160 const confirmed = nearestDuoView(orbit.rotation, activeSnaps());
161 if (confirmed) {
162 restFace = confirmed.face;
163 orbit.setPose(confirmed.rotation, performance.now());
164 }
165 scheduler.invalidate();
166 }, 5000);
167 } else if (
168 screen &&
169 requestedPanel === null &&
170 snap.orientation !== viewOrientation &&
171 options.onOrientationRequested
172 ) {
173 viewOrientation = snap.orientation;
174 requestedOrientation = snap.orientation;
175 options.onOrientationRequested(snap.orientation);
176 }
177 return snap.rotation;
178 },
179 });
180 let angle = 180;
181 let targetAngle = 180;
182 let previewAngle: number | null = null;
183 let hingeLeaf: DuoHingeLeaf | null = null;
184 let appliedAngle = Number.NaN;
185 let interactionActive = false;
186 const framing = createDeviceFraming();
187 const framingBounds = new Box3();
188 let firstPose = true;
189 let physicalPose: DuoPose = "open";
190 let presentationAngle = 180;
191 let targetPresentation = new Quaternion();
192 let lastTime = 0;
193 const reduced =
194 typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
195 const applyPose = () => {
196 if (!model) return;
197 const before = hingeLeaf && appliedAngle !== angle ? model.leafRotation(hingeLeaf) : null;
198 model.setAngle(angle);
199 appliedAngle = angle;
200 if (before && hingeLeaf) {
201 // The primary surface stays in camera space; its partner supplies the fold.
202 // Rebase both the displayed rotation and its rest target so releasing a
203 // pinch cannot resume the pre-fold body rotation.
204 const correction = before.multiply(model.leafRotation(hingeLeaf).invert());
205 if (correction.angleTo(new Quaternion()) > 1e-8)
206 orbit.setPose(orbit.rotation.clone().multiply(correction), performance.now(), true);
207 }
208 model.root.quaternion.copy(orbit.rotation);
209 model.root.position.set(0, 0, 0);
210 const frames = model.restFrames(restFace === "cover" ? 1 : 3);
211 const frame = frames.find((frame) => frame.face === restFace) ?? frames[0];
212 targetPivot.copy(frame?.center ?? new Vector3());
213 model.root.position.copy(pivot).applyQuaternion(model.root.quaternion).negate();
214 };
215 const updateCamera = () => {
216 camera.position.set(framing.center.x, framing.center.y, framing.distance());
217 camera.lookAt(framing.center.x, framing.center.y, 0);
218 camera.updateProjectionMatrix();
219 };
220 const fit = (immediate = false) => {
221 if (!model || !viewport.width || !viewport.height) return;
222 camera.aspect = viewport.width / viewport.height;
223 framing.setBounds(
224 framingBounds.setFromObject(model.root),
225 (camera.fov * Math.PI) / 360,
226 camera.aspect,
227 performance.now(),
228 immediate,
229 );
230 updateCamera();
231 };
232 const moving = () =>
233 Math.abs(angle - targetAngle) > 0.01 || pivot.distanceTo(targetPivot) > 0.001;
234 const scheduler = createRenderScheduler(() => {
235 if (disposed || !model || !viewport.width || !viewport.height) return;
236 try {
237 const now = performance.now();
238 const elapsed = Math.max(0, (now - lastTime) / 1000);
239 const amount = reduced
240 ? 1
241 : 1 - Math.exp(-14 * Math.max(0, (now - lastTime) / 1000 || 0.016));
242 lastTime = now;
243 const inMotion = moving();
244 const orbitChanged = orbit.advance(now, reduced);
245 if (inMotion) {
246 angle += (targetAngle - angle) * amount;
247​
248 if (Math.abs(angle - targetAngle) <= 0.01) angle = targetAngle;
249 applyPose();
250 pivot.lerp(targetPivot, amount);
251 if (pivot.distanceTo(targetPivot) <= 0.001) pivot.copy(targetPivot);
252 applyPose();
253 fit(reduced || elapsed > 0.5);
254 }
255 if (orbitChanged) {
256 applyPose();
257 fit(reduced || elapsed > 0.5);
258 }
259 if (framing.advance(now, reduced)) updateCamera();
260 if (
261 buffer.width !== viewport.width ||
262 buffer.height !== viewport.height ||
263 buffer.ratio !== viewport.ratio
264 ) {
265 renderer.setDrawingBufferSize(viewport.width, viewport.height, viewport.ratio);
266 buffer = viewport;
267 }
268 renderer.render(scene, camera);
269 if (inMotion || moving() || orbit.needsFrame() || framing.needsFrame())
270 scheduler.invalidate();
271 } catch {
272 options.onUnavailable();
273 }
274 });
275 const slot = createDeviceModelSlot({
276 load: loadDeviceModel,
277 onError(cause) {
278 options.onModelError?.(cause);
279 options.onUnavailable();
280 },
281 install(loaded) {
282 const next = loaded
283 ? createDuoScene(loaded.asset, { 1: surfaces[0]!.texture, 3: surfaces[1]!.texture })
284 : null;
285 if (model) {
286 scene.remove(model.root);
287 model.dispose();
288 }
289 model = next;
290 appliedAngle = Number.NaN;
291 if (!model || disposed) return;
292 scene.add(model.root);
293 applyPose();
294 if (screen?.screenId === 1) {
295 const snap = nearestDuoView(orbit.rotation, activeSnaps());
296 if (snap) {
297 restFace = snap.face;
298 orbit.setPose(snap.rotation, performance.now(), true);
299 applyPose();
300 }
301 }
302 pivot.copy(targetPivot);
303 applyPose();
304 fit();
305 scheduler.invalidate();
306 },
307 });
308 const lost = (event: Event) => {
309 event.preventDefault();
310 options.onUnavailable();
311 };
312 options.canvas.addEventListener("webglcontextlost", lost);
313 slot.set(options.model);
314 return {
315 setScreen(next) {
316 if (disposed) return;
317 const wasMoving = moving() || orbit.needsFrame();
318 if (duoDisplayKey(screen) !== duoDisplayKey(next)) {
319 readyKey = "";
320 activationAt = performance.now();
321 model?.cancelInput();
322 }
323 const previous = screen;
324 const ownedHandoff = requestedPanel !== null;
325 if (!next || next.screenId === requestedPanel) clearHandoff();
326 const ownedRotation = requestedOrientation !== null && next?.screenId === previous?.screenId;
327 const changedDisplay = next?.screenId !== previous?.screenId;
328 requestedOrientation = null;
329 screen = next;
330 const changedPose = next?.hingePose && next.hingePose !== previous?.hingePose;
331 const folding = hingeLeaf !== null && !changedPose;
332 const rotated =
333 next?.screenId === previous?.screenId &&
334 next?.hingeAngle === previous?.hingeAngle &&
335 next?.orientation !== previous?.orientation;
336 const leftPhysicalPose =
337 rotated &&
338 !ownedRotation &&
339 !ownedHandoff &&
340 !folding &&
341 !next?.hingePose &&
342 previewAngle === null;
343 if (firstPose || changedPose || leftPhysicalPose) {
344 physicalPose = next?.hingePose ?? (next?.screenId === 1 ? "closed" : "open");
345 presentationAngle = next?.hingeAngle ?? (next?.screenId === 1 ? 0 : 180);
346 }
347 // A command reply/config confirms hinge state. Display identity, never an angle heuristic, owns input.
348 targetAngle = previewAngle ?? next?.hingeAngle ?? (next?.screenId === 1 ? 0 : 180);
349 // Native angle commands clear hingePose. They change articulation only;
350 // preserve the viewing pose, including laptop/tent and user orbit. A
351 // separate rotation clears the physical preset and follows panel orientation.
352 if (firstPose || changedPose || (rotated && !ownedRotation && !ownedHandoff && !folding)) {
353 hingeLeaf = null;
354 viewOrientation = next?.orientation ?? null;
355 const poseAngle = presentationAngle;
356 const fold = ((180 - poseAngle) * Math.PI) / 360;
357 let roll = physicalPose === "closed" ? 0 : Math.PI / 2;
358 if (next && next.width < next.height) {
359 if (next.orientation === "landscape_left") roll -= Math.PI / 2;
360 if (next.orientation === "landscape_right") roll += Math.PI / 2;
361 }
362 if (next?.orientation === "portrait_upside_down") roll -= Math.PI;
363 const physical =
364 physicalPose === "laptop"
365 ? new Euler(-fold + Math.PI / 9, -Math.PI / 9, Math.PI / 2, "YXZ")
366 : physicalPose === "tent"
367 ? new Euler(Math.PI / 2 + Math.PI / 18, -Math.PI / 9, -Math.PI / 2, "YXZ")
368 : new Euler(0, (Math.PI / 2) * Math.pow(1 - poseAngle / 180, 3), 0, "YXZ");
369 targetPresentation = new Quaternion().setFromEuler(physical);
370 if (physicalPose !== "laptop" && physicalPose !== "tent")
371 targetPresentation.premultiply(
372 new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), roll),
373 );
374 if (next?.screenId === 1) {
375 // Native readback can retain the cover even for an open physical preset.
376 // A screen-facing rest must use that display's actual hinged normal.
377 const snap = nearestDuoView(targetPresentation, activeSnaps());
378 if (snap) targetPresentation.copy(snap.rotation);
379 }
380 if (firstPose) angle = targetAngle;
381 restFace = next?.screenId === 1 ? "cover" : physicalPose === "laptop" ? "right" : "inside";
382 orbit.setPose(targetPresentation, performance.now(), firstPose);
383 firstPose = false;
384 } else if (next && changedDisplay && !ownedHandoff && !folding) {
385 // A sensor rotation can hand ownership to the other native display.
386 // Face that display without sending another rotation and creating a feedback loop.
387 const snap = nearestDuoView(orbit.rotation, activeSnaps());
388 if (snap) {
389 restFace = snap.face;
390 orbit.setPose(snap.rotation, performance.now());
391 }
392 }
393 if (!wasMoving) lastTime = performance.now();
394 applyPose();
395 fit();
396 scheduler.invalidate();
397 },
398 setHingePreview(next) {
399 if (disposed || (next !== null && (!Number.isFinite(next) || next < 0 || next > 180))) return;
400 if (!moving()) lastTime = performance.now();
401 previewAngle = next;
402 if (next !== null && !hingeLeaf && model) {
403 clearHandoff();
404 requestedOrientation = null;
405 hingeLeaf = screen?.screenId === 1 && angle > 20 ? "left" : "right";
406 orbit.setPose(orbit.rotation.clone(), performance.now(), true);
407 }
408 orbit.hold(interactionActive || next !== null, performance.now());
409 targetAngle = next ?? screen?.hingeAngle ?? (screen?.screenId === 1 ? 0 : 180);
410 if (next !== null) {
411 angle = next;
412 applyPose();
413 fit();
414 }
415 model?.cancelInput();
416 scheduler.invalidate();
417 },
418 setInteractionActive(active, mode = "touch") {
419 if (disposed) return;
420 if (mode === "orbit") {
421 if (active) hingeLeaf = null;
422 orbit.dragActive(active, performance.now());
423 } else {
424 interactionActive = active;
425 orbit.hold(active || previewAngle !== null, performance.now());
426 framing.hold(active, performance.now());
427 }
428 scheduler.invalidate();
429 },
430 rejectOrientation() {
431 if (disposed || (requestedOrientation === null && requestedPanel === null)) return;
432 clearHandoff();
433 requestedOrientation = null;
434 viewOrientation = screen?.orientation ?? null;
435 const confirmed = activeSnaps().filter((snap) => snap.orientation === screen?.orientation);
436 const snap = nearestDuoView(orbit.rotation, confirmed);
437 if (snap) {
438 restFace = snap.face;
439 orbit.setPose(snap.rotation, performance.now());
440 }
441 scheduler.invalidate();
442 },
443 frameUpdated(id, primary) {
444 if (disposed || screen?.screenId !== id) return;
445 const key = duoDisplayKey(screen);
446 // The elected native feed is authoritative during handoff. Fixed-panel
447 // encoders can retain an inactive blank until that surface changes again.
448 if (!primary && primaryKey === key) return;
449 const source = primary ?? options.sources[id];
450 if (!duoFrameMatches(source, screen)) return;
451 const surface = surfaces[id === 1 ? 0 : 1]!;
452 const { context, canvas } = surface;
453 // Ignore native shutdown blanks only while waiting for an activation. Steady black application content remains valid.
454 if (!primary && !readyKey && performance.now() - activationAt < 1500) {
455 const probe = document.createElement("canvas");
456 probe.width = probe.height = 8;
457 const probeContext = probe.getContext("2d", { willReadFrequently: true });
458 if (probeContext) {
459 probeContext.drawImage(source, 0, 0, 8, 8);
460 if (
461 !probeContext
462 .getImageData(0, 0, 8, 8)
463 .data.some((value, index) => index % 4 !== 3 && value > 3)
464 )
465 return;
466 }
467 }
468 context.save();
469 context.fillStyle = "#080a10";
470 context.fillRect(0, 0, canvas.width, canvas.height);
471 context.translate(canvas.width / 2, canvas.height / 2);
472 // The inner panel is mounted a quarter turn from the native framebuffer.
473 const rotate = id === 3;
474 if (rotate) context.rotate(Math.PI / 2);
475 const scale = Math.min(
476 canvas.width / (rotate ? source.height : source.width),
477 canvas.height / (rotate ? source.width : source.height),
478 );
479 context.drawImage(
480 source,
481 (-source.width * scale) / 2,
482 (-source.height * scale) / 2,
483 source.width * scale,
484 source.height * scale,
485 );
486 context.restore();
487 surface.texture.needsUpdate = true;
488 readyKey = duoDisplayKey(screen);
489 if (primary) primaryKey = readyKey;
490 scheduler.invalidate();
491 },
492 resize(width, height, ratio) {
493 if (disposed || ![width, height, ratio].every(Number.isFinite) || width <= 0 || height <= 0)
494 return;
495 viewport = { width, height, ratio: Math.min(2, Math.max(1, ratio)) };
496 fit(true);
497 scheduler.invalidate();
498 },
499 screenPoint(x, y, captured = false) {
500 if (
501 disposed ||
502 moving() ||
503 previewAngle !== null ||
504 requestedOrientation !== null ||
505 requestedPanel !== null
506 )
507 return null;
508 applyPose();
509 return model?.screenPoint(x, y, camera, screen, readyKey, captured) ?? null;
510 },
511 cancelInput() {
512 hingeLeaf = null;
513 model?.cancelInput();
514 },
515 orbit(x, y) {
516 if (disposed) return;
517 hingeLeaf = null;
518 orbit.orbit(x * viewport.width, y * viewport.height, performance.now());
519 scheduler.invalidate();
520 },
521 beginHinge(x, y) {
522 if (disposed || !model || !screen) return false;
523 applyPose();
524 const leaf = model.hingeLeafAt(x, y, camera);
525 if (!leaf) return false;
526 clearHandoff();
527 requestedOrientation = null;
528 // The right inner leaf and the shut cover share the front-facing plane.
529 // Holding that leaf lets the cover replace the inner image without a
530 // half turn, even when the pinch starts over the moving partner.
531 hingeLeaf = screen.screenId === 1 && angle > 20 ? "left" : "right";
532 orbit.setPose(orbit.rotation.clone(), performance.now(), true);
533 model.cancelInput();
534 return true;
535 },
536 resetPose() {
537 if (disposed) return;
538 hingeLeaf = null;
539 requestedOrientation = null;
540 clearHandoff();
541 const snap = activeSnaps().find((snap) => snap.orientation === screen?.orientation);
542 if (snap && snap.orientation !== viewOrientation && options.onOrientationRequested) {
543 viewOrientation = snap.orientation;
544 requestedOrientation = snap.orientation;
545 options.onOrientationRequested(snap.orientation);
546 }
547 orbit.reset(snap?.rotation ?? targetPresentation, performance.now());
548 applyPose();
549 fit();
550 scheduler.invalidate();
551 },
552 dispose() {
553 clearHandoff();
554 if (disposed) return;
555 disposed = true;
556 scheduler.dispose();
557 slot.dispose();
558 options.canvas.removeEventListener("webglcontextlost", lost);
559 for (const surface of surfaces) surface.texture.dispose();
560 scene.environment = null;
561 environment.dispose();
562 renderer.dispose();
563 renderer.forceContextLoss();
564 },
565 };