import * as THREE from 'three'; import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js'; import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js'; /** * A procedurally modelled iPhone (Pro-style titanium frame, glass, camera * plateau) whose screen displays native Jotley captures. * Units are centimetres, so the body matches a 6.3" phone (7.15 × 14.96 × 0.83). */ export type PhonePose = { rotateX: number; rotateY: number }; export type PhoneScreen = { image: string; video?: string }; export type PhoneSceneOptions = { screens: PhoneScreen[]; poses: PhonePose[]; reducedMotion: boolean; /** 0 = phone shows its back, 1 = facing the viewer. Read every frame. */ getEntryProgress: () => number; }; export type PhoneSceneHandle = { show: (index: number) => void; setActive: (active: boolean) => void; dispose: () => void; }; const BODY_W = 7.15; const BODY_H = 14.96; const BODY_D = 0.83; const EDGE = 0.12; // rounded transition between frame and glass const SCREEN_ASPECT = 1320 / 2868; // the iPhone captures’ native aspect const BEZEL = 0.124; const CORNER = 1.154; // corner radius of the glass faces function roundedRectShape(width: number, height: number, radius: number): THREE.Shape { const x = -width / 2; const y = -height / 2; const r = Math.min(radius, width / 2, height / 2); const shape = new THREE.Shape(); shape.moveTo(x + r, y); shape.lineTo(x + width - r, y); shape.quadraticCurveTo(x + width, y, x + width, y + r); shape.lineTo(x + width, y + height - r); shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height); shape.lineTo(x + r, y + height); shape.quadraticCurveTo(x, y + height, x, y + height - r); shape.lineTo(x, y + r); shape.quadraticCurveTo(x, y, x + r, y); return shape; } /** ShapeGeometry with UVs normalised to the shape's bounding box (for textures). */ function planarShapeGeometry(shape: THREE.Shape, segments = 48): THREE.ShapeGeometry { const geometry = new THREE.ShapeGeometry(shape, segments); geometry.computeBoundingBox(); const box = geometry.boundingBox!; const size = new THREE.Vector3(); box.getSize(size); const position = geometry.attributes.position; const uv = geometry.attributes.uv; for (let i = 0; i < position.count; i++) { uv.setXY(i, (position.getX(i) - box.min.x) / size.x, (position.getY(i) - box.min.y) / size.y); } uv.needsUpdate = true; return geometry; } /** Soft diagonal glare that slides across the glass as the phone turns. */ function glareTexture(): THREE.CanvasTexture { const canvas = document.createElement('canvas'); canvas.width = 256; canvas.height = 512; const ctx = canvas.getContext('2d')!; const gradient = ctx.createLinearGradient(0, 0, 256, 512); gradient.addColorStop(0, 'rgba(255,255,255,0)'); gradient.addColorStop(0.38, 'rgba(255,255,255,0)'); gradient.addColorStop(0.47, 'rgba(255,255,255,0.55)'); gradient.addColorStop(0.53, 'rgba(255,255,255,0.12)'); gradient.addColorStop(0.62, 'rgba(255,255,255,0)'); gradient.addColorStop(1, 'rgba(255,255,255,0)'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 256, 512); const texture = new THREE.CanvasTexture(canvas); texture.wrapS = THREE.RepeatWrapping; return texture; } function buildPhone(materials: { frame: THREE.Material; backGlass: THREE.Material; frontGlass: THREE.Material; lensRing: THREE.Material; lensGlass: THREE.Material; lensInner: THREE.Material; plateau: THREE.Material; flash: THREE.Material; screen: THREE.Material; glare: THREE.Material; }) { const phone = new THREE.Group(); const capW = BODY_W - EDGE * 2; const capH = BODY_H - EDGE * 2; const coreDepth = BODY_D - EDGE * 2; // Body: flat titanium sides with softly rounded edges into the glass. const body = new THREE.ExtrudeGeometry(roundedRectShape(capW, capH, CORNER), { depth: coreDepth, bevelEnabled: true, bevelThickness: EDGE, bevelSize: EDGE, bevelSegments: 8, curveSegments: 40, }); body.translate(0, 0, -coreDepth / 2); phone.add(new THREE.Mesh(body, [materials.backGlass, materials.frame])); const frontZ = coreDepth / 2 + EDGE; // Front glass (black border visible around the display). const front = new THREE.Mesh(planarShapeGeometry(roundedRectShape(capW, capH, CORNER)), materials.frontGlass); front.position.z = frontZ + 0.003; phone.add(front); // Display. Uniform 1.24mm bezel; the aspect matches the recordings exactly. const screenW = capW - BEZEL * 2; const screenH = screenW / SCREEN_ASPECT; const screenGeometry = planarShapeGeometry(roundedRectShape(screenW, screenH, CORNER - BEZEL)); const screen = new THREE.Mesh(screenGeometry, materials.screen); screen.position.z = frontZ + 0.014; phone.add(screen); const glare = new THREE.Mesh(screenGeometry, materials.glare); glare.position.z = frontZ + 0.024; phone.add(glare); // Back: camera plateau with three lenses, flash and LiDAR. const back = new THREE.Group(); back.rotation.y = Math.PI; // build in front-facing coords, then flip to the back back.position.z = -frontZ; phone.add(back); const plateauSize = 3.55; const plateauGeometry = new THREE.ExtrudeGeometry(roundedRectShape(plateauSize - 0.1, plateauSize - 0.1, 0.78), { depth: 0.06, bevelEnabled: true, bevelThickness: 0.05, bevelSize: 0.05, bevelSegments: 5, curveSegments: 24, }); const plateau = new THREE.Mesh(plateauGeometry, materials.plateau); // `back` is flipped, so its local axes read as seen from behind: the plateau sits top-left. const plateauX = -(capW / 2 - plateauSize / 2 - 0.28); const plateauY = capH / 2 - plateauSize / 2 - 0.28; plateau.position.set(plateauX, plateauY, 0); back.add(plateau); const lensRingGeometry = new THREE.CylinderGeometry(0.72, 0.74, 0.22, 48); lensRingGeometry.rotateX(Math.PI / 2); const lensGlassGeometry = new THREE.CircleGeometry(0.6, 48); const lensInnerGeometry = new THREE.CircleGeometry(0.26, 32); const lensSpots: [number, number][] = [ [-0.8, 0.8], [-0.8, -0.8], [0.75, 0], ]; for (const [dx, dy] of lensSpots) { const lens = new THREE.Group(); lens.position.set(plateauX + dx, plateauY + dy, 0.2); const ring = new THREE.Mesh(lensRingGeometry, materials.lensRing); lens.add(ring); const glass = new THREE.Mesh(lensGlassGeometry, materials.lensGlass); glass.position.z = 0.111; lens.add(glass); const inner = new THREE.Mesh(lensInnerGeometry, materials.lensInner); inner.position.z = 0.113; lens.add(inner); back.add(lens); } const flash = new THREE.Mesh(new THREE.CircleGeometry(0.2, 32), materials.flash); flash.position.set(plateauX + 0.78, plateauY + 1.05, 0.125); back.add(flash); const lidar = new THREE.Mesh(new THREE.CircleGeometry(0.2, 32), materials.lensGlass); lidar.position.set(plateauX + 0.78, plateauY - 1.05, 0.125); back.add(lidar); // Side buttons: action + volume on the left, side button + camera control on the right. const button = (length: number, x: number, y: number) => { const mesh = new THREE.Mesh(new RoundedBoxGeometry(0.1, length, 0.32, 3, 0.045), materials.frame); mesh.position.set(x, y, 0); phone.add(mesh); }; const sideX = BODY_W / 2 + 0.02; button(0.62, -sideX, 4.35); button(1.15, -sideX, 2.75); button(1.15, -sideX, 1.35); button(1.65, sideX, 2.6); button(1.0, sideX, -2.35); return { phone, screen }; } export async function createPhoneScene(container: HTMLElement, options: PhoneSceneOptions): Promise { const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' }); renderer.outputColorSpace = THREE.SRGBColorSpace; renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05; renderer.domElement.setAttribute('aria-hidden', 'true'); container.appendChild(renderer.domElement); const scene = new THREE.Scene(); const pmrem = new THREE.PMREMGenerator(renderer); const environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; scene.environment = environment; // A tight near/far range keeps depth precision high enough that the glass layers never z-fight. const camera = new THREE.PerspectiveCamera(28, 1, 4, 120); // Key, fill and two brand-coloured rim lights so the titanium edges catch purple. scene.add(new THREE.AmbientLight(0xffffff, 0.25)); const key = new THREE.DirectionalLight(0xffffff, 1.6); key.position.set(6, 10, 14); scene.add(key); const rimLeft = new THREE.DirectionalLight(0xa855f7, 3.2); rimLeft.position.set(-14, 4, -6); scene.add(rimLeft); const rimRight = new THREE.DirectionalLight(0x7c3aed, 2.4); rimRight.position.set(14, -6, -8); scene.add(rimRight); const textureLoader = new THREE.TextureLoader(); const screenTextures = options.screens.map((screen) => { const texture = textureLoader.load(screen.image); texture.colorSpace = THREE.SRGBColorSpace; texture.anisotropy = renderer.capabilities.getMaxAnisotropy(); return texture; }); const screenMaterial = new THREE.MeshBasicMaterial({ map: screenTextures[0], toneMapped: false }); // Video textures use a different sRGB decoding path in Three.js. const clips = options.screens.map(({ video: src }) => { if (!src || options.reducedMotion) return null; const video = document.createElement('video'); video.crossOrigin = 'anonymous'; video.muted = true; video.loop = true; video.playsInline = true; video.preload = 'none'; const texture = new THREE.VideoTexture(video); texture.colorSpace = THREE.SRGBColorSpace; // The angled screen shrinks fine text and waveform bars unevenly across the frame. texture.generateMipmaps = true; texture.minFilter = THREE.LinearMipmapLinearFilter; texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy()); const material = new THREE.MeshBasicMaterial({ map: texture, toneMapped: false }); material.onBeforeCompile = (shader) => { // Average subpixel samples before the video color conversion. UV gradients // follow the screen as it rotates, smoothing thin lines without blurring the whole phone. const videoMap = THREE.ShaderChunk.map_fragment.replace( 'texture2D( map, vMapUv )', `( texture2D( map, vMapUv + tapX + tapY ) + texture2D( map, vMapUv + tapX - tapY ) + texture2D( map, vMapUv - tapX + tapY ) + texture2D( map, vMapUv - tapX - tapY ) ) * 0.25` ); shader.fragmentShader = shader.fragmentShader.replace( '#include ', `#ifdef USE_MAP vec2 tapX = dFdx( vMapUv ) * 0.35; vec2 tapY = dFdy( vMapUv ) * 0.35; #endif ${videoMap}` ); }; return { src, video, material, texture }; }); const glareMap = glareTexture(); const glareMaterial = new THREE.MeshBasicMaterial({ map: glareMap, transparent: true, opacity: 0.09, blending: THREE.AdditiveBlending, depthWrite: false, }); const frameMaterial = new THREE.MeshPhysicalMaterial({ color: 0x5b5266, metalness: 1, roughness: 0.26, clearcoat: 0.4, clearcoatRoughness: 0.2, }); const backGlassMaterial = new THREE.MeshPhysicalMaterial({ color: 0x2f2a38, metalness: 0.15, roughness: 0.55, clearcoat: 0.6, clearcoatRoughness: 0.45, }); const materials = { frame: frameMaterial, backGlass: backGlassMaterial, frontGlass: new THREE.MeshPhysicalMaterial({ color: 0x050407, roughness: 0.08, clearcoat: 1, clearcoatRoughness: 0.04 }), plateau: new THREE.MeshPhysicalMaterial({ color: 0x3a3444, metalness: 0.2, roughness: 0.18, clearcoat: 1, clearcoatRoughness: 0.08 }), lensRing: new THREE.MeshPhysicalMaterial({ color: 0x6d6378, metalness: 1, roughness: 0.18 }), lensGlass: new THREE.MeshPhysicalMaterial({ color: 0x07060b, roughness: 0.04, clearcoat: 1, clearcoatRoughness: 0.02 }), lensInner: new THREE.MeshPhysicalMaterial({ color: 0x1b1530, metalness: 0.6, roughness: 0.1, iridescence: 1, iridescenceIOR: 1.6 }), flash: new THREE.MeshStandardMaterial({ color: 0xf3ead3, roughness: 0.4, emissive: 0x2a2416 }), screen: screenMaterial, glare: glareMaterial, }; const { phone, screen } = buildPhone(materials); const rig = new THREE.Group(); rig.add(phone); scene.add(rig); // ---- animation state ---- let activeIndex = 0; let shownIndex = 0; let fade = 1; // screen brightness (dips to black while switching screenshots) let switching = false; let running = false; let frame = 0; let last = performance.now(); const pointer = { x: 0, y: 0 }; const smoothPointer = { x: 0, y: 0 }; const rotation = { x: 0, y: options.reducedMotion ? 0 : Math.PI }; let playingIndex = -1; const syncPlayback = () => { // Save the start of the transcript for when the phone is facing the reader. const nextIndex = running && Math.cos(rotation.y) > 0.75 ? shownIndex : -1; if (nextIndex === playingIndex) return; playingIndex = nextIndex; clips.forEach((clip, index) => { if (!clip) return; const { video, src } = clip; if (index === playingIndex) { if (!video.hasAttribute('src')) video.src = src; void video.play().catch(() => undefined); } else { video.pause(); if (video.readyState >= 1) video.currentTime = 0; } }); }; const resize = () => { const width = container.clientWidth; const height = container.clientHeight; if (!width || !height) return; // Supersample angled UI on standard displays while bounding the canvas on larger screens. const pixelRatio = Math.min(Math.max(window.devicePixelRatio, 2.5), 3, Math.sqrt(4_500_000 / (width * height))); renderer.setPixelRatio(pixelRatio); renderer.setSize(width, height, false); camera.aspect = width / height; // Keep the whole phone (plus turning room) in frame for any aspect ratio. const halfFov = THREE.MathUtils.degToRad(camera.fov / 2); const fitHeight = (BODY_H * 1.08) / (2 * Math.tan(halfFov)); const fitWidth = (BODY_W * 1.9) / (2 * Math.tan(halfFov) * camera.aspect); camera.position.set(0, 0, Math.max(fitHeight, fitWidth)); camera.lookAt(0, 0, 0); camera.updateProjectionMatrix(); }; const resizeObserver = new ResizeObserver(resize); resizeObserver.observe(container); resize(); const onPointerMove = (event: PointerEvent) => { pointer.x = (event.clientX / window.innerWidth) * 2 - 1; pointer.y = (event.clientY / window.innerHeight) * 2 - 1; }; window.addEventListener('pointermove', onPointerMove, { passive: true }); const damp = (current: number, target: number, lambda: number, dt: number) => current + (target - current) * (1 - Math.exp(-lambda * dt)); const tick = (now: number) => { frame = requestAnimationFrame(tick); const dt = Math.min((now - last) / 1000, 0.05); last = now; const t = now / 1000; // Swap screenshots through a quick dip to black, like a screen changing apps. if (activeIndex !== shownIndex && !switching) switching = true; if (switching) { fade = Math.max(0, fade - dt * 7); if (fade === 0) { shownIndex = activeIndex; switching = false; } } else { fade = Math.min(1, fade + dt * 5); } screenMaterial.map = screenTextures[shownIndex]; const clip = clips[shownIndex]; const visibleMaterial = clip && clip.video.readyState >= 2 && !clip.video.error && !clip.video.paused ? clip.material : screenMaterial; visibleMaterial.color.setScalar(fade); screen.material = visibleMaterial; const pose = options.poses[activeIndex] ?? options.poses[0]; const entry = options.reducedMotion ? 1 : THREE.MathUtils.smootherstep(options.getEntryProgress(), 0, 1); smoothPointer.x = damp(smoothPointer.x, options.reducedMotion ? 0 : pointer.x, 3, dt); smoothPointer.y = damp(smoothPointer.y, options.reducedMotion ? 0 : pointer.y, 3, dt); const targetY = THREE.MathUtils.lerp(Math.PI * 1.02, pose.rotateY, entry) + smoothPointer.x * 0.16; const targetX = pose.rotateX + smoothPointer.y * 0.08; rotation.y = damp(rotation.y, targetY, 3.2, dt); rotation.x = damp(rotation.x, targetX, 3.2, dt); syncPlayback(); rig.rotation.set(rotation.x, rotation.y, options.reducedMotion ? 0 : Math.sin(t * 0.6) * 0.012); rig.position.y = options.reducedMotion ? 0 : Math.sin(t * 0.9) * 0.14; glareMap.offset.x = rotation.y * 0.35 + 0.1; renderer.render(scene, camera); }; const setActive = (active: boolean) => { if (active === running) return; running = active; if (active) { last = performance.now(); frame = requestAnimationFrame(tick); } else { cancelAnimationFrame(frame); } syncPlayback(); }; // Render one frame immediately so the canvas isn't blank before it scrolls in. renderer.render(scene, camera); return { show(index: number) { activeIndex = Math.max(0, Math.min(index, options.screens.length - 1)); }, setActive, dispose() { cancelAnimationFrame(frame); resizeObserver.disconnect(); window.removeEventListener('pointermove', onPointerMove); clips.forEach((clip) => { if (!clip) return; clip.video.pause(); clip.video.removeAttribute('src'); clip.video.load(); clip.material.dispose(); clip.texture.dispose(); }); scene.traverse((object) => { if (object instanceof THREE.Mesh) object.geometry.dispose(); }); Object.values(materials).forEach((material) => material.dispose()); [...screenTextures, glareMap, environment].forEach((texture) => texture.dispose()); pmrem.dispose(); renderer.dispose(); renderer.domElement.remove(); }, }; }