feat(web): control Android foldables in the Device panel (#13534)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
6391be2729
commit
9957349c0a
11 files changed
+985
-15
No files matched your search
@@ -111,6 +111,32 @@ describe("device hub proxy", () => {
|
||||
await response.text();
|
||||
});
|
||||
|
||||
it("reads Android fold state but requires operate scope to change it", async () => {
|
||||
const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
|
||||
const reader = fixture([AuthOrchestrationReadScope]);
|
||||
const read = await reader.handler(new Request(path));
|
||||
expect(read.status).toBe(200);
|
||||
await read.text();
|
||||
expect(reader.requests).toEqual([
|
||||
"http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
|
||||
]);
|
||||
const denied = await reader.handler(
|
||||
new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
|
||||
);
|
||||
expect(denied.status).toBe(403);
|
||||
expect(reader.requests).toHaveLength(1);
|
||||
|
||||
const operator = fixture([AuthOrchestrationOperateScope]);
|
||||
const changed = await operator.handler(
|
||||
new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
|
||||
);
|
||||
expect(changed.status).toBe(200);
|
||||
await changed.text();
|
||||
expect(operator.requests).toEqual([
|
||||
"http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
|
||||
]);
|
||||
});
|
||||
|
||||
it("never forwards the vendor shell endpoint", async () => {
|
||||
const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
|
||||
expect(
|
||||
|
||||
@@ -44,7 +44,7 @@ const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
|
||||
/^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
|
||||
/^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
|
||||
/^\/vendor\/serve-sim\/appstate$/,
|
||||
/^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility)$/,
|
||||
/^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
|
||||
/^\/vendor\/serve-emu\/health$/,
|
||||
];
|
||||
|
||||
@@ -52,6 +52,7 @@ const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
|
||||
const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
|
||||
/^\/vendor\/serve-sim\/api\/screenshot$/,
|
||||
/^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
|
||||
/^\/vendor\/serve-emu\/api\/fold$/,
|
||||
];
|
||||
|
||||
const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [
|
||||
@@ -204,7 +205,7 @@ const handler = Effect.gen(function* () {
|
||||
}
|
||||
const controlsDevice =
|
||||
(upgrade && hubPath !== "/api/devices/ws") ||
|
||||
(!readOnly && /\/api\/stream-(mode|settings)$/.test(hubPath));
|
||||
(!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
|
||||
yield* authenticate(controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope);
|
||||
const devices = yield* DeviceService.DeviceService;
|
||||
const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import {
|
||||
readAndroidFold,
|
||||
setAndroidFold,
|
||||
type AndroidFoldPosture,
|
||||
type AndroidFoldState,
|
||||
} from "./deviceFold";
|
||||
import { DeviceDuoGlyph } from "./DeviceDuoGlyph";
|
||||
|
||||
/** Capability comes from the emulator, not its AVD name or screen dimensions. */
|
||||
export function DeviceAndroidFoldControls(props: {
|
||||
readonly access: DeviceHubAccess;
|
||||
readonly deviceId: string;
|
||||
readonly visible: boolean;
|
||||
readonly enabled: boolean;
|
||||
readonly screenWidth: number | undefined;
|
||||
readonly screenHeight: number | undefined;
|
||||
readonly onFoldAngle: (angle: number | null) => void;
|
||||
}) {
|
||||
const [fold, setFold] = useState<AndroidFoldState | null>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const busy = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
const { access, deviceId, visible, enabled, screenWidth, screenHeight, onFoldAngle } = props;
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible || !enabled || pending || !screenWidth || !screenHeight) return;
|
||||
const controller = new AbortController();
|
||||
let retry: number | undefined;
|
||||
const read = () => {
|
||||
void readAndroidFold(access, deviceId, controller.signal)
|
||||
.then((next) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setFold(next);
|
||||
onFoldAngle(
|
||||
next.supported ? (next.hingeAngle ?? (next.posture === "closed" ? 0 : 180)) : null,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) retry = window.setTimeout(read, 3_000);
|
||||
});
|
||||
};
|
||||
read();
|
||||
return () => {
|
||||
controller.abort();
|
||||
window.clearTimeout(retry);
|
||||
};
|
||||
}, [access, deviceId, visible, enabled, screenWidth, screenHeight, pending, onFoldAngle]);
|
||||
|
||||
if (!fold?.supported || !props.visible) return null;
|
||||
|
||||
const change = (posture: AndroidFoldPosture) => {
|
||||
if (busy.current || !props.enabled) return;
|
||||
busy.current = true;
|
||||
setPending(true);
|
||||
setError(null);
|
||||
props.onFoldAngle(posture === "closed" ? 0 : 180);
|
||||
const controller = new AbortController();
|
||||
const timeout = window.setTimeout(() => controller.abort(), 12_000);
|
||||
void setAndroidFold(props.access, props.deviceId, posture, controller.signal)
|
||||
.then((next) => {
|
||||
if (mounted.current) {
|
||||
setFold(next);
|
||||
props.onFoldAngle(next.hingeAngle ?? (next.posture === "closed" ? 0 : 180));
|
||||
}
|
||||
})
|
||||
.catch((cause: unknown) => {
|
||||
if (mounted.current) {
|
||||
props.onFoldAngle(fold.hingeAngle ?? (fold.posture === "closed" ? 0 : 180));
|
||||
setError(
|
||||
controller.signal.aborted
|
||||
? "Fold command timed out."
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: "Could not change fold posture.",
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
window.clearTimeout(timeout);
|
||||
busy.current = false;
|
||||
if (mounted.current) setPending(false);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div aria-label="Android fold controls" className="flex flex-col items-center gap-2">
|
||||
<div className="pointer-events-auto flex shrink-0 flex-col items-center gap-1 rounded-full border border-border/50 bg-background/80 p-1 shadow-sm">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon"
|
||||
variant={fold.posture === "closed" ? "secondary" : "ghost"}
|
||||
aria-label="Fold device"
|
||||
aria-pressed={fold.posture === "closed"}
|
||||
disabled={pending || !props.enabled}
|
||||
onClick={() => change("closed")}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<DeviceDuoGlyph pose="closed" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="left">Fold device</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon"
|
||||
variant={fold.posture === "opened" ? "secondary" : "ghost"}
|
||||
aria-label="Unfold device"
|
||||
aria-pressed={fold.posture === "opened"}
|
||||
disabled={pending || !props.enabled}
|
||||
onClick={() => change("opened")}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<DeviceDuoGlyph pose="open" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="left">Unfold device</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{error ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
role="alert"
|
||||
aria-label={error}
|
||||
className="pointer-events-auto text-xs text-destructive"
|
||||
>
|
||||
!
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="left">{error}</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export function DevicePhoneViewport(props: {
|
||||
readonly onInputCancel: (cancel: (() => void) | null) => void;
|
||||
readonly client: RefObject<DeviceStreamClient | null>;
|
||||
readonly screen: DeviceScreenSize | null;
|
||||
readonly foldAngle: number | null;
|
||||
readonly onUnavailable: () => void;
|
||||
}) {
|
||||
const hostRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -29,11 +30,17 @@ export function DevicePhoneViewport(props: {
|
||||
const viewerRef = useRef<PhoneViewer | null>(null);
|
||||
const interactionRef = useRef<ReturnType<typeof createPhoneInteraction> | null>(null);
|
||||
const screenRef = useRef(props.screen);
|
||||
const foldAngleRef = useRef(props.foldAngle);
|
||||
const profileRef = useRef(props.profile);
|
||||
const modelRef = useRef(props.model);
|
||||
const accessoryRef = useRef(props.accessory);
|
||||
const { source, onFrameListener, client, onInputCancel, onResetReady, onUnavailable } = props;
|
||||
|
||||
useEffect(() => {
|
||||
foldAngleRef.current = props.foldAngle;
|
||||
viewerRef.current?.setFoldAngle(props.foldAngle);
|
||||
}, [props.foldAngle]);
|
||||
|
||||
useEffect(() => {
|
||||
screenRef.current = props.screen;
|
||||
profileRef.current = props.profile;
|
||||
@@ -76,6 +83,7 @@ export function DevicePhoneViewport(props: {
|
||||
profile: profileRef.current,
|
||||
model: modelRef.current,
|
||||
accessory: accessoryRef.current,
|
||||
foldAngle: foldAngleRef.current,
|
||||
});
|
||||
viewerRef.current = viewer;
|
||||
onResetReady(viewer.resetPose);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { deviceKeyboard, deviceModel } from "./deviceModels";
|
||||
import { fitDeviceFrame } from "./deviceFrameLayout";
|
||||
import { DeviceDuoViewport } from "./DeviceDuoViewport";
|
||||
import { DeviceDuoControls } from "./DeviceDuoControls";
|
||||
import { DeviceAndroidFoldControls } from "./DeviceAndroidFoldControls";
|
||||
import type { DuoControlState } from "@t3tools/client-runtime/device/duo-control";
|
||||
import { DevicePhoneViewport } from "./DevicePhoneViewport";
|
||||
import { DeviceLoadingView } from "./DeviceLoadingView";
|
||||
@@ -94,7 +95,9 @@ export function DeviceStreamView(props: {
|
||||
const clientRef = useRef<DeviceStreamClient | null>(null);
|
||||
const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
|
||||
const [detail, setDetail] = useState<string | undefined>(undefined);
|
||||
const [showRestartNotice, setShowRestartNotice] = useState(false);
|
||||
const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
|
||||
const [foldAngle, setFoldAngle] = useState<number | null>(null);
|
||||
const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);
|
||||
const [mjpegGeneration, setMjpegGeneration] = useState(0);
|
||||
const attachMjpegImage = useCallback((image: HTMLImageElement | null) => {
|
||||
@@ -121,6 +124,7 @@ export function DeviceStreamView(props: {
|
||||
onStatus: (next, nextDetail) => {
|
||||
setStatus(next);
|
||||
setDetail(nextDetail);
|
||||
if (next !== "connecting") setShowRestartNotice(false);
|
||||
},
|
||||
onScreen: (next) => {
|
||||
setScreen(next);
|
||||
@@ -136,6 +140,7 @@ export function DeviceStreamView(props: {
|
||||
},
|
||||
onInputConnected: (connected, detail) => {
|
||||
setInputState({ connected, ...(detail ? { detail } : {}) });
|
||||
if (!connected) setShowRestartNotice(false);
|
||||
onHandle?.({
|
||||
pressButton: client.pressButton,
|
||||
rotate: client.rotate,
|
||||
@@ -183,15 +188,27 @@ export function DeviceStreamView(props: {
|
||||
return w / h;
|
||||
}, [props.platform, screen]);
|
||||
|
||||
// Android restarts its encoder when a fold changes the framebuffer size.
|
||||
// Keep the last decoded frame and viewer mounted while the next keyframe arrives.
|
||||
const retainingAndroidFrame =
|
||||
props.platform === "android" &&
|
||||
status === "connecting" &&
|
||||
inputState.connected &&
|
||||
screen !== null;
|
||||
const showPhone =
|
||||
props.allowPhoneView &&
|
||||
status === "streaming" &&
|
||||
(status === "streaming" || retainingAndroidFrame) &&
|
||||
props.visible &&
|
||||
presentation === "phone" &&
|
||||
!phoneUnavailable &&
|
||||
!mjpegUrl &&
|
||||
!props.axOverlay &&
|
||||
(!isDuo || screen?.supportsHingeAngle === true);
|
||||
useEffect(() => {
|
||||
if (!retainingAndroidFrame || !showPhone) return;
|
||||
const timeout = window.setTimeout(() => setShowRestartNotice(true), 2_000);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [retainingAndroidFrame, showPhone]);
|
||||
const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
|
||||
|
||||
// The frame is the largest box at `aspect` that fits the container, so a
|
||||
@@ -330,7 +347,18 @@ export function DeviceStreamView(props: {
|
||||
streaming: status === "streaming",
|
||||
phoneUnavailableReason,
|
||||
foldingControls:
|
||||
showPhone && isDuo && screen?.supportsHingeAngle ? (
|
||||
props.platform === "android" && access ? (
|
||||
<DeviceAndroidFoldControls
|
||||
key={`${props.hostId}:${props.deviceId}`}
|
||||
access={access}
|
||||
deviceId={props.deviceId}
|
||||
visible={props.visible}
|
||||
enabled={status === "streaming"}
|
||||
screenWidth={screen?.width}
|
||||
screenHeight={screen?.height}
|
||||
onFoldAngle={setFoldAngle}
|
||||
/>
|
||||
) : showPhone && isDuo && screen?.supportsHingeAngle ? (
|
||||
<DeviceDuoControls
|
||||
screen={screen}
|
||||
state={duoControl}
|
||||
@@ -471,6 +499,7 @@ export function DeviceStreamView(props: {
|
||||
onInputCancel={onInputCancel}
|
||||
onResetReady={onResetReady}
|
||||
screen={screen}
|
||||
foldAngle={foldAngle}
|
||||
onUnavailable={onPhoneUnavailable}
|
||||
/>
|
||||
) : null}
|
||||
@@ -503,7 +532,14 @@ export function DeviceStreamView(props: {
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{status !== "streaming" ? (
|
||||
{retainingAndroidFrame && showPhone && showRestartNotice ? (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
|
||||
<span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
|
||||
Waiting for device video…
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{status !== "streaming" && !(retainingAndroidFrame && showPhone) ? (
|
||||
<div className="absolute inset-0">
|
||||
<DeviceLoadingView
|
||||
name={props.deviceName ?? "Device"}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
|
||||
import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
|
||||
|
||||
export type AndroidFoldPosture = "closed" | "opened";
|
||||
|
||||
export interface AndroidFoldState {
|
||||
readonly supported: boolean;
|
||||
readonly posture: "closed" | "half_opened" | "opened" | "flipped" | "tent" | null;
|
||||
readonly hingeAngle: number | null;
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const parseFold = (payload: unknown): AndroidFoldState => {
|
||||
if (!isRecord(payload) || payload.ok !== true || !isRecord(payload.fold)) {
|
||||
throw new Error("Unexpected Android fold response.");
|
||||
}
|
||||
const { supported, posture, hingeAngle } = payload.fold;
|
||||
if (
|
||||
typeof supported !== "boolean" ||
|
||||
(posture !== null &&
|
||||
posture !== "closed" &&
|
||||
posture !== "half_opened" &&
|
||||
posture !== "opened" &&
|
||||
posture !== "flipped" &&
|
||||
posture !== "tent") ||
|
||||
(hingeAngle !== null && (typeof hingeAngle !== "number" || !Number.isFinite(hingeAngle)))
|
||||
) {
|
||||
throw new Error("Unexpected Android fold response.");
|
||||
}
|
||||
return { supported, posture, hingeAngle };
|
||||
};
|
||||
|
||||
const foldRequest = async (
|
||||
access: DeviceHubAccess,
|
||||
deviceId: string,
|
||||
posture?: AndroidFoldPosture,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AndroidFoldState> => {
|
||||
const url = withDeviceHubQuery(
|
||||
`${access.httpBase}/vendor/serve-emu/api/fold?${new URLSearchParams({ device: deviceId })}`,
|
||||
access,
|
||||
);
|
||||
const response = await fetch(url, {
|
||||
method: posture ? "POST" : "GET",
|
||||
cache: "no-store",
|
||||
credentials: access.credentials ? "include" : "same-origin",
|
||||
...(posture
|
||||
? { headers: { "content-type": "application/json" }, body: JSON.stringify({ posture }) }
|
||||
: {}),
|
||||
...(signal ? { signal } : {}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload: unknown = await response.json().catch(() => null);
|
||||
const error = isRecord(payload) ? payload.error : null;
|
||||
throw new Error(
|
||||
typeof error === "string" ? error : `Fold command failed (${response.status}).`,
|
||||
);
|
||||
}
|
||||
return parseFold(await response.json());
|
||||
};
|
||||
|
||||
export const readAndroidFold = (access: DeviceHubAccess, deviceId: string, signal?: AbortSignal) =>
|
||||
foldRequest(access, deviceId, undefined, signal);
|
||||
|
||||
export const setAndroidFold = (
|
||||
access: DeviceHubAccess,
|
||||
deviceId: string,
|
||||
posture: AndroidFoldPosture,
|
||||
signal?: AbortSignal,
|
||||
) => foldRequest(access, deviceId, posture, signal);
|
||||
@@ -44,6 +44,8 @@ interactive. On iPhone Duo, use the fold and stance controls to change its
|
||||
physical pose, or pinch over the device to adjust the hinge. Turning the model
|
||||
to the other screen switches the live display and touch input to that screen.
|
||||
**Restore 3D view** returns the device to a screen-facing position.
|
||||
On supported Android foldables, use **Fold device** and **Unfold device** beside
|
||||
the screen to change its posture in either view.
|
||||
|
||||
## Tools
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Box3, Mesh, PerspectiveCamera, Texture, Vector3 } from "three";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { createAndroidFoldScene } from "./androidFoldScene.ts";
|
||||
import { phoneDisplayLayout } from "./phoneScene.ts";
|
||||
|
||||
describe("Android fold scene", () => {
|
||||
it("moves one physical half around the hinge while preserving both screen halves", () => {
|
||||
const texture = new Texture();
|
||||
const scene = createAndroidFoldScene(
|
||||
texture,
|
||||
phoneDisplayLayout({ width: 2200, height: 1840, orientation: "landscape_left" }, 2200, 1840),
|
||||
180,
|
||||
);
|
||||
const moving = scene.orientation.children[0]!;
|
||||
const fixed = scene.orientation.children[1]!;
|
||||
const openWidth = new Box3().setFromObject(scene.root).getSize(new Vector3()).x;
|
||||
const leftScreen = scene.root.getObjectByName("left-inner-screen") as Mesh;
|
||||
const rightScreen = scene.root.getObjectByName("right-inner-screen") as Mesh;
|
||||
leftScreen.geometry.computeBoundingBox();
|
||||
rightScreen.geometry.computeBoundingBox();
|
||||
const creaseWidth =
|
||||
rightScreen.geometry.boundingBox!.min.x - leftScreen.geometry.boundingBox!.max.x;
|
||||
expect(creaseWidth).toBeLessThan(0.01);
|
||||
const continuousScreen = scene.root.getObjectByName("continuous-inner-screen") as Mesh;
|
||||
const positions = continuousScreen.geometry.getAttribute("position");
|
||||
expect(continuousScreen.geometry.index).not.toBeNull();
|
||||
expect(Array.from({ length: positions.count }, (_, i) => positions.getX(i))).toContain(0);
|
||||
scene.setAngle(90);
|
||||
expect(moving.rotation.y).toBeCloseTo(Math.PI / 2);
|
||||
expect(fixed.rotation.y).toBe(0);
|
||||
scene.setAngle(0);
|
||||
const closedWidth = new Box3().setFromObject(scene.root).getSize(new Vector3()).x;
|
||||
expect(closedWidth).toBeLessThan(openWidth * 0.7);
|
||||
expect(scene.root.getObjectByName("cover-screen")?.visible).toBe(true);
|
||||
scene.dispose();
|
||||
texture.dispose();
|
||||
});
|
||||
|
||||
it("maps touches on each open half and the closed cover to the live frame", () => {
|
||||
const texture = new Texture();
|
||||
const scene = createAndroidFoldScene(texture, phoneDisplayLayout(null, 2200, 1840), 180);
|
||||
const camera = new PerspectiveCamera(32, 1, 0.1, 30);
|
||||
camera.position.z = 6;
|
||||
camera.updateMatrixWorld(true);
|
||||
const project = (x: number) => {
|
||||
const point = new Vector3(x, 0, 0.041).project(camera);
|
||||
return scene.screenPoint((point.x + 1) / 2, (1 - point.y) / 2, camera);
|
||||
};
|
||||
expect(project(-0.52)?.x).toBeCloseTo(0.25, 1);
|
||||
expect(project(0.52)?.x).toBeCloseTo(0.75, 1);
|
||||
expect(scene.screenPoint(0.99, 0.5, camera, true)?.x).toBe(1);
|
||||
scene.setAngle(0);
|
||||
expect(project(0.52)?.x).toBeCloseTo(0.5, 1);
|
||||
scene.dispose();
|
||||
texture.dispose();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
BoxGeometry,
|
||||
CircleGeometry,
|
||||
CylinderGeometry,
|
||||
ExtrudeGeometry,
|
||||
Group,
|
||||
Mesh,
|
||||
MeshBasicMaterial,
|
||||
MeshPhysicalMaterial,
|
||||
MeshStandardMaterial,
|
||||
PlaneGeometry,
|
||||
Raycaster,
|
||||
Shape,
|
||||
ShapeGeometry,
|
||||
Vector2,
|
||||
Vector3,
|
||||
type Camera,
|
||||
type Texture,
|
||||
} from "three";
|
||||
import type { PhoneDisplayLayout } from "./phoneScene.ts";
|
||||
|
||||
const HALF_WIDTH = 1.04;
|
||||
const HEIGHT = 2.2;
|
||||
const DEPTH = 0.075;
|
||||
const INSET = 0.026;
|
||||
const CREASE = 0.004;
|
||||
const BEVEL = 0.008;
|
||||
// The hinge axis sits just above the inner screens so closed halves meet face to face.
|
||||
const PIVOT_Z = DEPTH / 2 + 0.005;
|
||||
const SPINE_RADIUS = PIVOT_Z + DEPTH / 2 - 0.002;
|
||||
|
||||
function panelPath(side: "left" | "right", inset: number, radius: number, hingeInset = 0) {
|
||||
const left = side === "left" ? -HALF_WIDTH + inset : CREASE / 2 + hingeInset;
|
||||
const right = side === "left" ? -CREASE / 2 - hingeInset : HALF_WIDTH - inset;
|
||||
const bottom = -HEIGHT / 2 + inset;
|
||||
const top = HEIGHT / 2 - inset;
|
||||
const path = new Shape();
|
||||
if (side === "left") {
|
||||
path.moveTo(left + radius, bottom);
|
||||
path.lineTo(right, bottom);
|
||||
path.lineTo(right, top);
|
||||
path.lineTo(left + radius, top);
|
||||
path.quadraticCurveTo(left, top, left, top - radius);
|
||||
path.lineTo(left, bottom + radius);
|
||||
path.quadraticCurveTo(left, bottom, left + radius, bottom);
|
||||
} else {
|
||||
path.moveTo(left, bottom);
|
||||
path.lineTo(right - radius, bottom);
|
||||
path.quadraticCurveTo(right, bottom, right, bottom + radius);
|
||||
path.lineTo(right, top - radius);
|
||||
path.quadraticCurveTo(right, top, right - radius, top);
|
||||
path.lineTo(left, top);
|
||||
}
|
||||
path.closePath();
|
||||
return path;
|
||||
}
|
||||
|
||||
function roundedRectPath(width: number, height: number, radius: number) {
|
||||
const path = new Shape();
|
||||
path.moveTo(-width / 2 + radius, -height / 2);
|
||||
path.lineTo(width / 2 - radius, -height / 2);
|
||||
path.quadraticCurveTo(width / 2, -height / 2, width / 2, -height / 2 + radius);
|
||||
path.lineTo(width / 2, height / 2 - radius);
|
||||
path.quadraticCurveTo(width / 2, height / 2, width / 2 - radius, height / 2);
|
||||
path.lineTo(-width / 2 + radius, height / 2);
|
||||
path.quadraticCurveTo(-width / 2, height / 2, -width / 2, height / 2 - radius);
|
||||
path.lineTo(-width / 2, -height / 2 + radius);
|
||||
path.quadraticCurveTo(-width / 2, -height / 2, -width / 2 + radius, -height / 2);
|
||||
path.closePath();
|
||||
return path;
|
||||
}
|
||||
|
||||
function coverPath() {
|
||||
return roundedRectPath(HALF_WIDTH - INSET * 2 - 0.02, HEIGHT - INSET * 2 - 0.04, 0.07);
|
||||
}
|
||||
|
||||
/** A procedural book-style foldable: one fixed half, one half rotating around a shared hinge. */
|
||||
export function createAndroidFoldScene(
|
||||
texture: Texture,
|
||||
layout: PhoneDisplayLayout,
|
||||
initialAngle: number,
|
||||
) {
|
||||
const root = new Group();
|
||||
const orientation = new Group();
|
||||
root.add(orientation);
|
||||
const left = new Group();
|
||||
const right = new Group();
|
||||
orientation.add(left, right);
|
||||
const frameMetal = new MeshStandardMaterial({
|
||||
color: 0xa3abb2,
|
||||
metalness: 0.9,
|
||||
roughness: 0.28,
|
||||
});
|
||||
const polishedMetal = new MeshStandardMaterial({
|
||||
color: 0xc4cad0,
|
||||
metalness: 0.95,
|
||||
roughness: 0.16,
|
||||
});
|
||||
const bezel = new MeshPhysicalMaterial({
|
||||
color: 0x0b0d10,
|
||||
metalness: 0.1,
|
||||
roughness: 0.2,
|
||||
clearcoat: 1,
|
||||
});
|
||||
const backGlass = new MeshPhysicalMaterial({
|
||||
color: 0x2c3237,
|
||||
metalness: 0.35,
|
||||
roughness: 0.52,
|
||||
clearcoat: 0.4,
|
||||
clearcoatRoughness: 0.6,
|
||||
});
|
||||
const island = new MeshPhysicalMaterial({
|
||||
color: 0x1a1e22,
|
||||
metalness: 0.55,
|
||||
roughness: 0.3,
|
||||
clearcoat: 1,
|
||||
});
|
||||
const lensMaterial = new MeshPhysicalMaterial({
|
||||
color: 0x061022,
|
||||
metalness: 0.6,
|
||||
roughness: 0.1,
|
||||
clearcoat: 1,
|
||||
});
|
||||
const flashMaterial = new MeshBasicMaterial({ color: 0xf2ead6 });
|
||||
const displayMaterial = new MeshBasicMaterial({ map: texture, toneMapped: false });
|
||||
const hitMaterial = new MeshBasicMaterial({ colorWrite: false, depthWrite: false });
|
||||
const coverMaterial = new MeshBasicMaterial({ map: texture, toneMapped: false });
|
||||
const materials = [
|
||||
frameMetal,
|
||||
polishedMetal,
|
||||
bezel,
|
||||
backGlass,
|
||||
island,
|
||||
lensMaterial,
|
||||
flashMaterial,
|
||||
displayMaterial,
|
||||
hitMaterial,
|
||||
coverMaterial,
|
||||
];
|
||||
|
||||
// Each half's meshes live in body coordinates; `left` pivots them around the hinge axis.
|
||||
left.position.z = PIVOT_Z;
|
||||
const leftBody = new Group();
|
||||
leftBody.position.z = -PIVOT_Z;
|
||||
left.add(leftBody);
|
||||
|
||||
function half(group: Group, side: "left" | "right", back: MeshPhysicalMaterial) {
|
||||
const body = new Mesh(
|
||||
new ExtrudeGeometry(panelPath(side, BEVEL, 0.1, BEVEL), {
|
||||
depth: DEPTH - BEVEL * 2,
|
||||
bevelEnabled: true,
|
||||
bevelSize: BEVEL,
|
||||
bevelThickness: BEVEL,
|
||||
bevelSegments: 3,
|
||||
curveSegments: 12,
|
||||
}),
|
||||
frameMetal,
|
||||
);
|
||||
body.position.z = -DEPTH / 2 + BEVEL;
|
||||
group.add(body);
|
||||
const frame = new Mesh(new ShapeGeometry(panelPath(side, 0.01, 0.095, 0.002), 12), bezel);
|
||||
frame.position.z = DEPTH / 2 + 0.001;
|
||||
group.add(frame);
|
||||
// A back-facing shape mirrors X, so it is drawn from the opposite side's outline.
|
||||
const rear = new Mesh(
|
||||
new ShapeGeometry(panelPath(side === "left" ? "right" : "left", 0.01, 0.095, 0.002), 12),
|
||||
back,
|
||||
);
|
||||
rear.name = `${side}-back`;
|
||||
rear.rotation.y = Math.PI;
|
||||
rear.position.set(0, 0, -DEPTH / 2 - 0.001);
|
||||
group.add(rear);
|
||||
const geometry = new ShapeGeometry(panelPath(side, INSET, 0.076));
|
||||
geometry.computeBoundingBox();
|
||||
const display = new Mesh(geometry, hitMaterial);
|
||||
display.name = `${side}-inner-screen`;
|
||||
display.position.z = DEPTH / 2 + 0.003;
|
||||
group.add(display);
|
||||
return display;
|
||||
}
|
||||
|
||||
const innerLeft = half(leftBody, "left", bezel);
|
||||
const innerRight = half(right, "right", backGlass);
|
||||
// One indexed surface keeps adjacent pixels joined at the crease. The
|
||||
// physical halves move separately underneath it.
|
||||
const screenWidth = 2 * (HALF_WIDTH - INSET);
|
||||
const screenHeight = HEIGHT - 2 * INSET;
|
||||
const screenGeometry = new PlaneGeometry(screenWidth, screenHeight, 40, 48);
|
||||
const screenPositions = screenGeometry.getAttribute("position");
|
||||
const screenUvs = screenGeometry.getAttribute("uv");
|
||||
const baseX = new Float32Array(screenPositions.count);
|
||||
for (let i = 0; i < screenPositions.count; i++) {
|
||||
const y = screenPositions.getY(i);
|
||||
const outerX = screenWidth / 2;
|
||||
const outerY = screenHeight / 2;
|
||||
const radius = 0.076;
|
||||
const cornerY = Math.max(0, Math.abs(y) - (outerY - radius));
|
||||
const limit = outerX - radius + Math.sqrt(Math.max(0, radius * radius - cornerY * cornerY));
|
||||
const x = Math.max(-limit, Math.min(limit, screenPositions.getX(i)));
|
||||
baseX[i] = x;
|
||||
screenUvs.setXY(i, x / screenWidth + 0.5, y / screenHeight + 0.5);
|
||||
}
|
||||
screenUvs.needsUpdate = true;
|
||||
const innerSurface = new Mesh(screenGeometry, displayMaterial);
|
||||
innerSurface.name = "continuous-inner-screen";
|
||||
orientation.add(innerSurface);
|
||||
// The outer half of the hinge housing. It tucks behind the back glass when
|
||||
// open and becomes the rounded spine when closed.
|
||||
const spineSlack = 0.15;
|
||||
const spine = new Mesh(
|
||||
new CylinderGeometry(
|
||||
SPINE_RADIUS,
|
||||
SPINE_RADIUS,
|
||||
HEIGHT - 0.012,
|
||||
32,
|
||||
1,
|
||||
false,
|
||||
Math.PI / 2 + spineSlack,
|
||||
Math.PI - spineSlack * 2,
|
||||
),
|
||||
polishedMetal,
|
||||
);
|
||||
spine.name = "hinge-spine";
|
||||
spine.position.z = PIVOT_Z;
|
||||
orientation.add(spine);
|
||||
|
||||
const cover = new Mesh(new ShapeGeometry(coverPath()), coverMaterial);
|
||||
cover.name = "cover-screen";
|
||||
cover.position.set(-HALF_WIDTH / 2, 0, -DEPTH / 2 - 0.003);
|
||||
cover.rotation.y = Math.PI;
|
||||
leftBody.add(cover);
|
||||
|
||||
// Rear components use back-surface coordinates, with outward positive Z.
|
||||
const rearCamera = new Group();
|
||||
rearCamera.name = "rear-camera";
|
||||
const islandWidth = 0.46;
|
||||
const islandHeight = 0.2;
|
||||
rearCamera.position.set(
|
||||
HALF_WIDTH - 0.07 - islandWidth / 2,
|
||||
HEIGHT / 2 - 0.08 - islandHeight / 2,
|
||||
-DEPTH / 2 - 0.002,
|
||||
);
|
||||
rearCamera.rotation.y = Math.PI;
|
||||
right.add(rearCamera);
|
||||
const plateDepth = 0.02;
|
||||
const plate = new Mesh(
|
||||
new ExtrudeGeometry(roundedRectPath(islandWidth, islandHeight, 0.07), {
|
||||
depth: plateDepth,
|
||||
bevelEnabled: true,
|
||||
bevelSize: 0.008,
|
||||
bevelThickness: 0.006,
|
||||
bevelSegments: 3,
|
||||
curveSegments: 12,
|
||||
}),
|
||||
island,
|
||||
);
|
||||
plate.name = "camera-plate";
|
||||
rearCamera.add(plate);
|
||||
const plateFront = plateDepth + 0.006;
|
||||
for (const [x, radius] of [
|
||||
[-0.14, 0.05],
|
||||
[-0.01, 0.05],
|
||||
[0.105, 0.036],
|
||||
] as const) {
|
||||
const ring = new Mesh(
|
||||
new CylinderGeometry(radius + 0.012, radius + 0.012, 0.012, 32),
|
||||
frameMetal,
|
||||
);
|
||||
ring.rotation.x = Math.PI / 2;
|
||||
ring.position.set(x, 0, plateFront + 0.004);
|
||||
rearCamera.add(ring);
|
||||
const lens = new Mesh(new CircleGeometry(radius, 32), lensMaterial);
|
||||
lens.name = "camera-lens";
|
||||
lens.position.set(x, 0, plateFront + 0.0105);
|
||||
rearCamera.add(lens);
|
||||
}
|
||||
const flash = new Mesh(new CircleGeometry(0.018, 20), flashMaterial);
|
||||
flash.position.set(0.185, 0.045, plateFront + 0.0005);
|
||||
rearCamera.add(flash);
|
||||
|
||||
// Power and volume keys sit on the fixed half's outer edge.
|
||||
for (const [y, length] of [
|
||||
[0.52, 0.16],
|
||||
[0.2, 0.3],
|
||||
] as const) {
|
||||
const key = new Mesh(new BoxGeometry(0.02, length, DEPTH * 0.45), frameMetal);
|
||||
key.position.set(HALF_WIDTH + 0.008, y, 0);
|
||||
right.add(key);
|
||||
}
|
||||
|
||||
const raycaster = new Raycaster();
|
||||
const pointer = new Vector2();
|
||||
const local = new Vector3();
|
||||
let capturedDisplay: Mesh | null = null;
|
||||
let activeLayout = layout;
|
||||
let angle = initialAngle;
|
||||
const updateVisibleScreen = () => {
|
||||
const innerActive = angle >= 90;
|
||||
innerSurface.visible = innerActive;
|
||||
innerLeft.visible = innerActive;
|
||||
innerRight.visible = innerActive;
|
||||
cover.visible = !innerActive;
|
||||
};
|
||||
const setAngle = (next: number) => {
|
||||
angle = Math.max(0, Math.min(180, next));
|
||||
left.rotation.y = Math.PI * (1 - angle / 180);
|
||||
spine.rotation.y = left.rotation.y / 2;
|
||||
const radians = left.rotation.y;
|
||||
const cosine = Math.cos(radians);
|
||||
const sine = Math.sin(radians);
|
||||
const frontZ = DEPTH / 2 + 0.004 - PIVOT_Z;
|
||||
for (let i = 0; i < screenPositions.count; i++) {
|
||||
const x = baseX[i]!;
|
||||
if (x < 0) {
|
||||
screenPositions.setXYZ(
|
||||
i,
|
||||
x * cosine + frontZ * sine,
|
||||
screenPositions.getY(i),
|
||||
-x * sine + frontZ * cosine + PIVOT_Z,
|
||||
);
|
||||
} else {
|
||||
screenPositions.setXYZ(i, x, screenPositions.getY(i), frontZ + PIVOT_Z);
|
||||
}
|
||||
}
|
||||
screenPositions.needsUpdate = true;
|
||||
screenGeometry.computeBoundingBox();
|
||||
screenGeometry.computeBoundingSphere();
|
||||
updateVisibleScreen();
|
||||
};
|
||||
const setDisplay = (nextTexture: Texture, nextLayout: PhoneDisplayLayout) => {
|
||||
activeLayout = nextLayout;
|
||||
displayMaterial.map = nextTexture;
|
||||
coverMaterial.map = nextTexture;
|
||||
cover.geometry.computeBoundingBox();
|
||||
const bounds = cover.geometry.boundingBox!;
|
||||
const uv = cover.geometry.getAttribute("uv");
|
||||
const position = cover.geometry.getAttribute("position");
|
||||
for (let i = 0; i < uv.count; i++) {
|
||||
const u = (position.getX(i) - bounds.min.x) / (bounds.max.x - bounds.min.x);
|
||||
const v = (position.getY(i) - bounds.min.y) / (bounds.max.y - bounds.min.y);
|
||||
uv.setXY(i, u, v);
|
||||
}
|
||||
uv.needsUpdate = true;
|
||||
updateVisibleScreen();
|
||||
};
|
||||
setAngle(initialAngle);
|
||||
setDisplay(texture, layout);
|
||||
|
||||
return {
|
||||
root,
|
||||
orientation,
|
||||
width: HALF_WIDTH * 2,
|
||||
height: HEIGHT,
|
||||
setAngle,
|
||||
setDisplay,
|
||||
screenPoint(x: number, y: number, camera: Camera, captured = false) {
|
||||
orientation.updateWorldMatrix(true, true);
|
||||
camera.updateMatrixWorld(true);
|
||||
pointer.set(x * 2 - 1, 1 - y * 2);
|
||||
raycaster.setFromCamera(pointer, camera);
|
||||
const screens = cover.visible ? [cover] : [innerLeft, innerRight];
|
||||
const hit = raycaster.intersectObjects(screens, false)[0];
|
||||
if (!hit && !captured) {
|
||||
capturedDisplay = null;
|
||||
return null;
|
||||
}
|
||||
const display =
|
||||
(hit?.object as Mesh | undefined) ??
|
||||
(capturedDisplay?.visible ? capturedDisplay : screens[0]);
|
||||
if (!display) return null;
|
||||
if (hit) capturedDisplay = display;
|
||||
if (hit) local.copy(hit.point);
|
||||
else {
|
||||
const plane = new Vector3(0, 0, 1).transformDirection(display.matrixWorld);
|
||||
const point = new Vector3().setFromMatrixPosition(display.matrixWorld);
|
||||
const distance =
|
||||
plane.dot(point.clone().sub(raycaster.ray.origin)) / plane.dot(raycaster.ray.direction);
|
||||
if (!Number.isFinite(distance)) return null;
|
||||
local.copy(raycaster.ray.direction).multiplyScalar(distance).add(raycaster.ray.origin);
|
||||
}
|
||||
display.worldToLocal(local);
|
||||
const bounds = display.geometry.boundingBox!;
|
||||
const u = Math.max(0, Math.min(1, (local.x - bounds.min.x) / (bounds.max.x - bounds.min.x)));
|
||||
const v = Math.max(0, Math.min(1, (bounds.max.y - local.y) / (bounds.max.y - bounds.min.y)));
|
||||
const across = display === cover ? u : (display === innerLeft ? u : 1 + u) / 2;
|
||||
return activeLayout.rotation === Math.PI ? { x: 1 - across, y: 1 - v } : { x: across, y: v };
|
||||
},
|
||||
dispose() {
|
||||
root.traverse((object) => {
|
||||
if (object instanceof Mesh) object.geometry.dispose();
|
||||
});
|
||||
for (const material of materials) material.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,6 +11,7 @@ const gpu = vi.hoisted(() => ({
|
||||
scene: Scene;
|
||||
phone: Object3D | undefined;
|
||||
rotation: Quaternion | undefined;
|
||||
displayAngle: number | undefined;
|
||||
yaw: number | undefined;
|
||||
cameraZ: number;
|
||||
}[];
|
||||
@@ -50,6 +51,7 @@ vi.mock("three", async () => {
|
||||
scene,
|
||||
phone,
|
||||
rotation: phone?.quaternion.clone(),
|
||||
displayAngle: phone?.children[0]?.rotation.z,
|
||||
yaw: phone?.rotation.y,
|
||||
cameraZ: camera.position.z,
|
||||
});
|
||||
@@ -81,7 +83,12 @@ vi.mock("./modelScene.ts", async () => {
|
||||
import { BoxGeometry, Group, Mesh, MeshBasicMaterial, PlaneGeometry, Quaternion } from "three";
|
||||
import { disposeDeviceModel } from "./modelScene.ts";
|
||||
import { createPhoneViewer } from "./phoneViewer.ts";
|
||||
import { IOS_TABLET_SHAPE } from "./shapeProfile.ts";
|
||||
import {
|
||||
ANDROID_PHONE_SHAPE,
|
||||
IOS_TABLET_SHAPE,
|
||||
resolveDeviceShape,
|
||||
type DeviceShapeProfile,
|
||||
} from "./shapeProfile.ts";
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
@@ -90,7 +97,7 @@ afterEach(() => {
|
||||
models.pending.length = 0;
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
function fixture(profile?: DeviceShapeProfile) {
|
||||
const pending = new Map<number, FrameRequestCallback>();
|
||||
let id = 0;
|
||||
let now = 0;
|
||||
@@ -104,7 +111,13 @@ function fixture() {
|
||||
const source = { width: 1206, height: 2622 } as HTMLCanvasElement;
|
||||
const onUnavailable = vi.fn();
|
||||
const onFramingAspect = vi.fn();
|
||||
const viewer = createPhoneViewer({ canvas, source, onUnavailable, onFramingAspect });
|
||||
const viewer = createPhoneViewer({
|
||||
canvas,
|
||||
source,
|
||||
onUnavailable,
|
||||
onFramingAspect,
|
||||
...(profile ? { profile } : {}),
|
||||
});
|
||||
const draw = (time = now) => {
|
||||
now = time;
|
||||
const callbacks = [...pending.values()];
|
||||
@@ -194,6 +207,117 @@ it("changes device shape without replacing the renderer, decoded source or pose"
|
||||
viewer.dispose();
|
||||
});
|
||||
|
||||
it("keeps the Android viewer while the resized framebuffer turns between fold postures", () => {
|
||||
const openProfile = resolveDeviceShape({ platform: "android", portraitAspect: 0.96 });
|
||||
const { viewer, draw, source, state } = fixture(openProfile);
|
||||
const scene = state.frames.at(-1)!.scene;
|
||||
source.width = 2076;
|
||||
source.height = 2152;
|
||||
viewer.setScreen({ width: 2076, height: 2152, orientation: "landscape_left" });
|
||||
viewer.frameUpdated();
|
||||
draw(0);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(0);
|
||||
draw(225);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(-Math.PI / 4);
|
||||
draw(450);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(-Math.PI / 2);
|
||||
expect(state.frames.at(-1)!.scene).toBe(scene);
|
||||
expect(gpu.instances).toHaveLength(1);
|
||||
|
||||
source.width = 1080;
|
||||
source.height = 2424;
|
||||
viewer.setScreen({ width: 1080, height: 2424, orientation: "portrait" }, ANDROID_PHONE_SHAPE);
|
||||
viewer.frameUpdated();
|
||||
draw(450);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(-Math.PI / 2);
|
||||
draw(675);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(-Math.PI / 4);
|
||||
draw(900);
|
||||
expect(state.frames.at(-1)!.displayAngle).toBeCloseTo(0);
|
||||
expect(state.frames.at(-1)!.scene).toBe(scene);
|
||||
viewer.dispose();
|
||||
});
|
||||
|
||||
it("animates the Android hinge on the same scene through an encoder resize", () => {
|
||||
const openProfile = resolveDeviceShape({ platform: "android", portraitAspect: 0.96 });
|
||||
const { viewer, draw, source, state } = fixture(openProfile);
|
||||
viewer.setFoldAngle(180);
|
||||
draw(0);
|
||||
const shell = state.frames.at(-1)!.phone!;
|
||||
const moving = shell.children[0]!.children[0]!;
|
||||
viewer.setFoldAngle(0);
|
||||
draw(425);
|
||||
expect(moving.rotation.y).toBeCloseTo(Math.PI / 2);
|
||||
source.width = 1080;
|
||||
source.height = 2424;
|
||||
viewer.setScreen({ width: 1080, height: 2424, orientation: "portrait" }, ANDROID_PHONE_SHAPE);
|
||||
viewer.frameUpdated();
|
||||
draw(850);
|
||||
expect(moving.rotation.y).toBeCloseTo(Math.PI);
|
||||
expect(state.frames.at(-1)!.phone).toBe(shell);
|
||||
expect(gpu.instances).toHaveLength(1);
|
||||
viewer.dispose();
|
||||
});
|
||||
|
||||
it("retargets an unfinished hinge turn from its visible angle", () => {
|
||||
const { viewer, draw, state } = fixture(ANDROID_PHONE_SHAPE);
|
||||
viewer.setFoldAngle(180);
|
||||
draw(0);
|
||||
const moving = state.frames.at(-1)!.phone!.children[0]!.children[0]!;
|
||||
viewer.setFoldAngle(0);
|
||||
draw(200);
|
||||
const visibleAngle = moving.rotation.y;
|
||||
viewer.setFoldAngle(180);
|
||||
draw(200);
|
||||
expect(moving.rotation.y).toBeCloseTo(visibleAngle);
|
||||
draw(1050);
|
||||
expect(moving.rotation.y).toBeCloseTo(0);
|
||||
viewer.dispose();
|
||||
});
|
||||
|
||||
it("stops a hinge turn when a loaded model replaces the fold scene", async () => {
|
||||
const { viewer, draw, pending } = fixture(ANDROID_PHONE_SHAPE);
|
||||
viewer.setFoldAngle(180);
|
||||
draw(0);
|
||||
viewer.setFoldAngle(0);
|
||||
viewer.setModel({ id: "iphone-18-pro", url: "/fold.glb" });
|
||||
const asset = new Group();
|
||||
const body = new Mesh(new BoxGeometry(1, 2, 0.1), new MeshBasicMaterial());
|
||||
const display = new Mesh(new PlaneGeometry(0.9, 1.9), new MeshBasicMaterial());
|
||||
display.name = "device-screen";
|
||||
asset.add(body, display);
|
||||
models.pending[0]!.resolve({ asset, dispose: () => disposeDeviceModel(asset) });
|
||||
await Promise.resolve();
|
||||
draw(200);
|
||||
draw(1050);
|
||||
expect(pending.size).toBe(0);
|
||||
viewer.dispose();
|
||||
});
|
||||
|
||||
it("keeps a loaded model when the fold angle changes and releases it once", async () => {
|
||||
const { viewer, draw, state } = fixture(ANDROID_PHONE_SHAPE);
|
||||
viewer.setModel({ id: "iphone-18-pro", url: "/pro.glb" });
|
||||
const asset = new Group();
|
||||
const body = new Mesh(new BoxGeometry(1.15, 2.3, 0.1), new MeshBasicMaterial());
|
||||
body.position.z = -0.02;
|
||||
const display = new Mesh(new PlaneGeometry(1, 2.2), new MeshBasicMaterial());
|
||||
display.geometry.translate(0, 0, 0.043);
|
||||
display.name = "device-screen";
|
||||
asset.add(body, display);
|
||||
const dispose = vi.fn(() => disposeDeviceModel(asset));
|
||||
models.pending[0]!.resolve({ asset, dispose });
|
||||
await Promise.resolve();
|
||||
draw();
|
||||
const loaded = state.frames.at(-1)!.phone;
|
||||
expect(loaded?.getObjectByName("device-screen")).toBe(display);
|
||||
viewer.setFoldAngle(180);
|
||||
viewer.setFoldAngle(0);
|
||||
draw();
|
||||
expect(state.frames.at(-1)!.phone).toBe(loaded);
|
||||
viewer.dispose();
|
||||
expect(dispose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("retains the loaded model and pose through rotation and framebuffer resolution changes, then releases it once", async () => {
|
||||
const { viewer, draw, source, state } = fixture();
|
||||
viewer.orbit(0.08, 0.04);
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from "./model.ts";
|
||||
import { createImportedPhoneScene, loadDeviceModel } from "./modelScene.ts";
|
||||
import { createPhoneScene, phoneDisplayLayout } from "./phoneScene.ts";
|
||||
import { createAndroidFoldScene } from "./androidFoldScene.ts";
|
||||
import { createRenderScheduler } from "./renderScheduler.ts";
|
||||
import { createDeviceMotion } from "./deviceMotion.ts";
|
||||
import { createDeviceFraming } from "./deviceFraming.ts";
|
||||
@@ -31,6 +32,7 @@ export interface PhoneViewer {
|
||||
readonly setAccessory: (source: DeviceAccessorySource | null) => void;
|
||||
readonly frameUpdated: () => void;
|
||||
readonly setScreen: (screen: DeviceScreenSize | null, profile?: DeviceShapeProfile) => void;
|
||||
readonly setFoldAngle: (angle: number | null) => void;
|
||||
readonly resize: (width: number, height: number, pixelRatio: number) => void;
|
||||
readonly screenPoint: (
|
||||
x: number,
|
||||
@@ -43,6 +45,9 @@ export interface PhoneViewer {
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
const ANDROID_ORIENTATION_TURN_MS = 450;
|
||||
const ANDROID_FOLD_TURN_MS = 850;
|
||||
|
||||
/** Owns only presentation resources. The caller retains the decoded canvas and the stream connection. */
|
||||
export function createPhoneViewer(options: {
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
@@ -53,6 +58,7 @@ export function createPhoneViewer(options: {
|
||||
readonly profile?: DeviceShapeProfile;
|
||||
readonly model?: DeviceModelSource | null;
|
||||
readonly accessory?: DeviceAccessorySource | null;
|
||||
readonly foldAngle?: number | null;
|
||||
}): PhoneViewer {
|
||||
const renderer = new WebGLRenderer({
|
||||
canvas: options.canvas,
|
||||
@@ -87,11 +93,19 @@ export function createPhoneViewer(options: {
|
||||
let screen: DeviceScreenSize | null = null;
|
||||
let layout = phoneDisplayLayout(screen, options.source.width, options.source.height);
|
||||
let profile = options.profile ?? IOS_PHONE_SHAPE;
|
||||
let foldAngle = options.foldAngle ?? null;
|
||||
let orientationAngle =
|
||||
foldAngle !== null && profile.id.startsWith("android") ? 0 : layout.rotation;
|
||||
let orientationTurn: { from: number; to: number; startedAt: number } | null = null;
|
||||
let imported: Awaited<ReturnType<typeof loadDeviceModel>> | null = null;
|
||||
let modelSource = options.model ?? null;
|
||||
let accessory: Awaited<ReturnType<typeof loadDeviceModel>> | null = null;
|
||||
let accessoryBounds: Box3 | null = null;
|
||||
let phone = createPhoneScene(texture, layout, profile);
|
||||
let foldTurn: { from: number; to: number; startedAt: number } | null = null;
|
||||
let phone: ReturnType<typeof createPhoneScene> | ReturnType<typeof createAndroidFoldScene> =
|
||||
foldAngle !== null && profile.id.startsWith("android")
|
||||
? createAndroidFoldScene(texture, layout, foldAngle)
|
||||
: createPhoneScene(texture, layout, profile);
|
||||
scene.add(phone.root);
|
||||
let disposed = false;
|
||||
const rest = new Quaternion();
|
||||
@@ -116,7 +130,7 @@ export function createPhoneViewer(options: {
|
||||
new Vector3(phone.width / 2, phone.height / 2, 0),
|
||||
);
|
||||
if (imported && accessoryBounds) bounds.union(accessoryBounds);
|
||||
bounds.applyMatrix4(new Matrix4().makeRotationZ(layout.rotation));
|
||||
bounds.applyMatrix4(new Matrix4().makeRotationZ(orientationAngle));
|
||||
const size = bounds.getSize(new Vector3());
|
||||
const aspect = size.x / size.y;
|
||||
if (aspect !== framingAspect) {
|
||||
@@ -140,7 +154,7 @@ export function createPhoneViewer(options: {
|
||||
};
|
||||
const applyPose = () => {
|
||||
phone.root.quaternion.copy(motion.rotation);
|
||||
phone.orientation.rotation.z = layout.rotation;
|
||||
phone.orientation.rotation.z = orientationAngle;
|
||||
};
|
||||
const scheduler = createRenderScheduler(() => {
|
||||
if (disposed || !viewport.width || !viewport.height) return;
|
||||
@@ -160,10 +174,30 @@ export function createPhoneViewer(options: {
|
||||
applyPose();
|
||||
fit(reducedMotion());
|
||||
}
|
||||
if (orientationTurn) {
|
||||
const progress = Math.min(
|
||||
1,
|
||||
(now - orientationTurn.startedAt) / ANDROID_ORIENTATION_TURN_MS,
|
||||
);
|
||||
const eased = progress * progress * (3 - 2 * progress);
|
||||
orientationAngle =
|
||||
orientationTurn.from + (orientationTurn.to - orientationTurn.from) * eased;
|
||||
if (progress === 1) orientationTurn = null;
|
||||
applyPose();
|
||||
fit(reducedMotion());
|
||||
}
|
||||
if (foldTurn && "setAngle" in phone) {
|
||||
const progress = Math.min(1, (now - foldTurn.startedAt) / ANDROID_FOLD_TURN_MS);
|
||||
const eased = progress * progress * (3 - 2 * progress);
|
||||
phone.setAngle(foldTurn.from + (foldTurn.to - foldTurn.from) * eased);
|
||||
if (progress === 1) foldTurn = null;
|
||||
fit(reducedMotion());
|
||||
}
|
||||
framing.advance(now, reducedMotion());
|
||||
applyCamera();
|
||||
renderer.render(scene, camera);
|
||||
if (motion.needsFrame() || framing.needsFrame()) scheduler.invalidate();
|
||||
if (motion.needsFrame() || framing.needsFrame() || orientationTurn || foldTurn)
|
||||
scheduler.invalidate();
|
||||
} catch {
|
||||
options.onUnavailable();
|
||||
}
|
||||
@@ -188,7 +222,11 @@ export function createPhoneViewer(options: {
|
||||
phone.setDisplay(texture, next);
|
||||
previous.dispose();
|
||||
}
|
||||
if (!imported && (nextProfile !== profile || next.aspect !== layout.aspect)) {
|
||||
if (
|
||||
!imported &&
|
||||
!("setAngle" in phone) &&
|
||||
(nextProfile !== profile || next.aspect !== layout.aspect)
|
||||
) {
|
||||
scene.remove(phone.root);
|
||||
phone.dispose();
|
||||
phone = createPhoneScene(texture, next, nextProfile);
|
||||
@@ -196,10 +234,26 @@ export function createPhoneViewer(options: {
|
||||
} else {
|
||||
phone.setDisplay(texture, next);
|
||||
}
|
||||
if (next.rotation !== layout.rotation) {
|
||||
if (nextProfile.id.startsWith("android") && !("setAngle" in phone) && !reducedMotion()) {
|
||||
const difference = Math.atan2(
|
||||
Math.sin(next.rotation - orientationAngle),
|
||||
Math.cos(next.rotation - orientationAngle),
|
||||
);
|
||||
orientationTurn = {
|
||||
from: orientationAngle,
|
||||
to: orientationAngle + difference,
|
||||
startedAt: performance.now(),
|
||||
};
|
||||
} else {
|
||||
orientationTurn = null;
|
||||
orientationAngle = "setAngle" in phone ? 0 : next.rotation;
|
||||
}
|
||||
}
|
||||
layout = next;
|
||||
profile = nextProfile;
|
||||
applyPose();
|
||||
fit(true);
|
||||
fit(!orientationTurn);
|
||||
}
|
||||
applyPose();
|
||||
};
|
||||
@@ -212,7 +266,10 @@ export function createPhoneViewer(options: {
|
||||
? null
|
||||
: model
|
||||
? createImportedPhoneScene(model.asset, texture, layout)
|
||||
: createPhoneScene(texture, layout, profile);
|
||||
: foldAngle !== null && profile.id.startsWith("android")
|
||||
? createAndroidFoldScene(texture, layout, foldAngle)
|
||||
: createPhoneScene(texture, layout, profile);
|
||||
foldTurn = null;
|
||||
scene.remove(phone.root);
|
||||
phone.dispose();
|
||||
imported = model;
|
||||
@@ -267,6 +324,43 @@ export function createPhoneViewer(options: {
|
||||
modelSlot.set(source);
|
||||
},
|
||||
setAccessory,
|
||||
setFoldAngle(next) {
|
||||
if (disposed || next === foldAngle) return;
|
||||
const previous = foldAngle;
|
||||
foldAngle = next;
|
||||
// A loaded model owns the scene; install() reads foldAngle if it is removed.
|
||||
if (imported) return;
|
||||
if (next === null || !("setAngle" in phone)) {
|
||||
scene.remove(phone.root);
|
||||
phone.dispose();
|
||||
phone =
|
||||
next === null
|
||||
? createPhoneScene(texture, layout, profile)
|
||||
: createAndroidFoldScene(texture, layout, next);
|
||||
scene.add(phone.root);
|
||||
orientationTurn = null;
|
||||
orientationAngle = next === null ? layout.rotation : 0;
|
||||
foldTurn = null;
|
||||
applyPose();
|
||||
fit(true);
|
||||
} else {
|
||||
const progress = foldTurn
|
||||
? Math.min(1, (performance.now() - foldTurn.startedAt) / ANDROID_FOLD_TURN_MS)
|
||||
: 1;
|
||||
const eased = progress * progress * (3 - 2 * progress);
|
||||
const from = foldTurn
|
||||
? foldTurn.from + (foldTurn.to - foldTurn.from) * eased
|
||||
: (previous ?? next);
|
||||
if (reducedMotion()) {
|
||||
foldTurn = null;
|
||||
phone.setAngle(next);
|
||||
fit(true);
|
||||
} else {
|
||||
foldTurn = { from, to: next, startedAt: performance.now() };
|
||||
}
|
||||
}
|
||||
scheduler.invalidate();
|
||||
},
|
||||
frameUpdated() {
|
||||
if (disposed) return;
|
||||
updateLayout();
|
||||
|
||||
Reference in new issue
Block a user