Create professional demos and 3D mockups in seconds, directly in your browser
feat: Implement 3D motion presets and customization options
CristianOlivera1ea3103d9338b
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 305ed1a..c6289af 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -309,6 +309,7 @@ export default function Editor() {} = useMockupMotionFragments({currentTime, videoDuration, setActiveTool, lastCopyActionRef,selectedMockupMotionFragmentId, setSelectedMockupMotionFragmentId,+ motionMode: imagePhoneActive ? "3d" : (isVideoMode ? "2d" : null),});const {diff --git a/app/components/ui/editor/ControlPanel.tsx b/app/components/ui/editor/ControlPanel.tsxindex 79e868b..6521306 100644--- a/app/components/ui/editor/ControlPanel.tsx+++ b/app/components/ui/editor/ControlPanel.tsx@@ -28,6 +28,8 @@ const VideosMenu = lazy(() => import("./VideosMenu").then(mod => ({ default: modconst HistoryMenu = lazy(() => import("./HistoryMenu").then(mod => ({ default: mod.HistoryMenu })));const MotionGlobalConfig = lazy(() => import("./MotionGlobalConfig").then(mod => ({ default: mod.MotionGlobalConfig })));const MotionFragmentEditor = lazy(() => import("./MotionFragmentEditor").then(mod => ({ default: mod.MotionFragmentEditor })));+const MotionFragmentEditor3D = lazy(() => import("./MotionFragmentEditor3D").then(mod => ({ default: mod.MotionFragmentEditor3D })));+import { MOTION_PRESET_3D_IDS } from "@/lib/mockup-motion";interface ExtendedControlPanelProps extends ControlPanelProps {onTogglePanel?: () => void;@@ -139,6 +141,7 @@ export function ControlPanel({const { imagePhoneActive } = useMockup3dContext();const [isGlobalMotionEnabled, setIsGlobalMotionEnabled] = useState(true);const hasMockup2D = mediaType === "video" && !imagePhoneActive;+ const hasMockup3D = imagePhoneActive;const [isDark, setIsDark] = useState(() => typeof window !== "undefined" && document.documentElement.classList.contains("dark")@@ -324,30 +327,37 @@ export function ControlPanel({)}{activeTool === "motion" && (<>- {selectedMockupMotionFragment && hasMockup2D ? (- <Suspense fallback={<MotionFragmentEditorSkeleton />}>- <MotionFragmentEditor- fragment={selectedMockupMotionFragment}- isGlobalMotionEnabled={isGlobalMotionEnabled}- onUpdate={(updates) =>- selectedMockupMotionFragmentId &&- onUpdateMockupMotionFragment?.(selectedMockupMotionFragmentId, updates)- }- onDelete={() => {- if (selectedMockupMotionFragmentId) {- onDeleteMockupMotionFragment?.(selectedMockupMotionFragmentId);- }- onSelectMockupMotionFragment?.(null);- }}- onClose={() => onSelectMockupMotionFragment?.(null)}- />- </Suspense>+ {selectedMockupMotionFragment && (hasMockup2D || hasMockup3D) ? (+ (() => {+ const is3DFragment = MOTION_PRESET_3D_IDS.has(selectedMockupMotionFragment.presetId);+ const EditorComponent = is3DFragment ? MotionFragmentEditor3D : MotionFragmentEditor;+ return (+ <Suspense key={is3DFragment ? "3d" : "2d"} fallback={<MotionFragmentEditorSkeleton />}>+ <EditorComponent+ fragment={selectedMockupMotionFragment}+ isGlobalMotionEnabled={isGlobalMotionEnabled}+ onUpdate={(updates) =>+ selectedMockupMotionFragmentId &&+ onUpdateMockupMotionFragment?.(selectedMockupMotionFragmentId, updates)+ }+ onDelete={() => {+ if (selectedMockupMotionFragmentId) {+ onDeleteMockupMotionFragment?.(selectedMockupMotionFragmentId);+ }+ onSelectMockupMotionFragment?.(null);+ }}+ onClose={() => onSelectMockupMotionFragment?.(null)}+ />+ </Suspense>+ );+ })()) : (<Suspense fallback={<MotionGlobalConfigSkeleton />}><MotionGlobalConfigfragments={mockupMotionFragments}onAddOrReplacePreset={(presetId) => onAddOrReplaceMotionPreset?.(presetId)}hasMockup2D={hasMockup2D}+ hasMockup3D={hasMockup3D}isGlobalMotionEnabled={isGlobalMotionEnabled}onToggleGlobalMotion={setIsGlobalMotionEnabled}/>diff --git a/app/components/ui/editor/MockupMotionTrackItem.tsx b/app/components/ui/editor/MockupMotionTrackItem.tsxindex 9b5a6b8..3de6038 100644--- a/app/components/ui/editor/MockupMotionTrackItem.tsx+++ b/app/components/ui/editor/MockupMotionTrackItem.tsx@@ -37,6 +37,8 @@ export function MockupMotionTrackItem({const label = t(`presets.${fragment.presetId}`);+ const is3D = fragment.presetId === "orbit-entrance" || fragment.presetId === "turntable-drift" || fragment.presetId === "flick-exit";+const timeToPixels = useCallback((time: number) => (time / videoDuration) * contentWidth,[videoDuration, contentWidth]@@ -199,7 +201,7 @@ export function MockupMotionTrackItem({<div className="flex-1 flex flex-col items-center justify-center pointer-events-none overflow-hidden px-2"><span className={`text-[10px] truncate ${isSelected || isInteracting ? "text-orange-700 dark:text-orange-200" : "text-orange-700/70 dark:text-orange-300/70"}`}>- {label}+ {is3D && <span className="mr-0.5 text-[8px] font-bold align-middle">3D</span>}{label}</span><span className={`text-[8px] truncate ${isSelected || isInteracting ? "text-orange-700/70 dark:text-orange-300/70" : "text-orange-700/50 dark:text-orange-400/45"}`}>{duration.toFixed(1)}sdiff --git a/app/components/ui/editor/MotionFragmentEditor.tsx b/app/components/ui/editor/MotionFragmentEditor.tsxindex 9bba15f..6dba851 100644--- a/app/components/ui/editor/MotionFragmentEditor.tsx+++ b/app/components/ui/editor/MotionFragmentEditor.tsx@@ -8,6 +8,9 @@ import {MockupMotionFragment,DEFAULT_MOTION_CUSTOM_OFFSETS,type MotionCustomOffsets,+ MOTION_PRESET_3D_IDS,+ DEFAULT_3D_MOTION_CUSTOM_OFFSETS,+ type Mockup3DMotionCustomOffsets,} from "@/lib/mockup-motion";import {MotionPresetIconStyles,@@ -32,10 +35,28 @@ export function MotionFragmentEditor({onClose,}: MotionFragmentEditorProps) {const t = useTranslations("motionMenu");- const custom = fragment.custom ?? DEFAULT_MOTION_CUSTOM_OFFSETS;++ // Detect whether this fragment belongs to a 3D preset. 3D presets use a+ // separate custom-offsets object (custom3D) that lacks the `blur` field+ // since motion blur is not applicable to real 3D geometry.+ const is3D = MOTION_PRESET_3D_IDS.has(fragment.presetId);++ const custom2D = fragment.custom ?? DEFAULT_MOTION_CUSTOM_OFFSETS;+ const custom3D = fragment.custom3D ?? DEFAULT_3D_MOTION_CUSTOM_OFFSETS;++ // Unified accessor so the JSX below doesn't need to branch at every+ // control. `blur` is always 0 in 3D mode.+ const custom = is3D+ ? { ...custom3D, blur: 0 }+ : custom2D;const updateCustom = (partial: Partial<MotionCustomOffsets>) => {- onUpdate({ custom: { ...custom, ...partial } });+ if (is3D) {+ const { blur: _blur, ...rest } = partial;+ onUpdate({ custom3D: { ...custom3D, ...(rest as Partial<Mockup3DMotionCustomOffsets>) } });+ } else {+ onUpdate({ custom: { ...custom2D, ...partial } });+ }};const hasCustomChanges =@@ -45,15 +66,28 @@ export function MotionFragmentEditor({custom.rotateX !== 0 ||custom.rotateY !== 0 ||custom.rotateZ !== 0 ||- custom.blur !== 0 ||+ (!is3D && custom.blur !== 0) ||custom.reverse;+ const resetCustom = () => {+ if (is3D) {+ onUpdate({ custom3D: { ...DEFAULT_3D_MOTION_CUSTOM_OFFSETS } });+ } else {+ onUpdate({ custom: { ...DEFAULT_MOTION_CUSTOM_OFFSETS } });+ }+ };+return (<div className="flex flex-col h-full text-foreground"><MotionPresetIconStyles /><div className="flex items-center gap-2 p-3 border-b border-border shrink-0"><DetailPageHeader label={t("title")} icon="ph:arrow-left-bold" onBack={onClose} />+ {is3D && (+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 bg-muted/60 px-1.5 py-0.5 rounded shrink-0">+ 3D+ </span>+ )}<TooltipAction label={t("deleteTooltip")}><buttononClick={onDelete}@@ -131,6 +165,16 @@ export function MotionFragmentEditor({max={45}onChange={(v: number) => updateCustom({ rotateZ: v })}/>+ {!is3D && (+ <SliderControl+ icon="mdi:blur"+ label={t("customize.blurLabel")}+ value={custom.blur}+ min={0}+ max={20}+ onChange={(v: number) => updateCustom({ blur: v })}+ />+ )}<label className="flex items-center justify-between px-3 py-2.5 rounded-lg bg-muted/40 border border-border"><span className="text-xs text-muted-foreground">{t("customize.reverseLabel")}</span><Toggle@@ -141,7 +185,7 @@ export function MotionFragmentEditor({</label>{hasCustomChanges && (<button- onClick={() => onUpdate({ custom: { ...DEFAULT_MOTION_CUSTOM_OFFSETS } })}+ onClick={resetCustom}className="self-start text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2">{t("customize.resetButton")}@@ -151,4 +195,4 @@ export function MotionFragmentEditor({</div></div>);-}\ No newline at end of file+}diff --git a/app/components/ui/editor/MotionFragmentEditor3D.tsx b/app/components/ui/editor/MotionFragmentEditor3D.tsxnew file mode 100644index 0000000..1d1b529--- /dev/null+++ b/app/components/ui/editor/MotionFragmentEditor3D.tsx@@ -0,0 +1,220 @@+"use client";++import { Icon } from "@iconify/react";+import { useTranslations } from "next-intl";+import { SliderControl } from "../../../../components/ui/SliderControl";+import { Toggle } from "@/components/ui/toggle";+import {+ MockupMotionFragment,+ DEFAULT_3D_MOTION_CUSTOM_OFFSETS,+ type Mockup3DMotionCustomOffsets,+} from "@/lib/mockup-motion";+import {+ MotionPresetIconStyles,+} from "../../../../components/ui/MotionPresetIcon";+import { PositionPad } from "@/components/ui/PositionPad";+import { TooltipAction } from "@/components/ui/tooltip-action";+import { DetailPageHeader } from "@/components/ui/DetailHeaderMenu";++interface MotionFragmentEditor3DProps {+ fragment: MockupMotionFragment;+ isGlobalMotionEnabled: boolean;+ onUpdate: (updates: Partial<MockupMotionFragment>) => void;+ onDelete: () => void;+ onClose: () => void;+}++/**+ * Dedicated editor for 3D motion fragments.+ *+ * 3D motion offsets (Mockup3DMotionCustomOffsets) are applied additively on+ * top of the preset's base animation by apply3DMotionCustomOffsets() in+ * lib/mockup-motion-3d.ts:+ *+ * scale = base.scale * custom.zoomMultiplier+ * posX = base.posX * sign + custom.positionX (scene units)+ * posY = base.posY * sign + custom.positionY (scene units)+ * rotX = base.rotX * sign + custom.rotateX * DEG (degrees → radians)+ * rotY = base.rotY * sign + custom.rotateY * DEG (degrees → radians)+ * rotZ = base.rotZ * sign + custom.rotateZ * DEG (degrees → radians)+ *+ * Where sign = custom.reverse ? -1 : 1.+ *+ * The model is scaled at ~0.004 in the viewer, so a position offset of ~0.2+ * roughly equals one body width.+ *+ * Instead, the position offsets are controlled via a PositionPad (drag to set+ * X/Y simultaneously) and rotation/scale/reverse use dedicated sliders. This+ * avoids DirectionPad (CSS perspective preview that doesn't match real 3D+ * geometry) and the blur slider (motion blur on 3D geometry requires+ * post-processing).+ */+export function MotionFragmentEditor3D({+ fragment,+ onUpdate,+ onDelete,+ onClose,+}: MotionFragmentEditor3DProps) {+ const t = useTranslations("motionMenu");+ const custom = fragment.custom3D ?? DEFAULT_3D_MOTION_CUSTOM_OFFSETS;++ const updateCustom = (partial: Partial<Mockup3DMotionCustomOffsets>) => {+ onUpdate({ custom3D: { ...custom, ...partial } });+ };++ const hasCustomChanges =+ custom.positionX !== 0 ||+ custom.positionY !== 0 ||+ custom.zoomMultiplier !== 1 ||+ custom.rotateX !== 0 ||+ custom.rotateY !== 0 ||+ custom.rotateZ !== 0 ||+ custom.reverse;++ return (+ <div className="flex flex-col h-full text-foreground">+ <MotionPresetIconStyles />++ <div className="flex items-center gap-2 p-3 border-b border-border shrink-0">+ <DetailPageHeader label={t("title")} icon="ph:arrow-left-bold" onBack={onClose} />+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 bg-muted/60 px-1.5 py-0.5 rounded shrink-0">+ 3D+ </span>+ <TooltipAction label={t("deleteTooltip")}>+ <button+ onClick={onDelete}+ className="ml-auto flex items-center gap-1.5 text-[11px] text-destructive/80 hover:text-destructive px-2 py-1 rounded-md transition-colors shrink-0"+ >+ <Icon icon="ph:trash-bold" width="12" />+ {t("actions.delete")}+ </button>+ </TooltipAction>+ </div>++ <div className="flex-1 overflow-y-auto custom-scrollbar px-4 py-4 space-y-5">+ {/* Preset intensity & speed */}+ <div className="flex flex-col gap-4">+ <SliderControl+ icon="mdi:tune-variant"+ label={t("controls.intensity")}+ value={fragment.intensity}+ min={0}+ max={100}+ onChange={(v: number) => onUpdate({ intensity: v })}+ />+ <SliderControl+ icon="mdi:speedometer"+ label={t("controls.speed")}+ value={fragment.speed}+ min={0}+ max={100}+ onChange={(v: number) => onUpdate({ speed: v })}+ />+ </div>++ {/* Rotation offsets (degrees, applied additively to base animation) */}+ <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">+ <div className="flex items-center gap-2">+ <Icon icon="mdi:rotate-3d-variant" width="16" className="text-muted-foreground" />+ <div>+ <p className="text-xs font-medium text-foreground/90">{t("customize3D.rotationTitle")}</p>+ <p className="text-[11px] text-muted-foreground">{t("customize3D.rotationSubtitle")}</p>+ </div>+ </div>++ <SliderControl+ icon="mdi:rotate-x"+ label={t("customize3D.rotateXLabel")}+ value={custom.rotateX}+ min={-180}+ max={180}+ onChange={(v: number) => updateCustom({ rotateX: v })}+ suffix="°"+ />+ <SliderControl+ icon="mdi:rotate-y"+ label={t("customize3D.rotateYLabel")}+ value={custom.rotateY}+ min={-180}+ max={180}+ onChange={(v: number) => updateCustom({ rotateY: v })}+ suffix="°"+ />+ <SliderControl+ icon="mdi:rotate-z"+ label={t("customize3D.rotateZLabel")}+ value={custom.rotateZ}+ min={-180}+ max={180}+ onChange={(v: number) => updateCustom({ rotateZ: v })}+ suffix="°"+ />+ </div>++ {/* Position offsets (scene units, applied additively to base animation) */}+ <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">+ <div className="flex items-center gap-2">+ <Icon icon="mdi:axis-arrow" width="16" className="text-muted-foreground" />+ <div>+ <p className="text-xs font-medium text-foreground/90">{t("customize3D.positionTitle")}</p>+ <p className="text-[11px] text-muted-foreground">{t("customize3D.positionSubtitle")}</p>+ </div>+ </div>++ <PositionPad+ x={Math.round(custom.positionX * 100)}+ y={Math.round(custom.positionY * 100)}+ onChange={(x, y) => updateCustom({ positionX: x / 100, positionY: y / 100 })}+ range={30}+ accentRgb="249,115,22"+ label={t("customize3D.positionLabel")}+ hint={t("customize3D.positionHint")}+ />+ </div>++ {/* Scale multiplier (uniform, applied multiplicatively) */}+ <div className="space-y-3 p-3 bg-muted/40 border border-border squircle-element">+ <div className="flex items-center gap-2">+ <Icon icon="mdi:resize" width="16" className="text-muted-foreground" />+ <div>+ <p className="text-xs font-medium text-foreground/90">{t("customize3D.scaleTitle")}</p>+ <p className="text-[11px] text-muted-foreground">{t("customize3D.scaleSubtitle")}</p>+ </div>+ </div>++ <SliderControl+ icon="mdi:magnify"+ label={t("customize3D.scaleLabel")}+ value={Math.round(custom.zoomMultiplier * 100)}+ min={50}+ max={200}+ onChange={(v: number) => updateCustom({ zoomMultiplier: v / 100 })}+ suffix="%"+ />+ </div>++ {/* Reverse direction toggle */}+ <label className="flex items-center justify-between px-3 py-2.5 rounded-lg bg-muted/40 border border-border">+ <span className="flex items-center gap-2 text-xs text-muted-foreground">+ <Icon icon="mdi:flip-horizontal" width="14" />+ {t("customize.reverseLabel")}+ </span>+ <Toggle+ checked={custom.reverse}+ onChange={(v: boolean) => updateCustom({ reverse: v })}+ activeColor="bg-orange-600"+ />+ </label>++ {hasCustomChanges && (+ <button+ onClick={() => onUpdate({ custom3D: { ...DEFAULT_3D_MOTION_CUSTOM_OFFSETS } })}+ className="self-start text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"+ >+ {t("customize.resetButton")}+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/app/components/ui/editor/MotionGlobalConfig.tsx b/app/components/ui/editor/MotionGlobalConfig.tsxindex fe646d0..519097c 100644--- a/app/components/ui/editor/MotionGlobalConfig.tsx+++ b/app/components/ui/editor/MotionGlobalConfig.tsx@@ -1,7 +1,7 @@"use client";import { Icon } from "@iconify/react";import { useTranslations } from "next-intl";-import { MOCKUP_MOTION_PRESETS, type MockupMotionPresetId, MockupMotionFragment } from "@/lib/mockup-motion";+import { MOCKUP_MOTION_PRESETS, type MockupMotionPresetId, type MockupMotionMode, MockupMotionFragment, getMotionPresetMode } from "@/lib/mockup-motion";import { MotionPresetIcon, MotionPresetIconStyles } from "../../../../components/ui/MotionPresetIcon";import { Toggle } from "@/components/ui/toggle";@@ -9,6 +9,7 @@ interface MotionGlobalConfigProps {fragments: MockupMotionFragment[];onAddOrReplacePreset: (presetId: MockupMotionPresetId) => void;hasMockup2D: boolean;+ hasMockup3D?: boolean;isGlobalMotionEnabled: boolean;onToggleGlobalMotion: (enabled: boolean) => void;}@@ -18,12 +19,22 @@ const CATEGORY_ORDER = ["Entrance", "Continue", "Exit"] as const;export function MotionGlobalConfig({onAddOrReplacePreset,hasMockup2D,+ hasMockup3D = false,isGlobalMotionEnabled,onToggleGlobalMotion,}: MotionGlobalConfigProps) {const t = useTranslations("motionMenu");- if (!hasMockup2D) {+ // Derive which motion mode is active: 3D takes priority when a 3D mockup+ // is present, otherwise fall back to 2D. When neither is present we show+ // the empty state.+ const activeMode: MockupMotionMode | null = hasMockup3D+ ? "3d"+ : hasMockup2D+ ? "2d"+ : null;++ if (!activeMode) {return (<div className="p-4 flex flex-col gap-5 h-full relative"><div className="flex items-center justify-between shrink-0">@@ -47,6 +58,8 @@ export function MotionGlobalConfig({);}+ const presetsForMode = MOCKUP_MOTION_PRESETS.filter((p) => p.mode === activeMode);+return (<div className="p-4 flex flex-col gap-4 h-full relative min-h-0"><MotionPresetIconStyles />@@ -54,6 +67,9 @@ export function MotionGlobalConfig({<div className="flex items-center gap-2 text-foreground font-medium"><Icon icon="ph:film-strip-bold" width="20" aria-hidden="true" /><span>{t("title")}</span>+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/70 bg-muted/60 px-1.5 py-0.5 rounded">+ {activeMode === "3d" ? "3D" : "2D"}+ </span></div><label className="flex items-center gap-2 text-xs text-muted-foreground"><span>{t("globalMotionLabel")}</span>@@ -63,7 +79,7 @@ export function MotionGlobalConfig({<div className="flex-1 min-h-0 overflow-y-auto custom-scrollbar -mx-1 px-1"><div className="flex flex-col gap-6">{CATEGORY_ORDER.map((category) => {- const presets = MOCKUP_MOTION_PRESETS.filter((p) => p.category === category);+ const presets = presetsForMode.filter((p) => p.category === category);if (presets.length === 0) return null;return (<div key={category}>@@ -95,4 +111,4 @@ export function MotionGlobalConfig({</div></div>);-}\ No newline at end of file+}diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsxindex 59d5393..63f5166 100644--- a/app/components/ui/editor/VideoCanvas.tsx+++ b/app/components/ui/editor/VideoCanvas.tsx@@ -1,6 +1,7 @@"use client";import { useRef, useEffect, useImperativeHandle, useMemo, useState, useCallback, memo } from "react";+import type * as THREE from "three";import type { VideoCanvasHandle, VideoCanvasProps, VideoThumbnail } from "@/types";import type { ImageElement } from "@/types/canvas-elements.types";import { ASPECT_RATIO_DIMENSIONS } from "@/types";@@ -31,7 +32,7 @@ import { renderCanvasElements } from "@/lib/canvas-elements-render.utils";import { drawMaskedImage } from "@/lib/masked-image-draw.utils";import { drawMockupAndMedia, type MockupDrawContext } from "@/lib/mockup-media-draw.utils";import { drawPhone3DCompositeWithZoom, type Phone3DCompositeContext } from "@/lib/phone3d-composite-draw.utils";-import { buildMockupMotionCss, MockupMotionTransform, REST_MOCKUP_MOTION, sampleCombinedMockupMotion } from "@/lib/mockup-motion";+import { buildMockupMotionCss, MockupMotionTransform, REST_MOCKUP_MOTION, sampleCombinedMockupMotion, sampleCombined3DMotion, REST_MOCKUP_3D_MOTION, Mockup3DMotionTransform, MOTION_PRESET_3D_IDS } from "@/lib/mockup-motion";import { Mockup3DFrame } from "./mockups-3d/Mockup3DFrame";import { filterVisibleElements } from "@/lib/canvas-elements-timeline.utils";import { ZoomPointOverlay, ZOOM_POINT_VISUAL_SCALE } from "@/components/ui/ZoomPointOverlay";@@ -239,6 +240,8 @@ function VideoCanvasInner({useEffect(() => { paddingRef.current = padding; }, [padding]);// WebGL canvas from image phone Phone3DViewer, captured via onMount prop for exportconst imagePhoneCanvasRef = useRef<HTMLCanvasElement | null>(null);+ // Root THREE.Group ref for applying 3D motion during export rendering.+ const imagePhoneRootRef = useRef<THREE.Group | null>(null);const imagePhoneApiRef = useRef<{renderAt: (w: number, h: number) => void;restorePreview: () => void;@@ -744,6 +747,19 @@ function VideoCanvasInner({[hasMockup2DMotion, mockupMotionFragments, currentTime]);+ // 3D motion: sample fragments that belong to 3D presets only.+ const hasMockup3DMotion = imagePhoneActive && mockupMotionFragments.some((f) => MOTION_PRESET_3D_IDS.has(f.presetId));++ const mockup3DMotionPreview = useMemo<Mockup3DMotionTransform>(+ () => {+ if (!hasMockup3DMotion) return REST_MOCKUP_3D_MOTION;+ const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId));+ if (fragments3D.length === 0) return REST_MOCKUP_3D_MOTION;+ return sampleCombined3DMotion(fragments3D as unknown as Parameters<typeof sampleCombined3DMotion>[0], currentTime);+ },+ [hasMockup3DMotion, mockupMotionFragments, currentTime]+ );+// Effective aspect ratio for the "none" mockup contain-box, adjusted for// any active crop — mirrors the same math used in drawFrame's computeContainer.const effectiveMediaAspect = mediaType === "video" ? (activeMediaAspect ?? mediaAspect) : mediaAspect;@@ -1330,6 +1346,16 @@ function VideoCanvasInner({? sampleCombinedMockupMotion(mockupMotionFragments, frameTime): undefined;+ // 3D motion sampled at this export frame's time.+ const motion3DForFrame: Mockup3DMotionTransform = hasMockup3DMotion+ ? (() => {+ const fragments3D = mockupMotionFragments.filter((f) => MOTION_PRESET_3D_IDS.has(f.presetId));+ return fragments3D.length > 0+ ? sampleCombined3DMotion(fragments3D as unknown as Parameters<typeof sampleCombined3DMotion>[0], frameTime)+ : REST_MOCKUP_3D_MOTION;+ })()+ : REST_MOCKUP_3D_MOTION;+const mockupDrawCtx: MockupDrawContext = {videoTransform, imageTransform, apply3DToBackground, imageZoomScale, shadows,mockupId, mockupConfig, mediaType, cropArea, sourceWidth, sourceHeight,@@ -1341,6 +1367,8 @@ function VideoCanvasInner({imagePhoneCanvasRef, imagePhoneApiRef, canvasDimensions, imagePhoneDevice,imagePhoneScale, imagePhoneX, imagePhoneY, imagePhoneShadow, imagePhoneShadowColor,effectivePhoneMaskConfig, maskCompositeCanvasRef,+ imagePhoneRootRef,+ motion3DForFrame,};ctx.setTransform(1, 0, 0, 1, 0, 0);@@ -1460,6 +1488,47 @@ function VideoCanvasInner({ctx.fill();ctx.restore();}+ // Apply 3D motion before rendering so the export frame reflects it.+ //+ // The preview's Motion3DApplicator runs useFrame every tick and+ // applies mockup3DMotionPreview (sampled at `currentTime`) to the+ // root group. By the time we reach here, motionRoot already holds+ // base + previewMotion. To produce a frame that matches the export+ // timeline (frameTime), we must subtract the preview motion first,+ // then apply the export motion (motion3DForFrame) on the real base.+ const motionRoot = imagePhoneRootRef.current;+ const m3d = motion3DForFrame;+ const previewMotion = mockup3DMotionPreview;+ const has3DMotion = motionRoot && m3d !== REST_MOCKUP_3D_MOTION;+ let savedBase: { rx: number; ry: number; rz: number; sx: number; sy: number; sz: number; px: number; py: number; pz: number } | null = null;+ if (has3DMotion && motionRoot) {+ // Save the current (base + previewMotion) state...+ savedBase = {+ rx: motionRoot.rotation.x, ry: motionRoot.rotation.y, rz: motionRoot.rotation.z,+ sx: motionRoot.scale.x, sy: motionRoot.scale.y, sz: motionRoot.scale.z,+ px: motionRoot.position.x, py: motionRoot.position.y, pz: motionRoot.position.z,+ };+ // ...compute the true base by subtracting the preview motion...+ const baseRx = savedBase.rx - previewMotion.rotX;+ const baseRy = savedBase.ry - previewMotion.rotY;+ const baseRz = savedBase.rz - previewMotion.rotZ;+ const baseSx = previewMotion.scale !== 0 ? savedBase.sx / previewMotion.scale : savedBase.sx;+ const baseSy = previewMotion.scale !== 0 ? savedBase.sy / previewMotion.scale : savedBase.sy;+ const baseSz = previewMotion.scale !== 0 ? savedBase.sz / previewMotion.scale : savedBase.sz;+ const basePx = savedBase.px - previewMotion.posX;+ const basePy = savedBase.py - previewMotion.posY;+ const basePz = savedBase.pz - previewMotion.posZ;+ // ...and apply the export-frame motion on the true base.+ motionRoot.rotation.x = baseRx + m3d.rotX;+ motionRoot.rotation.y = baseRy + m3d.rotY;+ motionRoot.rotation.z = baseRz + m3d.rotZ;+ motionRoot.scale.x = baseSx * m3d.scale;+ motionRoot.scale.y = baseSy * m3d.scale;+ motionRoot.scale.z = baseSz * m3d.scale;+ motionRoot.position.x = basePx + m3d.posX;+ motionRoot.position.y = basePy + m3d.posY;+ motionRoot.position.z = basePz + m3d.posZ;+ }if (highQuality) {imagePhoneApiRef.current?.renderAt(drawW, drawH);drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig, maskCompositeCanvasRef);@@ -1467,6 +1536,18 @@ function VideoCanvasInner({} else {drawMaskedImage(ctx, phoneGL, phoneCx - drawW / 2, phoneCy - drawH / 2, drawW, drawH, effectivePhoneMaskConfig, maskCompositeCanvasRef);}+ // Restore the root group's base transform after rendering.+ if (has3DMotion && motionRoot && savedBase) {+ motionRoot.rotation.x = savedBase.rx;+ motionRoot.rotation.y = savedBase.ry;+ motionRoot.rotation.z = savedBase.rz;+ motionRoot.scale.x = savedBase.sx;+ motionRoot.scale.y = savedBase.sy;+ motionRoot.scale.z = savedBase.sz;+ motionRoot.position.x = savedBase.px;+ motionRoot.position.y = savedBase.py;+ motionRoot.position.z = savedBase.pz;+ }}ctx.restore();@@ -2431,6 +2512,7 @@ function VideoCanvasInner({) : (<Mockup3DFramedevice={imagePhoneDevice}+ rootRef={imagePhoneRootRef}imageUrl={imageUrl}videoElement={activeVideoElement ?? undefined}openingProgress={imagePhoneDevice === "laptop" ? imagePhoneOpening : undefined}@@ -2453,6 +2535,7 @@ function VideoCanvasInner({isSelected={isVideoSelected}isHovered={isVideoHovered}onSelectChange={(value) => setIsVideoSelected(value)}+ motionTransform={mockup3DMotionPreview}/>)}</div>diff --git a/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx b/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsxindex 9b9f010..c8b1e19 100644--- a/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx+++ b/app/components/ui/editor/mockups-3d/Mockup3DFrame.tsx@@ -72,9 +72,9 @@ interface FrameProps extends Mockup3DStageProps {device: ImageDeviceId;}-export function Mockup3DFrame({ device, ...stageProps }: FrameProps) {+export function Mockup3DFrame({ device, rootRef: externalRootRef, ...stageProps }: FrameProps) {const layout = DEVICE_LAYOUT[device];- const rootRef = useRef<THREE.Group | null>(null);+ const rootRef = externalRootRef ?? useRef<THREE.Group | null>(null);const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);const canvasElRef = useRef<HTMLCanvasElement | null>(null);const raycasterRef = useRef(new THREE.Raycaster());diff --git a/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx b/app/components/ui/editor/mockups-3d/Mockup3DStage.tsxindex 9d7d6f7..347b448 100644--- a/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx+++ b/app/components/ui/editor/mockups-3d/Mockup3DStage.tsx@@ -1,6 +1,6 @@"use client";import { Canvas } from "@react-three/fiber";-import { Suspense, useRef, useState } from "react";+import { Suspense, useEffect, useRef, useState } from "react";import * as THREE from "three";import { IPhone13ProMax3DApi, IPhone13ProMaxScene } from "./IPhone13ProMax3DViewer";import { DoubleIPhone3DApi, DoubleIPhoneScene } from "./DoubleIPhone3DViewer";@@ -11,6 +11,8 @@ import { IPadMini63DApi, IPadMiniScene } from "./IPadMini63DViewer";import { ImageMaskConfigLike } from "@/lib/phone3d.utils";import type { ImageDeviceId } from "@/types/mockup.types";import { EnvironmentPreset } from "@/lib/viewer-controls3d";+import { REST_MOCKUP_3D_MOTION, type Mockup3DMotionTransform } from "@/lib/mockup-motion-3d";+import { useFrame } from "@react-three/fiber";export type Mockup3DApi =| IPhone13ProMax3DApi@@ -45,15 +47,82 @@ export interface Mockup3DStageProps {isHovered?: boolean;onHoverChange?: (isHovered: boolean) => void;onSelectChange?: (isSelected: boolean) => void;+ /** 3D motion transform applied additively to the root group every frame. */+ motionTransform?: Mockup3DMotionTransform;+ /** External root group ref, used for export-time motion application. */+ rootRef?: React.MutableRefObject<THREE.Group | null>;}interface StageProps extends Mockup3DStageProps {device: ImageDeviceId;- rootRef?: React.MutableRefObject<THREE.Group | null>;cameraRef?: React.MutableRefObject<THREE.PerspectiveCamera | null>;onLoadedChange?: (loaded: boolean) => void;}+/**+ * Applies a 3D motion transform to the root group every frame.+ * Records the base rotation/scale/position on first mount, then adds+ * the motion transform additively so the model's base pose is preserved.+ */+function Motion3DApplicator({+ rootRef,+ motionTransform,+}: {+ rootRef: React.MutableRefObject<THREE.Group | null>;+ motionTransform: Mockup3DMotionTransform;+}) {+ const baseRef = useRef<{ rx: number; ry: number; rz: number; sx: number; sy: number; sz: number; px: number; py: number; pz: number } | null>(null);++ useEffect(() => {+ const root = rootRef.current;+ if (!root || baseRef.current) return;+ baseRef.current = {+ rx: root.rotation.x,+ ry: root.rotation.y,+ rz: root.rotation.z,+ sx: root.scale.x,+ sy: root.scale.y,+ sz: root.scale.z,+ px: root.position.x,+ py: root.position.y,+ pz: root.position.z,+ };+ }, [rootRef]);++ useFrame(() => {+ const root = rootRef.current;+ if (!root) return;+ // Capture the base transform lazily inside useFrame in case the group+ // mounts after the initial useEffect (R3F suspends scene children).+ if (!baseRef.current) {+ baseRef.current = {+ rx: root.rotation.x,+ ry: root.rotation.y,+ rz: root.rotation.z,+ sx: root.scale.x,+ sy: root.scale.y,+ sz: root.scale.z,+ px: root.position.x,+ py: root.position.y,+ pz: root.position.z,+ };+ }+ const base = baseRef.current;+ const m = motionTransform;+ root.rotation.x = base.rx + m.rotX;+ root.rotation.y = base.ry + m.rotY;+ root.rotation.z = base.rz + m.rotZ;+ root.scale.x = base.sx * m.scale;+ root.scale.y = base.sy * m.scale;+ root.scale.z = base.sz * m.scale;+ root.position.x = base.px + m.posX;+ root.position.y = base.py + m.posY;+ root.position.z = base.pz + m.posZ;+ });++ return null;+}+export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: externalCameraRef, onLoadedChange, ...props }: StageProps) {const internalRootRef = useRef<THREE.Group | null>(null);const internalCameraRef = useRef<THREE.PerspectiveCamera | null>(null);@@ -61,6 +130,11 @@ export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: extconst cameraRef = externalCameraRef ?? internalCameraRef;const canvasElRef = useRef<HTMLCanvasElement | null>(null);+ // When 3D motion is active we need a continuous render loop so the+ // Motion3DApplicator's useFrame fires every tick. Without this, the+ // "demand" frameloop would only re-render on user interaction.+ const hasMotion = props.motionTransform && props.motionTransform !== REST_MOCKUP_3D_MOTION;+const [loaded, setLoaded] = useState(false);const [prevDevice, setPrevDevice] = useState(device);if (device !== prevDevice) {@@ -91,7 +165,7 @@ export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: extfailIfMajorPerformanceCaveat: false,}}dpr={3}- frameloop={props.videoElement ? "always" : "demand"}+ frameloop={props.videoElement || hasMotion ? "always" : "demand"}resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}onCreated={({ gl, scene }) => {gl.outputColorSpace = THREE.SRGBColorSpace;@@ -101,6 +175,7 @@ export function Mockup3DStage({ device, rootRef: externalRootRef, cameraRef: exthandleMount(gl.domElement);}}>+ <Motion3DApplicator rootRef={rootRef} motionTransform={props.motionTransform ?? REST_MOCKUP_3D_MOTION} /><Suspense fallback={null}>{device === "iphone-13-pro-max" && (<IPhone13ProMaxScene {...props} rootRef={rootRef} cameraRef={cameraRef} onLoaded={markLoaded} />diff --git a/components/ui/MotionPresetIcon.tsx b/components/ui/MotionPresetIcon.tsxindex 4d386fe..8ac0b67 100644--- a/components/ui/MotionPresetIcon.tsx+++ b/components/ui/MotionPresetIcon.tsx@@ -138,6 +138,18 @@ export function MotionPresetIconStyles() {.force-animate .mp-card--crane-sweep {animation: mp-crane-sweep 3.2s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;}+ .group:hover .mp-card--orbit-entrance,+ .force-animate .mp-card--orbit-entrance {+ animation: mp-orbit-entrance 1.6s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }+ .group:hover .mp-card--turntable-drift,+ .force-animate .mp-card--turntable-drift {+ animation: mp-turntable-drift 3s ease-in-out infinite alternate;+ }+ .group:hover .mp-card--flick-exit,+ .force-animate .mp-card--flick-exit {+ animation: mp-flick-exit 1s cubic-bezier(0.65, 0, 0.35, 1) infinite alternate;+ }}@keyframes mp-focus-in {0% { transform: scale(1.22); filter: blur(3.5px); opacity: 0.45; }@@ -199,6 +211,23 @@ export function MotionPresetIconStyles() {82% { transform: scale(1.14) rotateX(12deg) rotateY(16deg) translate(-3%, 2%); }100% { transform: scale(1) rotateX(-58deg); }}+ @keyframes mp-orbit-entrance {+ 0% { transform: scale(0.55) rotateY(180deg) rotateX(30deg) translateY(20%); opacity: 0; }+ 60% { transform: scale(0.9) rotateY(40deg) rotateX(10deg) translateY(5%); opacity: 0.8; }+ 100% { transform: scale(1) rotateY(0) rotateX(0) translateY(0); opacity: 1; }+ }+ @keyframes mp-turntable-drift {+ 0% { transform: rotateY(0deg) translateY(0) scale(1); opacity: 0.6; }+ 25% { transform: rotateY(90deg) translateY(-3%) scale(1.01); opacity: 1; }+ 50% { transform: rotateY(180deg) translateY(0) scale(0.99); opacity: 1; }+ 75% { transform: rotateY(270deg) translateY(3%) scale(1.01); opacity: 1; }+ 100% { transform: rotateY(360deg) translateY(0) scale(1); opacity: 0.6; }+ }+ @keyframes mp-flick-exit {+ 0% { transform: rotateY(0) translateX(0) scale(1); opacity: 1; }+ 50% { transform: rotateY(40deg) translateX(10%) scale(0.95); opacity: 0.7; }+ 100% { transform: rotateY(100deg) translateX(35%) scale(0.8); opacity: 0; }+ }`}</style>);}\ No newline at end of filediff --git a/hooks/useMockupMotionFragments.ts b/hooks/useMockupMotionFragments.tsindex 72e10fa..a8207fb 100644--- a/hooks/useMockupMotionFragments.ts+++ b/hooks/useMockupMotionFragments.ts@@ -3,8 +3,10 @@ import { useState, useCallback, useMemo, useRef, useEffect } from "react";import {DEFAULT_MOCKUP_MOTION_CONFIG,findValidMotionPlacement,+ MOTION_PRESET_3D_IDS,type MockupMotionFragment,type MockupMotionPresetId,+ type MockupMotionMode,} from "@/lib/mockup-motion";import { Tool } from "@/types";@@ -15,16 +17,46 @@ interface UseMockupMotionFragmentsParams {lastCopyActionRef: React.MutableRefObject<'element' | 'zoom' | 'motion' | null>;selectedMockupMotionFragmentId: string | null;setSelectedMockupMotionFragmentId: React.Dispatch<React.SetStateAction<string | null>>;+ /** Current active motion mode — when this changes, orphan fragments from+ * the previous mode are pruned so the timeline stays clean. */+ motionMode?: MockupMotionMode | null;}export function useMockupMotionFragments({currentTime, videoDuration, setActiveTool, lastCopyActionRef,selectedMockupMotionFragmentId, setSelectedMockupMotionFragmentId,+ motionMode,}: UseMockupMotionFragmentsParams) {const [mockupMotionFragments, setMockupMotionFragments] = useState<MockupMotionFragment[]>([]);const mockupMotionFragmentsRef = useRef<MockupMotionFragment[]>([]);useEffect(() => { mockupMotionFragmentsRef.current = mockupMotionFragments; }, [mockupMotionFragments]);+ // Prune orphan fragments when the motion mode changes (e.g. switching from+ // a 3D mockup to a 2D mockup). Fragments whose preset belongs to the other+ // mode are removed, and the selection is cleared if it pointed to one of them.+ const prevMotionModeRef = useRef<MockupMotionMode | null | undefined>(motionMode);+ useEffect(() => {+ if (prevMotionModeRef.current === motionMode) return;+ const prevMode = prevMotionModeRef.current;+ prevMotionModeRef.current = motionMode;+ if (!prevMode || !motionMode || prevMode === motionMode) return;++ setMockupMotionFragments((prev) => {+ const kept = prev.filter((f) => {+ const is3D = MOTION_PRESET_3D_IDS.has(f.presetId);+ return motionMode === "3d" ? is3D : !is3D;+ });+ if (kept.length !== prev.length) {+ const removed = prev.filter((f) => !kept.includes(f));+ const removedIds = new Set(removed.map((f) => f.id));+ if (removedIds.has(selectedMockupMotionFragmentId ?? "")) {+ setSelectedMockupMotionFragmentId(null);+ }+ }+ return kept;+ });+ }, [motionMode, selectedMockupMotionFragmentId, setSelectedMockupMotionFragmentId]);+const [copiedMockupMotionFragment, setCopiedMockupMotionFragment] = useState<Omit<MockupMotionFragment, 'id' | 'startTime' | 'endTime'> | null>(null);const selectedMockupMotionFragment = useMemo(diff --git a/lib/mockup-motion-3d.ts b/lib/mockup-motion-3d.tsnew file mode 100644index 0000000..9b3239e--- /dev/null+++ b/lib/mockup-motion-3d.ts@@ -0,0 +1,408 @@+/**+ * Motion presets for 3D mockups (Three.js / React Three Fiber).+ *+ * Unlike 2D motion (which produces CSS transforms applied to a DOM element),+ * 3D motion produces values intended to be applied directly to a THREE.Group+ * inside the scene graph: Euler rotation (radians), position offset (scene+ * units), uniform scale, and opacity. The consumers (Mockup3DStage) apply+ * these on top of the model's base transform every frame via useFrame.+ *+ * The preset vocabulary is intentionally separate from 2D motion because the+ * visual language differs: 3D models benefit from real orbital camera moves,+ * physical depth parallax, and tumbling reveals that CSS perspective cannot+ * reproduce faithfully.+ */++export type Mockup3DMotionPresetId =+ | "none"+ | "orbit-entrance"+ | "turntable-drift"+ | "flick-exit";++export const MOCKUP_3D_MOTION_PRESETS: {+ id: Mockup3DMotionPresetId;+ category: "Entrance" | "Continue" | "Exit";+}[] = [+ { id: "orbit-entrance", category: "Entrance" },+ { id: "turntable-drift", category: "Continue" },+ { id: "flick-exit", category: "Exit" },+];++export interface Mockup3DMotionConfig {+ presetId: Mockup3DMotionPresetId;+ intensity: number;+ speed: number;+}++export const DEFAULT_MOCKUP_3D_MOTION_CONFIG: Mockup3DMotionConfig = {+ presetId: "none",+ intensity: 50,+ speed: 50,+};++/**+ * Transform payload consumed by the 3D stage. All rotations are in RADIANS,+ * position offsets are in scene units (the model is scaled at scale=0.004 in+ * the iPhone viewer, so a position offset of ~0.2 roughly equals one body+ * width), and scale is a uniform multiplier on top of the base scale.+ */+export interface Mockup3DMotionTransform {+ /** Euler rotation applied additively to the root group (radians). */+ rotX: number;+ rotY: number;+ rotZ: number;+ /** Position offset added to the root group (scene units). */+ posX: number;+ posY: number;+ posZ: number;+ /** Uniform scale multiplier (1 = no change). */+ scale: number;+ /** Opacity [0..1] — applied to materials when < 1. */+ opacity: number;+}++export const REST_MOCKUP_3D_MOTION: Mockup3DMotionTransform = {+ rotX: 0,+ rotY: 0,+ rotZ: 0,+ posX: 0,+ posY: 0,+ posZ: 0,+ scale: 1,+ opacity: 1,+};++const clamp01 = (n: number) => Math.max(0, Math.min(1, n));+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+const DEG = Math.PI / 180;++function easeOutCubic(t: number) {+ return 1 - (1 - t) ** 3;+}++function easeInOutCubic(t: number) {+ return t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;+}++function easeOutBack(t: number) {+ const c1 = 1.70158;+ const c3 = c1 + 1;+ return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2;+}++function easeOutQuint(t: number) {+ return 1 - (1 - t) ** 5;+}++function speedToDurationSec(speed: number): number {+ return lerp(1.6, 0.5, clamp01(speed / 100));+}++export function sampleMockup3DMotion(+ config: Mockup3DMotionConfig,+ currentTime: number,+ clipDurationSec: number+): Mockup3DMotionTransform {+ const { presetId, intensity, speed } = config;+ const i = clamp01(intensity / 100);++ if (presetId === "none" || clipDurationSec <= 0) return REST_MOCKUP_3D_MOTION;++ switch (presetId) {+ /**+ * ORBIT ENTRANCE — the model sweeps in from a dramatic three-quarter+ * angle while rising on the Y axis, then settles into its resting pose.+ * Feels like a hero product reveal on a turntable.+ */+ case "orbit-entrance": {+ const dur = Math.min(speedToDurationSec(speed) * 1.2, clipDurationSec);+ const t = clamp01(currentTime / dur);+ const eased = easeOutCubic(t);++ const startRotY = lerp(140, 220, i) * DEG;+ const startRotX = lerp(20, 40, i) * DEG;+ const startRotZ = lerp(-12, -24, i) * DEG;+ const startY = lerp(0.12, 0.28, i);+ const startScale = lerp(0.65, 0.4, i);++ const settleRot = easeOutBack(clamp01(t));+ const rotY = lerp(startRotY, 0, eased);+ const rotX = lerp(startRotX, 0, settleRot);+ const rotZ = lerp(startRotZ, 0, eased);+ const posY = lerp(startY, 0, eased);+ const scale = lerp(startScale, 1, settleRot);++ return {+ ...REST_MOCKUP_3D_MOTION,+ rotX,+ rotY,+ rotZ,+ posY,+ scale,+ opacity: easeOutCubic(clamp01(t * 2.2)),+ };+ }++ /**+ * TURNTABLE DRIFT — a continuous, slow orbital drift with subtle vertical+ * bob and a gentle scale breathing. Designed to run for the whole clip+ * duration so the model always feels alive without distracting from the+ * screen content.+ */+ case "turntable-drift": {+ const p = clamp01(currentTime / clipDurationSec);+ const speedT = clamp01(speed / 100);++ // Full revolution cadence: faster speed completes more turns.+ const turns = lerp(0.4, 1.1, speedT);+ const rotY = p * Math.PI * 2 * turns;++ // Vertical bob: 1.5 oscillations across the clip.+ const bobAmp = lerp(0.015, 0.045, i);+ const posY = Math.sin(p * Math.PI * 2 * 1.5) * bobAmp;++ // Subtle X-axis tilt sway synced to the bob for a floating feel.+ const tiltAmp = lerp(3, 8, i) * DEG;+ const rotX = Math.sin(p * Math.PI * 2 * 1.5 + Math.PI / 2) * tiltAmp;++ // Gentle breathing scale.+ const breathAmp = lerp(0.008, 0.02, i);+ const scale = 1 + Math.sin(p * Math.PI * 2 * 1.5) * breathAmp;++ // Soft entry fade-in over the first ~12% so it never pops.+ const entryFade = easeOutCubic(clamp01(p / 0.12));++ return {+ ...REST_MOCKUP_3D_MOTION,+ rotX,+ rotY,+ scale,+ posY,+ opacity: entryFade,+ };+ }++ /**+ * FLICK EXIT — the model quickly tilts, rotates, and accelerates away+ * while fading out. Mirrors the physical "swipe away" gesture.+ */+ case "flick-exit": {+ const dur = Math.min(speedToDurationSec(speed), clipDurationSec);+ const startAt = Math.max(0, clipDurationSec - dur);+ const t = clamp01((currentTime - startAt) / dur);+ const eased = easeOutQuint(t);++ const exitRotY = lerp(60, 140, i) * DEG;+ const exitRotX = lerp(-15, -35, i) * DEG;+ const exitRotZ = lerp(8, 20, i) * DEG;+ const exitX = lerp(0.15, 0.4, i);+ const exitY = lerp(0.05, 0.18, i);+ const exitScale = lerp(0.92, 0.75, i);++ return {+ ...REST_MOCKUP_3D_MOTION,+ rotX: lerp(0, exitRotX, eased),+ rotY: lerp(0, exitRotY, eased),+ rotZ: lerp(0, exitRotZ, eased),+ posX: lerp(0, exitX, eased),+ posY: lerp(0, exitY, eased),+ scale: lerp(1, exitScale, eased),+ opacity: lerp(1, 0, eased),+ };+ }++ default:+ return REST_MOCKUP_3D_MOTION;+ }+}++const ENTRANCE_EXIT_PADDING = 1.4;+const DEFAULT_CONTINUOUS_DURATION = 3;++const SMALL_DURATION_PRESETS_3D = new Set<Mockup3DMotionPresetId>(["orbit-entrance"]);++const LONG_DURATION_PRESETS_3D = new Set<Mockup3DMotionPresetId>(["turntable-drift"]);++export function getDefault3DFragmentDuration(+ presetId: Mockup3DMotionPresetId,+ speed: number+): number {+ if (LONG_DURATION_PRESETS_3D.has(presetId)) {+ return lerp(10, 6.0, clamp01(speed / 100));+ }++ if (SMALL_DURATION_PRESETS_3D.has(presetId)) {+ return lerp(6, 3.5, clamp01(speed / 100));+ }++ const category = get3DMotionPresetCategory(presetId);++ if (category === "Entrance" || category === "Exit") {+ return speedToDurationSec(speed) * ENTRANCE_EXIT_PADDING;+ }++ return DEFAULT_CONTINUOUS_DURATION;+}++export interface Mockup3DMotionCustomOffsets {+ positionX: number;+ positionY: number;+ zoomMultiplier: number;+ rotateX: number;+ rotateY: number;+ rotateZ: number;+ reverse: boolean;+}++export const DEFAULT_3D_MOTION_CUSTOM_OFFSETS: Mockup3DMotionCustomOffsets = {+ positionX: 0,+ positionY: 0,+ zoomMultiplier: 1,+ rotateX: 0,+ rotateY: 0,+ rotateZ: 0,+ reverse: false,+};++export function get3DMotionPresetCategory(+ id: Mockup3DMotionPresetId+): (typeof MOCKUP_3D_MOTION_PRESETS)[number]["category"] {+ return MOCKUP_3D_MOTION_PRESETS.find((p) => p.id === id)?.category ?? "Continue";+}++function apply3DMotionCustomOffsets(+ base: Mockup3DMotionTransform,+ custom: Mockup3DMotionCustomOffsets | undefined+): Mockup3DMotionTransform {+ if (!custom) return base;++ const sign = custom.reverse ? -1 : 1;++ return {+ ...base,+ scale: base.scale * custom.zoomMultiplier,+ posX: base.posX * sign + custom.positionX,+ posY: base.posY * sign + custom.positionY,+ rotX: base.rotX * sign + custom.rotateX * DEG,+ rotY: base.rotY * sign + custom.rotateY * DEG,+ rotZ: base.rotZ * sign + custom.rotateZ * DEG,+ };+}++export interface Mockup3DMotionFragment extends Mockup3DMotionConfig {+ id: string;+ startTime: number;+ endTime: number;+ custom3D?: Mockup3DMotionCustomOffsets;+}++export function sample3DFragmentMotion(+ fragment: Mockup3DMotionFragment,+ currentTime: number+): Mockup3DMotionTransform {+ if (currentTime < fragment.startTime || currentTime > fragment.endTime) {+ return REST_MOCKUP_3D_MOTION;+ }++ const localTime = currentTime - fragment.startTime;+ const localDuration = fragment.endTime - fragment.startTime;++ const base = sampleMockup3DMotion(+ { presetId: fragment.presetId, intensity: fragment.intensity, speed: fragment.speed },+ localTime,+ localDuration+ );++ return apply3DMotionCustomOffsets(base, fragment.custom3D);+}++export function sampleCombined3DMotion(+ fragments: Mockup3DMotionFragment[],+ currentTime: number+): Mockup3DMotionTransform {+ const active = fragments.filter(+ (f) => currentTime >= f.startTime && currentTime <= f.endTime+ );++ if (active.length === 0) return REST_MOCKUP_3D_MOTION;++ return active.reduce<Mockup3DMotionTransform>(+ (acc, fragment) => {+ const t = sample3DFragmentMotion(fragment, currentTime);+ return {+ rotX: acc.rotX + t.rotX,+ rotY: acc.rotY + t.rotY,+ rotZ: acc.rotZ + t.rotZ,+ posX: acc.posX + t.posX,+ posY: acc.posY + t.posY,+ posZ: acc.posZ + t.posZ,+ scale: acc.scale * t.scale,+ opacity: acc.opacity * t.opacity,+ };+ },+ { ...REST_MOCKUP_3D_MOTION }+ );+}++export function findValid3DMotionPlacement(+ presetId: Mockup3DMotionPresetId,+ speed: number,+ hintTime: number,+ existingFragments: Mockup3DMotionFragment[],+ clipDurationSec: number+): { startTime: number; endTime: number } | null {+ const duration = Math.min(getDefault3DFragmentDuration(presetId, speed), clipDurationSec);+ if (duration <= 0 || clipDurationSec <= 0) return null;++ const category = get3DMotionPresetCategory(presetId);+ const sorted = [...existingFragments].sort((a, b) => a.startTime - b.startTime);++ const overlaps = (start: number, end: number) =>+ sorted.some((f) => start < f.endTime && end > f.startTime);++ const tryPlace = (start: number) => {+ const end = start + duration;+ if (start < 0 || end > clipDurationSec) return null;+ return overlaps(start, end) ? null : { startTime: start, endTime: end };+ };++ const preferredStart =+ category === "Entrance"+ ? 0+ : category === "Exit"+ ? Math.max(0, clipDurationSec - duration)+ : Math.max(0, Math.min(hintTime - duration / 2, clipDurationSec - duration));++ const direct = tryPlace(preferredStart);+ if (direct) return direct;++ const gaps: { start: number; end: number }[] = [];+ let cursor = 0;++ for (const f of sorted) {+ if (f.startTime > cursor) gaps.push({ start: cursor, end: f.startTime });+ cursor = Math.max(cursor, f.endTime);+ }++ if (cursor < clipDurationSec) gaps.push({ start: cursor, end: clipDurationSec });++ const fitting = gaps.filter((g) => g.end - g.start >= duration);+ if (fitting.length === 0) return null;++ fitting.sort((a, b) => {+ const da = Math.min(+ Math.abs(a.start - preferredStart),+ Math.abs(a.end - duration - preferredStart)+ );+ const db = Math.min(+ Math.abs(b.start - preferredStart),+ Math.abs(b.end - duration - preferredStart)+ );+ return da - db;+ });++ const gap = fitting[0];+ const start = Math.max(gap.start, Math.min(preferredStart, gap.end - duration));++ return { startTime: start, endTime: start + duration };+}diff --git a/lib/mockup-motion.ts b/lib/mockup-motion.tsindex ad18d0f..c5d04f7 100644--- a/lib/mockup-motion.ts+++ b/lib/mockup-motion.ts@@ -1,3 +1,5 @@+import { getDefault3DFragmentDuration, type Mockup3DMotionPresetId } from "./mockup-motion-3d";+export type MockupMotionPresetId =| "none"| "focus-in"@@ -11,26 +13,46 @@ export type MockupMotionPresetId =| "spatial-roam"| "rise-crash"| "crane-sweep"- | "z-spin-reveal";+ | "z-spin-reveal"+ | "orbit-entrance"+ | "turntable-drift"+ | "flick-exit";++export type MockupMotionMode = "2d" | "3d";-export const MOCKUP_MOTION_PRESETS: {+export interface MockupMotionPresetDef {id: MockupMotionPresetId;category: "Entrance" | "Continue" | "Exit";-}[] = [- { id: "focus-in", category: "Entrance" },- { id: "depth-emerge", category: "Entrance" },- { id: "z-spin-reveal", category: "Entrance" },- { id: "isometric-lift", category: "Entrance" },- { id: "cinematic-showcase", category: "Continue" },- { id: "macro-track", category: "Continue" },- { id: "whip-showcase", category: "Continue" },- { id: "spatial-roam", category: "Continue" },- { id: "crane-sweep", category: "Continue" },- { id: "rise-crash", category: "Continue" },- { id: "exit-fade-down", category: "Exit" },- { id: "exit-scale-blur", category: "Exit" },+ mode: MockupMotionMode;+}++export const MOCKUP_MOTION_PRESETS: MockupMotionPresetDef[] = [+ { id: "focus-in", category: "Entrance", mode: "2d" },+ { id: "depth-emerge", category: "Entrance", mode: "2d" },+ { id: "z-spin-reveal", category: "Entrance", mode: "2d" },+ { id: "isometric-lift", category: "Entrance", mode: "2d" },+ { id: "cinematic-showcase", category: "Continue", mode: "2d" },+ { id: "macro-track", category: "Continue", mode: "2d" },+ { id: "whip-showcase", category: "Continue", mode: "2d" },+ { id: "spatial-roam", category: "Continue", mode: "2d" },+ { id: "crane-sweep", category: "Continue", mode: "2d" },+ { id: "rise-crash", category: "Continue", mode: "2d" },+ { id: "exit-fade-down", category: "Exit", mode: "2d" },+ { id: "exit-scale-blur", category: "Exit", mode: "2d" },+ { id: "orbit-entrance", category: "Entrance", mode: "3d" },+ { id: "turntable-drift", category: "Continue", mode: "3d" },+ { id: "flick-exit", category: "Exit", mode: "3d" },];+/** IDs that belong to 3D mode (used for routing to the 3D sampler). */+export const MOTION_PRESET_3D_IDS: ReadonlySet<MockupMotionPresetId> = new Set(+ MOCKUP_MOTION_PRESETS.filter((p) => p.mode === "3d").map((p) => p.id)+);++export function getMotionPresetMode(id: MockupMotionPresetId): MockupMotionMode {+ return MOCKUP_MOTION_PRESETS.find((p) => p.id === id)?.mode ?? "2d";+}+export interface MockupMotionConfig {presetId: MockupMotionPresetId;intensity: number;@@ -1206,6 +1228,8 @@ export interface MockupMotionFragment extends MockupMotionConfig {startTime: number;endTime: number;custom?: MotionCustomOffsets;+ /** Custom offsets for 3D presets. Only used when presetId is a 3D preset. */+ custom3D?: import("./mockup-motion-3d").Mockup3DMotionCustomOffsets;}export function getMotionPresetCategory(@@ -1245,6 +1269,14 @@ export function sampleFragmentMotion(const localTime = currentTime - fragment.startTime;const localDuration = fragment.endTime - fragment.startTime;+ // 3D presets produce CSS-compatible values by mapping the 3D transform+ // back into the 2D transform space so the existing CSS pipeline keeps+ // working. The real 3D application happens in Mockup3DStage via+ // sampleCombined3DMotion.+ if (MOTION_PRESET_3D_IDS.has(fragment.presetId)) {+ return REST_MOCKUP_MOTION;+ }+const base = sampleMockupMotion({ presetId: fragment.presetId, intensity: fragment.intensity, speed: fragment.speed },localTime,@@ -1290,7 +1322,11 @@ export function findValidMotionPlacement(existingFragments: MockupMotionFragment[],clipDurationSec: number): { startTime: number; endTime: number } | null {- const duration = Math.min(getDefaultFragmentDuration(presetId, speed), clipDurationSec);+ const is3D = MOTION_PRESET_3D_IDS.has(presetId);+ const defaultDur = is3D+ ? getDefault3DFragmentDuration(presetId as Mockup3DMotionPresetId, speed)+ : getDefaultFragmentDuration(presetId, speed);+ const duration = Math.min(defaultDur, clipDurationSec);if (duration <= 0 || clipDurationSec <= 0) return null;const category = getMotionPresetCategory(presetId);@@ -1344,4 +1380,14 @@ export function findValidMotionPlacement(const start = Math.max(gap.start, Math.min(preferredStart, gap.end - duration));return { startTime: start, endTime: start + duration };-}\ No newline at end of file+}++// Re-export 3D helpers so consumers can import everything from one module.+export {+ getDefault3DFragmentDuration,+ sampleCombined3DMotion,+ type Mockup3DMotionTransform,+ type Mockup3DMotionCustomOffsets,+ DEFAULT_3D_MOTION_CUSTOM_OFFSETS,+ REST_MOCKUP_3D_MOTION,+} from "./mockup-motion-3d";\ No newline at end of filediff --git a/lib/phone3d-composite-draw.utils.ts b/lib/phone3d-composite-draw.utils.tsindex 7685f51..d97ab4f 100644--- a/lib/phone3d-composite-draw.utils.ts+++ b/lib/phone3d-composite-draw.utils.ts@@ -1,6 +1,9 @@import type { MutableRefObject } from "react";import { drawMaskedImage } from "@/lib/masked-image-draw.utils";import { PHONE_H, PHONE_W, DEVICE_3D_DIMENSIONS, type ImageMaskConfigLike } from "@/lib/phone3d.utils";+import type { Mockup3DMotionTransform } from "@/lib/mockup-motion-3d";+import { REST_MOCKUP_3D_MOTION } from "@/lib/mockup-motion-3d";+import * as THREE from "three";export interface Phone3DApi {renderAt: (w: number, h: number) => void;@@ -21,8 +24,19 @@ export interface Phone3DCompositeContext {imagePhoneShadowColor: string;effectivePhoneMaskConfig: ImageMaskConfigLike | null | undefined;maskCompositeCanvasRef: MutableRefObject<HTMLCanvasElement | null>;+ /** Root group ref for applying 3D motion during export. */+ imagePhoneRootRef?: MutableRefObject<THREE.Group | null>;+ /** 3D motion transform to apply before rendering each export frame. */+ motion3DForFrame?: Mockup3DMotionTransform;}+// Cache of the base transform so we can restore after export rendering.+let cachedBase: {+ rx: number; ry: number; rz: number;+ sx: number; sy: number; sz: number;+ px: number; py: number; pz: number;+} | null = null;+export function drawPhone3DCompositeWithZoom(c: CanvasRenderingContext2D,canvasWidth: number,@@ -38,6 +52,7 @@ export function drawPhone3DCompositeWithZoom(imagePhoneCanvasRef, imagePhoneApiRef, canvasDimensions, imagePhoneDevice,imagePhoneScale, imagePhoneX, imagePhoneY, imagePhoneShadow, imagePhoneShadowColor,effectivePhoneMaskConfig, maskCompositeCanvasRef,+ imagePhoneRootRef, motion3DForFrame,} = ctx2;const phoneGL = imagePhoneCanvasRef.current!;@@ -54,6 +69,32 @@ export function drawPhone3DCompositeWithZoom(const baseW = deviceDims.width * imagePhoneScale * pxScale;const baseH = deviceDims.height * imagePhoneScale * pxScale;+ // Apply 3D motion to the root group before high-quality render so the+ // exported frame reflects the motion at this frame time. We capture the+ // base transform on first use and restore it after rendering.+ const root = imagePhoneRootRef?.current;+ const motion = motion3DForFrame ?? REST_MOCKUP_3D_MOTION;+ const hasMotion = root && motion !== REST_MOCKUP_3D_MOTION;++ if (hasMotion && root) {+ if (!cachedBase) {+ cachedBase = {+ rx: root.rotation.x, ry: root.rotation.y, rz: root.rotation.z,+ sx: root.scale.x, sy: root.scale.y, sz: root.scale.z,+ px: root.position.x, py: root.position.y, pz: root.position.z,+ };+ }+ root.rotation.x = cachedBase.rx + motion.rotX;+ root.rotation.y = cachedBase.ry + motion.rotY;+ root.rotation.z = cachedBase.rz + motion.rotZ;+ root.scale.x = cachedBase.sx * motion.scale;+ root.scale.y = cachedBase.sy * motion.scale;+ root.scale.z = cachedBase.sz * motion.scale;+ root.position.x = cachedBase.px + motion.posX;+ root.position.y = cachedBase.py + motion.posY;+ root.position.z = cachedBase.pz + motion.posZ;+ }+if (highQuality) {imagePhoneApiRef.current?.renderAt(baseW, baseH);}@@ -106,4 +147,18 @@ export function drawPhone3DCompositeWithZoom(if (highQuality) {imagePhoneApiRef.current?.restorePreview();}-}\ No newline at end of file++ // Restore the root group's base transform after rendering so the live+ // preview's Motion3DApplicator doesn't compound on our changes.+ if (hasMotion && root && cachedBase) {+ root.rotation.x = cachedBase.rx;+ root.rotation.y = cachedBase.ry;+ root.rotation.z = cachedBase.rz;+ root.scale.x = cachedBase.sx;+ root.scale.y = cachedBase.sy;+ root.scale.z = cachedBase.sz;+ root.position.x = cachedBase.px;+ root.position.y = cachedBase.py;+ root.position.z = cachedBase.pz;+ }+}diff --git a/messages/en.json b/messages/en.jsonindex af777cb..4d9b521 100644--- a/messages/en.json+++ b/messages/en.json@@ -1402,6 +1402,20 @@"reverseLabel": "Reverse direction","resetButton": "Reset customization","blurLabel": "Motion blur"+ },+ "customize3D": {+ "rotationTitle": "Rotation offsets",+ "rotationSubtitle": "Added to the preset's base rotation (degrees)",+ "rotateXLabel": "Rotate X (pitch)",+ "rotateYLabel": "Rotate Y (yaw)",+ "rotateZLabel": "Rotate Z (roll)",+ "positionTitle": "Position offsets",+ "positionSubtitle": "Added to the preset's base position (scene units)",+ "positionLabel": "Position",+ "positionHint": "Drag to set X / Y position",+ "scaleTitle": "Scale",+ "scaleSubtitle": "Uniform multiplier applied to the model",+ "scaleLabel": "Scale"}},"MobileTools": {diff --git a/messages/es.json b/messages/es.jsonindex 65eb175..ddf6c57 100644--- a/messages/es.json+++ b/messages/es.json@@ -1380,6 +1380,20 @@"reverseLabel": "Invertir dirección","resetButton": "Restablecer personalización","blurLabel": "Desenfoque de movimiento"+ },+ "customize3D": {+ "rotationTitle": "Offsets de rotación",+ "rotationSubtitle": "Sumados a la rotación base del preset (grados)",+ "rotateXLabel": "Rotar X (pitch)",+ "rotateYLabel": "Rotar Y (yaw)",+ "rotateZLabel": "Rotar Z (roll)",+ "positionTitle": "Offsets de posición",+ "positionSubtitle": "Sumados a la posición base del preset (unidades de escena)",+ "positionLabel": "Posición",+ "positionHint": "Arrastra para ajustar la posición X / Y",+ "scaleTitle": "Escala",+ "scaleSubtitle": "Multiplicador uniforme aplicado al modelo",+ "scaleLabel": "Escala"}},"MobileTools": {diff --git a/messages/ko.json b/messages/ko.jsonindex e5b3206..adb2273 100644--- a/messages/ko.json+++ b/messages/ko.json@@ -1402,6 +1402,20 @@"reverseLabel": "방향 반전","resetButton": "커스터마이즈 초기화","blurLabel": "모션 블러"+ },+ "customize3D": {+ "rotationTitle": "회전 오프셋",+ "rotationSubtitle": "프리셋 기본 회전에 추가됨 (도)",+ "rotateXLabel": "X 회전 (피치)",+ "rotateYLabel": "Y 회전 (요)",+ "rotateZLabel": "Z 회전 (롤)",+ "positionTitle": "위치 오프셋",+ "positionSubtitle": "프리셋 기본 위치에 추가됨 (씬 단위)",+ "positionLabel": "위치",+ "positionHint": "드래그하여 X / Y 위치 설정",+ "scaleTitle": "크기",+ "scaleSubtitle": "모델에 적용되는 균일 승수",+ "scaleLabel": "크기"}},"MobileTools": {diff --git a/messages/ru.json b/messages/ru.jsonindex c1d03cc..37c1815 100644--- a/messages/ru.json+++ b/messages/ru.json@@ -1402,6 +1402,20 @@"reverseLabel": "Обратное направление","resetButton": "Сбросить настройки","blurLabel": "Размытие движения"+ },+ "customize3D": {+ "rotationTitle": "Смещения вращения",+ "rotationSubtitle": "Добавляются к базовому вращению пресета (градусы)",+ "rotateXLabel": "Вращение X (тангаж)",+ "rotateYLabel": "Вращение Y (рысканье)",+ "rotateZLabel": "Вращение Z (крен)",+ "positionTitle": "Смещения позиции",+ "positionSubtitle": "Добавляются к базовой позиции пресета (единицы сцены)",+ "positionLabel": "Позиция",+ "positionHint": "Перетащите для настройки позиции X / Y",+ "scaleTitle": "Масштаб",+ "scaleSubtitle": "Единый множитель, применяемый к модели",+ "scaleLabel": "Масштаб"}},"MobileTools": {