Skip to content

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

feat: update 3D viewer components and improve rendering performance

CristianOlivera1edc7a332c9c4
diff --git a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
index 351299c..12adf14 100644
--- a/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
+++ b/app/components/ui/editor/IPhone13ProMax3DViewer.tsx
@@ -409,7 +409,7 @@ function ModelScene({
/>
)}
- <group ref={rootRef} rotation={[0, Math.PI, 0]} scale={0.01} dispose={null}>
+ <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} />
@@ -599,7 +599,7 @@ export function IPhone13ProMax3DViewer({
<div
style={{
position: "absolute",
- inset: "-200px",
+ inset: "-400px",
zIndex: 2,
overflow: "visible",
cursor: grabbing ? "grabbing" : "grab",
diff --git a/app/components/ui/editor/Laptop3DViewer.tsx b/app/components/ui/editor/Laptop3DViewer.tsx
index 4e5b593..1d39d7e 100644
--- a/app/components/ui/editor/Laptop3DViewer.tsx
+++ b/app/components/ui/editor/Laptop3DViewer.tsx
@@ -121,10 +121,16 @@ function ModelScene({
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
- (cam as THREE.PerspectiveCamera).aspect = w / h;
+ const RENDER_PIXEL_RATIO = 2;
+ 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(2);
- gl.setSize(w, h, false);
+ gl.setPixelRatio(RENDER_PIXEL_RATIO);
+ gl.setSize(safeW, safeH, false);
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
gl.render(scene, cam);
},
@@ -198,17 +204,6 @@ function ModelScene({
return;
}
- if (!imageUrl) {
- if (mat.map) {
- mat.map.dispose();
- mat.map = null;
- mat.needsUpdate = true;
- }
- lastLoadedUrlRef.current = null;
- lastLoadedCropKeyRef.current = null;
- return;
- }
-
if (
lastLoadedUrlRef.current === imageUrl &&
lastLoadedCropKeyRef.current === cropKey &&
diff --git a/app/components/ui/editor/Mockup3dMenu.tsx b/app/components/ui/editor/Mockup3dMenu.tsx
index 83c13af..9f7a006 100644
--- a/app/components/ui/editor/Mockup3dMenu.tsx
+++ b/app/components/ui/editor/Mockup3dMenu.tsx
@@ -46,30 +46,29 @@ function PositionPad({
const bgLayerStyle: React.CSSProperties = backgroundUrl
? {
- backgroundImage: `url('${backgroundUrl}')`,
- backgroundSize: "cover",
- backgroundPosition: "center",
- backgroundRepeat: "no-repeat",
- }
+ backgroundImage: `url('${backgroundUrl}')`,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ backgroundRepeat: "no-repeat",
+ }
: backgroundColorCss
? backgroundColorCss.startsWith("#") || backgroundColorCss.startsWith("rgb")
? { backgroundColor: backgroundColorCss }
: {
- backgroundImage: backgroundColorCss,
- backgroundSize: "cover",
- backgroundPosition: "center",
- }
+ backgroundImage: backgroundColorCss,
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ }
: {};
return (
<div className="relative group w-full cursor-default">
<div
ref={padRef}
- className={`relative w-full rounded-[14px] overflow-hidden select-none border shadow-[inset_0_2px_8px_rgba(0,0,0,0.8)] transition-all duration-200 ${
- isDraggingState
- ? "border-cyan-500/40 ring-1 ring-cyan-500/20"
- : "border-zinc-800/50"
- }`}
+ className={`relative w-full rounded-[14px] overflow-hidden select-none border shadow-[inset_0_2px_8px_rgba(0,0,0,0.8)] transition-all duration-200 ${isDraggingState
+ ? "border-cyan-500/40 ring-1 ring-cyan-500/20"
+ : "border-zinc-800/50"
+ }`}
style={{ height: PAD_H }}
onPointerDown={(e) => {
dragging.current = true;
@@ -176,9 +175,8 @@ function ActiveDevicePreview({
src={tpl.posterUrl}
alt={tpl.title}
draggable={false}
- className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${
- isHovering ? "scale-105 opacity-0" : "scale-100 opacity-100"
- }`}
+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${isHovering ? "scale-105 opacity-0" : "scale-100 opacity-100"
+ }`}
/>
) : (
<div className="absolute inset-0 flex items-center justify-center">
@@ -200,16 +198,14 @@ function ActiveDevicePreview({
playsInline
preload="metadata"
onLoadedData={() => setVideoReady(true)}
- className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${
- isHovering && videoReady ? "scale-105 opacity-100" : "scale-100 opacity-0"
- }`}
+ className={`absolute inset-0 h-full w-full object-cover transition-all duration-500 ${isHovering && videoReady ? "scale-105 opacity-100" : "scale-100 opacity-0"
+ }`}
/>
)}
<div
- className={`absolute inset-0 z-20 bg-black/20 transition-opacity duration-300 ${
- isHovering ? "opacity-100" : "opacity-0"
- }`}
+ className={`absolute inset-0 z-20 bg-black/20 transition-opacity duration-300 ${isHovering ? "opacity-100" : "opacity-0"
+ }`}
/>
<div className=" flex items-center gap-2 absolute bottom-0 left-0 right-0 px-3 py-2 bg-gradient-to-t from-black/80 to-transparent z-30">
@@ -246,7 +242,6 @@ export interface Mockup3dMenuProps {
activeDeviceTpl: ActiveDeviceTpl | null;
imagePhoneDevice: string;
isLaptop: boolean;
-
imagePhoneScale: number;
setImagePhoneScale: (v: number) => void;
imagePhoneOpening: number;
@@ -272,7 +267,6 @@ export function Mockup3dMenu({
activeDeviceTpl,
imagePhoneDevice,
isLaptop,
-
imagePhoneScale,
setImagePhoneScale,
imagePhoneOpening,
@@ -298,7 +292,7 @@ export function Mockup3dMenu({
const handleReset = () => {
setImagePhoneX(0);
setImagePhoneY(0);
- setImagePhoneScale(0.8);
+ setImagePhoneScale(0.9);
const defaultRotX = imagePhoneDevice === "laptop" ? 43.23 : -58.23;
const defaultRotY = imagePhoneDevice === "laptop" ? -37.82 : -29.82;
setImagePhoneRotX(defaultRotX);
@@ -306,6 +300,9 @@ export function Mockup3dMenu({
if (imagePhoneDevice === "laptop") {
setImagePhoneOpening(1);
setImagePhoneShadow(0.7);
+ } else if (imagePhoneDevice === "double_iphone_13_pro") {
+ setImagePhoneRotX(-30.23);
+ setImagePhoneRotY(-60.82);
} else {
setImagePhoneShadow(0.4);
}
diff --git a/app/components/ui/editor/Phone3DViewer.tsx b/app/components/ui/editor/Phone3DViewer.tsx
index 8a16f93..3aaff19 100644
--- a/app/components/ui/editor/Phone3DViewer.tsx
+++ b/app/components/ui/editor/Phone3DViewer.tsx
@@ -415,7 +415,7 @@ function ModelScene({
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;
+ const sf = (halfH * 2 * 0.6) / size.y;
group.scale.setScalar(sf);
group.position.copy(center).negate().multiplyScalar(sf);
const deviceConfig = deviceConfigs[device];
@@ -468,14 +468,31 @@ function ModelScene({
};
}, [modelUrl]);
+ const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+
useEffect(() => {
- 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();
+ if (
+ prevRotationRef.current?.x === initialRotationX &&
+ prevRotationRef.current?.y === initialRotationY
+ ) {
+ return;
+ }
+
+ 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(() => {
@@ -615,7 +632,7 @@ export function Phone3DViewer(props: Props) {
<div
style={{
position: "absolute",
- inset: "-200px",
+ inset: "-400px",
zIndex: 2,
overflow: "visible",
cursor: grabbing ? "grabbing" : "grab",
diff --git a/app/components/ui/editor/PlayerControls.tsx b/app/components/ui/editor/PlayerControls.tsx
index b359eb0..c68dce4 100644
--- a/app/components/ui/editor/PlayerControls.tsx
+++ b/app/components/ui/editor/PlayerControls.tsx
@@ -169,6 +169,17 @@ export function PlayerControls({
</span>
</div>
+ <div className="h-4 w-px bg-white/10" />
+
+ {/* <TooltipAction label="Dividir video">
+ <button
+ className="text-zinc-500 hover:text-white active:scale-95 transition-all p-1 flex items-center justify-center"
+ aria-label="Dividir track en la línea de tiempo"
+ >
+ <Icon icon="lucide:scissors" width="15" aria-hidden="true" />
+ </button>
+ </TooltipAction> */}
+
{/* Select de Mask Image aqui */}
<div className="h-4 w-px bg-white/10" />
<ImageMaskEditor
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index a7c36fc..7c45aca 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -44,6 +44,11 @@ const IPhone13ProMax3DViewer = dynamic(
{ ssr: false }
);
+const DoubleIPhone3DViewer = dynamic(
+ () => import("./DoubleIPhone3DViewer").then((m) => ({ default: m.DoubleIPhone3DViewer })),
+ { ssr: false }
+);
+
const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
activeTool: _activeTool,
mediaType = "video",
@@ -106,9 +111,10 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
const {
imagePhoneActive, imagePhoneX, imagePhoneY,
imagePhoneScale, setImagePhoneScale,
+ setImagePhoneX, setImagePhoneY,
imagePhoneRotX, setImagePhoneRotX, imagePhoneRotY, setImagePhoneRotY,
imagePhoneRotZ,
- imagePhoneDevice, imagePhonePresetId,
+ imagePhoneDevice,
imagePhoneOpening,
imagePhoneShadow, imagePhoneShadowColor
} = useMockup3dContext();
@@ -145,6 +151,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
phone: '/models/phone-gltf.glb',
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',
laptop: '/models/mac-book.glb',
};
@@ -292,14 +299,10 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
const dragStartPos = useRef({ x: 0, y: 0, initialRotation: 0, initialTranslateX: 0, initialTranslateY: 0 });
const lastAngleRef = useRef<number | null>(null);
const videoContainerRef = useRef<HTMLDivElement>(null);
- // Click vs drag detection for the 2D mockup canvas: we record the
- // pointer-down position and only fire onMockupClick if the pointer
- // stayed within CLICK_THRESHOLD pixels (i.e. it was a click, not a drag).
const clickStartPosRef = useRef<{ x: number; y: number } | null>(null);
const CLICK_THRESHOLD = 5; // px
const [elementCorners, setElementCorners] = useState<Record<string, Corner | null>>({});
- // Camera overlay refs / state
const cameraVideoRef = useRef<HTMLVideoElement | null>(null);
const previewContainerRef = useRef<HTMLDivElement>(null);
const canvasWrapperRef = useRef<HTMLDivElement>(null);
@@ -323,57 +326,51 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // attach once — ctrlScrollWheelRef.current updated each render
- // Compute canvas dimensions to fill available space while maintaining aspect ratio
const [canvasDimensions, setCanvasDimensions] = useState<{ width: number; height: number } | null>(null);
+ const canvasWidthRef = useRef<number | null>(null);
+ useEffect(() => {
+ canvasWidthRef.current = canvasDimensions?.width ?? null;
+ }, [canvasDimensions?.width]);
+
useEffect(() => {
const wrapper = canvasWrapperRef.current;
if (!wrapper) return;
const arNumber = getAspectRatioNumber(aspectRatio, customAspectRatio ?? undefined);
- const compute = (containerWidth: number, containerHeight: number) => {
- if (containerWidth <= 0 || containerHeight <= 0) return;
+ const computeDims = (containerWidth: number, containerHeight: number) => {
+ if (containerWidth <= 0 || containerHeight <= 0) return null;
const byHeight = { width: containerHeight * arNumber, height: containerHeight };
- if (byHeight.width <= containerWidth) {
- setCanvasDimensions(byHeight);
- } else {
- setCanvasDimensions({ width: containerWidth, height: containerWidth / arNumber });
- }
+ if (byHeight.width <= containerWidth) return byHeight;
+ return { width: containerWidth, height: containerWidth / arNumber };
};
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
- compute(width, height);
+ const dims = computeDims(width, height);
+ if (dims) setCanvasDimensions(dims);
});
-
observer.observe(wrapper);
const rect = wrapper.getBoundingClientRect();
- compute(rect.width, rect.height);
+ const dims = computeDims(rect.width, rect.height);
+ if (dims) {
+ const prevWidth = canvasWidthRef.current;
+ setCanvasDimensions(dims);
+
+ if (prevWidth) {
+ const ratio = dims.width / prevWidth;
+ if (Math.abs(ratio - 1) >= 0.005) {
+ setImagePhoneX(prev => prev * ratio);
+ setImagePhoneY(prev => prev * ratio);
+ setImagePhoneScale(prev => prev * ratio);
+ }
+ }
+ }
return () => observer.disconnect();
}, [aspectRatio, customAspectRatio]);
-
- const phoneCalibrationWidthRef = useRef<number>(canvasDimensions?.width ?? 0);
- useEffect(() => {
- if (canvasDimensions?.width) {
- phoneCalibrationWidthRef.current = canvasDimensions.width;
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [imagePhoneX, imagePhoneY, imagePhoneScale]);
-
- const phoneCanvasScaleFactor = (canvasDimensions?.width && phoneCalibrationWidthRef.current)
- ? canvasDimensions.width / phoneCalibrationWidthRef.current
- : 1;
-
- // Usar SIEMPRE estos valores para posicionar/dimensionar el mockup 3D —
- // nunca imagePhoneX/Y/Scale crudos, excepto dentro del cálculo que llama
- // a setImagePhoneScale() (ese debe leer el valor real almacenado).
- const effectiveImagePhoneX = imagePhoneX * phoneCanvasScaleFactor;
- const effectiveImagePhoneY = imagePhoneY * phoneCanvasScaleFactor;
- const effectiveImagePhoneScale = imagePhoneScale * phoneCanvasScaleFactor;
-
const cameraDragRef = useRef<{
pointerId: number;
startX: number;
@@ -1218,12 +1215,12 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
const phoneGL = imagePhoneCanvasRef.current;
const domW = canvasDimensions?.width ?? canvasWidth;
const pxScale = canvasWidth / domW;
- const phoneCx = canvasWidth / 2 + effectiveImagePhoneX * pxScale;
- const phoneCy = canvasHeight / 2 + effectiveImagePhoneY * pxScale;
+ const phoneCx = canvasWidth / 2 + imagePhoneX * pxScale;
+ const phoneCy = canvasHeight / 2 + imagePhoneY * pxScale;
// Use device-specific dimensions instead of generic PHONE_W/H
const deviceDims = DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };
- const drawW = deviceDims.width * effectiveImagePhoneScale * pxScale;
- const drawH = deviceDims.height * effectiveImagePhoneScale * pxScale;
+ const drawW = deviceDims.width * imagePhoneScale * pxScale;
+ const drawH = deviceDims.height * imagePhoneScale * pxScale;
// Paint CSS-shadow replica as a 2D radial gradient underneath the model,
// but only for devices whose 3D viewer doesn't already render ContactShadows.
const hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;
@@ -1473,15 +1470,15 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
const centerX = canvasWidth / 2;
const centerY = canvasHeight / 2;
- const baseCx = centerX + effectiveImagePhoneX * pxScale;
- const baseCy = centerY + effectiveImagePhoneY * pxScale;
+ const baseCx = centerX + imagePhoneX * pxScale;
+ const baseCy = centerY + imagePhoneY * pxScale;
const phoneCx = (baseCx - focusPxX) * zScale + centerX;
const phoneCy = (baseCy - focusPxY) * zScale + centerY;
const deviceDims = DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };
- const drawW = deviceDims.width * effectiveImagePhoneScale * pxScale * zScale;
- const drawH = deviceDims.height * effectiveImagePhoneScale * pxScale * zScale;
+ const drawW = deviceDims.width * imagePhoneScale * pxScale * zScale;
+ const drawH = deviceDims.height * imagePhoneScale * pxScale * zScale;
const hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;
if (imagePhoneShadow > 0.01 && !hasBuiltInShadow) {
@@ -2162,8 +2159,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
style={{
left: "50%",
top: "50%",
- transform: `translate(calc(-50% + ${effectiveImagePhoneX}px), calc(-50% + ${effectiveImagePhoneY}px))`,
-
+ transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px))`,
transformOrigin: "center center",
pointerEvents: "none",
userSelect: "none",
@@ -2178,7 +2174,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
pointerEvents: "none",
}}
>
- <EditorHoverTooltip show={isVideoHovered && imagePhoneActive} />
+ {/* <EditorHoverTooltip show={isVideoHovered && imagePhoneActive} /> */}
</div>
</div>
@@ -2208,8 +2204,7 @@ const VideoCanvasInner = forwardRef<VideoCanvasHandle, VideoCanvasProps>(functio
style={{
left: "50%",
top: "50%",
- transform: `translate(calc(-50% + ${effectiveImagePhoneX}px), calc(-50% + ${effectiveImagePhoneY}px)) scale(${effectiveImagePhoneScale})`,
-
+ transform: `translate(calc(-50% + ${imagePhoneX}px), calc(-50% + ${imagePhoneY}px)) scale(${imagePhoneScale})`,
transformOrigin: "center center",
pointerEvents: "auto",
userSelect: "none",
@@ -2263,6 +2258,24 @@ 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}
diff --git a/lib/viewer-controls3d.ts b/lib/viewer-controls3d.ts
index cfd9573..d6afdf0 100644
--- a/lib/viewer-controls3d.ts
+++ b/lib/viewer-controls3d.ts
@@ -20,10 +20,8 @@ export function ViewerControls3D({ defaultEnvironment = "studio", defaultGlow =
}));
useEffect(() => {
- set({
- environment: defaultEnvironment
- });
- }, [defaultEnvironment, set]);
+ set({ environment: defaultEnvironment, glow: defaultGlow });
+ }, [defaultEnvironment, defaultGlow, set]);
return controls;
}
\ No newline at end of file
diff --git a/types/control-panel.types.ts b/types/control-panel.types.ts
index 449d897..4d21a0b 100644
--- a/types/control-panel.types.ts
+++ b/types/control-panel.types.ts
@@ -44,14 +44,6 @@ export interface ControlPanelProps {
mockupConfig?: MockupConfig;
onMockupChange?: (mockupId: string) => void;
onMockupConfigChange?: (config: Partial<MockupConfig>) => void;
- /**
- * Initial page for the MockupMenu (home | detail-2d | detail-3d). Set by
- * the parent when the user clicks a mockup already applied on the canvas,
- * so the menu opens directly on the config panel of that frame. The
- * MockupMenu is keyed by `mockupMenuNavigationToken` to re-mount on every
- * canvas click so the `useState(initialPage)` re-reads the new value
- * even when the same page is selected twice in a row.
- */
initialMockupMenuPage?: MenuPage;
mockupMenuNavigationToken?: number;
onAddCanvasElement?: (element: CanvasElement) => void;