Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

Refactor device models and configurations

CristianOlivera17b229efd85e2
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 5fc8a06..c28d5dc 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -49,6 +49,11 @@ const DoubleIPhone3DViewer = dynamic(
{ ssr: false }
);
+const IPhone17ProMax3DViewer = dynamic(
+ () => import("./mockups-3d/IPhone17ProMax3DViewer").then((m) => ({ default: m.IPhone17ProMax3DViewer })),
+ { ssr: false }
+);
+
const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
activeTool: _activeTool,
mediaType = "video",
@@ -152,7 +157,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
iphone: '/models/iphone-15-pro-max.glb',
'iphone-13-pro-max': '/models/apple_iphone_13_pro_max.glb',
'double_iphone_13_pro': '/models/double_iphone_13_pro.glb',
- samsung: '/models/samsung-galaxy-s25-ultra.glb',
+ 'iphone-17-pro-max': '/models/iphone-17-pro-max.glb',
laptop: '/models/mac-book.glb',
};
const imagePhoneModelUrl = PHONE_DEVICE_URLS[imagePhoneDevice];
@@ -2258,44 +2263,62 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
shadowIntensity={imagePhoneShadow}
shadowColor={imagePhoneShadowColor}
/>
- ) : activePhoneDevice === "double_iphone_13_pro" ? (
- <DoubleIPhone3DViewer
- key="double_iphone_13_pro"
- imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
- imageMaskConfig={imageMaskConfig}
- cropArea={cropArea}
- initialRotationX={imagePhoneRotX}
- initialRotationY={imagePhoneRotY}
- initialRotationZ={imagePhoneRotZ}
- onRotationChange={handlePhoneRotationChange}
- onMount={handlePhoneMount}
- onApi={handlePhoneApi}
- scale={1}
- zoom={1}
- shadowIntensity={imagePhoneShadow}
- shadowColor={imagePhoneShadowColor}
- />
- ) : (
- <Phone3DViewer
- key={imagePhoneDevice}
- imageUrl={imageUrl}
- videoElement={mediaType === "video" ? videoRef.current : undefined}
- imageMaskConfig={imageMaskConfig}
- cropArea={cropArea}
- initialRotationX={imagePhoneRotX}
- initialRotationY={imagePhoneRotY}
- initialRotationZ={imagePhoneRotZ}
- modelUrl={imagePhoneModelUrl}
- scale={1}
- zoom={1}
- shadowIntensity={imagePhoneShadow}
- shadowColor={imagePhoneShadowColor}
- onRotationChange={handlePhoneRotationChange}
- onMount={handlePhoneMount}
- onApi={handlePhoneApi}
- />
- )}
+ ): activePhoneDevice === "iphone-17-pro-max" ? (
+ <IPhone17ProMax3DViewer
+ key="iphone-17-pro-max"
+ imageUrl={imageUrl}
+ videoElement={mediaType === "video" ? videoRef.current : undefined}
+ imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ initialRotationZ={imagePhoneRotZ}
+ onRotationChange={handlePhoneRotationChange}
+ onMount={handlePhoneMount}
+ onApi={handlePhoneApi}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ />
+ ) : activePhoneDevice === "double_iphone_13_pro" ? (
+ <DoubleIPhone3DViewer
+ key="double_iphone_13_pro"
+ imageUrl={imageUrl}
+ videoElement={mediaType === "video" ? videoRef.current : undefined}
+ imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ initialRotationZ={imagePhoneRotZ}
+ onRotationChange={handlePhoneRotationChange}
+ onMount={handlePhoneMount}
+ onApi={handlePhoneApi}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ />
+ ) : (
+ <Phone3DViewer
+ key={imagePhoneDevice}
+ imageUrl={imageUrl}
+ videoElement={mediaType === "video" ? videoRef.current : undefined}
+ imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
+ initialRotationX={imagePhoneRotX}
+ initialRotationY={imagePhoneRotY}
+ initialRotationZ={imagePhoneRotZ}
+ modelUrl={imagePhoneModelUrl}
+ scale={1}
+ zoom={1}
+ shadowIntensity={imagePhoneShadow}
+ shadowColor={imagePhoneShadowColor}
+ onRotationChange={handlePhoneRotationChange}
+ onMount={handlePhoneMount}
+ onApi={handlePhoneApi}
+ />
+ )}
</div>
</div>
)}
diff --git a/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx b/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
index 453261a..b3c88b6 100644
--- a/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
@@ -1,10 +1,9 @@
"use client";
import { Canvas, useThree, useFrame } from "@react-three/fiber";
-import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei";
+import { PerspectiveCamera, Environment, OrbitControls, useGLTF } from "@react-three/drei";
import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } from "react";
import * as THREE from "three";
-import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import {
PHONE_W,
PHONE_H,
@@ -43,17 +42,10 @@ interface Props {
const DEG = Math.PI / 180;
const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";
const MODEL_URL = "/models/double_iphone_13_pro.glb";
+const DRACO_URL = "https://www.gstatic.com/draco/versioned/decoders/1.5.6/";
+const DEFAULT_CAMERA_POS: [number, number, number] = [0, 0, 1.5];
-let cachedDoublePhonePromise: Promise<THREE.Group> | null = null;
-
-function loadDoubleIPhoneGltf(): Promise<THREE.Group> {
- if (!cachedDoublePhonePromise) {
- cachedDoublePhonePromise = new Promise((resolve, reject) => {
- new GLTFLoader().load(MODEL_URL, (gltf) => resolve(gltf.scene), undefined, reject);
- });
- }
- return cachedDoublePhonePromise;
-}
+useGLTF.preload(MODEL_URL, DRACO_URL);
function ModelScene({
imageUrl,
@@ -74,16 +66,16 @@ function ModelScene({
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera } = useThree();
+ const { gl, scene, camera, invalidate } = useThree();
+ const gltf = useGLTF(MODEL_URL, DRACO_URL);
const orbitRef = useRef<OrbitControlsType | null>(null);
const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);
-
const lastLoadedUrlRef = useRef<string | null>(null);
const lastLoadedCropKeyRef = useRef<string | null>(null);
-
const onApiRef = useRef(onApi);
+
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -107,6 +99,7 @@ function ModelScene({
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
+
const maxTexSize = gl.capabilities.maxTextureSize || 4096;
const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
@@ -117,19 +110,21 @@ function ModelScene({
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
+
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
gl.render(scene, cam);
},
restorePreview: () => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
+
const freshW = gl.domElement.clientWidth;
const freshH = gl.domElement.clientHeight;
(cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(3);
+ gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
},
hasBuiltInShadow: true,
@@ -141,6 +136,7 @@ function ModelScene({
const applyTexture = useCallback(() => {
if (videoElement) return;
+
const mat = screenMatRef.current;
if (!mat) return;
@@ -163,7 +159,6 @@ function ModelScene({
const TARGET_W = 1080;
const TARGET_H = 2340;
-
const sourceImg = cropArea ? applyCropToImage(img, cropArea) : img;
const cover = createCoverScreenCanvas(sourceImg, TARGET_W, TARGET_H, 0, imageMaskConfig);
@@ -184,17 +179,20 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = targetImgUrl;
lastLoadedCropKeyRef.current = cropKey;
+ invalidate();
};
+
img.onerror = () => {
if (mat.map) mat.map.dispose();
mat.color.set(0x111111);
mat.needsUpdate = true;
+ invalidate();
};
+
img.src = targetImgUrl;
- }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement]);
+ }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
const applyVideoTextureIfReady = useCallback(() => {
const mat = screenMatRef.current;
@@ -206,11 +204,13 @@ function ModelScene({
}
tex.flipY = false;
tex.needsUpdate = true;
+
mat.map = tex;
mat.color.set(0xffffff);
mat.needsUpdate = true;
+ invalidate();
}
- }, []);
+ }, [invalidate]);
useEffect(() => {
if (!videoElement) {
@@ -246,6 +246,7 @@ function ModelScene({
}, [videoElement, applyVideoTextureIfReady]);
const applyTextureRef = useRef(applyTexture);
+
useEffect(() => {
applyTextureRef.current = applyTexture;
}, [applyTexture]);
@@ -256,56 +257,57 @@ function ModelScene({
useEffect(() => {
let isMounted = true;
+ const group = gltf.scene.clone(true);
+ const camZ = 1.5;
- const finalizeSetup = (group: THREE.Group) => {
- if (!isMounted) return;
- setModelGroup(group);
- setTimeout(() => {
- if (!isMounted) return;
- applyTextureRef.current();
- onLoaded?.();
- }, 50);
- };
+ const box = new THREE.Box3().setFromObject(group);
+ const center = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
- loadDoubleIPhoneGltf().then((loadedScene) => {
- const group = loadedScene.clone(true);
-
- const camZ = 1.5;
- const box = new THREE.Box3().setFromObject(group);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
- const halfH = camZ * Math.tan((40 / 2) * DEG);
- const sf = (halfH * 2 * 0.55) / size.y;
-
- group.scale.setScalar(sf);
- group.position.copy(center).negate().multiplyScalar(sf);
-
- const basicMat = new THREE.MeshBasicMaterial({
- color: 0x111111,
- side: THREE.FrontSide,
- transparent: false,
- depthTest: true,
- depthWrite: true,
- });
-
- screenMatRef.current = basicMat;
- applyVideoTextureIfReady();
-
- group.traverse((child) => {
- if (child instanceof THREE.Mesh) {
- if (child.name === "Object_13" || child.name === "Object_26") {
- child.material = basicMat;
- }
- }
- });
+ const halfH = camZ * Math.tan((40 / 2) * DEG);
+ const sf = (halfH * 2 * 0.55) / size.y;
+
+ group.scale.setScalar(sf);
+ group.position.copy(center).negate().multiplyScalar(sf);
+
+ const basicMat = new THREE.MeshBasicMaterial({
+ color: 0x111111,
+ side: THREE.FrontSide,
+ transparent: false,
+ depthTest: true,
+ depthWrite: true,
+ });
+ screenMatRef.current = basicMat;
+
+ applyVideoTextureIfReady();
- finalizeSetup(group);
+ group.traverse((child) => {
+ if (child instanceof THREE.Mesh) {
+ if (child.name === "Object_13" || child.name === "Object_26") {
+ child.material = basicMat;
+ }
+ }
});
+ setModelGroup(group);
+
+ setTimeout(() => {
+ if (!isMounted) return;
+ applyTextureRef.current();
+ onLoaded?.();
+ invalidate();
+ }, 50);
+
return () => {
isMounted = false;
+ if (screenMatRef.current) {
+ if (screenMatRef.current.map) {
+ screenMatRef.current.map.dispose();
+ }
+ screenMatRef.current.dispose();
+ }
};
- }, []);
+ }, [gltf.scene, applyVideoTextureIfReady, onLoaded, invalidate]);
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
@@ -321,29 +323,38 @@ function ModelScene({
const orbit = orbitRef.current;
if (!orbit) return;
- const radius = 1.5 / zoom;
+ const radius = 1.5;
const phi = Math.PI / 2 - initialRotationX * DEG;
const theta = initialRotationY * DEG;
orbit.object.position.setFromSphericalCoords(radius, phi, theta);
orbit.update();
+ invalidate();
prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
}, 0);
return () => clearTimeout(id);
- }, [initialRotationX, initialRotationY, zoom]);
+ }, [initialRotationX, initialRotationY, zoom, invalidate]);
useEffect(() => {
if (rootRef.current) {
- // Aplicamos el valor Z de la UI al eje Y del modelo
rootRef.current.rotation.y = initialRotationZ * DEG;
+ invalidate();
}
- }, [initialRotationZ]);
+ }, [initialRotationZ, invalidate]);
return (
<>
- <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={[0, 0, 1.5 / zoom]} />
+ <PerspectiveCamera
+ ref={cameraRef}
+ makeDefault
+ fov={40}
+ near={0.01}
+ far={100}
+ position={DEFAULT_CAMERA_POS}
+ zoom={zoom}
+ />
<OrbitControls
ref={orbitRef}
enableZoom={false}
@@ -361,12 +372,10 @@ function ModelScene({
}}
/>
<Environment preset={environment as EnvironmentPreset} environmentIntensity={glow} background={false} />
-
<ambientLight intensity={0.3} />
<directionalLight position={[3, 6, 5]} intensity={0.6} />
<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
<directionalLight position={[0, -5, 5]} intensity={0.35} />
-
<group ref={rootRef} rotation={[0, initialRotationZ * DEG, 0]}>
{modelGroup && <primitive object={modelGroup} />}
</group>
@@ -395,6 +404,7 @@ function CanvasWithLoader(
failIfMajorPerformanceCaveat: false,
}}
dpr={3}
+ frameloop={props.videoElement ? "always" : "demand"}
resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
onCreated={({ gl, scene }) => {
gl.outputColorSpace = THREE.SRGBColorSpace;
@@ -422,7 +432,6 @@ function CanvasWithLoader(
export function DoubleIPhone3DViewer(props: Props) {
const { scale = 1, shadowIntensity = 0, shadowColor = "#000000" } = props;
-
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
const [grabbing, setGrabbing] = useState(false);
@@ -434,7 +443,6 @@ export function DoubleIPhone3DViewer(props: Props) {
const shadowRgba = shadowColor.startsWith("#")
? parseShadowColor(shadowColor, computedOpacity)
: shadowColor;
-
const hasShadow = t > 0.01;
return (
@@ -468,7 +476,6 @@ export function DoubleIPhone3DViewer(props: Props) {
}}
/>
)}
-
<div
style={{
position: "absolute",
diff --git a/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
index fc5295a..d09a4c1 100644
--- a/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
@@ -4,216 +4,277 @@ import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { PerspectiveCamera, useGLTF, Environment, OrbitControls, ContactShadows } from "@react-three/drei";
import { useEffect, useRef, useState, Suspense, useLayoutEffect } from "react";
import * as THREE from "three";
-import {
- createCoverScreenCanvas,
- applyCropToImage,
- parseShadowColor,
- type ImageMaskConfigLike,
-} from "@/lib/phone3d.utils";
+import { createCoverScreenCanvas, applyCropToImage, parseShadowColor, type ImageMaskConfigLike } from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
-
import { ControlsPopup } from "@/components/ui/ControlsPopup";
import { EnvironmentPreset, ViewerControls3D } from "@/lib/viewer-controls3d";
export interface IPhone13ProMax3DApi {
- renderAt: (width: number, height: number) => void;
- restorePreview: () => void;
- hasBuiltInShadow: boolean;
+ renderAt: (width: number, height: number) => void;
+ restorePreview: () => void;
+ hasBuiltInShadow: boolean;
}
interface Props {
- imageUrl?: string | null;
- imageMaskConfig?: ImageMaskConfigLike | null;
- cropArea?: { x: number; y: number; width: number; height: number } | null;
- initialRotationX?: number;
- initialRotationY?: number;
- initialRotationZ?: number;
- onRotationChange?: (rx: number, ry: number) => void;
- onMount?: (canvas: HTMLCanvasElement) => void;
- onApi?: (api: IPhone13ProMax3DApi | null) => void;
- scale?: number;
- zoom?: number;
- shadowIntensity?: number;
- shadowColor?: string;
- videoElement?: HTMLVideoElement | null;
+ imageUrl?: string | null;
+ imageMaskConfig?: ImageMaskConfigLike | null;
+ cropArea?: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX?: number;
+ initialRotationY?: number;
+ initialRotationZ?: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ onApi?: (api: IPhone13ProMax3DApi | null) => void;
+ scale?: number;
+ zoom?: number;
+ shadowIntensity?: number;
+ shadowColor?: string;
+ videoElement?: HTMLVideoElement | null;
}
const TEX_W = 1284 * 2;
const TEX_H = 2778 * 2;
const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";
+const DEFAULT_CAMERA_POS: [number, number, number] = [0, 0, 1.5];
+const DRACO_URL = "https://www.gstatic.com/draco/versioned/decoders/1.5.6/";
-useGLTF.preload("/models/apple_iphone_13_pro_max.glb");
+useGLTF.preload("/models/apple_iphone_13_pro_max.glb", DRACO_URL);
interface GLTFNodes {
- Frame_Frame_0: THREE.Mesh;
- Frame_Frame2_0: THREE.Mesh;
- Frame_Port_0: THREE.Mesh;
- Frame_Antenna_0: THREE.Mesh;
- Frame_Mic_0: THREE.Mesh;
- Body_Mic_0: THREE.Mesh;
- Body_Bezel_0: THREE.Mesh;
- Body_Body_0: THREE.Mesh;
- Body_Wallpaper_0: THREE.Mesh;
- Body_Camera_Glass_0: THREE.Mesh;
- Body_Lens_0: THREE.Mesh;
- Body_Material_0: THREE.Mesh;
- Camera_Body_0: THREE.Mesh;
- Camera_Glass_0: THREE.Mesh;
- Camera_Camera_Frame001_0: THREE.Mesh;
- Camera_Mic_0: THREE.Mesh;
- Body001_Screen_Glass_0: THREE.Mesh;
- Button_Frame_0: THREE.Mesh;
- Circle003_Frame_0: THREE.Mesh;
- Apple_Logo_Logo_0: THREE.Mesh;
- Camera001_Body_0: THREE.Mesh;
- Camera001_Gray_Glass_0: THREE.Mesh;
- Camera001_Flash_0: THREE.Mesh;
- Camera001_Port_0: THREE.Mesh;
- Camera001_Camera_Frame_0: THREE.Mesh;
- Camera001_Camera_Glass_0: THREE.Mesh;
- Camera001_Lens_0: THREE.Mesh;
- Camera001_Black_Glass_0: THREE.Mesh;
- Camera003_Material002_0: THREE.Mesh;
+ Frame_Frame_0: THREE.Mesh;
+ Frame_Frame2_0: THREE.Mesh;
+ Frame_Port_0: THREE.Mesh;
+ Frame_Antenna_0: THREE.Mesh;
+ Frame_Mic_0: THREE.Mesh;
+ Body_Mic_0: THREE.Mesh;
+ Body_Bezel_0: THREE.Mesh;
+ Body_Body_0: THREE.Mesh;
+ Body_Wallpaper_0: THREE.Mesh;
+ Body_Camera_Glass_0: THREE.Mesh;
+ Body_Lens_0: THREE.Mesh;
+ Body_Material_0: THREE.Mesh;
+ Camera_Body_0: THREE.Mesh;
+ Camera_Glass_0: THREE.Mesh;
+ Camera_Camera_Frame001_0: THREE.Mesh;
+ Camera_Mic_0: THREE.Mesh;
+ Body001_Screen_Glass_0: THREE.Mesh;
+ Button_Frame_0: THREE.Mesh;
+ Circle003_Frame_0: THREE.Mesh;
+ Apple_Logo_Logo_0: THREE.Mesh;
+ Camera001_Body_0: THREE.Mesh;
+ Camera001_Gray_Glass_0: THREE.Mesh;
+ Camera001_Flash_0: THREE.Mesh;
+ Camera001_Port_0: THREE.Mesh;
+ Camera001_Camera_Frame_0: THREE.Mesh;
+ Camera001_Camera_Glass_0: THREE.Mesh;
+ Camera001_Lens_0: THREE.Mesh;
+ Camera001_Black_Glass_0: THREE.Mesh;
+ Camera003_Material002_0: THREE.Mesh;
}
interface GLTFMaterials {
- Frame: THREE.Material;
- Frame2: THREE.Material;
- Port: THREE.Material;
- Antenna: THREE.Material;
- material: THREE.Material;
- Bezel: THREE.Material;
- Body: THREE.Material;
- Wallpaper: THREE.Material;
- Camera_Glass: THREE.Material;
- Lens: THREE.Material;
- Material: THREE.Material;
- Glass: THREE.Material;
- "Camera_Frame.001": THREE.Material;
- Screen_Glass: THREE.Material;
- Logo: THREE.Material;
- Gray_Glass: THREE.Material;
- Flash: THREE.Material;
- Camera_Frame: THREE.Material;
- Black_Glass: THREE.Material;
- "Material.002": THREE.Material;
+ Frame: THREE.Material;
+ Frame2: THREE.Material;
+ Port: THREE.Material;
+ Antenna: THREE.Material;
+ material: THREE.Material;
+ Bezel: THREE.Material;
+ Body: THREE.Material;
+ Wallpaper: THREE.Material;
+ Camera_Glass: THREE.Material;
+ Lens: THREE.Material;
+ Material: THREE.Material;
+ Glass: THREE.Material;
+ "Camera_Frame.001": THREE.Material;
+ Screen_Glass: THREE.Material;
+ Logo: THREE.Material;
+ Gray_Glass: THREE.Material;
+ Flash: THREE.Material;
+ Camera_Frame: THREE.Material;
+ Black_Glass: THREE.Material;
+ "Material.002": THREE.Material;
}
function ModelScene({
- imageUrl,
- imageMaskConfig,
- cropArea,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- onRotationChange,
- rootRef,
- cameraRef,
- zoom,
- onApi,
- onLoaded,
- videoElement,
- shadowIntensity = 0,
- shadowColor = "#000000",
+ imageUrl,
+ imageMaskConfig,
+ cropArea,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+ onLoaded,
+ videoElement,
+ shadowIntensity = 0,
+ shadowColor = "#000000",
}: {
- imageUrl: string | null;
- imageMaskConfig: ImageMaskConfigLike | null;
- cropArea: { x: number; y: number; width: number; height: number } | null;
- initialRotationX: number;
- initialRotationY: number;
- initialRotationZ: number;
- onRotationChange?: (rx: number, ry: number) => void;
- rootRef: React.MutableRefObject<THREE.Group | null>;
- cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
- zoom: number;
- onApi?: (api: IPhone13ProMax3DApi | null) => void;
- onLoaded?: () => void;
- videoElement?: HTMLVideoElement | null;
- shadowIntensity?: number;
- shadowColor?: string;
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ cropArea: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX: number;
+ initialRotationY: number;
+ initialRotationZ: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ zoom: number;
+ onApi?: (api: IPhone13ProMax3DApi | null) => void;
+ onLoaded?: () => void;
+ videoElement?: HTMLVideoElement | null;
+ shadowIntensity?: number;
+ shadowColor?: string;
}) {
- const { gl, scene, camera, invalidate } = useThree();
- const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb") as unknown as {
- nodes: GLTFNodes;
- materials: GLTFMaterials;
+ const { gl, scene, camera, invalidate } = useThree();
+ const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb", DRACO_URL) as unknown as {
+ nodes: GLTFNodes;
+ materials: GLTFMaterials;
+ };
+ const { nodes, materials } = gltf;
+
+ const orbitRef = useRef<OrbitControlsType | null>(null);
+ const lastLoadedImageUrlRef = useRef<string | null>(null);
+ const lastLoadedMaskKeyRef = useRef<string | null>(null);
+ const lastLoadedCropKeyRef = useRef<string | null>(null);
+ const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);
+ const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
+
+ const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D({
+ defaultEnvironment: "sunset",
+ defaultGlow: 2.0,
+ });
+
+ const onApiRef = useRef(onApi);
+
+ useLayoutEffect(() => {
+ onApiRef.current = onApi;
+ });
+
+ useFrame(() => {
+ if (videoElement && videoTextureRef.current) {
+ videoTextureRef.current.needsUpdate = true;
+ }
+ });
+
+ useEffect(() => {
+ const capturedOnApi = onApiRef.current;
+ const RENDER_PIXEL_RATIO = 2;
+
+ const api: IPhone13ProMax3DApi = {
+ renderAt: (w, h) => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+ const maxTexSize = gl.capabilities.maxTextureSize || 4096;
+ const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
+ const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
+ const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
+
+ (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
+ gl.setPixelRatio(RENDER_PIXEL_RATIO);
+ gl.setSize(safeW, safeH, false);
+
+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+ gl.render(scene, cam);
+ },
+ restorePreview: () => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+ const freshW = gl.domElement.clientWidth;
+ const freshH = gl.domElement.clientHeight;
+
+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
+ gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
+ gl.setSize(freshW, freshH, false);
+ },
+ hasBuiltInShadow: true,
};
- const { nodes, materials } = gltf;
-
- const orbitRef = useRef<OrbitControlsType | null>(null);
- const lastLoadedImageUrlRef = useRef<string | null>(null);
- const lastLoadedMaskKeyRef = useRef<string | null>(null);
- const lastLoadedCropKeyRef = useRef<string | null>(null);
- const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);
- const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
- const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D({
- defaultEnvironment: "sunset",
- defaultGlow: 2.0,
- });
-
- const onApiRef = useRef(onApi);
- useLayoutEffect(() => { onApiRef.current = onApi; });
-
- useFrame(() => {
- if (videoElement && videoTextureRef.current) {
- videoTextureRef.current.needsUpdate = true;
- }
- });
-
- useEffect(() => {
- const capturedOnApi = onApiRef.current;
- const RENDER_PIXEL_RATIO = 2;
- const api: IPhone13ProMax3DApi = {
- renderAt: (w, h) => {
- const cam = cameraRef.current ?? camera;
- if (!cam) return;
-
- const maxTexSize = gl.capabilities.maxTextureSize || 4096;
- const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
- const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
- const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
-
- (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
- (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(RENDER_PIXEL_RATIO);
- gl.setSize(safeW, safeH, false);
- if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
- gl.render(scene, cam);
- },
- restorePreview: () => {
- const cam = cameraRef.current ?? camera;
- if (!cam) return;
- const freshW = gl.domElement.clientWidth;
- const freshH = gl.domElement.clientHeight;
- (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
- (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(3);
- gl.setSize(freshW, freshH, false);
- },
- hasBuiltInShadow: true,
- };
- capturedOnApi?.(api);
- return () => capturedOnApi?.(null);
- }, [gl, scene, camera, cameraRef]);
-
- useEffect(() => {
- onLoaded?.();
- }, [onLoaded]);
-
- useEffect(() => {
- if (materials.Wallpaper) {
- wallpaperMatRef.current = materials.Wallpaper as THREE.MeshStandardMaterial;
- }
- }, [materials.Wallpaper]);
-
- useEffect(() => {
- if (!videoElement) {
- if (videoTextureRef.current) {
- videoTextureRef.current.dispose();
- videoTextureRef.current = null;
- }
- return;
+
+ capturedOnApi?.(api);
+ return () => capturedOnApi?.(null);
+ }, [gl, scene, camera, cameraRef]);
+
+ useEffect(() => {
+ onLoaded?.();
+ }, [onLoaded]);
+
+ useEffect(() => {
+ if (materials.Wallpaper) {
+ wallpaperMatRef.current = materials.Wallpaper as THREE.MeshStandardMaterial;
+ }
+ }, [materials.Wallpaper]);
+
+ useEffect(() => {
+ if (!videoElement) {
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ videoTextureRef.current = null;
+ }
+ return;
+ }
+
+ const tex = new THREE.VideoTexture(videoElement);
+ tex.flipY = true;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ }
+ videoTextureRef.current = tex;
+
+ const applyVideoTex = () => {
+ const mat = wallpaperMatRef.current;
+ if (!mat) return;
+ if (mat.map && mat.map !== tex) {
+ mat.map.dispose();
+ }
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+ };
+
+ applyVideoTex();
+
+ return () => {
+ if (videoTextureRef.current === tex) {
+ videoTextureRef.current = null;
+ }
+ tex.dispose();
+ };
+ }, [videoElement]);
+
+ useEffect(() => {
+ const mat = wallpaperMatRef.current;
+ if (!mat) return;
+ if (videoElement) return;
+
+ const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
+ const cropKey = cropArea ? JSON.stringify(cropArea) : null;
+
+ if (!imageUrl) {
+ const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
+ if (lastLoadedImageUrlRef.current === placeholderKey) return;
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
}
- const tex = new THREE.VideoTexture(videoElement);
+ const tex = new THREE.CanvasTexture(cover);
tex.flipY = true;
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
@@ -221,424 +282,375 @@ function ModelScene({
tex.magFilter = THREE.LinearFilter;
tex.wrapS = THREE.ClampToEdgeWrapping;
tex.wrapT = THREE.ClampToEdgeWrapping;
- if (videoTextureRef.current) {
- videoTextureRef.current.dispose();
- }
- videoTextureRef.current = tex;
-
- const applyVideoTex = () => {
- const mat = wallpaperMatRef.current;
- if (!mat) return;
- if (mat.map && mat.map !== tex) {
- mat.map.dispose();
- }
- mat.map = tex;
- mat.color.set(0xffffff);
- mat.needsUpdate = true;
- };
- applyVideoTex();
-
- return () => {
- if (videoTextureRef.current === tex) {
- videoTextureRef.current = null;
- }
- tex.dispose();
- };
- }, [videoElement]);
-
- useEffect(() => {
- const mat = wallpaperMatRef.current;
- if (!mat) return;
-
- if (videoElement) return;
-
- const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
- const cropKey = cropArea ? JSON.stringify(cropArea) : null;
-
- if (!imageUrl) {
- const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
- if (lastLoadedImageUrlRef.current === placeholderKey) return;
-
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);
-
- if (mat.map) {
- mat.map.dispose();
- mat.map = null;
- }
-
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = true;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- mat.map = tex;
- mat.needsUpdate = true;
-
- lastLoadedImageUrlRef.current = placeholderKey;
- lastLoadedMaskKeyRef.current = null;
- lastLoadedCropKeyRef.current = null;
- };
- img.onerror = () => {
- if (mat.map) {
- mat.map.dispose();
- mat.map = null;
- }
- mat.color.set(0x1a1a1a);
- mat.needsUpdate = true;
- lastLoadedImageUrlRef.current = placeholderKey;
- };
- img.src = PLACEHOLDER_PHONE_URL;
- return;
- }
-
- if (
- lastLoadedImageUrlRef.current === imageUrl &&
- lastLoadedMaskKeyRef.current === maskKey &&
- lastLoadedCropKeyRef.current === cropKey
- )
- return;
-
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- const sourceImage = cropArea ? applyCropToImage(img, cropArea) : img;
- const cover = createCoverScreenCanvas(sourceImage, TEX_W, TEX_H, 0, imageMaskConfig);
-
- if (mat.map) {
- mat.map.dispose();
- mat.map = null;
- }
-
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = true;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- mat.map = tex;
- mat.needsUpdate = true;
- invalidate();
-
- lastLoadedImageUrlRef.current = imageUrl;
- lastLoadedMaskKeyRef.current = maskKey;
- lastLoadedCropKeyRef.current = cropKey;
- };
- img.src = imageUrl;
- }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement]);
-
- const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
- useEffect(() => {
- if (prevRotationRef.current?.x === initialRotationX &&
- prevRotationRef.current?.y === initialRotationY) return;
- const id = setTimeout(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
- const DEG = Math.PI / 180;
- const radius = 1.5 / zoom;
- const phi = Math.PI / 2 - initialRotationX * DEG;
- const theta = initialRotationY * DEG;
- orbit.object.position.setFromSphericalCoords(radius, phi, theta);
- orbit.update();
- invalidate();
-
- prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
- }, 0);
- return () => clearTimeout(id);
- }, [initialRotationX, initialRotationY, zoom]);
-
- useEffect(() => {
- const root = rootRef.current;
- if (root) {
- root.rotation.z = initialRotationZ * (Math.PI / 180);
- invalidate();
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+ mat.map = tex;
+ mat.needsUpdate = true;
+ lastLoadedImageUrlRef.current = placeholderKey;
+ lastLoadedMaskKeyRef.current = null;
+ lastLoadedCropKeyRef.current = null;
+ };
+ img.onerror = () => {
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
}
- }, [initialRotationZ, invalidate]);
-
- const shadowT = Math.max(0, Math.min(1, shadowIntensity));
- const showContactShadow = shadowT > 0.01;
- const contactOpacity = shadowT * 0.65;
- const contactBlur = 1.5 + shadowT * 1.5;
-
- return (
- <>
- <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={[0, 0, 1.5 / zoom]} />
-
- <Environment
- preset={environment as EnvironmentPreset}
- environmentIntensity={glow}
- background={false}
- />
-
- <OrbitControls
- ref={orbitRef}
- enableZoom={false}
- enablePan={false}
- enableDamping
- dampingFactor={0.08}
- autoRotate={autoRotate}
- autoRotateSpeed={rotationSpeed}
- onEnd={() => {
- const orbit = orbitRef.current;
- if (!orbit || !onRotationChange) return;
- const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
- const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
- onRotationChange(rx, ry);
- }}
- />
-
- <ambientLight intensity={0.3} />
- <directionalLight position={[3, 6, 5]} intensity={0.6} />
- <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
- <directionalLight position={[0, -5, 5]} intensity={0.35} />
-
- {showContactShadow && (
- <ContactShadows
- position={[0, -0.55, 0]}
- opacity={contactOpacity}
- scale={3}
- blur={contactBlur}
- far={4}
- color={shadowColor}
- resolution={512}
- />
- )}
-
- <group ref={rootRef} rotation={[0, Math.PI, 0]} scale={0.007} dispose={null}>
- <group scale={100}>
- <mesh castShadow receiveShadow geometry={nodes.Frame_Frame_0.geometry} material={materials.Frame} />
- <mesh castShadow receiveShadow geometry={nodes.Frame_Frame2_0.geometry} material={materials.Frame2} />
- <mesh castShadow receiveShadow geometry={nodes.Frame_Port_0.geometry} material={materials.Port} />
- <mesh castShadow receiveShadow geometry={nodes.Frame_Antenna_0.geometry} material={materials.Antenna} />
- <mesh castShadow receiveShadow geometry={nodes.Frame_Mic_0.geometry} material={materials.material} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Mic_0.geometry} material={materials.material} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Bezel_0.geometry} material={materials.Bezel} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Body_0.geometry} material={materials.Body} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Wallpaper_0.geometry} material={materials.Wallpaper} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Camera_Glass_0.geometry} material={materials.Camera_Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Lens_0.geometry} material={materials.Lens} />
- <mesh castShadow receiveShadow geometry={nodes.Body_Material_0.geometry} material={materials.Material} />
- <mesh castShadow receiveShadow geometry={nodes.Camera_Body_0.geometry} material={materials.Body} />
- <mesh castShadow receiveShadow geometry={nodes.Camera_Glass_0.geometry} material={materials.Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Camera_Camera_Frame001_0.geometry} material={materials["Camera_Frame.001"]} />
- <mesh castShadow receiveShadow geometry={nodes.Camera_Mic_0.geometry} material={materials.material} />
- <mesh castShadow receiveShadow geometry={nodes.Body001_Screen_Glass_0.geometry} material={materials.Screen_Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Button_Frame_0.geometry} material={materials.Frame} />
- <mesh castShadow receiveShadow geometry={nodes.Circle003_Frame_0.geometry} material={materials.Frame} />
- <mesh castShadow receiveShadow geometry={nodes.Apple_Logo_Logo_0.geometry} material={materials.Logo} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Body_0.geometry} material={materials.Body} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Gray_Glass_0.geometry} material={materials.Gray_Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Flash_0.geometry} material={materials.Flash} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Port_0.geometry} material={materials.Port} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Frame_0.geometry} material={materials.Camera_Frame} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Glass_0.geometry} material={materials.Camera_Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Lens_0.geometry} material={materials.Lens} />
- <mesh castShadow receiveShadow geometry={nodes.Camera001_Black_Glass_0.geometry} material={materials.Black_Glass} />
- <mesh castShadow receiveShadow geometry={nodes.Camera003_Material002_0.geometry} material={materials["Material.002"]} />
- </group>
- </group>
- </>
- );
+ mat.color.set(0x1a1a1a);
+ mat.needsUpdate = true;
+ lastLoadedImageUrlRef.current = placeholderKey;
+ };
+ img.src = PLACEHOLDER_PHONE_URL;
+ return;
+ }
+
+ if (
+ lastLoadedImageUrlRef.current === imageUrl &&
+ lastLoadedMaskKeyRef.current === maskKey &&
+ lastLoadedCropKeyRef.current === cropKey
+ )
+ return;
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const sourceImage = cropArea ? applyCropToImage(img, cropArea) : img;
+ const cover = createCoverScreenCanvas(sourceImage, TEX_W, TEX_H, 0, imageMaskConfig);
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
+ }
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = true;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+ mat.map = tex;
+ mat.needsUpdate = true;
+ invalidate();
+ lastLoadedImageUrlRef.current = imageUrl;
+ lastLoadedMaskKeyRef.current = maskKey;
+ lastLoadedCropKeyRef.current = cropKey;
+ };
+ img.src = imageUrl;
+ }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement]);
+
+ useEffect(() => {
+ return () => {
+ if (wallpaperMatRef.current && wallpaperMatRef.current.map) {
+ wallpaperMatRef.current.map.dispose();
+ }
+ };
+ }, []);
+
+ const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+
+ useEffect(() => {
+ if (
+ prevRotationRef.current?.x === initialRotationX &&
+ prevRotationRef.current?.y === initialRotationY
+ )
+ return;
+
+ const id = setTimeout(() => {
+ const orbit = orbitRef.current;
+ if (!orbit) return;
+
+ const DEG = Math.PI / 180;
+ const radius = 1.5;
+ const phi = Math.PI / 2 - initialRotationX * DEG;
+ const theta = initialRotationY * DEG;
+
+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);
+ orbit.update();
+ invalidate();
+ prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
+ }, 0);
+
+ return () => clearTimeout(id);
+ }, [initialRotationX, initialRotationY, zoom]);
+
+ useEffect(() => {
+ const root = rootRef.current;
+ if (root) {
+ root.rotation.z = initialRotationZ * (Math.PI / 180);
+ invalidate();
+ }
+ }, [initialRotationZ, invalidate]);
+
+ const shadowT = Math.max(0, Math.min(1, shadowIntensity));
+ const showContactShadow = shadowT > 0.01;
+ const contactOpacity = shadowT * 0.65;
+ const contactBlur = 1.5 + shadowT * 1.5;
+
+ return (
+ <>
+ <PerspectiveCamera
+ ref={cameraRef}
+ makeDefault
+ fov={40}
+ near={0.01}
+ far={100}
+ position={DEFAULT_CAMERA_POS}
+ zoom={zoom}
+ />
+ <Environment preset={environment as EnvironmentPreset} environmentIntensity={glow} background={false} />
+ <OrbitControls
+ ref={orbitRef}
+ enableZoom={false}
+ enablePan={false}
+ enableDamping
+ dampingFactor={0.08}
+ autoRotate={autoRotate}
+ autoRotateSpeed={rotationSpeed}
+ onEnd={() => {
+ const orbit = orbitRef.current;
+ if (!orbit || !onRotationChange) return;
+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
+ onRotationChange(rx, ry);
+ }}
+ />
+ <ambientLight intensity={0.3} />
+ <directionalLight position={[3, 6, 5]} intensity={0.6} />
+ <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
+ <directionalLight position={[0, -5, 5]} intensity={0.35} />
+ {showContactShadow && (
+ <ContactShadows
+ position={[0, -0.55, 0]}
+ opacity={contactOpacity}
+ scale={3}
+ blur={contactBlur}
+ far={4}
+ color={shadowColor}
+ resolution={512}
+ />
+ )}
+ <group ref={rootRef} rotation={[0, Math.PI, 0]} scale={0.007} dispose={null}>
+ <group scale={100}>
+ <mesh castShadow receiveShadow geometry={nodes.Frame_Frame_0.geometry} material={materials.Frame} />
+ <mesh castShadow receiveShadow geometry={nodes.Frame_Frame2_0.geometry} material={materials.Frame2} />
+ <mesh castShadow receiveShadow geometry={nodes.Frame_Port_0.geometry} material={materials.Port} />
+ <mesh castShadow receiveShadow geometry={nodes.Frame_Antenna_0.geometry} material={materials.Antenna} />
+ <mesh castShadow receiveShadow geometry={nodes.Frame_Mic_0.geometry} material={materials.material} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Mic_0.geometry} material={materials.material} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Bezel_0.geometry} material={materials.Bezel} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Body_0.geometry} material={materials.Body} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Wallpaper_0.geometry} material={materials.Wallpaper} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Camera_Glass_0.geometry} material={materials.Camera_Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Lens_0.geometry} material={materials.Lens} />
+ <mesh castShadow receiveShadow geometry={nodes.Body_Material_0.geometry} material={materials.Material} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera_Body_0.geometry} material={materials.Body} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera_Glass_0.geometry} material={materials.Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera_Camera_Frame001_0.geometry} material={materials["Camera_Frame.001"]} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera_Mic_0.geometry} material={materials.material} />
+ <mesh castShadow receiveShadow geometry={nodes.Body001_Screen_Glass_0.geometry} material={materials.Screen_Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Button_Frame_0.geometry} material={materials.Frame} />
+ <mesh castShadow receiveShadow geometry={nodes.Circle003_Frame_0.geometry} material={materials.Frame} />
+ <mesh castShadow receiveShadow geometry={nodes.Apple_Logo_Logo_0.geometry} material={materials.Logo} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Body_0.geometry} material={materials.Body} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Gray_Glass_0.geometry} material={materials.Gray_Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Flash_0.geometry} material={materials.Flash} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Port_0.geometry} material={materials.Port} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Frame_0.geometry} material={materials.Camera_Frame} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Camera_Glass_0.geometry} material={materials.Camera_Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Lens_0.geometry} material={materials.Lens} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera001_Black_Glass_0.geometry} material={materials.Black_Glass} />
+ <mesh castShadow receiveShadow geometry={nodes.Camera003_Material002_0.geometry} material={materials["Material.002"]} />
+ </group>
+ </group>
+ </>
+ );
}
function CanvasWithLoader({
- imageUrl,
- imageMaskConfig,
- cropArea,
- initialRotationX,
- initialRotationY,
- initialRotationZ,
- onRotationChange,
- rootRef,
- cameraRef,
- zoom,
- onApi,
- onMount,
- videoElement,
- shadowIntensity,
- shadowColor,
+ imageUrl,
+ imageMaskConfig,
+ cropArea,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+ onMount,
+ videoElement,
+ shadowIntensity,
+ shadowColor,
}: {
- imageUrl: string | null;
- imageMaskConfig: ImageMaskConfigLike | null;
- cropArea: { x: number; y: number; width: number; height: number } | null;
- initialRotationX: number;
- initialRotationY: number;
- initialRotationZ: number;
- onRotationChange?: (rx: number, ry: number) => void;
- rootRef: React.MutableRefObject<THREE.Group | null>;
- cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
- zoom: number;
- onApi?: (api: IPhone13ProMax3DApi | null) => void;
- onMount?: (canvas: HTMLCanvasElement) => void;
- videoElement?: HTMLVideoElement | null;
- shadowIntensity?: number;
- shadowColor?: string;
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ cropArea: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX: number;
+ initialRotationY: number;
+ initialRotationZ: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ zoom: number;
+ onApi?: (api: IPhone13ProMax3DApi | null) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ videoElement?: HTMLVideoElement | null;
+ shadowIntensity?: number;
+ shadowColor?: string;
}) {
- const [loaded, setLoaded] = useState(false);
- return (
- <>
- <Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
- gl={{
- antialias: true,
- alpha: true,
- preserveDrawingBuffer: true,
- powerPreference: "high-performance",
- failIfMajorPerformanceCaveat: false,
- }}
- dpr={3}
- frameloop={videoElement ? "always" : "demand"}
- resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
- onCreated={({ gl, scene }) => {
- gl.outputColorSpace = THREE.SRGBColorSpace;
- gl.toneMapping = THREE.NeutralToneMapping;
- gl.toneMappingExposure = 1.0;
- scene.environmentIntensity = 1.6;
- onMount?.(gl.domElement);
- }}
- >
- <Suspense fallback={null}>
- <ModelScene
- imageUrl={imageUrl}
- imageMaskConfig={imageMaskConfig}
- cropArea={cropArea}
- initialRotationX={initialRotationX}
- initialRotationY={initialRotationY}
- initialRotationZ={initialRotationZ}
- onRotationChange={onRotationChange}
- rootRef={rootRef}
- cameraRef={cameraRef}
- zoom={zoom}
- onApi={onApi}
- onLoaded={() => setLoaded(true)}
- videoElement={videoElement}
- shadowIntensity={shadowIntensity}
- shadowColor={shadowColor}
- />
- </Suspense>
- </Canvas>
- {!loaded && (
- <div
- className="absolute inset-0 flex items-center justify-center pointer-events-none"
- style={{ zIndex: 4 }}
- >
- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
- </div>
- )}
- </>
- );
+ const [loaded, setLoaded] = useState(false);
+
+ return (
+ <>
+ <Canvas
+ style={{ width: "100%", height: "100%", overflow: "visible" }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ failIfMajorPerformanceCaveat: false,
+ }}
+ dpr={3}
+ frameloop={videoElement ? "always" : "demand"}
+ resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
+ onCreated={({ gl, scene }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ scene.environmentIntensity = 1.6;
+ onMount?.(gl.domElement);
+ }}
+ >
+ <Suspense fallback={null}>
+ <ModelScene
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
+ initialRotationX={initialRotationX}
+ initialRotationY={initialRotationY}
+ initialRotationZ={initialRotationZ}
+ onRotationChange={onRotationChange}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ zoom={zoom}
+ onApi={onApi}
+ onLoaded={() => setLoaded(true)}
+ videoElement={videoElement}
+ shadowIntensity={shadowIntensity}
+ shadowColor={shadowColor}
+ />
+ </Suspense>
+ </Canvas>
+ {!loaded && (
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none"
+ style={{ zIndex: 4 }}
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </>
+ );
}
export function IPhone13ProMax3DViewer({
- imageUrl = null,
- imageMaskConfig = null,
- cropArea = null,
- initialRotationX = -58.23,
- initialRotationY = -29.82,
- initialRotationZ = 0,
- onRotationChange,
- onMount,
- onApi,
- scale = 1,
- zoom = 1,
- shadowIntensity = 0,
- shadowColor = "#000000",
- videoElement = null,
+ imageUrl = null,
+ imageMaskConfig = null,
+ cropArea = null,
+ initialRotationX = -58.23,
+ initialRotationY = -29.82,
+ initialRotationZ = 0,
+ onRotationChange,
+ onMount,
+ onApi,
+ scale = 1,
+ zoom = 1,
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ videoElement = null,
}: Props) {
- const rootRef = useRef<THREE.Group | null>(null);
- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
- const [grabbing, setGrabbing] = useState(false);
-
- const t = Math.max(0, Math.min(1, shadowIntensity));
- const tEased = t * t;
- const computedBlur = tEased * 60;
- const computedOpacity = tEased * 0.7;
-
- const shadowRgba = shadowColor.startsWith("#")
- ? parseShadowColor(shadowColor, computedOpacity)
- : shadowColor;
-
- const hasShadow = t > 0.01;
-
- return (
- <>
- <ControlsPopup />
-
+ const rootRef = useRef<THREE.Group | null>(null);
+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const [grabbing, setGrabbing] = useState(false);
+
+ const t = Math.max(0, Math.min(1, shadowIntensity));
+ const tEased = t * t;
+ const computedBlur = tEased * 60;
+ const computedOpacity = tEased * 0.7;
+ const shadowRgba = shadowColor.startsWith("#")
+ ? parseShadowColor(shadowColor, computedOpacity)
+ : shadowColor;
+ const hasShadow = t > 0.01;
+
+ return (
+ <>
+ <ControlsPopup />
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ width: 480,
+ height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "200px",
+ marginLeft: "170px",
+ }}
+ >
+ <div style={{ position: "relative", width: 480, height: 1000 }}>
+ {hasShadow && (
<div
- style={{
- display: "inline-block",
- transformOrigin: "top center",
- width: 480,
- height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
- marginTop: "200px",
- marginLeft: "170px"
- }}
- >
- <div style={{ position: "relative", width: 480, height: 1000 }}>
- {hasShadow && (
- <div
- aria-hidden
- style={{
- position: "absolute",
- bottom: -(computedBlur * 0.5),
- left: `${20 + tEased * 5}%`,
- width: `${60 - tEased * 10}%`,
- height: Math.max(4, computedBlur * 0.55),
- borderRadius: "50%",
- background: shadowRgba,
- filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,
- zIndex: 0,
- pointerEvents: "none",
- }}
- />
- )}
-
- <div
- style={{
- position: "absolute",
- inset: "-400px",
- zIndex: 2,
- overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: hasShadow
- ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
- : "none",
- transition: "filter 0.15s ease",
- pointerEvents: "auto",
- }}
- onPointerDown={() => setGrabbing(true)}
- onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
- >
- <CanvasWithLoader
- imageUrl={imageUrl}
- imageMaskConfig={imageMaskConfig}
- cropArea={cropArea}
- initialRotationX={initialRotationX}
- initialRotationY={initialRotationY}
- initialRotationZ={initialRotationZ}
- onRotationChange={onRotationChange}
- rootRef={rootRef}
- cameraRef={cameraRef}
- zoom={zoom}
- onApi={onApi}
- onMount={onMount}
- videoElement={videoElement}
- shadowIntensity={shadowIntensity}
- shadowColor={shadowColor}
- />
- </div>
- </div>
- </div>
- </>
- );
+ aria-hidden
+ style={{
+ position: "absolute",
+ bottom: -(computedBlur * 0.5),
+ left: `${20 + tEased * 5}%`,
+ width: `${60 - tEased * 10}%`,
+ height: Math.max(4, computedBlur * 0.55),
+ borderRadius: "50%",
+ background: shadowRgba,
+ filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,
+ zIndex: 0,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+ <div
+ style={{
+ position: "absolute",
+ inset: "-400px",
+ zIndex: 2,
+ overflow: "visible",
+ cursor: grabbing ? "grabbing" : "grab",
+ filter: hasShadow
+ ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
+ : "none",
+ transition: "filter 0.15s ease",
+ pointerEvents: "auto",
+ }}
+ onPointerDown={() => setGrabbing(true)}
+ onPointerUp={() => setGrabbing(false)}
+ onPointerLeave={() => setGrabbing(false)}
+ >
+ <CanvasWithLoader
+ imageUrl={imageUrl}
+ imageMaskConfig={imageMaskConfig}
+ cropArea={cropArea}
+ initialRotationX={initialRotationX}
+ initialRotationY={initialRotationY}
+ initialRotationZ={initialRotationZ}
+ onRotationChange={onRotationChange}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ zoom={zoom}
+ onApi={onApi}
+ onMount={onMount}
+ videoElement={videoElement}
+ shadowIntensity={shadowIntensity}
+ shadowColor={shadowColor}
+ />
+ </div>
+ </div>
+ </div>
+ </>
+ );
}
\ No newline at end of file
diff --git a/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx b/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx
new file mode 100644
index 0000000..1901e5b
--- /dev/null
+++ b/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx
@@ -0,0 +1,468 @@
+"use client";
+
+import { Canvas, useThree, useFrame } from "@react-three/fiber";
+import { PerspectiveCamera, useGLTF, Environment, OrbitControls, ContactShadows } from "@react-three/drei";
+import { useEffect, useRef, useState, Suspense, useLayoutEffect, useMemo, useCallback } from "react";
+import * as THREE from "three";
+import { createCoverScreenCanvas, applyCropToImage, parseShadowColor, type ImageMaskConfigLike } from "@/lib/phone3d.utils";
+import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
+import { ControlsPopup } from "@/components/ui/ControlsPopup";
+import { EnvironmentPreset, ViewerControls3D } from "@/lib/viewer-controls3d";
+
+export interface IPhone17ProMax3DApi {
+ renderAt: (width: number, height: number) => void;
+ restorePreview: () => void;
+ hasBuiltInShadow: boolean;
+}
+
+interface Props {
+ imageUrl?: string | null;
+ imageMaskConfig?: ImageMaskConfigLike | null;
+ cropArea?: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX?: number;
+ initialRotationY?: number;
+ initialRotationZ?: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ onApi?: (api: IPhone17ProMax3DApi | null) => void;
+ scale?: number;
+ zoom?: number;
+ shadowIntensity?: number;
+ shadowColor?: string;
+ videoElement?: HTMLVideoElement | null;
+}
+
+const TEX_W = 1284 * 2;
+const TEX_H = 2778 * 2;
+const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";
+const DEFAULT_CAMERA_POS: [number, number, number] = [0, 0, 1.5];
+const DRACO_URL = "https://www.gstatic.com/draco/versioned/decoders/1.5.6/";
+
+useGLTF.preload("/models/iphone-17-pro-max.glb", DRACO_URL);
+
+function ModelScene({
+ imageUrl,
+ imageMaskConfig,
+ cropArea,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+ onLoaded,
+ videoElement,
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+}: {
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ cropArea: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX: number;
+ initialRotationY: number;
+ initialRotationZ: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ zoom: number;
+ onApi?: (api: IPhone17ProMax3DApi | null) => void;
+ onLoaded?: () => void;
+ videoElement?: HTMLVideoElement | null;
+ shadowIntensity?: number;
+ shadowColor?: string;
+}) {
+ const { gl, scene, camera, invalidate } = useThree();
+ const gltf = useGLTF("/models/iphone-17-pro-max.glb", DRACO_URL);
+
+ const clonedScene = useMemo(() => gltf.scene.clone(true), [gltf.scene]);
+
+ const orbitRef = useRef<OrbitControlsType | null>(null);
+ const lastLoadedImageUrlRef = useRef<string | null>(null);
+ const lastLoadedMaskKeyRef = useRef<string | null>(null);
+ const lastLoadedCropKeyRef = useRef<string | null>(null);
+ const wallpaperMatRef = useRef<THREE.MeshPhysicalMaterial | null>(null);
+ const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
+
+ const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D({
+ defaultEnvironment: "studio",
+ defaultGlow: 1.0,
+ });
+
+ const onApiRef = useRef(onApi);
+ useLayoutEffect(() => {
+ onApiRef.current = onApi;
+ });
+
+ useFrame(() => {
+ if (videoElement && videoTextureRef.current) {
+ videoTextureRef.current.needsUpdate = true;
+ }
+ });
+
+ useEffect(() => {
+ clonedScene.traverse((child) => {
+ if (child instanceof THREE.Mesh) {
+ if (child.name.includes("HkNSnYzBPABcqwM")) {
+ const targetMat = (child.material as THREE.MeshPhysicalMaterial).clone();
+
+ targetMat.normalMap = null;
+ targetMat.roughnessMap = null;
+ targetMat.metalnessMap = null;
+ targetMat.clearcoatMap = null;
+ targetMat.emissiveMap = null;
+ targetMat.emissive = new THREE.Color(0x000000);
+ targetMat.roughness = 0.8;
+ targetMat.metalness = 0.1;
+ targetMat.envMapIntensity = 0.1;
+
+ child.material = targetMat;
+ wallpaperMatRef.current = targetMat;
+ }
+ }
+ });
+ invalidate();
+ }, [clonedScene, invalidate]);
+
+ useEffect(() => {
+ const capturedOnApi = onApiRef.current;
+ const RENDER_PIXEL_RATIO = 2;
+ const api: IPhone17ProMax3DApi = {
+ renderAt: (w, h) => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+ const maxTexSize = gl.capabilities.maxTextureSize || 4096;
+ const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
+ const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
+ const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
+ (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+ gl.setPixelRatio(RENDER_PIXEL_RATIO);
+ gl.setSize(safeW, safeH, false);
+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+ gl.render(scene, cam);
+ },
+ restorePreview: () => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+ const freshW = gl.domElement.clientWidth;
+ const freshH = gl.domElement.clientHeight;
+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+ gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
+ gl.setSize(freshW, freshH, false);
+ invalidate();
+ },
+ hasBuiltInShadow: true,
+ };
+ capturedOnApi?.(api);
+ return () => capturedOnApi?.(null);
+ }, [gl, scene, camera, cameraRef, invalidate]);
+
+ useEffect(() => {
+ onLoaded?.();
+ }, [onLoaded]);
+
+ useEffect(() => {
+ if (!videoElement) {
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ videoTextureRef.current = null;
+ }
+ return;
+ }
+ const tex = new THREE.VideoTexture(videoElement);
+
+ tex.flipY = false;
+
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ }
+ videoTextureRef.current = tex;
+
+ const applyVideoTex = () => {
+ const mat = wallpaperMatRef.current;
+ if (!mat) return;
+ if (mat.map && mat.map !== tex) {
+ mat.map.dispose();
+ }
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+ if (mat.map) mat.map.needsUpdate = true;
+ invalidate();
+ };
+
+ applyVideoTex();
+
+ return () => {
+ if (videoTextureRef.current === tex) {
+ videoTextureRef.current = null;
+ }
+ tex.dispose();
+ };
+ }, [videoElement, invalidate]);
+
+ useEffect(() => {
+ const mat = wallpaperMatRef.current;
+ if (!mat) return;
+
+ if (videoElement) return;
+
+ const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
+ const cropKey = cropArea ? JSON.stringify(cropArea) : null;
+
+ if (!imageUrl) {
+ const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
+ if (lastLoadedImageUrlRef.current === placeholderKey) return;
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
+ }
+ const tex = new THREE.CanvasTexture(cover);
+
+ tex.flipY = false;
+
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+
+ lastLoadedImageUrlRef.current = placeholderKey;
+ lastLoadedMaskKeyRef.current = null;
+ lastLoadedCropKeyRef.current = null;
+ invalidate();
+ };
+ img.onerror = () => {
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
+ }
+ mat.color.set(0x1a1a1a);
+ mat.needsUpdate = true;
+ lastLoadedImageUrlRef.current = placeholderKey;
+ invalidate();
+ };
+ img.src = PLACEHOLDER_PHONE_URL;
+ return;
+ }
+
+ if (
+ lastLoadedImageUrlRef.current === imageUrl &&
+ lastLoadedMaskKeyRef.current === maskKey &&
+ lastLoadedCropKeyRef.current === cropKey
+ ) return;
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const sourceImage = cropArea ? applyCropToImage(img, cropArea) : img;
+ const cover = createCoverScreenCanvas(sourceImage, TEX_W, TEX_H, 0, imageMaskConfig);
+ if (mat.map) {
+ mat.map.dispose();
+ mat.map = null;
+ }
+ const tex = new THREE.CanvasTexture(cover);
+
+ tex.flipY = false;
+
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+
+ invalidate();
+
+ lastLoadedImageUrlRef.current = imageUrl;
+ lastLoadedMaskKeyRef.current = maskKey;
+ lastLoadedCropKeyRef.current = cropKey;
+ };
+ img.src = imageUrl;
+ }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
+
+ useEffect(() => {
+ return () => {
+ if (wallpaperMatRef.current && wallpaperMatRef.current.map) {
+ wallpaperMatRef.current.map.dispose();
+ }
+ };
+ }, []);
+
+ const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+ useEffect(() => {
+ if (prevRotationRef.current?.x === initialRotationX && prevRotationRef.current?.y === initialRotationY) return;
+ const id = setTimeout(() => {
+ const orbit = orbitRef.current;
+ if (!orbit) return;
+ const DEG = Math.PI / 180;
+ const radius = 1.5;
+ const phi = Math.PI / 2 - initialRotationX * DEG;
+ const theta = initialRotationY * DEG;
+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);
+ orbit.update();
+ invalidate();
+ prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
+ }, 0);
+ return () => clearTimeout(id);
+ }, [initialRotationX, initialRotationY, zoom, invalidate]);
+
+ useEffect(() => {
+ const root = rootRef.current;
+ if (root) {
+ root.rotation.z = initialRotationZ * (Math.PI / 180);
+ invalidate();
+ }
+ }, [initialRotationZ, invalidate]);
+
+ const shadowT = Math.max(0, Math.min(1, shadowIntensity));
+ const showContactShadow = shadowT > 0.01;
+ const contactOpacity = shadowT * 0.65;
+ const contactBlur = 1.5 + shadowT * 1.5;
+
+ return (
+ <>
+ <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={DEFAULT_CAMERA_POS} zoom={zoom} />
+ <Environment preset={environment as EnvironmentPreset} environmentIntensity={glow} background={false} />
+ <OrbitControls ref={orbitRef} enableZoom={false} enablePan={false} enableDamping dampingFactor={0.08} autoRotate={autoRotate} autoRotateSpeed={rotationSpeed} onEnd={() => {
+ const orbit = orbitRef.current;
+ if (!orbit || !onRotationChange) return;
+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
+ onRotationChange(rx, ry);
+ }} />
+ <ambientLight intensity={0.3} />
+ <directionalLight position={[3, 6, 5]} intensity={0.6} />
+ <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
+ <directionalLight position={[0, -5, 5]} intensity={0.35} />
+ {showContactShadow && (
+ <ContactShadows position={[0, -0.55, 0]} opacity={contactOpacity} scale={3} blur={contactBlur} far={4} color={shadowColor} resolution={512} />
+ )}
+
+ <group ref={rootRef} rotation={[0, 0, 0]} scale={1} dispose={null}>
+ <primitive object={clonedScene} scale={5} rotation={[0, 0, 0]} castShadow receiveShadow />
+ </group>
+ </>
+ );
+}
+
+function CanvasWithLoader({
+ imageUrl,
+ imageMaskConfig,
+ cropArea,
+ initialRotationX,
+ initialRotationY,
+ initialRotationZ,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom,
+ onApi,
+ onMount,
+ videoElement,
+ shadowIntensity,
+ shadowColor,
+}: {
+ imageUrl: string | null;
+ imageMaskConfig: ImageMaskConfigLike | null;
+ cropArea: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX: number;
+ initialRotationY: number;
+ initialRotationZ: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ zoom: number;
+ onApi?: (api: IPhone17ProMax3DApi | null) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ videoElement?: HTMLVideoElement | null;
+ shadowIntensity?: number;
+ shadowColor?: string;
+}) {
+ const [loaded, setLoaded] = useState(false);
+ const handleLoaded = useCallback(() => setLoaded(true), []);
+
+ return (
+ <>
+ <Canvas style={{ width: "100%", height: "100%", overflow: "visible" }} gl={{ antialias: true, alpha: true, preserveDrawingBuffer: true, powerPreference: "high-performance" }} dpr={3} frameloop={videoElement ? "always" : "demand"} resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }} onCreated={({ gl, scene }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ scene.environmentIntensity = 1.6;
+ onMount?.(gl.domElement);
+ }} >
+ <Suspense fallback={null}>
+ <ModelScene imageUrl={imageUrl} imageMaskConfig={imageMaskConfig} cropArea={cropArea} initialRotationX={initialRotationX} initialRotationY={initialRotationY} initialRotationZ={initialRotationZ} onRotationChange={onRotationChange} rootRef={rootRef} cameraRef={cameraRef} zoom={zoom} onApi={onApi} onLoaded={handleLoaded} videoElement={videoElement} shadowIntensity={shadowIntensity} shadowColor={shadowColor} />
+ </Suspense>
+ </Canvas>
+ {!loaded && (
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </>
+ );
+}
+
+export function IPhone17ProMax3DViewer({
+ imageUrl = null,
+ imageMaskConfig = null,
+ cropArea = null,
+ initialRotationX = -58.23,
+ initialRotationY = -29.82,
+ initialRotationZ = 0,
+ onRotationChange,
+ onMount,
+ onApi,
+ zoom = 1,
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ videoElement = null,
+}: Props) {
+ const rootRef = useRef<THREE.Group | null>(null);
+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const [grabbing, setGrabbing] = useState(false);
+
+ const t = Math.max(0, Math.min(1, shadowIntensity));
+ const tEased = t * t;
+ const computedBlur = tEased * 60;
+ const computedOpacity = tEased * 0.7;
+ const shadowRgba = shadowColor.startsWith("#") ? parseShadowColor(shadowColor, computedOpacity) : shadowColor;
+ const hasShadow = t > 0.01;
+
+ return (
+ <>
+ <ControlsPopup />
+ <div style={{ display: "inline-block", transformOrigin: "top center", width: 480, height: 1000 + (hasShadow ? computedBlur * 0.8 : 0), marginTop: "200px", marginLeft: "170px" }}>
+ <div style={{ position: "relative", width: 480, height: 1000 }}>
+ {hasShadow && (
+ <div aria-hidden style={{ position: "absolute", bottom: -(computedBlur * 0.5), left: `${20 + tEased * 5}%`, width: `${60 - tEased * 10}%`, height: Math.max(4, computedBlur * 0.55), borderRadius: "50%", background: shadowRgba, filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`, zIndex: 0, pointerEvents: "none" }} />
+ )}
+ <div style={{ position: "absolute", inset: "-400px", zIndex: 2, overflow: "visible", cursor: grabbing ? "grabbing" : "grab", filter: hasShadow ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})` : "none", transition: "filter 0.15s ease", pointerEvents: "auto" }} onPointerDown={() => setGrabbing(true)} onPointerUp={() => setGrabbing(false)} onPointerLeave={() => setGrabbing(false)} >
+ <CanvasWithLoader imageUrl={imageUrl} imageMaskConfig={imageMaskConfig} cropArea={cropArea} initialRotationX={initialRotationX} initialRotationY={initialRotationY} initialRotationZ={initialRotationZ} onRotationChange={onRotationChange} rootRef={rootRef} cameraRef={cameraRef} zoom={zoom} onApi={onApi} onMount={onMount} videoElement={videoElement} shadowIntensity={shadowIntensity} shadowColor={shadowColor} />
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx b/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
index ee21210..8ee4a2c 100644
--- a/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
@@ -12,21 +12,19 @@ import {
type ImageMaskConfigLike,
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
-
import { ControlsPopup } from "@/components/ui/ControlsPopup";
import { EnvironmentPreset, ViewerControls3D } from "@/lib/viewer-controls3d";
+THREE.Cache.enabled = true;
+
const LAPTOP_W = 1500;
const LAPTOP_H = 1035;
-
const RENDER_MULTIPLIER = 3;
const RENDER_W = LAPTOP_W * RENDER_MULTIPLIER;
const RENDER_H = LAPTOP_H * RENDER_MULTIPLIER;
-
const CAM_FOV = 40;
const CAM_RADIUS = 75;
const screenSize: [number, number] = [29.4, 20];
-
const LID_CLOSED_X = Math.PI * 0.5;
const LID_OPEN_X = -0.2 * Math.PI;
const DEG = Math.PI / 180;
@@ -59,6 +57,7 @@ interface Props {
}
let gltfCachePromise: Promise<THREE.Group> | null = null;
+
function loadLaptopGltf(): Promise<THREE.Group> {
if (!gltfCachePromise) {
gltfCachePromise = new Promise<THREE.Group>((resolve, reject) =>
@@ -93,8 +92,7 @@ function ModelScene({
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera } = useThree();
-
+ const { gl, scene, camera, invalidate } = useThree();
const orbitRef = useRef<OrbitControlsType | null>(null);
const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);
const lidGroupRef = useRef<THREE.Group | null>(null);
@@ -103,10 +101,13 @@ function ModelScene({
const lastLoadedUrlRef = useRef<string | null>(null);
const lastLoadedCropKeyRef = useRef<string | null>(null);
const onApiRef = useRef(onApi);
- useLayoutEffect(() => { onApiRef.current = onApi; });
+
+ useLayoutEffect(() => {
+ onApiRef.current = onApi;
+ });
const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D({
- defaultEnvironment: "forest"
+ defaultEnvironment: "forest",
});
useFrame(() => {
@@ -121,6 +122,7 @@ function ModelScene({
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
+
const RENDER_PIXEL_RATIO = 2;
const maxTexSize = gl.capabilities.maxTextureSize || 4096;
const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
@@ -129,29 +131,37 @@ function ModelScene({
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
+
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
gl.render(scene, cam);
},
restorePreview: () => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
+
const freshW = gl.domElement.clientWidth;
const freshH = gl.domElement.clientHeight;
+
(cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(3);
+
+ gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+ invalidate();
},
hasBuiltInShadow: true,
};
+
capturedOnApi?.(api);
return () => capturedOnApi?.(null);
- }, [gl, scene, camera, cameraRef]);
+ }, [gl, scene, camera, cameraRef, invalidate]);
const applyTexture = useCallback(() => {
if (videoElement) return;
+
const mat = screenMatRef.current;
if (!mat) return;
@@ -169,7 +179,6 @@ function ModelScene({
const TEX_W = RENDER_W;
const TEX_H = RENDER_H;
-
const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);
if (currentMat.map) {
@@ -182,7 +191,7 @@ function ModelScene({
tex.colorSpace = THREE.SRGBColorSpace;
if (cover.width && cover.height) {
- tex.repeat.y = ((cover.width / cover.height) / screenSize[0]) * screenSize[1];
+ tex.repeat.y = (cover.width / cover.height / screenSize[0]) * screenSize[1];
}
tex.generateMipmaps = true;
@@ -196,6 +205,7 @@ function ModelScene({
lastLoadedUrlRef.current = placeholderKey;
lastLoadedCropKeyRef.current = null;
+ invalidate();
};
img.onerror = () => {
lastLoadedUrlRef.current = placeholderKey;
@@ -220,7 +230,6 @@ function ModelScene({
const TEX_W = RENDER_W;
const TEX_H = RENDER_H;
-
const cropped = applyCropToImage(img, cropArea);
const cover = createCoverScreenCanvas(cropped, TEX_W, TEX_H, 0, imageMaskConfig);
@@ -234,7 +243,7 @@ function ModelScene({
tex.colorSpace = THREE.SRGBColorSpace;
if (cover.width && cover.height) {
- tex.repeat.y = ((cover.width / cover.height) / screenSize[0]) * screenSize[1];
+ tex.repeat.y = (cover.width / cover.height / screenSize[0]) * screenSize[1];
}
tex.generateMipmaps = true;
@@ -248,15 +257,14 @@ function ModelScene({
lastLoadedUrlRef.current = imageUrl;
lastLoadedCropKeyRef.current = cropKey;
+ invalidate();
};
-
img.onerror = () => {
lastLoadedUrlRef.current = imageUrl;
lastLoadedCropKeyRef.current = cropKey;
};
-
img.src = imageUrl;
- }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement]);
+ }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
const applyVideoTextureIfReady = useCallback(() => {
const mat = screenMatRef.current;
@@ -268,8 +276,9 @@ function ModelScene({
mat.map = tex;
mat.color.set(0xffffff);
mat.needsUpdate = true;
+ invalidate();
}
- }, []);
+ }, [invalidate]);
useEffect(() => {
if (!videoElement) {
@@ -279,6 +288,7 @@ function ModelScene({
}
return;
}
+
const tex = new THREE.VideoTexture(videoElement);
tex.flipY = false;
tex.colorSpace = THREE.SRGBColorSpace;
@@ -287,6 +297,7 @@ function ModelScene({
tex.magFilter = THREE.LinearFilter;
tex.wrapS = THREE.ClampToEdgeWrapping;
tex.wrapT = THREE.ClampToEdgeWrapping;
+
if (videoTextureRef.current) {
videoTextureRef.current.dispose();
}
@@ -320,24 +331,25 @@ function ModelScene({
const baseMetalMaterial = new THREE.MeshStandardMaterial({ color: 0xcecfd3, roughness: 0.25, metalness: 0.85 });
const tStart = Math.max(0, Math.min(1, openingProgress));
-
const screenMaterial = new THREE.MeshBasicMaterial({
map: null,
transparent: true,
opacity: 0.96 * tStart,
side: THREE.BackSide,
color: 0xffffff,
- toneMapped: false
+ toneMapped: false,
});
screenMatRef.current = screenMaterial;
applyVideoTextureIfReady();
const textLoader = new THREE.TextureLoader();
const keyboardMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, toneMapped: false });
+
textLoader.load("/images/pages/keyboard-overlay.png", (tex) => {
tex.anisotropy = gl.capabilities.getMaxAnisotropy();
keyboardMaterial.alphaMap = tex;
keyboardMaterial.needsUpdate = true;
+ invalidate();
});
const finalizeSetup = (group: THREE.Group) => {
@@ -347,66 +359,77 @@ function ModelScene({
if (!isMounted) return;
applyTextureRef.current();
onLoaded?.();
+ invalidate();
}, 50);
};
- loadLaptopGltf().then((cachedGltf) => {
- const root = cachedGltf.clone(true);
- root.position.z = -10;
-
- const lidGroup = new THREE.Group();
- const bottomGroup = new THREE.Group();
-
- ;[...root.children].forEach((child) => {
- if (child.name === "_top") {
- lidGroup.add(child);
- ;[...child.children].forEach((obj) => {
- if (!(obj instanceof THREE.Mesh)) return;
- const m = obj as THREE.Mesh;
- if (m.name === "lid") m.material = baseMetalMaterial;
- else if (m.name === "logo") m.material = logoMaterial;
- else if (m.name === "screen-frame") m.material = darkPlasticMaterial;
- else if (m.name === "camera") m.material = cameraMaterial;
- });
- } else if (child.name === "_bottom") {
- bottomGroup.add(child);
- ;[...child.children].forEach((obj) => {
- if (!(obj instanceof THREE.Mesh)) return;
- const m = obj as THREE.Mesh;
- if (m.name === "base") m.material = baseMetalMaterial;
- else if (["legs", "keyboard", "inner"].includes(m.name)) m.material = darkPlasticMaterial;
- });
- }
+ loadLaptopGltf()
+ .then((cachedGltf) => {
+ const root = cachedGltf.clone(true);
+ root.position.z = -10;
+
+ const lidGroup = new THREE.Group();
+ const bottomGroup = new THREE.Group();
+
+ [...root.children].forEach((child) => {
+ if (child.name === "_top") {
+ lidGroup.add(child);
+ [...child.children].forEach((obj) => {
+ if (!(obj instanceof THREE.Mesh)) return;
+ const m = obj as THREE.Mesh;
+ if (m.name === "lid") m.material = baseMetalMaterial;
+ else if (m.name === "logo") m.material = logoMaterial;
+ else if (m.name === "screen-frame") m.material = darkPlasticMaterial;
+ else if (m.name === "camera") m.material = cameraMaterial;
+ });
+ } else if (child.name === "_bottom") {
+ bottomGroup.add(child);
+ [...child.children].forEach((obj) => {
+ if (!(obj instanceof THREE.Mesh)) return;
+ const m = obj as THREE.Mesh;
+ if (m.name === "base") m.material = baseMetalMaterial;
+ else if (["legs", "keyboard", "inner"].includes(m.name)) m.material = darkPlasticMaterial;
+ });
+ }
+ });
+
+ root.add(lidGroup);
+ root.add(bottomGroup);
+ lidGroupRef.current = lidGroup;
+
+ const screenMesh = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), screenMaterial);
+ screenMesh.position.set(0, 10.5, -0.11);
+ screenMesh.rotation.set(Math.PI, 0, 0);
+ lidGroup.add(screenMesh);
+
+ const darkScreen = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), darkPlasticMaterial);
+ darkScreen.position.set(0, 10.5, -0.111);
+ darkScreen.rotation.set(Math.PI, Math.PI, 0);
+ lidGroup.add(darkScreen);
+
+ const keyboardKeys = new THREE.Mesh(new THREE.PlaneGeometry(27.7, 11.6), keyboardMaterial);
+ keyboardKeys.rotation.set(-0.5 * Math.PI, 0, 0);
+ keyboardKeys.position.set(0, 0.045, 7.21);
+ bottomGroup.add(keyboardKeys);
+
+ finalizeSetup(root);
+ })
+ .catch((err) => {
+ console.error("Error al cargar el GLB del laptop:", err);
});
- root.add(lidGroup);
- root.add(bottomGroup);
- lidGroupRef.current = lidGroup;
-
- const screenMesh = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), screenMaterial);
- screenMesh.position.set(0, 10.5, -0.11);
- screenMesh.rotation.set(Math.PI, 0, 0);
- lidGroup.add(screenMesh);
-
- const darkScreen = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), darkPlasticMaterial);
- darkScreen.position.set(0, 10.5, -0.111);
- darkScreen.rotation.set(Math.PI, Math.PI, 0);
- lidGroup.add(darkScreen);
-
- const keyboardKeys = new THREE.Mesh(new THREE.PlaneGeometry(27.7, 11.6), keyboardMaterial);
- keyboardKeys.rotation.set(-0.5 * Math.PI, 0, 0);
- keyboardKeys.position.set(0, 0.045, 7.21);
- bottomGroup.add(keyboardKeys);
-
- finalizeSetup(root);
- }).catch((err) => {
- console.error("Error al cargar el GLB del laptop:", err);
- });
-
return () => {
isMounted = false;
+ darkPlasticMaterial.dispose();
+ cameraMaterial.dispose();
+ logoMaterial.dispose();
+ baseMetalMaterial.dispose();
+ keyboardMaterial.dispose();
+ if (screenMatRef.current) {
+ screenMatRef.current.dispose();
+ }
};
- }, []);
+ }, [openingProgress, applyVideoTextureIfReady, onLoaded, gl, invalidate]);
const prevRotationRef = useRef({ x: initialRotationX, y: initialRotationY });
@@ -418,14 +441,20 @@ function ModelScene({
const radius = CAM_RADIUS / zoom;
const phi = Math.PI / 2 - initialRotationX * DEG;
const theta = initialRotationY * DEG;
+
orbit.object.position.setFromSphericalCoords(radius, phi, theta);
orbit.update();
+ invalidate();
+
prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
- }, [initialRotationX, initialRotationY, zoom]);
+ }, [initialRotationX, initialRotationY, zoom, invalidate]);
useEffect(() => {
- if (rootRef.current) rootRef.current.rotation.z = initialRotationZ * DEG;
- }, [initialRotationZ, modelGroup]);
+ if (rootRef.current) {
+ rootRef.current.rotation.z = initialRotationZ * DEG;
+ invalidate();
+ }
+ }, [initialRotationZ, modelGroup, invalidate]);
useEffect(() => {
const lid = lidGroupRef.current;
@@ -434,12 +463,12 @@ function ModelScene({
const t = Math.max(0, Math.min(1, openingProgress));
lid.rotation.x = lerp(LID_CLOSED_X, LID_OPEN_X, t);
mat.opacity = 0.96 * t;
- }, [openingProgress, modelGroup]);
+ invalidate();
+ }, [openingProgress, modelGroup, invalidate]);
return (
<>
<PerspectiveCamera ref={cameraRef} makeDefault fov={CAM_FOV} near={10} far={1000} position={[0, 0, CAM_RADIUS / zoom]} />
-
<OrbitControls
ref={orbitRef}
enableZoom={false}
@@ -456,13 +485,7 @@ function ModelScene({
onRotationChange(rx, ry);
}}
/>
-
- <Environment
- preset={environment as EnvironmentPreset}
- environmentIntensity={glow}
- background={false}
- />
-
+ <Environment preset={environment as EnvironmentPreset} environmentIntensity={glow} background={false} />
<ambientLight intensity={3.2} />
<group>
<pointLight position={[0, 5, 50]} intensity={0.8} color="#fff5e1" />
@@ -470,7 +493,6 @@ function ModelScene({
<directionalLight position={[4, 8, 7]} intensity={2.6} />
<directionalLight position={[-5, -2, 4]} intensity={0.8} color="#aabbff" />
<directionalLight position={[0, -6, 6]} intensity={1.3} />
-
<group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
{modelGroup && <primitive object={modelGroup} />}
</group>
@@ -478,7 +500,12 @@ function ModelScene({
);
}
-function CanvasWithLoader(props: Props & { rootRef: React.MutableRefObject<THREE.Group | null>; cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>; }) {
+function CanvasWithLoader(
+ props: Props & {
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ }
+) {
const [loaded, setLoaded] = useState(false);
const handleLoaded = useCallback(() => setLoaded(true), []);
@@ -490,9 +517,10 @@ function CanvasWithLoader(props: Props & { rootRef: React.MutableRefObject<THREE
antialias: true,
alpha: true,
preserveDrawingBuffer: true,
- powerPreference: "high-performance"
+ powerPreference: "high-performance",
}}
- dpr={Math.min((typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1) * RENDER_MULTIPLIER, 4)}
+ dpr={3}
+ frameloop={props.videoElement ? "always" : "demand"}
resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
onCreated={({ gl }) => {
gl.setClearColor(0x000000, 0);
@@ -517,7 +545,6 @@ function CanvasWithLoader(props: Props & { rootRef: React.MutableRefObject<THREE
export function Laptop3DViewer(props: Props) {
const { shadowIntensity = 0, shadowColor = "#000000" } = props;
-
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
const [grabbing, setGrabbing] = useState(false);
@@ -526,17 +553,12 @@ export function Laptop3DViewer(props: Props) {
const tEased = t * t;
const computedBlur = tEased * 60;
const computedOpacity = tEased * 0.7;
-
- const shadowRgba = shadowColor.startsWith("#")
- ? parseShadowColor(shadowColor, computedOpacity)
- : shadowColor;
-
+ const shadowRgba = shadowColor.startsWith("#") ? parseShadowColor(shadowColor, computedOpacity) : shadowColor;
const hasShadow = t > 0.01;
return (
<>
<ControlsPopup />
-
<div
style={{
display: "inline-block",
@@ -572,7 +594,6 @@ export function Laptop3DViewer(props: Props) {
}}
/>
)}
-
<div
style={{
position: "absolute",
diff --git a/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx b/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
index 59a0b88..e6242da 100644
--- a/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
@@ -6,44 +6,45 @@ import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } f
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import {
- PHONE_W,
- PHONE_H,
- deviceConfigs,
- getDeviceFromModelUrl,
- createCoverScreenCanvas,
- applyCropToImage,
- loadGltfGroup,
- cloneGroup,
- type ImageMaskConfigLike,
- parseShadowColor,
+ PHONE_W,
+ PHONE_H,
+ deviceConfigs,
+ getDeviceFromModelUrl,
+ createCoverScreenCanvas,
+ applyCropToImage,
+ loadGltfGroup,
+ cloneGroup,
+ type ImageMaskConfigLike,
+ parseShadowColor,
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
-
import { ControlsPopup } from "@/components/ui/ControlsPopup";
import { EnvironmentPreset, ViewerControls3D } from "@/lib/viewer-controls3d";
+THREE.Cache.enabled = true;
+
export interface Phone3DApi {
- renderAt: (width: number, height: number) => void;
- restorePreview: () => void;
- hasBuiltInShadow: boolean;
+ renderAt: (width: number, height: number) => void;
+ restorePreview: () => void;
+ hasBuiltInShadow: boolean;
}
interface Props {
- imageUrl?: string | null;
- imageMaskConfig?: ImageMaskConfigLike | null;
- cropArea?: { x: number; y: number; width: number; height: number } | null;
- initialRotationX?: number;
- initialRotationY?: number;
- initialRotationZ?: number;
- onRotationChange?: (rx: number, ry: number) => void;
- onMount?: (canvas: HTMLCanvasElement) => void;
- onApi?: (api: Phone3DApi | null) => void;
- modelUrl?: string;
- scale?: number;
- zoom?: number;
- shadowIntensity?: number;
- shadowColor?: string;
- videoElement?: HTMLVideoElement | null;
+ imageUrl?: string | null;
+ imageMaskConfig?: ImageMaskConfigLike | null;
+ cropArea?: { x: number; y: number; width: number; height: number } | null;
+ initialRotationX?: number;
+ initialRotationY?: number;
+ initialRotationZ?: number;
+ onRotationChange?: (rx: number, ry: number) => void;
+ onMount?: (canvas: HTMLCanvasElement) => void;
+ onApi?: (api: Phone3DApi | null) => void;
+ modelUrl?: string;
+ scale?: number;
+ zoom?: number;
+ shadowIntensity?: number;
+ shadowColor?: string;
+ videoElement?: HTMLVideoElement | null;
}
const DEG = Math.PI / 180;
@@ -51,606 +52,675 @@ const specificGltfCache = new Map<string, Promise<THREE.Group>>();
const PLACEHOLDER_PHONE_URL = "/images/mockups-3d/placeholder-phone.avif";
function loadSpecificGltf(url: string): Promise<THREE.Group> {
- if (!specificGltfCache.has(url)) {
- specificGltfCache.set(
- url,
- new Promise((resolve, reject) => {
- new GLTFLoader().load(url, (gltf) => resolve(gltf.scene), undefined, reject);
- })
- );
- }
- return specificGltfCache.get(url)!;
+ if (!specificGltfCache.has(url)) {
+ specificGltfCache.set(
+ url,
+ new Promise((resolve, reject) => {
+ new GLTFLoader().load(url, (gltf) => resolve(gltf.scene), undefined, reject);
+ })
+ );
+ }
+ return specificGltfCache.get(url)!;
}
function applyMetalMaterial(m: THREE.MeshStandardMaterial, matName: string): void {
- if (matName.includes("Body")) {
- m.color.set(0x787878); m.roughness = 0.18; m.metalness = 0.85; m.envMapIntensity = 1.4;
- }
- if (matName.includes("Bezel")) {
- m.color.set(0x909090); m.roughness = 0.12; m.metalness = 0.92; m.envMapIntensity = 1.6;
- }
- if (matName.includes("Buttons")) {
- m.color.set(0x999999); m.roughness = 0.15; m.metalness = 0.88; m.envMapIntensity = 1.5;
- }
- if (matName.includes("Lenses")) {
- m.color.set(0x060608); m.roughness = 0.04; m.metalness = 0.70; m.envMapIntensity = 2.0;
- }
+ if (matName.includes("Body")) {
+ m.color.set(0x787878);
+ m.roughness = 0.18;
+ m.metalness = 0.85;
+ m.envMapIntensity = 1.4;
+ }
+ if (matName.includes("Bezel")) {
+ m.color.set(0x909090);
+ m.roughness = 0.12;
+ m.metalness = 0.92;
+ m.envMapIntensity = 1.6;
+ }
+ if (matName.includes("Buttons")) {
+ m.color.set(0x999999);
+ m.roughness = 0.15;
+ m.metalness = 0.88;
+ m.envMapIntensity = 1.5;
+ }
+ if (matName.includes("Lenses")) {
+ m.color.set(0x060608);
+ m.roughness = 0.04;
+ m.metalness = 0.70;
+ m.envMapIntensity = 2.0;
+ }
}
function ModelScene({
- imageUrl,
- imageMaskConfig,
- cropArea,
- initialRotationX = -58.23,
- initialRotationY = -29,
- initialRotationZ = 0,
- onRotationChange,
- rootRef,
- cameraRef,
- zoom = 1,
- modelUrl,
- onApi,
- onLoaded,
- videoElement,
+ imageUrl,
+ imageMaskConfig,
+ cropArea,
+ initialRotationX = -58.23,
+ initialRotationY = -29,
+ initialRotationZ = 0,
+ onRotationChange,
+ rootRef,
+ cameraRef,
+ zoom = 1,
+ modelUrl,
+ onApi,
+ onLoaded,
+ videoElement,
}: Props & {
- rootRef: React.MutableRefObject<THREE.Group | null>;
- cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
- onLoaded?: () => void;
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ onLoaded?: () => void;
}) {
- const { gl, scene, camera } = useThree();
-
- const orbitRef = useRef<OrbitControlsType | null>(null);
- const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
- const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
- const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);
- const lastLoadedUrlRef = useRef<string | null>(null);
- const lastLoadedCropKeyRef = useRef<string | null>(null);
- const screenAspectRef = useRef<number>(0.459);
- const flipYRef = useRef<boolean>(false);
- const onApiRef = useRef(onApi);
- useLayoutEffect(() => { onApiRef.current = onApi; });
-
- const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D();
-
- useFrame(() => {
- if (videoElement && videoTextureRef.current) {
- videoTextureRef.current.needsUpdate = true;
- }
- });
-
- useEffect(() => {
- const capturedOnApi = onApiRef.current;
- const RENDER_PIXEL_RATIO = 2;
- const api: Phone3DApi = {
- renderAt: (w, h) => {
- const cam = cameraRef.current ?? camera;
- if (!cam) return;
-
- const maxTexSize = gl.capabilities.maxTextureSize || 4096;
- const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
- const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
- const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
-
- (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
- (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(RENDER_PIXEL_RATIO);
- gl.setSize(safeW, safeH, false);
- if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
- gl.render(scene, cam);
- },
- restorePreview: () => {
- const cam = cameraRef.current ?? camera;
- if (!cam) return;
- const freshW = gl.domElement.clientWidth;
- const freshH = gl.domElement.clientHeight;
- (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
- (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- gl.setPixelRatio(3);
- gl.setSize(freshW, freshH, false);
- },
- hasBuiltInShadow: true,
- };
- capturedOnApi?.(api);
- return () => capturedOnApi?.(null);
- }, [gl, scene, camera, cameraRef]);
-
- const applyTexture = useCallback(() => {
- if (videoElement) return;
- const mat = screenMatRef.current;
- if (!mat) return;
- const cropKey = cropArea ? JSON.stringify(cropArea) : null;
-
- if (!imageUrl) {
- const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
- if (lastLoadedUrlRef.current === placeholderKey) return;
-
- const device = getDeviceFromModelUrl(modelUrl);
- const deviceConfig = deviceConfigs[device];
- const isDefaultPhone = device === "phone";
-
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- const currentMat = screenMatRef.current;
- if (!currentMat) return;
-
- let TARGET_W = 2048;
- let TARGET_H = 0;
- let cornerRadius = 0;
- if (isDefaultPhone) {
- TARGET_W = PHONE_W * 4;
- TARGET_H = Math.round(TARGET_W / screenAspectRef.current);
- } else {
- TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
- cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
- }
-
- const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, cornerRadius, null);
-
- if (currentMat.map) {
- currentMat.map.dispose();
- currentMat.map = null;
- }
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = flipYRef.current;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- currentMat.map = tex;
- currentMat.color.set(0xffffff);
- currentMat.needsUpdate = true;
-
- lastLoadedUrlRef.current = placeholderKey;
- lastLoadedCropKeyRef.current = null;
- };
- img.onerror = () => {
- const currentMat = screenMatRef.current;
- if (!currentMat) return;
- if (currentMat.map) {
- currentMat.map.dispose();
- currentMat.map = null;
- }
- currentMat.color.set(0x1a1a1a);
- currentMat.needsUpdate = true;
- lastLoadedUrlRef.current = placeholderKey;
- };
- img.src = PLACEHOLDER_PHONE_URL;
- return;
- }
+ const { gl, scene, camera, invalidate } = useThree();
+ const orbitRef = useRef<OrbitControlsType | null>(null);
+ const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
+ const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
+ const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);
+ const lastLoadedUrlRef = useRef<string | null>(null);
+ const lastLoadedCropKeyRef = useRef<string | null>(null);
+ const screenAspectRef = useRef<number>(0.459);
+ const flipYRef = useRef<boolean>(false);
+ const onApiRef = useRef(onApi);
+
+ useLayoutEffect(() => {
+ onApiRef.current = onApi;
+ });
+
+ const { autoRotate, rotationSpeed, glow, environment } = ViewerControls3D();
+
+ useFrame(() => {
+ if (videoElement && videoTextureRef.current) {
+ videoTextureRef.current.needsUpdate = true;
+ }
+ });
- if (
- lastLoadedUrlRef.current === imageUrl &&
- lastLoadedCropKeyRef.current === cropKey &&
- mat.map !== null
- ) {
- return;
- }
- const device = getDeviceFromModelUrl(modelUrl);
- const deviceConfig = deviceConfigs[device];
- const isDefaultPhone = device === "phone";
- const img = new Image();
- img.crossOrigin = "anonymous";
- img.onload = () => {
- const currentMat = screenMatRef.current;
- if (!currentMat) return;
- let TARGET_W = 2048;
- let TARGET_H = 0;
- let cornerRadius = 0;
- if (isDefaultPhone) {
- TARGET_W = PHONE_W * 4;
- TARGET_H = Math.round(TARGET_W / screenAspectRef.current);
- } else {
- TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
- cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
- }
- const cropped = applyCropToImage(img, cropArea);
- const cover = createCoverScreenCanvas(
- cropped,
- TARGET_W,
- TARGET_H,
- cornerRadius,
- imageMaskConfig
- );
- if (currentMat.map) {
- currentMat.map.dispose();
- currentMat.map = null;
- }
- const tex = new THREE.CanvasTexture(cover);
- tex.flipY = flipYRef.current;
- tex.colorSpace = THREE.SRGBColorSpace;
- tex.generateMipmaps = true;
- tex.minFilter = THREE.LinearMipmapLinearFilter;
- tex.magFilter = THREE.LinearFilter;
- tex.wrapS = THREE.ClampToEdgeWrapping;
- tex.wrapT = THREE.ClampToEdgeWrapping;
- tex.anisotropy = gl.capabilities.getMaxAnisotropy();
- currentMat.map = tex;
- currentMat.color.set(0xffffff);
- currentMat.needsUpdate = true;
- lastLoadedUrlRef.current = imageUrl;
- lastLoadedCropKeyRef.current = cropKey;
- };
- img.onerror = () => {
- const currentMat = screenMatRef.current;
- if (!currentMat) return;
- if (currentMat.map) {
- currentMat.map.dispose();
- currentMat.map = null;
- }
- currentMat.color.set(0x111111);
- currentMat.needsUpdate = true;
- lastLoadedUrlRef.current = imageUrl;
- lastLoadedCropKeyRef.current = cropKey;
- };
- img.src = imageUrl;
- }, [imageUrl, imageMaskConfig, cropArea, modelUrl, gl, videoElement]);
-
- const applyVideoTextureIfReady = useCallback(() => {
- const mat = screenMatRef.current;
- const tex = videoTextureRef.current;
- if (mat && tex) {
- if (mat.map && mat.map !== tex) {
- mat.map.dispose();
- }
-
- const device = getDeviceFromModelUrl(modelUrl);
- const isDefaultPhone = device === "phone";
-
- tex.flipY = !isDefaultPhone;
- tex.needsUpdate = true;
-
- mat.map = tex;
- mat.color.set(0xffffff);
- mat.needsUpdate = true;
- }
- }, [modelUrl]);
-
- useEffect(() => {
- if (!videoElement) {
- if (videoTextureRef.current) {
- videoTextureRef.current.dispose();
- videoTextureRef.current = null;
- }
- return;
- }
+ useEffect(() => {
+ const capturedOnApi = onApiRef.current;
+ const RENDER_PIXEL_RATIO = 2;
+
+ const api: Phone3DApi = {
+ renderAt: (w, h) => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+
+ const maxTexSize = gl.capabilities.maxTextureSize || 4096;
+ const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
+ const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
+ const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
- const device = getDeviceFromModelUrl(modelUrl);
- const isDefaultPhone = device === "phone";
+ (cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
- const tex = new THREE.VideoTexture(videoElement);
+ gl.setPixelRatio(RENDER_PIXEL_RATIO);
+ gl.setSize(safeW, safeH, false);
- tex.flipY = !isDefaultPhone;
+ if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+ gl.render(scene, cam);
+ },
+ restorePreview: () => {
+ const cam = cameraRef.current ?? camera;
+ if (!cam) return;
+ const freshW = gl.domElement.clientWidth;
+ const freshH = gl.domElement.clientHeight;
+
+ (cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
+ (cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
+ gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
+ gl.setSize(freshW, freshH, false);
+ },
+ hasBuiltInShadow: true,
+ };
+
+ capturedOnApi?.(api);
+ return () => capturedOnApi?.(null);
+ }, [gl, scene, camera, cameraRef]);
+
+ const applyTexture = useCallback(() => {
+ if (videoElement) return;
+
+ const mat = screenMatRef.current;
+ if (!mat) return;
+
+ const cropKey = cropArea ? JSON.stringify(cropArea) : null;
+
+ if (!imageUrl) {
+ const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
+ if (lastLoadedUrlRef.current === placeholderKey) return;
+
+ const device = getDeviceFromModelUrl(modelUrl);
+ const deviceConfig = deviceConfigs[device];
+ const isDefaultPhone = device === "phone";
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const currentMat = screenMatRef.current;
+ if (!currentMat) return;
+
+ let TARGET_W = 2048;
+ let TARGET_H = 0;
+ let cornerRadius = 0;
+
+ if (isDefaultPhone) {
+ TARGET_W = PHONE_W * 4;
+ TARGET_H = Math.round(TARGET_W / screenAspectRef.current);
+ } else {
+ TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
+ cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
+ }
+
+ const cover = createCoverScreenCanvas(img, TARGET_W, TARGET_H, cornerRadius, null);
+
+ if (currentMat.map) {
+ currentMat.map.dispose();
+ currentMat.map = null;
+ }
+
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = flipYRef.current;
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
tex.magFilter = THREE.LinearFilter;
tex.wrapS = THREE.ClampToEdgeWrapping;
tex.wrapT = THREE.ClampToEdgeWrapping;
-
- if (videoTextureRef.current) {
- videoTextureRef.current.dispose();
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+
+ currentMat.map = tex;
+ currentMat.color.set(0xffffff);
+ currentMat.needsUpdate = true;
+
+ lastLoadedUrlRef.current = placeholderKey;
+ lastLoadedCropKeyRef.current = null;
+ invalidate();
+ };
+ img.onerror = () => {
+ const currentMat = screenMatRef.current;
+ if (!currentMat) return;
+ if (currentMat.map) {
+ currentMat.map.dispose();
+ currentMat.map = null;
}
- videoTextureRef.current = tex;
- applyVideoTextureIfReady();
+ currentMat.color.set(0x1a1a1a);
+ currentMat.needsUpdate = true;
+ lastLoadedUrlRef.current = placeholderKey;
+ invalidate();
+ };
+ img.src = PLACEHOLDER_PHONE_URL;
+ return;
+ }
- return () => {
- if (videoTextureRef.current === tex) {
- videoTextureRef.current = null;
- }
- tex.dispose();
- };
- }, [videoElement, modelUrl, applyVideoTextureIfReady]);
-
- const applyTextureRef = useRef(applyTexture);
- useEffect(() => {
- applyTextureRef.current = applyTexture;
- }, [applyTexture]);
-
- useEffect(() => {
- applyTexture();
- }, [applyTexture]);
-
- useEffect(() => {
- let isMounted = true;
- const device = getDeviceFromModelUrl(modelUrl);
- const isDefaultPhone = device === "phone";
- const finalizeSetup = (group: THREE.Group) => {
- if (!isMounted) return;
- setModelGroup(group);
- setTimeout(() => {
- if (!isMounted) return;
- applyTextureRef.current();
- onLoaded?.();
- }, 50);
- };
- if (isDefaultPhone) {
- flipYRef.current = false;
- loadGltfGroup().then((cached) => {
- const group = cloneGroup(cached);
- const camZ = 1.5;
- const box = new THREE.Box3().setFromObject(group);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
- const halfH = camZ * Math.tan((40 / 2) * DEG);
- const sf = (halfH * 2 * 0.8) / size.y;
- group.scale.setScalar(sf);
- group.position.copy(center).negate().multiplyScalar(sf);
- group.traverse((child) => {
- if (!(child instanceof THREE.Mesh)) return;
- const mat = Array.isArray(child.material) ? child.material[0] : child.material;
- const matName = (mat as THREE.Material)?.name ?? "";
- const isScreen = matName === "Screen.editable" || child.name === "Screen";
- if (isScreen) {
- const meshBox = new THREE.Box3().setFromObject(child);
- const meshSize = meshBox.getSize(new THREE.Vector3());
- if (meshSize.x > 0 && meshSize.y > 0) screenAspectRef.current = meshSize.x / meshSize.y;
- const basicMat = new THREE.MeshBasicMaterial({
- color: 0x111111,
- side: THREE.FrontSide,
- transparent: true,
- depthTest: false,
- depthWrite: false,
- });
- child.material = basicMat;
- child.renderOrder = 10;
- screenMatRef.current = basicMat;
- applyVideoTextureIfReady();
- } else if (mat.isMeshStandardMaterial) {
- applyMetalMaterial(mat, matName);
- }
- });
- finalizeSetup(group);
- });
- } else {
- flipYRef.current = true;
- loadSpecificGltf(modelUrl!).then((loadedScene) => {
- const group = loadedScene.clone(true);
- const camZ = 1.5;
- const box = new THREE.Box3().setFromObject(group);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
- const halfH = camZ * Math.tan((40 / 2) * DEG);
- const sf = (halfH * 2 * 0.6) / size.y;
- group.scale.setScalar(sf);
- group.position.copy(center).negate().multiplyScalar(sf);
- const deviceConfig = deviceConfigs[device];
- const planeH = 4.3 * deviceConfig.screenHeightFactor;
- const planeW = planeH * deviceConfig.aspectRatio;
- const cornerRadius = planeH * (deviceConfig.cornerRadiusFactor ?? 0);
- const basicMat = new THREE.MeshBasicMaterial({
- color: 0x111111,
- side: THREE.FrontSide,
- transparent: true,
- depthTest: false,
- depthWrite: false,
- });
- screenMatRef.current = basicMat;
- applyVideoTextureIfReady();
- const hw = planeW / 2;
- const hh = planeH / 2;
-
- const baseRadius = Math.min(cornerRadius, Math.min(hw, hh));
-
- const REDUCTION_FACTOR = 0.40;
- const r = baseRadius * REDUCTION_FACTOR;
-
- const shape = new THREE.Shape();
- shape.moveTo(-hw + r, -hh);
- shape.lineTo(hw - r, -hh);
- shape.quadraticCurveTo(hw, -hh, hw, -hh + r);
- shape.lineTo(hw, hh - r);
- shape.quadraticCurveTo(hw, hh, hw - r, hh);
- shape.lineTo(-hw + r, hh);
- shape.quadraticCurveTo(-hw, hh, -hw, hh - r);
- shape.lineTo(-hw, -hh + r);
- shape.quadraticCurveTo(-hw, -hh, -hw + r, -hh);
- const plane = new THREE.Mesh(new THREE.ShapeGeometry(shape), basicMat);
- const uvAttr = plane.geometry.getAttribute("uv") as THREE.BufferAttribute;
- for (let i = 0; i < uvAttr.count; i++) {
- const x = plane.geometry.getAttribute("position").getX(i);
- const y = plane.geometry.getAttribute("position").getY(i);
- uvAttr.setXY(i, (x + hw) / planeW, (y + hh) / planeH);
- }
- uvAttr.needsUpdate = true;
- plane.position.set(deviceConfig.screenOffset.x, deviceConfig.screenOffset.y, deviceConfig.screenOffset.z);
- plane.renderOrder = 10;
- group.add(plane);
- finalizeSetup(group);
+ if (
+ lastLoadedUrlRef.current === imageUrl &&
+ lastLoadedCropKeyRef.current === cropKey &&
+ mat.map !== null
+ ) {
+ return;
+ }
+
+ const device = getDeviceFromModelUrl(modelUrl);
+ const deviceConfig = deviceConfigs[device];
+ const isDefaultPhone = device === "phone";
+
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ const currentMat = screenMatRef.current;
+ if (!currentMat) return;
+
+ let TARGET_W = 2048;
+ let TARGET_H = 0;
+ let cornerRadius = 0;
+
+ if (isDefaultPhone) {
+ TARGET_W = PHONE_W * 4;
+ TARGET_H = Math.round(TARGET_W / screenAspectRef.current);
+ } else {
+ TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
+ cornerRadius = Math.round(TARGET_W * deviceConfig.cornerRadiusFactor);
+ }
+
+ const cropped = applyCropToImage(img, cropArea);
+ const cover = createCoverScreenCanvas(
+ cropped,
+ TARGET_W,
+ TARGET_H,
+ cornerRadius,
+ imageMaskConfig
+ );
+
+ if (currentMat.map) {
+ currentMat.map.dispose();
+ currentMat.map = null;
+ }
+
+ const tex = new THREE.CanvasTexture(cover);
+ tex.flipY = flipYRef.current;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.anisotropy = gl.capabilities.getMaxAnisotropy();
+
+ currentMat.map = tex;
+ currentMat.color.set(0xffffff);
+ currentMat.needsUpdate = true;
+
+ lastLoadedUrlRef.current = imageUrl;
+ lastLoadedCropKeyRef.current = cropKey;
+ invalidate();
+ };
+ img.onerror = () => {
+ const currentMat = screenMatRef.current;
+ if (!currentMat) return;
+ if (currentMat.map) {
+ currentMat.map.dispose();
+ currentMat.map = null;
+ }
+ currentMat.color.set(0x111111);
+ currentMat.needsUpdate = true;
+ lastLoadedUrlRef.current = imageUrl;
+ lastLoadedCropKeyRef.current = cropKey;
+ invalidate();
+ };
+ img.src = imageUrl;
+ }, [imageUrl, imageMaskConfig, cropArea, modelUrl, gl, videoElement, invalidate]);
+
+ const applyVideoTextureIfReady = useCallback(() => {
+ const mat = screenMatRef.current;
+ const tex = videoTextureRef.current;
+
+ if (mat && tex) {
+ if (mat.map && mat.map !== tex) {
+ mat.map.dispose();
+ }
+ const device = getDeviceFromModelUrl(modelUrl);
+ const isDefaultPhone = device === "phone";
+ tex.flipY = !isDefaultPhone;
+ tex.needsUpdate = true;
+
+ mat.map = tex;
+ mat.color.set(0xffffff);
+ mat.needsUpdate = true;
+ invalidate();
+ }
+ }, [modelUrl, invalidate]);
+
+ useEffect(() => {
+ if (!videoElement) {
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ videoTextureRef.current = null;
+ }
+ return;
+ }
+
+ const device = getDeviceFromModelUrl(modelUrl);
+ const isDefaultPhone = device === "phone";
+
+ const tex = new THREE.VideoTexture(videoElement);
+ tex.flipY = !isDefaultPhone;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.generateMipmaps = true;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.wrapS = THREE.ClampToEdgeWrapping;
+ tex.wrapT = THREE.ClampToEdgeWrapping;
+
+ if (videoTextureRef.current) {
+ videoTextureRef.current.dispose();
+ }
+ videoTextureRef.current = tex;
+
+ applyVideoTextureIfReady();
+
+ return () => {
+ if (videoTextureRef.current === tex) {
+ videoTextureRef.current = null;
+ }
+ tex.dispose();
+ };
+ }, [videoElement, modelUrl, applyVideoTextureIfReady]);
+
+ const applyTextureRef = useRef(applyTexture);
+
+ useEffect(() => {
+ applyTextureRef.current = applyTexture;
+ }, [applyTexture]);
+
+ useEffect(() => {
+ applyTexture();
+ }, [applyTexture]);
+
+ useEffect(() => {
+ let isMounted = true;
+ const device = getDeviceFromModelUrl(modelUrl);
+ const isDefaultPhone = device === "phone";
+
+ const finalizeSetup = (group: THREE.Group) => {
+ if (!isMounted) return;
+ setModelGroup(group);
+ setTimeout(() => {
+ if (!isMounted) return;
+ applyTextureRef.current();
+ onLoaded?.();
+ invalidate();
+ }, 50);
+ };
+
+ if (isDefaultPhone) {
+ flipYRef.current = false;
+ loadGltfGroup().then((cached) => {
+ const group = cloneGroup(cached);
+ const camZ = 1.5;
+
+ const box = new THREE.Box3().setFromObject(group);
+ const center = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
+
+ const halfH = camZ * Math.tan((40 / 2) * DEG);
+ const sf = (halfH * 2 * 0.8) / size.y;
+
+ group.scale.setScalar(sf);
+ group.position.copy(center).negate().multiplyScalar(sf);
+
+ group.traverse((child) => {
+ if (!(child instanceof THREE.Mesh)) return;
+ const mat = Array.isArray(child.material) ? child.material[0] : child.material;
+ const matName = (mat as THREE.Material)?.name ?? "";
+
+ const isScreen = matName === "Screen.editable" || child.name === "Screen";
+
+ if (isScreen) {
+ const meshBox = new THREE.Box3().setFromObject(child);
+ const meshSize = meshBox.getSize(new THREE.Vector3());
+ if (meshSize.x > 0 && meshSize.y > 0) screenAspectRef.current = meshSize.x / meshSize.y;
+
+ const basicMat = new THREE.MeshBasicMaterial({
+ color: 0x111111,
+ side: THREE.FrontSide,
+ transparent: true,
+ depthTest: false,
+ depthWrite: false,
});
+
+ child.material = basicMat;
+ child.renderOrder = 10;
+ screenMatRef.current = basicMat;
+ applyVideoTextureIfReady();
+ } else if (mat.isMeshStandardMaterial) {
+ applyMetalMaterial(mat, matName);
+ }
+ });
+
+ finalizeSetup(group);
+ });
+ } else {
+ flipYRef.current = true;
+ loadSpecificGltf(modelUrl!).then((loadedScene) => {
+ const group = loadedScene.clone(true);
+ const camZ = 1.5;
+
+ const box = new THREE.Box3().setFromObject(group);
+ const center = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3());
+
+ const halfH = camZ * Math.tan((40 / 2) * DEG);
+ const sf = (halfH * 2 * 0.6) / size.y;
+
+ group.scale.setScalar(sf);
+ group.position.copy(center).negate().multiplyScalar(sf);
+
+ const deviceConfig = deviceConfigs[device];
+ const planeH = 4.3 * deviceConfig.screenHeightFactor;
+ const planeW = planeH * deviceConfig.aspectRatio;
+ const cornerRadius = planeH * (deviceConfig.cornerRadiusFactor ?? 0);
+
+ const basicMat = new THREE.MeshBasicMaterial({
+ color: 0x111111,
+ side: THREE.FrontSide,
+ transparent: true,
+ depthTest: false,
+ depthWrite: false,
+ });
+
+ screenMatRef.current = basicMat;
+ applyVideoTextureIfReady();
+
+ const hw = planeW / 2;
+ const hh = planeH / 2;
+ const baseRadius = Math.min(cornerRadius, Math.min(hw, hh));
+ const REDUCTION_FACTOR = 0.40;
+ const r = baseRadius * REDUCTION_FACTOR;
+
+ const shape = new THREE.Shape();
+ shape.moveTo(-hw + r, -hh);
+ shape.lineTo(hw - r, -hh);
+ shape.quadraticCurveTo(hw, -hh, hw, -hh + r);
+ shape.lineTo(hw, hh - r);
+ shape.quadraticCurveTo(hw, hh, hw - r, hh);
+ shape.lineTo(-hw + r, hh);
+ shape.quadraticCurveTo(-hw, hh, -hw, hh - r);
+ shape.lineTo(-hw, -hh + r);
+ shape.quadraticCurveTo(-hw, -hh, -hw + r, -hh);
+
+ const plane = new THREE.Mesh(new THREE.ShapeGeometry(shape), basicMat);
+ const uvAttr = plane.geometry.getAttribute("uv") as THREE.BufferAttribute;
+
+ for (let i = 0; i < uvAttr.count; i++) {
+ const x = plane.geometry.getAttribute("position").getX(i);
+ const y = plane.geometry.getAttribute("position").getY(i);
+ uvAttr.setXY(i, (x + hw) / planeW, (y + hh) / planeH);
}
- return () => {
- isMounted = false;
- };
- }, [modelUrl]);
-
- const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
-
- useEffect(() => {
- if (
- prevRotationRef.current?.x === initialRotationX &&
- prevRotationRef.current?.y === initialRotationY
- ) {
- return;
- }
+ uvAttr.needsUpdate = true;
- const id = setTimeout(() => {
- const orbit = orbitRef.current;
- if (!orbit) return;
-
- const radius = 1.5 / zoom;
- const phi = Math.PI / 2 - initialRotationX * DEG;
- const theta = initialRotationY * DEG;
-
- orbit.object.position.setFromSphericalCoords(radius, phi, theta);
- orbit.update();
-
- prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
- }, 0);
-
- return () => clearTimeout(id);
- }, [initialRotationX, initialRotationY, zoom]);
-
- useEffect(() => {
- if (rootRef.current) rootRef.current.rotation.z = initialRotationZ * DEG;
- }, [initialRotationZ]);
-
- return (
- <>
- <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={[0, 0, 1.5 / zoom]} />
-
- <OrbitControls
- ref={orbitRef}
- enableZoom={false}
- enablePan={false}
- enableDamping
- dampingFactor={0.08}
- autoRotate={autoRotate}
- autoRotateSpeed={rotationSpeed}
- onEnd={() => {
- const orbit = orbitRef.current;
- if (!orbit || !onRotationChange) return;
- const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
- const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
- onRotationChange(rx, ry);
- }}
- />
+ plane.position.set(
+ deviceConfig.screenOffset.x,
+ deviceConfig.screenOffset.y,
+ deviceConfig.screenOffset.z
+ );
+ plane.renderOrder = 10;
+ group.add(plane);
- <Environment
- preset={environment as EnvironmentPreset}
- environmentIntensity={glow}
- background={false}
- />
+ finalizeSetup(group);
+ });
+ }
- <ambientLight intensity={0.3} />
- <directionalLight position={[3, 6, 5]} intensity={0.6} />
- <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
- <directionalLight position={[0, -5, 5]} intensity={0.35} />
- <group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
- {modelGroup && <primitive object={modelGroup} />}
- </group>
- </>
- );
-}
+ return () => {
+ isMounted = false;
+ };
+ }, [modelUrl, applyVideoTextureIfReady, onLoaded, invalidate]);
-function CanvasWithLoader(props: Props & { rootRef: React.MutableRefObject<THREE.Group | null>; cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>; }) {
- const [loaded, setLoaded] = useState(false);
- const handleLoaded = useCallback(() => setLoaded(true), []);
-
- return (
- <>
- <Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
- gl={{
- antialias: true,
- alpha: true,
- preserveDrawingBuffer: true,
- powerPreference: "high-performance",
- failIfMajorPerformanceCaveat: false,
- }}
- dpr={3}
- resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
- onCreated={({ gl, scene }) => {
- gl.outputColorSpace = THREE.SRGBColorSpace;
- gl.toneMapping = THREE.NeutralToneMapping;
- gl.toneMappingExposure = 1.0;
- scene.environmentIntensity = 1.6;
- props.onMount?.(gl.domElement);
- }}
- >
- <Suspense fallback={null}>
- <ModelScene {...props} onLoaded={handleLoaded} />
- </Suspense>
- </Canvas>
- {!loaded && (
- <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>
- <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
- </div>
- )}
- </>
- );
-}
+ const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
-export function Phone3DViewer(props: Props) {
- const {
- scale = 1,
- shadowIntensity = 0,
- shadowColor = "#000000",
- } = props;
+ useEffect(() => {
+ if (
+ prevRotationRef.current?.x === initialRotationX &&
+ prevRotationRef.current?.y === initialRotationY
+ ) {
+ return;
+ }
- const rootRef = useRef<THREE.Group | null>(null);
- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
- const [grabbing, setGrabbing] = useState(false);
+ const id = setTimeout(() => {
+ const orbit = orbitRef.current;
+ if (!orbit) return;
- const t = Math.max(0, Math.min(1, shadowIntensity));
- const tEased = t * t;
- const computedBlur = tEased * 60;
- const computedOpacity = tEased * 0.7;
+ const radius = 1.5 / zoom;
+ const phi = Math.PI / 2 - initialRotationX * DEG;
+ const theta = initialRotationY * DEG;
- const shadowRgba = shadowColor.startsWith("#")
- ? parseShadowColor(shadowColor, computedOpacity)
- : shadowColor;
+ orbit.object.position.setFromSphericalCoords(radius, phi, theta);
+ orbit.update();
+ invalidate();
- const hasShadow = t > 0.01;
+ prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
+ }, 0);
- return (
- <>
- <ControlsPopup />
+ return () => clearTimeout(id);
+ }, [initialRotationX, initialRotationY, zoom, invalidate]);
+ useEffect(() => {
+ if (rootRef.current) {
+ rootRef.current.rotation.z = initialRotationZ * DEG;
+ invalidate();
+ }
+ }, [initialRotationZ, invalidate]);
+
+ return (
+ <>
+ <PerspectiveCamera
+ ref={cameraRef}
+ makeDefault
+ fov={40}
+ near={0.01}
+ far={100}
+ position={[0, 0, 1.5 / zoom]}
+ />
+ <OrbitControls
+ ref={orbitRef}
+ enableZoom={false}
+ enablePan={false}
+ enableDamping
+ dampingFactor={0.08}
+ autoRotate={autoRotate}
+ autoRotateSpeed={rotationSpeed}
+ onEnd={() => {
+ const orbit = orbitRef.current;
+ if (!orbit || !onRotationChange) return;
+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
+ onRotationChange(rx, ry);
+ }}
+ />
+ <Environment preset={environment as EnvironmentPreset} environmentIntensity={glow} background={false} />
+ <ambientLight intensity={0.3} />
+ <directionalLight position={[3, 6, 5]} intensity={0.6} />
+ <directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
+ <directionalLight position={[0, -5, 5]} intensity={0.35} />
+ <group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
+ {modelGroup && <primitive object={modelGroup} />}
+ </group>
+ </>
+ );
+}
+
+function CanvasWithLoader(
+ props: Props & {
+ rootRef: React.MutableRefObject<THREE.Group | null>;
+ cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
+ }
+) {
+ const [loaded, setLoaded] = useState(false);
+ const handleLoaded = useCallback(() => setLoaded(true), []);
+
+ return (
+ <>
+ <Canvas
+ style={{ width: "100%", height: "100%", overflow: "visible" }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+ failIfMajorPerformanceCaveat: false,
+ }}
+ dpr={3}
+ frameloop={props.videoElement ? "always" : "demand"}
+ resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
+ onCreated={({ gl, scene }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ scene.environmentIntensity = 1.6;
+ props.onMount?.(gl.domElement);
+ }}
+ >
+ <Suspense fallback={null}>
+ <ModelScene {...props} onLoaded={handleLoaded} />
+ </Suspense>
+ </Canvas>
+ {!loaded && (
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none"
+ style={{ zIndex: 4 }}
+ >
+ <div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
+ </div>
+ )}
+ </>
+ );
+}
+
+export function Phone3DViewer(props: Props) {
+ const { scale = 1, shadowIntensity = 0, shadowColor = "#000000" } = props;
+ const rootRef = useRef<THREE.Group | null>(null);
+ const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const [grabbing, setGrabbing] = useState(false);
+
+ const t = Math.max(0, Math.min(1, shadowIntensity));
+ const tEased = t * t;
+ const computedBlur = tEased * 60;
+ const computedOpacity = tEased * 0.7;
+ const shadowRgba = shadowColor.startsWith("#")
+ ? parseShadowColor(shadowColor, computedOpacity)
+ : shadowColor;
+ const hasShadow = t > 0.01;
+
+ return (
+ <>
+ <ControlsPopup />
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ width: PHONE_W,
+ height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "220px",
+ marginLeft: "140px",
+ }}
+ >
+ <div style={{ position: "relative", width: PHONE_W, height: PHONE_H }}>
+ {hasShadow && (
<div
- style={{
- display: "inline-block",
- transformOrigin: "top center",
- width: PHONE_W,
- height: PHONE_H + (hasShadow ? computedBlur * 0.8 : 0),
- marginTop: "220px",
- marginLeft: "140px",
- }}
- >
- <div style={{ position: "relative", width: PHONE_W, height: PHONE_H }}>
- {hasShadow && (
- <div
- aria-hidden
- style={{
- position: "absolute",
- bottom: -(computedBlur * 0.5),
- left: `${20 + tEased * 5}%`,
- width: `${60 - tEased * 10}%`,
- height: Math.max(4, computedBlur * 0.55),
- borderRadius: "50%",
- background: shadowRgba,
- filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,
- zIndex: 0,
- pointerEvents: "none",
- }}
- />
- )}
-
- <div
- style={{
- position: "absolute",
- inset: "-400px",
- zIndex: 2,
- overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: hasShadow
- ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
- : "none",
- transition: "filter 0.15s ease",
- pointerEvents: "auto",
- }}
- onPointerDown={() => setGrabbing(true)}
- onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
- >
- <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
- </div>
- </div>
- </div>
- </>
- );
+ aria-hidden
+ style={{
+ position: "absolute",
+ bottom: -(computedBlur * 0.5),
+ left: `${20 + tEased * 5}%`,
+ width: `${60 - tEased * 10}%`,
+ height: Math.max(4, computedBlur * 0.55),
+ borderRadius: "50%",
+ background: shadowRgba,
+ filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,
+ zIndex: 0,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+ <div
+ style={{
+ position: "absolute",
+ inset: "-400px",
+ zIndex: 2,
+ overflow: "visible",
+ cursor: grabbing ? "grabbing" : "grab",
+ filter: hasShadow
+ ? `drop-shadow(0px ${(tEased * 22).toFixed(1)}px ${(tEased * 32).toFixed(1)}px ${shadowRgba})`
+ : "none",
+ transition: "filter 0.15s ease",
+ pointerEvents: "auto",
+ }}
+ onPointerDown={() => setGrabbing(true)}
+ onPointerUp={() => setGrabbing(false)}
+ onPointerLeave={() => setGrabbing(false)}
+ >
+ <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
+ </div>
+ </div>
+ </div>
+ </>
+ );
}
\ No newline at end of file
diff --git a/claude.md b/claude.md
index d42ed3a..ccf0960 100644
--- a/claude.md
+++ b/claude.md
@@ -287,7 +287,7 @@ openvidshot/
│ │ ├── mockups/ (bg-browser, bg-ide, bg-mobile)
│ │ ├── pages/ (hero, demos, login, qr, posters, openvid)
│ │ └── scroll/ (logos sponsors/decoradores)
-│ ├── models/ # glTF/GLB: iphone-15-pro-max.glb, samsung-galaxy-s25-ultra.glb, apple_iphone_13_pro_max.glb, phone-gltf.json
+│ ├── models/ # glTF/GLB: iphone-15-pro-max.glb, apple_iphone_13_pro_max.glb, phone-gltf.json
│ ├── svg/ # logo, mockups, cursores, openvid
│ ├── videos/ # Previews de features (audio, mockup, zoom, ...)
│ ├── elements/images/ # assets, overlays, stickers
@@ -332,7 +332,7 @@ openvidshot/
| `MockupMenu.tsx` + `mockups/*` | **Consolida** device picker (phone/iphone/iphone-13-pro-max/samsung/laptop), presets thumbnails (front/top-left/etc), popup Custom (scale/rotX/Y/Z/translateY/perspective), crop sync. Lee `Mockup3dContext` y `useActiveTool`. Lazy-loaded con `MockupMenuSkeleton`. |
| `MotionMenu.tsx` | Casi vacío (placeholder). `ImageMotionMenu.tsx` eliminado. Toda la lógica se movió a `MockupMenu`. |
| `CameraMenu.tsx` | Configuración de camera overlay (shape, corner, size, mirror). |
-| `Phone3DViewer.tsx` | **Vanilla Three.js + OrbitControls + RoomEnvironment**. Carga GLTF (`/models/iphone-15-pro-max.glb`, `/models/samsung-galaxy-s25-ultra.glb`, etc) según `modelUrl`. Inyecta imagen del usuario en el screen plane vía `createCoverScreenCanvas` con `applyCropToImage` + `imageMaskConfig`. Soporta `onRotationChange` desde el `end` de OrbitControls. Maneja `webglcontextlost`/`webglcontextrestored`. |
+| `Phone3DViewer.tsx` | **Vanilla Three.js + OrbitControls + RoomEnvironment**. Carga GLTF (`/models/iphone-15-pro-max.glb`, etc) según `modelUrl`. Inyecta imagen del usuario en el screen plane vía `createCoverScreenCanvas` con `applyCropToImage` + `imageMaskConfig`. Soporta `onRotationChange` desde el `end` de OrbitControls. Maneja `webglcontextlost`/`webglcontextrestored`. |
| `IPhone13ProMax3DViewer.tsx` | **Vanilla Three.js** para el iPhone 13 Pro Max. Carga `/models/apple_iphone_13_pro_max.glb`. Inyecta la imagen directamente en `Body_Wallpaper_0` (los UVs del mesh están listos, no requiere plane overlay). Mismos OrbitControls + RoomEnvironment + manejo de context lost. |
| `Laptop3DViewer.tsx` | **Vanilla Three.js** con su propio sistema de drag (NO usa OrbitControls) + inertia/damping via RAF loop. Carga `/models/mac-book.glb`. Pantalla customizable con `screenMaterial`. `lid` rotación animada por `openingProgress`. **Viewer de referencia** — copiar este patrón al crear viewers nuevos. |
| `FloatingCameraPreview.tsx` | Preview flotante arrastrable de la cámara (sidebar). |
diff --git a/lib/phone3d.utils.ts b/lib/phone3d.utils.ts
index 0a3f4e6..b21fa8f 100644
--- a/lib/phone3d.utils.ts
+++ b/lib/phone3d.utils.ts
@@ -1,6 +1,25 @@
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+export interface DeviceConfig {
+ modelUrl: string | null;
+ aspectRatio: number;
+ screenHeightFactor: number;
+ screenOffset: { x: number; y: number; z: number };
+ cornerRadiusFactor: number;
+}
+
+export interface ImageMaskConfigLike {
+ enabled?: boolean;
+ top?: { from: number; to?: number };
+ right?: { from: number; to?: number };
+ bottom?: { from: number; to?: number };
+ left?: { from: number; to?: number };
+ angle?: number;
+ angleFrom?: number;
+ angleTo?: number;
+}
+
export const PHONE_H = 704;
export const PHONE_W = Math.round(PHONE_H * 0.479);
@@ -13,23 +32,13 @@ export const DEVICE_3D_DIMENSIONS: Record<string, { width: number; height: numbe
'iphone': { width: PHONE_W, height: PHONE_H },
'iphone-13-pro-max': { width: 480, height: 1000 },
'double_iphone_13_pro': { width: 960, height: 2000 },
- 'samsung': { width: PHONE_W, height: PHONE_H },
'laptop': { width: 1500, height: 1035 },
};
-// Camera settings (based on appscreen-main reference: fov=20, position=[-3,-1,4])
export const CAM_FOV = 20;
export const CAM_Z = 6;
-export type DeviceKey = "iphone" | "samsung" | "phone" | "double_iphone_13_pro";
-
-export interface DeviceConfig {
- modelUrl: string | null;
- aspectRatio: number;
- screenHeightFactor: number;
- screenOffset: { x: number; y: number; z: number };
- cornerRadiusFactor: number;
-}
+export type DeviceKey = "iphone" | "phone" | "double_iphone_13_pro";
export const deviceConfigs: Record<DeviceKey, DeviceConfig> = {
iphone: {
@@ -46,13 +55,6 @@ export const deviceConfigs: Record<DeviceKey, DeviceConfig> = {
screenOffset: { x: 0.027, y: 0.745, z: 0.098 },
cornerRadiusFactor: 0.16,
},
- samsung: {
- modelUrl: "/models/samsung-galaxy-s25-ultra.glb",
- aspectRatio: 1440 / 3120,
- screenHeightFactor: 0.66,
- screenOffset: { x: 0, y: 0.0, z: 0.08 },
- cornerRadiusFactor: 0.04,
- },
phone: {
modelUrl: "/models/phone-gltf.glb",
aspectRatio: 0,
@@ -65,21 +67,9 @@ export const deviceConfigs: Record<DeviceKey, DeviceConfig> = {
export function getDeviceFromModelUrl(modelUrl: string | undefined): DeviceKey {
if (!modelUrl) return "phone";
if (modelUrl.includes("iphone")) return "iphone";
- if (modelUrl.includes("samsung")) return "samsung";
return "phone";
}
-export interface ImageMaskConfigLike {
- enabled?: boolean;
- top?: { from: number; to?: number };
- right?: { from: number; to?: number };
- bottom?: { from: number; to?: number };
- left?: { from: number; to?: number };
- angle?: number;
- angleFrom?: number;
- angleTo?: number;
-}
-
export function createCoverScreenCanvas(
source: HTMLImageElement | HTMLVideoElement | HTMLCanvasElement,
targetW: number,
@@ -201,11 +191,6 @@ export function cloneGroup(src: THREE.Group): THREE.Group {
return cloned;
}
-/** Shortest arc in degrees from curRy to targetRy, result in [-180, 180] */
-export function shortArc(curRy: number, targetRy: number): number {
- return ((targetRy - curRy) % 360 + 540) % 360 - 180;
-}
-
export function parseShadowColor(hex: string, opacity: number): string {
const h = hex.replace("#", "");
const r = parseInt(h.length === 3 ? h[0] + h[0] : h.slice(0, 2), 16);
@@ -267,3 +252,16 @@ export function applyCropToImage(
ctx.drawImage(source, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
return canvas;
}
+
+export function easeInOutCubic(t: number): number {
+ return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
+}
+
+export interface CameraFlyAnimation {
+ fromPos: THREE.Vector3;
+ toPos: THREE.Vector3;
+ fromTarget: THREE.Vector3;
+ toTarget: THREE.Vector3;
+ startTime: number;
+ duration: number;
+}
\ No newline at end of file
diff --git a/public/models/apple_iphone_13_pro_max.glb b/public/models/apple_iphone_13_pro_max.glb
index bbe3e76..374a0c9 100644
Binary files a/public/models/apple_iphone_13_pro_max.glb and b/public/models/apple_iphone_13_pro_max.glb differ
diff --git a/public/models/double_iphone_13_pro.glb b/public/models/double_iphone_13_pro.glb
index b1332ab..a34f2c6 100644
Binary files a/public/models/double_iphone_13_pro.glb and b/public/models/double_iphone_13_pro.glb differ
diff --git a/public/models/iphone-17-pro-max.glb b/public/models/iphone-17-pro-max.glb
new file mode 100644
index 0000000..fc5ece5
Binary files /dev/null and b/public/models/iphone-17-pro-max.glb differ
diff --git a/public/models/samsung-galaxy-s25-ultra.glb b/public/models/samsung-galaxy-s25-ultra.glb
deleted file mode 100644
index b69f245..0000000
Binary files a/public/models/samsung-galaxy-s25-ultra.glb and /dev/null differ
diff --git a/types/mockup.types.ts b/types/mockup.types.ts
index 4ac5aa8..7f3ae20 100644
--- a/types/mockup.types.ts
+++ b/types/mockup.types.ts
@@ -106,6 +106,15 @@ export const IMAGE_DEVICE_TEMPLATES = [
posterUrl: encodeURI("/images/mockups-3d/double-iphone-13pro.avif"),
videoUrl: encodeURI("/videos/mockups-3d/double-iphone-13pro.mp4"),
},
+ {
+ id: "iphone-17-pro-max",
+ title: "iPhone 17 Pro",
+ accentColor: "#00A3FF",
+ icon: "simple-icons:apple",
+ modelUrl: "/models/iphone-17-pro-max.glb",
+ posterUrl: encodeURI("/images/mockups-3d/iphone-13pro.avif"),
+ videoUrl: encodeURI("/videos/mockups-3d/iphone-13pro.mp4"),
+ },
{
id: "iphone",
title: "iPhone 15 Pro",
@@ -115,15 +124,6 @@ export const IMAGE_DEVICE_TEMPLATES = [
posterUrl: encodeURI("/images/mockups-3d/iphone-15pro.avif"),
videoUrl: encodeURI("/videos/mockups-3d/iphone-15pro.mp4"),
},
- {
- id: "samsung",
- title: "Samsung S25",
- accentColor: "#2443ff",
- icon: "simple-icons:samsung",
- modelUrl: "/models/samsung-galaxy-s25-ultra.glb",
- posterUrl: encodeURI("/images/mockups-3d/samsung-s25.avif"),
- videoUrl: encodeURI("/videos/mockups-3d/samsung-s25.mp4"),
- },
{
id: "phone",
title: "Phone",