clipoox-render 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server-text/titleRaster.js +1394 -0
- package/package.json +5 -3
- package/scripts/render-local.mjs +1514 -1379
- package/shared/transitionStarterPack.json +261 -0
- package/web/assets/{FxEmbed-BymBArNa.js → FxEmbed-D7k1ThAF.js} +1 -1
- package/web/assets/{GLTFLoader-Dy6SrZg8.js → GLTFLoader-BHWu1lKg.js} +1 -1
- package/web/assets/{MotionEmbed-PmXWSWe5.js → MotionEmbed-DFni5IAh.js} +1 -1
- package/web/assets/PluginStore-BrupM_8E.js +3 -0
- package/web/assets/{ShotComposer-Dprx-Yi7.js → ShotComposer-BLztjSKy.js} +4 -4
- package/web/assets/TemplateEmbed-BbAimhLj.js +2 -0
- package/web/assets/TimelinePlugins-BI1bE9pX.js +5 -0
- package/web/assets/TimelinePlugins-DYarX9RK.css +1 -0
- package/web/assets/TimelineShotFx-CQN3WIfN.js +2 -0
- package/web/assets/TransitionEmbed-CmoIrHVr.js +1 -0
- package/web/assets/{Whiteboard-DybaKCdo.js → Whiteboard-DMk0unYK.js} +3 -3
- package/web/assets/aerial-DT_gUtSh.js +2 -0
- package/web/assets/{agentTools-CxZqRLeR.js → agentTools-qOww5RUs.js} +2 -2
- package/web/assets/analyzerRun-B2FLUp4G.js +1 -0
- package/web/assets/{analyzerSandbox-DO5ZTv5q.js → analyzerSandbox-CJVsEhrg.js} +2 -2
- package/web/assets/{api-BsKbf3l3.js → api-QBI5GJTZ.js} +148 -148
- package/web/assets/auraTrack-CEs_Q9EP.js +1 -0
- package/web/assets/{breakthrough-Dv1bndQb.js → breakthrough-DvkxvNK9.js} +2 -2
- package/web/assets/{cameraPresets-B234aNzE.js → cameraPresets-4pFeF2YG.js} +1 -1
- package/web/assets/{captionLayout-CNgb471H.js → captionLayout-C67EMVI1.js} +1 -1
- package/web/assets/{clientExport-NtJmxOYP.js → clientExport-C4VgAJtO.js} +1 -1
- package/web/assets/{depthEstimate-wVYSJtW8.js → depthEstimate-mnXDZMW-.js} +1 -1
- package/web/assets/{directorTools-BqFcShgT.js → directorTools-BOHZjcww.js} +1 -1
- package/web/assets/{distortFrames-D3TQNcJA.js → distortFrames-Csuj2jHE.js} +2 -2
- package/web/assets/{distortGL-BklPDXPq.js → distortGL-BaXfN0IK.js} +2 -2
- package/web/assets/{editTools-BQlG5WB_.js → editTools-m0VGPmfF.js} +1 -1
- package/web/assets/{exportEncode-CaKEPgsy.js → exportEncode-D9OT7_5k.js} +1 -1
- package/web/assets/{exportGlb-DstxwzH5.js → exportGlb-CLfTnbMG.js} +1 -1
- package/web/assets/faceTracker-W0iZSiMe.js +1 -0
- package/web/assets/fightDirector-CECPf2iH.js +1 -0
- package/web/assets/{fightDrama-G7bXfpQu.js → fightDrama-CqNoa5XI.js} +2 -2
- package/web/assets/{frameSink-Dj71jCRb.js → frameSink-BGRj7wqY.js} +3 -3
- package/web/assets/{gpuCompose-DIxBHlTa.js → gpuCompose-CIEoLFem.js} +1 -1
- package/web/assets/gpuExport-uyOAyrhm.js +190 -0
- package/web/assets/handMatte-mHxZwLZD.js +1 -0
- package/web/assets/handTracker-dTVeSUzt.js +2 -0
- package/web/assets/{index-CZn97Ygs.js → index-D7M5t2re.js} +1 -1
- package/web/assets/layer-worker-Cp0pjurp.js +5 -0
- package/web/assets/library-Dsz_MLyd.js +1 -0
- package/web/assets/{lottieLayer-CfUPParC.js → lottieLayer-CDCGeJyv.js} +5 -5
- package/web/assets/{lottie_light_canvas-7iv3btPX.js → lottie_light_canvas-BblLU4nU.js} +1 -1
- package/web/assets/main-BQ8IY0WV.css +1 -0
- package/web/assets/{main-M1vRa-gd.js → main-CVRIuDW2.js} +76 -76
- package/web/assets/{mapBake-lPNhNZgv.js → mapBake-CNMOKXA7.js} +1 -1
- package/web/assets/maskTrack-Dtv6Jr06.js +1 -0
- package/web/assets/matteFixRun-BLDH2AjH.js +1 -0
- package/web/assets/{objectLocate-BDqfSo9J.js → objectLocate-Cy3IFBSF.js} +1 -1
- package/web/assets/{objectTrack.worker-ENzKeSiV.js → objectTrack.worker-BlZkgpOX.js} +483 -352
- package/web/assets/pendingMatte-C2AWApuv.js +2 -0
- package/web/assets/personAi-DPUnoymj.js +2 -0
- package/web/assets/plateCamera-C96L5GKm.js +1 -0
- package/web/assets/{plateCameraMatch-D41LQrsm.js → plateCameraMatch-Chk-ZjDi.js} +2 -2
- package/web/assets/{plateFollow-CNfi4xuP.js → plateFollow-B9_QTgvo.js} +2 -2
- package/web/assets/plateMatte-BiqyI_8x.js +2 -0
- package/web/assets/{pluginAutomation-BtQ_w2TB.js → pluginAutomation-5DYldFrb.js} +1 -1
- package/web/assets/poseTracker-PuI8vWpR.js +1 -0
- package/web/assets/{productTools-r2RgILaA.js → productTools-B1h5cgyt.js} +2 -2
- package/web/assets/remote-BJdzzFZg.js +1241 -0
- package/web/assets/{rigTrack-Bx9QHlFv.js → rigTrack-CUt4O67J.js} +1 -1
- package/web/assets/{rotoMaskStore-pxpRt5Cj.js → rotoMaskStore-DIi45swK.js} +1 -1
- package/web/assets/{rotoMatte-DyXlW4jK.js → rotoMatte-013RKqHu.js} +1 -1
- package/web/assets/{rotoscope-GORCSVBr.js → rotoscope-d_TUxa-J.js} +1 -1
- package/web/assets/{sceneTrack.worker-CEvCN5OB.js → sceneTrack.worker-CT4uoTKn.js} +475 -344
- package/web/assets/{shot-worker-B8JWkmBz.js → shot-worker-B1iZT6F5.js} +1 -1
- package/web/assets/{shotFxAgent-CzHfe75S.js → shotFxAgent-BDfe73TP.js} +2 -2
- package/web/assets/{skin-BkaT2QuX.js → skin-GDY3QPkV.js} +1 -1
- package/web/assets/{spark.module-BRT8yMS4.js → spark.module-DdwuJ_hb.js} +1 -1
- package/web/assets/{spellDuel-BUy289OT.js → spellDuel-DjNN00bv.js} +2 -2
- package/web/assets/{store-BSSbvpzr.js → store-2zneEhhu.js} +1 -1
- package/web/assets/{surfaceLight-CMaBhZ_d.js → surfaceLight-B_SYg_f8.js} +1 -1
- package/web/assets/surfacePin-zDPmq-hH.js +2 -0
- package/web/assets/{textAnimators-Cihw35O8.js → textAnimators-Bdt5LWXk.js} +1 -1
- package/web/assets/{thumb-Cs636sYt.js → thumb-byAKvhQP.js} +1 -1
- package/web/assets/timeline3d-YIIk_Kn2.js +2 -0
- package/web/assets/timeline3dExport-CEH1RjNf.js +1 -0
- package/web/assets/{timelineComp-CRRzLazc.js → timelineComp-B73i_8vD.js} +1 -1
- package/web/assets/{timelineProps-tN2YsMYN.js → timelineProps-B2pnudeT.js} +1 -1
- package/web/assets/{timelineText-CkoUgWcY.js → timelineText-BcL4Pw3C.js} +1 -1
- package/web/assets/{titleArt-CcTdJuOC.js → titleArt-hb_T45WJ.js} +5 -5
- package/web/assets/{titleFrameBudget-3MFHWIT6.js → titleFrameBudget-Cml-MO53.js} +970 -839
- package/web/assets/titleFrames-Dw0PEBdV.js +1 -0
- package/web/assets/{tool-BhIsq238.js → tool-Bt9bclIf.js} +1 -1
- package/web/assets/{tools-DMUnabc_.js → tools-BXeJbgZJ.js} +1 -1
- package/web/assets/{toonTools-CICrV3QB.js → toonTools-u7Y9fdEZ.js} +2 -2
- package/web/assets/trackAnchor-9MnVHe4S.js +1 -0
- package/web/assets/{userFonts-BZ4QL-zq.js → userFonts-BHduCNtc.js} +1 -1
- package/web/assets/{vfxAlpha-D3Dk1tfF.js → vfxAlpha-DpV4rbI-.js} +1 -1
- package/web/assets/vfxBackground-Ddviync5.js +2 -0
- package/web/assets/{videoExport-l5MGvMn_.js → videoExport-z5WjM0hw.js} +1 -1
- package/web/assets/{views-BdWnG2xK.js → views-CsrYzCSR.js} +1 -1
- package/web/assets/weaponDuel-CLLgv5A4.js +1 -0
- package/web/assets/{windowFrames-CoIyWqxr.js → windowFrames-BQEWQkEs.js} +1 -1
- package/web/layer-worker.html +3 -3
- package/web/assets/PluginStore-BVsm6n6N.js +0 -3
- package/web/assets/TemplateEmbed-CrZXoUk_.js +0 -2
- package/web/assets/TimelinePlugins-B1KGtbmb.js +0 -5
- package/web/assets/TimelinePlugins-B5WmAawO.css +0 -1
- package/web/assets/TimelineShotFx-DoLx312Y.js +0 -2
- package/web/assets/TransitionEmbed-C5SUosv2.js +0 -1
- package/web/assets/aerial-DSt_mJNA.js +0 -2
- package/web/assets/analyzerRun-DCJwb_-Z.js +0 -1
- package/web/assets/auraTrack-QR0WqBHp.js +0 -1
- package/web/assets/desktop-BWhFnYwd.js +0 -1
- package/web/assets/faceTracker-DWxxieVC.js +0 -1
- package/web/assets/fightDirector-OMlPZgjv.js +0 -1
- package/web/assets/gpuExport-CPSw_dmq.js +0 -189
- package/web/assets/handMatte-DHsHHz4m.js +0 -1
- package/web/assets/handTracker-D_O-C4Dw.js +0 -2
- package/web/assets/layer-worker-Bar7WgOA.js +0 -5
- package/web/assets/library-BtBrCaFk.js +0 -1
- package/web/assets/main-BPmr0TOL.css +0 -1
- package/web/assets/maskTrack-D2jUh7aw.js +0 -1
- package/web/assets/matteFixRun-B7tWV9Y1.js +0 -1
- package/web/assets/pendingMatte-q35zVaiB.js +0 -2
- package/web/assets/personAi-ZjQVo-80.js +0 -2
- package/web/assets/plateCamera-A2E_WO_x.js +0 -1
- package/web/assets/plateMatte-BdIxGhw5.js +0 -2
- package/web/assets/poseTracker-DVX__OK7.js +0 -1
- package/web/assets/remote-sTZauTqM.js +0 -1220
- package/web/assets/surfacePin-DM9b9ubh.js +0 -2
- package/web/assets/timeline3d-BEuZZOxM.js +0 -2
- package/web/assets/timeline3dExport-CmSI_pjv.js +0 -1
- package/web/assets/titleFrames-w-iWje9N.js +0 -1
- package/web/assets/trackAnchor-D2bB5mZE.js +0 -1
- package/web/assets/vfxBackground-CHlCg8lb.js +0 -2
- package/web/assets/vfxTrack-CqiQDEYm.js +0 -1
- package/web/assets/weaponDuel-B2wTffPC.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/productTools-
|
|
2
|
-
import{_ as Wn}from"./titleFrameBudget-3MFHWIT6.js";import{dr as _a,ds as st,dt as Ws,du as as,dv as om,dw as Rh,dx as Fh,dy as is,dz as bt,dA as In,b as fn,dB as Ph,dC as im,dD as Cl,dE as wr,dF as Dt,dG as $h,dH as rm,dI as ja,dJ as Wo,dK as lm,dL as Oh,dM as cm,j as t,dN as hm,dO as Lo,dP as dm,dQ as um,dR as mm,dS as Dh,dT as pm,dU as fm,dV as $a,dW as zh,dX as ka,dY as gm,dZ as Nl,d_ as xm,d$ as bm,e0 as hi,e1 as Es,e2 as Oa,e3 as qs,e4 as zs,e5 as Al,e6 as Tl,e7 as Ll,e8 as _h,e9 as ym,ea as wa,eb as rn,I as Ce,N as gn,cW as Is,ec as di,ed as El,ee as Il,ef as vm,eg as Rl,eh as Mn,ei as jm,ej as km,ek as wm,el as Eo,em as Mm,en as Bh,eo as Da,ep as Fl,eq as Sm,er as ko,es as Kh,et as Cm,eu as Nm,ev as Am,ew as Tm,ex as Lm,ey as Em,ez as Io,eA as Im,eB as Rm,eC as Gi,eD as ln,eE as Ui,eF as Xi,eG as Fm,eH as Pl,eI as Pm,eJ as $m,eK as Om,eL as Dm,eM as Un,eN as Mr,eO as zm,eP as $l,eQ as qo,eR as Hh,eS as za,eT as _m,eU as Wh,eV as qh,eW as ui,eX as Fn,eY as Gs,eZ as Bm,e_ as Gh,e$ as mi,f0 as Rs,f1 as Km,f2 as Hm,f3 as Uh,f4 as Sr,f5 as Wm,f6 as qm,f7 as Cr,f8 as Ol,f9 as Gm,fa as Um,Q as Xm,fb as Vm,dq as Ym,fc as Qm,fd as Zm,fe as Jm,ff as ep,fg as tp,fh as Nr,fi as Xh,fj as np,fk as Za,fl as sp,fm as ap,fn as op,fo as ip,fp as rp,fq as lp,fr as cp,fs as hp,ft as dp,fu as Dl,fv as zl,fw as pi,fx as up,fy as mp,fz as pp,fA as Vh,fB as Yh,fC as Qh,fD as Ro,fE as _l,fF as Ar,fG as fp,fH as gp,fI as xp,fJ as Bl,fK as bp,fL as Tn,fM as yp,fN as vp,fO as Kl,fP as oa,fQ as bs,fR as jp,fS as kp,fT as wp,fU as Mp,fV as ks,fW as Sp,fX as Cp,fY as Np,fZ as Ap,f_ as Tp,f$ as Zh,g0 as Fo,g1 as Lp,g2 as Hl,g3 as Ep,g4 as fi,g5 as Wl,g6 as gi,g7 as Ip,g8 as Po,g9 as Rp,ga as Fp,gb as Pp,gc as ns,gd as $o,r as Jh,ge as $p,gf as Op,gg as Dp,gh as ql,gi as zp,gj as _p,gk as Tr,gl as Lr,gm as Ma,gn as Bp,go as Kp,gp as Hp,gq as Ja,gr as xi,gs as Vi,gt as ed,gu as Wp,gv as bi,gw as qp,gx as Gp,gy as Up,gz as Xp,gA as td,gB as nd,a as Pt,gC as Vp,am as Yp,gD as Qp,gE as Zp,gF as Jp,gG as ef,cT as tf,dj as nf,dk as sf,gH as af,gI as of,gJ as Yi,gK as rf,gL as lf,gM as cf,gN as hf,gO as df,gP as Gl,gQ as Qi,gR as Aa,gS as uf,gT as Ta,gU as wo,n as mf,gV as pf,u as yi,gW as Ul,gX as ff,gY as gf,dl as Xl,gZ as xf,g_ as Vl,g$ as bf,h0 as yf,h1 as vf,h2 as jf,h3 as vi,q as kf,h4 as wf,h5 as Mf,h6 as Sf,h7 as ji,h8 as Cf,h9 as Nf,ha as Af,hb as Tf,hc as Lf,hd as Ef,he as If,hf as Rf,hg as ki,hh as Ff,hi as Yl,hj as wi,hk as Ql,hl as Zl,hm as Mi,hn as Pf,ho as $f,hp as Of,hq as Df,hr as Si,hs as zf,ht as _f,hu as Bf,hv as Kf,hw as Hf,hx as Wf,hy as qf,hz as Gf,hA as Uf,hB as Xf,hC as Vf,hD as Yf,hE as Qf,hF as Zf,hG as Jf,hH as e0,hI as t0,hJ as n0,hK as s0,hL as a0,hM as o0,hN as i0,hO as r0,hP as l0,hQ as c0,hR as h0,hS as Jl,hT as d0,hU as u0,hV as ec,hW as tc,hX as m0}from"./remote-sTZauTqM.js";import{u as ht,r as R,t as o,bE as p0,c as _s,bF as nc,h as Ys,bG as f0,bH as g0,bI as x0,bJ as b0,bK as y0,bL as v0,bM as j0,bN as k0,bO as w0,bP as M0,az as S0,bQ as C0,bR as sc,a6 as N0,s as A0}from"./api-BsKbf3l3.js";import{Mesh as ut,SkinnedMesh as Er,Box3 as $t,Vector3 as ie,Matrix4 as St,Group as tn,Uint16BufferAttribute as sd,Float32BufferAttribute as Ot,BufferGeometry as Ct,BufferAttribute as Nt,MathUtils as Ln,DirectionalLight as Go,WebGLRenderer as Ir,SRGBColorSpace as Uo,AgXToneMapping as ad,PCFSoftShadowMap as T0,Scene as Rr,PMREMGenerator as od,HemisphereLight as id,PlaneGeometry as Xo,ShadowMaterial as L0,PerspectiveCamera as Fr,InstancedMesh as Bs,DataTexture as E0,RGBAFormat as I0,RepeatWrapping as rd,LinearFilter as ac,CanvasTexture as Pr,NoColorSpace as ld,LinearMipmapLinearFilter as cd,InstancedBufferAttribute as Zi,DynamicDrawUsage as Qs,MeshStandardMaterial as Gn,ShaderMaterial as Ba,Color as Qe,DoubleSide as cs,AdditiveBlending as $r,LinearSRGBColorSpace as rs,CapsuleGeometry as hd,ConeGeometry as R0,CylinderGeometry as hs,TorusGeometry as Or,SphereGeometry as Rn,BoxGeometry as Ka,MeshPhysicalMaterial as Cs,Vector2 as ta,LatheGeometry as dd,FrontSide as Ha,Quaternion as tt,Vector4 as ws,InstancedInterleavedBuffer as ud,InterleavedBufferAttribute as kn,InstancedBufferGeometry as F0,OneMinusSrcAlphaFactor as P0,OneFactor as $0,AddEquation as O0,CustomBlending as D0,NormalBlending as z0,DetachedBindMode as _0,OctahedronGeometry as Ji,MeshBasicMaterial as os,Line as Ci,LineBasicMaterial as oc,PointLight as B0,Euler as er,Bone as La,Uint8BufferAttribute as ls,ShaderChunk as K0,Sphere as H0,LOD as W0,Skeleton as Ni,Object3D as q0,NearestFilter as G0,ACESFilmicToneMapping as U0,CircleGeometry as X0,Raycaster as ic}from"./three.module-Bx43vjkH.js";import{R as md}from"./RoomEnvironment-Dmv_G5ka.js";import{i as rc,p as lc,g as V0,e as Y0}from"./tool-BhIsq238.js";import{rowProps as Q0,rowKeyed as Z0,readProp as J0,writeProp as eg,keyAllAt as tg,copyKeys as ng,pasteKeys as sg,easeKeys as ag,nudgeKeys as cc}from"./timelineProps-tN2YsMYN.js";import{b as og,c as ig,A as rg,d as hc,a as lg,t as cg}from"./thumb-Cs636sYt.js";import{f as hg,p as dg}from"./shotFxAgent-CzHfe75S.js";import{c as pd,G as ug}from"./GLTFLoader-Dy6SrZg8.js";import{p as mg,C as pg,a as fg,b as gg,c as dc}from"./cameraPresets-B234aNzE.js";import{F as xg}from"./rigTrack-Bx9QHlFv.js";import{D as bg,s as yg}from"./weaponDuel-B2wTffPC.js";import{u as dt}from"./store-BSSbvpzr.js";import{r as uc,a as vg,b as jg,o as kg,w as wg,c as Mg,d as Sg,e as Ai,f as Cg,g as Ng,p as Ag,h as Tg}from"./skin-BkaT2QuX.js";import{renderRigViews as Lg}from"./views-BdWnG2xK.js";import{M as ia}from"./motionBlur-uAm030t9.js";import{fitLibraryFingers as mc}from"./library-BtBrCaFk.js";import"./rotoMaskStore-pxpRt5Cj.js";import"./textAnimators-Cihw35O8.js";import"./timelineComp-CRRzLazc.js";function Eg(e,n,s){const a=[e[0]*n[0]+e[4]*n[1]+e[8]*n[2]+e[12],e[1]*n[0]+e[5]*n[1]+e[9]*n[2]+e[13],e[2]*n[0]+e[6]*n[1]+e[10]*n[2]+e[14]],i=[0,1,2].map(r=>Math.abs(e[r]*s[0])+Math.abs(e[4+r]*s[1])+Math.abs(e[8+r]*s[2]));return{c:a,h:i,min:a.map((r,l)=>r-i[l]),max:a.map((r,l)=>r+i[l])}}function Ig(e,{cell:n=1}={}){const s=e.length,a=Array.from({length:s},()=>[]),i=Array.from({length:s},()=>[]),r=e.reduce((C,M)=>Math.min(C,M.min[1]),1/0),l=e.reduce((C,M)=>Math.max(C,M.max[1]),-1/0),c=Math.max(.03,n*.2),u=Math.max(.02,n*.06),m=e.map(C=>C.min[1]<=r+c);for(let C=0;C<s;C++){const M=e[C],S=(M.min[1]+M.max[1])/2,I=(M.max[1]-M.min[1])/2;for(let y=C+1;y<s;y++){const k=e[y],T=[0,1,2].map(A=>Math.min(M.max[A],k.max[A])-Math.max(M.min[A],k.min[A]));if(T[0]<-u||T[2]<-u||T[1]<-c)continue;const j=(k.min[1]+k.max[1])/2,L=(k.max[1]-k.min[1])/2,N=j-S;if(Math.abs(N)>.3*(I+L)){const A=N>0?k:M,O=_=>T[_]/Math.max(.001,A.max[_]-A.min[_]);if(O(0)<.45||O(2)<.45)continue;N>0?a[C].push(y):a[y].push(C)}else i[C].push(y),i[y].push(C)}}const d=new Uint8Array(s).fill(1);let f=tr({ups:a,side:i,ground:m},d,null);const p=Math.max(.05,n*.25);for(let C=0;C<3;C++){let M=!1;for(let S=0;S<s;S++){if(Number.isFinite(f[S]))continue;const I=e[S],y=(I.min[1]+I.max[1])/2,k=(I.max[1]-I.min[1])/2;for(let T=0;T<s;T++){if(T===S||i[S].includes(T)||a[S].includes(T)||a[T].includes(S))continue;const j=e[T];if(![0,1,2].every(A=>Math.min(I.max[A],j.max[A])-Math.max(I.min[A],j.min[A])>=-p))continue;const L=(j.min[1]+j.max[1])/2-y,N=(j.max[1]-j.min[1])/2;Math.abs(L)>.3*(k+N)?L>0?a[S].push(T):a[T].push(S):(i[S].push(T),i[T].push(S)),M=!0}}if(!M)break;f=tr({ups:a,side:i,ground:m},d,null)}const x=e.map(C=>[C.min[0],C.max[0],C.min[2],C.max[2]]),g=e.map(C=>[(C.min[0]+C.max[0])/2,(C.min[2]+C.max[2])/2]),v={n:s,ups:a,side:i,ground:m,need0:f,base:r,top:l,foot:x,plan:g,cell:n,tops:e.map(C=>C.max[1]),slender0:0},w=[...Array(s).keys()].filter(C=>Number.isFinite(f[C]));return v.slender0=w.length?xd(v,w):0,v.stable0=Fg(v,d,0),v}function Rg(e,n){if(!e.adj){e.adj=Array.from({length:e.n},(s,a)=>[...e.ups[a],...e.side[a]]);for(let s=0;s<e.n;s++)for(const a of e.ups[s])e.adj[a].push(s)}return e.adj[n]}function fd(e,n){const s=new Int32Array(e.n).fill(-1),a=[];for(let i=0;i<e.n;i++){if(!n[i]||s[i]>=0)continue;const r=[i];s[i]=a.length;for(let l=0;l<r.length;l++)for(const c of Rg(e,r[l]))n[c]&&s[c]<0&&(s[c]=a.length,r.push(c));a.push(r)}return a}function gd(e,n){let s=1/0,a=-1/0,i=1/0,r=-1/0,l=0;for(const c of n){if(!e.ground[c])continue;l++;const u=e.foot[c];s=Math.min(s,u[0]),a=Math.max(a,u[1]),i=Math.min(i,u[2]),r=Math.max(r,u[3])}return{x0:s,x1:a,z0:i,z1:r,ng:l}}function xd(e,n){const s=gd(e,n),a=(e.cell??1)*.25;return s.ng?(n.reduce((r,l)=>Math.max(r,e.tops[l]),-1/0)-e.base)/Math.max(.001,Math.min(s.x1-s.x0,s.z1-s.z0)+2*a):0}function bd(e,n,s,a){const i=gd(e,n),r=i.ng;if(!r||n.length-r<2)return!0;let l=0,c=0;for(const m of n)l+=e.plan[m][0],c+=e.plan[m][1];l/=n.length,c/=n.length;const u=(e.cell??1)*.5*(1+s);return l<i.x0-u||l>i.x1+u||c<i.z0-u||c>i.z1+u||e.tops&&xd(e,n)>Math.max(4,2*(e.slender0??0))*(1+.25*s)?!1:r/n.length>=a*(.3/(1+s))}function yd(e){let n=0,s=0;for(let a=0;a<e.n;a++)Number.isFinite(e.need0[a])&&(s++,e.ground[a]&&n++);return s?n/s:0}function Fg(e,n,s){const a=yd(e);return fd(e,n).every(i=>bd(e,i,s,a))}function tr(e,n,s){const a=n.length,i=new Float64Array(a).fill(1/0),r=[];for(let l=0;l<a;l++)n[l]&&e.ground[l]&&(i[l]=0,r.push(l));for(let l=0;l<r.length;l++){const c=r[l],u=i[c],m=u+1;for(const d of e.ups[c])n[d]&&i[d]>0&&(i[d]=0,r.push(d));for(const d of e.side[c])n[d]&&i[d]>m&&(!s||m<=s[d])&&(i[d]=m,r.push(d))}return i}const Pg=e=>e>=.8?0:e>=.4?1:2;function $g(e,n,{slack:s=0,seed:a=1,centres:i}={}){const r=e.n,l=new Array(r).fill(null),c=new Uint8Array(r).fill(1);if(!r)return l;const u=Float64Array.from(e.need0,v=>v+s),m=Math.max(.1,e.top-e.base),d=_a(a|0,7717,5),f=[],p=e.stable0!==!1&&!!e.foot,x=p?yd(e):0;for(let v=0;v<r;v++)Number.isFinite(n[v])&&f.push({t:n[v],i:v});f.sort((v,w)=>v.t-w.t||v.i-w.i);let g=0;for(;g<f.length;){const v=f[g].t,w=[];for(;g<f.length&&f[g].t<=v+1e-9;){const S=f[g++];c[S.i]&&(c[S.i]=0,w.push(S.i))}if(!w.length)continue;const C=tr(e,c,u),M=i?st.mul(w.reduce((S,I)=>st.add(S,i[I]),[0,0,0]),1/w.length):null;for(let S=0;S<r;S++){if(!c[S]||!Number.isFinite(e.need0[S])||C[S]<=u[S])continue;c[S]=0;const I=i?Ws((i[S][1]-e.base)/m):.5,y=v+.05+.13*I+.07*as(d,S,1);l[S]={t:y,from:M}}if(p){for(const S of fd(e,c))if(!bd(e,S,s,x))for(const I of S){if(e.ground[I])continue;c[I]=0;const y=i?Ws((i[I][1]-e.base)/m):.5;l[I]={t:v+.08+.15*y+.07*as(d,I,1),from:M}}}}return l}function Og(e,n,{base:s=0,cell:a=1}={}){const i=Math.max(.05,a*.25),r=new Map,l=(d,f)=>`${d},${f}`,c=(d,f,p,x,g)=>{const v=[];for(let w=Math.floor((d-p*g)/i);w<=Math.floor((d+p*g)/i);w++)for(let C=Math.floor((f-x*g)/i);C<=Math.floor((f+x*g)/i);C++)v.push(l(w,C));return v};for(const d of n)for(const f of c(d.x,d.z,d.hx,d.hz,.85))r.set(f,Math.max(r.get(f)??s,d.y1));const u=new Map,m=Math.max(.1,a*.5);for(const d of[...e].sort((f,p)=>f.t-p.t||f.i-p.i)){const f=d.hy*.8;let p=null;for(const x of d.dirs??[[1,0,0]])for(let g=0;g<=8;g++){const v=d.x+x[0]*m*g,w=d.z+x[2]*m*g,C=c(v,w,d.hx,d.hz,.6),M=C.reduce((I,y)=>Math.max(I,r.get(y)??s),s),S=M+.45*m*g;(!p||S<p.score-1e-9)&&(p={x:v,z:w,y:Math.min(d.top,M+f),foot:C,score:S})}u.set(d.i,{x:p.x,z:p.z,y:p.y});for(const x of p.foot)r.set(x,Math.max(r.get(x)??s,p.y+f*.9))}return u}function Dg(e,n,s,{gravity:a=9.8,seed:i=1,crumble:r=.6}={}){if(!e||!(s>=e.t))return null;const l=s-e.t,c=Math.max(.5,a),u=Math.max(0,e.p0[1]-e.land),m=Math.sqrt(2*u/c),d=Math.min(l,m),f=m>1e-6?d/m:1,p=om(u,0,c,l,.12),x=l>m?(1-Math.exp(-3*(l-m)))/3:0,g=e.p0[0]+(e.to[0]-e.p0[0])*f+e.dir[0]*.4*x,v=e.p0[2]+(e.to[1]-e.p0[2])*f+e.dir[2]*.4*x,w=_a(i|0,n,4441),C=(.25+.9*as(w,1,1))*(.4+.6*r),M=st.norm([e.dir[2]+(as(w,2,1)-.5)*.3,0,-e.dir[0]+(as(w,3,1)-.5)*.3]),S=C*Rh(0,1,f)+(l>m?.15*C*x:0);return{pos:[g,e.land+p.y,v],axis:Number.isFinite(M[0])?M:[1,0,0],angle:S,landed:l>=m}}function zg(e,n,s,{base:a=0,cell:i=1,seed:r=1,centre:l=null}={}){const c=_a(r|0,3301,7),u=[],m=n.map((f,p)=>{if(!f)return null;const x=e[p],g=f.from??x.c,v=[g[0]-x.c[0],0,g[2]-x.c[2]],w=Math.hypot(v[0],v[2]),C=as(c,p,1)*Math.PI*2,M=(as(c,p,2)-.5)*.9,S=w>1e-4?st.norm([v[0]/w+Math.cos(C)*.25,0,v[2]/w+Math.sin(C)*.25]):[Math.cos(C),0,Math.sin(C)],I=l?[x.c[0]-l[0],0,x.c[2]-l[2]]:[Math.cos(C+1),0,Math.sin(C+1)],y=Math.hypot(I[0],I[2]),k=y>1e-4?[I[0]/y,0,I[2]/y]:[Math.cos(C+1),0,Math.sin(C+1)],T=(j,L)=>[j[0]*Math.cos(L)-j[2]*Math.sin(L),0,j[0]*Math.sin(L)+j[2]*Math.cos(L)];return u.push({i:p,t:f.t,x:x.c[0],z:x.c[2],hx:x.h[0],hz:x.h[2],hy:Math.min(x.h[1],Math.max(x.h[0],x.h[2])*1.2),top:x.c[1],dirs:[S,T(k,M),T(k,M+.8),T(k,M-.8)]}),{t:f.t,p0:[...x.c],dir:S,to:[x.c[0],x.c[2]],land:a,by:"fall"}}),d=s.map(f=>({x:e[f].c[0],z:e[f].c[2],hx:e[f].h[0],hz:e[f].h[2],y1:e[f].c[1]+e[f].h[1]}));for(const[f,p]of Og(u,d,{base:a,cell:i}))m[f]&&(m[f].land=p.y,m[f].to=[p.x,p.z]);return m}function _g(e,{mode:n="pancake",start:s=0,duration:a=4,yaw:i=0,crumble:r=.6,seed:l=1,cell:c=1,gone:u=null,gravity:m=9.8}={}){const d=e.reduce((j,L)=>Math.min(j,L.min[1]),1/0),f=e.reduce((j,L)=>Math.max(j,L.max[1]),-1/0),p=Math.max(.3,a),x=Math.max(.1,f-d),g=.17+.13*(1-r),v=[0,2].map(j=>e.reduce((L,N)=>Math.min(L,N.min[j]),1/0)),w=[0,2].map(j=>e.reduce((L,N)=>Math.max(L,N.max[j]),-1/0)),C=[(v[0]+w[0])/2,d,(v[1]+w[1])/2],M=i*Math.PI/180,S=[Math.sin(M),0,Math.cos(M)],I=e.reduce((j,L)=>Math.max(j,...[0,1].flatMap(N=>[0,1].map(A=>(N?L.max[0]:L.min[0])*S[0]+(A?L.max[2]:L.min[2])*S[2]))),-1/0)-(C[0]*S[0]+C[2]*S[2]),y=[C[0]+S[0]*I,d,C[2]+S[2]*I],k=[S[2],0,-S[0]],T={mode:Kg.has(n)?n:"pancake",t0:s,D:p,base:d,top:f,H:x,c:g,centre:C,pivot:y,dir:S,axis:k,ext:I,seed:l|0,crumble:r,cell:c};if(T.mode==="pancake"){const j=.008333333333333333,L=Math.max(.5,m),N=Math.max(.3,c),A=Math.max(.3,c*1.5),O=e.map(P=>`${Math.floor(P.c[0]/A)},${Math.floor(P.c[2]/A)}`),_=new Map;e.forEach((P,W)=>{const z=O[W];_.has(z)||_.set(z,[]),_.get(z).push(W)});const $=new Map;for(const[P,W]of _){const z=[f];let Q=f,J=0;for(let V=1;Q>d&&V<7200;V++){const B=s+V*j,q=Ws((B-s)/p),D=x*1.6*Math.pow(Math.max(q,.02),.6)/p;J=W.some(Z=>e[Z].c[1]<=Q&&e[Z].c[1]>=Q-N&&!(u&&u[Z]<=B))?Math.max(D,J+L*.6*j):J+L*j,Q=Math.max(d,Q-J*j),z.push(Q)}$.set(P,z)}T.fronts=$,T.colOf=O,T.dt=j,T.starts=e.map((P,W)=>{const z=$.get(O[W]),Q=z.findIndex(J=>J<P.c[1]);return s+(Q<0?z.length:Q)*j})}else T.starts=e.map(()=>s);return T}const Bg=(e,n,s)=>{const a=e.fronts.get(e.colOf[n]),i=(s-e.t0)/e.dt;if(i<=0)return e.top;const r=Math.floor(i);return r>=a.length-1?a[a.length-1]:a[r]+(a[r+1]-a[r])*(i-r)},Kg=new Set(["pancake","topple","base"]),Hg=(e,n,s)=>{const a=Math.cos(s),i=Math.sin(s),r=st.dot(n,e),l=st.cross(n,e);return[e[0]*a+l[0]*i+n[0]*r*(1-a),e[1]*a+l[1]*i+n[1]*r*(1-a),e[2]*a+l[2]*i+n[2]*r*(1-a)]};function pc(e,n,s,a){if(!e||!(a>=e.starts[s]))return null;const i=_a(e.seed,s,6067),r=g=>as(i,g,1),l=Ws((a-e.t0)/e.D),c=e.crumble,u=e.base+Math.min(n.h[1],Math.max(n.h[0],n.h[2]))*.55,m=st.norm([n.c[0]-e.centre[0]+(r(1)-.5)*.6,0,n.c[2]-e.centre[2]+(r(2)-.5)*.6]),d=st.norm([r(3)-.5,(r(4)-.5)*.4,r(5)-.5]);if(e.mode==="topple"){const g=Math.PI/2*l*l,v=st.sub(n.c,e.pivot),w=st.add(e.pivot,Hg(v,e.axis,g)),C=Math.max(0,a-(e.t0+e.D)),M=(1-Math.exp(-2.5*C))/2.5,S=Rh(.55,1,l),I=c*e.cell*(.4+1.2*r(6)),y=st.add(st.mul(e.dir,(.8+2.2*r(7))*c*M*2),st.mul(m,I*S*.5+c*M*r(8))),k=st.add(w,y);return k[1]=Math.max(u,k[1]),{pos:k,axis:e.axis,angle:g,extra:{axis:d,angle:c*(S*.6+M*2)*(.3+r(9))}}}let f,p;if(e.mode==="base"){const g=e.base+e.H*Math.pow(l,1.3),v=n.c[1];v>=g?(f=v-(g-e.base)*(1-e.c),p=0):(f=e.base+(v-e.base)*e.c,p=Ws((g-v)/Math.max(.2,e.cell*2)))}else{const g=Bg(e,s,a),v=n.c[1];f=g>=v?v:g+(v-g)*e.c;const w=e.base+(v-e.base)*e.c;p=v-w>1e-6?Ws((v-f)/(v-w)):1}f=Math.max(u,f);const x=(.15+1.1*c)*e.cell*(.5+r(10))*p;return{pos:[n.c[0]+m[0]*x,f,n.c[2]+m[2]*x],axis:d,angle:p*(.15+1.1*c)*(.3+r(11))}}function Wg(e,{blasts:n=[],collapses:s=[],falls:a=[]}={}){const i=new Array(e).fill(null),r=(l,c)=>{(!i[l]||c.t<i[l].t-1e-9||Math.abs(c.t-i[l].t)<=1e-9&&fc[c.kind]<fc[i[l].kind])&&(i[l]=c)};for(const l of n)for(let c=0;c<e;c++){const u=l.hits[c];u&&r(c,{kind:"hit",e:l.e,t:u.t})}for(let l=0;l<e;l++)a[l]&&r(l,{kind:"fall",e:-1,t:a[l].t});for(const l of s)for(let c=0;c<e;c++)r(c,{kind:"collapse",e:l.e,t:l.plan.starts[c]});return i}const fc={hit:0,fall:1,collapse:2};function qg(e,n){const s=new Float64Array(e).fill(1/0);for(const a of n)for(let i=0;i<e;i++){const r=a.hits[i];r&&r.t<s[i]&&(s[i]=r.t)}return s}function Gg(e){const n=Math.floor(e.length/3);if(n<4)return null;const s=y=>[e[y*3],e[y*3+1],e[y*3+2]];let a=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let y=0;y<n;y++)for(let k=0;k<3;k++)a[k]=Math.min(a[k],e[y*3+k]),i[k]=Math.max(i[k],e[y*3+k]);const r=Math.max(1e-9,...i.map((y,k)=>y-a[k])),l=r*1e-7;let c=0;for(let y=1;y<n;y++)e[y*3]<e[c*3]&&(c=y);let u=-1,m=0;for(let y=0;y<n;y++){const k=st.dist(s(y),s(c));k>m+l&&(m=k,u=y)}if(u<0)return null;let d=-1,f=0;const p=st.sub(s(u),s(c));for(let y=0;y<n;y++){const k=st.len(st.cross(p,st.sub(s(y),s(c))));k>f+l*r&&(f=k,d=y)}if(d<0)return null;const x=st.cross(p,st.sub(s(d),s(c)));let g=-1,v=0;for(let y=0;y<n;y++){const k=Math.abs(st.dot(x,st.sub(s(y),s(c))));k>v+l*r*r&&(v=k,g=y)}if(g<0||v<l*r*r*10)return null;const w=[],C=(y,k,T)=>{const j=st.cross(st.sub(s(k),s(y)),st.sub(s(T),s(y))),L=st.len(j)||1,N=st.mul(j,1/L);return{v:[y,k,T],n:N,d:st.dot(N,s(y)),alive:!0}},M=st.mul(st.add(st.add(s(c),s(u)),st.add(s(d),s(g))),.25);for(const[y,k,T]of[[c,u,d],[c,u,g],[c,d,g],[u,d,g]]){let j=C(y,k,T);st.dot(j.n,M)-j.d>0&&(j=C(y,T,k)),w.push(j)}const S=new Set([c,u,d,g]);for(let y=0;y<n;y++){if(S.has(y))continue;const k=s(y),T=[];for(const L of w)L.alive&&st.dot(L.n,k)-L.d>l&&T.push(L);if(!T.length)continue;const j=new Map;for(const L of T){L.alive=!1;for(let N=0;N<3;N++){const A=L.v[N],O=L.v[(N+1)%3],_=`${O},${A}`;j.has(_)?j.delete(_):j.set(`${A},${O}`,[A,O])}}for(const[L,N]of j.values())w.push(C(L,N,y))}const I=[];for(const y of w)y.alive&&I.push(...y.v);return I.length?I:null}function Ug(e,n,s,a=48){const i=Math.floor(e.length/3),r=Math.max(1,Math.ceil(i/a)),l=[],c=st.norm(n),u=st.len(n)>1e-6?s:0;for(let m=0;m<i;m+=r){const d=[e[m*3],e[m*3+1],e[m*3+2]];l.push(...d,d[0]+c[0]*u,d[1]+c[1]*u,d[2]+c[2]*u)}return l}const Fs=e=>Array.isArray(e)&&e.length===3&&e.every(n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=1e6),un=e=>{throw new Error(e)};function Xg(e,n){(!e||typeof e.message!="string"||e.message.length>4e3||!Array.isArray(e.tracks)||e.tracks.length>100||e.additions!=null&&(!Array.isArray(e.additions)||e.additions.length>1))&&un("Đề xuất AI không hợp lệ."),(!Number.isFinite(e.duration)||e.duration<n.duration||e.duration>1e7)&&un("Thời lượng đề xuất không hợp lệ.");for(const a of e.additions||[])(!a||a.kind!=="box"||typeof a.id!="string"||!/^agent-block-[a-zA-Z0-9_-]{1,96}$/.test(a.id)||n.items.some(i=>i.id===a.id)||!Fs(a.position)||!Fs(a.scale)||a.scale.some(i=>i<.1||i>100)||typeof a.name!="string"||a.name.length>80)&&un("Khối Agent không hợp lệ.");const s=new Set;for(const a of e.tracks){s.has(a.subjectId)&&un("AI trả về track trùng lặp."),s.add(a.subjectId);const i=n.items.find(l=>l.id===a.subjectId);if(a.subjectId!=="camera"&&(!i||i.locked)&&un("Đối tượng không tồn tại hoặc đã khóa."),(!Array.isArray(a.keys)||!a.keys.length||a.keys.length>200)&&un("Số key không hợp lệ."),a.replaceRange!=null){const l=a.replaceRange;(!Number.isFinite(l.start)||!Number.isFinite(l.end)||l.start<0||l.end<=l.start||l.end>e.duration||a.keys[0].seconds!==l.start||a.keys.at(-1).seconds!==l.end)&&un("Đoạn sửa phải có key ở cả hai đầu."),a.keys.some(c=>c.seconds<l.start||c.seconds>l.end)&&un("Key nằm ngoài đoạn sửa.")}let r=-1;for(const l of a.keys)(!Number.isFinite(l.seconds)||l.seconds<0||l.seconds>e.duration||l.seconds<=r||!Fs(l.position))&&un("Thời điểm hoặc vị trí key không hợp lệ."),r=l.seconds,a.subjectId==="camera"?(!Fs(l.target)||!Number.isFinite(l.lens)||l.lens<14||l.lens>200||!Number.isFinite(l.roll)||Math.abs(l.roll)>36e3||l.position.every((c,u)=>Math.abs(c-l.target[u])<1e-8))&&un("Thông số camera không hợp lệ."):(!Fs(l.rotation)||!Fs(l.scale)||l.scale.some(c=>c<.01||c>1e3))&&un("Góc xoay hoặc kích thước không hợp lệ."),l.pose!==void 0&&!["Ngồi","Đứng"].includes(l.pose)&&un("Tư thế key không hợp lệ.")}return e}function gc(e,n,s,a={},i=[]){const r=e.shots.find(c=>c.id===e.activeShot),l=Fh(r,s);return{placement:{camera:r.position,colliders:i.slice(0,400).map(c=>({id:c.id,itemId:c.itemId,name:c.name,kind:c.kind,min:c.min.map(u=>Math.round(u*1e3)/1e3),max:c.max.map(u=>Math.round(u*1e3)/1e3)}))},shotId:r.id,duration:r.duration,playheadSeconds:s*r.duration,selectedId:n||"camera",camera:{position:l.position,target:l.target,lens:l.lens,roll:l.roll,motion:r.motion,keys:r.cameraKeys?.map(c=>({...c,seconds:c.time*r.duration}))||[]},items:e.items.map(c=>{const u=is(c,r,s),m=a[c.id],d=[...r.objectKeys?.[c.id]||[]].sort((x,g)=>x.time-g.time),f=d.slice(1).map((x,g)=>{const v=d[g],w=(x.time-v.time)*r.duration,C=Math.hypot(...x.position.map((M,S)=>M-v.position[S]));return{start:v.time*r.duration,end:x.time*r.duration,distance:C,speed:w>0?C/w:null}}),p=Object.entries(a).filter(([x])=>x!==c.id).map(([x,g])=>{const v=m?u.position[0]-m.min[0]:.5,w=m?m.max[0]-u.position[0]:.5,C=m?u.position[2]-m.min[2]:.5,M=m?m.max[2]-u.position[2]:.5,S=(g.min[0]+g.max[0])/2,I=(g.min[2]+g.max[2])/2,y=[[g.min[0]-w-.3,u.position[1],I],[g.max[0]+v+.3,u.position[1],I],[S,u.position[1],g.min[2]-M-.3],[S,u.position[1],g.max[2]+C+.3]];return{targetId:x,worldAxisPoints:y,nearest:y.reduce((k,T)=>Math.hypot(T[0]-u.position[0],T[2]-u.position[2])<Math.hypot(k[0]-u.position[0],k[2]-u.position[2])?T:k)}});return{motionProfile:m?.motionProfile||null,segments:f,bounds:m||null,approachPoints:p.slice(0,6),baseTransform:{position:c.position,rotation:c.rotation,scale:c.scale},...c.kind==="person"?{pose:{hipL:c.pose.hipL,hipR:c.pose.hipR,kneeL:c.pose.kneeL,kneeR:c.pose.kneeR,lean:c.pose.lean},...c.figure?{figure:c.figure}:{}}:{},...c.kind==="set"&&c.set?{set:{id:c.set.id}}:{},id:c.id,name:c.name,kind:c.kind,locked:c.locked,hidden:c.hidden,position:u.position,rotation:u.rotation,scale:u.scale,keys:r.objectKeys?.[c.id]?.map(x=>({...x,seconds:x.time*r.duration}))||[]}})}}function Ti(e,n){const s=e.shots.find(l=>l.id===e.activeShot);Xg(n,{duration:s.duration,items:e.items});const a=s.duration/n.duration,i={...s,duration:n.duration,objectKeys:Object.fromEntries(Object.entries(s.objectKeys||{}).map(([l,c])=>[l,c.map(u=>({...u,time:u.time*a}))])),cameraKeys:s.cameraKeys?.map(l=>({...l,time:l.time*a}))};for(const l of n.tracks){const c=u=>!l.replaceRange||u.time*n.duration<l.replaceRange.start-1e-7||u.time*n.duration>l.replaceRange.end+1e-7;if(l.subjectId==="camera"){const u=l.keys.map(f=>({id:bt(),time:f.seconds/n.duration,position:f.position,target:f.target,lens:f.lens,roll:f.roll}));i.cameraKeys=[...(i.cameraKeys||[]).filter(f=>c(f)&&!u.some(p=>Math.abs(p.time-f.time)<1e-7)),...u].sort((f,p)=>f.time-p.time);const m=i.cameraKeys[0],d=i.cameraKeys.at(-1);Object.assign(i,{motion:"path",position:m.position,target:m.target,lens:m.lens,roll:m.roll,endPosition:d.position,endTarget:d.target,endLens:d.lens,pathSmooth:s.motion==="path"?s.pathSmooth:void 0})}else{const u=l.keys.map(m=>({id:bt(),time:m.seconds/n.duration,position:m.position,rotation:m.rotation,scale:m.scale,...m.stance?{stance:m.stance}:{},...m.pose&&In[m.pose]?{pose:{...In[m.pose]}}:{}}));i.objectKeys[l.subjectId]=[...(i.objectKeys[l.subjectId]||[]).filter(m=>c(m)&&!u.some(d=>Math.abs(d.time-m.time)<1e-7)),...u].sort((m,d)=>m.time-d.time)}}const r=(n.additions||[]).map((l,c)=>({...fn("box",e.items.length+c),id:l.id,name:l.name,position:l.position,scale:l.scale,color:"#849095"}));return{...e,items:[...e.items,...r],shots:e.shots.map(l=>l.id===s.id?i:l)}}const Ea=Object.freeze({oval:{vi:"Trái xoan",en:"Oval",width:1,length:1,eyes:1},round:{vi:"Tròn",en:"Round",width:1.1,length:.94,eyes:1.08},long:{vi:"Dài",en:"Long",width:.92,length:1.1,eyes:.95},square:{vi:"Vuông",en:"Square",width:1.12,length:1.02,eyes:.92},child:{vi:"Trẻ con",en:"Child",width:1.05,length:.96,eyes:1.3}}),js=Object.freeze({width:[.85,1.2],length:[.85,1.2],eyes:[.7,1.4]}),xc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Vg=/^#[0-9a-fA-F]{6}$/,Qn=(e,n)=>{throw Object.assign(new Error(`${e}: ${n}`),{status:400})};function Mo(e={}){xc(e)||Qn("character","object");for(const u of Object.keys(e))["preset","figure","look","face","color"].includes(u)||Qn("character",`unknown field "${u}"`);const n=e.preset!=null?Ph(String(e.preset)):null;e.preset!=null&&!n&&Qn("character.preset","unknown character preset");const s={height:1.75,face:"simple",...n?.figure??{},...e.figure!=null?im(e.figure,"character.figure"):{}},a=Cl({...n?.look??{},...e.look!=null?Cl(e.look,"character.look"):{}},"character.look");e.color!==void 0&&!(typeof e.color=="string"&&Vg.test(e.color))&&Qn("character.color","#rrggbb");const i=(e.color??s.skin??n?.color??wr[2]).toLowerCase();s.skin||(s.skin=i);const r=e.face??{};xc(r)||Qn("character.face","object");for(const u of Object.keys(r))["preset","width","length","eyes"].includes(u)||Qn("character.face",`unknown field "${u}"`);r.preset!==void 0&&!Ea[r.preset]&&Qn("character.face.preset",Object.keys(Ea).join("|"));const l=Ea[r.preset??"oval"],c={preset:r.preset??"oval"};for(const[u,[m,d]]of Object.entries(js)){const f=r[u]===void 0?l[u]:r[u];(typeof f!="number"||!Number.isFinite(f))&&Qn(`character.face.${u}`,`number ${m}..${d}`),c[u]=+Math.min(d,Math.max(m,f)).toFixed(3)}return{...n?{preset:n.id}:{},figure:s,look:a,color:i,face:c}}function Yg(e){const n=JSON.stringify(e);let s=2166136261;for(let a=0;a<n.length;a++)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}const Qg=e=>`gen:character:${Yg(e)}`,nr={torso:"torso",head:"head",eyes:"head",eyeL:"head",eyeR:"head"};for(const e of["L","R"])Object.assign(nr,{[`arm${e}`]:`arm${e}`,[`fore${e}`]:`fore${e}`,[`wrist${e}`]:`wrist${e}`,[`hand${e}`]:`wrist${e}`,[`thigh${e}`]:`thigh${e}`,[`shin${e}`]:`shin${e}`,[`foot${e}`]:`foot${e}`});function Zg(){return{...Object.fromEntries(Object.entries(In.Đứng).map(([n,s])=>[n,typeof s=="number"&&!/^(grip|thumb|index)/.test(n)?0:s])),lean:0,spineTwist:0,head:0,headPitch:0,headRoll:0}}function Jg(e){const n=Dt({height:1.8,head:1,build:1,...e.figure}),s=$h(Zg(),e.color,n,e.look);s.scale.setScalar(n.height/rm(n));const a=s.getObjectByName("head"),i=s.getObjectByName("eyes");a&&a.scale.set(a.scale.x*e.face.width,a.scale.y*e.face.length,a.scale.z*(e.face.width+1)/2),i&&i.scale.setScalar(e.face.eyes),s.updateMatrixWorld(!0);const r=k=>{for(let T=k;T;T=T.parent)if(nr[T.name])return nr[T.name];return"torso"},l=k=>s.getObjectByName(k).getWorldPosition(new ie),c=[];s.traverse(k=>{if(!(k instanceof ut)||!k.visible||!k.geometry.getAttribute("position"))return;let T=!1;for(let L=k;L;L=L.parent)L.visible||(T=!0);if(T)return;if(k instanceof Er){c.push(tx(k));return}const j=k.geometry.clone();j.morphAttributes={};for(const L of Object.keys(j.attributes))L!=="position"&&L!=="normal"&&L!=="uv"&&j.deleteAttribute(L);j.applyMatrix4(k.matrixWorld),c.push({geo:j,material:k.material,joint:r(k),name:k.name||r(k)})});const u=new $t,m=new Map;for(const k of c){if(k.geo.computeBoundingBox(),u.union(k.geo.boundingBox),k.weights){const j=k.geo.getAttribute("position"),L=new ie;for(let N=0;N<j.count;N++){const A=ja[k.weights.index[N*4]][0],O=m.get(A)??new $t;O.expandByPoint(L.fromBufferAttribute(j,N)),m.set(A,O)}continue}const T=m.get(k.joint)??new $t;T.union(k.geo.boundingBox),m.set(k.joint,T)}const d={};for(const[k]of ja)s.getObjectByName(k)&&(d[k]=l(k));d.headTop=new ie(d.head.x,m.get("head").max.y,d.head.z);for(const k of["L","R"]){const T=m.get(`wrist${k}`)??new $t().setFromCenterAndSize(d[`wrist${k}`],new ie(.05,.2,.05));d[`handTip${k}`]=new ie(d[`wrist${k}`].x,T.min.y,d[`wrist${k}`].z);const j=m.get(`foot${k}`)??new $t().setFromCenterAndSize(d[`foot${k}`],new ie(.1,.1,.25));d[`toe${k}`]=new ie(d[`foot${k}`].x,j.min.y,j.max.z)}const f=u.getSize(new ie),p=2/Math.max(f.x,f.y,f.z),x=u.getCenter(new ie),g=new St().makeScale(p,p,p).multiply(new St().makeTranslation(-x.x,-u.min.y,-x.z)),v=k=>Math.round(k*1e4)/1e4,w=ja.map(([k,T])=>({name:k,parent:T,pos:d[k].clone().applyMatrix4(g).toArray().map(v)})),C=Wo({kind:"humanoid",source:"template",joints:w,seed:1}),M=new Map(C.joints.map((k,T)=>[k.name,T])),S=lm(C),I=new tn;let y=0;for(const k of c){k.geo.applyMatrix4(g);const T=k.geo.getAttribute("position").count,j=M.get(k.joint)??0,L=new Uint16Array(T*4),N=new Float32Array(T*4);if(k.weights)for(let O=0;O<T*4;O++)L[O]=M.get(ja[k.weights.index[O]][0])??0,N[O]=k.weights.weight[O];else for(let O=0;O<T;O++)L[O*4]=j,N[O*4]=1;k.geo.setAttribute("skinIndex",new sd(L,4)),k.geo.setAttribute("skinWeight",new Ot(N,4)),k.geo.userData.rigWeights=S,k.geo.computeBoundingBox(),k.geo.computeBoundingSphere();const A=new ut(k.geo,k.material);A.name=k.name,A.castShadow=!0,A.receiveShadow=!0,I.add(A),y+=T}return I.userData.normalizedHeight=f.y*p,{root:I,rig:C,normalizedHeight:f.y*p,height:+f.y.toFixed(4),vertices:y}}const vd=new Map(ja.map(([e],n)=>[e,n]));function ex(e){if(vd.has(e))return[[e,1]];const n=/^(arm|fore|wrist|thigh|shin|foot)Half([LR])$/.exec(e);if(n){const a={arm:"torso",fore:"arm",wrist:"fore",thigh:"torso",shin:"thigh",foot:"shin"},i=a[n[1]];return[[n[1]+n[2],.5],[i==="torso"?"torso":i+n[2],.5]]}if(e==="headHalf")return[["head",.5],["torso",.5]];const s=/^(thumb|index|middle|ring|pinky)\d([LR])$/.exec(e);return s?[[`wrist${s[2]}`,1]]:/^(jaw|lid|eye|hair)/.test(e)?[["head",1]]:[["torso",1]]}function tx(e){const n=e.geometry,s=n.getAttribute("position").count,a=new Float32Array(s*3),i=new ie,r=n.getAttribute("skinIndex"),l=n.getAttribute("skinWeight"),c=e.skeleton.bones.map(f=>f.name),u=new Uint16Array(s*4),m=new Float32Array(s*4);e.skeleton.update();for(let f=0;f<s;f++){i.fromBufferAttribute(n.getAttribute("position"),f),e.applyBoneTransform(f,i),i.applyMatrix4(e.matrixWorld),a[f*3]=i.x,a[f*3+1]=i.y,a[f*3+2]=i.z;const p=new Map;for(let v=0;v<4;v++){const w=l.getComponent(f,v);if(w)for(const[C,M]of ex(c[r.getComponent(f,v)]??"torso")){const S=vd.get(C)??0;p.set(S,(p.get(S)??0)+w*M)}}const x=[...p].sort((v,w)=>w[1]-v[1]).slice(0,4),g=x.reduce((v,w)=>v+w[1],0)||1;x.forEach(([v,w],C)=>{u[f*4+C]=v,m[f*4+C]=w/g})}const d=new Ct;return d.setAttribute("position",new Nt(a,3)),n.getAttribute("color")&&d.setAttribute("color",n.getAttribute("color").clone()),d.setIndex(n.getIndex()?Array.from(n.getIndex().array):null),d.computeVertexNormals(),{geo:d,material:e.material,joint:"torso",name:e.name||"skin",weights:{index:u,weight:m}}}const Os=new Map;function jd(e){const n=JSON.stringify(e);let s=Os.get(n);if(!s)for(s=Jg(e),Os.set(n,s);Os.size>16;)Os.delete(Os.keys().next().value);return s}function kd(){Os.clear()}const bc=e=>Array.isArray(e)&&e.length===3&&e.every(n=>Number.isFinite(Number(n)))?e.map(Number):null;function Li(e,n){const s=e.getStage(),a=String(n.name||"Nhân vật").trim().slice(0,60)||"Nhân vật",i=s.items.find(f=>f.name===a&&f.kind==="model"&&f.gen?.kind==="character");let r;try{const f=i?.gen?.kind==="character"?i.gen.spec:void 0,p=Object.fromEntries(["figure","look","face","color"].filter(g=>n[g]!=null).map(g=>[g,n[g]])),x=n.face;r=Mo(n.preset!=null||!f?{...n.preset!=null?{preset:n.preset}:{},...p}:{figure:{...f.figure,...n.figure||{}},look:{...f.look,...n.look||{}},face:x?.preset?x:{...f.face,...x||{}},color:n.color??f.color})}catch(f){return{ok:!1,error:f.message}}const l=jd(r),c=l.height,u={model:{gcsUri:Qg(r),name:`${a}.character`,height:c},gen:{kind:"character",spec:r},rig:l.rig,color:r.color,...bc(n.position)?{position:bc(n.position)}:{},...n.yaw_deg!=null?{rotation:[0,Number(n.yaw_deg)||0,0]}:{}};let m=i?.id;if(i)e.setStage(f=>({...f,items:f.items.map(p=>p.id===i.id?{...p,...u}:p)}));else{const f=Oh(s,{kind:"model",name:a,...u});m=f.id,e.setStage(p=>({...p,items:[...p.items,f]}))}const d=l.rig.joints.filter(f=>!cm(l.rig.joints,f)).map(f=>f.name);return{ok:!0,name:a,id:m,rebuilt:!!i,height_m:c,vertices:l.vertices,rig:"humanoid",bones:d,...r.preset?{preset:r.preset}:{},face:r.face,hint:"already rigged with the humanoid skeleton: set_pose, play_motion, hold_prop, set_gaze, resolve_hits and set_bone_rotation work on it; same name = rebuild with new parameters"}}const nx=[{key:"height",vi:"Chiều cao (m)",lo:1,hi:2.1,step:.01},{key:"weight",vi:"Cân nặng (gầy → mập)",lo:-1,hi:1,step:.05},{key:"muscle",vi:"Cơ bắp",lo:0,hi:1,step:.05},{key:"posture",vi:"Dáng (thẳng → còng)",lo:0,hi:1,step:.05},{key:"shoulders",vi:"Vai",lo:.6,hi:1.6,step:.02},{key:"hips",vi:"Hông",lo:.6,hi:1.6,step:.02},{key:"sex",vi:"Giới tính (nam ↔ nữ)",lo:0,hi:1,step:.05},{key:"age",vi:"Tuổi",lo:3,hi:90,step:1}],sx=[{key:"width",vi:"Mặt rộng",lo:js.width[0],hi:js.width[1],step:.01},{key:"length",vi:"Mặt dài",lo:js.length[0],hi:js.length[1],step:.01},{key:"eyes",vi:"Mắt to",lo:js.eyes[0],hi:js.eyes[1],step:.01}];function ax({host:e,item:n,ground:s,onSelect:a,setError:i}){const r=ht(),l=M=>r==="en"?M.en:M.vi,[c,u]=R.useState(()=>Mo({preset:"office-f"})),m=(n?.gen?.kind==="character"?n.gen.spec:null)??c,d=R.useRef(void 0),f=M=>{let S;try{S=Mo({figure:{...m.figure,...M.figure||{}},look:M.look??m.look,face:{...m.face,...M.face||{}},color:M.color??m.color})}catch(I){i(I.message);return}if(!n){u(S);return}window.clearTimeout(d.current),d.current=window.setTimeout(()=>{const I=Li(e,{name:n.name,figure:S.figure,look:S.look,face:S.face,color:S.color});I.ok||i(String(I.error))},250)},p=M=>{if(!Ph(M))return;if(!n){u(Mo({preset:M}));return}const I=Li(e,{name:n.name,preset:M});I.ok||i(String(I.error))},x=()=>{const M=Li(e,{name:ox(e,o("Nhân vật")),figure:m.figure,look:m.look,face:m.face,color:m.color,position:s()});M.ok&&M.id?a(M.id):i(String(M.error))},g=m.figure,v=(M,S,I)=>t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o(M.vi)}),t.jsx("input",{type:"range","aria-label":o(M.vi),min:M.lo,max:M.hi,step:M.step,value:S,onChange:y=>I(+y.target.value)}),t.jsx("input",{type:"number","aria-label":`${o(M.vi)} (${o("số")})`,min:M.lo,max:M.hi,step:M.step,value:S,onChange:y=>{const k=+y.target.value;Number.isFinite(k)&&I(Math.min(M.hi,Math.max(M.lo,k)))}})]},M.key),w=m.look,C=(M,S,I,y)=>{const k=w[M];return t.jsxs("div",{className:"shot-char-piece",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o(y)}),t.jsxs("select",{"aria-label":o(y),value:k?String(k[I]):"",onChange:T=>{const j=T.target.value,L={...m.look};j?L[M]={...k||{color:M==="hair"?"#2a211b":"#4a6fa5"},[I]:j}:delete L[M],f({look:L})},children:[t.jsx("option",{value:"",children:o("Không")}),Object.entries(S).map(([T,j])=>t.jsx("option",{value:T,children:l(j)},T))]})]}),k&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Màu {0}",[o(y).toLowerCase()])}),t.jsx("input",{type:"color","aria-label":o("Màu {0}",[o(y).toLowerCase()]),value:k.color,onChange:T=>f({look:{...m.look,[M]:{...k,color:T.target.value}}})})]})]},M)};return t.jsxs("div",{className:"shot-model-edit shot-char",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["🧍 ",n?n.name:o("Nhân vật mới")]}),t.jsx("small",{className:"muted",children:n?o("Đang sửa: thay đổi dựng lại ngay, đã gắn xương người."):o("Lưới 3D tạo từ tham số, gắn sẵn xương người: tạo dáng, chuyển động, cầm đồ ngay.")})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Mẫu nhân vật")}),t.jsxs("select",{"aria-label":o("Mẫu nhân vật"),value:m.preset??"",onChange:M=>p(M.target.value),children:[t.jsx("option",{value:"",children:o("Tự chỉnh")}),hm.map(M=>t.jsx("option",{value:M.id,children:l(M.name)},M.id))]})]}),t.jsx("h4",{children:o("Dáng người")}),nx.map(M=>v(M,Number(g[M.key]??(M.key==="height"?1.75:M.key==="shoulders"||M.key==="hips"?1:M.key==="sex"?+Lo(g).fem.toFixed(2):M.key==="age"?Lo(g).age:0)),S=>f({figure:{[M.key]:S}}))),t.jsx("div",{className:"shot-char-skins",role:"group","aria-label":o("Màu da"),children:wr.map(M=>t.jsx("button",{type:"button","aria-label":M,"aria-pressed":m.color===M,className:m.color===M?"on":"",style:{background:M},onClick:()=>f({color:M,figure:{skin:M}})},M))}),t.jsx("h4",{children:o("Khuôn mặt")}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Kiểu mặt")}),t.jsx("select",{"aria-label":o("Kiểu mặt"),value:m.face.preset,onChange:M=>{const S=Ea[M.target.value];f({face:{preset:M.target.value,width:S.width,length:S.length,eyes:S.eyes}})},children:Object.entries(Ea).map(([M,S])=>t.jsx("option",{value:M,children:l(S)},M))})]}),sx.map(M=>v(M,m.face[M.key],S=>f({face:{[M.key]:S}}))),t.jsx("h4",{children:o("Tóc & trang phục")}),C("hair",dm,"style","Tóc"),C("top",um,"type","Áo"),C("bottom",mm,"type","Quần / váy"),!n&&t.jsx("button",{className:"pill-btn primary",onClick:x,children:o("+ Tạo nhân vật (đã gắn xương)")}),n&&t.jsx("small",{className:"muted",children:o("Mở tab Rigging để xoay xương, hoặc dùng thư viện chuyển động như với ma-nơ-canh.")})]})}function ox(e,n){const s=e.getStage();let a=n,i=2;for(;s.items.some(r=>r.name===a);)a=`${n} ${i++}`;return a}let mn=null,En,ts,yc=null,Ks;const vc=new Map,Ei=new Map;let jc=Promise.resolve(),kc=0;const wc=160,Mc=120;function ix(){if(mn)return mn;mn=new Ir({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),mn.outputColorSpace=Uo,mn.toneMapping=ad,mn.toneMappingExposure=1.15,mn.shadowMap.enabled=!0,mn.shadowMap.type=T0,mn.setClearColor(0,0),mn.setSize(wc,Mc,!1),En=new Rr;const e=new od(mn);yc=e.fromScene(new md,.04).texture,e.dispose(),En.environment=yc,En.environmentIntensity=.7,En.add(new id("#e8eeff","#5d5a55",.9));const n=new Go("#fff4e4",2.4);return n.castShadow=!0,n.shadow.mapSize.set(512,512),n.shadow.bias=-4e-4,En.add(n,n.target),Ks=new ut(new Xo(1,1),new L0({opacity:.32})),Ks.rotation.x=-Math.PI/2,Ks.receiveShadow=!0,En.add(Ks),ts=new Fr(28,wc/Mc,.05,2e3),mn}function rx(e){const n=new $t,s=new St;return e.updateMatrixWorld(!0),e.traverse(a=>{if(a instanceof Bs){const i=a.geometry.boundingBox??(a.geometry.computeBoundingBox(),a.geometry.boundingBox);for(let r=0;r<a.count;r++)a.getMatrixAt(r,s),n.union(i.clone().applyMatrix4(s).applyMatrix4(a.matrixWorld))}else a instanceof ut&&n.union(new $t().setFromObject(a))}),n}function lx(e){const n=ix(),s=pm(fm(e).recipe);En.add(s);try{const a=rx(s);if(a.isEmpty())throw new Error(`empty model ${e}`);const i=a.getSize(new ie),r=a.getCenter(new ie),l=Math.max(.05,i.length()/2),c=Ln.degToRad(ts.fov)/2,u=l/Math.sin(c)*.98,m=new ie(.62,.42,1).normalize();ts.position.copy(r).addScaledVector(m,u),ts.near=u/100,ts.far=u*4,ts.updateProjectionMatrix(),ts.lookAt(r),Ks.position.set(r.x,a.min.y+.001,r.z),Ks.scale.setScalar(l*6);const d=En.children.find(p=>p instanceof Go);d.position.copy(r).add(new ie(-.6,1.4,.9).multiplyScalar(l*3)),d.target.position.copy(r);const f=d.shadow.camera;return f.left=f.bottom=-l*1.6,f.right=f.top=l*1.6,f.near=l*.1,f.far=l*8,f.updateProjectionMatrix(),n.render(En,ts),n.domElement.toDataURL("image/png")}finally{En.remove(s),s.traverse(a=>{a instanceof ut&&(a.geometry.dispose(),a.material.dispose())})}}function cx(e){const n=vc.get(e);if(n)return Promise.resolve(n);const s=Ei.get(e);if(s)return s;if(!Dh(e))return Promise.reject(new Error(`unknown model kit ${e}`));const a=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof a=="number"&&kc>=a)return Promise.reject(new Error("thumbnail limit"));kc++;const i=jc.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const c=lx(e);vc.set(e,c),r(c)}catch(c){l(c)}},16))).finally(()=>Ei.delete(e));return jc=i.catch(()=>{}),Ei.set(e,i),i}const Sa="claude-opus-5-5",Sc=e=>`${Math.round(e/1e3).toLocaleString("vi-VN")}k đ`;function eo({quote:e,error:n}){return n?t.jsx("small",{className:"shot-hq-quote",role:"alert",children:n}):e?!Number.isFinite(e.credits?.low)||!Number.isFinite(e.credits?.high)||!e.vnd?null:t.jsx("small",{className:"shot-hq-quote",children:o("Ước tính {0}–{1} credit (≈ {2}–{3}) cho một model mới · tối đa {4} credit mỗi lượt, tính theo token dùng thật",[e.credits.low.toFixed(1),e.credits.high.toFixed(1),Sc(e.vnd.low),Sc(e.vnd.high),$a])}):t.jsx("small",{className:"shot-hq-quote",children:o("Đang ước tính chi phí…")})}const Cc=[["real","Chân thật","photoreal, real materials"],["stylized","Stylized","stylized, clean shapes, saturated colours"],["lowpoly","Low-poly","low-poly, faceted (flat:true), few segments"]];function hx({host:e,item:n,onSelect:s,setError:a}){ht();const i=zh(),[r,l]=R.useState(""),[c,u]=R.useState(""),[m,d]=R.useState("real"),[f,p]=R.useState(null),[x,g]=R.useState(null),[v,w]=R.useState(null),[C,M]=R.useState(""),[S,I]=R.useState(""),[y,k]=R.useState(!1),T=R.useRef(void 0),j=rc(n)&&n.gen?.kind==="code"?n.gen:null,L=["thinking","acting","rendering"].includes(i.phase),N=i.purpose==="model"&&(i.log.length>0||L),A=[...e.getStage().items].reverse().find(V=>rc(V));R.useEffect(()=>{g(null),w(null),M("")},[n?.id]);const O=async V=>{M("");try{g(await p0(Sa,V)),w(V)}catch(B){M(B.message)}},_=async V=>{if(!V){p(null);return}if(V.size>28e4||!["image/jpeg","image/png"].includes(V.type)){a(o("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const B=await new Promise((q,D)=>{const ee=new FileReader;ee.onload=()=>q(String(ee.result)),ee.onerror=()=>D(ee.error),ee.readAsDataURL(V)});p({name:V.name,data:B})},$=()=>{const V=r.trim();if(!V||L)return;const B=Cc.find(D=>D[0]===m),q=`${V}
|
|
3
|
-
Style: ${B[2]}.${c.trim()?` Real size: ${c.trim()}.`:""}${f?" Match the attached reference photo.":""}`;i.start(q,f?.data||null,Sa,"model",{quality:"high"}),g(null),w(null)},P=()=>{const V=S.trim();if(!V||!j||L)return;const B=`Edit the code model named "${n.name}" (read_model_code, then code_model with the same name; keep everything not mentioned): ${V}`;i.purpose==="model"&&(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===Sa&&i.quality==="high"?i.followUp(B):i.start(B,null,Sa,"model",{quality:"high"}),I(""),g(null),w(null)},W=(V,B)=>{if(!j||!n)return;const q={...j.code.params,[V]:B};e.setStage(D=>({...D,items:D.items.map(ee=>ee.id===n.id&&ee.gen?.kind==="code"?{...ee,gen:{...ee.gen,code:{...ee.gen.code,params:q}}}:ee)})),window.clearTimeout(T.current),T.current=window.setTimeout(()=>{lc(e,{name:n.name,params:q,views:!1}).then(D=>{D.ok||a(String(D.error))})},250)},z=async()=>{if(!(!j||!n)){k(!0);try{const V=await lc(e,{name:n.name,seed:j.code.seed%2147483e3+1,views:!1});V.ok||a(String(V.error))}finally{k(!1)}}},Q=async()=>{if(!(!j||!n)){k(!0);try{const V=await V0(j.code),B=URL.createObjectURL(V),q=document.createElement("a");q.href=B,q.download=`${n.name.replace(/[^\p{L}\p{N}_-]+/gu,"_")||"model"}.glb`,q.click(),window.setTimeout(()=>URL.revokeObjectURL(B),4e3)}catch(V){a(V.message)}finally{k(!1)}}},J=N&&t.jsxs("div",{className:"shot-hq-progress",role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[t.jsx("b",{className:"shot-hq-badge",children:o("Chất lượng cao · Opus")}),L?o("Đang dựng…"):i.phase==="capped"?o("Đã dùng hết {0} credit của lượt này",[$a]):i.phase==="done"?o("Xong"):i.phase==="error"?o("Lỗi"):i.phase==="cancelled"?o("Đã dừng"):""," · ",o("bước")," ",i.step," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-6).map((V,B)=>t.jsx("div",{className:"shot-mission-line",children:V},B)),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:o('Lượt này đã dùng hết {0} credit nên Agent dừng lại; model đang có vẫn giữ nguyên. Gõ yêu cầu ở ô "Sửa bằng lời" để làm tiếp (thêm {0} credit).',[$a])}),i.error&&t.jsx("p",{role:"alert",children:i.error}),L&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>i.stop(),children:o("Dừng")}),!L&&!j&&A&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(A.id),children:o("Chỉnh model vừa dựng: {0}",[A.name])})]});return j&&n?t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsx("strong",{children:n.name}),t.jsx("small",{className:"muted",children:o("Model dựng bằng code · Opus")})]}),j.prompt&&t.jsx("small",{className:"muted shot-hq-prompt",children:j.prompt}),(j.schema||[]).length>0?t.jsx("div",{className:"shot-model-params",children:(j.schema||[]).map(V=>t.jsx(dx,{p:V,value:j.code.params[V.key]??V.default,onChange:B=>W(V.key,B)},V.key))}):t.jsx("small",{className:"muted",children:o("Model này không có thanh trượt tham số.")}),t.jsx("small",{className:"muted",children:o("Kéo thanh trượt để dựng lại ngay trên máy: không gọi AI, 0 credit.")}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:y,onClick:()=>void z(),children:o("Biến thể khác (0 credit)")}),t.jsx("button",{type:"button",className:"pill-btn thin",disabled:y,onClick:()=>void Q(),children:o("Tải .glb")})]}),t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:o("Sửa bằng lời (AI · Opus)")}),t.jsx("textarea",{rows:3,maxLength:1500,value:S,disabled:L,placeholder:o("Ví dụ: cổ chai dài hơn, thêm nắp nhôm, nhãn màu xanh lá"),onChange:V=>{I(V.target.value),v!=="edit"&&g(null)}})]}),v==="edit"&&x?t.jsx(eo,{quote:x}):C?t.jsx(eo,{quote:null,error:C}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:L||!S.trim(),onClick:()=>void O("edit"),children:o("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:L||!S.trim()||v!=="edit",title:v!=="edit"?o("Xem ước tính chi phí trước"):"",onClick:P,children:o("Sửa (≈ {0}–{1} cr)",[x?.credits.low.toFixed(1)??"?",x?.credits.high.toFixed(1)??"?"])})]}),J,t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(null),children:o("+ Dựng model mới")})]}):t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:o("Mô tả model")}),t.jsx("textarea",{rows:4,maxLength:3e3,value:r,disabled:L,placeholder:o("Ví dụ: chai nước hoa thuỷ tinh 50 ml, thân vuông bo góc, nắp vàng xước, nước màu hồng nhạt"),onChange:V=>l(V.target.value)})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:o("Kích thước thật (tuỳ chọn)")}),t.jsx("input",{value:c,maxLength:80,disabled:L,placeholder:o("vd: cao 12 cm"),onChange:V=>u(V.target.value)})]}),t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:o("Phong cách")}),t.jsx("select",{value:m,disabled:L,onChange:V=>d(V.target.value),children:Cc.map(([V,B])=>t.jsx("option",{value:V,children:o(B)},V))})]})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-mission-ref",children:[t.jsx("input",{type:"file",accept:"image/jpeg,image/png",hidden:!0,disabled:L,onChange:V=>{_(V.target.files?.[0]),V.target.value=""}}),t.jsx("span",{children:f?`🖼 ${f.name}`:o("+ Ảnh tham chiếu (tuỳ chọn)")})]}),f&&!L&&t.jsx("button",{type:"button",onClick:()=>p(null),children:"×"})]}),v==="build"&&x?t.jsx(eo,{quote:x}):C?t.jsx(eo,{quote:null,error:C}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:L||!r.trim(),onClick:()=>void O("build"),children:o("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:L||!r.trim()||v!=="build",title:v!=="build"?o("Xem ước tính chi phí trước"):"",onClick:$,children:o("Dựng (≈ {0}–{1} cr)",[x?.credits.low.toFixed(1)??"?",x?.credits.high.toFixed(1)??"?"])})]}),J]})}function dx({p:e,value:n,onChange:s}){return e.type==="num"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"range",min:e.min,max:e.max,step:e.step,value:Number(n),onChange:a=>s(Number(a.target.value))}),t.jsx("output",{children:Number(n).toFixed(e.step<1?Math.min(3,Math.max(0,-Math.floor(Math.log10(e.step)))):0)})]}):e.type==="bool"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"checkbox",checked:!!n,onChange:a=>s(a.target.checked)})]}):e.type==="choice"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("select",{value:String(n),onChange:a=>s(a.target.value),children:e.options.map(a=>t.jsx("option",{value:a,children:a},a))})]}):t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"color",value:String(n),onChange:a=>s(a.target.value)}),t.jsx("output",{children:String(n)})]})}function ux({host:e,item:n,ground:s,onSelect:a,setError:i}){ht();const[r,l]=R.useState("Sản phẩm"),[c,u]=R.useState(""),[m,d]=R.useState(null),[f,p]=R.useState(null),[x,g]=R.useState([]),[v,w]=R.useState(""),[C,M]=R.useState(null),S=async(N,A)=>{if(N){if(!/^image\/(png|jpeg|webp)$/.test(N.type)){i(o("Ảnh phải là PNG, JPG hoặc WEBP."));return}w(o("Đang tải ảnh lên…"));try{const O=await _s(N,void 0,"image");A({name:N.name,url:O.url})}catch(O){i(O.message)}finally{w("")}}},I=N=>Number(String(N).replace(",","."))/100,y=async()=>{if(!m){i(o("Chọn ảnh chính diện của sản phẩm."));return}if(!(I(c)>0)){i(o("Nhập chiều cao thật của sản phẩm (cm)."));return}w(o("Đang dựng sản phẩm…")),M(null);try{const{modelProduct:N}=await Wn(async()=>{const{modelProduct:O}=await import("./productTools-r2RgILaA.js");return{modelProduct:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),A=await N({image:m.url,...f?{back_image:f.url}:{},height_m:I(c),name:r.trim()||"Sản phẩm",position:s(),labels:x.filter(O=>O.url&&I(O.height)>0).map(O=>({image:O.url,bottom_m:I(O.bottom)||0,height_m:I(O.height),center_deg:Number(O.side),finish:O.finish}))},e);A.ok?A.id&&a(String(A.id)):i(String(A.error))}finally{w("")}},k=async()=>{if(n){w(o("Đang xuất GLB…"));try{const{saveGlb:N}=await Wn(async()=>{const{saveGlb:O}=await import("./productTools-r2RgILaA.js");return{saveGlb:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),A=await N({name:n.name},e);A.ok?M({file:String(A.file),url:String(A.url)}):i(String(A.error))}finally{w("")}}},T=async()=>{if(n?.set){w(o("Đang xuất GLB…"));try{const{recipeGlb:N}=await Wn(async()=>{const{recipeGlb:W}=await import("./exportGlb-DstxwzH5.js");return{recipeGlb:W}},__vite__mapDeps([11,1,2,3,4,5,6,7,8,9,10])),{loadSetOf:A}=await Wn(async()=>{const{loadSetOf:W}=await import("./remote-sTZauTqM.js").then(z=>z.jq);return{loadSetOf:W}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10])),O=e.engine()?.setRecipe(n.set.id)??await A(e)(n.set.id),_=await N(O),$=document.createElement("a"),P=URL.createObjectURL(_);$.href=P,$.download=`${n.name}.glb`,$.click(),setTimeout(()=>URL.revokeObjectURL(P),5e3)}catch(N){i(N.message)}finally{w("")}}},j=(N,A,O)=>t.jsxs("label",{className:"shot-product-pick",children:[t.jsx("span",{children:N}),t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:_=>void S(_.target.files?.[0],O)}),A?t.jsx("img",{src:A.url,alt:""}):t.jsx("em",{children:o("Chưa chọn")})]}),L=(N,A)=>g(O=>O.map(_=>_.key===N?{..._,...A}:_));return t.jsxs("div",{className:"shot-product",children:[t.jsx("p",{className:"shot-product-hint",children:o("Ảnh sản phẩm chụp thẳng, nền trơn (hoặc PNG trong suốt) cho dáng và màu; file thiết kế nhãn cho bao bì sắc nét, đúng kích thước.")}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:o("Tên")}),t.jsx("input",{value:r,onChange:N=>l(N.target.value)})]}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:o("Chiều cao thật (cm)")}),t.jsx("input",{inputMode:"decimal",value:c,placeholder:"29",onChange:N=>u(N.target.value)})]}),j(o("Ảnh chính diện"),m,d),j(o("Ảnh mặt sau (không bắt buộc)"),f,p),t.jsxs("div",{className:"shot-product-labels",children:[t.jsx("b",{children:o("File thiết kế nhãn / bao bì")}),x.map(N=>t.jsxs("div",{className:"shot-product-label",children:[N.url?t.jsx("img",{src:N.url,alt:""}):t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:A=>void S(A.target.files?.[0],O=>O&&L(N.key,{url:O.url,name:O.name}))}),t.jsxs("label",{children:[o("Đáy nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.bottom,onChange:A=>L(N.key,{bottom:A.target.value})})]}),t.jsxs("label",{children:[o("Cao nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.height,onChange:A=>L(N.key,{height:A.target.value})})]}),t.jsxs("label",{children:[o("Mặt"),t.jsxs("select",{value:N.side,onChange:A=>L(N.key,{side:A.target.value}),children:[t.jsx("option",{value:"0",children:o("Trước")}),t.jsx("option",{value:"180",children:o("Sau")})]})]}),t.jsxs("label",{children:[o("Bề mặt"),t.jsxs("select",{value:N.finish,onChange:A=>L(N.key,{finish:A.target.value}),children:[t.jsx("option",{value:"matte",children:o("Giấy mờ")}),t.jsx("option",{value:"gloss",children:o("Bóng")}),t.jsx("option",{value:"foil",children:o("Nhũ kim loại")})]})]}),t.jsx("button",{type:"button",onClick:()=>g(A=>A.filter(O=>O.key!==N.key)),children:"✕"})]},N.key)),t.jsxs("button",{type:"button",onClick:()=>g(N=>[...N,{key:Date.now(),name:"",url:"",bottom:"",height:"",side:"0",finish:"matte"}]),children:["+ ",o("Thêm nhãn")]})]}),t.jsx("button",{type:"button",className:"shot-product-build",disabled:!!v,onClick:()=>void y(),children:o("Dựng sản phẩm")}),n?.set&&t.jsxs("div",{className:"shot-product-export",children:[t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void k(),children:o("Lưu GLB vào Tài sản của tôi")}),t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void T(),children:o("Tải .glb")}),C&&t.jsxs("span",{children:[o("Đã lưu")," ",C.file]})]}),v&&t.jsx("p",{className:"shot-product-busy",children:v})]})}function wd(){return t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 2.8 20 7.4v9.2L12 21.2 4 16.6V7.4z"}),t.jsx("path",{d:"m4 7.4 8 4.6 8-4.6M12 12v9.2"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.3",fill:"currentColor"})]})}const Nc={oak:["Gỗ sồi","Oak"],walnut:["Gỗ óc chó","Walnut"],painted_wood:["Gỗ sơn","Painted wood"],concrete:["Bê tông","Concrete"],polished_concrete:["Bê tông mài","Polished concrete"],plaster:["Tường sơn","Plaster"],brick_red:["Gạch đỏ","Red brick"],brick_white:["Gạch sơn trắng","White brick"],tile_small:["Gạch nhỏ","Small tiles"],tile_medium:["Gạch 30 cm","Medium tiles"],tile_large:["Gạch 60 cm","Large tiles"],marble:["Đá cẩm thạch","Marble"],terrazzo:["Đá mài","Terrazzo"],linen:["Vải lanh","Linen"],velvet:["Nhung","Velvet"],leather:["Da","Leather"],carpet:["Thảm","Carpet"],glass_clear:["Kính trong","Clear glass"],glass_frosted:["Kính mờ","Frosted glass"],brushed_steel:["Inox xước","Brushed steel"],chrome:["Crôm","Chrome"],gold:["Vàng / đồng","Gold / brass"],plastic_matte:["Nhựa mờ","Matte plastic"],plastic_glossy:["Nhựa bóng","Glossy plastic"],rubber:["Cao su","Rubber"],asphalt:["Nhựa đường","Asphalt"],paving:["Gạch lát vỉa hè","Paving"],grass:["Cỏ","Grass"],soil:["Đất","Soil"],sand:["Cát","Sand"],water:["Nước","Water"],roof_tiles:["Ngói","Roof tiles"],ceramic:["Gốm sứ","Ceramic"],paper:["Giấy / bìa","Paper / cardboard"]},mx=[.01,.05,.1,.25,.5],px={box:["hộp","box"],cylinder:["trụ","cylinder"],cone:["nón","cone"],sphere:["cầu","sphere"],stairs:["bậc thang","stairs"],lathe:["khối tiện","lathe"],extrude:["khối đùn","extrusion"]};function fx(e){const{stage:n,selected:s}=e,a=n.items.find(m=>m.id===s&&m.kind==="set"&&m.set),i=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="character"),r=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="code"),[l,c]=R.useState(r?"ai":i?"character":a?.set?.kit?.id===ka?"hand":"library");R.useEffect(()=>{a?.set?.kit&&c(a.set.kit.id===ka?"hand":"library")},[a?.id,a?.set?.kit?.id]),R.useEffect(()=>{i&&c("character")},[i?.id]),R.useEffect(()=>{r&&c("ai")},[r?.id]);const u={getStage:e.getStage,setStage:e.change,engine:()=>e.engine};return t.jsxs("div",{className:"shot-panel-body shot-modeling",role:"region","aria-label":o("Dựng model"),children:[t.jsx("div",{className:"shot-model-tabs",role:"tablist",children:["library","hand","character","product"].map(m=>t.jsx("button",{role:"tab","aria-selected":l===m,className:l===m?"on":"",onClick:()=>c(m),children:m==="library"?o("Thư viện model"):m==="hand"?o("Dựng tay"):m==="character"?o("Nhân vật"):o("Sản phẩm từ ảnh")},m))}),t.jsxs("button",{type:"button",className:`shot-model-ai-tab${l==="ai"?" on":""}`,"aria-pressed":l==="ai",onClick:()=>c("ai"),children:["✦ ",o("AI chất lượng cao")]}),l==="library"?t.jsx(gx,{...e,host:u,item:a?.set?.kit&&a.set.kit.id!==ka?a:void 0}):l==="hand"?t.jsx(wx,{...e,item:a?.set?.kit?.id===ka?a:void 0}):l==="character"?t.jsx(ax,{host:u,item:i,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):l==="product"?t.jsx(ux,{host:u,item:a,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):t.jsx(hx,{host:u,item:r,ground:e.ground,onSelect:e.onSelect,setError:e.setError}),a&&l!=="character"&&l!=="ai"&&l!=="product"&&t.jsx(yx,{item:a,change:e.change})]})}function gx({host:e,item:n,ground:s,onSelect:a,setError:i}){const r=ht(),l=j=>r==="en"?j.en:j.vi,[c,u]=R.useState("all"),[m,d]=R.useState(""),[f,p]=R.useState(null),[x,g]=R.useState({}),[v,w]=R.useState(!1),C=n?.set?.kit,M=Dh(C?.id??f??""),S=C?C.params:x,I=R.useRef(void 0),y=(j,L)=>{if(!M)return;const N={...S,[j]:L};if(!C){g(N);return}window.clearTimeout(I.current),I.current=window.setTimeout(()=>{Al(e,{kit:M.id,params:N,name:n.name}).then(A=>{A.ok||i(String(A.error))})},280)},k=async()=>{if(M){w(!0);try{const j=await Al(e,{kit:M.id,params:x,name:Sd(e.getStage(),l(M)),position:s()});j.ok?a(String(j.id)):i(String(j.error))}catch(j){i(j.message)}finally{w(!1)}}},T=R.useMemo(()=>gm(m,c),[m,c]);return M?t.jsxs("div",{className:"shot-model-edit",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("button",{className:"pill-btn thin",onClick:()=>{C&&a(null),p(null)},children:["← ",o("Thư viện")]}),t.jsx(Ac,{id:M.id,alt:l(M),small:!0}),t.jsx("strong",{children:l(M)}),C&&t.jsx("small",{className:"muted",children:o("Đang sửa: {0}",[n.name])})]}),t.jsx("div",{className:"shot-model-params",children:M.params.map(j=>t.jsx(xx,{spec:j,value:S[j.key]??Nl(M.id)[j.key],locale:r,onChange:L=>y(j.key,L)},j.key))}),!C&&t.jsx("button",{className:"pill-btn primary",disabled:v,onClick:()=>void k(),children:v?o("Đang dựng model…"):o("Thêm vào cảnh")}),t.jsx("small",{className:"muted",children:C?o("Thay đổi được dựng lại ngay trên cảnh. Kích thước tính bằng mét thật."):o("Model đặt ở giữa khung nhìn, mặt trước hướng +Z. Kích thước tính bằng mét thật.")})]}):t.jsxs("div",{className:"shot-model-lib",children:[t.jsx("input",{type:"search",className:"shot-model-search","aria-label":o("Tìm model"),placeholder:o("Tìm: nhà phố, sofa, ô tô…"),value:m,onChange:j=>d(j.target.value)}),t.jsx("div",{className:"shot-model-groups",role:"group","aria-label":o("Nhóm model"),children:[{id:"all",vi:"Tất cả",en:"All"},...xm].map(j=>t.jsx("button",{className:`pill-btn thin${c===j.id?" on":""}`,"aria-pressed":c===j.id,onClick:()=>u(j.id),children:l(j)},j.id))}),t.jsxs("div",{className:"shot-model-grid",children:[T.map(j=>t.jsxs("button",{className:"shot-model-card","aria-label":`${o("Chọn model")} ${l(j)}`,onClick:()=>{p(j.id),g(Nl(j.id))},children:[t.jsx(Ac,{id:j.id,alt:""}),t.jsx("strong",{children:l(j)}),t.jsxs("small",{children:[j.params.length," ",o("tham số")]})]},j.id)),!T.length&&t.jsx("p",{className:"muted",children:o("Không có model nào khớp.")})]})]})}function Ac({id:e,alt:n,small:s}){const[a,i]=R.useState(null),[r,l]=R.useState(!1),c=R.useRef(null);R.useEffect(()=>{if(r||!c.current||typeof IntersectionObserver>"u"){r||l(!0);return}const m=new IntersectionObserver(d=>{d.some(f=>f.isIntersecting)&&(l(!0),m.disconnect())},{rootMargin:"160px"});return m.observe(c.current),()=>m.disconnect()},[r]),R.useEffect(()=>{if(!r)return;let m=!0;return i(null),cx(e).then(d=>{m&&i(d)}).catch(()=>{}),()=>{m=!1}},[r,e]);const u=`shot-model-thumb${s?" small":""}`;return a?t.jsx("img",{className:u,src:a,alt:n,draggable:!1,"data-kit":e}):t.jsx("span",{ref:c,className:`${u} loading`,role:n?"img":void 0,"aria-label":n||void 0,"aria-hidden":n?void 0:!0,children:t.jsx(wd,{})})}function xx({spec:e,value:n,locale:s,onChange:a}){const i=s==="en"?e.en:e.vi;if(e.type==="num"||e.type==="int"){const r=Number(n);return t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"range","aria-label":i,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>a(+l.target.value)}),t.jsx("input",{type:"number","aria-label":`${i} (${o("số")})`,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>{const c=+l.target.value;Number.isFinite(c)&&a(Math.min(e.max,Math.max(e.min,c)))}})]})}return e.type==="choice"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>a(r.target.value),children:e.options.map(r=>t.jsx("option",{value:r.id,children:s==="en"?r.en:r.vi},r.id))})]}):e.type==="material"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>a(r.target.value),children:e.allowed.map(r=>t.jsx("option",{value:r,children:bx(r,s)},r))})]}):e.type==="text"?t.jsxs("label",{className:"shot-model-param shot-model-text",children:[t.jsx("span",{children:i}),t.jsx("textarea",{"aria-label":i,rows:2,maxLength:e.max,value:String(n),onChange:r=>a(r.target.value)})]}):t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"color","aria-label":i,value:String(n),onChange:r=>a(r.target.value)})]})}const bx=(e,n)=>Nc[e]?Nc[e][n==="en"?1:0]:e;function Md({value:e,onChange:n,label:s,none:a}){const i=ht();return t.jsxs("select",{"aria-label":s,value:e,onChange:r=>n(r.target.value),children:[a&&t.jsx("option",{value:"",children:a}),_h.map(r=>t.jsx("optgroup",{label:i==="en"?r.en:r.vi,children:ym.filter(l=>l.cat===r.id).map(l=>t.jsx("option",{value:l.id,children:wa(l,i==="en"?"en":"vi")},l.id))},r.id))]})}function yx({item:e,change:n}){const s=e.materials?.[qs]?.preset??"";return t.jsxs("label",{className:"shot-model-param shot-model-whole",children:[t.jsx("span",{children:o("Vật liệu cả model")}),t.jsx(Md,{label:o("Vật liệu cả model"),value:s,none:o("Theo từng khối"),onChange:a=>n(i=>zs(i,e.id,qs,a?{preset:a}:null))})]})}function Sd(e,n){let s=n,a=2;for(;e.items.some(i=>i.name===s);)s=`${n} ${a++}`;return s}const Tc={box:()=>({shape:"box",name:"Hộp",size:[1,1,1],position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cylinder:()=>({shape:"cylinder",name:"Trụ",size:[.5,1,.5],position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),cone:()=>({shape:"cone",name:"Nón",size:[.8,1,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),sphere:()=>({shape:"sphere",name:"Cầu",size:[.8,.8,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),stairs:()=>({shape:"stairs",name:"Bậc thang",size:[1.2,1.5,2.5],steps:9,position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),wall_door:()=>({shape:"extrude",name:"Tường có cửa",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.45,0],[.45,0],[.45,2.1],[-.45,2.1]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),wall_window:()=>({shape:"extrude",name:"Tường có cửa sổ",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.7,.9],[.7,.9],[.7,2.2],[-.7,2.2]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cut_box:()=>({shape:"box",name:"Khoét",size:[.5,.5,2],position:[0,.25,0],rotation:[0,0,0],op:"subtract"}),cut_cylinder:()=>({shape:"cylinder",name:"Lỗ tròn",size:[.4,2,.4],position:[0,-.5,0],rotation:[0,0,0],op:"subtract"}),arch:()=>({shape:"extrude",name:"Cổng vòm",outline:[[-1.5,0],[1.5,0],[1.5,3.2],[-1.5,3.2]],holes:[[[-.8,0],[.8,0],[.8,1.8],...Array.from({length:9},(e,n)=>{const s=(n+1)*Math.PI/10;return[+(.8*Math.cos(s)).toFixed(3),+(1.8+.8*Math.sin(s)).toFixed(3)]}),[-.8,1.8]]],depth:.4,position:[0,0,0],rotation:[0,0,0],look:{preset:"brick_white"}})},vx=[["box","Hộp"],["cylinder","Trụ"],["cone","Nón"],["sphere","Cầu"],["stairs","Bậc thang"],["wall_door","Tường có cửa"],["wall_window","Tường có cửa sổ"],["arch","Cổng vòm"],["cut_box","Khoét hộp"],["cut_cylinder","Khoét lỗ tròn"]],jx={union:"Hợp (gộp vào)",subtract:"Trừ (khoét)",intersect:"Giao (giữ phần chung)"},kx={union:"gộp vào",subtract:"khoét",intersect:"giao với"};function wx({stage:e,change:n,engine:s,onSelect:a,ground:i,setError:r,item:l}){const c=ht(),[u,m]=R.useState(null),[d,f]=R.useState(0),[p,x]=R.useState(.05),g=l?.set?.id;R.useEffect(()=>{f(0),m(g?s?.setRecipe(g)??null:null)},[g,s]);const v=R.useRef(void 0),w=(N,A=l)=>{if(!A?.set)return;let O;try{O=Tl(N)}catch($){r($.message);return}m(O),s?.cacheSet(A.set.id,O);const _=Ll(O);n($=>({...$,items:$.items.map(P=>P.id===A.id?{...P,set:{...P.set,parts:O.parts.length,min:_.min,max:_.max}}:P)})),window.clearTimeout(v.current),v.current=window.setTimeout(()=>{nc(A.set.id,A.name,O).catch($=>r($.message))},400)},C=async()=>{const N=crypto.randomUUID(),A=Sd(e,o("Model tự dựng")),O=Tl({v:1,parts:[Tc.box()]});try{await nc(N,A,O)}catch(P){r(P.message);return}s?.cacheSet(N,O);const _=Ll(O),$=Oh(e,{kind:"set",name:A,color:"#9aa3a8",position:i(),set:{id:N,name:A,parts:1,min:_.min,max:_.max,kit:{id:ka,params:{}}}});n(P=>({...P,items:[...P.items,$]})),a($.id)};if(!l||!u)return t.jsxs("div",{className:"shot-model-hand-empty",children:[t.jsx("p",{className:"muted",children:o("Tự dựng model từ khối cơ bản: hộp, trụ, nón, cầu, bậc thang, tường có cửa, cổng vòm. Mọi kích thước tính bằng mét.")}),t.jsx("button",{className:"pill-btn primary",onClick:()=>void C(),children:o("+ Tạo model mới")}),l&&!u&&t.jsx("p",{className:"muted",children:o("Đang tải model…")})]});const M=u.parts,S=M[Math.min(d,M.length-1)],I=N=>+(Math.round(N/p)*p).toFixed(3),y=N=>w({...u,parts:M.map((A,O)=>O===d?{...A,...N}:A)}),k=N=>{const A=Tc[N]();w({...u,parts:[...M,A]}),f(M.length)},T=(N,A,O,_=-500)=>t.jsxs("div",{className:"shot-model-vec",children:[t.jsx("span",{children:N}),["X","Y","Z"].map(($,P)=>t.jsx("input",{type:"number",step:p,"aria-label":`${N} ${$}`,value:A[P],onChange:W=>{const z=+W.target.value;if(!Number.isFinite(z))return;const Q=[...A];Q[P]=Math.max(_,I(z)),O(Q)}},$))]}),j=N=>{const A=(N.outline||[]).map(_=>_[0]),O=(N.outline||[]).map(_=>_[1]);return[+(Math.max(...A)-Math.min(...A)).toFixed(3),+(Math.max(...O)-Math.min(...O)).toFixed(3),N.depth||.2]},L=(N,A)=>{const[O,_]=j(N),$=A[0]/(O||1),P=A[1]/(_||1),W=z=>z.map(([Q,J])=>[+(Q*$).toFixed(3),+(J*P).toFixed(3)]);return{outline:W(N.outline||[]),holes:N.holes?.map(W),depth:Math.max(.005,A[2])}};return t.jsxs("div",{className:"shot-model-hand",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["✎ ",l.name]}),t.jsxs("small",{className:"muted",children:[M.length," ",o("khối")]}),t.jsxs("label",{className:"shot-model-snap",children:[o("Bước lưới"),t.jsx("select",{"aria-label":o("Bước lưới"),value:p,onChange:N=>x(+N.target.value),children:mx.map(N=>t.jsx("option",{value:N,children:N<.1?`${N*100} cm`:`${N} m`},N))})]})]}),t.jsx("div",{className:"shot-model-add",role:"group","aria-label":o("Thêm khối"),children:vx.map(([N,A])=>t.jsxs("button",{className:"pill-btn thin",onClick:()=>k(N),children:["+ ",o(A)]},N))}),t.jsx("ul",{className:"shot-model-parts","aria-label":o("Các khối"),children:M.map((N,A)=>t.jsx("li",{children:t.jsxs("button",{className:A===d?"on":"",onClick:()=>f(A),children:[N.name||N.shape," ",t.jsx("small",{children:px[N.shape]?.[c==="en"?1:0]??N.shape})]})},A))}),S&&t.jsxs("div",{className:"shot-model-part",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Tên khối")}),t.jsx("input",{"aria-label":o("Tên khối"),maxLength:40,value:S.name||"",onChange:N=>y({name:N.target.value.slice(0,40)})})]}),S.shape==="extrude"?T(o("Rộng / cao / dày (m)"),j(S),N=>y(L(S,N)),.005):T(o("Kích thước (m)"),S.size||[1,1,1],N=>y({size:N.map(A=>Math.max(.005,A))}),.005),T(o("Vị trí (m)"),S.position,N=>y({position:N})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Xoay quanh trục đứng (°)")}),t.jsx("input",{type:"number","aria-label":o("Xoay quanh trục đứng (°)"),step:15,value:S.rotation[1],onChange:N=>{const A=+N.target.value;Number.isFinite(A)&&y({rotation:[S.rotation[0],Math.max(-360,Math.min(360,A)),S.rotation[2]]})}})]}),S.shape==="stairs"&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Số bậc")}),t.jsx("input",{type:"number","aria-label":o("Số bậc"),min:2,max:80,value:S.steps||10,onChange:N=>y({steps:Math.max(2,Math.min(80,Math.round(+N.target.value)||2))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Phép khối")}),t.jsxs("select",{"aria-label":o("Phép khối"),value:S.op||"",onChange:N=>{const A=N.target.value||void 0;y(A?{op:A}:{op:void 0,target:void 0})},children:[t.jsx("option",{value:"",children:o("Khối thường")}),bm.map(N=>t.jsx("option",{value:N,children:o(jx[N])},N))]})]}),S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Tác động lên")}),t.jsxs("select",{"aria-label":o("Tác động lên"),value:S.target||"",onChange:N=>y({target:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Khối liền trước")}),M.slice(0,d).filter(N=>!N.op&&N.name&&!N.repeat&&!N.mirror).map((N,A)=>t.jsx("option",{value:N.name,children:N.name},A))]})]}),S.op&&t.jsx("small",{className:"muted",children:hi(M,d)>=0?o("Khối này không hiện; nó {0} “{1}”.",[o(kx[S.op]),M[hi(M,d)].name||M[hi(M,d)].shape]):o("Cần một khối thường phía trước để tác động.")}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Vật liệu")}),t.jsx(Md,{label:o("Vật liệu"),value:Es(S)?.preset??"painted_wood",onChange:N=>y({look:{preset:N,...Es(S)?.params?.color?{params:{color:Es(S).params.color}}:{}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})})]}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Màu")}),t.jsx("input",{type:"color","aria-label":o("Màu khối"),value:Es(S)?.params?.color||Oa(Es(S)?.preset??"")?.colors[0]||"#cccccc",onChange:N=>{const A=Es(S)??{preset:"painted_wood"};y({look:{...A,params:{...A.params||{},color:N.target.value}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})}})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Bo cạnh (m)")}),t.jsx("input",{type:"number","aria-label":o("Bo cạnh (m)"),min:0,max:.5,step:.005,value:S.bevel??0,onChange:N=>y({bevel:Math.max(0,Math.min(.5,+N.target.value||0))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Nhân bản (số bản)")}),t.jsx("input",{type:"number","aria-label":o("Nhân bản (số bản)"),min:1,max:200,value:S.repeat?.count??1,onChange:N=>{const A=Math.max(1,Math.min(200,Math.round(+N.target.value)||1));y({repeat:A>1?{count:A,offset:S.repeat?.offset??[1,0,0],yaw:S.repeat?.yaw??0}:void 0})}})]}),S.repeat&&T(o("Khoảng cách bản sao (m)"),S.repeat.offset,N=>y({repeat:{...S.repeat,offset:N}})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Đối xứng")}),t.jsxs("select",{"aria-label":o("Đối xứng"),value:S.mirror||"",onChange:N=>y({mirror:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Không")}),t.jsx("option",{value:"x",children:o("Trái – phải (X)")}),t.jsx("option",{value:"z",children:o("Trước – sau (Z)")}),t.jsx("option",{value:"xz",children:o("Cả hai")})]})]}),t.jsxs("div",{className:"shot-model-actions",children:[t.jsx("button",{className:"pill-btn thin",onClick:()=>{w({...u,parts:[...M,{...S,name:`${S.name||S.shape} 2`,position:[I(S.position[0]+.5),S.position[1],S.position[2]]}]}),f(M.length)},children:o("Nhân đôi khối")}),t.jsx("button",{className:"pill-btn thin",disabled:M.length<2,onClick:()=>{w({...u,parts:M.filter((N,A)=>A!==d)}),f(Math.max(0,d-1))},children:o("Xoá khối")})]})]})]})}function Mx({loop:e,onLoop:n,range:s,rangeOn:a,onRangeOn:i,onEnd:r,onKeyAll:l,onCopy:c,onPaste:u,canPaste:m,onEase:d,onNudge:f,stage:p,cameraActive:x,cameraHidden:g,cameraLocked:v,onToggle:w,onProp:C,shot:M,items:S,time:I,fxBars:y,onFxTiming:k,onParent:T,playing:j,selected:L,picked:N=[],onPick:A,onSeek:O,onPlay:_,onRow:$,onSelect:P,onAdd:W,onMove:z,onDelete:Q,height:J,onHeight:V}){ht();const[B,q]=R.useState(1),[D,ee]=R.useState(220),Z=J??D,xe=G=>{ee(G),V?.(G)},[be,U]=R.useState(null),[pe,me]=R.useState({}),[X,re]=R.useState(!0),ue=R.useRef(void 0),Ee=R.useRef(null),[ye,ne]=R.useState(null),Ie=(G,Se)=>N.some(le=>le.row===G&&le.id===Se),ze=(G,Se,le)=>{if(G.button!==0||!Ee.current)return;G.preventDefault(),ue.current?.();const $e=Ee.current,Le=$e.parentElement,Te=$e.getBoundingClientRect(),Je=G.clientX-Te.left,ke=G.clientY-Te.top,Ue=G.pointerId,At=G.shiftKey,qe=()=>{const rt=$e.getBoundingClientRect();return[rt.left+Je,rt.top+ke]};$e.setPointerCapture(Ue);let mt=!1;const kt=(rt,Tt)=>{const[Rt,sn]=qe(),Sn=Math.min(Rt,rt),Ns=Math.max(Rt,rt),As=Math.min(sn,Tt),Pn=Math.max(sn,Tt),an=At?[...N]:[];return $e.querySelectorAll(".shot-time-key:not([disabled]),.shot-prop-key[data-key]").forEach(xn=>{const oe=xn.getBoundingClientRect(),Ne=oe.left+oe.width/2,Oe=oe.top+oe.height/2;Ne>=Sn&&Ne<=Ns&&Oe>=As&&Oe<=Pn&&!an.some(Re=>Re.row===xn.dataset.row&&Re.id===xn.dataset.key)&&an.push({row:xn.dataset.row,id:xn.dataset.key})}),an};let Xe=[G.clientX,G.clientY],it=0;const xt=()=>{const[rt,Tt]=qe(),[Rt,sn]=Xe,Sn=$e.getBoundingClientRect();ne({x:Math.min(rt,Rt)-Sn.left,y:Math.min(Tt,sn)-Sn.top,w:Math.abs(Rt-rt),h:Math.abs(sn-Tt)}),A?.(kt(Rt,sn))},wt=()=>{if(it=0,!mt||!Le)return;const rt=Le.getBoundingClientRect(),Tt=Xe[1],Rt=Tt<rt.top+28?-Math.ceil((rt.top+28-Tt)/3):Tt>rt.bottom-16?Math.ceil((Tt-rt.bottom+16)/3):0;if(!Rt)return;const sn=Le.scrollTop;Le.scrollTop+=Rt,Le.scrollTop!==sn&&(xt(),it=requestAnimationFrame(wt))},nn=rt=>{if(rt.pointerId!==Ue)return;const[Tt,Rt]=qe();!mt&&Math.hypot(rt.clientX-Tt,rt.clientY-Rt)<4||(mt=!0,Xe=[rt.clientX,rt.clientY],xt(),it||(it=requestAnimationFrame(wt)))},cn=()=>{it&&cancelAnimationFrame(it),it=0,$e.removeEventListener("pointermove",nn),$e.removeEventListener("pointerup",_t),$e.removeEventListener("pointercancel",cn),$e.hasPointerCapture(Ue)&&$e.releasePointerCapture(Ue),ne(null)},_t=rt=>{if(cn(),mt)A?.(kt(rt.clientX,rt.clientY));else{$(Se);const Tt=le.getBoundingClientRect();O(Math.max(0,Math.min(1,(rt.clientX-Tt.left)/Tt.width)))}};ue.current=cn,$e.addEventListener("pointermove",nn),$e.addEventListener("pointerup",_t),$e.addEventListener("pointercancel",cn)};R.useEffect(()=>()=>ue.current?.(),[]);const[we,de]=R.useState(null),H=(G,Se,le,$e)=>{const Le=y?.[Se];if(G.button!==0||!Le||!k)return;G.preventDefault(),G.stopPropagation(),ue.current?.();const Te=G.currentTarget,Je=G.pointerId,ke=G.clientX,Ue=$e.getBoundingClientRect().width,At=M.duration,qe=.2;Te.setPointerCapture(Je);let mt={id:Se,start:Le.start,duration:Le.duration};const kt=wt=>Math.round(wt*20)/20,Xe=wt=>{if(wt.pointerId!==Je)return;const nn=(wt.clientX-ke)/Ue*At;if(le==="move")mt={id:Se,start:kt(Math.max(0,Math.min(At-qe,Le.start+nn))),duration:Le.duration};else if(le==="start"){const cn=Le.start+Le.duration,_t=kt(Math.max(0,Math.min(cn-qe,Le.start+nn)));mt={id:Se,start:_t,duration:+(cn-_t).toFixed(2)}}else mt={id:Se,start:Le.start,duration:kt(Math.max(qe,Le.duration+nn))};de(mt)},it=()=>{Te.removeEventListener("pointermove",Xe),Te.removeEventListener("pointerup",xt),Te.removeEventListener("pointercancel",it),Te.hasPointerCapture(Je)&&Te.releasePointerCapture(Je),de(null)},xt=()=>{it(),(mt.start!==Le.start||mt.duration!==Le.duration)&&k(Se,{start:mt.start,duration:mt.duration})};ue.current=it,Te.addEventListener("pointermove",Xe),Te.addEventListener("pointerup",xt),Te.addEventListener("pointercancel",it)},se=[{id:"camera",kind:"camera",name:"📷 Camera",locked:!!v,hidden:!!g,keys:M.motion==="path"?M.cameraKeys||[]:[]},...S.map(G=>({id:G.id,kind:G.kind==="fx"?"fx":G.kind==="person"?"person":"object",name:G.kind==="fx"?`✦ ${G.name}`:G.name,locked:G.locked,hidden:G.hidden,keys:M.objectKeys?.[G.id]||[],fx:G.kind==="fx",parent:G.fx?.attach?.to??""}))],he=S.filter(G=>G.kind!=="fx"&&!G.hidden),ce=(L?se.filter(G=>G.id===L.row):se).flatMap(G=>G.keys.map(Se=>Se.time)).sort((G,Se)=>G-Se),Pe=G=>{const Se=G>0?ce.find(le=>le>I+1e-4):[...ce].reverse().find(le=>le<I-1e-4);Se!==void 0&&O(Se)},Be=(G,Se)=>{if(G.button!==0)return;G.preventDefault(),G.stopPropagation(),ue.current?.();const le=G.pointerId;Se.setPointerCapture(le);const $e=ke=>{const Ue=Se.getBoundingClientRect(),At=Math.max(0,Math.min(1,(ke.clientX-Ue.left)/Ue.width)),qe=rn(M);O(Math.min(1,Math.round(At*M.duration*qe)/qe/M.duration))},Le=ke=>{ke.pointerId===le&&$e(ke)},Te=()=>{Se.removeEventListener("pointermove",Le),Se.removeEventListener("pointerup",Je),Se.removeEventListener("pointercancel",Te),Se.removeEventListener("lostpointercapture",Te),Se.hasPointerCapture(le)&&Se.releasePointerCapture(le)},Je=ke=>{$e(ke),Te()};ue.current=Te,Se.addEventListener("pointermove",Le),Se.addEventListener("pointerup",Je),Se.addEventListener("pointercancel",Te),Se.addEventListener("lostpointercapture",Te),$e(G)},ot=(G,Se,le,$e)=>{G.preventDefault(),G.stopPropagation(),P(Se,le);const Le=$e.getBoundingClientRect();let Te;const Je=At=>{if(Te=Math.max(0,Math.min(1,(At.clientX-Le.left)/Le.width)),X){const qe=rn(M);Te=Math.min(1,Math.round(Te*M.duration*qe)/qe/M.duration);const mt=se.flatMap(kt=>kt.keys.filter(Xe=>!(kt.id===Se&&Xe.id===le)).map(Xe=>Xe.time)).find(kt=>Math.abs(kt-Te)*Le.width<6);mt!==void 0&&(Te=mt)}U({row:Se,id:le,time:Te})},ke=()=>{window.removeEventListener("mousemove",Je),window.removeEventListener("mouseup",Ue),U(null)},Ue=()=>{ke(),Te!==void 0&&z(Se,le,Te)};ue.current?.(),ue.current=ke,window.addEventListener("mousemove",Je),window.addEventListener("mouseup",Ue)};return t.jsxs("section",{className:"shot-timeline","aria-label":o("Timeline keyframe"),style:{height:Z},children:[t.jsx("div",{className:"shot-timeline-tools",children:(()=>{const G=rn(M),Se=M.duration,le=I*Se,$e=Je=>{const ke=Math.floor(Je/60),Ue=Je-ke*60;return`${String(ke).padStart(2,"0")}:${Ue.toFixed(2).padStart(5,"0")}`},Le=Je=>{O(Math.max(0,Math.min(1,(Math.round(le*G)+Je)/G/Se)))},Te=N.length?!1:!L||se.find(Je=>Je.id===L.row)?.locked;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-tc",children:[t.jsxs("span",{children:[$e(le)," / ",$e(Se)]}),t.jsx("small",{children:o("Khung {0} / {1} · {2} fps",[Math.round(le*G),Math.round(Se*G),G])})]}),t.jsxs("div",{className:"shot-transport",role:"group","aria-label":o("Điều khiển phát"),children:[t.jsx("button",{className:"shot-tp-btn",onClick:()=>O(0),"aria-label":o("Về đầu"),title:o("Về đầu")+" (Home)",children:t.jsx(Ce.skipStart,{})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>Le(-1),disabled:le<=1e-6,"aria-label":o("Lùi 1 khung hình"),title:o("Lùi 1 khung hình")+" (,)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M15 6v12L7 12z"}),t.jsx("rect",{x:"17",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:"shot-tp-play",onClick:_,"aria-label":j?o("Tạm dừng"):o("Phát"),title:(j?o("Tạm dừng"):o("Phát"))+" (Space)",children:j?t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:[t.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",rx:"1"}),t.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",rx:"1"})]}):t.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:t.jsx("path",{d:"M8 5.5v13l11-6.5z"})})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>Le(1),disabled:le>=Se-1e-6,"aria-label":o("Tới 1 khung hình"),title:o("Tới 1 khung hình")+" (.)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M9 6v12l8-6z"}),t.jsx("rect",{x:"5",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:`shot-tp-btn${e?" on":""}`,"data-tool":"loop",onClick:n,disabled:!n,"aria-pressed":!!e,"aria-label":o("Phát lặp"),title:o("Phát lặp")+" (L)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M20 12a8 8 0 1 1-2.6-5.9"}),t.jsx("path",{d:"M20 4v4.5h-4.5"})]})})]}),t.jsxs("div",{className:"shot-tl-right",children:[t.jsx("button",{className:"shot-tp-del",disabled:Te,onClick:Q,"aria-label":N.length>1?o("Xoá {0} key",[N.length]):o("Xoá key"),title:N.length>1?o("Xoá {0} key",[N.length]):o("Xoá key"),children:t.jsx("svg",{viewBox:"0 0 24 24",width:"15",height:"15","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"})})}),t.jsxs("label",{children:[o("Zoom")," ",t.jsx("input",{"aria-label":o("Zoom timeline"),type:"range",min:1,max:8,step:.5,value:B,onChange:Je=>q(+Je.target.value)})]}),t.jsxs("label",{children:[o("Cao")," ",t.jsx("input",{"aria-label":o("Chiều cao timeline"),type:"range",min:140,max:360,step:20,value:Z,onChange:Je=>xe(+Je.target.value)})]})]})]})})()}),t.jsx("div",{className:"shot-edit-bar",role:"toolbar","aria-label":o("Công cụ keyframe"),children:(()=>{const G=N.length?N:L?[L]:[],Se=G.length>0,le=L?.row,$e=(qe,mt)=>mt?`${o(qe)} (${mt})`:o(qe),Le=(qe,mt,kt,Xe,it={})=>t.jsx("button",{type:"button",className:`shot-edit-btn${it.on?" on":""}`,"data-tool":qe,"aria-label":o(kt),"aria-pressed":it.on===void 0?void 0:it.on,title:$e(kt,it.key),disabled:it.disabled||!Xe,onClick:Xe,children:mt},qe),Te=qe=>t.jsx("i",{className:"shot-edit-sep","aria-hidden":!0},qe),Je=qe=>t.jsx("svg",{viewBox:"0 0 20 20",width:"18",height:"18","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:qe}),ke=(qe,mt,kt)=>Le("ease-"+qe,Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M3 17h14M3 3v14"}),t.jsx("path",{d:kt})]})),mt,()=>d?.(qe),{disabled:!Se||!d}),Ue=()=>{q(1),requestAnimationFrame(()=>{const qe=Ee.current?.parentElement;qe&&(qe.scrollLeft=0)})},At=()=>{const qe=se.flatMap(it=>it.keys.filter(xt=>G.some(wt=>wt.row===it.id&&wt.id===xt.id)).map(xt=>xt.time)),mt=Math.min(...qe),kt=Math.max(...qe),Xe=Math.min(8,Math.max(1,.8/Math.max(.02,kt-mt)));q(Xe),requestAnimationFrame(()=>{const it=Ee.current?.parentElement;it&&(it.scrollLeft=Math.max(0,(mt-.05/Xe)*it.clientWidth*Xe))})};return t.jsxs(t.Fragment,{children:[Le("add",Is.key,"Thêm key trên hàng đang chọn",le?()=>W(le):void 0,{key:"K",disabled:!le}),Le("key-all",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m7 4 4 5.5L7 15 3 9.5z"}),t.jsx("path",{d:"m13 4 4 5.5-4 5.5"})]})),"Key tất cả: camera và mọi hàng chưa khoá",l,{key:"⇧K"}),Le("key-prev",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m11 5-5 5 5 5"}),t.jsx("path",{d:"m15 7 3 3-3 3-3-3z"})]})),"Key trước",ce.some(qe=>qe<I-1e-4)?()=>Pe(-1):void 0),Le("key-next",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m9 5 5 5-5 5"}),t.jsx("path",{d:"m5 7 3 3-3 3-3-3z"})]})),"Key sau",ce.some(qe=>qe>I+1e-4)?()=>Pe(1):void 0),Te("s1"),Le("copy",Is.copy,"Copy các key đang chọn",Se?c:void 0,{key:"⌘C",disabled:!Se}),Le("paste",Is.paste,"Dán key tại playhead (giữ khoảng cách)",u,{key:"⌘V",disabled:!m}),Te("s2"),ke("linear","Easing: Tuyến tính","M3 17 17 3"),ke("in","Easing: Vào chậm (ease in)","M3 17C10 17 14 12 17 3"),ke("snap","Easing: Ra chậm (ease out)","M3 17C6 8 10 3 17 3"),ke("smooth","Easing: Vào và ra chậm (ease in-out)","M3 17C10 17 10 3 17 3"),ke("hold","Easing: Giữ nguyên (hold)","M3 17h7V3h7"),Te("s3"),Le("nudge-back",Je(t.jsx("path",{d:"m12 5-5 5 5 5M16 4v12"})),"Dịch key lùi 1 khung hình",Se?()=>f?.(-1):void 0,{key:"Alt+,",disabled:!Se}),Le("nudge-fwd",Je(t.jsx("path",{d:"m8 5 5 5-5 5M4 4v12"})),"Dịch key tới 1 khung hình",Se?()=>f?.(1):void 0,{key:"Alt+.",disabled:!Se}),Te("s4"),Le("range",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M5 4v12M15 4v12"}),t.jsx("path",{d:"M5 10h10",strokeDasharray:"2 2"})]})),s?"Chỉ phát trong vùng I–O":"Chỉ phát trong vùng (đặt I và O trước)",s?i:void 0,{key:"I / O",on:!!a,disabled:!s}),Le("snap",Is.magnet,"Bám khung hình và key khác khi kéo key",()=>re(qe=>!qe),{on:X}),Te("s5"),Le("zoom-fit",Is.fit,"Thu phóng vừa cả shot",Ue),Le("zoom-sel",Is.zoomIn,"Thu phóng vào các key đang chọn",Se?At:void 0,{disabled:!Se}),Le("end",Je(t.jsx("path",{d:"m6 5 5 5-5 5M15 4v12"})),"Về cuối",r,{key:"End"})]})})()}),t.jsx("div",{className:"shot-timeline-scroll",children:t.jsxs("div",{className:"shot-timeline-content",ref:Ee,style:{width:`${B*100}%`},children:[ye&&t.jsx("div",{className:"shot-marquee",style:{left:ye.x,top:ye.y,width:ye.w,height:ye.h}}),t.jsxs("div",{className:"shot-time-row shot-ruler-row",children:[t.jsx("div",{className:"shot-track-name",children:o("Đối tượng")}),t.jsxs("div",{className:"shot-time-ruler",onPointerDown:G=>Be(G,G.currentTarget),children:[(M.lockUntil??0)>0&&t.jsx("div",{className:"shot-lock-band",role:"img",style:{width:`${Math.min(1,M.lockUntil/M.duration)*100}%`},"aria-label":o("Đã khoá 0–{0}s cho Agent",[String(Math.round(Math.min(M.lockUntil,M.duration)*100)/100)]),title:o("Agent không sửa phần này"),children:t.jsx("span",{children:"🔒"})}),s&&t.jsx("div",{className:`shot-range${a?" on":""}`,style:{left:`${s.in*100}%`,width:`${Math.max(0,s.out-s.in)*100}%`},"aria-hidden":!0}),t.jsx("button",{className:"shot-playhead-handle",role:"slider","aria-label":o("Vị trí phát timeline"),"aria-valuemin":0,"aria-valuemax":M.duration,"aria-valuenow":Number((I*M.duration).toFixed(2)),style:{left:`${I*100}%`},onKeyDown:G=>{const Se=G.shiftKey?1:.1,le=1/rn(M);["ArrowLeft","ArrowRight","Home","End",",","."].includes(G.key)&&(G.preventDefault(),O(G.key==="Home"?0:G.key==="End"?1:G.key===","||G.key==="."?Math.max(0,Math.min(1,Math.round(I*M.duration/le+(G.key==="."?1:-1))*le/M.duration)):Math.max(0,Math.min(1,I+(G.key==="ArrowRight"?Se:-Se)/M.duration))))}}),Array.from({length:11},(G,Se)=>t.jsxs("span",{style:{left:`${Se*10}%`},children:[Number((M.duration*Se/10).toFixed(2)),o("s")]},Se))]})]}),se.map(G=>{const Se=p&&pe[G.id]?Q0(p,G.id):[];return t.jsxs(R.Fragment,{children:[t.jsxs("div",{className:`shot-time-row${G.id==="camera"&&x?" camera-active":""}${G.hidden?" is-hidden":""}${G.locked?" is-locked":""}`,children:[t.jsxs("div",{className:"shot-track-name",children:[w&&t.jsx("button",{className:`shot-row-eye${G.hidden?" off":""}`,"aria-pressed":!G.hidden,"aria-label":G.hidden?o("Hiện {0}",[G.name]):o("Ẩn {0}",[G.name]),title:G.id==="camera"?G.hidden?o("Hiện camera trong khung nhìn"):o("Ẩn camera khỏi khung nhìn (không ảnh hưởng ảnh xuất)"):G.hidden?o("Hiện trong cảnh và khi xuất"):o("Ẩn khỏi cảnh và khi xuất"),onClick:()=>w(G.id,"hidden"),children:G.hidden?"◌":"◉"}),p&&t.jsx("button",{className:`shot-row-keys${G.keys.length?" keyed":""}${pe[G.id]?" open":""}`,"aria-expanded":!!pe[G.id],"aria-label":o("Thuộc tính {0}",[G.name]),title:o("Mở / đóng các thuộc tính keyframe"),onClick:()=>me(le=>({...le,[G.id]:!le[G.id]})),children:"◆"}),w&&t.jsx("button",{className:`shot-row-lock${G.locked?" on":""}`,"aria-pressed":G.locked,"aria-label":G.locked?o("Mở khoá {0}",[G.name]):o("Khoá {0}",[G.name]),title:G.locked?o("Mở khoá: cho chọn và kéo"):o("Khoá: không chọn, không kéo, không sửa key"),onClick:()=>w(G.id,"locked"),children:G.locked?"🔒":"🔓"}),t.jsx("button",{className:"shot-row-name",title:G.name,onClick:()=>{G.locked||$(G.id)},children:G.name}),"fx"in G&&G.fx&&T&&t.jsxs("select",{className:"shot-track-parent","aria-label":o("Parent của {0}",[G.name]),title:o("Parent: hiệu ứng đi theo đối tượng này"),disabled:G.locked,value:G.parent,onChange:le=>T(G.id,le.target.value),children:[t.jsx("option",{value:"",children:o("Tự do")}),he.map(le=>t.jsxs("option",{value:le.id,children:["🔗 ",le.name]},le.id))]}),t.jsx("button",{"aria-label":o("Thêm key {0}",[G.name]),disabled:G.locked,onClick:()=>W(G.id),children:"+◆"})]}),t.jsxs("div",{className:"shot-key-track","data-row":G.id,onPointerDown:le=>{le.target.closest(".shot-time-key")||ze(le,G.id,le.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),(M.clipSpans?.[G.id]||[]).map(le=>t.jsx("div",{className:"shot-clip-block","data-clip-block":le.clip,style:{left:`${le.start/M.duration*100}%`,width:`${Math.max(.5,(Math.min(M.duration,le.end)-le.start)/M.duration*100)}%`},title:`${le.label} · ${le.start.toFixed(1)}–${le.end.toFixed(1)}s`,children:t.jsx("span",{children:le.label})},le.id)),(M.motionEdits?.[G.id]||[]).map(le=>t.jsx("div",{className:`shot-edit-mark${le.off?" off":""}`,"data-edit-mark":!0,style:{left:`${Math.max(0,le.start-(le.scope==="span"?0:le.fade))/M.duration*100}%`,width:`${((le.scope==="after"?M.duration:le.end+(le.scope==="span"?0:le.fade))-Math.max(0,le.start-(le.scope==="span"?0:le.fade)))/M.duration*100}%`},title:`${le.label||o("Chỉnh")} · ${(Number(le.start)||0).toFixed(1)}s`},le.id)),y?.[G.id]&&(()=>{const le=we?.id===G.id?we:y[G.id],$e=!!k&&!G.locked,Le=Te=>Te.currentTarget.closest(".shot-key-track");return t.jsx("div",{className:`shot-fx-bar${G.hidden||G.locked?" dim":""}${$e?" editable":""}${we?.id===G.id?" dragging":""}`,"data-fx-bar":G.id,title:o("Hiệu ứng: {0}s → {1}s · kéo để dời, kéo mép để đổi độ dài",[le.start.toFixed(2),(le.start+le.duration).toFixed(2)]),style:{left:`${Math.min(100,le.start/M.duration*100)}%`,width:`${Math.max(.6,Math.min(100-le.start/M.duration*100,le.duration/M.duration*100))}%`},onPointerDown:$e?Te=>H(Te,G.id,"move",Le(Te)):void 0,children:$e&&t.jsxs(t.Fragment,{children:[t.jsx("i",{className:"shot-fx-edge start","aria-hidden":!0,onPointerDown:Te=>H(Te,G.id,"start",Le(Te))}),t.jsx("i",{className:"shot-fx-edge end","aria-hidden":!0,onPointerDown:Te=>H(Te,G.id,"end",Le(Te))})]})})})(),!y?.[G.id]&&G.kind!=="fx"&&t.jsx("div",{className:`shot-dur-bar kind-${G.kind}${G.hidden||G.locked?" dim":""}`,"data-dur":G.id,title:G.kind==="camera"?o("Camera chạy suốt shot: 0s → {0}s",[M.duration]):o("Có mặt suốt shot: 0s → {0}s",[M.duration]),style:{left:"0%",width:"100%"}}),G.keys.map((le,$e)=>t.jsx("button",{"aria-label":`Key ${$e+1} ${G.name}`,title:o("{0}s · kéo để đổi thời điểm",[(le.time*M.duration).toFixed(2)]),disabled:G.locked,"data-row":G.id,"data-key":le.id,className:`shot-time-key ${"pose"in le&&le.pose?"pose":""} ${L?.row===G.id&&L.id===le.id||Ie(G.id,le.id)?"active":""}`,style:{left:`${(be?.id===le.id&&be.row===G.id?be.time:le.time)*100}%`},onClick:Le=>{Le.detail===0&&P(G.id,le.id)},onMouseDown:Le=>{if(Le.shiftKey||Le.metaKey||Le.ctrlKey){Le.preventDefault(),Le.stopPropagation();const Te=Ie(G.id,le.id),Je=N.length?N:L?[L]:[];A?.(Te?Je.filter(ke=>!(ke.row===G.id&&ke.id===le.id)):[...Je,{row:G.id,id:le.id}]);return}ot(Le,G.id,le.id,Le.currentTarget.parentElement)},children:"◆"},le.id))]})]}),Se.map(le=>{const $e=Z0(M,G.id);return t.jsxs("div",{className:"shot-time-row shot-prop-row","data-prop":`${G.id}:${le.id}`,children:[t.jsxs("div",{className:"shot-track-name",children:[t.jsx("span",{className:`shot-stopwatch${$e?" keyed":""}`,role:"img","aria-label":$e?o("Đã có key"):o("Chưa có key"),title:$e?o("Thuộc tính đã có key: sửa số sẽ ghi key tại playhead"):o("Chưa có key: sửa số đổi giá trị cố định"),children:"⏱"}),t.jsxs("label",{className:"shot-prop-label",children:[o(le.label),t.jsx(gn,{"aria-label":`${o(le.label)} · ${G.name}`,className:"shot-prop-number",step:le.step,min:le.min,max:le.max,precision:3,disabled:G.locked,value:J0(p,G.id,le.id,I),onCommit:Le=>C?.(G.id,le.id,Le)})]}),t.jsx("button",{className:"shot-prop-add","aria-label":`${o("Thêm key")} ${o(le.label)} · ${G.name}`,title:o("Thêm key tại playhead"),disabled:G.locked,onClick:()=>W(G.id),children:"◆"})]}),t.jsxs("div",{className:"shot-key-track shot-prop-track",onPointerDown:Le=>{G.locked||ze(Le,G.id,Le.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),G.keys.map(Le=>t.jsx("i",{"data-row":G.locked?void 0:G.id,"data-key":G.locked?void 0:Le.id,className:`shot-prop-key${Ie(G.id,Le.id)||L?.row===G.id&&L.id===Le.id?" active":""}`,style:{left:`${Le.time*100}%`}},Le.id))]})]},le.id)})]},G.id)})]})})]})}let Zn=null;function Sx(){return Zn||(Zn=new Pr(ig()),Zn.colorSpace=ld,Zn.anisotropy=4,Zn.generateMipmaps=!0,Zn.minFilter=cd,Zn)}const Lc=new Map;function Cx(e){let n=Lc.get(e);return n||(n=new Pr(og(e)),n.colorSpace=ld,n.anisotropy=8,n.generateMipmaps=!0,n.minFilter=cd,Lc.set(e,n)),n}let _n=null;function Nx(){if(_n)return _n;const e=128,n=new Uint8Array(e*e*4),s=r=>{const l=new Float32Array(r*r);let c=1013904223+r;for(let u=0;u<l.length;u++)c=Math.imul(c,1664525)+1013904223>>>0,l[u]=c/4294967296;return l},a=[4,8,16,32].map(r=>({g:r,v:s(r)})),i=r=>r*r*(3-2*r);for(let r=0;r<e;r++)for(let l=0;l<e;l++){let c=0,u=.5,m=0;for(const{g:p,v:x}of a){const g=l/e*p,v=r/e*p,w=Math.floor(g),C=Math.floor(v),M=i(g-w),S=i(v-C),I=(T,j)=>x[j%p*p+T%p],y=I(w,C)+(I(w+1,C)-I(w,C))*M,k=I(w,C+1)+(I(w+1,C+1)-I(w,C+1))*M;c+=(y+(k-y)*S)*u,m+=u,u*=.5}const d=(r*e+l)*4,f=Math.round(c/m*255);n[d]=n[d+1]=n[d+2]=f,n[d+3]=255}return _n=new E0(n,e,e,I0),_n.wrapS=_n.wrapT=rd,_n.magFilter=ac,_n.minFilter=ac,_n.needsUpdate=!0,_n}const Ax=Symbol.for("clipoox.shot.fxSoftDepth"),Tx=e=>e[Ax]??null,Dr={uOcclude:{value:0}},Ec={day:.22,golden:.16,overcast:.2,night:.03},Ia={blade:.78,width:.034,thick:.0075,grip:.19};function Ic(e,n){return[[-e,0],[-e*.62,n*.82],[-e*.26,n],[-e*.15,n*.38],[e*.15,n*.38],[e*.26,n],[e*.62,n*.82],[e,0],[e*.62,-n*.82],[e*.26,-n],[e*.15,-n*.38],[-e*.15,-n*.38],[-e*.26,-n],[-e*.62,-n*.82]]}function Rc(e=0){const{blade:n,width:s,thick:a}=Ia,i=[[0,.86,1],[.06,1,1],[.7,.96,.9],[.84,.74,.72],[.94,.4,.5],[1,.02,.15]],r=Ic(1,1).length,l=[],c=[];i.forEach(([m,d,f])=>{for(const[p,x]of Ic(s*d+e,a*f+e*.5))l.push(p,m*n,x)});for(let m=0;m<i.length-1;m++)for(let d=0;d<r;d++){const f=m*r+d,p=m*r+(d+1)%r,x=(m+1)*r+d,g=(m+1)*r+(d+1)%r;c.push(f,x,p,p,x,g)}const u=new Ct;return u.setAttribute("position",new Ot(l,3)),u.setIndex(c),u.computeVertexNormals(),u}function Lx(){const e=[],n=new hd(.0105,.15,4,10);n.rotateZ(Math.PI/2),n.scale(1,1,1.5),e.push(n);for(const i of[-1,1]){const r=new R0(.0125,.03,10);r.rotateZ(-i*Math.PI/2),r.translate(i*.086,.012,0),e.push(r)}const s=new hs(.016,.02,.026,14);s.translate(0,-.016,0),e.push(s);const a=Cd(e);return e.forEach(i=>i.dispose()),a}function Ex(){const e=[],n=new hs(.0125,.0125,Ia.grip,12);n.translate(0,-.03-Ia.grip/2,0),e.push(n);for(let i=0;i<5;i++){const r=new Or(.0132,.0028,6,14);r.rotateX(Math.PI/2),r.translate(0,-.05-i*.034,0),e.push(r)}const s=new Rn(.0235,14,10);s.translate(0,-.03-Ia.grip-.012,0),e.push(s);const a=Cd(e);return e.forEach(i=>i.dispose()),a}function Cd(e){const n=[],s=[],a=[],i=[];let r=0;for(const c of e){const u=c.getAttribute("position"),m=c.getAttribute("normal"),d=c.getAttribute("uv");for(let f=0;f<u.count;f++)n.push(u.getX(f),u.getY(f),u.getZ(f)),s.push(m.getX(f),m.getY(f),m.getZ(f)),a.push(d?d.getX(f):0,d?d.getY(f):0);if(c.index)for(let f=0;f<c.index.count;f++)i.push(r+c.index.getX(f));else for(let f=0;f<u.count;f++)i.push(r+f);r+=u.count}const l=new Ct;return l.setAttribute("position",new Ot(n,3)),l.setAttribute("normal",new Ot(s,3)),l.setAttribute("uv",new Ot(a,2)),l.setIndex(i),l}const Ix=`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/productTools-B1h5cgyt.js","assets/titleFrameBudget-Cml-MO53.js","assets/remote-BJdzzFZg.js","assets/api-QBI5GJTZ.js","assets/three.module-Bx43vjkH.js","assets/GLTFLoader-BHWu1lKg.js","assets/store-2zneEhhu.js","assets/rotoMaskStore-DIi45swK.js","assets/textAnimators-Bdt5LWXk.js","assets/timelineComp-B73i_8vD.js","assets/rigTrack-CUt4O67J.js","assets/exportGlb-CLfTnbMG.js","assets/plateFollow-B9_QTgvo.js","assets/plateCamera-C96L5GKm.js","assets/plateMatte-BiqyI_8x.js","assets/rotoMatte-013RKqHu.js","assets/videoExport-z5WjM0hw.js","assets/motionBlur-uAm030t9.js","assets/id3-BCR9Bqgo.js","assets/output-BwZzMbp-.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as Wn}from"./titleFrameBudget-Cml-MO53.js";import{ds as _a,dt as st,du as Ws,dv as as,dw as om,dx as Rh,dy as Fh,dz as is,dA as bt,dB as In,b as fn,dC as Ph,dD as im,dE as Cl,dF as wr,dG as Dt,dH as $h,dI as rm,dJ as ja,dK as Wo,dL as lm,dM as Oh,dN as cm,j as t,dO as hm,dP as Lo,dQ as dm,dR as um,dS as mm,dT as Dh,dU as pm,dV as fm,dW as $a,dX as zh,dY as ka,dZ as gm,d_ as Nl,d$ as xm,e0 as bm,e1 as hi,e2 as Es,e3 as Oa,e4 as qs,e5 as zs,e6 as Al,e7 as Tl,e8 as Ll,e9 as _h,ea as ym,eb as wa,ec as rn,I as Ce,N as gn,cX as Is,ed as di,ee as El,ef as Il,eg as vm,eh as Rl,ei as Mn,ej as jm,ek as km,el as wm,em as Eo,en as Mm,eo as Bh,ep as Da,eq as Fl,er as Sm,es as ko,et as Kh,eu as Cm,ev as Nm,ew as Am,ex as Tm,ey as Lm,ez as Em,eA as Io,eB as Im,eC as Rm,eD as Gi,eE as ln,eF as Ui,eG as Xi,eH as Fm,eI as Pl,eJ as Pm,eK as $m,eL as Om,eM as Dm,eN as Un,eO as Mr,eP as zm,eQ as $l,eR as qo,eS as Hh,eT as za,eU as _m,eV as Wh,eW as qh,eX as ui,eY as Fn,eZ as Gs,e_ as Bm,e$ as Gh,f0 as mi,f1 as Rs,f2 as Km,f3 as Hm,f4 as Uh,f5 as Sr,f6 as Wm,f7 as qm,f8 as Cr,f9 as Ol,fa as Gm,fb as Um,Q as Xm,fc as Vm,dr as Ym,fd as Qm,fe as Zm,ff as Jm,fg as ep,fh as tp,fi as Nr,fj as Xh,fk as np,fl as Za,fm as sp,fn as ap,fo as op,fp as ip,fq as rp,fr as lp,fs as cp,ft as hp,fu as dp,fv as Dl,fw as zl,fx as pi,fy as up,fz as mp,fA as pp,fB as Vh,fC as Yh,fD as Qh,fE as Ro,fF as _l,fG as Ar,fH as fp,fI as gp,fJ as xp,fK as Bl,fL as bp,fM as Tn,fN as yp,fO as vp,fP as Kl,fQ as oa,fR as bs,fS as jp,fT as kp,fU as wp,fV as Mp,fW as ks,fX as Sp,fY as Cp,fZ as Np,f_ as Ap,f$ as Tp,g0 as Zh,g1 as Fo,g2 as Lp,g3 as Hl,g4 as Ep,g5 as fi,g6 as Wl,g7 as gi,g8 as Ip,g9 as Po,ga as Rp,gb as Fp,gc as Pp,gd as ns,ge as $o,r as Jh,gf as $p,gg as Op,gh as Dp,gi as ql,gj as zp,gk as _p,gl as Tr,gm as Lr,gn as Ma,go as Bp,gp as Kp,gq as Hp,gr as Ja,gs as xi,gt as Vi,gu as ed,gv as Wp,gw as bi,gx as qp,gy as Gp,gz as Up,gA as Xp,gB as td,gC as nd,a as Pt,gD as Vp,am as Yp,gE as Qp,gF as Zp,gG as Jp,gH as ef,cU as tf,dk as nf,dl as sf,gI as af,gJ as of,gK as Yi,gL as rf,gM as lf,gN as cf,gO as hf,gP as df,gQ as Gl,gR as Qi,gS as Aa,gT as uf,gU as Ta,gV as wo,n as mf,gW as pf,u as yi,gX as Ul,gY as ff,gZ as gf,dm as Xl,g_ as xf,g$ as Vl,h0 as bf,h1 as yf,h2 as vf,h3 as jf,h4 as vi,q as kf,h5 as wf,h6 as Mf,h7 as Sf,h8 as ji,h9 as Cf,ha as Nf,hb as Af,hc as Tf,hd as Lf,he as Ef,hf as If,hg as Rf,hh as ki,hi as Ff,hj as Yl,hk as wi,hl as Ql,hm as Zl,hn as Mi,ho as Pf,hp as $f,hq as Of,hr as Df,hs as Si,ht as zf,hu as _f,hv as Bf,hw as Kf,hx as Hf,hy as Wf,hz as qf,hA as Gf,hB as Uf,hC as Xf,hD as Vf,hE as Yf,hF as Qf,hG as Zf,hH as Jf,hI as e0,hJ as t0,hK as n0,hL as s0,hM as a0,hN as o0,hO as i0,hP as r0,hQ as l0,hR as c0,hS as h0,hT as Jl,hU as d0,hV as u0,hW as ec,hX as tc,hY as m0}from"./remote-BJdzzFZg.js";import{u as ht,r as R,t as o,bE as p0,c as _s,bF as nc,h as Ys,bG as f0,bH as g0,bI as x0,bJ as b0,bK as y0,bL as v0,bM as j0,bN as k0,bO as w0,bP as M0,az as S0,bQ as C0,bR as sc,a6 as N0,s as A0}from"./api-QBI5GJTZ.js";import{Mesh as ut,SkinnedMesh as Er,Box3 as $t,Vector3 as ie,Matrix4 as St,Group as tn,Uint16BufferAttribute as sd,Float32BufferAttribute as Ot,BufferGeometry as Ct,BufferAttribute as Nt,MathUtils as Ln,DirectionalLight as Go,WebGLRenderer as Ir,SRGBColorSpace as Uo,AgXToneMapping as ad,PCFSoftShadowMap as T0,Scene as Rr,PMREMGenerator as od,HemisphereLight as id,PlaneGeometry as Xo,ShadowMaterial as L0,PerspectiveCamera as Fr,InstancedMesh as Bs,DataTexture as E0,RGBAFormat as I0,RepeatWrapping as rd,LinearFilter as ac,CanvasTexture as Pr,NoColorSpace as ld,LinearMipmapLinearFilter as cd,InstancedBufferAttribute as Zi,DynamicDrawUsage as Qs,MeshStandardMaterial as Gn,ShaderMaterial as Ba,Color as Qe,DoubleSide as cs,AdditiveBlending as $r,LinearSRGBColorSpace as rs,CapsuleGeometry as hd,ConeGeometry as R0,CylinderGeometry as hs,TorusGeometry as Or,SphereGeometry as Rn,BoxGeometry as Ka,MeshPhysicalMaterial as Cs,Vector2 as ta,LatheGeometry as dd,FrontSide as Ha,Quaternion as tt,Vector4 as ws,InstancedInterleavedBuffer as ud,InterleavedBufferAttribute as kn,InstancedBufferGeometry as F0,OneMinusSrcAlphaFactor as P0,OneFactor as $0,AddEquation as O0,CustomBlending as D0,NormalBlending as z0,DetachedBindMode as _0,OctahedronGeometry as Ji,MeshBasicMaterial as os,Line as Ci,LineBasicMaterial as oc,PointLight as B0,Euler as er,Bone as La,Uint8BufferAttribute as ls,ShaderChunk as K0,Sphere as H0,LOD as W0,Skeleton as Ni,Object3D as q0,NearestFilter as G0,ACESFilmicToneMapping as U0,CircleGeometry as X0,Raycaster as ic}from"./three.module-Bx43vjkH.js";import{R as md}from"./RoomEnvironment-Dmv_G5ka.js";import{i as rc,p as lc,g as V0,e as Y0}from"./tool-Bt9bclIf.js";import{rowProps as Q0,rowKeyed as Z0,readProp as J0,writeProp as eg,keyAllAt as tg,copyKeys as ng,pasteKeys as sg,easeKeys as ag,nudgeKeys as cc}from"./timelineProps-B2pnudeT.js";import{b as og,c as ig,A as rg,d as hc,a as lg,t as cg}from"./thumb-byAKvhQP.js";import{f as hg,p as dg}from"./shotFxAgent-BDfe73TP.js";import{c as pd,G as ug}from"./GLTFLoader-BHWu1lKg.js";import{p as mg,C as pg,a as fg,b as gg,c as dc}from"./cameraPresets-4pFeF2YG.js";import{F as xg}from"./rigTrack-CUt4O67J.js";import{D as bg,s as yg}from"./weaponDuel-CLLgv5A4.js";import{u as dt}from"./store-2zneEhhu.js";import{r as uc,a as vg,b as jg,o as kg,w as wg,c as Mg,d as Sg,e as Ai,f as Cg,g as Ng,p as Ag,h as Tg}from"./skin-GDY3QPkV.js";import{renderRigViews as Lg}from"./views-CsrYzCSR.js";import{M as ia}from"./motionBlur-uAm030t9.js";import{fitLibraryFingers as mc}from"./library-Dsz_MLyd.js";import"./rotoMaskStore-DIi45swK.js";import"./textAnimators-Bdt5LWXk.js";import"./timelineComp-B73i_8vD.js";function Eg(e,n,s){const a=[e[0]*n[0]+e[4]*n[1]+e[8]*n[2]+e[12],e[1]*n[0]+e[5]*n[1]+e[9]*n[2]+e[13],e[2]*n[0]+e[6]*n[1]+e[10]*n[2]+e[14]],i=[0,1,2].map(r=>Math.abs(e[r]*s[0])+Math.abs(e[4+r]*s[1])+Math.abs(e[8+r]*s[2]));return{c:a,h:i,min:a.map((r,l)=>r-i[l]),max:a.map((r,l)=>r+i[l])}}function Ig(e,{cell:n=1}={}){const s=e.length,a=Array.from({length:s},()=>[]),i=Array.from({length:s},()=>[]),r=e.reduce((C,M)=>Math.min(C,M.min[1]),1/0),l=e.reduce((C,M)=>Math.max(C,M.max[1]),-1/0),c=Math.max(.03,n*.2),u=Math.max(.02,n*.06),m=e.map(C=>C.min[1]<=r+c);for(let C=0;C<s;C++){const M=e[C],S=(M.min[1]+M.max[1])/2,I=(M.max[1]-M.min[1])/2;for(let y=C+1;y<s;y++){const k=e[y],T=[0,1,2].map(A=>Math.min(M.max[A],k.max[A])-Math.max(M.min[A],k.min[A]));if(T[0]<-u||T[2]<-u||T[1]<-c)continue;const j=(k.min[1]+k.max[1])/2,L=(k.max[1]-k.min[1])/2,N=j-S;if(Math.abs(N)>.3*(I+L)){const A=N>0?k:M,O=_=>T[_]/Math.max(.001,A.max[_]-A.min[_]);if(O(0)<.45||O(2)<.45)continue;N>0?a[C].push(y):a[y].push(C)}else i[C].push(y),i[y].push(C)}}const d=new Uint8Array(s).fill(1);let f=tr({ups:a,side:i,ground:m},d,null);const p=Math.max(.05,n*.25);for(let C=0;C<3;C++){let M=!1;for(let S=0;S<s;S++){if(Number.isFinite(f[S]))continue;const I=e[S],y=(I.min[1]+I.max[1])/2,k=(I.max[1]-I.min[1])/2;for(let T=0;T<s;T++){if(T===S||i[S].includes(T)||a[S].includes(T)||a[T].includes(S))continue;const j=e[T];if(![0,1,2].every(A=>Math.min(I.max[A],j.max[A])-Math.max(I.min[A],j.min[A])>=-p))continue;const L=(j.min[1]+j.max[1])/2-y,N=(j.max[1]-j.min[1])/2;Math.abs(L)>.3*(k+N)?L>0?a[S].push(T):a[T].push(S):(i[S].push(T),i[T].push(S)),M=!0}}if(!M)break;f=tr({ups:a,side:i,ground:m},d,null)}const x=e.map(C=>[C.min[0],C.max[0],C.min[2],C.max[2]]),g=e.map(C=>[(C.min[0]+C.max[0])/2,(C.min[2]+C.max[2])/2]),v={n:s,ups:a,side:i,ground:m,need0:f,base:r,top:l,foot:x,plan:g,cell:n,tops:e.map(C=>C.max[1]),slender0:0},w=[...Array(s).keys()].filter(C=>Number.isFinite(f[C]));return v.slender0=w.length?xd(v,w):0,v.stable0=Fg(v,d,0),v}function Rg(e,n){if(!e.adj){e.adj=Array.from({length:e.n},(s,a)=>[...e.ups[a],...e.side[a]]);for(let s=0;s<e.n;s++)for(const a of e.ups[s])e.adj[a].push(s)}return e.adj[n]}function fd(e,n){const s=new Int32Array(e.n).fill(-1),a=[];for(let i=0;i<e.n;i++){if(!n[i]||s[i]>=0)continue;const r=[i];s[i]=a.length;for(let l=0;l<r.length;l++)for(const c of Rg(e,r[l]))n[c]&&s[c]<0&&(s[c]=a.length,r.push(c));a.push(r)}return a}function gd(e,n){let s=1/0,a=-1/0,i=1/0,r=-1/0,l=0;for(const c of n){if(!e.ground[c])continue;l++;const u=e.foot[c];s=Math.min(s,u[0]),a=Math.max(a,u[1]),i=Math.min(i,u[2]),r=Math.max(r,u[3])}return{x0:s,x1:a,z0:i,z1:r,ng:l}}function xd(e,n){const s=gd(e,n),a=(e.cell??1)*.25;return s.ng?(n.reduce((r,l)=>Math.max(r,e.tops[l]),-1/0)-e.base)/Math.max(.001,Math.min(s.x1-s.x0,s.z1-s.z0)+2*a):0}function bd(e,n,s,a){const i=gd(e,n),r=i.ng;if(!r||n.length-r<2)return!0;let l=0,c=0;for(const m of n)l+=e.plan[m][0],c+=e.plan[m][1];l/=n.length,c/=n.length;const u=(e.cell??1)*.5*(1+s);return l<i.x0-u||l>i.x1+u||c<i.z0-u||c>i.z1+u||e.tops&&xd(e,n)>Math.max(4,2*(e.slender0??0))*(1+.25*s)?!1:r/n.length>=a*(.3/(1+s))}function yd(e){let n=0,s=0;for(let a=0;a<e.n;a++)Number.isFinite(e.need0[a])&&(s++,e.ground[a]&&n++);return s?n/s:0}function Fg(e,n,s){const a=yd(e);return fd(e,n).every(i=>bd(e,i,s,a))}function tr(e,n,s){const a=n.length,i=new Float64Array(a).fill(1/0),r=[];for(let l=0;l<a;l++)n[l]&&e.ground[l]&&(i[l]=0,r.push(l));for(let l=0;l<r.length;l++){const c=r[l],u=i[c],m=u+1;for(const d of e.ups[c])n[d]&&i[d]>0&&(i[d]=0,r.push(d));for(const d of e.side[c])n[d]&&i[d]>m&&(!s||m<=s[d])&&(i[d]=m,r.push(d))}return i}const Pg=e=>e>=.8?0:e>=.4?1:2;function $g(e,n,{slack:s=0,seed:a=1,centres:i}={}){const r=e.n,l=new Array(r).fill(null),c=new Uint8Array(r).fill(1);if(!r)return l;const u=Float64Array.from(e.need0,v=>v+s),m=Math.max(.1,e.top-e.base),d=_a(a|0,7717,5),f=[],p=e.stable0!==!1&&!!e.foot,x=p?yd(e):0;for(let v=0;v<r;v++)Number.isFinite(n[v])&&f.push({t:n[v],i:v});f.sort((v,w)=>v.t-w.t||v.i-w.i);let g=0;for(;g<f.length;){const v=f[g].t,w=[];for(;g<f.length&&f[g].t<=v+1e-9;){const S=f[g++];c[S.i]&&(c[S.i]=0,w.push(S.i))}if(!w.length)continue;const C=tr(e,c,u),M=i?st.mul(w.reduce((S,I)=>st.add(S,i[I]),[0,0,0]),1/w.length):null;for(let S=0;S<r;S++){if(!c[S]||!Number.isFinite(e.need0[S])||C[S]<=u[S])continue;c[S]=0;const I=i?Ws((i[S][1]-e.base)/m):.5,y=v+.05+.13*I+.07*as(d,S,1);l[S]={t:y,from:M}}if(p){for(const S of fd(e,c))if(!bd(e,S,s,x))for(const I of S){if(e.ground[I])continue;c[I]=0;const y=i?Ws((i[I][1]-e.base)/m):.5;l[I]={t:v+.08+.15*y+.07*as(d,I,1),from:M}}}}return l}function Og(e,n,{base:s=0,cell:a=1}={}){const i=Math.max(.05,a*.25),r=new Map,l=(d,f)=>`${d},${f}`,c=(d,f,p,x,g)=>{const v=[];for(let w=Math.floor((d-p*g)/i);w<=Math.floor((d+p*g)/i);w++)for(let C=Math.floor((f-x*g)/i);C<=Math.floor((f+x*g)/i);C++)v.push(l(w,C));return v};for(const d of n)for(const f of c(d.x,d.z,d.hx,d.hz,.85))r.set(f,Math.max(r.get(f)??s,d.y1));const u=new Map,m=Math.max(.1,a*.5);for(const d of[...e].sort((f,p)=>f.t-p.t||f.i-p.i)){const f=d.hy*.8;let p=null;for(const x of d.dirs??[[1,0,0]])for(let g=0;g<=8;g++){const v=d.x+x[0]*m*g,w=d.z+x[2]*m*g,C=c(v,w,d.hx,d.hz,.6),M=C.reduce((I,y)=>Math.max(I,r.get(y)??s),s),S=M+.45*m*g;(!p||S<p.score-1e-9)&&(p={x:v,z:w,y:Math.min(d.top,M+f),foot:C,score:S})}u.set(d.i,{x:p.x,z:p.z,y:p.y});for(const x of p.foot)r.set(x,Math.max(r.get(x)??s,p.y+f*.9))}return u}function Dg(e,n,s,{gravity:a=9.8,seed:i=1,crumble:r=.6}={}){if(!e||!(s>=e.t))return null;const l=s-e.t,c=Math.max(.5,a),u=Math.max(0,e.p0[1]-e.land),m=Math.sqrt(2*u/c),d=Math.min(l,m),f=m>1e-6?d/m:1,p=om(u,0,c,l,.12),x=l>m?(1-Math.exp(-3*(l-m)))/3:0,g=e.p0[0]+(e.to[0]-e.p0[0])*f+e.dir[0]*.4*x,v=e.p0[2]+(e.to[1]-e.p0[2])*f+e.dir[2]*.4*x,w=_a(i|0,n,4441),C=(.25+.9*as(w,1,1))*(.4+.6*r),M=st.norm([e.dir[2]+(as(w,2,1)-.5)*.3,0,-e.dir[0]+(as(w,3,1)-.5)*.3]),S=C*Rh(0,1,f)+(l>m?.15*C*x:0);return{pos:[g,e.land+p.y,v],axis:Number.isFinite(M[0])?M:[1,0,0],angle:S,landed:l>=m}}function zg(e,n,s,{base:a=0,cell:i=1,seed:r=1,centre:l=null}={}){const c=_a(r|0,3301,7),u=[],m=n.map((f,p)=>{if(!f)return null;const x=e[p],g=f.from??x.c,v=[g[0]-x.c[0],0,g[2]-x.c[2]],w=Math.hypot(v[0],v[2]),C=as(c,p,1)*Math.PI*2,M=(as(c,p,2)-.5)*.9,S=w>1e-4?st.norm([v[0]/w+Math.cos(C)*.25,0,v[2]/w+Math.sin(C)*.25]):[Math.cos(C),0,Math.sin(C)],I=l?[x.c[0]-l[0],0,x.c[2]-l[2]]:[Math.cos(C+1),0,Math.sin(C+1)],y=Math.hypot(I[0],I[2]),k=y>1e-4?[I[0]/y,0,I[2]/y]:[Math.cos(C+1),0,Math.sin(C+1)],T=(j,L)=>[j[0]*Math.cos(L)-j[2]*Math.sin(L),0,j[0]*Math.sin(L)+j[2]*Math.cos(L)];return u.push({i:p,t:f.t,x:x.c[0],z:x.c[2],hx:x.h[0],hz:x.h[2],hy:Math.min(x.h[1],Math.max(x.h[0],x.h[2])*1.2),top:x.c[1],dirs:[S,T(k,M),T(k,M+.8),T(k,M-.8)]}),{t:f.t,p0:[...x.c],dir:S,to:[x.c[0],x.c[2]],land:a,by:"fall"}}),d=s.map(f=>({x:e[f].c[0],z:e[f].c[2],hx:e[f].h[0],hz:e[f].h[2],y1:e[f].c[1]+e[f].h[1]}));for(const[f,p]of Og(u,d,{base:a,cell:i}))m[f]&&(m[f].land=p.y,m[f].to=[p.x,p.z]);return m}function _g(e,{mode:n="pancake",start:s=0,duration:a=4,yaw:i=0,crumble:r=.6,seed:l=1,cell:c=1,gone:u=null,gravity:m=9.8}={}){const d=e.reduce((j,L)=>Math.min(j,L.min[1]),1/0),f=e.reduce((j,L)=>Math.max(j,L.max[1]),-1/0),p=Math.max(.3,a),x=Math.max(.1,f-d),g=.17+.13*(1-r),v=[0,2].map(j=>e.reduce((L,N)=>Math.min(L,N.min[j]),1/0)),w=[0,2].map(j=>e.reduce((L,N)=>Math.max(L,N.max[j]),-1/0)),C=[(v[0]+w[0])/2,d,(v[1]+w[1])/2],M=i*Math.PI/180,S=[Math.sin(M),0,Math.cos(M)],I=e.reduce((j,L)=>Math.max(j,...[0,1].flatMap(N=>[0,1].map(A=>(N?L.max[0]:L.min[0])*S[0]+(A?L.max[2]:L.min[2])*S[2]))),-1/0)-(C[0]*S[0]+C[2]*S[2]),y=[C[0]+S[0]*I,d,C[2]+S[2]*I],k=[S[2],0,-S[0]],T={mode:Kg.has(n)?n:"pancake",t0:s,D:p,base:d,top:f,H:x,c:g,centre:C,pivot:y,dir:S,axis:k,ext:I,seed:l|0,crumble:r,cell:c};if(T.mode==="pancake"){const j=.008333333333333333,L=Math.max(.5,m),N=Math.max(.3,c),A=Math.max(.3,c*1.5),O=e.map(P=>`${Math.floor(P.c[0]/A)},${Math.floor(P.c[2]/A)}`),_=new Map;e.forEach((P,W)=>{const z=O[W];_.has(z)||_.set(z,[]),_.get(z).push(W)});const $=new Map;for(const[P,W]of _){const z=[f];let Q=f,J=0;for(let V=1;Q>d&&V<7200;V++){const B=s+V*j,q=Ws((B-s)/p),D=x*1.6*Math.pow(Math.max(q,.02),.6)/p;J=W.some(Z=>e[Z].c[1]<=Q&&e[Z].c[1]>=Q-N&&!(u&&u[Z]<=B))?Math.max(D,J+L*.6*j):J+L*j,Q=Math.max(d,Q-J*j),z.push(Q)}$.set(P,z)}T.fronts=$,T.colOf=O,T.dt=j,T.starts=e.map((P,W)=>{const z=$.get(O[W]),Q=z.findIndex(J=>J<P.c[1]);return s+(Q<0?z.length:Q)*j})}else T.starts=e.map(()=>s);return T}const Bg=(e,n,s)=>{const a=e.fronts.get(e.colOf[n]),i=(s-e.t0)/e.dt;if(i<=0)return e.top;const r=Math.floor(i);return r>=a.length-1?a[a.length-1]:a[r]+(a[r+1]-a[r])*(i-r)},Kg=new Set(["pancake","topple","base"]),Hg=(e,n,s)=>{const a=Math.cos(s),i=Math.sin(s),r=st.dot(n,e),l=st.cross(n,e);return[e[0]*a+l[0]*i+n[0]*r*(1-a),e[1]*a+l[1]*i+n[1]*r*(1-a),e[2]*a+l[2]*i+n[2]*r*(1-a)]};function pc(e,n,s,a){if(!e||!(a>=e.starts[s]))return null;const i=_a(e.seed,s,6067),r=g=>as(i,g,1),l=Ws((a-e.t0)/e.D),c=e.crumble,u=e.base+Math.min(n.h[1],Math.max(n.h[0],n.h[2]))*.55,m=st.norm([n.c[0]-e.centre[0]+(r(1)-.5)*.6,0,n.c[2]-e.centre[2]+(r(2)-.5)*.6]),d=st.norm([r(3)-.5,(r(4)-.5)*.4,r(5)-.5]);if(e.mode==="topple"){const g=Math.PI/2*l*l,v=st.sub(n.c,e.pivot),w=st.add(e.pivot,Hg(v,e.axis,g)),C=Math.max(0,a-(e.t0+e.D)),M=(1-Math.exp(-2.5*C))/2.5,S=Rh(.55,1,l),I=c*e.cell*(.4+1.2*r(6)),y=st.add(st.mul(e.dir,(.8+2.2*r(7))*c*M*2),st.mul(m,I*S*.5+c*M*r(8))),k=st.add(w,y);return k[1]=Math.max(u,k[1]),{pos:k,axis:e.axis,angle:g,extra:{axis:d,angle:c*(S*.6+M*2)*(.3+r(9))}}}let f,p;if(e.mode==="base"){const g=e.base+e.H*Math.pow(l,1.3),v=n.c[1];v>=g?(f=v-(g-e.base)*(1-e.c),p=0):(f=e.base+(v-e.base)*e.c,p=Ws((g-v)/Math.max(.2,e.cell*2)))}else{const g=Bg(e,s,a),v=n.c[1];f=g>=v?v:g+(v-g)*e.c;const w=e.base+(v-e.base)*e.c;p=v-w>1e-6?Ws((v-f)/(v-w)):1}f=Math.max(u,f);const x=(.15+1.1*c)*e.cell*(.5+r(10))*p;return{pos:[n.c[0]+m[0]*x,f,n.c[2]+m[2]*x],axis:d,angle:p*(.15+1.1*c)*(.3+r(11))}}function Wg(e,{blasts:n=[],collapses:s=[],falls:a=[]}={}){const i=new Array(e).fill(null),r=(l,c)=>{(!i[l]||c.t<i[l].t-1e-9||Math.abs(c.t-i[l].t)<=1e-9&&fc[c.kind]<fc[i[l].kind])&&(i[l]=c)};for(const l of n)for(let c=0;c<e;c++){const u=l.hits[c];u&&r(c,{kind:"hit",e:l.e,t:u.t})}for(let l=0;l<e;l++)a[l]&&r(l,{kind:"fall",e:-1,t:a[l].t});for(const l of s)for(let c=0;c<e;c++)r(c,{kind:"collapse",e:l.e,t:l.plan.starts[c]});return i}const fc={hit:0,fall:1,collapse:2};function qg(e,n){const s=new Float64Array(e).fill(1/0);for(const a of n)for(let i=0;i<e;i++){const r=a.hits[i];r&&r.t<s[i]&&(s[i]=r.t)}return s}function Gg(e){const n=Math.floor(e.length/3);if(n<4)return null;const s=y=>[e[y*3],e[y*3+1],e[y*3+2]];let a=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let y=0;y<n;y++)for(let k=0;k<3;k++)a[k]=Math.min(a[k],e[y*3+k]),i[k]=Math.max(i[k],e[y*3+k]);const r=Math.max(1e-9,...i.map((y,k)=>y-a[k])),l=r*1e-7;let c=0;for(let y=1;y<n;y++)e[y*3]<e[c*3]&&(c=y);let u=-1,m=0;for(let y=0;y<n;y++){const k=st.dist(s(y),s(c));k>m+l&&(m=k,u=y)}if(u<0)return null;let d=-1,f=0;const p=st.sub(s(u),s(c));for(let y=0;y<n;y++){const k=st.len(st.cross(p,st.sub(s(y),s(c))));k>f+l*r&&(f=k,d=y)}if(d<0)return null;const x=st.cross(p,st.sub(s(d),s(c)));let g=-1,v=0;for(let y=0;y<n;y++){const k=Math.abs(st.dot(x,st.sub(s(y),s(c))));k>v+l*r*r&&(v=k,g=y)}if(g<0||v<l*r*r*10)return null;const w=[],C=(y,k,T)=>{const j=st.cross(st.sub(s(k),s(y)),st.sub(s(T),s(y))),L=st.len(j)||1,N=st.mul(j,1/L);return{v:[y,k,T],n:N,d:st.dot(N,s(y)),alive:!0}},M=st.mul(st.add(st.add(s(c),s(u)),st.add(s(d),s(g))),.25);for(const[y,k,T]of[[c,u,d],[c,u,g],[c,d,g],[u,d,g]]){let j=C(y,k,T);st.dot(j.n,M)-j.d>0&&(j=C(y,T,k)),w.push(j)}const S=new Set([c,u,d,g]);for(let y=0;y<n;y++){if(S.has(y))continue;const k=s(y),T=[];for(const L of w)L.alive&&st.dot(L.n,k)-L.d>l&&T.push(L);if(!T.length)continue;const j=new Map;for(const L of T){L.alive=!1;for(let N=0;N<3;N++){const A=L.v[N],O=L.v[(N+1)%3],_=`${O},${A}`;j.has(_)?j.delete(_):j.set(`${A},${O}`,[A,O])}}for(const[L,N]of j.values())w.push(C(L,N,y))}const I=[];for(const y of w)y.alive&&I.push(...y.v);return I.length?I:null}function Ug(e,n,s,a=48){const i=Math.floor(e.length/3),r=Math.max(1,Math.ceil(i/a)),l=[],c=st.norm(n),u=st.len(n)>1e-6?s:0;for(let m=0;m<i;m+=r){const d=[e[m*3],e[m*3+1],e[m*3+2]];l.push(...d,d[0]+c[0]*u,d[1]+c[1]*u,d[2]+c[2]*u)}return l}const Fs=e=>Array.isArray(e)&&e.length===3&&e.every(n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=1e6),un=e=>{throw new Error(e)};function Xg(e,n){(!e||typeof e.message!="string"||e.message.length>4e3||!Array.isArray(e.tracks)||e.tracks.length>100||e.additions!=null&&(!Array.isArray(e.additions)||e.additions.length>1))&&un("Đề xuất AI không hợp lệ."),(!Number.isFinite(e.duration)||e.duration<n.duration||e.duration>1e7)&&un("Thời lượng đề xuất không hợp lệ.");for(const a of e.additions||[])(!a||a.kind!=="box"||typeof a.id!="string"||!/^agent-block-[a-zA-Z0-9_-]{1,96}$/.test(a.id)||n.items.some(i=>i.id===a.id)||!Fs(a.position)||!Fs(a.scale)||a.scale.some(i=>i<.1||i>100)||typeof a.name!="string"||a.name.length>80)&&un("Khối Agent không hợp lệ.");const s=new Set;for(const a of e.tracks){s.has(a.subjectId)&&un("AI trả về track trùng lặp."),s.add(a.subjectId);const i=n.items.find(l=>l.id===a.subjectId);if(a.subjectId!=="camera"&&(!i||i.locked)&&un("Đối tượng không tồn tại hoặc đã khóa."),(!Array.isArray(a.keys)||!a.keys.length||a.keys.length>200)&&un("Số key không hợp lệ."),a.replaceRange!=null){const l=a.replaceRange;(!Number.isFinite(l.start)||!Number.isFinite(l.end)||l.start<0||l.end<=l.start||l.end>e.duration||a.keys[0].seconds!==l.start||a.keys.at(-1).seconds!==l.end)&&un("Đoạn sửa phải có key ở cả hai đầu."),a.keys.some(c=>c.seconds<l.start||c.seconds>l.end)&&un("Key nằm ngoài đoạn sửa.")}let r=-1;for(const l of a.keys)(!Number.isFinite(l.seconds)||l.seconds<0||l.seconds>e.duration||l.seconds<=r||!Fs(l.position))&&un("Thời điểm hoặc vị trí key không hợp lệ."),r=l.seconds,a.subjectId==="camera"?(!Fs(l.target)||!Number.isFinite(l.lens)||l.lens<14||l.lens>200||!Number.isFinite(l.roll)||Math.abs(l.roll)>36e3||l.position.every((c,u)=>Math.abs(c-l.target[u])<1e-8))&&un("Thông số camera không hợp lệ."):(!Fs(l.rotation)||!Fs(l.scale)||l.scale.some(c=>c<.01||c>1e3))&&un("Góc xoay hoặc kích thước không hợp lệ."),l.pose!==void 0&&!["Ngồi","Đứng"].includes(l.pose)&&un("Tư thế key không hợp lệ.")}return e}function gc(e,n,s,a={},i=[]){const r=e.shots.find(c=>c.id===e.activeShot),l=Fh(r,s);return{placement:{camera:r.position,colliders:i.slice(0,400).map(c=>({id:c.id,itemId:c.itemId,name:c.name,kind:c.kind,min:c.min.map(u=>Math.round(u*1e3)/1e3),max:c.max.map(u=>Math.round(u*1e3)/1e3)}))},shotId:r.id,duration:r.duration,playheadSeconds:s*r.duration,selectedId:n||"camera",camera:{position:l.position,target:l.target,lens:l.lens,roll:l.roll,motion:r.motion,keys:r.cameraKeys?.map(c=>({...c,seconds:c.time*r.duration}))||[]},items:e.items.map(c=>{const u=is(c,r,s),m=a[c.id],d=[...r.objectKeys?.[c.id]||[]].sort((x,g)=>x.time-g.time),f=d.slice(1).map((x,g)=>{const v=d[g],w=(x.time-v.time)*r.duration,C=Math.hypot(...x.position.map((M,S)=>M-v.position[S]));return{start:v.time*r.duration,end:x.time*r.duration,distance:C,speed:w>0?C/w:null}}),p=Object.entries(a).filter(([x])=>x!==c.id).map(([x,g])=>{const v=m?u.position[0]-m.min[0]:.5,w=m?m.max[0]-u.position[0]:.5,C=m?u.position[2]-m.min[2]:.5,M=m?m.max[2]-u.position[2]:.5,S=(g.min[0]+g.max[0])/2,I=(g.min[2]+g.max[2])/2,y=[[g.min[0]-w-.3,u.position[1],I],[g.max[0]+v+.3,u.position[1],I],[S,u.position[1],g.min[2]-M-.3],[S,u.position[1],g.max[2]+C+.3]];return{targetId:x,worldAxisPoints:y,nearest:y.reduce((k,T)=>Math.hypot(T[0]-u.position[0],T[2]-u.position[2])<Math.hypot(k[0]-u.position[0],k[2]-u.position[2])?T:k)}});return{motionProfile:m?.motionProfile||null,segments:f,bounds:m||null,approachPoints:p.slice(0,6),baseTransform:{position:c.position,rotation:c.rotation,scale:c.scale},...c.kind==="person"?{pose:{hipL:c.pose.hipL,hipR:c.pose.hipR,kneeL:c.pose.kneeL,kneeR:c.pose.kneeR,lean:c.pose.lean},...c.figure?{figure:c.figure}:{}}:{},...c.kind==="set"&&c.set?{set:{id:c.set.id}}:{},id:c.id,name:c.name,kind:c.kind,locked:c.locked,hidden:c.hidden,position:u.position,rotation:u.rotation,scale:u.scale,keys:r.objectKeys?.[c.id]?.map(x=>({...x,seconds:x.time*r.duration}))||[]}})}}function Ti(e,n){const s=e.shots.find(l=>l.id===e.activeShot);Xg(n,{duration:s.duration,items:e.items});const a=s.duration/n.duration,i={...s,duration:n.duration,objectKeys:Object.fromEntries(Object.entries(s.objectKeys||{}).map(([l,c])=>[l,c.map(u=>({...u,time:u.time*a}))])),cameraKeys:s.cameraKeys?.map(l=>({...l,time:l.time*a}))};for(const l of n.tracks){const c=u=>!l.replaceRange||u.time*n.duration<l.replaceRange.start-1e-7||u.time*n.duration>l.replaceRange.end+1e-7;if(l.subjectId==="camera"){const u=l.keys.map(f=>({id:bt(),time:f.seconds/n.duration,position:f.position,target:f.target,lens:f.lens,roll:f.roll}));i.cameraKeys=[...(i.cameraKeys||[]).filter(f=>c(f)&&!u.some(p=>Math.abs(p.time-f.time)<1e-7)),...u].sort((f,p)=>f.time-p.time);const m=i.cameraKeys[0],d=i.cameraKeys.at(-1);Object.assign(i,{motion:"path",position:m.position,target:m.target,lens:m.lens,roll:m.roll,endPosition:d.position,endTarget:d.target,endLens:d.lens,pathSmooth:s.motion==="path"?s.pathSmooth:void 0})}else{const u=l.keys.map(m=>({id:bt(),time:m.seconds/n.duration,position:m.position,rotation:m.rotation,scale:m.scale,...m.stance?{stance:m.stance}:{},...m.pose&&In[m.pose]?{pose:{...In[m.pose]}}:{}}));i.objectKeys[l.subjectId]=[...(i.objectKeys[l.subjectId]||[]).filter(m=>c(m)&&!u.some(d=>Math.abs(d.time-m.time)<1e-7)),...u].sort((m,d)=>m.time-d.time)}}const r=(n.additions||[]).map((l,c)=>({...fn("box",e.items.length+c),id:l.id,name:l.name,position:l.position,scale:l.scale,color:"#849095"}));return{...e,items:[...e.items,...r],shots:e.shots.map(l=>l.id===s.id?i:l)}}const Ea=Object.freeze({oval:{vi:"Trái xoan",en:"Oval",width:1,length:1,eyes:1},round:{vi:"Tròn",en:"Round",width:1.1,length:.94,eyes:1.08},long:{vi:"Dài",en:"Long",width:.92,length:1.1,eyes:.95},square:{vi:"Vuông",en:"Square",width:1.12,length:1.02,eyes:.92},child:{vi:"Trẻ con",en:"Child",width:1.05,length:.96,eyes:1.3}}),js=Object.freeze({width:[.85,1.2],length:[.85,1.2],eyes:[.7,1.4]}),xc=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Vg=/^#[0-9a-fA-F]{6}$/,Qn=(e,n)=>{throw Object.assign(new Error(`${e}: ${n}`),{status:400})};function Mo(e={}){xc(e)||Qn("character","object");for(const u of Object.keys(e))["preset","figure","look","face","color"].includes(u)||Qn("character",`unknown field "${u}"`);const n=e.preset!=null?Ph(String(e.preset)):null;e.preset!=null&&!n&&Qn("character.preset","unknown character preset");const s={height:1.75,face:"simple",...n?.figure??{},...e.figure!=null?im(e.figure,"character.figure"):{}},a=Cl({...n?.look??{},...e.look!=null?Cl(e.look,"character.look"):{}},"character.look");e.color!==void 0&&!(typeof e.color=="string"&&Vg.test(e.color))&&Qn("character.color","#rrggbb");const i=(e.color??s.skin??n?.color??wr[2]).toLowerCase();s.skin||(s.skin=i);const r=e.face??{};xc(r)||Qn("character.face","object");for(const u of Object.keys(r))["preset","width","length","eyes"].includes(u)||Qn("character.face",`unknown field "${u}"`);r.preset!==void 0&&!Ea[r.preset]&&Qn("character.face.preset",Object.keys(Ea).join("|"));const l=Ea[r.preset??"oval"],c={preset:r.preset??"oval"};for(const[u,[m,d]]of Object.entries(js)){const f=r[u]===void 0?l[u]:r[u];(typeof f!="number"||!Number.isFinite(f))&&Qn(`character.face.${u}`,`number ${m}..${d}`),c[u]=+Math.min(d,Math.max(m,f)).toFixed(3)}return{...n?{preset:n.id}:{},figure:s,look:a,color:i,face:c}}function Yg(e){const n=JSON.stringify(e);let s=2166136261;for(let a=0;a<n.length;a++)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}const Qg=e=>`gen:character:${Yg(e)}`,nr={torso:"torso",head:"head",eyes:"head",eyeL:"head",eyeR:"head"};for(const e of["L","R"])Object.assign(nr,{[`arm${e}`]:`arm${e}`,[`fore${e}`]:`fore${e}`,[`wrist${e}`]:`wrist${e}`,[`hand${e}`]:`wrist${e}`,[`thigh${e}`]:`thigh${e}`,[`shin${e}`]:`shin${e}`,[`foot${e}`]:`foot${e}`});function Zg(){return{...Object.fromEntries(Object.entries(In.Đứng).map(([n,s])=>[n,typeof s=="number"&&!/^(grip|thumb|index)/.test(n)?0:s])),lean:0,spineTwist:0,head:0,headPitch:0,headRoll:0}}function Jg(e){const n=Dt({height:1.8,head:1,build:1,...e.figure}),s=$h(Zg(),e.color,n,e.look);s.scale.setScalar(n.height/rm(n));const a=s.getObjectByName("head"),i=s.getObjectByName("eyes");a&&a.scale.set(a.scale.x*e.face.width,a.scale.y*e.face.length,a.scale.z*(e.face.width+1)/2),i&&i.scale.setScalar(e.face.eyes),s.updateMatrixWorld(!0);const r=k=>{for(let T=k;T;T=T.parent)if(nr[T.name])return nr[T.name];return"torso"},l=k=>s.getObjectByName(k).getWorldPosition(new ie),c=[];s.traverse(k=>{if(!(k instanceof ut)||!k.visible||!k.geometry.getAttribute("position"))return;let T=!1;for(let L=k;L;L=L.parent)L.visible||(T=!0);if(T)return;if(k instanceof Er){c.push(tx(k));return}const j=k.geometry.clone();j.morphAttributes={};for(const L of Object.keys(j.attributes))L!=="position"&&L!=="normal"&&L!=="uv"&&j.deleteAttribute(L);j.applyMatrix4(k.matrixWorld),c.push({geo:j,material:k.material,joint:r(k),name:k.name||r(k)})});const u=new $t,m=new Map;for(const k of c){if(k.geo.computeBoundingBox(),u.union(k.geo.boundingBox),k.weights){const j=k.geo.getAttribute("position"),L=new ie;for(let N=0;N<j.count;N++){const A=ja[k.weights.index[N*4]][0],O=m.get(A)??new $t;O.expandByPoint(L.fromBufferAttribute(j,N)),m.set(A,O)}continue}const T=m.get(k.joint)??new $t;T.union(k.geo.boundingBox),m.set(k.joint,T)}const d={};for(const[k]of ja)s.getObjectByName(k)&&(d[k]=l(k));d.headTop=new ie(d.head.x,m.get("head").max.y,d.head.z);for(const k of["L","R"]){const T=m.get(`wrist${k}`)??new $t().setFromCenterAndSize(d[`wrist${k}`],new ie(.05,.2,.05));d[`handTip${k}`]=new ie(d[`wrist${k}`].x,T.min.y,d[`wrist${k}`].z);const j=m.get(`foot${k}`)??new $t().setFromCenterAndSize(d[`foot${k}`],new ie(.1,.1,.25));d[`toe${k}`]=new ie(d[`foot${k}`].x,j.min.y,j.max.z)}const f=u.getSize(new ie),p=2/Math.max(f.x,f.y,f.z),x=u.getCenter(new ie),g=new St().makeScale(p,p,p).multiply(new St().makeTranslation(-x.x,-u.min.y,-x.z)),v=k=>Math.round(k*1e4)/1e4,w=ja.map(([k,T])=>({name:k,parent:T,pos:d[k].clone().applyMatrix4(g).toArray().map(v)})),C=Wo({kind:"humanoid",source:"template",joints:w,seed:1}),M=new Map(C.joints.map((k,T)=>[k.name,T])),S=lm(C),I=new tn;let y=0;for(const k of c){k.geo.applyMatrix4(g);const T=k.geo.getAttribute("position").count,j=M.get(k.joint)??0,L=new Uint16Array(T*4),N=new Float32Array(T*4);if(k.weights)for(let O=0;O<T*4;O++)L[O]=M.get(ja[k.weights.index[O]][0])??0,N[O]=k.weights.weight[O];else for(let O=0;O<T;O++)L[O*4]=j,N[O*4]=1;k.geo.setAttribute("skinIndex",new sd(L,4)),k.geo.setAttribute("skinWeight",new Ot(N,4)),k.geo.userData.rigWeights=S,k.geo.computeBoundingBox(),k.geo.computeBoundingSphere();const A=new ut(k.geo,k.material);A.name=k.name,A.castShadow=!0,A.receiveShadow=!0,I.add(A),y+=T}return I.userData.normalizedHeight=f.y*p,{root:I,rig:C,normalizedHeight:f.y*p,height:+f.y.toFixed(4),vertices:y}}const vd=new Map(ja.map(([e],n)=>[e,n]));function ex(e){if(vd.has(e))return[[e,1]];const n=/^(arm|fore|wrist|thigh|shin|foot)Half([LR])$/.exec(e);if(n){const a={arm:"torso",fore:"arm",wrist:"fore",thigh:"torso",shin:"thigh",foot:"shin"},i=a[n[1]];return[[n[1]+n[2],.5],[i==="torso"?"torso":i+n[2],.5]]}if(e==="headHalf")return[["head",.5],["torso",.5]];const s=/^(thumb|index|middle|ring|pinky)\d([LR])$/.exec(e);return s?[[`wrist${s[2]}`,1]]:/^(jaw|lid|eye|hair)/.test(e)?[["head",1]]:[["torso",1]]}function tx(e){const n=e.geometry,s=n.getAttribute("position").count,a=new Float32Array(s*3),i=new ie,r=n.getAttribute("skinIndex"),l=n.getAttribute("skinWeight"),c=e.skeleton.bones.map(f=>f.name),u=new Uint16Array(s*4),m=new Float32Array(s*4);e.skeleton.update();for(let f=0;f<s;f++){i.fromBufferAttribute(n.getAttribute("position"),f),e.applyBoneTransform(f,i),i.applyMatrix4(e.matrixWorld),a[f*3]=i.x,a[f*3+1]=i.y,a[f*3+2]=i.z;const p=new Map;for(let v=0;v<4;v++){const w=l.getComponent(f,v);if(w)for(const[C,M]of ex(c[r.getComponent(f,v)]??"torso")){const S=vd.get(C)??0;p.set(S,(p.get(S)??0)+w*M)}}const x=[...p].sort((v,w)=>w[1]-v[1]).slice(0,4),g=x.reduce((v,w)=>v+w[1],0)||1;x.forEach(([v,w],C)=>{u[f*4+C]=v,m[f*4+C]=w/g})}const d=new Ct;return d.setAttribute("position",new Nt(a,3)),n.getAttribute("color")&&d.setAttribute("color",n.getAttribute("color").clone()),d.setIndex(n.getIndex()?Array.from(n.getIndex().array):null),d.computeVertexNormals(),{geo:d,material:e.material,joint:"torso",name:e.name||"skin",weights:{index:u,weight:m}}}const Os=new Map;function jd(e){const n=JSON.stringify(e);let s=Os.get(n);if(!s)for(s=Jg(e),Os.set(n,s);Os.size>16;)Os.delete(Os.keys().next().value);return s}function kd(){Os.clear()}const bc=e=>Array.isArray(e)&&e.length===3&&e.every(n=>Number.isFinite(Number(n)))?e.map(Number):null;function Li(e,n){const s=e.getStage(),a=String(n.name||"Nhân vật").trim().slice(0,60)||"Nhân vật",i=s.items.find(f=>f.name===a&&f.kind==="model"&&f.gen?.kind==="character");let r;try{const f=i?.gen?.kind==="character"?i.gen.spec:void 0,p=Object.fromEntries(["figure","look","face","color"].filter(g=>n[g]!=null).map(g=>[g,n[g]])),x=n.face;r=Mo(n.preset!=null||!f?{...n.preset!=null?{preset:n.preset}:{},...p}:{figure:{...f.figure,...n.figure||{}},look:{...f.look,...n.look||{}},face:x?.preset?x:{...f.face,...x||{}},color:n.color??f.color})}catch(f){return{ok:!1,error:f.message}}const l=jd(r),c=l.height,u={model:{gcsUri:Qg(r),name:`${a}.character`,height:c},gen:{kind:"character",spec:r},rig:l.rig,color:r.color,...bc(n.position)?{position:bc(n.position)}:{},...n.yaw_deg!=null?{rotation:[0,Number(n.yaw_deg)||0,0]}:{}};let m=i?.id;if(i)e.setStage(f=>({...f,items:f.items.map(p=>p.id===i.id?{...p,...u}:p)}));else{const f=Oh(s,{kind:"model",name:a,...u});m=f.id,e.setStage(p=>({...p,items:[...p.items,f]}))}const d=l.rig.joints.filter(f=>!cm(l.rig.joints,f)).map(f=>f.name);return{ok:!0,name:a,id:m,rebuilt:!!i,height_m:c,vertices:l.vertices,rig:"humanoid",bones:d,...r.preset?{preset:r.preset}:{},face:r.face,hint:"already rigged with the humanoid skeleton: set_pose, play_motion, hold_prop, set_gaze, resolve_hits and set_bone_rotation work on it; same name = rebuild with new parameters"}}const nx=[{key:"height",vi:"Chiều cao (m)",lo:1,hi:2.1,step:.01},{key:"weight",vi:"Cân nặng (gầy → mập)",lo:-1,hi:1,step:.05},{key:"muscle",vi:"Cơ bắp",lo:0,hi:1,step:.05},{key:"posture",vi:"Dáng (thẳng → còng)",lo:0,hi:1,step:.05},{key:"shoulders",vi:"Vai",lo:.6,hi:1.6,step:.02},{key:"hips",vi:"Hông",lo:.6,hi:1.6,step:.02},{key:"sex",vi:"Giới tính (nam ↔ nữ)",lo:0,hi:1,step:.05},{key:"age",vi:"Tuổi",lo:3,hi:90,step:1}],sx=[{key:"width",vi:"Mặt rộng",lo:js.width[0],hi:js.width[1],step:.01},{key:"length",vi:"Mặt dài",lo:js.length[0],hi:js.length[1],step:.01},{key:"eyes",vi:"Mắt to",lo:js.eyes[0],hi:js.eyes[1],step:.01}];function ax({host:e,item:n,ground:s,onSelect:a,setError:i}){const r=ht(),l=M=>r==="en"?M.en:M.vi,[c,u]=R.useState(()=>Mo({preset:"office-f"})),m=(n?.gen?.kind==="character"?n.gen.spec:null)??c,d=R.useRef(void 0),f=M=>{let S;try{S=Mo({figure:{...m.figure,...M.figure||{}},look:M.look??m.look,face:{...m.face,...M.face||{}},color:M.color??m.color})}catch(I){i(I.message);return}if(!n){u(S);return}window.clearTimeout(d.current),d.current=window.setTimeout(()=>{const I=Li(e,{name:n.name,figure:S.figure,look:S.look,face:S.face,color:S.color});I.ok||i(String(I.error))},250)},p=M=>{if(!Ph(M))return;if(!n){u(Mo({preset:M}));return}const I=Li(e,{name:n.name,preset:M});I.ok||i(String(I.error))},x=()=>{const M=Li(e,{name:ox(e,o("Nhân vật")),figure:m.figure,look:m.look,face:m.face,color:m.color,position:s()});M.ok&&M.id?a(M.id):i(String(M.error))},g=m.figure,v=(M,S,I)=>t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o(M.vi)}),t.jsx("input",{type:"range","aria-label":o(M.vi),min:M.lo,max:M.hi,step:M.step,value:S,onChange:y=>I(+y.target.value)}),t.jsx("input",{type:"number","aria-label":`${o(M.vi)} (${o("số")})`,min:M.lo,max:M.hi,step:M.step,value:S,onChange:y=>{const k=+y.target.value;Number.isFinite(k)&&I(Math.min(M.hi,Math.max(M.lo,k)))}})]},M.key),w=m.look,C=(M,S,I,y)=>{const k=w[M];return t.jsxs("div",{className:"shot-char-piece",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o(y)}),t.jsxs("select",{"aria-label":o(y),value:k?String(k[I]):"",onChange:T=>{const j=T.target.value,L={...m.look};j?L[M]={...k||{color:M==="hair"?"#2a211b":"#4a6fa5"},[I]:j}:delete L[M],f({look:L})},children:[t.jsx("option",{value:"",children:o("Không")}),Object.entries(S).map(([T,j])=>t.jsx("option",{value:T,children:l(j)},T))]})]}),k&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Màu {0}",[o(y).toLowerCase()])}),t.jsx("input",{type:"color","aria-label":o("Màu {0}",[o(y).toLowerCase()]),value:k.color,onChange:T=>f({look:{...m.look,[M]:{...k,color:T.target.value}}})})]})]},M)};return t.jsxs("div",{className:"shot-model-edit shot-char",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["🧍 ",n?n.name:o("Nhân vật mới")]}),t.jsx("small",{className:"muted",children:n?o("Đang sửa: thay đổi dựng lại ngay, đã gắn xương người."):o("Lưới 3D tạo từ tham số, gắn sẵn xương người: tạo dáng, chuyển động, cầm đồ ngay.")})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Mẫu nhân vật")}),t.jsxs("select",{"aria-label":o("Mẫu nhân vật"),value:m.preset??"",onChange:M=>p(M.target.value),children:[t.jsx("option",{value:"",children:o("Tự chỉnh")}),hm.map(M=>t.jsx("option",{value:M.id,children:l(M.name)},M.id))]})]}),t.jsx("h4",{children:o("Dáng người")}),nx.map(M=>v(M,Number(g[M.key]??(M.key==="height"?1.75:M.key==="shoulders"||M.key==="hips"?1:M.key==="sex"?+Lo(g).fem.toFixed(2):M.key==="age"?Lo(g).age:0)),S=>f({figure:{[M.key]:S}}))),t.jsx("div",{className:"shot-char-skins",role:"group","aria-label":o("Màu da"),children:wr.map(M=>t.jsx("button",{type:"button","aria-label":M,"aria-pressed":m.color===M,className:m.color===M?"on":"",style:{background:M},onClick:()=>f({color:M,figure:{skin:M}})},M))}),t.jsx("h4",{children:o("Khuôn mặt")}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Kiểu mặt")}),t.jsx("select",{"aria-label":o("Kiểu mặt"),value:m.face.preset,onChange:M=>{const S=Ea[M.target.value];f({face:{preset:M.target.value,width:S.width,length:S.length,eyes:S.eyes}})},children:Object.entries(Ea).map(([M,S])=>t.jsx("option",{value:M,children:l(S)},M))})]}),sx.map(M=>v(M,m.face[M.key],S=>f({face:{[M.key]:S}}))),t.jsx("h4",{children:o("Tóc & trang phục")}),C("hair",dm,"style","Tóc"),C("top",um,"type","Áo"),C("bottom",mm,"type","Quần / váy"),!n&&t.jsx("button",{className:"pill-btn primary",onClick:x,children:o("+ Tạo nhân vật (đã gắn xương)")}),n&&t.jsx("small",{className:"muted",children:o("Mở tab Rigging để xoay xương, hoặc dùng thư viện chuyển động như với ma-nơ-canh.")})]})}function ox(e,n){const s=e.getStage();let a=n,i=2;for(;s.items.some(r=>r.name===a);)a=`${n} ${i++}`;return a}let mn=null,En,ts,yc=null,Ks;const vc=new Map,Ei=new Map;let jc=Promise.resolve(),kc=0;const wc=160,Mc=120;function ix(){if(mn)return mn;mn=new Ir({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),mn.outputColorSpace=Uo,mn.toneMapping=ad,mn.toneMappingExposure=1.15,mn.shadowMap.enabled=!0,mn.shadowMap.type=T0,mn.setClearColor(0,0),mn.setSize(wc,Mc,!1),En=new Rr;const e=new od(mn);yc=e.fromScene(new md,.04).texture,e.dispose(),En.environment=yc,En.environmentIntensity=.7,En.add(new id("#e8eeff","#5d5a55",.9));const n=new Go("#fff4e4",2.4);return n.castShadow=!0,n.shadow.mapSize.set(512,512),n.shadow.bias=-4e-4,En.add(n,n.target),Ks=new ut(new Xo(1,1),new L0({opacity:.32})),Ks.rotation.x=-Math.PI/2,Ks.receiveShadow=!0,En.add(Ks),ts=new Fr(28,wc/Mc,.05,2e3),mn}function rx(e){const n=new $t,s=new St;return e.updateMatrixWorld(!0),e.traverse(a=>{if(a instanceof Bs){const i=a.geometry.boundingBox??(a.geometry.computeBoundingBox(),a.geometry.boundingBox);for(let r=0;r<a.count;r++)a.getMatrixAt(r,s),n.union(i.clone().applyMatrix4(s).applyMatrix4(a.matrixWorld))}else a instanceof ut&&n.union(new $t().setFromObject(a))}),n}function lx(e){const n=ix(),s=pm(fm(e).recipe);En.add(s);try{const a=rx(s);if(a.isEmpty())throw new Error(`empty model ${e}`);const i=a.getSize(new ie),r=a.getCenter(new ie),l=Math.max(.05,i.length()/2),c=Ln.degToRad(ts.fov)/2,u=l/Math.sin(c)*.98,m=new ie(.62,.42,1).normalize();ts.position.copy(r).addScaledVector(m,u),ts.near=u/100,ts.far=u*4,ts.updateProjectionMatrix(),ts.lookAt(r),Ks.position.set(r.x,a.min.y+.001,r.z),Ks.scale.setScalar(l*6);const d=En.children.find(p=>p instanceof Go);d.position.copy(r).add(new ie(-.6,1.4,.9).multiplyScalar(l*3)),d.target.position.copy(r);const f=d.shadow.camera;return f.left=f.bottom=-l*1.6,f.right=f.top=l*1.6,f.near=l*.1,f.far=l*8,f.updateProjectionMatrix(),n.render(En,ts),n.domElement.toDataURL("image/png")}finally{En.remove(s),s.traverse(a=>{a instanceof ut&&(a.geometry.dispose(),a.material.dispose())})}}function cx(e){const n=vc.get(e);if(n)return Promise.resolve(n);const s=Ei.get(e);if(s)return s;if(!Dh(e))return Promise.reject(new Error(`unknown model kit ${e}`));const a=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof a=="number"&&kc>=a)return Promise.reject(new Error("thumbnail limit"));kc++;const i=jc.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const c=lx(e);vc.set(e,c),r(c)}catch(c){l(c)}},16))).finally(()=>Ei.delete(e));return jc=i.catch(()=>{}),Ei.set(e,i),i}const Sa="claude-opus-5-5",Sc=e=>`${Math.round(e/1e3).toLocaleString("vi-VN")}k đ`;function eo({quote:e,error:n}){return n?t.jsx("small",{className:"shot-hq-quote",role:"alert",children:n}):e?!Number.isFinite(e.credits?.low)||!Number.isFinite(e.credits?.high)||!e.vnd?null:t.jsx("small",{className:"shot-hq-quote",children:o("Ước tính {0}–{1} credit (≈ {2}–{3}) cho một model mới · tối đa {4} credit mỗi lượt, tính theo token dùng thật",[e.credits.low.toFixed(1),e.credits.high.toFixed(1),Sc(e.vnd.low),Sc(e.vnd.high),$a])}):t.jsx("small",{className:"shot-hq-quote",children:o("Đang ước tính chi phí…")})}const Cc=[["real","Chân thật","photoreal, real materials"],["stylized","Stylized","stylized, clean shapes, saturated colours"],["lowpoly","Low-poly","low-poly, faceted (flat:true), few segments"]];function hx({host:e,item:n,onSelect:s,setError:a}){ht();const i=zh(),[r,l]=R.useState(""),[c,u]=R.useState(""),[m,d]=R.useState("real"),[f,p]=R.useState(null),[x,g]=R.useState(null),[v,w]=R.useState(null),[C,M]=R.useState(""),[S,I]=R.useState(""),[y,k]=R.useState(!1),T=R.useRef(void 0),j=rc(n)&&n.gen?.kind==="code"?n.gen:null,L=["thinking","acting","rendering"].includes(i.phase),N=i.purpose==="model"&&(i.log.length>0||L),A=[...e.getStage().items].reverse().find(V=>rc(V));R.useEffect(()=>{g(null),w(null),M("")},[n?.id]);const O=async V=>{M("");try{g(await p0(Sa,V)),w(V)}catch(B){M(B.message)}},_=async V=>{if(!V){p(null);return}if(V.size>28e4||!["image/jpeg","image/png"].includes(V.type)){a(o("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const B=await new Promise((q,D)=>{const ee=new FileReader;ee.onload=()=>q(String(ee.result)),ee.onerror=()=>D(ee.error),ee.readAsDataURL(V)});p({name:V.name,data:B})},$=()=>{const V=r.trim();if(!V||L)return;const B=Cc.find(D=>D[0]===m),q=`${V}
|
|
3
|
+
Style: ${B[2]}.${c.trim()?` Real size: ${c.trim()}.`:""}${f?" Match the attached reference photo.":""}`;i.start(q,f?.data||null,Sa,"model",{quality:"high"}),g(null),w(null)},P=()=>{const V=S.trim();if(!V||!j||L)return;const B=`Edit the code model named "${n.name}" (read_model_code, then code_model with the same name; keep everything not mentioned): ${V}`;i.purpose==="model"&&(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===Sa&&i.quality==="high"?i.followUp(B):i.start(B,null,Sa,"model",{quality:"high"}),I(""),g(null),w(null)},W=(V,B)=>{if(!j||!n)return;const q={...j.code.params,[V]:B};e.setStage(D=>({...D,items:D.items.map(ee=>ee.id===n.id&&ee.gen?.kind==="code"?{...ee,gen:{...ee.gen,code:{...ee.gen.code,params:q}}}:ee)})),window.clearTimeout(T.current),T.current=window.setTimeout(()=>{lc(e,{name:n.name,params:q,views:!1}).then(D=>{D.ok||a(String(D.error))})},250)},z=async()=>{if(!(!j||!n)){k(!0);try{const V=await lc(e,{name:n.name,seed:j.code.seed%2147483e3+1,views:!1});V.ok||a(String(V.error))}finally{k(!1)}}},Q=async()=>{if(!(!j||!n)){k(!0);try{const V=await V0(j.code),B=URL.createObjectURL(V),q=document.createElement("a");q.href=B,q.download=`${n.name.replace(/[^\p{L}\p{N}_-]+/gu,"_")||"model"}.glb`,q.click(),window.setTimeout(()=>URL.revokeObjectURL(B),4e3)}catch(V){a(V.message)}finally{k(!1)}}},J=N&&t.jsxs("div",{className:"shot-hq-progress",role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[t.jsx("b",{className:"shot-hq-badge",children:o("Chất lượng cao · Opus")}),L?o("Đang dựng…"):i.phase==="capped"?o("Đã dùng hết {0} credit của lượt này",[$a]):i.phase==="done"?o("Xong"):i.phase==="error"?o("Lỗi"):i.phase==="cancelled"?o("Đã dừng"):""," · ",o("bước")," ",i.step," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-6).map((V,B)=>t.jsx("div",{className:"shot-mission-line",children:V},B)),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:o('Lượt này đã dùng hết {0} credit nên Agent dừng lại; model đang có vẫn giữ nguyên. Gõ yêu cầu ở ô "Sửa bằng lời" để làm tiếp (thêm {0} credit).',[$a])}),i.error&&t.jsx("p",{role:"alert",children:i.error}),L&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>i.stop(),children:o("Dừng")}),!L&&!j&&A&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(A.id),children:o("Chỉnh model vừa dựng: {0}",[A.name])})]});return j&&n?t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsx("strong",{children:n.name}),t.jsx("small",{className:"muted",children:o("Model dựng bằng code · Opus")})]}),j.prompt&&t.jsx("small",{className:"muted shot-hq-prompt",children:j.prompt}),(j.schema||[]).length>0?t.jsx("div",{className:"shot-model-params",children:(j.schema||[]).map(V=>t.jsx(dx,{p:V,value:j.code.params[V.key]??V.default,onChange:B=>W(V.key,B)},V.key))}):t.jsx("small",{className:"muted",children:o("Model này không có thanh trượt tham số.")}),t.jsx("small",{className:"muted",children:o("Kéo thanh trượt để dựng lại ngay trên máy: không gọi AI, 0 credit.")}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:y,onClick:()=>void z(),children:o("Biến thể khác (0 credit)")}),t.jsx("button",{type:"button",className:"pill-btn thin",disabled:y,onClick:()=>void Q(),children:o("Tải .glb")})]}),t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:o("Sửa bằng lời (AI · Opus)")}),t.jsx("textarea",{rows:3,maxLength:1500,value:S,disabled:L,placeholder:o("Ví dụ: cổ chai dài hơn, thêm nắp nhôm, nhãn màu xanh lá"),onChange:V=>{I(V.target.value),v!=="edit"&&g(null)}})]}),v==="edit"&&x?t.jsx(eo,{quote:x}):C?t.jsx(eo,{quote:null,error:C}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:L||!S.trim(),onClick:()=>void O("edit"),children:o("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:L||!S.trim()||v!=="edit",title:v!=="edit"?o("Xem ước tính chi phí trước"):"",onClick:P,children:o("Sửa (≈ {0}–{1} cr)",[x?.credits.low.toFixed(1)??"?",x?.credits.high.toFixed(1)??"?"])})]}),J,t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(null),children:o("+ Dựng model mới")})]}):t.jsxs("div",{className:"shot-hq-panel",children:[t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:o("Mô tả model")}),t.jsx("textarea",{rows:4,maxLength:3e3,value:r,disabled:L,placeholder:o("Ví dụ: chai nước hoa thuỷ tinh 50 ml, thân vuông bo góc, nắp vàng xước, nước màu hồng nhạt"),onChange:V=>l(V.target.value)})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:o("Kích thước thật (tuỳ chọn)")}),t.jsx("input",{value:c,maxLength:80,disabled:L,placeholder:o("vd: cao 12 cm"),onChange:V=>u(V.target.value)})]}),t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:o("Phong cách")}),t.jsx("select",{value:m,disabled:L,onChange:V=>d(V.target.value),children:Cc.map(([V,B])=>t.jsx("option",{value:V,children:o(B)},V))})]})]}),t.jsxs("div",{className:"shot-hq-row",children:[t.jsxs("label",{className:"shot-mission-ref",children:[t.jsx("input",{type:"file",accept:"image/jpeg,image/png",hidden:!0,disabled:L,onChange:V=>{_(V.target.files?.[0]),V.target.value=""}}),t.jsx("span",{children:f?`🖼 ${f.name}`:o("+ Ảnh tham chiếu (tuỳ chọn)")})]}),f&&!L&&t.jsx("button",{type:"button",onClick:()=>p(null),children:"×"})]}),v==="build"&&x?t.jsx(eo,{quote:x}):C?t.jsx(eo,{quote:null,error:C}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:L||!r.trim(),onClick:()=>void O("build"),children:o("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:L||!r.trim()||v!=="build",title:v!=="build"?o("Xem ước tính chi phí trước"):"",onClick:$,children:o("Dựng (≈ {0}–{1} cr)",[x?.credits.low.toFixed(1)??"?",x?.credits.high.toFixed(1)??"?"])})]}),J]})}function dx({p:e,value:n,onChange:s}){return e.type==="num"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"range",min:e.min,max:e.max,step:e.step,value:Number(n),onChange:a=>s(Number(a.target.value))}),t.jsx("output",{children:Number(n).toFixed(e.step<1?Math.min(3,Math.max(0,-Math.floor(Math.log10(e.step)))):0)})]}):e.type==="bool"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"checkbox",checked:!!n,onChange:a=>s(a.target.checked)})]}):e.type==="choice"?t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("select",{value:String(n),onChange:a=>s(a.target.value),children:e.options.map(a=>t.jsx("option",{value:a,children:a},a))})]}):t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"color",value:String(n),onChange:a=>s(a.target.value)}),t.jsx("output",{children:String(n)})]})}function ux({host:e,item:n,ground:s,onSelect:a,setError:i}){ht();const[r,l]=R.useState("Sản phẩm"),[c,u]=R.useState(""),[m,d]=R.useState(null),[f,p]=R.useState(null),[x,g]=R.useState([]),[v,w]=R.useState(""),[C,M]=R.useState(null),S=async(N,A)=>{if(N){if(!/^image\/(png|jpeg|webp)$/.test(N.type)){i(o("Ảnh phải là PNG, JPG hoặc WEBP."));return}w(o("Đang tải ảnh lên…"));try{const O=await _s(N,void 0,"image");A({name:N.name,url:O.url})}catch(O){i(O.message)}finally{w("")}}},I=N=>Number(String(N).replace(",","."))/100,y=async()=>{if(!m){i(o("Chọn ảnh chính diện của sản phẩm."));return}if(!(I(c)>0)){i(o("Nhập chiều cao thật của sản phẩm (cm)."));return}w(o("Đang dựng sản phẩm…")),M(null);try{const{modelProduct:N}=await Wn(async()=>{const{modelProduct:O}=await import("./productTools-B1h5cgyt.js");return{modelProduct:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),A=await N({image:m.url,...f?{back_image:f.url}:{},height_m:I(c),name:r.trim()||"Sản phẩm",position:s(),labels:x.filter(O=>O.url&&I(O.height)>0).map(O=>({image:O.url,bottom_m:I(O.bottom)||0,height_m:I(O.height),center_deg:Number(O.side),finish:O.finish}))},e);A.ok?A.id&&a(String(A.id)):i(String(A.error))}finally{w("")}},k=async()=>{if(n){w(o("Đang xuất GLB…"));try{const{saveGlb:N}=await Wn(async()=>{const{saveGlb:O}=await import("./productTools-B1h5cgyt.js");return{saveGlb:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),A=await N({name:n.name},e);A.ok?M({file:String(A.file),url:String(A.url)}):i(String(A.error))}finally{w("")}}},T=async()=>{if(n?.set){w(o("Đang xuất GLB…"));try{const{recipeGlb:N}=await Wn(async()=>{const{recipeGlb:W}=await import("./exportGlb-CLfTnbMG.js");return{recipeGlb:W}},__vite__mapDeps([11,1,2,3,4,5,6,7,8,9,10])),{loadSetOf:A}=await Wn(async()=>{const{loadSetOf:W}=await import("./remote-BJdzzFZg.js").then(z=>z.js);return{loadSetOf:W}},__vite__mapDeps([2,3,1,4,5,6,7,8,9,10])),O=e.engine()?.setRecipe(n.set.id)??await A(e)(n.set.id),_=await N(O),$=document.createElement("a"),P=URL.createObjectURL(_);$.href=P,$.download=`${n.name}.glb`,$.click(),setTimeout(()=>URL.revokeObjectURL(P),5e3)}catch(N){i(N.message)}finally{w("")}}},j=(N,A,O)=>t.jsxs("label",{className:"shot-product-pick",children:[t.jsx("span",{children:N}),t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:_=>void S(_.target.files?.[0],O)}),A?t.jsx("img",{src:A.url,alt:""}):t.jsx("em",{children:o("Chưa chọn")})]}),L=(N,A)=>g(O=>O.map(_=>_.key===N?{..._,...A}:_));return t.jsxs("div",{className:"shot-product",children:[t.jsx("p",{className:"shot-product-hint",children:o("Ảnh sản phẩm chụp thẳng, nền trơn (hoặc PNG trong suốt) cho dáng và màu; file thiết kế nhãn cho bao bì sắc nét, đúng kích thước.")}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:o("Tên")}),t.jsx("input",{value:r,onChange:N=>l(N.target.value)})]}),t.jsxs("label",{className:"shot-product-row",children:[t.jsx("span",{children:o("Chiều cao thật (cm)")}),t.jsx("input",{inputMode:"decimal",value:c,placeholder:"29",onChange:N=>u(N.target.value)})]}),j(o("Ảnh chính diện"),m,d),j(o("Ảnh mặt sau (không bắt buộc)"),f,p),t.jsxs("div",{className:"shot-product-labels",children:[t.jsx("b",{children:o("File thiết kế nhãn / bao bì")}),x.map(N=>t.jsxs("div",{className:"shot-product-label",children:[N.url?t.jsx("img",{src:N.url,alt:""}):t.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:A=>void S(A.target.files?.[0],O=>O&&L(N.key,{url:O.url,name:O.name}))}),t.jsxs("label",{children:[o("Đáy nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.bottom,onChange:A=>L(N.key,{bottom:A.target.value})})]}),t.jsxs("label",{children:[o("Cao nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.height,onChange:A=>L(N.key,{height:A.target.value})})]}),t.jsxs("label",{children:[o("Mặt"),t.jsxs("select",{value:N.side,onChange:A=>L(N.key,{side:A.target.value}),children:[t.jsx("option",{value:"0",children:o("Trước")}),t.jsx("option",{value:"180",children:o("Sau")})]})]}),t.jsxs("label",{children:[o("Bề mặt"),t.jsxs("select",{value:N.finish,onChange:A=>L(N.key,{finish:A.target.value}),children:[t.jsx("option",{value:"matte",children:o("Giấy mờ")}),t.jsx("option",{value:"gloss",children:o("Bóng")}),t.jsx("option",{value:"foil",children:o("Nhũ kim loại")})]})]}),t.jsx("button",{type:"button",onClick:()=>g(A=>A.filter(O=>O.key!==N.key)),children:"✕"})]},N.key)),t.jsxs("button",{type:"button",onClick:()=>g(N=>[...N,{key:Date.now(),name:"",url:"",bottom:"",height:"",side:"0",finish:"matte"}]),children:["+ ",o("Thêm nhãn")]})]}),t.jsx("button",{type:"button",className:"shot-product-build",disabled:!!v,onClick:()=>void y(),children:o("Dựng sản phẩm")}),n?.set&&t.jsxs("div",{className:"shot-product-export",children:[t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void k(),children:o("Lưu GLB vào Tài sản của tôi")}),t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void T(),children:o("Tải .glb")}),C&&t.jsxs("span",{children:[o("Đã lưu")," ",C.file]})]}),v&&t.jsx("p",{className:"shot-product-busy",children:v})]})}function wd(){return t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 2.8 20 7.4v9.2L12 21.2 4 16.6V7.4z"}),t.jsx("path",{d:"m4 7.4 8 4.6 8-4.6M12 12v9.2"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.3",fill:"currentColor"})]})}const Nc={oak:["Gỗ sồi","Oak"],walnut:["Gỗ óc chó","Walnut"],painted_wood:["Gỗ sơn","Painted wood"],concrete:["Bê tông","Concrete"],polished_concrete:["Bê tông mài","Polished concrete"],plaster:["Tường sơn","Plaster"],brick_red:["Gạch đỏ","Red brick"],brick_white:["Gạch sơn trắng","White brick"],tile_small:["Gạch nhỏ","Small tiles"],tile_medium:["Gạch 30 cm","Medium tiles"],tile_large:["Gạch 60 cm","Large tiles"],marble:["Đá cẩm thạch","Marble"],terrazzo:["Đá mài","Terrazzo"],linen:["Vải lanh","Linen"],velvet:["Nhung","Velvet"],leather:["Da","Leather"],carpet:["Thảm","Carpet"],glass_clear:["Kính trong","Clear glass"],glass_frosted:["Kính mờ","Frosted glass"],brushed_steel:["Inox xước","Brushed steel"],chrome:["Crôm","Chrome"],gold:["Vàng / đồng","Gold / brass"],plastic_matte:["Nhựa mờ","Matte plastic"],plastic_glossy:["Nhựa bóng","Glossy plastic"],rubber:["Cao su","Rubber"],asphalt:["Nhựa đường","Asphalt"],paving:["Gạch lát vỉa hè","Paving"],grass:["Cỏ","Grass"],soil:["Đất","Soil"],sand:["Cát","Sand"],water:["Nước","Water"],roof_tiles:["Ngói","Roof tiles"],ceramic:["Gốm sứ","Ceramic"],paper:["Giấy / bìa","Paper / cardboard"]},mx=[.01,.05,.1,.25,.5],px={box:["hộp","box"],cylinder:["trụ","cylinder"],cone:["nón","cone"],sphere:["cầu","sphere"],stairs:["bậc thang","stairs"],lathe:["khối tiện","lathe"],extrude:["khối đùn","extrusion"]};function fx(e){const{stage:n,selected:s}=e,a=n.items.find(m=>m.id===s&&m.kind==="set"&&m.set),i=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="character"),r=n.items.find(m=>m.id===s&&m.kind==="model"&&m.gen?.kind==="code"),[l,c]=R.useState(r?"ai":i?"character":a?.set?.kit?.id===ka?"hand":"library");R.useEffect(()=>{a?.set?.kit&&c(a.set.kit.id===ka?"hand":"library")},[a?.id,a?.set?.kit?.id]),R.useEffect(()=>{i&&c("character")},[i?.id]),R.useEffect(()=>{r&&c("ai")},[r?.id]);const u={getStage:e.getStage,setStage:e.change,engine:()=>e.engine};return t.jsxs("div",{className:"shot-panel-body shot-modeling",role:"region","aria-label":o("Dựng model"),children:[t.jsx("div",{className:"shot-model-tabs",role:"tablist",children:["library","hand","character","product"].map(m=>t.jsx("button",{role:"tab","aria-selected":l===m,className:l===m?"on":"",onClick:()=>c(m),children:m==="library"?o("Thư viện model"):m==="hand"?o("Dựng tay"):m==="character"?o("Nhân vật"):o("Sản phẩm từ ảnh")},m))}),t.jsxs("button",{type:"button",className:`shot-model-ai-tab${l==="ai"?" on":""}`,"aria-pressed":l==="ai",onClick:()=>c("ai"),children:["✦ ",o("AI chất lượng cao")]}),l==="library"?t.jsx(gx,{...e,host:u,item:a?.set?.kit&&a.set.kit.id!==ka?a:void 0}):l==="hand"?t.jsx(wx,{...e,item:a?.set?.kit?.id===ka?a:void 0}):l==="character"?t.jsx(ax,{host:u,item:i,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):l==="product"?t.jsx(ux,{host:u,item:a,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):t.jsx(hx,{host:u,item:r,ground:e.ground,onSelect:e.onSelect,setError:e.setError}),a&&l!=="character"&&l!=="ai"&&l!=="product"&&t.jsx(yx,{item:a,change:e.change})]})}function gx({host:e,item:n,ground:s,onSelect:a,setError:i}){const r=ht(),l=j=>r==="en"?j.en:j.vi,[c,u]=R.useState("all"),[m,d]=R.useState(""),[f,p]=R.useState(null),[x,g]=R.useState({}),[v,w]=R.useState(!1),C=n?.set?.kit,M=Dh(C?.id??f??""),S=C?C.params:x,I=R.useRef(void 0),y=(j,L)=>{if(!M)return;const N={...S,[j]:L};if(!C){g(N);return}window.clearTimeout(I.current),I.current=window.setTimeout(()=>{Al(e,{kit:M.id,params:N,name:n.name}).then(A=>{A.ok||i(String(A.error))})},280)},k=async()=>{if(M){w(!0);try{const j=await Al(e,{kit:M.id,params:x,name:Sd(e.getStage(),l(M)),position:s()});j.ok?a(String(j.id)):i(String(j.error))}catch(j){i(j.message)}finally{w(!1)}}},T=R.useMemo(()=>gm(m,c),[m,c]);return M?t.jsxs("div",{className:"shot-model-edit",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("button",{className:"pill-btn thin",onClick:()=>{C&&a(null),p(null)},children:["← ",o("Thư viện")]}),t.jsx(Ac,{id:M.id,alt:l(M),small:!0}),t.jsx("strong",{children:l(M)}),C&&t.jsx("small",{className:"muted",children:o("Đang sửa: {0}",[n.name])})]}),t.jsx("div",{className:"shot-model-params",children:M.params.map(j=>t.jsx(xx,{spec:j,value:S[j.key]??Nl(M.id)[j.key],locale:r,onChange:L=>y(j.key,L)},j.key))}),!C&&t.jsx("button",{className:"pill-btn primary",disabled:v,onClick:()=>void k(),children:v?o("Đang dựng model…"):o("Thêm vào cảnh")}),t.jsx("small",{className:"muted",children:C?o("Thay đổi được dựng lại ngay trên cảnh. Kích thước tính bằng mét thật."):o("Model đặt ở giữa khung nhìn, mặt trước hướng +Z. Kích thước tính bằng mét thật.")})]}):t.jsxs("div",{className:"shot-model-lib",children:[t.jsx("input",{type:"search",className:"shot-model-search","aria-label":o("Tìm model"),placeholder:o("Tìm: nhà phố, sofa, ô tô…"),value:m,onChange:j=>d(j.target.value)}),t.jsx("div",{className:"shot-model-groups",role:"group","aria-label":o("Nhóm model"),children:[{id:"all",vi:"Tất cả",en:"All"},...xm].map(j=>t.jsx("button",{className:`pill-btn thin${c===j.id?" on":""}`,"aria-pressed":c===j.id,onClick:()=>u(j.id),children:l(j)},j.id))}),t.jsxs("div",{className:"shot-model-grid",children:[T.map(j=>t.jsxs("button",{className:"shot-model-card","aria-label":`${o("Chọn model")} ${l(j)}`,onClick:()=>{p(j.id),g(Nl(j.id))},children:[t.jsx(Ac,{id:j.id,alt:""}),t.jsx("strong",{children:l(j)}),t.jsxs("small",{children:[j.params.length," ",o("tham số")]})]},j.id)),!T.length&&t.jsx("p",{className:"muted",children:o("Không có model nào khớp.")})]})]})}function Ac({id:e,alt:n,small:s}){const[a,i]=R.useState(null),[r,l]=R.useState(!1),c=R.useRef(null);R.useEffect(()=>{if(r||!c.current||typeof IntersectionObserver>"u"){r||l(!0);return}const m=new IntersectionObserver(d=>{d.some(f=>f.isIntersecting)&&(l(!0),m.disconnect())},{rootMargin:"160px"});return m.observe(c.current),()=>m.disconnect()},[r]),R.useEffect(()=>{if(!r)return;let m=!0;return i(null),cx(e).then(d=>{m&&i(d)}).catch(()=>{}),()=>{m=!1}},[r,e]);const u=`shot-model-thumb${s?" small":""}`;return a?t.jsx("img",{className:u,src:a,alt:n,draggable:!1,"data-kit":e}):t.jsx("span",{ref:c,className:`${u} loading`,role:n?"img":void 0,"aria-label":n||void 0,"aria-hidden":n?void 0:!0,children:t.jsx(wd,{})})}function xx({spec:e,value:n,locale:s,onChange:a}){const i=s==="en"?e.en:e.vi;if(e.type==="num"||e.type==="int"){const r=Number(n);return t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"range","aria-label":i,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>a(+l.target.value)}),t.jsx("input",{type:"number","aria-label":`${i} (${o("số")})`,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>{const c=+l.target.value;Number.isFinite(c)&&a(Math.min(e.max,Math.max(e.min,c)))}})]})}return e.type==="choice"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>a(r.target.value),children:e.options.map(r=>t.jsx("option",{value:r.id,children:s==="en"?r.en:r.vi},r.id))})]}):e.type==="material"?t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("select",{"aria-label":i,value:String(n),onChange:r=>a(r.target.value),children:e.allowed.map(r=>t.jsx("option",{value:r,children:bx(r,s)},r))})]}):e.type==="text"?t.jsxs("label",{className:"shot-model-param shot-model-text",children:[t.jsx("span",{children:i}),t.jsx("textarea",{"aria-label":i,rows:2,maxLength:e.max,value:String(n),onChange:r=>a(r.target.value)})]}):t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:i}),t.jsx("input",{type:"color","aria-label":i,value:String(n),onChange:r=>a(r.target.value)})]})}const bx=(e,n)=>Nc[e]?Nc[e][n==="en"?1:0]:e;function Md({value:e,onChange:n,label:s,none:a}){const i=ht();return t.jsxs("select",{"aria-label":s,value:e,onChange:r=>n(r.target.value),children:[a&&t.jsx("option",{value:"",children:a}),_h.map(r=>t.jsx("optgroup",{label:i==="en"?r.en:r.vi,children:ym.filter(l=>l.cat===r.id).map(l=>t.jsx("option",{value:l.id,children:wa(l,i==="en"?"en":"vi")},l.id))},r.id))]})}function yx({item:e,change:n}){const s=e.materials?.[qs]?.preset??"";return t.jsxs("label",{className:"shot-model-param shot-model-whole",children:[t.jsx("span",{children:o("Vật liệu cả model")}),t.jsx(Md,{label:o("Vật liệu cả model"),value:s,none:o("Theo từng khối"),onChange:a=>n(i=>zs(i,e.id,qs,a?{preset:a}:null))})]})}function Sd(e,n){let s=n,a=2;for(;e.items.some(i=>i.name===s);)s=`${n} ${a++}`;return s}const Tc={box:()=>({shape:"box",name:"Hộp",size:[1,1,1],position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cylinder:()=>({shape:"cylinder",name:"Trụ",size:[.5,1,.5],position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),cone:()=>({shape:"cone",name:"Nón",size:[.8,1,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),sphere:()=>({shape:"sphere",name:"Cầu",size:[.8,.8,.8],position:[0,0,0],rotation:[0,0,0],look:{preset:"plastic_matte"}}),stairs:()=>({shape:"stairs",name:"Bậc thang",size:[1.2,1.5,2.5],steps:9,position:[0,0,0],rotation:[0,0,0],look:{preset:"concrete"}}),wall_door:()=>({shape:"extrude",name:"Tường có cửa",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.45,0],[.45,0],[.45,2.1],[-.45,2.1]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),wall_window:()=>({shape:"extrude",name:"Tường có cửa sổ",outline:[[-2,0],[2,0],[2,3],[-2,3]],holes:[[[-.7,.9],[.7,.9],[.7,2.2],[-.7,2.2]]],depth:.2,position:[0,0,0],rotation:[0,0,0],look:{preset:"painted_wood"}}),cut_box:()=>({shape:"box",name:"Khoét",size:[.5,.5,2],position:[0,.25,0],rotation:[0,0,0],op:"subtract"}),cut_cylinder:()=>({shape:"cylinder",name:"Lỗ tròn",size:[.4,2,.4],position:[0,-.5,0],rotation:[0,0,0],op:"subtract"}),arch:()=>({shape:"extrude",name:"Cổng vòm",outline:[[-1.5,0],[1.5,0],[1.5,3.2],[-1.5,3.2]],holes:[[[-.8,0],[.8,0],[.8,1.8],...Array.from({length:9},(e,n)=>{const s=(n+1)*Math.PI/10;return[+(.8*Math.cos(s)).toFixed(3),+(1.8+.8*Math.sin(s)).toFixed(3)]}),[-.8,1.8]]],depth:.4,position:[0,0,0],rotation:[0,0,0],look:{preset:"brick_white"}})},vx=[["box","Hộp"],["cylinder","Trụ"],["cone","Nón"],["sphere","Cầu"],["stairs","Bậc thang"],["wall_door","Tường có cửa"],["wall_window","Tường có cửa sổ"],["arch","Cổng vòm"],["cut_box","Khoét hộp"],["cut_cylinder","Khoét lỗ tròn"]],jx={union:"Hợp (gộp vào)",subtract:"Trừ (khoét)",intersect:"Giao (giữ phần chung)"},kx={union:"gộp vào",subtract:"khoét",intersect:"giao với"};function wx({stage:e,change:n,engine:s,onSelect:a,ground:i,setError:r,item:l}){const c=ht(),[u,m]=R.useState(null),[d,f]=R.useState(0),[p,x]=R.useState(.05),g=l?.set?.id;R.useEffect(()=>{f(0),m(g?s?.setRecipe(g)??null:null)},[g,s]);const v=R.useRef(void 0),w=(N,A=l)=>{if(!A?.set)return;let O;try{O=Tl(N)}catch($){r($.message);return}m(O),s?.cacheSet(A.set.id,O);const _=Ll(O);n($=>({...$,items:$.items.map(P=>P.id===A.id?{...P,set:{...P.set,parts:O.parts.length,min:_.min,max:_.max}}:P)})),window.clearTimeout(v.current),v.current=window.setTimeout(()=>{nc(A.set.id,A.name,O).catch($=>r($.message))},400)},C=async()=>{const N=crypto.randomUUID(),A=Sd(e,o("Model tự dựng")),O=Tl({v:1,parts:[Tc.box()]});try{await nc(N,A,O)}catch(P){r(P.message);return}s?.cacheSet(N,O);const _=Ll(O),$=Oh(e,{kind:"set",name:A,color:"#9aa3a8",position:i(),set:{id:N,name:A,parts:1,min:_.min,max:_.max,kit:{id:ka,params:{}}}});n(P=>({...P,items:[...P.items,$]})),a($.id)};if(!l||!u)return t.jsxs("div",{className:"shot-model-hand-empty",children:[t.jsx("p",{className:"muted",children:o("Tự dựng model từ khối cơ bản: hộp, trụ, nón, cầu, bậc thang, tường có cửa, cổng vòm. Mọi kích thước tính bằng mét.")}),t.jsx("button",{className:"pill-btn primary",onClick:()=>void C(),children:o("+ Tạo model mới")}),l&&!u&&t.jsx("p",{className:"muted",children:o("Đang tải model…")})]});const M=u.parts,S=M[Math.min(d,M.length-1)],I=N=>+(Math.round(N/p)*p).toFixed(3),y=N=>w({...u,parts:M.map((A,O)=>O===d?{...A,...N}:A)}),k=N=>{const A=Tc[N]();w({...u,parts:[...M,A]}),f(M.length)},T=(N,A,O,_=-500)=>t.jsxs("div",{className:"shot-model-vec",children:[t.jsx("span",{children:N}),["X","Y","Z"].map(($,P)=>t.jsx("input",{type:"number",step:p,"aria-label":`${N} ${$}`,value:A[P],onChange:W=>{const z=+W.target.value;if(!Number.isFinite(z))return;const Q=[...A];Q[P]=Math.max(_,I(z)),O(Q)}},$))]}),j=N=>{const A=(N.outline||[]).map(_=>_[0]),O=(N.outline||[]).map(_=>_[1]);return[+(Math.max(...A)-Math.min(...A)).toFixed(3),+(Math.max(...O)-Math.min(...O)).toFixed(3),N.depth||.2]},L=(N,A)=>{const[O,_]=j(N),$=A[0]/(O||1),P=A[1]/(_||1),W=z=>z.map(([Q,J])=>[+(Q*$).toFixed(3),+(J*P).toFixed(3)]);return{outline:W(N.outline||[]),holes:N.holes?.map(W),depth:Math.max(.005,A[2])}};return t.jsxs("div",{className:"shot-model-hand",children:[t.jsxs("div",{className:"shot-model-edit-head",children:[t.jsxs("strong",{children:["✎ ",l.name]}),t.jsxs("small",{className:"muted",children:[M.length," ",o("khối")]}),t.jsxs("label",{className:"shot-model-snap",children:[o("Bước lưới"),t.jsx("select",{"aria-label":o("Bước lưới"),value:p,onChange:N=>x(+N.target.value),children:mx.map(N=>t.jsx("option",{value:N,children:N<.1?`${N*100} cm`:`${N} m`},N))})]})]}),t.jsx("div",{className:"shot-model-add",role:"group","aria-label":o("Thêm khối"),children:vx.map(([N,A])=>t.jsxs("button",{className:"pill-btn thin",onClick:()=>k(N),children:["+ ",o(A)]},N))}),t.jsx("ul",{className:"shot-model-parts","aria-label":o("Các khối"),children:M.map((N,A)=>t.jsx("li",{children:t.jsxs("button",{className:A===d?"on":"",onClick:()=>f(A),children:[N.name||N.shape," ",t.jsx("small",{children:px[N.shape]?.[c==="en"?1:0]??N.shape})]})},A))}),S&&t.jsxs("div",{className:"shot-model-part",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Tên khối")}),t.jsx("input",{"aria-label":o("Tên khối"),maxLength:40,value:S.name||"",onChange:N=>y({name:N.target.value.slice(0,40)})})]}),S.shape==="extrude"?T(o("Rộng / cao / dày (m)"),j(S),N=>y(L(S,N)),.005):T(o("Kích thước (m)"),S.size||[1,1,1],N=>y({size:N.map(A=>Math.max(.005,A))}),.005),T(o("Vị trí (m)"),S.position,N=>y({position:N})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Xoay quanh trục đứng (°)")}),t.jsx("input",{type:"number","aria-label":o("Xoay quanh trục đứng (°)"),step:15,value:S.rotation[1],onChange:N=>{const A=+N.target.value;Number.isFinite(A)&&y({rotation:[S.rotation[0],Math.max(-360,Math.min(360,A)),S.rotation[2]]})}})]}),S.shape==="stairs"&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Số bậc")}),t.jsx("input",{type:"number","aria-label":o("Số bậc"),min:2,max:80,value:S.steps||10,onChange:N=>y({steps:Math.max(2,Math.min(80,Math.round(+N.target.value)||2))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Phép khối")}),t.jsxs("select",{"aria-label":o("Phép khối"),value:S.op||"",onChange:N=>{const A=N.target.value||void 0;y(A?{op:A}:{op:void 0,target:void 0})},children:[t.jsx("option",{value:"",children:o("Khối thường")}),bm.map(N=>t.jsx("option",{value:N,children:o(jx[N])},N))]})]}),S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Tác động lên")}),t.jsxs("select",{"aria-label":o("Tác động lên"),value:S.target||"",onChange:N=>y({target:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Khối liền trước")}),M.slice(0,d).filter(N=>!N.op&&N.name&&!N.repeat&&!N.mirror).map((N,A)=>t.jsx("option",{value:N.name,children:N.name},A))]})]}),S.op&&t.jsx("small",{className:"muted",children:hi(M,d)>=0?o("Khối này không hiện; nó {0} “{1}”.",[o(kx[S.op]),M[hi(M,d)].name||M[hi(M,d)].shape]):o("Cần một khối thường phía trước để tác động.")}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Vật liệu")}),t.jsx(Md,{label:o("Vật liệu"),value:Es(S)?.preset??"painted_wood",onChange:N=>y({look:{preset:N,...Es(S)?.params?.color?{params:{color:Es(S).params.color}}:{}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})})]}),!S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Màu")}),t.jsx("input",{type:"color","aria-label":o("Màu khối"),value:Es(S)?.params?.color||Oa(Es(S)?.preset??"")?.colors[0]||"#cccccc",onChange:N=>{const A=Es(S)??{preset:"painted_wood"};y({look:{...A,params:{...A.params||{},color:N.target.value}},material:void 0,color:void 0,roughness:void 0,metalness:void 0})}})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Bo cạnh (m)")}),t.jsx("input",{type:"number","aria-label":o("Bo cạnh (m)"),min:0,max:.5,step:.005,value:S.bevel??0,onChange:N=>y({bevel:Math.max(0,Math.min(.5,+N.target.value||0))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Nhân bản (số bản)")}),t.jsx("input",{type:"number","aria-label":o("Nhân bản (số bản)"),min:1,max:200,value:S.repeat?.count??1,onChange:N=>{const A=Math.max(1,Math.min(200,Math.round(+N.target.value)||1));y({repeat:A>1?{count:A,offset:S.repeat?.offset??[1,0,0],yaw:S.repeat?.yaw??0}:void 0})}})]}),S.repeat&&T(o("Khoảng cách bản sao (m)"),S.repeat.offset,N=>y({repeat:{...S.repeat,offset:N}})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:o("Đối xứng")}),t.jsxs("select",{"aria-label":o("Đối xứng"),value:S.mirror||"",onChange:N=>y({mirror:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Không")}),t.jsx("option",{value:"x",children:o("Trái – phải (X)")}),t.jsx("option",{value:"z",children:o("Trước – sau (Z)")}),t.jsx("option",{value:"xz",children:o("Cả hai")})]})]}),t.jsxs("div",{className:"shot-model-actions",children:[t.jsx("button",{className:"pill-btn thin",onClick:()=>{w({...u,parts:[...M,{...S,name:`${S.name||S.shape} 2`,position:[I(S.position[0]+.5),S.position[1],S.position[2]]}]}),f(M.length)},children:o("Nhân đôi khối")}),t.jsx("button",{className:"pill-btn thin",disabled:M.length<2,onClick:()=>{w({...u,parts:M.filter((N,A)=>A!==d)}),f(Math.max(0,d-1))},children:o("Xoá khối")})]})]})]})}function Mx({loop:e,onLoop:n,range:s,rangeOn:a,onRangeOn:i,onEnd:r,onKeyAll:l,onCopy:c,onPaste:u,canPaste:m,onEase:d,onNudge:f,stage:p,cameraActive:x,cameraHidden:g,cameraLocked:v,onToggle:w,onProp:C,shot:M,items:S,time:I,fxBars:y,onFxTiming:k,onParent:T,playing:j,selected:L,picked:N=[],onPick:A,onSeek:O,onPlay:_,onRow:$,onSelect:P,onAdd:W,onMove:z,onDelete:Q,height:J,onHeight:V}){ht();const[B,q]=R.useState(1),[D,ee]=R.useState(220),Z=J??D,xe=G=>{ee(G),V?.(G)},[be,U]=R.useState(null),[pe,me]=R.useState({}),[X,re]=R.useState(!0),ue=R.useRef(void 0),Ee=R.useRef(null),[ye,ne]=R.useState(null),Ie=(G,Se)=>N.some(le=>le.row===G&&le.id===Se),ze=(G,Se,le)=>{if(G.button!==0||!Ee.current)return;G.preventDefault(),ue.current?.();const $e=Ee.current,Le=$e.parentElement,Te=$e.getBoundingClientRect(),Je=G.clientX-Te.left,ke=G.clientY-Te.top,Ue=G.pointerId,At=G.shiftKey,qe=()=>{const rt=$e.getBoundingClientRect();return[rt.left+Je,rt.top+ke]};$e.setPointerCapture(Ue);let mt=!1;const kt=(rt,Tt)=>{const[Rt,sn]=qe(),Sn=Math.min(Rt,rt),Ns=Math.max(Rt,rt),As=Math.min(sn,Tt),Pn=Math.max(sn,Tt),an=At?[...N]:[];return $e.querySelectorAll(".shot-time-key:not([disabled]),.shot-prop-key[data-key]").forEach(xn=>{const oe=xn.getBoundingClientRect(),Ne=oe.left+oe.width/2,Oe=oe.top+oe.height/2;Ne>=Sn&&Ne<=Ns&&Oe>=As&&Oe<=Pn&&!an.some(Re=>Re.row===xn.dataset.row&&Re.id===xn.dataset.key)&&an.push({row:xn.dataset.row,id:xn.dataset.key})}),an};let Xe=[G.clientX,G.clientY],it=0;const xt=()=>{const[rt,Tt]=qe(),[Rt,sn]=Xe,Sn=$e.getBoundingClientRect();ne({x:Math.min(rt,Rt)-Sn.left,y:Math.min(Tt,sn)-Sn.top,w:Math.abs(Rt-rt),h:Math.abs(sn-Tt)}),A?.(kt(Rt,sn))},wt=()=>{if(it=0,!mt||!Le)return;const rt=Le.getBoundingClientRect(),Tt=Xe[1],Rt=Tt<rt.top+28?-Math.ceil((rt.top+28-Tt)/3):Tt>rt.bottom-16?Math.ceil((Tt-rt.bottom+16)/3):0;if(!Rt)return;const sn=Le.scrollTop;Le.scrollTop+=Rt,Le.scrollTop!==sn&&(xt(),it=requestAnimationFrame(wt))},nn=rt=>{if(rt.pointerId!==Ue)return;const[Tt,Rt]=qe();!mt&&Math.hypot(rt.clientX-Tt,rt.clientY-Rt)<4||(mt=!0,Xe=[rt.clientX,rt.clientY],xt(),it||(it=requestAnimationFrame(wt)))},cn=()=>{it&&cancelAnimationFrame(it),it=0,$e.removeEventListener("pointermove",nn),$e.removeEventListener("pointerup",_t),$e.removeEventListener("pointercancel",cn),$e.hasPointerCapture(Ue)&&$e.releasePointerCapture(Ue),ne(null)},_t=rt=>{if(cn(),mt)A?.(kt(rt.clientX,rt.clientY));else{$(Se);const Tt=le.getBoundingClientRect();O(Math.max(0,Math.min(1,(rt.clientX-Tt.left)/Tt.width)))}};ue.current=cn,$e.addEventListener("pointermove",nn),$e.addEventListener("pointerup",_t),$e.addEventListener("pointercancel",cn)};R.useEffect(()=>()=>ue.current?.(),[]);const[we,de]=R.useState(null),H=(G,Se,le,$e)=>{const Le=y?.[Se];if(G.button!==0||!Le||!k)return;G.preventDefault(),G.stopPropagation(),ue.current?.();const Te=G.currentTarget,Je=G.pointerId,ke=G.clientX,Ue=$e.getBoundingClientRect().width,At=M.duration,qe=.2;Te.setPointerCapture(Je);let mt={id:Se,start:Le.start,duration:Le.duration};const kt=wt=>Math.round(wt*20)/20,Xe=wt=>{if(wt.pointerId!==Je)return;const nn=(wt.clientX-ke)/Ue*At;if(le==="move")mt={id:Se,start:kt(Math.max(0,Math.min(At-qe,Le.start+nn))),duration:Le.duration};else if(le==="start"){const cn=Le.start+Le.duration,_t=kt(Math.max(0,Math.min(cn-qe,Le.start+nn)));mt={id:Se,start:_t,duration:+(cn-_t).toFixed(2)}}else mt={id:Se,start:Le.start,duration:kt(Math.max(qe,Le.duration+nn))};de(mt)},it=()=>{Te.removeEventListener("pointermove",Xe),Te.removeEventListener("pointerup",xt),Te.removeEventListener("pointercancel",it),Te.hasPointerCapture(Je)&&Te.releasePointerCapture(Je),de(null)},xt=()=>{it(),(mt.start!==Le.start||mt.duration!==Le.duration)&&k(Se,{start:mt.start,duration:mt.duration})};ue.current=it,Te.addEventListener("pointermove",Xe),Te.addEventListener("pointerup",xt),Te.addEventListener("pointercancel",it)},se=[{id:"camera",kind:"camera",name:"📷 Camera",locked:!!v,hidden:!!g,keys:M.motion==="path"?M.cameraKeys||[]:[]},...S.map(G=>({id:G.id,kind:G.kind==="fx"?"fx":G.kind==="person"?"person":"object",name:G.kind==="fx"?`✦ ${G.name}`:G.name,locked:G.locked,hidden:G.hidden,keys:M.objectKeys?.[G.id]||[],fx:G.kind==="fx",parent:G.fx?.attach?.to??""}))],he=S.filter(G=>G.kind!=="fx"&&!G.hidden),ce=(L?se.filter(G=>G.id===L.row):se).flatMap(G=>G.keys.map(Se=>Se.time)).sort((G,Se)=>G-Se),Pe=G=>{const Se=G>0?ce.find(le=>le>I+1e-4):[...ce].reverse().find(le=>le<I-1e-4);Se!==void 0&&O(Se)},Be=(G,Se)=>{if(G.button!==0)return;G.preventDefault(),G.stopPropagation(),ue.current?.();const le=G.pointerId;Se.setPointerCapture(le);const $e=ke=>{const Ue=Se.getBoundingClientRect(),At=Math.max(0,Math.min(1,(ke.clientX-Ue.left)/Ue.width)),qe=rn(M);O(Math.min(1,Math.round(At*M.duration*qe)/qe/M.duration))},Le=ke=>{ke.pointerId===le&&$e(ke)},Te=()=>{Se.removeEventListener("pointermove",Le),Se.removeEventListener("pointerup",Je),Se.removeEventListener("pointercancel",Te),Se.removeEventListener("lostpointercapture",Te),Se.hasPointerCapture(le)&&Se.releasePointerCapture(le)},Je=ke=>{$e(ke),Te()};ue.current=Te,Se.addEventListener("pointermove",Le),Se.addEventListener("pointerup",Je),Se.addEventListener("pointercancel",Te),Se.addEventListener("lostpointercapture",Te),$e(G)},ot=(G,Se,le,$e)=>{G.preventDefault(),G.stopPropagation(),P(Se,le);const Le=$e.getBoundingClientRect();let Te;const Je=At=>{if(Te=Math.max(0,Math.min(1,(At.clientX-Le.left)/Le.width)),X){const qe=rn(M);Te=Math.min(1,Math.round(Te*M.duration*qe)/qe/M.duration);const mt=se.flatMap(kt=>kt.keys.filter(Xe=>!(kt.id===Se&&Xe.id===le)).map(Xe=>Xe.time)).find(kt=>Math.abs(kt-Te)*Le.width<6);mt!==void 0&&(Te=mt)}U({row:Se,id:le,time:Te})},ke=()=>{window.removeEventListener("mousemove",Je),window.removeEventListener("mouseup",Ue),U(null)},Ue=()=>{ke(),Te!==void 0&&z(Se,le,Te)};ue.current?.(),ue.current=ke,window.addEventListener("mousemove",Je),window.addEventListener("mouseup",Ue)};return t.jsxs("section",{className:"shot-timeline","aria-label":o("Timeline keyframe"),style:{height:Z},children:[t.jsx("div",{className:"shot-timeline-tools",children:(()=>{const G=rn(M),Se=M.duration,le=I*Se,$e=Je=>{const ke=Math.floor(Je/60),Ue=Je-ke*60;return`${String(ke).padStart(2,"0")}:${Ue.toFixed(2).padStart(5,"0")}`},Le=Je=>{O(Math.max(0,Math.min(1,(Math.round(le*G)+Je)/G/Se)))},Te=N.length?!1:!L||se.find(Je=>Je.id===L.row)?.locked;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-tc",children:[t.jsxs("span",{children:[$e(le)," / ",$e(Se)]}),t.jsx("small",{children:o("Khung {0} / {1} · {2} fps",[Math.round(le*G),Math.round(Se*G),G])})]}),t.jsxs("div",{className:"shot-transport",role:"group","aria-label":o("Điều khiển phát"),children:[t.jsx("button",{className:"shot-tp-btn",onClick:()=>O(0),"aria-label":o("Về đầu"),title:o("Về đầu")+" (Home)",children:t.jsx(Ce.skipStart,{})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>Le(-1),disabled:le<=1e-6,"aria-label":o("Lùi 1 khung hình"),title:o("Lùi 1 khung hình")+" (,)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M15 6v12L7 12z"}),t.jsx("rect",{x:"17",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:"shot-tp-play",onClick:_,"aria-label":j?o("Tạm dừng"):o("Phát"),title:(j?o("Tạm dừng"):o("Phát"))+" (Space)",children:j?t.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:[t.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",rx:"1"}),t.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",rx:"1"})]}):t.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":!0,fill:"currentColor",children:t.jsx("path",{d:"M8 5.5v13l11-6.5z"})})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>Le(1),disabled:le>=Se-1e-6,"aria-label":o("Tới 1 khung hình"),title:o("Tới 1 khung hình")+" (.)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"19",height:"19","aria-hidden":!0,fill:"currentColor",children:[t.jsx("path",{d:"M9 6v12l8-6z"}),t.jsx("rect",{x:"5",y:"6",width:"2",height:"12",rx:"1"})]})}),t.jsx("button",{className:`shot-tp-btn${e?" on":""}`,"data-tool":"loop",onClick:n,disabled:!n,"aria-pressed":!!e,"aria-label":o("Phát lặp"),title:o("Phát lặp")+" (L)",children:t.jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M20 12a8 8 0 1 1-2.6-5.9"}),t.jsx("path",{d:"M20 4v4.5h-4.5"})]})})]}),t.jsxs("div",{className:"shot-tl-right",children:[t.jsx("button",{className:"shot-tp-del",disabled:Te,onClick:Q,"aria-label":N.length>1?o("Xoá {0} key",[N.length]):o("Xoá key"),title:N.length>1?o("Xoá {0} key",[N.length]):o("Xoá key"),children:t.jsx("svg",{viewBox:"0 0 24 24",width:"15",height:"15","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"})})}),t.jsxs("label",{children:[o("Zoom")," ",t.jsx("input",{"aria-label":o("Zoom timeline"),type:"range",min:1,max:8,step:.5,value:B,onChange:Je=>q(+Je.target.value)})]}),t.jsxs("label",{children:[o("Cao")," ",t.jsx("input",{"aria-label":o("Chiều cao timeline"),type:"range",min:140,max:360,step:20,value:Z,onChange:Je=>xe(+Je.target.value)})]})]})]})})()}),t.jsx("div",{className:"shot-edit-bar",role:"toolbar","aria-label":o("Công cụ keyframe"),children:(()=>{const G=N.length?N:L?[L]:[],Se=G.length>0,le=L?.row,$e=(qe,mt)=>mt?`${o(qe)} (${mt})`:o(qe),Le=(qe,mt,kt,Xe,it={})=>t.jsx("button",{type:"button",className:`shot-edit-btn${it.on?" on":""}`,"data-tool":qe,"aria-label":o(kt),"aria-pressed":it.on===void 0?void 0:it.on,title:$e(kt,it.key),disabled:it.disabled||!Xe,onClick:Xe,children:mt},qe),Te=qe=>t.jsx("i",{className:"shot-edit-sep","aria-hidden":!0},qe),Je=qe=>t.jsx("svg",{viewBox:"0 0 20 20",width:"18",height:"18","aria-hidden":!0,fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:qe}),ke=(qe,mt,kt)=>Le("ease-"+qe,Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M3 17h14M3 3v14"}),t.jsx("path",{d:kt})]})),mt,()=>d?.(qe),{disabled:!Se||!d}),Ue=()=>{q(1),requestAnimationFrame(()=>{const qe=Ee.current?.parentElement;qe&&(qe.scrollLeft=0)})},At=()=>{const qe=se.flatMap(it=>it.keys.filter(xt=>G.some(wt=>wt.row===it.id&&wt.id===xt.id)).map(xt=>xt.time)),mt=Math.min(...qe),kt=Math.max(...qe),Xe=Math.min(8,Math.max(1,.8/Math.max(.02,kt-mt)));q(Xe),requestAnimationFrame(()=>{const it=Ee.current?.parentElement;it&&(it.scrollLeft=Math.max(0,(mt-.05/Xe)*it.clientWidth*Xe))})};return t.jsxs(t.Fragment,{children:[Le("add",Is.key,"Thêm key trên hàng đang chọn",le?()=>W(le):void 0,{key:"K",disabled:!le}),Le("key-all",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m7 4 4 5.5L7 15 3 9.5z"}),t.jsx("path",{d:"m13 4 4 5.5-4 5.5"})]})),"Key tất cả: camera và mọi hàng chưa khoá",l,{key:"⇧K"}),Le("key-prev",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m11 5-5 5 5 5"}),t.jsx("path",{d:"m15 7 3 3-3 3-3-3z"})]})),"Key trước",ce.some(qe=>qe<I-1e-4)?()=>Pe(-1):void 0),Le("key-next",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"m9 5 5 5-5 5"}),t.jsx("path",{d:"m5 7 3 3-3 3-3-3z"})]})),"Key sau",ce.some(qe=>qe>I+1e-4)?()=>Pe(1):void 0),Te("s1"),Le("copy",Is.copy,"Copy các key đang chọn",Se?c:void 0,{key:"⌘C",disabled:!Se}),Le("paste",Is.paste,"Dán key tại playhead (giữ khoảng cách)",u,{key:"⌘V",disabled:!m}),Te("s2"),ke("linear","Easing: Tuyến tính","M3 17 17 3"),ke("in","Easing: Vào chậm (ease in)","M3 17C10 17 14 12 17 3"),ke("snap","Easing: Ra chậm (ease out)","M3 17C6 8 10 3 17 3"),ke("smooth","Easing: Vào và ra chậm (ease in-out)","M3 17C10 17 10 3 17 3"),ke("hold","Easing: Giữ nguyên (hold)","M3 17h7V3h7"),Te("s3"),Le("nudge-back",Je(t.jsx("path",{d:"m12 5-5 5 5 5M16 4v12"})),"Dịch key lùi 1 khung hình",Se?()=>f?.(-1):void 0,{key:"Alt+,",disabled:!Se}),Le("nudge-fwd",Je(t.jsx("path",{d:"m8 5 5 5-5 5M4 4v12"})),"Dịch key tới 1 khung hình",Se?()=>f?.(1):void 0,{key:"Alt+.",disabled:!Se}),Te("s4"),Le("range",Je(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M5 4v12M15 4v12"}),t.jsx("path",{d:"M5 10h10",strokeDasharray:"2 2"})]})),s?"Chỉ phát trong vùng I–O":"Chỉ phát trong vùng (đặt I và O trước)",s?i:void 0,{key:"I / O",on:!!a,disabled:!s}),Le("snap",Is.magnet,"Bám khung hình và key khác khi kéo key",()=>re(qe=>!qe),{on:X}),Te("s5"),Le("zoom-fit",Is.fit,"Thu phóng vừa cả shot",Ue),Le("zoom-sel",Is.zoomIn,"Thu phóng vào các key đang chọn",Se?At:void 0,{disabled:!Se}),Le("end",Je(t.jsx("path",{d:"m6 5 5 5-5 5M15 4v12"})),"Về cuối",r,{key:"End"})]})})()}),t.jsx("div",{className:"shot-timeline-scroll",children:t.jsxs("div",{className:"shot-timeline-content",ref:Ee,style:{width:`${B*100}%`},children:[ye&&t.jsx("div",{className:"shot-marquee",style:{left:ye.x,top:ye.y,width:ye.w,height:ye.h}}),t.jsxs("div",{className:"shot-time-row shot-ruler-row",children:[t.jsx("div",{className:"shot-track-name",children:o("Đối tượng")}),t.jsxs("div",{className:"shot-time-ruler",onPointerDown:G=>Be(G,G.currentTarget),children:[(M.lockUntil??0)>0&&t.jsx("div",{className:"shot-lock-band",role:"img",style:{width:`${Math.min(1,M.lockUntil/M.duration)*100}%`},"aria-label":o("Đã khoá 0–{0}s cho Agent",[String(Math.round(Math.min(M.lockUntil,M.duration)*100)/100)]),title:o("Agent không sửa phần này"),children:t.jsx("span",{children:"🔒"})}),s&&t.jsx("div",{className:`shot-range${a?" on":""}`,style:{left:`${s.in*100}%`,width:`${Math.max(0,s.out-s.in)*100}%`},"aria-hidden":!0}),t.jsx("button",{className:"shot-playhead-handle",role:"slider","aria-label":o("Vị trí phát timeline"),"aria-valuemin":0,"aria-valuemax":M.duration,"aria-valuenow":Number((I*M.duration).toFixed(2)),style:{left:`${I*100}%`},onKeyDown:G=>{const Se=G.shiftKey?1:.1,le=1/rn(M);["ArrowLeft","ArrowRight","Home","End",",","."].includes(G.key)&&(G.preventDefault(),O(G.key==="Home"?0:G.key==="End"?1:G.key===","||G.key==="."?Math.max(0,Math.min(1,Math.round(I*M.duration/le+(G.key==="."?1:-1))*le/M.duration)):Math.max(0,Math.min(1,I+(G.key==="ArrowRight"?Se:-Se)/M.duration))))}}),Array.from({length:11},(G,Se)=>t.jsxs("span",{style:{left:`${Se*10}%`},children:[Number((M.duration*Se/10).toFixed(2)),o("s")]},Se))]})]}),se.map(G=>{const Se=p&&pe[G.id]?Q0(p,G.id):[];return t.jsxs(R.Fragment,{children:[t.jsxs("div",{className:`shot-time-row${G.id==="camera"&&x?" camera-active":""}${G.hidden?" is-hidden":""}${G.locked?" is-locked":""}`,children:[t.jsxs("div",{className:"shot-track-name",children:[w&&t.jsx("button",{className:`shot-row-eye${G.hidden?" off":""}`,"aria-pressed":!G.hidden,"aria-label":G.hidden?o("Hiện {0}",[G.name]):o("Ẩn {0}",[G.name]),title:G.id==="camera"?G.hidden?o("Hiện camera trong khung nhìn"):o("Ẩn camera khỏi khung nhìn (không ảnh hưởng ảnh xuất)"):G.hidden?o("Hiện trong cảnh và khi xuất"):o("Ẩn khỏi cảnh và khi xuất"),onClick:()=>w(G.id,"hidden"),children:G.hidden?"◌":"◉"}),p&&t.jsx("button",{className:`shot-row-keys${G.keys.length?" keyed":""}${pe[G.id]?" open":""}`,"aria-expanded":!!pe[G.id],"aria-label":o("Thuộc tính {0}",[G.name]),title:o("Mở / đóng các thuộc tính keyframe"),onClick:()=>me(le=>({...le,[G.id]:!le[G.id]})),children:"◆"}),w&&t.jsx("button",{className:`shot-row-lock${G.locked?" on":""}`,"aria-pressed":G.locked,"aria-label":G.locked?o("Mở khoá {0}",[G.name]):o("Khoá {0}",[G.name]),title:G.locked?o("Mở khoá: cho chọn và kéo"):o("Khoá: không chọn, không kéo, không sửa key"),onClick:()=>w(G.id,"locked"),children:G.locked?"🔒":"🔓"}),t.jsx("button",{className:"shot-row-name",title:G.name,onClick:()=>{G.locked||$(G.id)},children:G.name}),"fx"in G&&G.fx&&T&&t.jsxs("select",{className:"shot-track-parent","aria-label":o("Parent của {0}",[G.name]),title:o("Parent: hiệu ứng đi theo đối tượng này"),disabled:G.locked,value:G.parent,onChange:le=>T(G.id,le.target.value),children:[t.jsx("option",{value:"",children:o("Tự do")}),he.map(le=>t.jsxs("option",{value:le.id,children:["🔗 ",le.name]},le.id))]}),t.jsx("button",{"aria-label":o("Thêm key {0}",[G.name]),disabled:G.locked,onClick:()=>W(G.id),children:"+◆"})]}),t.jsxs("div",{className:"shot-key-track","data-row":G.id,onPointerDown:le=>{le.target.closest(".shot-time-key")||ze(le,G.id,le.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),(M.clipSpans?.[G.id]||[]).map(le=>t.jsx("div",{className:"shot-clip-block","data-clip-block":le.clip,style:{left:`${le.start/M.duration*100}%`,width:`${Math.max(.5,(Math.min(M.duration,le.end)-le.start)/M.duration*100)}%`},title:`${le.label} · ${le.start.toFixed(1)}–${le.end.toFixed(1)}s`,children:t.jsx("span",{children:le.label})},le.id)),(M.motionEdits?.[G.id]||[]).map(le=>t.jsx("div",{className:`shot-edit-mark${le.off?" off":""}`,"data-edit-mark":!0,style:{left:`${Math.max(0,le.start-(le.scope==="span"?0:le.fade))/M.duration*100}%`,width:`${((le.scope==="after"?M.duration:le.end+(le.scope==="span"?0:le.fade))-Math.max(0,le.start-(le.scope==="span"?0:le.fade)))/M.duration*100}%`},title:`${le.label||o("Chỉnh")} · ${(Number(le.start)||0).toFixed(1)}s`},le.id)),y?.[G.id]&&(()=>{const le=we?.id===G.id?we:y[G.id],$e=!!k&&!G.locked,Le=Te=>Te.currentTarget.closest(".shot-key-track");return t.jsx("div",{className:`shot-fx-bar${G.hidden||G.locked?" dim":""}${$e?" editable":""}${we?.id===G.id?" dragging":""}`,"data-fx-bar":G.id,title:o("Hiệu ứng: {0}s → {1}s · kéo để dời, kéo mép để đổi độ dài",[le.start.toFixed(2),(le.start+le.duration).toFixed(2)]),style:{left:`${Math.min(100,le.start/M.duration*100)}%`,width:`${Math.max(.6,Math.min(100-le.start/M.duration*100,le.duration/M.duration*100))}%`},onPointerDown:$e?Te=>H(Te,G.id,"move",Le(Te)):void 0,children:$e&&t.jsxs(t.Fragment,{children:[t.jsx("i",{className:"shot-fx-edge start","aria-hidden":!0,onPointerDown:Te=>H(Te,G.id,"start",Le(Te))}),t.jsx("i",{className:"shot-fx-edge end","aria-hidden":!0,onPointerDown:Te=>H(Te,G.id,"end",Le(Te))})]})})})(),!y?.[G.id]&&G.kind!=="fx"&&t.jsx("div",{className:`shot-dur-bar kind-${G.kind}${G.hidden||G.locked?" dim":""}`,"data-dur":G.id,title:G.kind==="camera"?o("Camera chạy suốt shot: 0s → {0}s",[M.duration]):o("Có mặt suốt shot: 0s → {0}s",[M.duration]),style:{left:"0%",width:"100%"}}),G.keys.map((le,$e)=>t.jsx("button",{"aria-label":`Key ${$e+1} ${G.name}`,title:o("{0}s · kéo để đổi thời điểm",[(le.time*M.duration).toFixed(2)]),disabled:G.locked,"data-row":G.id,"data-key":le.id,className:`shot-time-key ${"pose"in le&&le.pose?"pose":""} ${L?.row===G.id&&L.id===le.id||Ie(G.id,le.id)?"active":""}`,style:{left:`${(be?.id===le.id&&be.row===G.id?be.time:le.time)*100}%`},onClick:Le=>{Le.detail===0&&P(G.id,le.id)},onMouseDown:Le=>{if(Le.shiftKey||Le.metaKey||Le.ctrlKey){Le.preventDefault(),Le.stopPropagation();const Te=Ie(G.id,le.id),Je=N.length?N:L?[L]:[];A?.(Te?Je.filter(ke=>!(ke.row===G.id&&ke.id===le.id)):[...Je,{row:G.id,id:le.id}]);return}ot(Le,G.id,le.id,Le.currentTarget.parentElement)},children:"◆"},le.id))]})]}),Se.map(le=>{const $e=Z0(M,G.id);return t.jsxs("div",{className:"shot-time-row shot-prop-row","data-prop":`${G.id}:${le.id}`,children:[t.jsxs("div",{className:"shot-track-name",children:[t.jsx("span",{className:`shot-stopwatch${$e?" keyed":""}`,role:"img","aria-label":$e?o("Đã có key"):o("Chưa có key"),title:$e?o("Thuộc tính đã có key: sửa số sẽ ghi key tại playhead"):o("Chưa có key: sửa số đổi giá trị cố định"),children:"⏱"}),t.jsxs("label",{className:"shot-prop-label",children:[o(le.label),t.jsx(gn,{"aria-label":`${o(le.label)} · ${G.name}`,className:"shot-prop-number",step:le.step,min:le.min,max:le.max,precision:3,disabled:G.locked,value:J0(p,G.id,le.id,I),onCommit:Le=>C?.(G.id,le.id,Le)})]}),t.jsx("button",{className:"shot-prop-add","aria-label":`${o("Thêm key")} ${o(le.label)} · ${G.name}`,title:o("Thêm key tại playhead"),disabled:G.locked,onClick:()=>W(G.id),children:"◆"})]}),t.jsxs("div",{className:"shot-key-track shot-prop-track",onPointerDown:Le=>{G.locked||ze(Le,G.id,Le.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),G.keys.map(Le=>t.jsx("i",{"data-row":G.locked?void 0:G.id,"data-key":G.locked?void 0:Le.id,className:`shot-prop-key${Ie(G.id,Le.id)||L?.row===G.id&&L.id===Le.id?" active":""}`,style:{left:`${Le.time*100}%`}},Le.id))]})]},le.id)})]},G.id)})]})})]})}let Zn=null;function Sx(){return Zn||(Zn=new Pr(ig()),Zn.colorSpace=ld,Zn.anisotropy=4,Zn.generateMipmaps=!0,Zn.minFilter=cd,Zn)}const Lc=new Map;function Cx(e){let n=Lc.get(e);return n||(n=new Pr(og(e)),n.colorSpace=ld,n.anisotropy=8,n.generateMipmaps=!0,n.minFilter=cd,Lc.set(e,n)),n}let _n=null;function Nx(){if(_n)return _n;const e=128,n=new Uint8Array(e*e*4),s=r=>{const l=new Float32Array(r*r);let c=1013904223+r;for(let u=0;u<l.length;u++)c=Math.imul(c,1664525)+1013904223>>>0,l[u]=c/4294967296;return l},a=[4,8,16,32].map(r=>({g:r,v:s(r)})),i=r=>r*r*(3-2*r);for(let r=0;r<e;r++)for(let l=0;l<e;l++){let c=0,u=.5,m=0;for(const{g:p,v:x}of a){const g=l/e*p,v=r/e*p,w=Math.floor(g),C=Math.floor(v),M=i(g-w),S=i(v-C),I=(T,j)=>x[j%p*p+T%p],y=I(w,C)+(I(w+1,C)-I(w,C))*M,k=I(w,C+1)+(I(w+1,C+1)-I(w,C+1))*M;c+=(y+(k-y)*S)*u,m+=u,u*=.5}const d=(r*e+l)*4,f=Math.round(c/m*255);n[d]=n[d+1]=n[d+2]=f,n[d+3]=255}return _n=new E0(n,e,e,I0),_n.wrapS=_n.wrapT=rd,_n.magFilter=ac,_n.minFilter=ac,_n.needsUpdate=!0,_n}const Ax=Symbol.for("clipoox.shot.fxSoftDepth"),Tx=e=>e[Ax]??null,Dr={uOcclude:{value:0}},Ec={day:.22,golden:.16,overcast:.2,night:.03},Ia={blade:.78,width:.034,thick:.0075,grip:.19};function Ic(e,n){return[[-e,0],[-e*.62,n*.82],[-e*.26,n],[-e*.15,n*.38],[e*.15,n*.38],[e*.26,n],[e*.62,n*.82],[e,0],[e*.62,-n*.82],[e*.26,-n],[e*.15,-n*.38],[-e*.15,-n*.38],[-e*.26,-n],[-e*.62,-n*.82]]}function Rc(e=0){const{blade:n,width:s,thick:a}=Ia,i=[[0,.86,1],[.06,1,1],[.7,.96,.9],[.84,.74,.72],[.94,.4,.5],[1,.02,.15]],r=Ic(1,1).length,l=[],c=[];i.forEach(([m,d,f])=>{for(const[p,x]of Ic(s*d+e,a*f+e*.5))l.push(p,m*n,x)});for(let m=0;m<i.length-1;m++)for(let d=0;d<r;d++){const f=m*r+d,p=m*r+(d+1)%r,x=(m+1)*r+d,g=(m+1)*r+(d+1)%r;c.push(f,x,p,p,x,g)}const u=new Ct;return u.setAttribute("position",new Ot(l,3)),u.setIndex(c),u.computeVertexNormals(),u}function Lx(){const e=[],n=new hd(.0105,.15,4,10);n.rotateZ(Math.PI/2),n.scale(1,1,1.5),e.push(n);for(const i of[-1,1]){const r=new R0(.0125,.03,10);r.rotateZ(-i*Math.PI/2),r.translate(i*.086,.012,0),e.push(r)}const s=new hs(.016,.02,.026,14);s.translate(0,-.016,0),e.push(s);const a=Cd(e);return e.forEach(i=>i.dispose()),a}function Ex(){const e=[],n=new hs(.0125,.0125,Ia.grip,12);n.translate(0,-.03-Ia.grip/2,0),e.push(n);for(let i=0;i<5;i++){const r=new Or(.0132,.0028,6,14);r.rotateX(Math.PI/2),r.translate(0,-.05-i*.034,0),e.push(r)}const s=new Rn(.0235,14,10);s.translate(0,-.03-Ia.grip-.012,0),e.push(s);const a=Cd(e);return e.forEach(i=>i.dispose()),a}function Cd(e){const n=[],s=[],a=[],i=[];let r=0;for(const c of e){const u=c.getAttribute("position"),m=c.getAttribute("normal"),d=c.getAttribute("uv");for(let f=0;f<u.count;f++)n.push(u.getX(f),u.getY(f),u.getZ(f)),s.push(m.getX(f),m.getY(f),m.getZ(f)),a.push(d?d.getX(f):0,d?d.getY(f):0);if(c.index)for(let f=0;f<c.index.count;f++)i.push(r+c.index.getX(f));else for(let f=0;f<u.count;f++)i.push(r+f);r+=u.count}const l=new Ct;return l.setAttribute("position",new Ot(n,3)),l.setAttribute("normal",new Ot(s,3)),l.setAttribute("uv",new Ot(a,2)),l.setIndex(i),l}const Ix=`
|
|
4
4
|
attribute float iGlow; varying float vGlow; varying vec3 vN; varying vec3 vV; varying float vY;
|
|
5
5
|
void main(){
|
|
6
6
|
mat4 im = mat4(1.0);
|
|
@@ -284,4 +284,4 @@ void main(){
|
|
|
284
284
|
reflectedLight.directDiffuse += ( irradiance + directLight.color * max( 0.0, hqWrap - dotNL ) * vec3( 0.9, 0.36, 0.24 ) ) * BRDF_Lambert( material.diffuseContribution );`;function Bb(e){return e.onBeforeCompile=n=>{const s=K0.lights_physical_pars_fragment;s.includes(zc)&&(n.fragmentShader=n.fragmentShader.replace("#include <lights_physical_pars_fragment>",s.replace(zc,_b)))},e.customProgramCacheKey=()=>"hq-skin-sss-v1",e}function Kb(e,n=!0){return Wa(`skin|${e}|${n}`,()=>{const s=new Qe(e),a=Bb(new Cs({color:s,roughness:.52,metalness:0,sheen:.35,sheenRoughness:.45,sheenColor:s.clone().lerp(new Qe("#ffd9c8"),.5),specularIntensity:.55,vertexColors:n}));return a.name="skin",a})}function Hb(e){return Wa(`hair|${e}`,()=>{const n=new Qe(e),s=new Cs({color:n,roughness:.42,metalness:0,sheen:.55,sheenRoughness:.35,sheenColor:n.clone().lerp(new Qe("#ffffff"),.35),anisotropy:.75,specularIntensity:.7,side:cs});return s.name="hair",s})}function Wb(e){return Wa(`facial|${e}`,()=>{const n=new Qe(e),s=new Cs({color:"#ffffff",vertexColors:!0,alphaHash:!0,roughness:.7,metalness:0,sheen:.25,sheenRoughness:.6,sheenColor:n.clone().lerp(new Qe("#ffffff"),.2),anisotropy:.5,specularIntensity:.3});return s.name="beard",s})}function qb(){return Wa("eye",()=>{const e=new Cs({vertexColors:!0,roughness:.18,clearcoat:1,clearcoatRoughness:.04});return e.name="eyes",e})}function Fi(e,n,s=.6,a=Ha){return Wa(`plain|${e}|${n}|${s}|${a}`,()=>{const i=new Gn({color:n,roughness:s,side:a});return i.name=e,i})}const _c=[],Bc=new St,ir=new ie,ua=new ie,Kc=new ie;function Gb(e,n=5,s=.16){let a=e.userData.samples;if(a)return a;const i=e.getAttribute("position"),r=[];for(let l=0;l<i.count;l++)(l%n===0||i.getY(l)<s)&&r.push(l);return a=Uint32Array.from(r),e.userData.samples=a,a}function Zs(e,n,s,a=!1){const i=e.geometry,r=e.skeleton,l=a?Array.from({length:i.getAttribute("position").count},(d,f)=>f):Gb(i),c=i.getAttribute("position"),u=i.getAttribute("skinIndex"),m=i.getAttribute("skinWeight");Bc.copy((s??e).matrixWorld).invert();for(let d=0;d<r.bones.length;d++)(_c[d]??=new St).multiplyMatrices(r.bones[d].matrixWorld,r.boneInverses[d]).premultiply(Bc);for(const d of l){ir.fromBufferAttribute(c,d),ua.set(0,0,0);for(let f=0;f<4;f++){const p=m.getComponent(d,f);p&&(Kc.copy(ir).applyMatrix4(_c[u.getComponent(d,f)]),ua.addScaledVector(Kc,p))}n(ua.x,ua.y,ua.z,d)}}function Ub(e){return e.computeBoundingBox=function(){const n=(this.boundingBox??=new $t).makeEmpty();Zs(this,(s,a,i)=>{n.expandByPoint(ir.set(s,a,i))}),n.expandByScalar(.004)},e.computeBoundingSphere=function(){this.boundingBox||this.computeBoundingBox(),this.boundingBox.getBoundingSphere(this.boundingSphere??=new H0)},e}const Jt=(e,n,s)=>{const a=Math.min(1,Math.max(0,(s-e)/(n-e)));return a*a*(3-2*a)};function Xb(e,n){const s=e.face.landmarks,a=e.regions,i=a.indexOf("lips"),r=a.indexOf("stubble"),l=Math.abs(s.corner[0])+.007,c=s.upper[1]+.0025,u=s.nostril[1]-.004,m=(p,x,g,v)=>{const w=Math.abs(p),C=Jt(.35,1,w/l),M=u-.009*C,S=c-.0045*C-.004*C*C,I=Jt(0,.0022,x-S)*Jt(0,.0028,M-x)*Jt(0,.004,l-w)*Jt(.11,.13,g);return v===i?I*Jt(.8,1,w/l):I},d=(p,x,g,v)=>{const w=Math.abs(p),C=.019-.006*Jt(s.lower[1]-.01,s.lower[1]-.003,x),M=Jt(0,.003,s.lower[1]-.0045-x)*Jt(0,.006,x-(s.chin[1]-.016))*Jt(0,.004,C-w)*Jt(.1,.125,g);return v===i?0:M},f=(p,x,g,v)=>(v===i?0:v===r?1:0)||m(p,x,g,v);return n==="goatee"?{zone:d,th:p=>.0042*Math.pow(p,.6)}:n==="beard"?{zone:f,th:(p,x,g)=>(.0032+.002*Jt(s.mouthY,s.chin[1],g))*Math.pow(p,.7)}:{zone:m,th:(p,x)=>(.0032+.001*(1-Jt(0,.02,Math.abs(x))))*Math.pow(p,.55)}}const no=new Map;function Vb(e,n,s,a){const i=`${Fn(n)}|${s}|${a}`;let r=no.get(i);if(r)return r;const l=ds(e,n,0),c=l.getAttribute("position"),u=l.getAttribute("normal"),m=l.getIndex(),d=Xn(e),f=l.userData.region,p=c.count,{zone:x,th:g}=Xb(e,s),v=new Float32Array(p);for(let Q=0;Q<p;Q++){const J=c.getX(Q)-d[0],V=c.getY(Q)-d[1],B=c.getZ(Q)-d[2];V>.02||V<-.2||B<0||(v[Q]=x(J,V,B,f[Q]))}const w=Array.from({length:p},()=>[]);for(let Q=0;Q<m.count;Q+=3){const J=m.getX(Q),V=m.getX(Q+1),B=m.getX(Q+2);(v[J]||v[V]||v[B])&&(w[J].push(V,B),w[V].push(J,B),w[B].push(J,V))}for(let Q=0;Q<2;Q++){const J=Float32Array.from(v);for(let V=0;V<p;V++){if(!w[V].length)continue;let B=0;for(const q of w[V])B+=J[q];J[V]>0&&(v[V]=Math.min(J[V],.5*J[V]+.5*(B/w[V].length)))}}const C=new Int32Array(p).fill(-1),M=[],S=[],I=Q=>(C[Q]<0&&(C[Q]=S.length,S.push(Q)),C[Q]);for(let Q=0;Q<m.count;Q+=3){const J=m.getX(Q),V=m.getX(Q+1),B=m.getX(Q+2);Math.max(v[J],v[V],v[B])<.04||M.push(I(J),I(V),I(B))}if(!M.length)return null;const y=S.length,k=new Float32Array(y*3),T=new Float32Array(y*4),j=new Float32Array(y*4),L=new Uint8Array(y*4),N=new Uint8Array(y*4),A=l.getAttribute("skinIndex"),O=l.getAttribute("skinWeight"),_=new Qe(a),$=_.clone().lerp(new Qe("#8a6a4e"),.22),P=_.clone().multiplyScalar(.7),W=l.morphAttributes.position||[],z=W.map(()=>new Float32Array(y*3));return S.forEach((Q,J)=>{const V=c.getX(Q)-d[0],B=c.getY(Q)-d[1],q=v[Q],D=g(q,V,B)+3e-4;k[J*3]=c.getX(Q)+u.getX(Q)*D,k[J*3+1]=c.getY(Q)+u.getY(Q)*D,k[J*3+2]=c.getZ(Q)+u.getZ(Q)*D;const ee=.5+.5*Math.sin(V*2300+Math.sin(B*900)*2.2)*Math.sin(V*870-B*610),Z=P.clone().lerp($,Math.pow(ee,2.5)*.85);T[J*4]=Z.r,T[J*4+1]=Z.g,T[J*4+2]=Z.b,T[J*4+3]=Jt(.04,.55,q);const xe=Math.sign(V)*.55,be=Math.hypot(xe,1,.25);j[J*4]=xe/be,j[J*4+1]=-1/be,j[J*4+2]=.25/be,j[J*4+3]=1;for(let U=0;U<4;U++)L[J*4+U]=A.getComponent(Q,U),N[J*4+U]=Math.round(O.getComponent(Q,U)*(O.normalized?255:1));z.forEach((U,pe)=>{const me=W[pe];U[J*3]=me.getX(Q),U[J*3+1]=me.getY(Q),U[J*3+2]=me.getZ(Q)})}),r=new Ct,r.setAttribute("position",new Nt(k,3)),r.setAttribute("color",new Nt(T,4)),r.setAttribute("tangent",new Nt(j,4)),r.setAttribute("skinIndex",new ls(L,4)),r.setAttribute("skinWeight",new ls(N,4,!0)),r.setIndex(M),r.computeVertexNormals(),r.morphAttributes.position=z.map(Q=>new Nt(Q,3)),r.morphTargetsRelative=!0,r.userData.shared=!0,r.userData.facialHair={type:s,triangles:M.length/3,maxLift:Math.max(...S.map((Q,J)=>Math.hypot(k[J*3]-c.getX(Q),k[J*3+1]-c.getY(Q),k[J*3+2]-c.getZ(Q))))},r.dispose=()=>{},no.size>32&&no.clear(),no.set(i,r),r}const Yb=Gh,Cn=(e,n,s)=>{const a=Math.min(1,Math.max(0,(s-e)/(n-e)));return a*a*(3-2*a)},wn=Math.PI*2;function Qb(e){const n=e.face.stats,s=e.face.landmarks,a=n.eye+.02;return{cy:a,cz:(n.front+n.back)/2,ax:n.half*1.04,ay:n.crown-a,az:(n.front-n.back)/2,eye:n.eye,brow:Math.max(s.browIn[1],s.browMid[1],s.browOut[1]),crown:n.crown}}const Hs=(e,n,s)=>Math.atan2(n,s-e.cz),Do=(e,n,s,a)=>Math.hypot(n/e.ax,(s-e.cy)/e.ay,(a-e.cz)/e.az);function Ss(e,n,s,a){const i=(a-e.cy)/(n*e.ay),r=n*Math.sqrt(Math.max(0,1-i*i));return[e.ax*r*Math.sin(s),a,e.cz+e.az*r*Math.cos(s)]}const Ps=(e,n)=>s=>n+(e-n)*(.5+.5*Math.cos(s)),Hc=new WeakMap;function So(e){let n=Hc.get(e);if(n)return n;const s=e.lods[0],a=Xn(e),i=["head","jaw","lidUL","lidUR","lidDL","lidDR"].map(c=>e.bones.indexOf(c)),r=[];for(let c=0;c<s.vertices;c++){let u=0;for(let m=0;m<4;m++)i.includes(s.skinIndex[c*4+m])&&(u+=s.skinWeight[c*4+m]/255);u>=.5&&r.push(s.position[c*3]-a[0],s.position[c*3+1]-a[1],s.position[c*3+2]-a[2])}const l=new Map;for(const[c,u]of e.hair)u.kind==="hair"&&l.set(c,u.position.map((m,d)=>m-a[d%3]));return n={skin:Float32Array.from(r),hair:l},Hc.set(e,n),n}const Wc=new WeakMap;function Zb(e,n){let s=Wc.get(e);if(s)return s;const a=e.lods[0],i=Xn(e),r=["torso","pelvis","headHalf"].map(f=>e.bones.indexOf(f)),l=48,c=-.36,u=.01,m=30,d=new Float32Array(l*m);for(let f=0;f<a.vertices;f++){if(!r.includes(a.skinIndex[f*4]))continue;const p=a.position[f*3]-i[0],x=a.position[f*3+1]-i[1],g=a.position[f*3+2]-i[2],v=Math.round((x-c)/u);if(v<0||v>=m)continue;const w=(Math.round(Math.atan2(p,g-n)/wn*l)%l+l)%l;d[v*l+w]=Math.max(d[v*l+w],Math.hypot(p,g-n))}for(let f=0;f<3;f++){const p=d.slice();for(let x=0;x<m;x++)for(let g=0;g<l;g++)d[x*l+g]=Math.max(p[x*l+g],p[x*l+(g+1)%l],p[x*l+(g+l-1)%l])}for(let f=m-2;f>=0;f--)for(let p=0;p<l;p++)d[f*l+p]=Math.max(d[f*l+p],d[(f+1)*l+p]);for(let f=0;f<4;f++){const p=d.slice();for(let x=0;x<m;x++)for(let g=0;g<l;g++)d[x*l+g]=.5*p[x*l+g]+.25*(p[x*l+(g+1)%l]+p[x*l+(g+l-1)%l])}return s=(f,p)=>{const x=(f/wn*l+l*4)%l,g=Math.floor(x),v=x-g,w=Math.min(m-1,Math.max(0,Math.round((p-c)/u)));return d[w*l+g]*(1-v)+d[w*l+(g+1)%l]*v},Wc.set(e,s),s}function vs(e,n,s,a,i=.004,r=.0025){const l=So(e),c=(n.ax+n.az)/2;let u=1;for(let d=0;d<l.skin.length;d+=3){const f=l.skin[d],p=l.skin[d+1],x=l.skin[d+2];p>s(Hs(n,f,x))-.004&&(u=Math.max(u,Do(n,f,p,x)+i/c))}const m=a?l.hair.get(a):void 0;if(m)for(let d=0;d<m.length;d+=3){const f=m[d],p=m[d+1],x=m[d+2],g=s(Hs(n,f,x));p>g-.006&&p<g+.012&&(u=Math.max(u,Do(n,f,p,x)+r/c))}return u}function ss(e,n,s,a,i=!1){const r=[],l=[],c=s?e:e+1;for(const p of[0,1])for(let x=0;x<=n;x++)for(let g=0;g<c;g++)r.push(...a(g/e,x/n,p));const u=(p,x,g)=>p*c*(n+1)+g*c+(s?x%e:x),m=(p,x,g)=>i?l.push(p,g,x):l.push(p,x,g);for(let p=0;p<n;p++)for(let x=0;x<e;x++){const g=T=>[u(T,x,p),u(T,x+1,p),u(T,x+1,p+1),u(T,x,p+1)],[v,w,C,M]=g(0),[S,I,y,k]=g(1);m(v,w,C),m(v,C,M),m(S,y,I),m(S,k,y)}const d=(p,x)=>{const g=u(0,...p),v=u(0,...x),w=u(1,...p),C=u(1,...x);m(g,w,C),m(g,C,v)};for(let p=0;p<e;p++)d([p,0],[p+1,0]),d([p+1,n],[p,n]);if(!s)for(let p=0;p<n;p++)d([e,p],[e,p+1]),d([0,p+1],[0,p]);const f=new Ct;return f.setAttribute("position",new Ot(r,3)),f.setIndex(l),f}function Kn(e){const n=[],s=[];for(const i of e){const r=n.length/3,l=i.getAttribute("position");for(let u=0;u<l.count;u++)n.push(l.getX(u),l.getY(u),l.getZ(u));const c=i.getIndex();for(let u=0;u<c.count;u++)s.push(c.getX(u)+r);i.dispose()}const a=new Ct;return a.setAttribute("position",new Ot(n,3)),a.setIndex(s),a.computeVertexNormals(),a}function qc(e,n,s,a,i,r){const l=(e.ax+e.az)/2;return ss(96,20,!0,(c,u,m)=>{const d=c*wn,f=m?n:n+s/l,p=a(d),x=e.cy+f*e.ay,g=Math.asin(Math.max(-1,Math.min(1,(p-e.cy)/(f*e.ay)))),v=g+(Math.PI/2-g)*u,w=Ss(e,f,d,Math.min(x,e.cy+f*e.ay*Math.sin(v)));if(r){const C=r(d,u);w[0]*=C,w[2]=e.cz+(w[2]-e.cz)*C}return!m&&i&&(w[1]+=i(w)),w})}function ma(e,n,s,a,i,r,l,c,u=!1){const m=(e.ax+e.az)/2,d=n+.6*c/m;return ss(u?72:40,8,u,(f,p,x)=>{const g=a+(i-a)*f,v=s(g),w=Ss(e,d,g,v),C=Math.sin(g)/e.ax,M=Math.cos(g)/e.az,S=Math.hypot(C,M),I=-.003+(r(g)+.003)*p;return[w[0]+C/S*I,v-l(g,Math.max(0,I))-(x?c:0),w[2]+M/S*I]},!0)}function so(e,n,s,a,i,r,l={}){const c=(e.ax+e.az)/2,u=22,m=14;return ss(64,u,!0,(d,f,p)=>{const x=d*wn,g=s(x),v=Ss(e,n+(p?0:r/c),x,g),w=v[0],C=v[2]-e.cz;if(f*u<=m){const k=f*u/m,T=i(k)*(l.pleats?.(x,k)??1);return[w*T,g+(a-(p?r:0)-g)*k,e.cz+C*T]}const M=1-(f*u-m)/(u-m),S=i(1)*M*(l.pleats?.(x,1)??1),I=w*S,y=C*S;return[I,a-(p?r:0)-(l.dent?.(I,y)??0)*(1-M*M),e.cz+y]})}function Pi(e,n,s,a,i,r,l=.0015){const c=(e.ax+e.az)/2;return ss(64,2,!0,(u,m,d)=>{const f=u*wn,p=s(f),x=Ss(e,n+(d?0:l/c),f,p),g=a+(i-a)*m,v=r(g);return[x[0]*v,p+g,e.cz+(x[2]-e.cz)*v]})}function Jb(e,n,s=[14,10]){const a=new Rn(1,s[0],s[1]);return a.scale(...e),a.translate(...n),a.deleteAttribute("uv"),a.deleteAttribute("normal"),a}function ey(e){const n=e.brow;return{cap:Ps(n+.02,e.eye+.008),helmet:Ps(n+.024,e.eye+.016),police:Ps(n+.022,e.eye+.012),fedora:Ps(n+.026,e.eye+.02),chef:Ps(n+.024,e.eye+.018),ancient:Ps(n+.028,e.eye+.022)}}function ty(e,n,s){const a=Qb(e),i=ey(a),r=(a.ax+a.az)/2,l=c=>(u,m,d)=>m>c(Hs(a,u,d))-.003;switch(n){case"cap":{const c=i.cap,u=vs(e,a,c,void 0),m=Math.min(vs(e,a,c,s),u+.02),d=.0035,f=(g,v)=>1-.045*Math.pow(1-Math.abs(Math.sin(3*g)),14)*Math.sin(Math.PI*Math.min(1,v*1.25))+.1*Math.pow(Math.max(0,Math.cos(g)),2)*Math.sin(Math.PI*Math.min(1,v*1.4))*(1-v),p=ma(a,m+.02,c,-.8,.8,g=>.075*Math.pow(Math.max(0,1-(g/.8)**2),.4),(g,v)=>.12*v*v+.05*(g/.8)**2*Cn(0,.05,v),.004),x=a.cy+(m+d/r)*a.ay;return{main:Kn([qc(a,m,d,c,void 0,f),p]),trim:Jb([.008,.004,.008],[0,x+.0015,a.cz]),cut:(g,v,w)=>{const C=Hs(a,g,w);return v>c(C)-.003-.035*Math.max(0,Math.cos(C))}}}case"helmet":{const c=i.helmet,u=vs(e,a,c,s,.02,.012),m=.005,d=p=>.007*Math.exp(-((p[0]/.014)**2))*Cn(a.cy,a.cy+a.ay*.6,p[1]),f=ma(a,u+m/r,c,0,wn,p=>.018+.028*Math.max(0,Math.cos(p))**2,(p,x)=>.25*x*x,.004,!0);return{main:Kn([qc(a,u,m,c,d),f]),cut:l(c)}}case"police":{const c=i.police,u=vs(e,a,c,s,.005),m=Math.max(c(0),c(Math.PI))+.068,d=so(a,u,c,m,p=>1+.17*Cn(.4,1,p),.003),f=ma(a,u+.004/r,c,-1.05,1.05,p=>.05*Math.pow(Math.max(0,1-(p/1.05)**2),.6),(p,x)=>.3*x,.003);return{main:Kn([d,f]),trim:Pi(a,u+.002/r,c,.004,.02,()=>1),cut:l(c)}}case"fedora":{const c=i.fedora,u=vs(e,a,c,s,.005),m=Math.max(c(0),c(Math.PI))+.09,d=so(a,u,c,m,p=>1-.07*p,.003,{dent:p=>.016*Math.exp(-((p/.022)**2)),pleats:(p,x)=>1-.05*Cn(.6,1,x)*Math.max(0,Math.cos(p))**4}),f=ma(a,u+.003/r,c,0,wn,p=>.055+.008*Math.cos(p)**2,(p,x)=>.18*x*x*Math.cos(p)**2-.3*x*x*Math.sin(p)**2,.003,!0);return{main:Kn([d,f]),trim:Pi(a,u+.0035/r,c,.002,.022,p=>1-.07*(p/.09)),cut:l(c)}}case"chef":{const c=i.chef,u=vs(e,a,c,s,.005),m=Math.max(c(0),c(Math.PI))+.17;return{main:so(a,u,c,m,f=>f<.42?1.01:1.01+.3*Math.sin(Math.min(1,(f-.42)/.4)*Math.PI/2)-.12*Cn(.85,1,f),.003,{pleats:(f,p)=>1+.03*Cn(.42,.6,p)*Math.sin(f*16)}),cut:l(c)}}case"ancient":{const c=i.ancient,u=vs(e,a,c,s,.006),m=Math.max(c(0),c(Math.PI))+.085,d=so(a,u,c,m,g=>1+.04*g,.003,{dent:(g,v)=>-.012*Math.exp(-((g/.05)**2+((v-a.cz)/.06)**2))}),f=c(Math.PI)+.055,p=a.cz-a.az*u*.7,x=[-1,1].map(g=>{const v=new hs(1,1,1,20);return v.rotateX(Math.PI/2),v.scale(.055,.017,.003),v.rotateZ(g*.22),v.translate(g*(a.ax*u+.045),f,p),v.deleteAttribute("uv"),v.deleteAttribute("normal"),v});return{main:Kn([d,...x]),trim:Pi(a,u+.0035/r,c,.002,.018,()=>1),cut:l(c)}}case"nonla":{const m=So(e),d=[m.skin,m.hair.get(s??"")??new Float32Array];let f=-1/0;for(const g of d)for(let v=0;v<g.length;v+=3)f=Math.max(f,g[v+1]+Math.hypot(g[v],g[v+2]-a.cz)*.15/.235+.008);const p=ss(56,10,!0,(g,v,w)=>{const C=g*wn,M=.235*v,S=f-.15*v-(w?.003:0);return[M*Math.sin(C),S,a.cz+M*Math.cos(C)]},!0),x=new Or(.235,.0035,6,56);return x.rotateX(Math.PI/2),x.translate(0,f-.15-.0015,a.cz),x.deleteAttribute("uv"),x.deleteAttribute("normal"),{main:Kn([p]),trim:Kn([x]),cut:null}}case"moto":{const c={...a,cy:a.eye-.004,ay:a.crown-a.eye+.004,ax:a.ax*1.1},u=g=>Cn(1.25,1.05,Math.abs(g)),m=g=>-.118+.012*Math.cos(g)**2+(a.brow+.016+.118)*u(g),d=So(e);let f=1;for(let g=0;g<d.skin.length;g+=3){const v=d.skin[g],w=d.skin[g+1],C=d.skin[g+2];w>m(Hs(c,v,C))-.01&&(f=Math.max(f,Do(c,v,w,C)+.025/r))}const p=ss(96,18,!0,(g,v,w)=>{const C=g*wn-Math.PI,M=w?f:f+.006/r,S=m(C),I=Math.asin(Math.max(-1,Math.min(1,(S-c.cy)/(M*c.ay)))),y=I+(Math.PI/2-I)*v;return Ss(c,M,C,c.cy+M*c.ay*Math.sin(y))}),x=ma(c,f+.006/r,m,-.8,.8,g=>.035*Math.pow(Math.max(0,1-(g/.8)**2),.6),(g,v)=>.2*v,.004);return{main:Kn([p,x]),cut:"hide"}}case"hijab":{const c={...a,cy:a.eye-.035,ay:a.crown-a.eye+.035,ax:a.ax*1.12,az:a.az*1.04},u=e.face.landmarks,m=u.chin[1],d=S=>Cn(1,.82,Math.abs(S)),f=S=>m-.012+(a.brow+.03-m+.012)*d(S)-.05*Cn(1.4,2.6,Math.abs(S)),p=So(e);let x=1;for(let S=0;S<p.skin.length;S+=3){const I=p.skin[S],y=p.skin[S+1],k=p.skin[S+2],T=Hs(c,I,k);y>f(T)-.004&&d(T)<.98&&(x=Math.max(x,Do(c,I,y,k)+.008/r))}const g=ss(96,18,!0,(S,I,y)=>{const k=S*wn-Math.PI,T=y?x:x+.003/r,j=f(k),L=Math.asin(Math.max(-1,Math.min(1,(j-c.cy)/(T*c.ay)))),N=L+(Math.PI/2-L)*I;return Ss(c,T,k,c.cy+T*c.ay*Math.sin(N))}),v=S=>Math.min(m+.004,f(S)+.02),w=-.27,C=Zb(e,a.cz),M=ss(72,12,!0,(S,I,y)=>{const k=S*wn-Math.PI,T=v(k),j=Ss(c,x+.004/r,k,T),L=T+(w-T)*I,N=Math.hypot(j[0],j[2]-a.cz),A=Math.max(N*(1+.5*I*I),(C(k,L)+.012)*Cn(0,.4,I))-(y?.003:0);return[Math.sin(k)*A,L,a.cz+Math.cos(k)*A]});return{main:Kn([g,M]),cut:"hide"}}}return null}const pa=new Map;function Gd(e,n,s){const a=`${e.bytes}|${n}|${s??""}`;if(!pa.has(a)){pa.size>48&&pa.clear();const i=ty(e,n,s);for(const r of[i?.main,i?.trim])r&&(r.computeVertexNormals(),r.userData.shared=!0,r.dispose=()=>{});pa.set(a,i)}return pa.get(a)}function ny(e,n,s){return Gd(e,n,s)?.cut??null}const Gc=(e,n)=>"#"+new Qe(e).lerp(new Qe(n>0?"#ffffff":"#000000"),Math.abs(n)).getHexString(),sy=e=>{const n=new Qe(e);return n.r*.3+n.g*.59+n.b*.11>.5?Gc(e,-.55):Gc(e,.65)},ao={cap:e=>`fab:cotton:${e}`,police:e=>`fab:wool:${e}`,fedora:e=>`fab:wool:${e}`,chef:e=>`fab:cotton:${e}`,ancient:e=>`fab:silk:${e}`,nonla:e=>`fab:linen:${e}`,hijab:e=>`fab:cotton:${e}`,helmet:e=>`sol:${e}:0.35:0`,moto:e=>`sol:${e}:0.25:0`};function ay(e,n,s){const a=Gd(e,n.type,s);if(!a)return[];const i=[{geometry:a.main,mat:(ao[n.type]??ao.cap)(n.color),slot:"hat"}],r=n.type==="cap"?n.color:n.color2??(n.type==="police"?"#d8b64a":sy(n.color));return a.trim&&i.push({geometry:a.trim,mat:n.type==="police"||n.type==="ancient"?`sol:${r}:0.35:0.6`:(ao[n.type]??ao.cap)(r),slot:"hat"}),i}const oo=new Map,$i=new Map;function oy(e,n){let s=$i.get(n.id);if(s!==void 0)return s;const a=e.morphs.findIndex(p=>p.name==="femFace"),i=e.lods[0];if(a<0)return $i.set(n.id,null),null;const r=i.morphs[a],l=i.position,c=n.position,u=c.length/3,m=[1/0,1/0,1/0],d=[-1/0,-1/0,-1/0];for(let p=0;p<u;p++)for(let x=0;x<3;x++)m[x]=Math.min(m[x],c[p*3+x]),d[x]=Math.max(d[x],c[p*3+x]);const f=[];for(let p=0;p<i.vertices;p++)[0,1,2].every(x=>l[p*3+x]>m[x]-.015&&l[p*3+x]<d[x]+.015)&&f.push(p);s=new Float32Array(u*3);for(let p=0;p<u;p++){let x=-1,g=1/0;for(const v of f){const w=(l[v*3]-c[p*3])**2+(l[v*3+1]-c[p*3+1])**2+(l[v*3+2]-c[p*3+2])**2;w<g&&(g=w,x=v)}if(x>=0)for(let v=0;v<3;v++)s[p*3+v]=r.data[x*3+v]*r.scale}return $i.set(n.id,s),s}function iy(e,n){const s=Xn(e),a=Float32Array.from(n),i=(l,c,u,m)=>{const d=l<c?(l-c+m)/m:l>u?(u+m-l)/m:1;return d<=0?0:d>=1?1:d*d*(3-2*d)};let r=!1;for(let l=0;l<a.length;l+=3){const c=a[l]-s[0],u=Math.abs(c);if(u<.05)continue;const m=i(a[l+1]-s[1],-.072,-.016,.015)*i(a[l+2]-s[2],.025,.075,.02),d=.091+(u-.072)*.3;m>0&&u<d&&(a[l]=s[0]+Math.sign(c)*(u+(d-u)*m),r=!0)}return r?a:null}function ry(e,n,s,a,i=0){const r=i>0&&(n.kind==="brows"||n.kind==="teeth"||n.kind==="lashes")?oy(e,n):null,l=r?Math.round(i*100)/100:0,c=`${n.id}|${a}|${l}`;let u=oo.get(c);if(u)return u;oo.size>96&&oo.clear();const m=r?n.position.map((w,C)=>w+r[C]*l):n.position,d=r?Hd(l):0;if(d>0){const w=[0,0,0];for(let C=0;C<m.length;C+=3)Wd(e,m[C],m[C+1],m[C+2],d,w),m[C]+=w[0],m[C+1]+=w[1],m[C+2]+=w[2]}const f=n.kind==="hair"?iy(e,n.position):null;u=new Ct,u.setAttribute("position",new Nt(f??m,3)),u.setAttribute("skinIndex",new ls(n.skinIndex,4)),u.setAttribute("skinWeight",new ls(n.skinWeight,4,!0));const p=n.position.length/3,x=new Float32Array(p*4);for(let w=0;w<p;w++)x[w*4]=n.flow[w*3],x[w*4+1]=n.flow[w*3+1],x[w*4+2]=n.flow[w*3+2],x[w*4+3]=1;u.setAttribute("tangent",new Nt(x,4));const g=Xn(e);let v=n.index;if(typeof s=="function"){const w=[],C=M=>s(m[M*3]-g[0],m[M*3+1]-g[1],m[M*3+2]-g[2]);for(let M=0;M<n.index.length;M+=3)C(n.index[M])&&C(n.index[M+1])&&C(n.index[M+2])||w.push(n.index[M],n.index[M+1],n.index[M+2]);v=w}return u.setIndex(Array.from(v)),u.computeVertexNormals(),(n.kind==="beard"||n.kind==="brows")&&(u.morphAttributes.position=_d(m,g).map(w=>new Nt(w,3)),u.morphTargetsRelative=!0),u.userData.shared=!0,u.dispose=()=>{},oo.set(c,u),u}function ly(e,n,s,a){const i=[],r=s.hat?ny(e,s.hat.type,s.hair?.style):null,l=s.hat?`hat:${s.hat.type}`:"",c=s.hair?.color??"#2a211b",u=(f,p,x,g)=>{const v=e.hair.get(f);if(!v||g==="hide")return;const w=n.bones.get("head"),C=new Map,M=v.chains.length?{kind:"hair",anchor:"head",chains:[]}:null;for(const[S,I]of v.chains.entries()){let y=w,k=[-Gs[0],-Gs[1],-Gs[2]];const T=[],j=[];I.forEach((L,N)=>{const A=new La;A.name=L.name,A.position.set(L.at[0]-k[0],L.at[1]-k[1],L.at[2]-k[2]),y.add(A),n.bones.set(L.name,A),T.push(A);const O=Xn(e);C.set(L.name,new St().makeTranslation(-(O[0]+L.at[0]),-(O[1]+L.at[1]),-(O[2]+L.at[2])));const _=I[N+1];j.push(_?new ie(_.at[0]-L.at[0],_.at[1]-L.at[1],_.at[2]-L.at[2]):j[N-1]?.clone()??new ie(0,-.08,0)),y=A,k=L.at}),M.chains.push({bones:T,rest:j,kind:"hair",stiffness:f==="long"?.55:.4,collide:!0,side:S})}i.push({geometry:ry(e,v,g,g?l:"",a.fem),material:typeof p=="string"?Hb(p):p,slot:x,bones:v.bones,inverses:C,chains:M,near:v.kind==="lashes"||v.kind==="teeth"||v.kind==="brows"})},m=s.hair?.style;if(m&&m!=="none"&&m!=="buzz"&&u(m,c,"hair",r),u("brows",cy(s.hair&&s.hair.style!=="none"?c:s.beard?.color??"#2a211b",a.skin),"hair",null),s.beard&&s.beard.type!=="none"){const f=Vb(e,a,s.beard.type,s.beard.color);f&&i.push({geometry:f,material:Wb(s.beard.color),slot:"beard",bones:[...Yb],inverses:new Map,chains:null,near:!1})}u("lashes",Fi("lashes","#17110d",.75,cs),"lashes",null);const d=Fi("teeth","#e6dfd2",.3);return u("teeth-upper",d,"teeth",null),u("teeth-lower",d,"teeth",null),u("tongue",Fi("tongue","#a5525a",.45),"mouth",null),i}function cy(e,n="#c9956f"){const s=new Qe(e);return"#"+(s.getHSL({h:0,s:0,l:0}).l>.7?s.multiplyScalar(.75):s.lerp(new Qe(n),.1)).getHexString()}const Wt=(e,n,s)=>{const a=Math.min(1,Math.max(0,(s-e)/(n-e)));return a*a*(3-2*a)},fa=-.1,zo={tshirt:{sleeve:.42,hem:-.11,neck:"crew",th:.0055},shirt:{sleeve:1.93,hem:-.13,neck:"collar",th:.0065},polo:{sleeve:.45,hem:-.11,neck:"collar",th:.006},blazer:{sleeve:1.9,hem:-.2,neck:"deepv",th:.013},hoodie:{sleeve:1.95,hem:-.13,neck:"high",th:.013},chef:{sleeve:1.9,hem:-.17,neck:"high",th:.011},doctor:{sleeve:1.9,hem:.02,neck:"v",th:.01,loose:{top:.02,length:.5,flare:1.12,open:34,folds:.004,chains:10}},police:{sleeve:1.92,hem:-.13,neck:"collar",th:.008},worker:{sleeve:-.06,hem:-.12,neck:"v",th:.011,stripes:!0},nurse:{sleeve:.45,hem:-.13,neck:"v",th:.007},sports:{sleeve:.36,hem:-.1,neck:"crew",th:.005},tank:{sleeve:-.08,hem:-.1,neck:"scoop",th:.0045},robe:{sleeve:1.97,hem:.06,neck:"v",th:.012,loose:{top:.2,length:1.06,flare:1.2,folds:.006,chains:14}},tunic:{sleeve:1.9,hem:.02,neck:"high",th:.011,loose:{top:.02,length:.48,flare:1.2,folds:.005,chains:12}},dress:{sleeve:.3,hem:.06,neck:"scoop",th:.005,loose:{top:.06,length:.55,flare:1.3,folds:.006,chains:12}},wedding:{sleeve:-.08,hem:.08,neck:"scoop",th:.006,loose:{top:.08,length:1.02,flare:1.9,folds:.012,chains:16}},armor:{sleeve:.32,hem:-.14,neck:"high",th:.02},hero:{sleeve:1.97,hem:-.15,neck:"high",th:.0035},aodai:{sleeve:1.97,hem:-.03,neck:"high",th:.005,loose:{top:.08,length:.9,flare:1.08,panels:"aodai",folds:.003,chains:14}}},pn={trousers:{waist:.06,leg:1.99,th:.0075},jeans:{waist:.02,leg:1.99,th:.0065},shorts:{waist:.05,leg:.52,th:.007},ancient:{waist:.08,leg:1.97,th:.014},miniskirt:{waist:.05,leg:.24,th:.005,loose:{top:.05,length:.32,flare:1.18,folds:.004,chains:16}},"skirt-mid":{waist:.07,leg:.4,th:.005,loose:{top:.07,length:.56,flare:1.28,folds:.006,chains:16}},"skirt-long":{waist:.07,leg:.45,th:.005,loose:{top:.07,length:.95,flare:1.4,folds:.008,chains:18}}},_o={coat:{sleeve:1.95,hem:.03,neck:"deepv",th:.018,loose:{top:.03,length:.6,flare:1.2,open:26,folds:.006,chains:12}},raincoat:{sleeve:1.95,hem:.03,neck:"high",th:.016,loose:{top:.03,length:.7,flare:1.25,open:18,folds:.006,chains:12}}},hy=e=>!!e.top||!!(e.outer&&_o[e.outer.type]),dy=e=>!!e.bottom||!!(e.top&&zo[e.top.type]?.loose&&zo[e.top.type].loose.length>.4)||!!(e.outer&&_o[e.outer.type]?.loose),uy=e=>e.fabric??Wm[e.type]??"cotton",at={torso:0,arm:1,hand:2,leg:3,foot:4,head:5},io=new Map;function Kr(e,n,s){const a=e.lods[n],i=`${n}|${Fn(s)}`;let r=io.get(i);if(r)return r;io.size>48&&io.clear();const l=Uh(qo({...s,head:1,posture:0},Sr,{bind:!0})),c=new Proxy(e.bind,{get:(f,p)=>l.get(p)?.t??f[p]}),u=a.vertices,m=ds(e,s,n).getAttribute("position").array;r={cat:new Uint8Array(u),yt:new Float32Array(u),armT:new Float32Array(u),legT:new Float32Array(u),x:new Float32Array(u),z:new Float32Array(u),footY:new Float32Array(u),sole:0};const d=(f,p,x)=>{const g=[x[0]-p[0],x[1]-p[1],x[2]-p[2]],v=g[0]**2+g[1]**2+g[2]**2;return((f[0]-p[0])*g[0]+(f[1]-p[1])*g[1]+(f[2]-p[2])*g[2])/v};for(let f=0;f<u;f++){const p=[m[f*3],m[f*3+1],m[f*3+2]],x=p[0]<0?"L":"R",g=e.bones[a.skinIndex[f*4]];r.cat[f]=/^(arm|fore)/.test(g)?at.arm:/^(wrist|thumb|index|middle|ring|pinky)/.test(g)?at.hand:/^(thigh|shin)/.test(g)?at.leg:/^foot/.test(g)?at.foot:/^(head|jaw|lid)/.test(g)?at.head:at.torso,r.yt[f]=p[1]-c.torso[1],r.x[f]=p[0],r.z[f]=p[2];const v=c[`arm${x}`],w=c[`fore${x}`],C=c[`wrist${x}`];let M=d(p,v,w);M>1&&(M=1+d(p,w,C),M>2&&(M=2+Math.hypot(p[0]-C[0],p[1]-C[1],p[2]-C[2])/.19)),r.armT[f]=M;const S=c[`thigh${x}`],I=c[`shin${x}`],y=c[`foot${x}`];let k=d(p,S,I);k>1&&(k=1+d(p,I,y)),r.legT[f]=k,r.footY[f]=p[1]-y[1],r.cat[f]===at.foot&&(r.sole=Math.max(r.sole,-r.footY[f]))}return io.set(i,r),r}function my(e,n,s){const a=Wt(-.015,.05,s),i=Math.abs(n);switch(e){case"crew":return .565-.045*a*Math.max(0,1-(i/.07)**2);case"collar":return .6-.065*a*Math.max(0,1-i/.035);case"v":return .565-.13*a*Math.max(0,1-i/.08);case"deepv":return .57-.24*a*Math.max(0,1-i/.1);case"scoop":return .53-.1*a*Math.max(0,1-(i/.11)**2);case"high":return .62-.02*a}}function Uc(e,n,s=.134){return a=>{const i=e.cat[a];if(i===at.head||i===at.foot)return-1;if(i===at.arm||i===at.hand)return n.sleeve<0?Math.min(-.01,s-Math.abs(e.x[a])):(n.sleeve-e.armT[a])*.29;let r=Math.min(e.yt[a]-n.hem,my(n.neck,e.x[a],e.z[a])-e.yt[a]);return n.sleeve<0&&(r=Math.min(r,s-Math.abs(e.x[a])+2.5*Math.max(0,.3-e.yt[a]))),r}}function py(e,n){return s=>{const a=e.cat[s];if(a===at.head||a===at.arm||a===at.hand)return-1;const i=n.waist-e.yt[s];return a===at.torso?i:Math.min(i,(n.leg-e.legT[s])*.43)}}const ga=new Map;function fy(e,n,s,a){const{out:i,nv:r,idx:l}=a,c=new Map,u=new Map;for(let O=0;O<l.length;O+=3)for(let _=0;_<3;_++){const $=l[O+_],P=l[O+(_+1)%3],W=Math.min($,P)*r+Math.max($,P);c.set(W,(c.get(W)??0)+1),u.set(W,[$,P])}const m=new Map;for(const[O,_]of c)if(_===1){const[$,P]=u.get(O);m.set(P,$)}let d=1+s.hem,f=null;const p=new Set;for(const O of m.keys()){if(p.has(O))continue;const _=[];let $=O;for(;!p.has($)&&m.has($);)p.add($),_.push($),$=m.get($);if(_.length<12)continue;const P=_.map(z=>i[z*3+1]),W=_.map(z=>i[z*3]);if(Math.max(...P.map(z=>Math.abs(z-d)))<.05&&Math.min(...W)<-.05&&Math.max(...W)>.05){f=_;break}}if(!f)return null;d=Math.min(...f.map(O=>i[O*3+1]));for(const O of f)i[O*3+1]=d;const x=120,g=.01,v=Math.ceil(s.length/g)+2,w=new Float32Array(x*v);for(let O=0;O<s.cat.length;O++){const _=s.cat[O];if(_===at.arm||_===at.hand||_===at.head)continue;const $=n[O*3+1],P=Math.round((d-$)/g);if(P<0||P>=v)continue;const W=n[O*3],z=n[O*3+2],Q=(Math.round(Math.atan2(W,z)/(Math.PI*2)*x)%x+x)%x;w[P*x+Q]=Math.max(w[P*x+Q],Math.hypot(W,z))}for(let O=0;O<v;O++)for(let _=0;_<4;_++){const $=w.slice(O*x,(O+1)*x);for(let P=0;P<x;P++)w[O*x+P]=Math.max($[P],($[(P+1)%x]+$[(P+x-1)%x])/2*.998)}{const O=w.slice(),_=($,P)=>$<0||$>=v?0:O[$*x+(P+x)%x];for(let $=0;$<v;$++)for(let P=0;P<x;P++){let W=0;for(let z=-1;z<=1;z++)for(let Q=-1;Q<=1;Q++)W=Math.max(W,_($+z,P+Q));w[$*x+P]=W}}const C=(O,_)=>{const $=(O/(Math.PI*2)*x+x*4)%x,P=Math.floor($),W=$-P,z=Math.min(v-1,Math.max(0,Math.round(_/g)));return w[z*x+P]*(1-W)+w[z*x+(P+1)%x]*W},M=e.bones.indexOf("pelvis"),S=e.bones.indexOf("thighHalfL"),I=e.bones.indexOf("thighHalfR"),y=e.bones.indexOf("thighL"),k=e.bones.indexOf("thighR"),T=f.length,j=Math.max(3,Math.round(s.length/.012)),L=[...i],N=f.map(O=>Math.hypot(i[O*3],i[O*3+2]));let A=f.slice();for(let O=1;O<=j;O++){const _=s.length*O/j,$=[];for(let W=0;W<T;W++){const z=f[W],Q=Math.atan2(i[z*3],i[z*3+2]);$.push(Math.max(N[W]-s.tuck*(s.length/j),C(Q,_)+a.th[z]+.004+.01*Math.min(1,_/.012)))}for(let W=0;W<3;W++){const z=$.slice();for(let Q=0;Q<T;Q++)$[Q]=Math.max(z[Q],(z[(Q+1)%T]+z[(Q+T-1)%T])/2)}const P=[];for(let W=0;W<T;W++){const z=f[W],Q=Math.atan2(i[z*3],i[z*3+2]),J=$[W]*(1+s.flare*_),V=L.length/3;L.push(Math.sin(Q)*J,d-_,Math.cos(Q)*J),a.base.push(Math.sin(Q)*(J-a.th[z]),d-_,Math.cos(Q)*(J-a.th[z])),a.nrm.push(Math.sin(Q),0,Math.cos(Q)),a.th.push(a.th[z]);const B=Math.min(1,_/.03),q=i[z*3],D=Wt(.015,.07,Math.abs(q)),ee=.45*D,Z=(Math.cos(Q)>0?.55:.3)*Wt(.1,.7,Math.abs(Math.cos(Q))),xe=Wt(-.04,.04,q),be=new Map;for(let X=0;X<4;X++){const re=a.sw[z*4+X];re&&be.set(a.si[z*4+X],(be.get(a.si[z*4+X])??0)+re*(1-B))}be.set(M,(be.get(M)??0)+B*(1-ee-Z));const U=q<0?S:I;if(be.set(U,(be.get(U)??0)+B*ee),Z>0)for(const[X,re]of[[y,1-xe],[k,xe]])re>0&&be.set(X,(be.get(X)??0)+B*Z*re);const pe=[...be].sort((X,re)=>re[1]-X[1]).slice(0,4);let me=0;for(const[,X]of pe)me+=X;for(let X=0;X<4;X++)a.si.push(pe[X]?.[0]??0),a.sw.push(pe[X]?pe[X][1]/me:0);a.col.length&&a.col.push(a.col[z*3],a.col[z*3+1],a.col[z*3+2]),P.push(V),N[W]=$[W]}for(let W=0;W<T;W++){const z=A[W],Q=A[(W+1)%T],J=P[W],V=P[(W+1)%T];l.push(z,Q,V,z,V,J)}A=P}return{out:Float32Array.from(L),nv:L.length/3}}function gy(e,n,s,a,i,r,l={}){const c=`${s}|${Fn(n)}|${a}`;let u=ga.get(c);if(u)return u;ga.size>96&&(ga.forEach(X=>X.geometry.userData.realDispose?.()),ga.clear());const m=e.lods[s],d=ds(e,n,s),f=d.getAttribute("position").array,p=d.getAttribute("normal").array,x=m.vertices,g=new Float32Array(x),v=new Uint8Array(x);for(let X=0;X<x;X++){let re=i(X);Math.abs(re)<.0012&&(re=re>=0?.0012:-.0012),g[X]=re,re>.028&&(v[X]=1)}const w=[],C=[],M=[],S=[],I=[],y=[],k=[],T=new Int32Array(x).fill(-1),j=new Map,L=X=>{const re=new Map;for(let ue=0;ue<4;ue++){const Ee=m.skinWeight[X*4+ue];Ee&&re.set(m.skinIndex[X*4+ue],Ee/255)}return re},N=(X,re,ue,Ee,ye)=>{const ne=C.length/3;C.push(X[0],X[1],X[2]),w.push(re[0],re[1],re[2]),M.push(Ee);const Ie=[...ue].sort((we,de)=>de[1]-we[1]).slice(0,4);let ze=0;for(const[,we]of Ie)ze+=we;for(let we=0;we<4;we++)S.push(Ie[we]?.[0]??0),I.push(Ie[we]?Ie[we][1]/ze:0);return ye&&y.push(...ye),ne},A=X=>(T[X]<0&&(T[X]=N([f[X*3],f[X*3+1],f[X*3+2]],[p[X*3],p[X*3+1],p[X*3+2]],L(X),r(X),l.colors?.(X))),T[X]),O=(X,re)=>{const ue=X<re?X*x+re:re*x+X;let Ee=j.get(ue);if(Ee!==void 0)return Ee;const ye=g[X]/(g[X]-g[re]),ne=(se,he)=>se[X*3+he]+(se[re*3+he]-se[X*3+he])*ye,Ie=L(X),ze=L(re),we=new Map;for(const[se,he]of Ie)we.set(se,he*(1-ye));for(const[se,he]of ze)we.set(se,(we.get(se)??0)+he*ye);const de=l.colors?.(X),H=l.colors?.(re);return Ee=N([ne(f,0),ne(f,1),ne(f,2)],[ne(p,0),ne(p,1),ne(p,2)],we,r(X)*(1-ye)+r(re)*ye,de&&H?[de[0]*(1-ye)+H[0]*ye,de[1]*(1-ye)+H[1]*ye,de[2]*(1-ye)+H[2]*ye]:void 0),j.set(ue,Ee),Ee},_=m.index;for(let X=0;X<_.length;X+=3){const re=[_[X],_[X+1],_[X+2]],ue=re.map(we=>g[we]>0),Ee=ue.filter(Boolean).length;if(!Ee)continue;if(Ee===3){k.push(A(re[0]),A(re[1]),A(re[2]));continue}let ye=0;Ee===1?ye=ue.indexOf(!0):ye=ue.indexOf(!1);const ne=re[ye],Ie=re[(ye+1)%3],ze=re[(ye+2)%3];if(Ee===1)k.push(A(ne),O(ne,Ie),O(ne,ze));else{const we=O(ne,Ie),de=O(ne,ze);k.push(we,A(Ie),A(ze),we,A(ze),de)}}let $=C.length/3;const P=Array.from({length:$},()=>[]);for(let X=0;X<k.length;X+=3)for(let re=0;re<3;re++){const ue=k[X+re],Ee=k[X+(re+1)%3];P[ue].push(Ee),P[Ee].push(ue)}if(l.smoothBase){const X=l.smoothBaseAbove,re=l.smoothBaseLift,ue=we=>X==null?1:Wt(X,X+.1,C[we*3+1])*Wt(.15,.45,w[we*3+2]),Ee=Float64Array.from({length:$},(we,de)=>ue(de)),ye=Float64Array.from({length:$},(we,de)=>re==null?0:1-Wt(re,re+.1,C[de*3+1])),ne=we=>{const de=Float64Array.from(C);for(let H=0;H<$;H++){if(!P[H].length||!Ee[H])continue;let se=0,he=0,ce=0;for(const $e of P[H])se+=C[$e*3],he+=C[$e*3+1],ce+=C[$e*3+2];const Pe=1/P[H].length,Be=we*Ee[H];let ot=(se*Pe-C[H*3])*Be,G=(he*Pe-C[H*3+1])*Be,Se=(ce*Pe-C[H*3+2])*Be;const le=ot*w[H*3]+G*w[H*3+1]+Se*w[H*3+2];le<0&&ye[H]&&(ot-=w[H*3]*le*ye[H],G-=w[H*3+1]*le*ye[H],Se-=w[H*3+2]*le*ye[H]),de[H*3]=C[H*3]+ot,de[H*3+1]=C[H*3+1]+G,de[H*3+2]=C[H*3+2]+Se}for(let H=0;H<de.length;H++)C[H]=de[H]};for(let we=0;we<l.smoothBase;we++)ne(.5);const Ie=new Ct;Ie.setAttribute("position",new Ot(C,3)),Ie.setIndex(k),Ie.computeVertexNormals();const ze=Ie.getAttribute("normal");for(let we=0;we<$;we++)w[we*3]=ze.getX(we),w[we*3+1]=ze.getY(we),w[we*3+2]=ze.getZ(we);Ie.dispose()}let W=new Float32Array($*3);for(let X=0;X<$;X++)for(let re=0;re<3;re++)W[X*3+re]=C[X*3+re]+w[X*3+re]*M[X];const z=l.smooth??4,Q=new Map;for(let X=0;X<k.length;X+=3)for(let re=0;re<3;re++){const ue=k[X+re],Ee=k[X+(re+1)%3],ye=Math.min(ue,Ee)*$+Math.max(ue,Ee);Q.set(ye,(Q.get(ye)??0)+1)}const J=Array.from({length:$},()=>[]);for(const[X,re]of Q)if(re===1){const ue=Math.floor(X/$),Ee=X%$;J[ue].push(Ee),J[Ee].push(ue)}for(let X=0;X<z+8;X++){const re=Float32Array.from(W);for(let ue=0;ue<$;ue++){const Ee=J[ue].length?J[ue]:P[ue];if(!Ee.length||X>=z&&!J[ue].length)continue;let ye=0,ne=0,Ie=0;for(const we of Ee)ye+=W[we*3],ne+=W[we*3+1],Ie+=W[we*3+2];const ze=1/Ee.length;re[ue*3]=W[ue*3]*.5+ye*ze*.5,re[ue*3+1]=W[ue*3+1]*.5+ne*ze*.5,re[ue*3+2]=W[ue*3+2]*.5+Ie*ze*.5}for(let ue=0;ue<$;ue++){const Ee=re[ue*3]-C[ue*3],ye=re[ue*3+1]-C[ue*3+1],ne=re[ue*3+2]-C[ue*3+2],Ie=Ee*w[ue*3]+ye*w[ue*3+1]+ne*w[ue*3+2],ze=M[ue]*.85;if(Ie<ze)for(let we=0;we<3;we++)re[ue*3+we]+=w[ue*3+we]*(ze-Ie)}W.set(re)}if(l.band){const X=fy(e,f,l.band,{out:W,base:C,nrm:w,th:M,si:S,sw:I,col:y,idx:k,nv:$});X&&(W=X.out,$=X.nv)}if(l.sole)for(let X=0;X<$;X++){const re=W[X*3+1];if(re<l.sole.y+.02){const ue=Wt(l.sole.y+.02,l.sole.y-.005,re);W[X*3+1]=re-l.sole.th*ue,W[X*3+1]<l.sole.y-l.sole.th&&(W[X*3+1]=l.sole.y-l.sole.th)}}const V=new Map;for(let X=0;X<k.length;X+=3)for(let re=0;re<3;re++){const ue=k[X+re],Ee=k[X+(re+1)%3],ye=Math.min(ue,Ee)*$+Math.max(ue,Ee);V.has(ye)?V.delete(ye):V.set(ye,[ue,Ee])}const B=[],q=new Map,D=X=>{let re=q.get(X);return re===void 0&&(re=$+B.length/3,B.push(C[X*3]+w[X*3]*M[X]*.12,C[X*3+1]+w[X*3+1]*M[X]*.12,C[X*3+2]+w[X*3+2]*M[X]*.12),q.set(X,re)),re};for(const[X,re]of V.values()){const ue=D(X),Ee=D(re);k.push(re,X,ue,re,ue,Ee)}const ee=$+B.length/3,Z=[...q.keys()],xe=new Float32Array(ee*3);xe.set(W),xe.set(B,$*3);const be=new Uint8Array(ee*4),U=new Float32Array(ee*4),pe=y.length?new Float32Array(ee*3):null;be.set(S),U.set(I),pe?.set(y),Z.forEach((X,re)=>{for(let ue=0;ue<4;ue++)be[($+re)*4+ue]=S[X*4+ue],U[($+re)*4+ue]=I[X*4+ue];if(pe)for(let ue=0;ue<3;ue++)pe[($+re)*3+ue]=y[X*3+ue]});const me=new Ct;return me.setAttribute("position",new Nt(xe,3)),me.setAttribute("skinIndex",new ls(be,4)),me.setAttribute("skinWeight",new Nt(U,4)),pe&&me.setAttribute("color",new Nt(pe,3)),me.setIndex(k),me.computeVertexNormals(),me.userData.shared=!0,me.userData.realDispose=me.dispose.bind(me),me.dispose=()=>{},u={geometry:me,covered:v},ga.set(c,u),u}const Ra=8;function Ud(e,n,s=Ra){const a=Math.hypot(e[0],e[1],e[2])||1,i=e[0]/a,r=e[1]/a,l=e[2]/a;let c=1-i*i,u=-i*r,m=-i*l;const d=Math.hypot(c,u,m);d<1e-4?(c=-l*i,u=-l*r,m=1-l*l):(c/=d,u/=d,m/=d);const f=r*m-l*u,p=l*c-i*m,x=i*u-r*c,g=Math.atan2(n[0]*f+n[1]*p+n[2]*x,n[0]*c+n[1]*u+n[2]*m);return(Math.round(g/(Math.PI*2)*s)%s+s)%s}const ro=new Map;function xy(e,n){const s=Fn(n);let a=ro.get(s);if(a)return a;const i=Kr(e,0,n),r=ds(e,n,0).getAttribute("position").array,l=Uh(qo({...n,head:1,posture:0},Sr,{bind:!0})),c=12,u=Ra;a={L:{thigh:new Float32Array(c*u),shin:new Float32Array(c*u)},R:{thigh:new Float32Array(c*u),shin:new Float32Array(c*u)}};for(const m of["L","R"])for(const[d,f,p]of[["thigh",`thigh${m}`,`shin${m}`],["shin",`shin${m}`,`foot${m}`]]){const x=l.get(f).t,g=l.get(p).t,v=[g[0]-x[0],g[1]-x[1],g[2]-x[2]],w=v[0]**2+v[1]**2+v[2]**2,C=a[m][d];for(let S=0;S<i.cat.length;S++){const I=d==="thigh"&&i.cat[S]===at.torso&&r[S*3+1]<x[1]+.02&&r[S*3+2]<x[2]+.02;if(i.cat[S]!==at.leg&&!I||Math.sign(r[S*3])!==(m==="L"?-1:1))continue;const y=[r[S*3]-x[0],r[S*3+1]-x[1],r[S*3+2]-x[2]],k=(y[0]*v[0]+y[1]*v[1]+y[2]*v[2])/w,T=I?Math.max(0,k):k;if(T<0||T>(I?.35:1)||I&&k<-.12)continue;const j=[y[0]-v[0]*T,y[1]-v[1]*T,y[2]-v[2]*T],L=Math.hypot(j[0],j[1],j[2]);if(L>(d==="thigh"&&T<.4&&j[2]<0?.18:.12))continue;const N=Math.min(c-1,Math.floor(T*c)),A=Ud(v,j,u);C[N*u+A]=Math.max(C[N*u+A],L)}const M=C.slice();for(let S=0;S<c;S++)for(let I=0;I<u;I++){let y=0;for(const k of[S-1,S,S+1])for(const T of[I-1,I,I+1])k<0||k>=c||(y=Math.max(y,M[k*u+(T+u)%u]));C[S*u+I]=y}for(let S=0;S<c;S++)for(let I=0;I<u;I++)C[S*u+I]||(C[S*u+I]=S?C[(S-1)*u+I]:.06)}return ro.size>48&&ro.clear(),ro.set(s,a),a}const Xc=new Map;function by(e,n,s,a,i,r){const l=`${s}|${Fn(n)}|${JSON.stringify(a)}|${i}|${r}`;let c=Xc.get(l);if(c)return c;const u=ds(e,n,s),m=u.getAttribute("position"),d=Kr(e,s,n),f=e.bind,p=r==="cape",x=p?"torso":"pelvis",g=f.torso[1]+a.top,v=72,w=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==at.torso&&d.cat[V]!==at.leg&&!(p&&d.cat[V]===at.arm&&d.armT[V]<.15)||Math.abs(m.getY(V)-g)>.025)continue;const B=m.getX(V),q=m.getZ(V),D=Math.atan2(B,q),ee=(Math.round(D/(Math.PI*2)*v)%v+v)%v;w[ee]=Math.max(w[ee],Math.hypot(B,q))}const C=a.panels==="apron"?.34:.2,M=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==at.torso&&!(C>.2&&d.cat[V]===at.leg))continue;const B=g-m.getY(V);if(B<0||B>C)continue;const q=m.getX(V),D=m.getZ(V),ee=Math.atan2(q,D),Z=(Math.round(ee/(Math.PI*2)*v)%v+v)%v;M[Z]=Math.max(M[Z],Math.hypot(q,D))}for(let V=0;V<3;V++){const B=Float32Array.from(w),q=Float32Array.from(M);for(let D=0;D<v;D++)w[D]=Math.max(B[D],(B[(D+v-1)%v]+B[(D+1)%v])/2),M[D]=Math.max(q[D],(q[(D+v-1)%v]+q[(D+1)%v])/2)}const S=V=>{const B=(V/(Math.PI*2)*v+v*4)%v,q=Math.floor(B),D=B-q;return M[q%v]*(1-D)+M[(q+1)%v]*D+.014+i*.006},I=V=>{const B=(V/(Math.PI*2)*v+v*4)%v,q=Math.floor(B),D=B-q;return w[q%v]*(1-D)+w[(q+1)%v]*D+.008+i*.006},y=(()=>{if(!p)return()=>0;const V=Math.ceil((a.length+.1)/.02),B=new Float32Array(V);for(let q=0;q<m.count;q++){if(d.cat[q]!==at.torso&&d.cat[q]!==at.leg)continue;const D=Math.floor((g-m.getY(q))/.02),ee=m.getZ(q);D<0||D>=V||ee>=0||Math.abs(m.getX(q))>.16||(B[D]=Math.max(B[D],-ee))}for(let q=1;q<V;q++)B[q]=Math.max(B[q],B[q-1]);return q=>{const D=g-q,ee=Math.max(0,Math.min(V-1,Math.floor(D/.02)));return B[ee]+.012+(a.clear??0)*Math.min(1,Math.max(0,(D-.35)/Math.max(.1,a.length-.35)))}})(),k=V=>p?.07*Math.sin(V)**2:0,T=V=>r==="cape"?I(V):Math.max(I(V),S(V)),j=V=>Math.max(T(V)*1.04,I(V)*a.flare),L=p?[[Math.PI*.55,Math.PI*1.45]]:a.panels==="aodai"?[[-.95,.95],[Math.PI-1.3,Math.PI+1.3]]:a.panels==="apron"?[[-1.1,1.1]]:a.open?[[a.open*Math.PI/180,Math.PI*2-a.open*Math.PI/180]]:[[0,Math.PI*2]],N=!p&&!a.panels&&!a.open,A=[],O=[],_=[],$=[],P=[],W=[],z=4,Q=Math.max(16,Math.round(a.length/.022));p?f.torso[1]:f.torso[1]-.07;for(const[V,B]of L){const q=B-V,D=Math.max(2,Math.round((a.chains??12)*q/(Math.PI*2))+(N?0:1)),ee=Math.max(8,Math.round(56*q/(Math.PI*2))),Z=P.length;for(let be=0;be<D;be++){const U=N?V+q*be/D:V+q*be/(D-1),pe=I(U),me=[Math.sin(U)*pe,g-k(U),Math.cos(U)*pe],X=(p?pe*a.flare:j(U))+(p?.03:0),re=[Math.sin(U)*X,g-a.length,Math.cos(U)*X];p&&(re[2]=Math.min(re[2],-.12-.02*Math.abs(Math.sin(U)),Math.cos(U)*y(re[1])));const ue=[(re[0]-me[0])/z,(re[1]-me[1])/z,(re[2]-me[2])/z];P.push({at:me,dirs:Array.from({length:z},()=>ue),seg:be})}const xe=A.length/3;W.push({base:xe,width:ee+1,rows:Q+1,wrap:N});for(let be=0;be<=Q;be++){const U=be/Q;for(let pe=0;pe<=ee;pe++){const me=V+q*pe/ee,X=I(me),re=(a.folds??0)*Math.sin(me*(p?14:22))*U,ue=T(me),Ee=p?0:Math.min(1,a.length*U/C),ye=X+(ue-X)*Math.sin(Math.min(1,Ee)*Math.PI/2);let ne=(p?X+(X*a.flare+.03-X)*U:U*a.length<=C?ye:ue+(j(me)-ue)*((a.length*U-C)/Math.max(1e-6,a.length-C)))+re,Ie=Math.cos(me)*ne;p&&(Ie=Math.min(Ie,Math.cos(me)*X+(-.12-Math.cos(me)*X)*U,Math.cos(me)*y(g-a.length*U))),A.push(Math.sin(me)*ne,g-k(me)*(1-U)-a.length*U,Ie);const ze=N?(me-V)/q*D:(me-V)/q*(D-1);let we=Math.floor(ze),de=ze-we;N?we%=D:we>=D-1&&(we=D-2,de=1);const H=N?(we+1)%D:we+1,se=U*z,he=Math.min(z-1,Math.floor(se)),ce=Math.min(1,se-he),Pe=Math.min(z-1,he+1),Be=[[(Z+we)*z+he,(1-de)*(Pe===he?1:1-ce)],[(Z+H)*z+he,de*(Pe===he?1:1-ce)]];for(Pe!==he&&Be.push([(Z+we)*z+Pe,(1-de)*ce],[(Z+H)*z+Pe,de*ce]);Be.length<4;)Be.push([0,0]);for(const[ot,G]of Be)_.push(ot),$.push(G)}}for(let be=0;be<Q;be++)for(let U=0;U<ee;U++){const pe=xe+be*(ee+1)+U,me=pe+ee+1;O.push(pe,me,pe+1,pe+1,me,me+1)}}const J=new Ct;return J.setAttribute("position",new Ot(A,3)),J.setAttribute("skinIndex",new sd(_,4)),J.setAttribute("skinWeight",new Ot($,4)),J.setIndex(O),J.computeVertexNormals(),J.userData.shared=!0,J.userData.rings=W,J.dispose=()=>{},c={geometry:J,roots:P,anchor:x},Xc.set(l,c),c}function yy(e,n,s){const a=e.bones.get(n.anchor),i=[],r=new Map,l=[],c=n.anchor==="torso"?new ie(0,1,0):new ie(0,.93,0);return n.roots.forEach((u,m)=>{let d=a,f=new ie(...u.at);const p=[],x=[];u.dirs.forEach((g,v)=>{const w=new La;w.name=`${s}${m}_${v}`;const C=v===0?f.clone().sub(c):new ie(...u.dirs[v-1]);w.position.copy(C),d.add(w),e.bones.set(w.name,w),r.set(w.name,new St().makeTranslation(-f.x,-f.y,-f.z)),i.push(w.name),p.push(w),x.push(new ie(...g)),d=w,f=f.clone().add(new ie(...g))}),l.push({bones:p,rest:x,kind:"cloth",stiffness:.5,collide:!0,side:m})}),{bones:i,inverses:r,set:{kind:"cloth",anchor:n.anchor,chains:l}}}const lo=new Map;function co(e,n,s,a,i,r,l){const c=e.pos.length/3,u=a?n:n+1;for(const f of[0,1])for(let p=0;p<=s;p++)for(let x=0;x<u;x++){const g=i(x/n,p/s,f),[v,w]=l(x/n,p/s);e.pos.push(...g),e.col.push(...r(x/n,p/s,f,g[1]));for(let C=0;C<4;C++)e.si.push(v[C]??0),e.sw.push(w[C]??0)}const m=(f,p,x)=>c+f*u*(s+1)+x*u+(a?p%n:p);for(let f=0;f<s;f++)for(let p=0;p<n;p++){const x=k=>[m(k,p,f),m(k,p+1,f),m(k,p+1,f+1),m(k,p,f+1)],[g,v,w,C]=x(0),[M,S,I,y]=x(1);e.idx.push(g,v,w,g,w,C,M,I,S,M,y,I)}const d=(f,p)=>{const x=m(0,...f),g=m(0,...p),v=m(1,...f),w=m(1,...p);e.idx.push(x,v,w,x,w,g)};for(let f=0;f<n;f++)d([f,0],[f+1,0]),d([f+1,s],[f,s]);if(!a)for(let f=0;f<s;f++)d([n,f],[n,f+1]),d([0,f+1],[0,f])}function vy(e,n,s,a,i,r,l,c,u=0){const m=`${s}|${Fn(n)}|${i}|${l}|${c}|${u}`;let d=lo.get(m);if(d)return d;const f=ds(e,n,s),p=f.getAttribute("position").array,x=a.cat.length,g=new Uint8Array(x),v={pos:[],idx:[],si:[],sw:[],col:[]},w=new Qe(l),C=_=>{const $=new Qe(_);return[$.r/Math.max(.02,w.r),$.g/Math.max(.02,w.g),$.b/Math.max(.02,w.b)]},M=w.r*.3+w.g*.59+w.b*.11,S=C(c),I=C(M>.55?"#8d8f94":"#d9d9d4"),y=C(M>.45?"#2b2c30":"#efefea"),k=C(w.clone().multiplyScalar(.45)),T=i==="boots"?.036:i==="heels"?.022:i==="sandals"?0:i==="sneakers"?.032:.026,j=40,L=12,N=i==="sneakers"?.0045:.003,A=i==="sneakers"?.12:.45;for(const _ of["L","R"]){const $=e.bind[`foot${_}`],P=e.bones.indexOf(`foot${_}`),W=e.bones.indexOf(`shin${_}`),z=[],Q=[];for(let de=0;de<x;de++)a.cat[de]===at.foot&&Math.sign(p[de*3])===(_==="L"?-1:1)&&(Q.push(de),a.footY[de]<-.012&&z.push(de));if(!z.length)continue;let J=1/0,V=-1/0;for(const de of z)J=Math.min(J,p[de*3+2]),V=Math.max(V,p[de*3+2]);J-=.006,V+=i==="heels"||i==="dress"?.02:i==="sandals"?.008:.014;const B=14,q=new Float64Array(B),D=new Float64Array(B),ee=new Float64Array(B);for(let de=0;de<B;de++){const H=J+(V-J)*(de/B),se=J+(V-J)*((de+1)/B);let he=1/0,ce=-1/0,Pe=-1/0;for(const Be of Q){const ot=p[Be*3+2];ot<H-.01||ot>se+.01||a.footY[Be]>.035||(he=Math.min(he,p[Be*3]),ce=Math.max(ce,p[Be*3]),Pe=Math.max(Pe,p[Be*3+1]))}he===1/0?(q[de]=de?q[de-1]:$[0],D[de]=de?D[de-1]:.04,ee[de]=de?ee[de-1]:$[1]-.03):(q[de]=(he+ce)/2,D[de]=(ce-he)/2,ee[de]=Pe)}const Z=(de,H)=>{const se=Math.min(B-1,Math.max(0,H*B-.5)),he=Math.floor(se),ce=Math.min(B-1,he+1),Pe=se-he;return de[he]*(1-Pe)+de[ce]*Pe},xe=$[1]-a.sole-r,be=xe+r,U=_==="L"?1:-1,pe=de=>{const H=Math.sqrt(Math.max(0,1-((.17-Math.min(de,.17))/.17)**2)),se=Math.max(0,(de-.62)/.38),he=Math.max(Z(D,de),.028)+.006;return{w:he*H*Math.sqrt(Math.max(0,1-Math.pow(se,2.4))),x0:Z(q,de)+U*he*.28*Math.pow(se,1.5),spring:.008*Wt(.7,1,de)**2,z:J+(V-J)*de}},me=$[1]-(i==="sneakers"?.012:i==="boots"?-.04:i==="heels"?.04:.018),X=i==="heels"?.6:i==="boots"?0:i==="sneakers"?.44:.5,re=i==="sneakers"||i==="boots"?.74:.66,ue=de=>{const H=Math.max(Math.min($[1]+(i==="boots"?.02:i==="sneakers"?.004:-.006),Z(ee,de)+.009),be+T)-be;return Math.max(.004,H*Math.sqrt(Math.max(0,1-Math.pow(Math.max(0,(de-re)/(1-re)),2))))},Ee=Math.min(me,Z(ee,X)+(i==="heels"?-.004:.006)),ye=de=>de>=X?1/0:de<.28?me:me+(Ee-me)*Wt(.28,X,de),ne=de=>Math.max(ue(de),Number.isFinite(ye(de))?ye(de)-be+.025*(1-Wt(X-.06,X,de)):0),Ie=(de,H,se)=>{const he=pe(de),ce=Math.cos(H),Pe=Math.max(0,Math.sin(H)),Be=Math.sign(ce)*Math.pow(Math.abs(ce),.8);return[he.x0+(he.w+se)*Be*(1-.16*Pe),be+he.spring-r*A+(ne(de)+r*A+se)*Math.pow(Pe,.85),he.z]},ze=de=>{const H=ye(de);if(!Number.isFinite(H))return Math.PI/2;const se=(H-be-pe(de).spring+r*A)/(ne(de)+r*A);return se>=1?Math.PI/2:Math.asin(Math.max(.05,Math.pow(Math.max(0,se),1/.85)))},we=()=>[[P],[1]];for(const de of Q){const H=Math.min(1,Math.max(0,(p[de*3+2]-J)/(V-J))),se=p[de*3+1];i==="sandals"?se<be+.004&&(g[de]=1):i==="heels"?(H>=X-.03||se<ye(H)-.005)&&(g[de]=1):g[de]=1}if(co(v,j,16,!1,(de,H,se)=>{const he=pe(de),ce=i==="heels"?.001:i==="sneakers"?.006:.0035,Pe=H*Math.PI*2,Be=Math.cos(Pe),ot=Math.sin(Pe),G=se?.6:1;return[he.x0+(he.w*1.03+ce)*G*Math.sign(Be)*Math.pow(Math.abs(Be),.35),xe+he.spring+r*.5+r*.5*G*Math.sign(ot)*Math.pow(Math.abs(ot),.35),he.z]},(de,H,se,he)=>i==="sneakers"&&he>xe+r*.62&&he<xe+r*.8?I:S,we),i==="sandals"){for(const[de,H]of[[.6,.66],[.38,.44]])co(v,6,16,!1,(se,he,ce)=>{const Pe=de+(H-de)*se,Be=pe(Pe),ot=Math.PI*he,G=Math.cos(ot),Se=Math.sin(ot),le=ce?.002:.0045,$e=Math.max(.006,Z(ee,Pe)+.004-be);return[Be.x0+(Be.w+le-.004)*Math.sign(G)*Math.pow(Math.abs(G),.7),be+Be.spring-.001+($e+le)*Math.pow(Se,.8),Be.z]},()=>[1,1,1],we);continue}for(const de of[1,-1])co(v,j,L,!1,(H,se,he)=>{const ce=ze(H),Pe=de>0?ce*se:Math.PI-ce*se;return Ie(H,Pe,he?0:N)},(H,se,he)=>he?H<X+.05?k:[1,1,1]:i==="sneakers"&&H>.44&&H<.68&&se>.82&&Math.sin(H*Math.PI*42)>.2?y:[1,1,1],we);if(i==="boots"){const de=ce=>{for(let Pe=.015;;Pe*=1.5){let Be=1/0,ot=-1/0,G=1/0,Se=-1/0,le=0;for(let $e=0;$e<x;$e++)a.cat[$e]!==at.leg&&a.cat[$e]!==at.foot||Math.sign(p[$e*3])!==(_==="L"?-1:1)||Math.abs(p[$e*3+1]-ce)>Pe||(le++,Be=Math.min(Be,p[$e*3]),ot=Math.max(ot,p[$e*3]),G=Math.min(G,p[$e*3+2]),Se=Math.max(Se,p[$e*3+2]));if(le>=24||Pe>.1)return{cx:(Be+ot)/2,cz:(G+Se)/2,rx:(ot-Be)/2,rz:(Se-G)/2}}},H=$[1]+.005,se=$[1]+.2,he=Array.from({length:9},(ce,Pe)=>{const Be=H+(se-H)*(Pe/8);return{y:Be,...de(Be)}});for(let ce=7;ce>=0;ce--)he[ce].rx=Math.max(he[ce].rx,he[ce+1].rx*.9),he[ce].rz=Math.max(he[ce].rz,he[ce+1].rz*.9);co(v,32,8,!0,(ce,Pe,Be)=>{const ot=he[Math.round(Pe*8)],G=ce*Math.PI*2,Se=u+(Be?.004:.0075);return[ot.cx+(ot.rx+Se)*Math.sin(G),ot.y,ot.cz+(ot.rz+Se)*Math.cos(G)]},()=>[1,1,1],(ce,Pe)=>{const Be=Wt($[1]-.01,$[1]+.05,he[Math.round(Pe*8)].y);return[[P,W],[1-Be,Be]]})}}const O=new Ct;return O.setAttribute("position",new Ot(v.pos,3)),O.setAttribute("skinIndex",new ls(v.si,4)),O.setAttribute("skinWeight",new Ot(v.sw,4)),O.setAttribute("color",new Ot(v.col,3)),O.setIndex(v.idx),O.computeVertexNormals(),O.userData.shared=!0,O.userData.realDispose=O.dispose.bind(O),O.dispose=()=>{},d={geometry:O,hide:g},lo.size>48&&lo.clear(),lo.set(m,d),d}const jy=new St().makeTranslation(0,-.008,-.0155).multiply(new St().makeScale(.66,1,.75));function ky(e,n,s,a,i,r={}){const l=[],c=Kr(e,i,s),u=[],m=[],d=(S,I,y,k,T,j={},L)=>{const N=gy(e,s,i,S,I,L??(()=>y),j);N.geometry.getIndex()?.count&&(l.push({geometry:N.geometry,material:k,slot:T,skinned:!0}),u.push(N.covered),m.push(S))},f=S=>Rs(`fab:${uy(S)}:${S.color}`),p=(S,I,y,k,T="skirt")=>{if(r.fittedOnly)return;const j=by(e,s,i,S,I,T),L=yy(n,j,`${k}${T}`);l.push({geometry:j.geometry,material:y,slot:k,skinned:!0,bones:L.bones,inverses:L.inverses,chains:L.set,drape:T!=="cape"})},x=a.top?zo[a.top.type]??zo.tshirt:null,g=!!x&&!!a.bottom&&(["shirt","police","polo"].includes(a.top.type)&&["trousers","jeans","shorts","ancient"].includes(a.bottom.type)||!!pn[a.bottom.type]?.loose&&!x.loose),v=x&&g?{...x,hem:(pn[a.bottom.type]?.waist??.05)-.05}:x,w=S=>c.cat[S]===at.torso?.003:0;if(a.bottom){const S=pn[a.bottom.type]??pn.trousers,I=g?v.th+.005:0,y=a.shoes?.type==="boots"&&S.leg>1.6;d(`bottom|${a.bottom.type}|${g}|${y}`,py(c,y?{...S,leg:1.6}:S),S.th,f(a.bottom),"bottom",{},k=>(a.bottom.type==="ancient"?S.th*(.6+.6*Wt(.6,1.8,c.legT[k])):S.th)+(I?I*Wt(-.2,-.05,c.yt[k]):0)),S.loose&&p(S.loose,0,f(a.bottom),"bottom")}if(a.top){const S=v,I=!S.loose&&S.hem<fa,y=I?{...S,hem:fa}:S,k=a.top.color2,T=a.bottom&&!g?(pn[a.bottom.type]?.th??.007)+.002:0,j=y.stripes?A=>{const O=c.yt[A],$=(Math.abs(O-.12)<.018||Math.abs(O-.26)<.018)&&c.cat[A]===at.torso?new Qe(k??"#e6e6e0"):new Qe(a.top.color),P=new Qe(a.top.color);return[$.r/Math.max(.02,P.r),$.g/Math.max(.02,P.g),$.b/Math.max(.02,P.b)]}:void 0,L=j?Yc(f(a.top)):f(a.top),N=Math.max(1+y.hem+.1,T?1+(pn[a.bottom.type]?.waist??.06)+.08:0);d(`top|${a.top.type}|${k??""}|${g}|${T}|${N.toFixed(3)}`,Uc(c,y,.67*za(s).shoulderX),y.th,L,"top",{colors:j,smooth:6,...y.th>=.01?{smoothBase:6,smoothBaseLift:N}:{},...I&&fa-S.hem>.015?{band:{hem:fa,length:fa-S.hem,flare:.25,tuck:.3,cat:c.cat}}:{}},A=>y.th+w(A)+(T&&c.yt[A]<.12?T*Wt(.12,.04,c.yt[A]):0)+(y.neck==="collar"||y.neck==="high"?.005*Wt(.5,.58,c.yt[A]):0)),y.loose&&p(y.loose,1,f(a.top),"top")}if(a.outer){const S=a.outer.type;if(_o[S]){const I=_o[S],y=Math.max(1+I.hem+.1,a.bottom&&pn[a.bottom.type]?1+pn[a.bottom.type].waist+.08:0);d(`outer|${S}|${y.toFixed(3)}`,Uc(c,I,.67*za(s).shoulderX),I.th,f(a.outer),"outer",{smooth:6,smoothBase:6,smoothBaseLift:y},k=>I.th+(c.cat[k]===at.torso?.006:0)),I.loose&&p(I.loose,2,f(a.outer),"outer")}else if(S==="cape"){const I=[v?.loose,a.bottom?pn[a.bottom.type]?.loose:void 0].reduce((y,k)=>k?Math.max(y,.025+(k.flare-1)*.16):y,0);p({top:.47,length:1.05,flare:1.15,folds:.012,chains:10,...I?{clear:Math.round(I*1e3)/1e3}:{}},2,f(a.outer),"outer","cape")}else S==="apron"&&p({top:.12,length:.55,flare:1.04,panels:"apron",folds:.002,chains:5},2,f(a.outer),"outer")}if(a.shoes&&a.shoes.type!=="barefoot"){const S=a.shoes.type,I=S==="sneakers"?.027:S==="boots"?.022:S==="sandals"?.014:S==="heels"?.008:.014,y=S==="sneakers"?"#f4f4f0":S==="sandals"?mi(a.shoes.color,-.25):S==="boots"||S==="dress"||S==="heels"?mi(a.shoes.color,-.55):mi(a.shoes.color,-.3),k=a.shoes.fabric??(S==="sneakers"||S==="cloth"?"cotton":"leather"),T=Yc(Rs(k==="leather"?`sol:${a.shoes.color}:0.36:0`:`fab:${k}:${a.shoes.color}`));S!=="sandals"&&S!=="heels"&&S!=="boots"&&d(`socks|${S}`,N=>c.cat[N]===at.leg?(c.legT[N]-1.8)*.43:c.cat[N]===at.foot?Math.min((c.legT[N]-1.8)*.43,(c.footY[N]+.045)*.6,(e.bind.footL[2]+.02-c.z[N])*.6):-1,.0018,Rs(`fab:cotton:${S==="sneakers"?"#e9e9e4":"#2a2a2d"}`),"shoes",{smooth:3});const j=S==="boots"&&a.bottom?pn[a.bottom.type]?.th??.007:0,L=vy(e,s,i,c,S,I,a.shoes.color,y,j);if(l.push({geometry:L.geometry,material:T,slot:"shoes",skinned:!0}),u.push(L.hide),m.push(`last|${S}`),S==="heels"&&!r.fittedOnly)for(const N of["L","R"]){const A=new hs(.011,.0055,.072,12);A.scale(1,1,1.15),A.rotateX(-22*Math.PI/180),A.translate(0,-.086,-.092),l.push({geometry:A,material:Rs(`sol:${a.shoes.color}:0.4:0`),slot:"shoes",skinned:!1,bone:`foot${N}`})}}if(a.hat&&!r.fittedOnly)for(const S of ay(e,a.hat,a.hair?.style))l.push({geometry:S.geometry,material:Rs(S.mat),slot:S.slot,skinned:!1,bone:"head"});if(a.accessories?.length&&!r.fittedOnly){const S=Km({shoulders:s.shoulders,hips:s.hips,chest:s.chest,waist:s.waist,weight:s.weight,muscle:s.muscle,face:"simple"},"#888888");for(const I of Hm(S,{accessories:a.accessories})){const y=I.geo.clone();I.group==="head"&&y.applyMatrix4(Rb(e).multiply(jy)),l.push({geometry:y,material:Rs(I.mat),slot:"accessory",skinned:!1,bone:I.group})}}const C=[v?.loose,a.bottom?pn[a.bottom.type]?.loose:void 0].find(S=>S&&S.length>=.45&&!S.panels&&!S.open);if(C&&!r.fittedOnly&&(!a.bottom||pn[a.bottom.type]?.loose)){const S=new Uint8Array(c.cat.length);for(let I=0;I<S.length;I++)(c.cat[I]===at.torso&&c.yt[I]<C.top-.02||c.cat[I]===at.leg&&c.legT[I]<.3)&&(S[I]=1);u.push(S),m.push(`seat|${C.top}`)}let M=null;if(u.length){M=new Uint8Array(c.cat.length);for(const S of u)for(let I=0;I<S.length;I++)S[I]&&(M[I]=1)}return{parts:l,hide:M,hideKey:m.join("§")}}const Vc=new Map;function Yc(e){let n=Vc.get(e);return n||(n=e.clone(),n.vertexColors=!0,n.onBeforeCompile=e.onBeforeCompile,n.customProgramCacheKey=e.customProgramCacheKey,n.userData.shared=!0,n.dispose=()=>{},Vc.set(e,n)),n}const Fa=new tt,Qc=new tt,Zc=new tt,wy=new St,Xd=new St,Ms=new ie,qn=new ie,Xt=new ie,vn=new ie,zt=new ie,ho=new ie,en=new ie,Xs=new ie,on=Array.from({length:14},()=>({a:new ie,b:new ie,r:0,rb:0,lap:!1})),uo=[0,0,0],mo=[0,0,0],Vd=(e,n,s,a,i)=>{const r=e.length/Ra,l=Math.min(r-1,Math.max(0,n*r-.5)),c=Math.floor(l),u=l-c,m=Math.min(r-1,c+1);uo[0]=s.b.x-s.a.x,uo[1]=s.b.y-s.a.y,uo[2]=s.b.z-s.a.z,mo[0]=a.x-i.x,mo[1]=a.y-i.y,mo[2]=a.z-i.z;const d=Ud(uo,mo);return e[c*Ra+d]*(1-u)+e[m*Ra+d]*u};function Js(e,n,s,a){const i=e.bones.get(n);return s.set(...a??[0,0,0]).applyMatrix4(i.matrixWorld).applyMatrix4(Xd),s}const Ht=7;function Yd(e){Xd.copy(e.root.matrixWorld).invert();let n=0;const s=(a,i,r,l,c,u=r)=>{const m=on[n++];Js(e,a,m.a,l),Js(e,i,m.b,c),m.r=r,m.rb=u,m.lap=!1};s("torso","torso",.155,[0,-.06,-.01],[0,.36,-.02]),s("head","head",.105,[0,0,-.01],[0,.06,-.015]),s("armL","armR",.07);for(const a of["L","R"])s(`fore${a}`,`hand${a}`,.045),s(`hand${a}`,`hand${a}`,.048,[0,0,.005],[0,-.13,.01]);if(n!==Ht)throw new Error("HQ dynamics: leg capsules must start at LEGS");for(const a of["L","R"])s(`thigh${a}`,`shin${a}`,.088,void 0,void 0,.064),s(`shin${a}`,`foot${a}`,.062,void 0,void 0,.05),s(`foot${a}`,`foot${a}`,.058,[0,-.03,-.02],[0,-.04,.2]);for(const[a,i]of[[3,4],[5,6]]){const r=on[i];Xs.addVectors(r.a,r.b).multiplyScalar(.5);for(const l of[Ht,Ht+3]){Hr(on[l],Xs,en),qn.subVectors(Xs,en);const c=qn.length();c<.16&&qn.y>.6*c&&(on[a].lap=on[i].lap=!0)}}return n}function Hr(e,n,s){Ms.subVectors(e.b,e.a);const a=Ms.lengthSq(),i=a>1e-10?Math.max(0,Math.min(1,qn.subVectors(n,e.a).dot(Ms)/a)):0;return s.copy(e.a).addScaledVector(Ms,i),i}function Jc(e,n,s){const a=Hr(n,e,en),i=e.distanceTo(en),r=(n.prof?Vd(n.prof,a,n,e,en):n.r+(n.rb-n.r)*a)+s;i<r&&i>1e-6&&e.sub(en).multiplyScalar(r/i).add(en)}const eh=.68,My=(e,n,s)=>{const a=n.x-s.x,i=n.z-s.z,r=Math.hypot(a,i);if(r<1e-6)return e.r;const l=a/r,c=i/r;return e.r/Math.sqrt(l*l+c*c/(eh*eh))};function rr(e,n,s,a=!1){for(let i=0;i<n;i++){const r=on[i];if(a&&(i<2||r.lap))continue;const l=Hr(r,e,en),c=e.distanceTo(en),u=(r.prof?Vd(r.prof,l,r,e,en):i===0?My(r,e,en):r.r+(r.rb-r.r)*l)+s;c>=u||(c<1e-6?e.y-=u:e.sub(en).multiplyScalar(u/c).add(en))}}function Sy(e,n,s,a){e.root.updateMatrixWorld(!0);const i=Yd(e);on[Ht].prof=s.L.thigh,on[Ht+1].prof=s.L.shin,on[Ht+3].prof=s.R.thigh,on[Ht+4].prof=s.R.shin;for(let r=0;r<n.length;r+=3){zt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<5;l++)rr(zt,i,.007,!0);for(const l of[Ht,Ht+1,Ht+3,Ht+4])Jc(zt,on[l],.007);n[r]=zt.x,n[r+1]=zt.y,n[r+2]=zt.z}if(a?.some(r=>r.wrap)){for(const r of a)r.wrap&&Cy(n,r);for(let r=0;r<n.length;r+=3){zt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<2;l++)for(const c of[Ht,Ht+1,Ht+3,Ht+4])Jc(zt,on[c],.007);n[r]=zt.x,n[r+1]=zt.y,n[r+2]=zt.z}}for(const r of[0,1,3,4])on[Ht+r].prof=void 0}function Cy(e,n){const s=n.width-1,a=new Float64Array(s),i=new Float64Array(s),r=new Float64Array(s),l=new Float64Array(s),c=new Float64Array(s);for(let u=0;u<n.rows;u++){const m=n.base+u*n.width;let d=0,f=0;for(let S=0;S<s;S++)a[S]=e[(m+S)*3],i[S]=e[(m+S)*3+2],d+=a[S],f+=i[S];d/=s,f/=s;const p=Array.from({length:s},(S,I)=>I).sort((S,I)=>a[S]-a[I]||i[S]-i[I]),x=(S,I,y)=>(a[I]-a[S])*(i[y]-i[S])-(i[I]-i[S])*(a[y]-a[S]),g=[],v=[];for(const S of p){for(;g.length>=2&&x(g[g.length-2],g[g.length-1],S)<=0;)g.pop();g.push(S)}for(let S=p.length-1;S>=0;S--){const I=p[S];for(;v.length>=2&&x(v[v.length-2],v[v.length-1],I)<=0;)v.pop();v.push(I)}const w=[...g.slice(0,-1),...v.slice(0,-1)];for(let S=0;S<s;S++){const I=a[S]-d,y=i[S]-f,k=Math.hypot(I,y);if(l[S]=Math.atan2(I,y),r[S]=k,k<1e-6)continue;const T=I/k,j=y/k;let L=k;for(let N=0;N<w.length;N++){const A=w[N],O=w[(N+1)%w.length],_=a[O]-a[A],$=i[O]-i[A],P=T*$-j*_;if(Math.abs(P)<1e-9)continue;const W=a[A]-d,z=i[A]-f,Q=(W*$-z*_)/P,J=(W*j-z*T)/P;Q>0&&J>=-1e-6&&J<=1+1e-6&&(L=Math.max(L,Q))}r[S]=L}for(let S=0;S<s;S++){let I=0;for(let y=-2;y<=2;y++)I+=r[(S+y+s)%s];c[S]=Math.max(r[S],I/5)}for(let S=0;S<s;S++){const I=(m+S)*3;e[I]=d+Math.sin(l[S])*c[S],e[I+2]=f+Math.cos(l[S])*c[S]}const C=(m+s)*3,M=m*3;e[C]=e[M],e[C+1]=e[M+1],e[C+2]=e[M+2]}}const xa=(e,n,s)=>{const a=Math.min(1,Math.max(0,(s-e)/(n-e)));return a*a*(3-2*a)},An=new ie,Bo=new ie,th=new ie,lr={L:new ie,R:new ie},Co={L:new ie,R:new ie},cr={L:1,R:1},nh=e=>n=>An.subVectors(n,lr[e]).dot(Co[e])/cr[e],sh={L:new tt,R:new tt,alongL:nh("L"),alongR:nh("R")};function Ny(e,n){e.bones.get("torso").getWorldQuaternion(Fa).premultiply(n),th.set(0,-1,0).applyQuaternion(Fa);for(const s of["L","R"])Js(e,`thigh${s}`,lr[s]),Js(e,`shin${s}`,Bo),cr[s]=Math.max(1e-6,Co[s].subVectors(Bo,lr[s]).length()),Co[s].divideScalar(cr[s]),sh[s].setFromUnitVectors(th,Co[s]);return sh}function Ay(e,n,s,a){if(!e.length)return;const i=Yd(n),r=a?.vel??[0,0,0],l=a?.acc??[0,0,0],c=a?.time??0,u=a?.air??0,m=Math.hypot(r[0],r[1],r[2]);n.root.updateMatrixWorld(!0);const d=new tt;n.root.getWorldQuaternion(d);const f=d.clone().invert(),p=Ny(n,f);for(const x of e)x.chains.forEach((g,v)=>{const w=g.kind==="cloth",C=(w?.085:.05)*(1+.8*u),M=w?.012:.008,S=new ie(-r[0]*C-l[0]*M,-r[1]*C*.6-l[1]*M,-r[2]*C-l[2]*M),I=Math.min(1,m/3)*(w?.12:.06);g.bones.forEach((y,k)=>{const T=y.parent;T.updateWorldMatrix(!0,!1),T.getWorldQuaternion(Qc).premultiply(f);let j=y;for(let O=0;O<=k;O++)j=j.parent;j.getWorldQuaternion(Fa).premultiply(f),ho.copy(g.rest[k]).normalize();const L=g.rest[k].length()*T.getWorldScale(en).x*y.scale.x/n.root.getWorldScale(qn).x;Xt.copy(ho).applyQuaternion(Fa);const N=g.stiffness*(k===0?1.4:1);if(Xt.multiplyScalar(N).add(Ms.set(0,-(1-Math.min(.95,N)),0)).add(S),I){const O=c*(w?5.3:3.7)+v*1.7+k*.9;Xt.x+=Math.sin(O)*I,Xt.z+=Math.cos(O*.8)*I*.5}if(Xt.normalize(),wy.copy(y.matrixWorld),Js(n,y.name,vn),w&&x.anchor==="pelvis"){const O=g.bones[0].position,_=Math.atan2(O.x,O.z),$=xa(.06,-.06,O.x),P=$*p.alongL(vn)+(1-$)*p.alongR(vn),W=(.6+.3*(k/g.bones.length))*(.3+.7*xa(-.5,.4,Math.cos(_)))*(1-xa(.82,1.02,P)),z=xa(.85,1.05,P)*xa(.2,.7,Math.cos(_));if(z>0)for(const Q of["L","R"]){const J=Q==="L"?$:1-$;J<=0||(Js(n,`foot${Q}`,Bo,[0,-.02,.24]),An.subVectors(Bo,vn),An.lengthSq()>1e-8&&An.y<0&&Xt.lerp(An.normalize(),z*J).normalize())}W>0&&(An.copy(ho).applyQuaternion(Fa),Ms.copy(An).applyQuaternion(p.L).multiplyScalar($),qn.copy(An).applyQuaternion(p.R).multiplyScalar(1-$),An.copy(Ms).add(qn).normalize(),Xt.lerp(An,W).normalize())}zt.copy(vn).addScaledVector(Xt,L);const A=w&&x.anchor==="pelvis";if(g.collide)for(let O=0;O<6;O++)Xs.copy(vn).addScaledVector(Xt,L*.5),rr(Xs,i,w?.014:.008,A),Xt.subVectors(Xs,vn).normalize(),zt.copy(vn).addScaledVector(Xt,L),rr(zt,i,w?.014:.008,A),Xt.subVectors(zt,vn).normalize(),zt.copy(vn).addScaledVector(Xt,L);Xt.subVectors(zt,vn).normalize(),qn.copy(Xt).applyQuaternion(Qc.clone().invert()),Zc.setFromUnitVectors(ho,qn),y.quaternion.copy(Zc),y.updateMatrixWorld(!0)})})}const Ty=6.5,ba=new Map;function Ly(e){const n=Fn(e);let s=ba.get(n);if(!s){const i=Br({...e,head:1,posture:0},Sr,{bind:!0});i.root.updateMatrixWorld(!0),s=[...i.bones.values()].map(l=>l.matrixWorld.clone().invert());const r=[...i.bones.keys()];s.names=r,ba.set(n,s),ba.size>64&&ba.delete(ba.keys().next().value)}const a=s.names;return new Map(a.map((i,r)=>[i,s[r]]))}function Qd(e){const n=new Qe(e),s={h:0,s:0,l:0};return n.getHSL(s),s.h>=.01&&s.h<=.14&&s.s>=.15&&s.s<=.75&&s.l>=.12&&s.l<=.93}function Ey(e,n,s){const a=qm(e),i=!e||!Object.keys(a).length,r=Qd(n)?"#6d7a86":n;if(i){const l="#"+new Qe(r).multiplyScalar(.45).getHexString();return{hair:{style:s.fem>.5?"bob":"short",color:"#2a211b"},top:{type:"tshirt",color:r},bottom:{type:"trousers",color:l},shoes:{type:"sneakers",color:"#2a2a2c"}}}return hy(a)||(a.top={type:"tank",color:"#e8e4dc"}),dy(a)||(a.bottom={type:"shorts",color:"#3a3f47"}),a}function Iy(e,n){return e?.skin??(Qd(n)?n:wr[2])}const po=(e,n)=>(e.name=n,e.castShadow=!0,e.receiveShadow=!0,e);function Ry(e,n,s,a,i={}){const r=_r();if(!r)throw new Error("HQ character asset not loaded");const l=Iy(s,n),c=Lo({...s??{},skin:l},l),u=i.bare?{}:Ey(a,n,c),m=u.shoes?.type==="heels",d=Br(c,e,{heels:m}),f=Ly(c),p=(L,N)=>new Ni(L.map(A=>d.bones.get(A)),L.map(A=>f.get(A).clone())),x=[],g=[],v=i.lod===void 0?[0,1]:[i.lod],w=new W0,C=v.map(()=>new tn);C.forEach((L,N)=>{L.name=`lod${v[N]}`,w.addLevel(L,N===0?0:Ty),N&&(L.visible=!1)}),w.name="hqLod",d.root.add(w);const M=(L,N,A,O,_=d.root,$=!0)=>{const P=new Er(L,N);return P.bind(O,new St),po(P,A),Ub(P),P.userData.grounds=$,x.push(P),_.add(P),P},S=p(Gh),I=u.hat?null:u.hair?.style,y={skin:l,buzz:I==="buzz"?u.hair.color:null,stubble:u.beard?.type==="beard"?u.beard.color:null},k=$y(l);for(const L of["L","R"])d.bones.get(`eye${L}`).add(po(new ut(zb(k),qb()),"eyes"));const T=[];for(const L of ly(r,d,u,c)){const N=new Ni(L.bones.map(O=>d.bones.get(O)),L.bones.map(O=>(L.inverses.get(O)??f.get(O)).clone())),A=L.near&&v[0]===0&&v.length>1?C[0]:d.root;M(L.geometry,L.material,L.slot,N,A,!1),L.chains&&T.push(L.chains)}v.forEach((L,N)=>{const A=ky(r,d,c,u,L,{fittedOnly:N>0}),O=M($b(r,c,L,y),Kb(l),"skin",S,C[N],N===0);A.hide&&(O.geometry=Py(O.geometry,A.hide,A.hideKey));for(const _ of A.parts){if(_.skinned){const $=_.bones?new Ni(_.bones.map(W=>d.bones.get(W)),_.bones.map(W=>(_.inverses?.get(W)??f.get(W)).clone())):S,P=M(_.geometry,_.material,_.slot,$,_.bones?d.root:C[N],N===0);if(_.drape){const W=new Ct,z=_.geometry.getAttribute("position").count;W.setAttribute("position",new Nt(new Float32Array(z*3),3)),W.setIndex(_.geometry.getIndex());const Q=po(new ut(W,_.material),_.slot);Q.userData.drape=!0,P.visible=!1,P.userData.grounds=!1,d.root.add(Q),g.push({src:P,mesh:Q})}}else{const $=po(new ut(_.geometry,_.material),_.slot);(d.bones.get(_.bone)??d.root).add($)}_.chains&&T.push(_.chains)}});const j={rig:d,b:c,look:u,meshes:x,chains:T,heels:m,drapes:g,legs:xy(r,c)};return d.root.userData.hq={repose:(L,N)=>ah(j,L,N??null),built:j,torso:Fy(r,c,u)},d.root.userData.hqLook=u,ah(j,e,i.motion??null,!0),d.root}function ah(e,n,s,a=!1){const{rig:i,b:r}=e;a||Oo(i,r,n,{heels:e.heels});const l=qh(n);for(const u of e.meshes)u.morphTargetInfluences&&Mr.forEach((m,d)=>{u.morphTargetInfluences[d]=l[m]});i.body.position.y=1,i.root.updateMatrixWorld(!0),Ay(e.chains,i,n,s);let c=1/0;for(const u of e.meshes)u.userData.grounds!==!1&&Zs(u,(m,d)=>{d<c&&(c=d)},i.root);i.body.position.y=1-(Number.isFinite(c)?c:0),i.root.updateMatrixWorld(!0);for(const u of e.meshes)u.boundingBox=null,u.boundingSphere=null;for(const u of e.drapes){const m=u.mesh.geometry.getAttribute("position"),d=m.array;Zs(u.src,(f,p,x,g)=>{d[g*3]=f,d[g*3+1]=p,d[g*3+2]=x},i.root,!0),Sy(i,d,e.legs,u.src.geometry.userData.rings),m.needsUpdate=!0,u.mesh.geometry.computeVertexNormals(),u.mesh.geometry.computeBoundingSphere(),u.mesh.geometry.computeBoundingBox()}}const fo=new Map;function Fy(e,n,s){const a=(s.top?.012:0)+(s.outer?.016:0),i=`${Fn(n)}|${a}`;let r=fo.get(i);if(r)return r;const l=e.lods.length-1,c=e.lods[l],u=ds(e,n,l).getAttribute("position"),m=new Set(["torso","pelvis"].map(v=>e.bones.indexOf(v)));let d=0,f=1/0,p=-1/0;const x=.02,g=.3;for(let v=0;v<c.vertices;v++){if(!m.has(c.skinIndex[v*4]))continue;const w=u.getY(v)-1;w<x||w>g||(d=Math.max(d,Math.abs(u.getX(v))),f=Math.min(f,u.getZ(v)),p=Math.max(p,u.getZ(v)))}return r=Number.isFinite(f)?{rx:d+a,rz:(p-f)/2+a,cz:(f+p)/2,y0:x,y1:g}:{rx:.16,rz:.12,cz:0,y0:x,y1:g},fo.size>64&&fo.clear(),fo.set(i,r),r}const go=new Map;function Py(e,n,s){const a=`${e.uuid}|${s}`;let i=go.get(a);if(i)return i;go.size>64&&go.clear();const r=e.getIndex(),l=[];for(let c=0;c<r.count;c+=3){const u=r.getX(c),m=r.getX(c+1),d=r.getX(c+2);n[u]&&n[m]&&n[d]||l.push(u,m,d)}i=new Ct;for(const c of Object.keys(e.attributes))i.setAttribute(c,e.getAttribute(c));return i.morphAttributes=e.morphAttributes,i.morphTargetsRelative=e.morphTargetsRelative,i.setIndex(l),i.userData={...e.userData,samples:void 0},i.userData.shared=!0,i.dispose=()=>{},go.set(a,i),i}function $y(e){const n=new Qe(e).getHSL({h:0,s:0,l:0}).l;return n>.78?"#4a6a8a":n>.62?"#5a3f2a":"#3a2618"}const hr="shot-hq-characters";function Wr(){try{return globalThis.localStorage?.getItem(hr)!=="off"}catch{return!0}}function Oy(e){try{e?globalThis.localStorage?.removeItem(hr):globalThis.localStorage?.setItem(hr,"off")}catch{}for(const n of[...dr])n()}const dr=new Set;function Zd(e){return dr.add(e),()=>{dr.delete(e)}}const Dy=()=>Wr()&&!!_r();Cr.active=Dy;Cr.build=Ry;Cr.samples=Zs;Un.hq={enabled:Wr,ready:()=>!!_r(),load:()=>Tb(),onSetting:Zd,onAsset:Bd};Bd(kd);Zd(kd);const Jd=["Thumb","Index","Middle","Ring","Pinky"],eu={l:"Left",r:"Right",left:"Left",right:"Right"};function zy(e){const n=String(e||"");let s=/^mixamorig\d*[_:]?([A-Za-z]+\d?)$/.exec(n);return s?ur.has(s[1])?s[1]:null:(s=/^Bip\d+[ _](.+)$/i.exec(n),s?_y(s[1].split(/[ _]+/)):(s=/^J_Bip_([CLR])_(\w+)$/i.exec(n),s?By(s[1].toUpperCase(),s[2]):(s=/^(pelvis|spine_0[1-5]|neck_01|head|clavicle|upperarm|lowerarm|hand|thigh|calf|foot|ball|(thumb|index|middle|ring|pinky)_0([1-3]))(?:_([lr]))?$/i.exec(n),s?Ky(s[1].toLowerCase(),s[4]?.toLowerCase()):(s=/^DEF-(shoulder|upper_arm|forearm|hand|thigh|shin|foot|toe|thumb[._]?0([1-3])|f_(index|middle|ring|pinky)[._]?0([1-3]))[._]?([LR])$/.exec(n),s?Hy(s):ur.has(n)?n:null))))}function _y(e){const[n,s]=e,a={Pelvis:"Hips",Spine:"Spine",Spine1:"Spine1",Spine2:"Spine2",Neck:"Neck",Head:"Head"};if(e.length===1)return a[n]??null;const i=eu[String(n).toLowerCase()];if(!i||e.length!==2)return null;const r={Clavicle:"Shoulder",UpperArm:"Arm",Forearm:"ForeArm",Hand:"Hand",Thigh:"UpLeg",Calf:"Leg",Foot:"Foot",Toe0:"ToeBase"}[s];if(r)return i+r;const l=/^Finger([0-4])([12])?$/.exec(s);return l?`${i}Hand${Jd[+l[1]]}${l[2]?+l[2]+1:1}`:null}function By(e,n){if(e==="C")return{Hips:"Hips",Spine:"Spine",Chest:"Spine1",UpperChest:"Spine2",Neck:"Neck",Head:"Head"}[n]??null;const s=e==="L"?"Left":"Right",a={Shoulder:"Shoulder",UpperArm:"Arm",LowerArm:"ForeArm",Hand:"Hand",UpperLeg:"UpLeg",LowerLeg:"Leg",Foot:"Foot",ToeBase:"ToeBase"}[n];if(a)return s+a;const i=/^(Thumb|Index|Middle|Ring|Little)([1-3])$/.exec(n);return i?`${s}Hand${i[1]==="Little"?"Pinky":i[1]}${i[2]}`:null}function Ky(e,n){const s={pelvis:"Hips",spine_01:"Spine",spine_02:"Spine1",spine_03:"Spine2",neck_01:"Neck",head:"Head"};if(s[e])return n?null:s[e];if(/^spine_0[45]$/.test(e))return null;const a=n?eu[n]:null;if(!a)return null;const i={clavicle:"Shoulder",upperarm:"Arm",lowerarm:"ForeArm",hand:"Hand",thigh:"UpLeg",calf:"Leg",foot:"Foot",ball:"ToeBase"}[e];if(i)return a+i;const r=/^(thumb|index|middle|ring|pinky)_0([1-3])$/.exec(e);return r?`${a}Hand${r[1][0].toUpperCase()}${r[1].slice(1)}${r[2]}`:null}function Hy(e){const n=e[5]==="L"?"Left":"Right";return e[2]?`${n}HandThumb${e[2]}`:e[3]?`${n}Hand${e[3][0].toUpperCase()}${e[3].slice(1)}${e[4]}`:n+{shoulder:"Shoulder",upper_arm:"Arm",forearm:"ForeArm",hand:"Hand",thigh:"UpLeg",shin:"Leg",foot:"Foot",toe:"ToeBase"}[e[1]]}function Wy(e){const n=new Map;for(const i of e){const r=/^DEF-spine(?:[._]?0*(\d+))?$/.exec(i);r&&n.set(r[1]?+r[1]:0,i)}if(!n.has(0))return[];const s=Math.max(...n.keys()),a=[[n.get(0),"Hips"]];for(const[i,r]of[[1,"Spine"],[2,"Spine1"],[3,"Spine2"]])n.has(i)&&i<s&&a.push([n.get(i),r]);return s>=5&&n.has(4)&&a.push([n.get(4),"Neck"]),s>=4&&a.push([n.get(s),"Head"]),a}const qr=["Hips","Spine","Spine2","Neck","Head"];for(const e of["Left","Right"])qr.push(...["Shoulder","Arm","ForeArm","Hand","UpLeg","Leg","Foot"].map(n=>e+n));const qy=Object.freeze(qr.slice()),ur=new Set([...qr,"Spine1","LeftToeBase","RightToeBase",...["Left","Right"].flatMap(e=>Jd.flatMap(n=>[1,2,3].map(s=>`${e}Hand${n}${s}`)))]);function Gy(e){const n=new Map,s=new Set;let a=0;for(const[r,l]of Wy(e||[]))n.set(r,l),s.add(l);for(const r of e||[]){if(n.has(r))continue;const l=zy(r);!l||s.has(l)||(n.set(r,l),s.add(l),(/^mixamorig/.test(r)||ur.has(r))&&a++)}if(!s.has("Spine2")&&s.has("Spine1"))for(const[r,l]of n)l==="Spine1"&&(n.set(r,"Spine2"),s.delete("Spine1"),s.add("Spine2"));const i=qy.filter(r=>!s.has(r));return{ok:i.length===0,exact:i.length===0&&a===n.size,rename:n,missing:i,bones:n.size}}const Uy={fingers:.85,palm:.2,across:.07},oh={x:"shot/bot/xbot.glb",y:"shot/bot/ybot.glb"},ea={};let ya=null;const mr=new Set,Xy=()=>!!ea.x&&!!ea.y;function Vy(e){return mr.add(e),()=>{mr.delete(e)}}function Yy(e){if(ya)return ya;const n="/";return ya=(async()=>{const s=new ug,[a,i]=await Promise.all([s.loadAsync(`${n}${oh.x}`),s.loadAsync(`${n}${oh.y}`)]);ea.x=ih(i.scene),ea.y=ih(a.scene);for(const r of[...mr])r()})().catch(s=>{throw ya=null,s}),ya}function ih(e){e.updateMatrixWorld(!0);const n=new $t().setFromObject(e),s=e.getObjectByName("mixamorigHips"),a=new ie;return s?.getWorldPosition(a),{scene:e,height:n.max.y-n.min.y,hipsY:a.y-n.min.y}}const Qy=[["head","Head"],["arm","Arm"],["fore","ForeArm"],["wrist","Hand"],["thigh","UpLeg"],["shin","Leg"],["foot","Foot"]],Zy={thumb:"HandThumb",index:"HandIndex",middle:"HandMiddle",ring:"HandRing",pinky:"HandPinky"},Jy=[["Hips",1-Wh,.3],["Spine",.73,.55],["Spine1",.87,.8],["Spine2",1,1]],ev=.45,tv=24,xo=e=>typeof e=="number"&&Number.isFinite(e)?e:0,nv=/hair|bang|fringe|pony|braid|plait|ahoge|tress|bun|tail|ribbon|tassel|earring|hat|ear_?ring/i,sv=/skirt|hem|coat|cape|cloak|robe|ribbon|tassel|sash|apron|scarf|cloth|flap|necktie|belt|frill|veil|mantle/i,av=/twist|eye|tooth|teeth|tongue|jaw|mouth|lip|brow|lid|cheek|nose|mask|weapon|sword|gun|ik|pole|target|end$|_end|helper/i,ov=e=>new Qe(e).lerp(new Qe("#d8dbe0"),.55),iv=e=>new Qe(e).offsetHSL(0,.05,-.12);function rv(e,n,s,a="x"){const i=ea[a]??ea.x;if(!i)throw new Error("bot asset not loaded");return nu(pd(i.scene),i.height,e,n,s,!1)}function tu(e){const n=[],s=new Set;let a=!1;e.traverse(r=>{r.isSkinnedMesh&&(a=!0),r.isBone&&!s.has(r.name)&&(s.add(r.name),n.push(r.name))});const i=Gy(n);return{...i,ok:i.ok&&a,skinned:a,total:n.length}}function lv(e,n,s,a){const i=tu(e);if(!i.ok)throw new Error(i.skinned?`bộ xương thiếu: ${i.missing.join(", ")}`:"model không có lưới gắn xương");const r=new Set;e.traverse(v=>r.add(v)),e.traverse(v=>{if(v.isSkinnedMesh){for(const w of v.skeleton.bones)if(w&&!r.has(w)){let C=w;for(;C.parent;)C=C.parent;r.has(C)||(e.add(C),C.traverse(M=>r.add(M)))}}});const l=new tn,c=pd(e);l.add(c);const u=new Set;c.traverse(v=>{const w=v.isBone?i.rename.get(v.name):void 0;w&&!u.has(v)&&(v.name=`mixamorig${w}`,u.add(v))}),c.traverse(v=>{v.isBone&&!u.has(v)&&/^mixamorig/.test(v.name)&&(v.name=`x_${v.name}`)}),l.updateMatrixWorld(!0);const m=v=>l.getObjectByName(`mixamorig${v}`)?.getWorldPosition(new ie);let d=0;for(const v of["Left","Right"]){const w=m(`${v}Foot`),C=m(`${v}ToeBase`);w&&C&&(d+=C.z-w.z)}d<0&&(c.rotation.y=Math.PI),l.updateMatrixWorld(!0);const f=l.getObjectByName("mixamorigHips");if(f){const v=new Set;for(let C=f.parent;C;C=C.parent)v.add(C);const w=[];l.traverse(C=>{if(!C.isBone||C===f||v.has(C))return;let M=C.parent;for(;M&&M!==f&&!v.has(M);)M=M.parent;M!==f&&C.parent&&v.has(C.parent)&&w.push(C)});for(const C of w)f.attach(C);l.updateMatrixWorld(!0)}const p=new $t().setFromObject(l),x=Math.max(.001,p.max.y-p.min.y);c.position.y-=p.min.y;const g=nu(l,x,n,s,{height:a},!0);return g.userData.botExact=i.exact,g.userData.nativeBones=i.bones,g}function nu(e,n,s,a,i,r){const l=Dt(i),c=Lo({...i??{}},a),u=new tn;u.name="bot";const m=Br(c,{},{bind:!0});m.root.name="driver",m.root.traverse(oe=>{oe.visible=!0}),u.add(m.root),m.root.updateMatrixWorld(!0),e.name="skin";const d=l.height/n;e.scale.setScalar(d),u.add(e),e.updateMatrixWorld(!0),e.traverse(oe=>{if(!(oe instanceof ut)||(oe.castShadow=!0,oe.receiveShadow=!0,oe.frustumCulled=!1,r))return;const Ne=/joint/i.test(oe.name);oe.material=new Gn({color:Ne?iv(a):ov(a),roughness:Ne?.5:.42,metalness:Ne?.15:.08})});const f=new Map;e.traverse(oe=>{oe.isBone&&!f.has(oe.name)&&f.set(oe.name,oe)});const p=f.get("mixamorigHips"),x=[],g=[],v=new ie,w=new ie,C=new tt,M=oe=>oe.getWorldQuaternion(new tt),S=(oe,Ne)=>{oe.getWorldPosition(v);let Oe=null,Re=1e-6;for(const _e of oe.children){_e.getWorldPosition(w);const Ze=w.clone().sub(v);Ze.lengthSq()>Re&&(Re=Ze.lengthSq(),Oe=Ze)}return Oe?Oe.normalize():Ne.clone()},I=oe=>Math.sign(oe.getWorldPosition(new ie).x||0),y=(oe,Ne,Oe,Re=!1)=>{const _e=m.bones.get(oe);if(!_e){g.push(`driver ${oe}`);return}const Ze=I(_e),nt=[...f.values()].filter(ct=>ct.name===`mixamorig${Ne}`||ct.name===`mixamorigLeft${Ne}`||ct.name===`mixamorigRight${Ne}`),et=nt.length===1?nt[0]:nt.find(ct=>Math.sign(ct.getWorldPosition(new ie).x||0)===Ze);if(!et){g.push(`bone ${Ne} for ${oe} (${nt.length} cands, want ${Ze})`);return}const Ge=Re?Oe:S(et,Oe),Ye=Re?Oe:S(_e,Oe),lt=new tt().setFromUnitVectors(Ge,Ye);x.push({bone:et,driver:_e,cal:lt,restInv:M(_e).invert(),mRest:M(et)})},k=new ie(0,1,0),T=new ie(0,-1,0),j=new ie(0,0,1);y("torso","Spine2",k,!0);for(const[oe,Ne]of Qy){if(oe==="head"){y("head",Ne,k,!0);continue}const Oe=oe==="thigh"||oe==="shin"||oe==="foot";for(const Re of["L","R"])y(`${oe}${Re}`,Ne,oe==="foot"?j:T,Oe)}for(const oe of["L","R"])for(const[Ne,Oe]of Object.entries(Zy))for(let Re=1;Re<=3;Re++)y(`${Ne}${Re}${oe}`,`${Oe}${Re}`,T);const L=oe=>f.get(`mixamorig${oe}`),N=m.bones.get("torso"),A=m.bones.get("head"),O=M(N),_=O.clone().invert(),$=M(A).invert(),P=L("Spine2"),W=P.getWorldPosition(new ie).applyMatrix4(N.matrixWorld.clone().invert()),z=Jy.filter(([oe])=>L(oe)).map(([oe,Ne,Oe])=>({bone:L(oe),lean:Ne,twist:Oe,mRest:M(L(oe)),pos:L(oe).position.clone()})),Q=L("Neck"),J=M(Q),V=["Left","Right"].map(oe=>{const Ne=f.get(`mixamorig${oe}Shoulder`),Oe=f.get(`mixamorig${oe}Arm`),Re=Math.sign(Ne.getWorldPosition(new ie).x||0),_e=["L","R"].map(Ze=>({S:Ze,a:m.bones.get(`arm${Ze}`),f:m.bones.get(`fore${Ze}`)})).find(Ze=>Math.sign(Ze.a.getWorldPosition(new ie).x||0)===Re);return{bone:Ne,arm:Oe,sx:Re,drv:_e,mRest:M(Ne),armPos:Oe.position.clone(),follow:new tt}}).filter(oe=>oe.bone&&oe.arm&&oe.drv),B=rh(m),q=p.getWorldPosition(new ie),D=p.position.clone(),ee=new Map;for(const oe of f.values())ee.set(oe,oe.parent);const Z=new Map;for(const oe of x)Z.set(oe.bone,oe);const xe=[];p.traverse(oe=>{oe.isBone&&xe.push(oe)});const be=[];if(r){const oe=new Set([...f.values()].filter(_e=>/^mixamorig/.test(_e.name))),Ne=f.get("mixamorigHead"),Oe=f.get("mixamorigNeck"),Re=new Map;for(const _e of xe){if(oe.has(_e)||av.test(_e.name))continue;const Ze=_e.children.find(ct=>ct.isBone);if(!Ze||Ze.position.lengthSq()<1e-10)continue;let nt=_e.parent,et=!1;for(;nt&&!oe.has(nt);)nt=nt.parent;(nt===Ne||nt===Oe)&&(et=!0);const Ge=Re.get(_e.parent);if(!(et?nv.test(_e.name)||Ge!==void 0:sv.test(_e.name)||Ge!==void 0))continue;const lt=Ge===void 0?0:Ge+1;Re.set(_e,lt),be.push({bone:_e,rest:_e.quaternion.clone(),tip:Ze.position.clone(),hair:et,depth:lt})}}const U={pos:new ie,time:-1},pe=new ie,me=new ie,X=new tt,re=new tt,ue=new tt,Ee=new tt,ye=new ie,ne=new ie,Ie=new ie,ze=new ie;function we(oe){if(!be.length)return;for(const et of be)et.bone.quaternion.copy(et.rest);e.updateMatrixWorld(!0);const Ne=f.get("mixamorigHead"),Oe=oe?.time??-1;Ne?.getWorldPosition(Ie),me.set(0,0,0),Ne&&Oe>=0&&U.time>=0&&Oe>U.time&&Oe-U.time<.2&&me.subVectors(Ie,U.pos).divideScalar(Oe-U.time),U.pos.copy(Ie),U.time=Oe,u.getWorldQuaternion(X);const Re=oe?.vel??[0,0,0],_e=oe?.acc??[0,0,0],Ze=oe?.air??0,nt=Math.hypot(Re[0],Re[1],Re[2]);for(const et of be){const Ge=(et.hair?.07:.1)*(1+.6*Ze),Ye=et.hair?.012:.016,lt=et.hair?.09:.05;pe.set(-Re[0]*Ge-_e[0]*Ye,-Re[1]*Ge*.6-_e[1]*Ye,-Re[2]*Ge-_e[2]*Ye).applyQuaternion(X).addScaledVector(me,-lt),pe.length()>1.6&&pe.setLength(1.6);const ct=et.bone,Ke=ct.parent;Ke.updateWorldMatrix(!0,!1),ct.updateWorldMatrix(!1,!1),ct.getWorldPosition(Ie),ze.copy(et.tip).applyMatrix4(ct.matrixWorld),ye.subVectors(ze,Ie);const vt=ye.length();if(vt<1e-6)continue;ye.divideScalar(vt);const je=.55+.25*Math.min(3,et.depth),Lt=Math.min(1,nt/3)*(et.hair?.07:.12),Bt=Math.max(0,Oe)*(et.hair?3.7:5.3)+et.depth*.9+ct.id*.37;ne.copy(ye).add(ze.set(0,et.hair?-.22:-.3,0)).addScaledVector(pe,je),Lt&&(ne.x+=Math.sin(Bt)*Lt,ne.z+=Math.cos(Bt*.8)*Lt*.5),ne.normalize();const Ae=u.getWorldPosition(ze).y+.02;if(Ie.y+ne.y*vt<Ae){ne.y=Math.min(1,(Ae-Ie.y)/vt);const Et=Math.hypot(ne.x,ne.z),Fe=Math.sqrt(Math.max(0,1-ne.y*ne.y));Et>1e-6?(ne.x*=Fe/Et,ne.z*=Fe/Et):ne.x=Fe,ne.normalize()}const Yt=et.depth===0?.96:.35,hn=ye.angleTo(ne);hn>Yt&&ne.lerp(ye,1-Yt/hn).normalize(),re.setFromUnitVectors(ye,ne),Ke.getWorldQuaternion(ue),ct.getWorldQuaternion(Ee),ct.quaternion.copy(ue.invert().multiply(re).multiply(Ee)),ct.updateMatrixWorld(!0)}}const de=new Map,H=new tt,se=new tt,he=new tt,ce=[];e.traverse(oe=>{oe.isSkinnedMesh&&ce.push(oe)});let Pe=0;const Be=()=>{e.updateMatrixWorld(!0);let oe=1/0;for(const Ne of ce)Zs(Ne,(Oe,Re)=>{Re<oe&&(oe=Re)},u);Number.isFinite(oe)&&(Pe-=oe,m.body.position.y=1+Pe)};let ot=s;const G=[];function Se(oe,Ne,Oe){ot=oe;for(const Re of be)Re.bone.quaternion.copy(Re.rest);Oo(m,c,oe),m.body.position.y=1+Pe,m.root.updateMatrixWorld(!0),qe(),Be(),qe();for(const Re of G)Re.userData.active=!!(Ne&&Ne.w>0);Ne&&Ne.w>0&&At(Ne),we(Oe)}const le=new tt,$e=new tt,Le=new tt,Te=new tt,Je=new ie,ke=new tt;function Ue(oe,Ne,Oe,Re,_e){const Ze=Math.max(0,Math.min(oe.n-1,Oe*oe.rate)),nt=Math.floor(Ze),et=Math.min(oe.n-1,nt+1),Ge=Ze-nt,Ye=oe.bones.length,lt=(nt*Ye+Ne)*4,ct=(et*Ye+Ne)*4;return le.set(oe.q[lt],oe.q[lt+1],oe.q[lt+2],oe.q[lt+3]),$e.set(oe.q[ct],oe.q[ct+1],oe.q[ct+2],oe.q[ct+3]),_e.copy(le).slerp($e,Ge).normalize(),Re&&(Je.set(0,0,1).applyQuaternion(_e),Te.setFromAxisAngle(k,-Math.atan2(Je.x,Je.z)),_e.premultiply(Te)),_e}function At(oe){const Ne=Ol(oe.id);if(!Ne)return;const Oe=Ne.bones.length,Re=Math.min(1,oe.w),_e=oe.from?Ol(oe.from.id):void 0,Ze=_e?new Map(_e.bones.map((Ge,Ye)=>[Ge,Ye])):null;for(let Ge=0;Ge<Oe;Ge++){const Ye=f.get(Ne.bones[Ge]);if(!Ye)continue;Ue(Ne,Ge,oe.t,Ye===p,Le);const lt=Ze?.get(Ne.bones[Ge]);_e&<!==void 0&&oe.from.k>0&&Le.slerp(Ue(_e,lt,oe.from.t,Ye===p,ke),Math.min(1,oe.from.k)).normalize(),Re>=1?Ye.quaternion.copy(Le):Ye.quaternion.slerp(Le,Re)}e.updateMatrixWorld(!0);let nt=1/0;for(const Ge of ce)Zs(Ge,(Ye,lt)=>{lt<nt&&(nt=lt)},u);const et=oe.po;if(Number.isFinite(nt)&&Math.abs(nt)>1e-4||et){const Ge=p.getWorldPosition(new ie);Number.isFinite(nt)&&(Ge.y-=nt*u.getWorldScale(new ie).y),et&&(Ge.x-=et[0]*Re,Ge.z-=et[1]*Re),p.position.copy(p.parent.worldToLocal(Ge)),e.updateMatrixWorld(!0)}}function qe(){m.root.updateMatrixWorld(!0);const oe=rh(m),Ne=q.clone().add(oe.sub(B));p.parent.updateWorldMatrix(!0,!1),p.position.copy(p.parent.worldToLocal(Ne)),D.y=D.y,de.clear();const Oe=Tt(ot);for(const Re of z.slice(1))Re.bone.position.copy(Re.pos);for(const Re of xe){const _e=ee.get(Re);de.has(_e)?H.copy(de.get(_e)):_e.getWorldQuaternion(H);const Ze=Z.get(Re),nt=Oe.get(Re);nt?(he.copy(H).invert(),Re.quaternion.copy(he).multiply(nt)):Ze&&(Ze.driver.getWorldQuaternion(C),se.copy(C).multiply(Ze.restInv).multiply(Ze.cal).multiply(Ze.mRest),he.copy(H).invert(),Re.quaternion.copy(he).multiply(se)),de.set(Re,H.clone().multiply(Re.quaternion))}e.updateMatrixWorld(!0),an()}const mt=new tt,kt=new tt,Xe=new tt,it=new tt,xt=new tt,wt=new ie(1,0,0),nn=new ie(0,1,0),cn=new ie(0,0,1),_t=new tt,rt=za(c);function Tt(oe){const Ne=new Map,Oe=Ln.degToRad,Re=xo(oe.lean),_e=xo(oe.spineTwist),Ze=xo(oe.sideBend),nt=xo(oe.tumble)+rt.torsoLean;N.parent.getWorldQuaternion(_t);const et=(Ke,vt)=>_t.clone().multiply(mt.setFromAxisAngle(wt,Oe(nt+Ke*Re))).multiply(kt.setFromAxisAngle(nn,Oe(vt*_e))).multiply(Xe.setFromAxisAngle(cn,Oe(Ke*Ze))).multiply(_);for(const Ke of z)(Ke.lean<1||Ke.twist<1)&&Ne.set(Ke.bone,et(Ke.lean,Ke.twist).multiply(Ke.mRest));const Ge=N.getWorldQuaternion(it).multiply(_).clone(),Ye=A.getWorldQuaternion(xt).multiply($).clone();Ne.set(Q,Ge.clone().slerp(Ye,ev).multiply(J));const lt=new ie(0,-1,0).applyQuaternion(Ge),ct=new ie(0,0,1).applyQuaternion(Ge);for(const Ke of V){const vt=Ke.drv.f.getWorldPosition(new ie).sub(Ke.drv.a.getWorldPosition(new ie)).normalize(),je=Ln.radToDeg(vt.angleTo(lt)),Lt=Ln.clamp((je-80)/90,0,1);Ke.follow.copy(Ge).multiply(Ke.mRest);const Bt=new tt().setFromAxisAngle(ct,Oe(Ke.sx*tv*Lt*Lt*(3-2*Lt)));Ne.set(Ke.bone,Bt.multiply(Ke.follow))}return Ne}const Rt=new ie,sn=new ie,Sn=new St,Ns=new ie,As=new ie,Pn=new tt;function an(){sn.copy(W).applyMatrix4(N.matrixWorld);const oe=sn.sub(P.getWorldPosition(Rt)).multiplyScalar(1/3);for(const Ne of z.slice(1)){Ne.bone.parent.updateWorldMatrix(!0,!1);const Oe=Ne.bone.getWorldPosition(new ie).add(oe);Ne.bone.position.copy(Ne.bone.parent.worldToLocal(Oe)),Ne.bone.updateMatrixWorld(!0)}for(const Ne of V){Ne.bone.matrixWorld.decompose(Ns,Pn,As);const Oe=Ne.armPos.clone().applyMatrix4(Sn.compose(Ns,Ne.follow,As));Ne.arm.position.copy(Ne.bone.worldToLocal(Oe)),Ne.arm.updateMatrixWorld(!0)}}Se(s),u.updateMatrixWorld(!0);for(const oe of["L","R"]){const Ne=x.find(Fe=>Fe.driver.name===`wrist${oe}`);if(!Ne)continue;const Oe=Fe=>f.get(`${Ne.bone.name}${Fe}`)?.getWorldPosition(new ie),Re=Ne.bone.getWorldPosition(new ie),_e=Oe("Index1"),Ze=Oe("Middle1"),nt=Oe("Pinky1"),et=Oe("Thumb1");if(!_e||!Ze||!nt||!et)continue;const Ge=_e.clone().sub(nt).normalize(),Ye=Ze.clone().sub(Re);Ye.addScaledVector(Ge,-Ye.dot(Ge)).normalize();let lt=new ie().crossVectors(Ye,Ge);lt.dot(et.clone().sub(Re))<0&<.negate();const ct=new ie().setFromMatrixScale(Ne.driver.matrixWorld),Ke=Ze.distanceTo(Re),vt=Uy,je=Re.clone().addScaledVector(Ye,vt.fingers*Ke).addScaledVector(lt,vt.palm*Ke).addScaledVector(Ge,vt.across*Ke),Lt=Ge,Bt=Ye,Ae=new ie().crossVectors(Bt,Lt).normalize(),Yt=new St().makeBasis(Ae,Bt,Lt).setPosition(je).scale(ct),hn=Ne.bone.matrixWorld.clone().invert().multiply(Yt),Et=new q0;Et.name=`rigHold${oe}`,Et.userData.rigHold=oe,Et.userData.active=!1,G.push(Et),hn.decompose(Et.position,Et.quaternion,Et.scale),Ne.bone.add(Et)}const xn=(oe,Ne,Oe,Re)=>{for(const Fe of xe){const pt=oe.get(Fe.name);pt&&Fe.quaternion.copy(pt)}Ne&&p.position.copy(Ne),e.rotation.y=0,e.updateMatrixWorld(!0);const _e=p.getWorldPosition(new ie),Ze=(()=>{const Fe=p.getWorldQuaternion(new tt),pt=new ie(0,0,1).applyQuaternion(Fe);if(!Re?.steadyYaw)return Math.atan2(pt.x,pt.z);const qt=new ie(1,0,0).applyQuaternion(Fe);return Math.atan2(pt.x-qt.z,pt.z+qt.x)})();e.rotation.y=-Ze,e.updateMatrixWorld(!0),Oo(m,c,{},{bind:!0}),m.root.updateMatrixWorld(!0);const nt=new tt,et=new tt,Ge=new tt;for(const Fe of x)Fe.bone.getWorldQuaternion(nt),et.copy(nt).multiply(Fe.mRest.clone().invert()).multiply(Fe.cal.clone().invert()).multiply(Fe.restInv.clone().invert()),Fe.driver.parent.getWorldQuaternion(Ge),Fe.driver.quaternion.copy(Ge.invert()).multiply(et),Fe.driver.updateMatrixWorld(!0);const Ye=za(c),lt=Ln.radToDeg,ct=new er,Ke={},vt=Fe=>((Fe+180)%360+360)%360-180,je=(Fe,pt,qt=[])=>{const bn=m.bones.get(Fe);ct.setFromQuaternion(bn.quaternion,pt);const $n=[lt(ct.x),lt(ct.y),lt(ct.z)],Me=Qt=>{const Ft=qt[Qt];if(!(!Oe||!Ft||Oe[Ft[0]]===void 0))return Oe[Ft[0]]*Ft[1]},On=pt[1]==="X"?0:pt[1]==="Y"?1:2,Ts=$n.map((Qt,Ft)=>vt(Ft===On?180-Qt:Qt+180)),Vn=Qt=>Qt.reduce((Ft,Gt,Dn)=>{const us=Me(Dn);return Ft+(us===void 0?0:Math.abs(vt(Gt-us)))+.05*Math.abs(Gt)},0);let He=Vn(Ts)<Vn($n)?Ts:$n;if(Oe&&Math.abs(He[On])>70){const Qt=[0,1,2].filter(ms=>ms!==On),[Ft,Gt]=Qt,Dn=(pt==="XYZ"?-1:1)*Math.sign(He[On]),us=Me(Ft),qa=Me(Gt);if(us!==void 0&&qa!==void 0){const ms=(vt(us-He[Ft])*Dn+vt(qa-He[Gt]))/2,Ut=[...He];Ut[Ft]=vt(He[Ft]+Dn*ms),Ut[Gt]=vt(He[Gt]+ms);const Ga=new er(Ln.degToRad(Ut[0]),Ln.degToRad(Ut[1]),Ln.degToRad(Ut[2]),pt),ps=new tt().setFromEuler(Ga);2*Math.acos(Math.min(1,Math.abs(ps.dot(bn.quaternion))))*57.3<4&&(He=Ut)}}return He},[Lt,Bt,Ae]=je("torso","XYZ",[["lean",1],["spineTwist",1],["sideBend",1]]);Ke.lean=Lt-Ye.torsoLean,Ke.spineTwist=Bt,Ke.sideBend=Ae;const[Yt,hn,Et]=je("head","YXZ",[["headPitch",1],["head",1],["headRoll",1]]);Ke.headPitch=Yt-Ye.headPitch,Ke.head=hn,Ke.headRoll=Et;for(const Fe of["L","R"]){const pt=Fe==="L",qt=pt?1:-1,[bn,$n,Me]=je(`arm${Fe}`,"XZY",[[`shoulder${Fe}`,1],[`armTwist${Fe}`,pt?1:-1],[`shoulderOut${Fe}`,pt?-1:1]]);Ke[`shoulder${Fe}`]=bn,Ke[`armTwist${Fe}`]=pt?$n:-$n,Ke[`shoulderOut${Fe}`]=pt?-Me:Me,Ke[`elbow${Fe}`]=-je(`fore${Fe}`,"XYZ")[0];const[On,Ts,Vn]=je(`wrist${Fe}`,"YXZ",[[`wrist${Fe}`,1],[`wristTwist${Fe}`,-qt],[`wristSide${Fe}`,-qt]]);Ke[`wrist${Fe}`]=On,Ke[`wristTwist${Fe}`]=-Ts*qt,Ke[`wristSide${Fe}`]=-Vn*qt;const[He,Qt,Ft]=je(`thigh${Fe}`,"XZY",[[`hip${Fe}`,1],[`hipTwist${Fe}`,pt?1:-1],[`hipOut${Fe}`,pt?-1:1]]);Ke[`hip${Fe}`]=He,Ke[`hipTwist${Fe}`]=pt?Qt:-Qt,Ke[`hipOut${Fe}`]=pt?-Ft:Ft,Ke[`knee${Fe}`]=je(`shin${Fe}`,"XYZ")[0],Ke[`ankle${Fe}`]=je(`foot${Fe}`,"XYZ")[0];const Gt=Dn=>Math.abs(je(`${Dn}2${Fe}`,"XYZ")[2]);Ke[`grip${Fe}`]=Math.max(0,Math.min(100,(Gt("index")+Gt("middle")+Gt("ring"))/3/100*100)),Ke[`thumb${Fe}`]=Math.max(0,Math.min(100,Gt("thumb")/60*100))}return e.rotation.y=0,{pose:Ke,hips:_e,yaw:lt(Ze)}};return u.userData.bot={repose:Se,poseFrom:xn},u.userData.dynamicBones=be.length,u.userData.botMisses=g,u.userData.botLinks=x.map(oe=>`${oe.driver.name}→${oe.bone.name.replace("mixamorig","")} cal ${Math.round(2*Math.acos(Math.min(1,Math.abs(oe.cal.w)))*57.3)}°`),u}function rh(e){const n=e.bones.get("thighL").getWorldPosition(new ie),s=e.bones.get("thighR").getWorldPosition(new ie);return n.add(s).multiplyScalar(.5)}Un.bot={ready:Xy,load:()=>Yy(),onAsset:Vy,build:rv,native:lv,nativeOf:tu};function cv(e,n,s={}){const a=n.items.find(c=>c.id===s.selected&&c.kind!=="fx"&&!c.hidden)??null,i=Math.max(0,+(s.start??0).toFixed(2)),r=dg(e,{items:n.items,selected:a,ground:s.ground??[0,0,0],reach:s.reach,anchor:s.anchor?(c,u)=>s.anchor(c.id,u,i):null}),l={...Um(e,s.seed??Math.floor(Math.random()*1e9)+1),start:i,...r.attach?{attach:r.attach}:{},...r.path?{path:r.path}:{},...r.target?{target:r.target}:{}};return{...fn("fx",n.items.length),name:e.name,color:e.color,position:r.position,rotation:r.rotation,fx:l}}function hv(e,n,s){const a=n.fx,i=e.shots.find(u=>u.id===e.activeShot)??e.shots[0],r=Math.min(a.start,Math.max(0,i.duration-.2)),l=s?.fill?Math.max(Math.min(s.duration,3),i.duration-r):a.duration,c={start:+r.toFixed(2),duration:+Math.min(60,l).toFixed(2),...a.loop?{loop:!0}:{}};return{...e,items:[...e.items,{...n,fx:{...a,start:c.start,duration:c.duration}}],shots:e.shots.map(u=>u.id===i.id?{...u,fxTiming:{...u.fxTiming,[n.id]:c}}:u)}}function su(e,n,s={}){const a=cv(n,e,s),i=e.items.filter(u=>u.kind==="fx"&&u.fx?.preset===n.preset).length,r={...a,name:`${s.label??n.name} ${i+1}`},l=Gm(e.items,r.fx);if(!l.ok)return{error:"limit",detail:l.errors.join("; ")};const c=hv(e,r,n);return{stage:c,item:c.items[c.items.length-1]}}let pr=0;const fr=new Set;function au(e=!1){return Xm("fx",e).then(n=>{Vm(n.filter(s=>s.kind==="fx"&&s.preset).map(s=>Ym(s))),pr++,fr.forEach(s=>s())},()=>{})}function dv(){const[e,n]=R.useState(pr);return R.useEffect(()=>{const s=()=>n(pr);return fr.add(s),au(),()=>{fr.delete(s)}},[]),{entries:Qm(),version:e}}const lh=new Map;function ou(e){let n=lh.get(e.id);return n||(n=Jm(e,24),lh.set(e.id,n)),n}const iu=(e,n)=>e[Math.max(0,Math.min(e.length-1,Math.round(n*24)))];function uv(e){const n=e.keys.find(s=>s.strike);return n?n.t:e.duration/2}const ch=(e,n)=>[e[0]-n[0],e[1]-n[1],e[2]-n[2]],Oi=(e,n)=>[e[1]*n[2]-e[2]*n[1],e[2]*n[0]-e[0]*n[2],e[0]*n[1]-e[1]*n[0]],Di=(e,n)=>e[0]*n[0]+e[1]*n[1]+e[2]*n[2],hh=e=>{const n=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/n,e[1]/n,e[2]/n]};function mv(e,n,s){const a=hh(ch(e.target,e.position)),i=hh(Oi(a,[0,1,0])),r=Oi(i,a),l=Math.cos(e.roll*Math.PI/180),c=Math.sin(e.roll*Math.PI/180),u=[i[0]*l+r[0]*c,i[1]*l+r[1]*c,i[2]*l+r[2]*c],m=Oi(u,a),d=e.lens/36*n;return f=>{const p=ch(f,e.position),x=Di(p,a);return x<.05?null:[n/2+Di(p,u)/x*d,s/2-Di(p,m)/x*d]}}const pv=[["pelvis","chest"],["chest","neck"],["shoulderL","shoulderR"],["shoulderL","elbowL"],["elbowL","handL"],["shoulderR","elbowR"],["elbowR","handR"],["hipL","hipR"],["hipL","kneeL"],["kneeL","ankleL"],["ankleL","toeL"],["hipR","kneeR"],["kneeR","ankleR"],["ankleR","toeR"]],dh={spear:{tip:1.42,blade:1.18,butt:.82},sword:{tip:.95,blade:.13,butt:.1},katana:{tip:.98,blade:.18,butt:.13},staff:{tip:1.1,blade:1.1,butt:.5}};function ru(e,n,s,a="spear"){const i=xg(e.pose),r=Math.cos(s*Math.PI/180),l=Math.sin(s*Math.PI/180),c=g=>[n[0]+g[0]*r+g[2]*l,n[1]+g[1],n[2]-g[0]*l+g[2]*r],u={};for(const g of Object.keys(i))g!=="lift"&&(u[g]=c(i[g]));const m=ep(e.pose),d=[0,1-i.lift,0],f=g=>c([d[0]+g[0],d[1]+g[1],d[2]+g[2]]),p=dh[a]??dh.spear,x=g=>f(m.front.map((v,w)=>v+m.dir[w]*g));return{pts:u,tip:x(p.tip),butt:x(-p.butt),blade:x(p.blade)}}function lu(e,n,s,a,i,r=0){const l=mv(a,n,s),c=e.createLinearGradient(0,0,0,s);c.addColorStop(0,"#1a2532"),c.addColorStop(1,"#0b1018"),e.fillStyle=c,e.fillRect(0,0,n,s),e.lineWidth=1,e.strokeStyle="rgba(140,170,200,.16)";const u=Math.round(i[0]?.pts.pelvis[0]??0),m=Math.round(i[0]?.pts.pelvis[2]??0);for(let d=-8;d<=8;d++)for(const[f,p]of[[[u+d,0,m-8],[u+d,0,m+8]],[[u-8,0,m+d],[u+8,0,m+d]]]){const x=l(f),g=l(p);!x||!g||(e.beginPath(),e.moveTo(x[0],x[1]),e.lineTo(g[0],g[1]),e.stroke())}for(const d of i){const f=(g,v,w,C)=>{const M=l(g),S=l(v);!M||!S||(e.strokeStyle=w,e.lineWidth=C,e.beginPath(),e.moveTo(M[0],M[1]),e.lineTo(S[0],S[1]),e.stroke())},p=(()=>{const g=l(d.pts.pelvis),v=l(d.pts.neck);return g&&v?Math.max(1,Math.hypot(g[0]-v[0],g[1]-v[1])/16):1})();e.lineCap="round";for(const[g,v]of pv)f(d.pts[g],d.pts[v],"#dfe6ee",2.2*p);const x=l(d.pts.head);x&&(e.fillStyle="#dfe6ee",e.beginPath(),e.arc(x[0],x[1],3.6*p,0,Math.PI*2),e.fill()),f(d.butt,d.blade,"#c79a5a",1.6*p),f(d.blade,d.tip,"#a8ff3c",2.4*p)}r>0&&(e.fillStyle=`rgba(168,255,60,${.22*r})`,e.fillRect(0,0,n,s))}function fv(e,n,s,a,i,r="spear"){const l=ou(n),c=iu(l,s),u=[c.dx??0,c.dy??0,c.dz??0],m=c.turn??0,d=l[l.length-1].dz??0,f=[0,.85,d/2],p={position:[4.4,1.25,f[2]+1.4],target:f,lens:30,roll:0};lu(e,a,i,p,[ru(c,u,m,r)])}const gv=["spear-thrust","spear-double-thrust","spear-spin"].map(e=>Zm.find(n=>n.id===e)).filter(Boolean),Vs=(()=>{let e=0,n=0;const s=gv.map(i=>{const r=ou(i),l={clip:i,s:r,at:e,z:n};return e+=i.duration,n+=r[r.length-1].dz??0,l}),a=s.flatMap(i=>i.clip.keys.filter(r=>r.strike).map(r=>i.at+r.t));return{parts:s,duration:e,beats:a}})(),xv=Vs.duration;function uh(e){const n=[...Vs.parts].reverse().find(a=>e>=a.at)??Vs.parts[0],s=iu(n.s,e-n.at);return{k:s,root:[s.dx??0,s.dy??0,n.z+(s.dz??0)],yaw:s.turn??0}}function bv(e,n,s,a,i){const r={start:0,end:Vs.duration,yaw:0,height:1.8,beats:Vs.beats,centre:m=>{const d=uh(m);return[d.root[0],0,d.root[2]]}},l=mg(n,s,r),c=uh(s),u=Vs.beats.reduce((m,d)=>Math.max(m,s>=d&&s-d<.12?1-(s-d)/.12:0),0);lu(e,a,i,l,[ru(c.k,c.root,c.yaw)],n.beats?u:0)}const Ko=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/đ/g,"d").toLowerCase();function cu({draw:e,rest:n,loop:s,hot:a}){const i=R.useRef(null);return R.useEffect(()=>{const r=i.current,l=r?.getContext("2d");if(!r||!l)return;if(!a){e(l,n,r.width,r.height);return}let c=0;const u=performance.now(),m=()=>{e(l,(performance.now()-u)/1e3%s,r.width,r.height),c=requestAnimationFrame(m)};return c=requestAnimationFrame(m),()=>cancelAnimationFrame(c)},[e,n,s,a]),t.jsx("canvas",{ref:i,width:192,height:108,"aria-hidden":"true"})}function yv({stage:e,selected:n,playhead:s,change:a,setError:i,query:r}){const l=ht(),c=l==="en",[u,m]=R.useState(null),[d,f]=R.useState("all"),p=Ko(r.trim()),x=pg.filter(w=>p?Ko(`${w.name} ${w.nameEn} ${w.desc??""} ${w.id}`).includes(p):d==="all"||w.cat===d),g=fg(e,n),v=w=>{if(!g){i(o("Thêm một nhân vật hoặc vật thể vào cảnh để camera bám theo."));return}const C=dc(e,{preset:w,subject:g.id,start:s});if(!C.ok){i(C.error.startsWith("not enough")?o("Không còn đủ thời lượng shot sau playhead cho chuyển động camera."):C.error);return}i(""),a(M=>{const S=dc(M,{preset:w,subject:g.id,start:s});return S.ok?S.stage:M})};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":o("Nhóm camera"),children:[{id:"all",name:"Tất cả",nameEn:"All"},...gg].map(w=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===w.id,className:d===w.id&&!p?"active":"",onClick:()=>f(w.id),children:c?w.nameEn:o(w.name)},w.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?o("Camera bám theo “{0}” từ playhead đến hết shot. Chọn đối tượng khác trước để đổi chủ thể.",[g.name]):o("Thêm một nhân vật vào cảnh để camera bám theo.")}),t.jsxs("div",{className:"shot-fx-grid",children:[x.map(w=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-camera":w.id,title:c?w.descEn:w.desc,onMouseEnter:()=>m(w.id),onMouseLeave:()=>m(null),onFocus:()=>m(w.id),onBlur:()=>m(null),onClick:()=>v(w),children:[t.jsx(cu,{draw:(C,M,S,I)=>bv(C,w,M,S,I),rest:1.2,loop:xv,hot:u===w.id}),t.jsx("span",{children:c?w.nameEn:w.name})]},w.id)),!x.length&&t.jsx("p",{className:"shot-fx-empty",children:o("Không có camera nào khớp.")})]})]})}function vv({stage:e,selected:n,onPlay:s,setError:a,query:i}){const r=ht(),l=r==="en",[c,u]=R.useState(null),[m,d]=R.useState("all"),f=Ko(i.trim()),p=tp.filter(({clip:w,pack:C})=>f?Ko(`${w.label} ${w.labelEn} ${w.id} ${C.label} ${C.labelEn} ${C.id==="spear"?"thuong giao":C.id==="katana"?"kiem guom":"con gay truong"}`).includes(f):m==="all"||C.id===m),x=n?e.items.find(w=>w.id===n):null,g=x&&Nr(x)?x:e.items.find(w=>w.kind==="person"&&!w.hidden)??null,v=w=>{const C=np(w.id);if(!g||!C){a(o("Thêm một nhân vật vào cảnh (hoặc chọn nhân vật) để áp combo vũ khí."));return}a(""),s(g.id,C)};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":o("Loại vũ khí"),children:[{id:"all",label:"Tất cả",labelEn:"All"},...Xh].map(w=>t.jsx("button",{type:"button",role:"tab","data-weapon-pack":w.id,"aria-selected":m===w.id,className:m===w.id&&!f?"active":"",onClick:()=>d(w.id),children:l?w.labelEn:o(w.label)},w.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?o("Áp lên “{0}” từ playhead — tự đặt vũ khí vào tay, hai tay bám cán.",[g.name]):o("Thêm một nhân vật vào cảnh để áp combo vũ khí.")}),t.jsxs("div",{className:"shot-fx-grid",children:[p.map(({clip:w,pack:C})=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-combo":w.id,title:`${l?w.labelEn:w.label} · ${w.duration}s`,onMouseEnter:()=>u(w.id),onMouseLeave:()=>u(null),onFocus:()=>u(w.id),onBlur:()=>u(null),onClick:()=>v(w),children:[t.jsx(cu,{draw:(M,S,I,y)=>fv(M,w,S,I,y,C.prop.prop),rest:uv(w),loop:w.duration+.4,hot:c===w.id}),t.jsx("span",{children:l?w.labelEn:w.label})]},w.id)),!p.length&&t.jsx("p",{className:"shot-fx-empty",children:o("Không có combo nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:o("Mẹo: nối nhiều combo liên tiếp (dời playhead), rồi chọn camera “Punch-in theo nhịp đòn” hoặc “Đạo diễn hành động” — camera tự bắt nhịp các đòn.")})]})}const jv=[.5,.3,.15],kv=[["sakuga","Sakuga · khung tối rồi chớp trắng 2 khung"],["anime","Anime · khung âm bản rồi tách màu"],["manga","Manga · mực đen trắng + vệt tốc độ"],["flash","Chớp trắng"],["invert","Đảo màu"],["rgb","Tách màu RGB"],["radial","Nhoè toả tâm"]],wv=e=>{const{trail:n,...s}=e;return s};function Mv({stage:e,playhead:n,change:s,setError:a}){ht();const[i,r]=R.useState("medium"),[l,c]=R.useState(.3),u=e.shots.find(y=>y.id===e.activeShot)??e.shots[0],m=u.duration,d=Za(u.timing,m),f=sp(e).map(y=>y.time),p=y=>s(k=>({...k,shots:k.shots.map(T=>{if(T.id!==k.activeShot)return T;const j=y(Za(T.timing,T.duration)),{timing:L,...N}=T;return j?{...N,timing:j}:N})})),x=()=>e.items.filter(y=>Nr(y)).flatMap(y=>dp([...u.objectKeys?.[y.id]||[]].sort((k,T)=>k.time-T.time).map(k=>({t:k.time*m,y:k.position[1],air:!!k.air})))),g=e.items.filter(y=>y.kind==="prop"&&y.hold&&y.prop&&ap[y.prop.kind]),v=g.length>0&&g.every(y=>y.trail),w=(y,k={})=>s(T=>({...T,items:T.items.map(j=>g.some(L=>L.id===j.id)?y?{...j,trail:{...j.trail||{},...k}}:wv(j):j)})),C=g[0]?.trail?.style??"ribbon",M=op({duration:m,timing:d??void 0}),S=ip(u.impactFrame),I=y=>s(k=>({...k,shots:k.shots.map(T=>{if(T.id!==k.activeShot)return T;const{impactFrame:j,...L}=T;return y?{...L,impactFrame:y}:L})}));return t.jsxs("div",{className:"shot-timing",children:[t.jsx("p",{className:"shot-fx-hint",children:o("Hit-stop khựng hình đúng lúc trúng đòn, slow-mo làm chậm khoảnh khắc đẹp nhất. Chỉ đổi cách phát và xuất video — key chuyển động giữ nguyên.")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Nhịp anime (sakuga)")}),t.jsx("p",{className:"shot-fx-hint",children:o("Nhịp đòn đo từ các cảnh đánh nhau anime vẽ tay: đỡ khựng 1 khung, trúng thân 3, trúng đầu 6, đòn kết 12; lặng một nhịp trước đòn kết rồi bùng nổ, dư chấn chậm lại; máy rung kiểu vẽ tay; khung tối rồi chớp trắng.")}),t.jsx("button",{type:"button","data-timing":"sakuga",disabled:!f.length&&!u.impacts?.length,onClick:()=>{const y=rp(u,lp(e),{keepLook:!1});if(!y){a(o("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."));return}a(""),s(k=>({...k,shots:k.shots.map(T=>T.id===k.activeShot?{...T,timing:y.shot.timing,impacts:y.shot.impacts,impactFrame:y.shot.impactFrame}:T)}))},children:o("Áp nhịp anime ({0} đòn)",[u.impacts?.length||f.length])})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Hit-stop")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Độ khựng")}),t.jsxs("select",{"aria-label":o("Độ khựng"),value:i,onChange:y=>r(y.target.value),children:[t.jsx("option",{value:"light",children:o("Nhẹ")}),t.jsx("option",{value:"medium",children:o("Vừa")}),t.jsx("option",{value:"heavy",children:o("Mạnh")})]})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"hitstops",disabled:!f.length,title:f.length?void 0:o("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."),onClick:()=>{a(""),p(y=>Dl(y,f,zl[i],m))},children:o("Khựng mọi đòn ({0})",[f.length])}),t.jsx("button",{type:"button",onClick:()=>p(y=>Dl(y,[n],zl[i],m)),children:o("Khựng tại playhead")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Slow-mo")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Tốc độ")}),t.jsx("select",{"aria-label":o("Tốc độ slow-mo"),value:l,onChange:y=>c(+y.target.value),children:jv.map(y=>t.jsxs("option",{value:y,children:[Math.round(y*100),"%"]},y))})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"apex",onClick:()=>{const y=x();if(!y.length){a(o("Không thấy cú nhảy nào trong shot."));return}a(""),p(k=>y.reduce((T,j)=>pi(T,j,.3,l,m),k))},children:o("Chậm ở đỉnh cú nhảy")}),t.jsx("button",{type:"button","data-timing":"slow-playhead",onClick:()=>p(y=>pi(y,n,.35,l,m)),children:o("Chậm quanh playhead")}),f.length>0&&t.jsx("button",{type:"button",onClick:()=>p(y=>pi(y,f[f.length-1],.3,l,m)),children:o("Chậm đòn kết")})]})]}),d&&t.jsxs("div",{className:"shot-list shot-timing-list",children:[d.holds.map(y=>t.jsxs("div",{children:[t.jsxs("span",{children:["⏸ ",o("Khựng {0}s · {1}s",[y.at.toFixed(2),y.hold.toFixed(2)])]}),t.jsx("button",{type:"button","aria-label":o("Bỏ khựng {0}s",[y.at.toFixed(2)]),onClick:()=>p(k=>Za({holds:(k?.holds||[]).filter(T=>T.at!==y.at),slows:k?.slows||[]},m)),children:t.jsx(Ce.trash,{})})]},`h${y.at}`)),d.slows.map(y=>t.jsxs("div",{children:[t.jsxs("span",{children:["🐢 ",o("Chậm {0}–{1}s · {2}%",[y.start.toFixed(2),y.end.toFixed(2),Math.round(y.speed*100)])]}),t.jsx("button",{type:"button","aria-label":o("Bỏ slow-mo {0}s",[y.start.toFixed(2)]),onClick:()=>p(k=>Za({holds:k?.holds||[],slows:(k?.slows||[]).filter(T=>T.start!==y.start)},m)),children:t.jsx(Ce.trash,{})})]},`s${y.start}`))]}),t.jsx("p",{className:"shot-fx-hint","data-testid":"timing-length",children:d?o("Video dài {0}s (shot {1}s).",[M.toFixed(2),m.toFixed(2)]):o("Chưa có hit-stop hay slow-mo.")}),d&&t.jsx("button",{type:"button",onClick:()=>p(()=>null),children:o("Xoá nhịp đòn")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Khung va chạm")}),t.jsx("p",{className:"shot-fx-hint",children:o("Mỗi lần khựng hình chớp một khung va chạm kiểu anime / game, hướng về chỗ hai nhân vật.")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Kiểu")}),t.jsxs("select",{"aria-label":o("Kiểu khung va chạm"),"data-timing":"impact-style",value:S?.style??"",onChange:y=>I(y.target.value?{style:y.target.value,strength:S?.strength??1}:null),children:[t.jsx("option",{value:"",children:o("Không")}),kv.map(([y,k])=>t.jsx("option",{value:y,children:o(k)},y))]})]}),S&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Độ mạnh")}),t.jsx("input",{type:"range","aria-label":o("Độ mạnh khung va chạm"),min:.1,max:1,step:.05,value:S.strength,onChange:y=>I({...S,strength:+y.target.value})})]}),S&&!d?.holds.length&&t.jsx("p",{className:"shot-fx-hint",children:o("Thêm hit-stop để khung va chạm hiện ra.")})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Vệt chém")}),g.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Vệt chém trên vũ khí đang cầm ({0})",[g.length])}),t.jsx("input",{type:"checkbox","aria-label":o("Vệt chém"),checked:v,onChange:y=>w(y.target.checked)})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Kiểu vệt")}),t.jsxs("select",{"aria-label":o("Kiểu vệt chém"),"data-timing":"trail-style",value:C,onChange:y=>w(!0,{style:y.target.value}),children:[t.jsx("option",{value:"ribbon",children:o("Dải sáng")}),t.jsx("option",{value:"smear",children:o("Smear trắng (anime)")})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Màu vệt")}),t.jsx("input",{type:"color","aria-label":o("Màu vệt chém"),value:g[0].trail?.color||(C==="smear"?cp.color:hp.color),onChange:y=>w(!0,{color:y.target.value})})]})]}):t.jsx("p",{className:"shot-fx-hint",children:o("Chưa có vũ khí nào đang cầm (thương, kiếm, côn, gậy, dao).")})]})]})}const Sv={blocked:"đỡ",miss:"né",body:"trúng"};function Cv({stage:e,playhead:n,change:s,setError:a}){const i=ht(),r=i==="en",l=e.items.filter(N=>Nr(N)&&!N.hidden),[c,u]=R.useState(""),[m,d]=R.useState(""),[f,p]=R.useState(["katana","katana"]),[x,g]=R.useState(4),[v,w]=R.useState(1),[C,M]=R.useState(!0),[S,I]=R.useState(""),y=l.find(N=>N.id===c)??l[0],k=l.find(N=>N.id===m&&N.id!==y?.id)??l.find(N=>N.id!==y?.id),T=()=>s(N=>{const A=N.items.find(_=>_.id===y?.id),O=A?[A.position[0],0,A.position[2]+2]:[0,0,2];return{...N,items:[...N.items,{...fn("person",N.items.length),name:o("Đối thủ"),position:O,rotation:[0,180,0]}]}}),j=N=>{if(!y||!k){a(o("Cần hai nhân vật trong cảnh để dàn cảnh đấu."));return}const A=yg(e,{a:y.id,b:k.id,packs:f,exchanges:x,seed:N,start:n},()=>crypto.randomUUID());if(!A.ok){a(A.error);return}let O=A.stage;if(C)try{O=up(O,{fighters:[y.name,k.name],start:n,end:A.end+.4}).stage}catch{}a(""),w(N),I(A.plan.map(_=>`${_.time.toFixed(1)}s ${_.attackerName} → ${r?_.result:o(Sv[_.result])}`).join(" · ")),s(()=>O)},L=(N,A)=>p(O=>N===0?[A,O[1]]:[O[0],A]);return t.jsxs("fieldset",{className:"shot-duel",children:[t.jsx("legend",{children:o("Đấu 2 người")}),l.length<2?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:o("Cần hai nhân vật trong cảnh để dàn cảnh đấu.")}),t.jsx("button",{type:"button","data-duel":"add-opponent",onClick:T,children:o("Thêm đối thủ")})]}):t.jsxs(t.Fragment,{children:[[0,1].map(N=>t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("select",{"aria-label":N===0?o("Người tấn công trước"):o("Đối thủ"),value:(N===0?y:k)?.id??"",onChange:A=>(N===0?u:d)(A.target.value),children:l.filter(A=>N===0||A.id!==y?.id).map(A=>t.jsx("option",{value:A.id,children:A.name},A.id))}),t.jsx("select",{"aria-label":o("Vũ khí"),"data-duel-weapon":N,value:f[N],onChange:A=>L(N,A.target.value),children:[...Xh.filter(A=>A.id in bg),{id:"fist",label:"Tay không",labelEn:"Unarmed"}].map(A=>t.jsx("option",{value:A.id,children:r?A.labelEn:o(A.label)},A.id))})]},N)),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Số pha đấu")}),t.jsx("input",{type:"number","aria-label":o("Số pha đấu"),min:1,max:10,value:x,onChange:N=>g(Math.max(1,Math.min(10,Number(N.target.value)||4)))})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Camera đấu (giữ cả hai trong khung)")}),t.jsx("input",{type:"checkbox","aria-label":o("Camera đấu"),checked:C,onChange:N=>M(N.target.checked)})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-duel":"stage",onClick:()=>j(v),children:o("Dàn cảnh đấu từ playhead")}),t.jsx("button",{type:"button","data-duel":"reroll",onClick:()=>j(v+1),children:o("Phương án khác")})]}),t.jsx("p",{className:"shot-fx-hint",children:S||o("Đòn tấn công gặp đỡ / né / trúng đúng khung chạm, tự thêm hit-stop và tia lửa. Thay toàn bộ chuyển động của hai người từ playhead.")})]})]})}const gr="application/x-clipoox-fx",xr=(e,n)=>e.lib?n==="en"&&e.nameEn?e.nameEn:e.name:o(e.name),Nv=(e,n)=>e.lib?n==="en"&&e.descEn?e.descEn:e.desc:o(e.desc);function Av({entry:e,hot:n}){const s=R.useRef(null);return R.useEffect(()=>{const a=s.current;if(!a)return;const i=a.getContext("2d");if(!i)return;const r=a.width,l=a.height;if(!n){hc(i,e,lg(e),r,l);return}let c=0;const u=performance.now(),m=cg(e),d=()=>{hc(i,e,(performance.now()-u)/1e3%m,r,l),c=requestAnimationFrame(d)};return c=requestAnimationFrame(d),()=>cancelAnimationFrame(c)},[e,n]),t.jsx("canvas",{ref:s,width:192,height:108,"aria-hidden":"true"})}function $s({label:e,value:n,onChange:s,min:a,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o(e)}),t.jsx(gn,{"aria-label":o(e),precision:2,value:n,min:a,max:i,step:r,onCommit:s})]})}const mh=[["chest","ngực"],["head","đầu"],["feet","chân"],["hand_right","tay phải"],["hand_left","tay trái"]];function Tv({stage:e,selected:n,playhead:s,change:a,onSelect:i,ground:r,anchor:l,setError:c,onEdit:u,onPlayClip:m}){const d=ht(),f=dv(),[p,x]=R.useState(""),[g,v]=R.useState("tu-tien"),[w,C]=R.useState(null),M=e.shots.find(T=>T.id===e.activeShot)??e.shots[0],S=R.useMemo(()=>g==="camera"||g==="weapon"||g==="timing"?[]:mp(p,p.trim()?void 0:g),[p,g,f.version]),I=e.items.filter(T=>T.kind==="fx"&&T.fx),y=I.find(T=>T.id===n)??null,k=T=>{const j=su(e,T,{selected:n,ground:r(),start:s,label:xr(T,d),anchor:l});if("error"in j){c(o("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[ln.maxItems]));return}c(""),a(()=>j.stage),i(j.item.id)};return t.jsxs("div",{className:"shot-fx",children:[y&&u&&t.jsxs("button",{type:"button",className:"shot-fx-edit-jump",onClick:u,children:["✎ ",o("Sửa {0}",[y.name])]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":o("Tìm hiệu ứng"),placeholder:o("Tìm hiệu ứng… (vd: kiem, set, aura)"),value:p,onChange:T=>x(T.target.value)})}),t.jsxs("div",{className:"shot-fx-cats",role:"tablist","aria-label":o("Nhóm hiệu ứng"),children:[pp.map(T=>t.jsxs("button",{type:"button",role:"tab","aria-selected":g===T.id&&!p.trim(),disabled:!T.ready,className:g===T.id&&!p.trim()?"active":"",title:T.ready?o(T.name):o("Sắp có"),onClick:()=>{v(T.id),x("")},children:[o(T.name),!T.ready&&t.jsx("small",{children:o("sắp có")})]},T.id)),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="camera",className:`shot-lib-tab${g==="camera"?" active":""}`,onClick:()=>v("camera"),children:["🎥 ",o("Camera")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="weapon",className:`shot-lib-tab${g==="weapon"?" active":""}`,onClick:()=>v("weapon"),children:["⚔ ",o("Combo vũ khí")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="timing",className:`shot-lib-tab${g==="timing"?" active":""}`,onClick:()=>v("timing"),children:["⏱ ",o("Nhịp đòn")]})]}),g==="camera"&&t.jsx(yv,{stage:e,selected:n,playhead:s,change:a,setError:c,query:p}),g==="weapon"&&!p&&t.jsx(Cv,{stage:e,playhead:s,change:a,setError:c}),g==="weapon"&&(m?t.jsx(vv,{stage:e,selected:n,onPlay:m,setError:c,query:p}):null),g==="timing"&&t.jsx(Mv,{stage:e,playhead:s,change:a,setError:c}),g!=="camera"&&g!=="weapon"&&g!=="timing"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-fx-grid",children:[S.map(T=>t.jsxs("button",{type:"button",className:`shot-fx-card${T.lib?" lib":""}`,"data-fx":T.id,draggable:!0,title:Nv(T,d),onMouseEnter:()=>C(T.id),onMouseLeave:()=>C(null),onFocus:()=>C(T.id),onBlur:()=>C(null),onDragStart:j=>{j.dataTransfer.setData(gr,T.id),j.dataTransfer.effectAllowed="copy"},onClick:()=>k(T),children:[t.jsx(Av,{entry:T,hot:w===T.id}),t.jsx("span",{children:xr(T,d)}),T.lib&&t.jsx("small",{className:"shot-fx-lib",children:o("Thư viện Clipoox")})]},T.id)),!S.length&&t.jsx("p",{className:"shot-fx-empty",children:o("Không có hiệu ứng nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:o("Bấm hoặc kéo thẻ vào khung 3D. Chọn nhân vật trước để hiệu ứng bám vào tay / chân và nhắm vào nhân vật khác.")})]}),t.jsxs("h3",{children:[o("Hiệu ứng trong cảnh")," ",t.jsxs("small",{className:"shot-total",children:["· ",I.length,"/",ln.maxItems]})]}),t.jsxs("div",{className:"shot-list shot-fx-list",children:[I.map(T=>{const j=Mn(T,M);return t.jsxs("div",{className:n===T.id?"active":"",children:[t.jsxs("button",{title:o("Sửa {0}",[T.name]),onClick:()=>{i(T.id),u?.()},children:["✦ ",T.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",j.off?o("không phát trong shot này"):`${j.start.toFixed(1)}s → ${(j.start+j.duration).toFixed(1)}s`]})]}),t.jsx("button",{title:T.hidden?o("Hiện"):o("Ẩn"),onClick:()=>a(L=>({...L,items:L.items.map(N=>N.id===T.id?{...N,hidden:!N.hidden}:N)})),children:T.hidden?"○":"●"}),t.jsx("button",{className:"shot-delete-item","aria-label":o("Xóa {0}",[T.name]),title:o("Xóa {0}",[T.name]),onClick:()=>{a(L=>({...L,items:L.items.filter(N=>N.id!==T.id),shots:L.shots.map(N=>N.fxTiming?.[T.id]?{...N,fxTiming:Object.fromEntries(Object.entries(N.fxTiming).filter(([A])=>A!==T.id))}:N)})),n===T.id&&i(null)},children:t.jsx(Ce.trash,{})})]},T.id)}),!I.length&&t.jsx("p",{className:"shot-fx-empty",children:o("Chưa có hiệu ứng. Chọn một thẻ ở trên.")})]})]})}function Lv({stage:e,selected:n,playhead:s,change:a,onSelect:i,ground:r,engine:l}){ht();const c=e.shots.find(d=>d.id===e.activeShot)??e.shots[0],u=e.items.filter(d=>d.kind==="fx"&&d.fx),m=u.find(d=>d.id===n)??null;return t.jsxs("div",{className:"shot-fx shot-fx-edit",children:[u.length>1&&t.jsxs("select",{"aria-label":o("Hiệu ứng đang sửa"),value:m?.id??"",onChange:d=>i(d.target.value||null),children:[!m&&t.jsx("option",{value:"",children:o("Chọn hiệu ứng…")}),u.map(d=>t.jsxs("option",{value:d.id,children:["✦ ",d.name]},d.id))]}),m?t.jsx(Ev,{item:m,stage:e,shot:c,playhead:s,change:a,ground:r,engine:l??null}):t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:u.length?o("Bấm vào một hiệu ứng trên timeline (hàng ✦) hoặc chọn ở trên để sửa."):o("Chưa có hiệu ứng. Thêm ở bảng Hiệu ứng.")}),u.length===1&&t.jsxs("button",{type:"button",onClick:()=>i(u[0].id),children:["✎ ",o("Sửa {0}",[u[0].name])]})]})]})}function Ev({item:e,stage:n,shot:s,playhead:a,change:i,ground:r,engine:l}){const c=ht(),[u,m]=R.useState(null),d=e.fx,f=Eo[d.preset],p=Vh(d.cat??""),x=Mn(e,s),g=!!s.fxTiming?.[e.id],v=n.items.filter(P=>P.id!==e.id&&P.kind!=="fx"&&!P.hidden),w=(P,W={})=>i(z=>({...z,items:z.items.map(Q=>Q.id===e.id?{...Q,...W,fx:{...Q.fx,...P}}:Q)})),C=P=>i(W=>({...W,items:W.items.map(z=>z.id===e.id?{...z,...P}:z)})),M=P=>i(W=>({...W,shots:W.shots.map(z=>z.id===W.activeShot?{...z,fxTiming:{...z.fxTiming,[e.id]:Ar({...Mn(e,z),...P,off:!1},z.duration)}}:z)})),S=(P,W)=>w({params:{...d.params,[P]:W}}),I=Xi(Ui(d).fx??d),y=d.path??[],k=P=>w({path:P.length>=2?P:void 0}),T=y.length;R.useEffect(()=>{if(!(!l||T<2))return l.setFxPathEditor({itemId:e.id,selected:u,select:m,move:(P,W)=>i(z=>({...z,items:z.items.map(Q=>Q.id===e.id&&Q.fx?.path?{...Q,fx:{...Q.fx,path:Q.fx.path.map((J,V)=>V===P?W.map(B=>+B.toFixed(2)):J)}}:Q)}))}),()=>l.setFxPathEditor(null)},[l,e.id,T,u]);const j=d.attach?v.find(P=>P.id===d.attach.to):void 0,L=s.duration>0?Math.min(1,Math.max(0,a/s.duration)):0,N=Yh(e,s),A=Io(e,s,L),O=P=>{N?i(W=>Ro(W,e.id,L,P)):P.position?w({attach:{...d.attach,offset:P.position}}):P.yaw!==void 0&&C({rotation:[e.rotation[0],P.yaw,e.rotation[2]]})},_=P=>{const[W,z]=P.split("|"),Q=v.find(J=>J.id===W);return Q?_l(Q,z).map(J=>+J.toFixed(2)):null},$=v.flatMap(P=>mh.filter(([W])=>P.kind==="person"||W==="chest"||W==="feet").map(([W,z])=>t.jsxs("option",{value:`${P.id}|${W}`,children:[P.name," · ",o(z)]},`${P.id}|${W}`)));return t.jsxs("div",{className:"shot-fx-inspector","aria-label":o("Chỉnh hiệu ứng"),children:[t.jsxs("h3",{children:[o("CHỈNH HIỆU ỨNG")," ",t.jsxs("small",{className:"shot-total",children:["· ",p?xr(p,c):e.name]})]}),t.jsx("input",{"aria-label":o("Tên hiệu ứng"),value:e.name,onChange:P=>C({name:P.target.value})}),n.plate&&t.jsxs("label",{className:"shot-field",title:o("Lớp sau người: Timeline tách người trong video và đặt hiệu ứng ra sau (aura, vòng sáng). Lớp trước người: phủ lên cả người (tia lửa, hạt bay qua)."),children:[t.jsx("span",{className:"shot-fx-vfx-label",children:o("Lớp VFX")}),t.jsxs("select",{"aria-label":o("Lớp VFX"),value:Qh(e),onChange:P=>C({vfxLayer:P.target.value}),children:[t.jsx("option",{value:"behind",children:o("Sau người")}),t.jsx("option",{value:"front",children:o("Trước người")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Thời gian trong shot")}),g?t.jsxs(t.Fragment,{children:[t.jsx($s,{label:"Bắt đầu (s)",value:x.start,min:0,max:Math.max(.1,s.duration),step:.1,onChange:P=>M({start:P})}),t.jsx($s,{label:"Kéo dài (s)",value:x.duration,min:.2,max:ln.maxDuration,step:.1,onChange:P=>M({duration:P})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Lặp lại")}),t.jsx("input",{type:"checkbox","aria-label":o("Lặp lại"),checked:x.loop,onChange:P=>M({loop:P.target.checked})})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",onClick:()=>M({start:+(a*s.duration).toFixed(2)}),children:o("Bắt đầu tại playhead")}),t.jsx("button",{type:"button",onClick:()=>i(P=>({...P,shots:P.shots.map(W=>W.id===P.activeShot?{...W,fxTiming:Object.fromEntries(Object.entries(W.fxTiming??{}).filter(([z])=>z!==e.id))}:W)})),children:o("Bỏ khỏi shot này")})]})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>M({start:+(a*s.duration).toFixed(2),duration:d.duration}),children:o("Phát trong shot này")})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Màu")}),t.jsx("input",{type:"color","aria-label":o("Màu hiệu ứng"),value:e.color,onChange:P=>C({color:P.target.value})})]}),t.jsx($s,{label:"Cường độ",value:d.intensity,min:.1,max:3,step:.1,onChange:P=>w({intensity:P})}),t.jsx($s,{label:"Kích thước",value:e.scale[0],min:.1,max:6,step:.1,onChange:P=>C({scale:[P,P,P]})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(gn,{"aria-label":o("Seed"),value:d.seed,min:0,max:2147483647,step:1,onCommit:P=>w({seed:Math.round(P)})}),t.jsxs("button",{type:"button","aria-label":o("Đổi seed ngẫu nhiên"),title:o("Đổi seed ngẫu nhiên"),onClick:()=>w({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ce.reset,{}),o("Xáo trộn")]})]})]}),f.params.length>0&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Thông số")}),f.params.map(P=>P.type==="number"?t.jsx($s,{label:P.label??P.key,value:Number(d.params[P.key]??P.def),min:P.min,max:P.max,step:P.max-P.min>20?1:.05,onChange:W=>S(P.key,W)},P.key):t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o(P.label??P.key)}),t.jsx("select",{"aria-label":o(P.label??P.key),value:String(d.params[P.key]??P.def),onChange:W=>S(P.key,W.target.value),children:P.options.map(W=>t.jsx("option",{value:W,children:W},W))})]},P.key))]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Gắn vào")}),t.jsxs("select",{"aria-label":o("Đối tượng gắn hiệu ứng"),value:d.attach?.to??"",onChange:P=>{const W=P.target.value;w({attach:W?{to:W,...d.attach?.hand?{hand:d.attach.hand}:{},offset:d.attach?.offset}:void 0})},children:[t.jsx("option",{value:"",children:o("Tự do (theo vị trí của hiệu ứng)")}),v.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]}),d.attach&&t.jsxs(t.Fragment,{children:[j?.kind==="person"&&t.jsxs("select",{"aria-label":o("Bộ phận gắn"),value:d.attach.hand??d.attach.part??"",onChange:P=>{const W=P.target.value,{hand:z,part:Q,...J}=d.attach;w({attach:{...J,...W==="L"||W==="R"?{hand:W}:W==="chest"||W==="head"?{part:W}:{}}})},children:[t.jsx("option",{value:"",children:o("Cơ thể (chân)")}),t.jsx("option",{value:"chest",children:o("Ngực")}),t.jsx("option",{value:"head",children:o("Đầu")}),t.jsx("option",{value:"R",children:o("Tay phải")}),t.jsx("option",{value:"L",children:o("Tay trái")})]}),d.attach.hand&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Ở đầu vật đang cầm (nòng súng)")}),t.jsx("input",{type:"checkbox","aria-label":o("Ở đầu vật đang cầm (nòng súng)"),checked:d.attach.tip===!0,onChange:P=>w({attach:{...d.attach,tip:P.target.checked?!0:void 0}})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Xoay theo đối tượng")}),t.jsx("input",{type:"checkbox","aria-label":o("Xoay theo đối tượng"),checked:d.attach.follow!=="position",onChange:P=>{const{follow:W,...z}=d.attach;w({attach:{...z,...P.target.checked?{}:{follow:"position"}}})}})]}),t.jsx("p",{className:"shot-fx-hint",children:N?o("Độ lệch theo key: {0} key trong shot này. Sửa số dưới đây là ghi key tại playhead.",[s.objectKeys?.[e.id]?.length??0]):o("Bấm +◆ ở hàng hiệu ứng trên timeline để thêm key độ lệch tại playhead (sửa khi hiệu ứng bị lệch).")}),t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map((P,W)=>t.jsxs("label",{children:[t.jsx("span",{children:P}),t.jsx(gn,{"aria-label":o("Lệch {0}",[P]),precision:2,step:.1,min:-100,max:100,value:+A.position[W].toFixed(3),onCommit:z=>{const Q=[...A.position];Q[W]=z,O({position:Q})}})]},P))}),t.jsx("button",{type:"button",onClick:()=>i(P=>Ro(P,e.id,L)),children:o("+◆ Key độ lệch tại playhead")})]}),!d.attach&&t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map((P,W)=>t.jsxs("label",{children:[t.jsx("span",{children:P}),t.jsx(gn,{"aria-label":o("Vị trí {0}",[P]),precision:2,step:.1,min:-1e3,max:1e3,value:e.position[W],onCommit:z=>{const Q=[...e.position];Q[W]=z,C({position:Q})}})]},P))}),t.jsx($s,{label:"Hướng (độ)",value:d.attach?+A.yaw.toFixed(1):e.rotation[1],min:-360,max:360,step:5,onChange:P=>d.attach?O({yaw:P}):C({rotation:[e.rotation[0],P,e.rotation[2]]})})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Nhắm vào")}),t.jsxs("select",{"aria-label":o("Mục tiêu bám theo"),value:d.target?`${d.target.to}|${d.target.part}`:"",onChange:P=>{const[W,z]=P.target.value.split("|");w({target:W?{to:W,part:z,...d.target?.to===W&&d.target.name?{name:d.target.name}:{}}:void 0})},children:[t.jsx("option",{value:"",children:o("Không (theo đường bay / hướng)")}),v.flatMap(P=>[...mh.filter(([W])=>["chest","head","feet"].includes(W)).map(([W,z])=>t.jsxs("option",{value:`${P.id}|${W}`,children:[P.name," · ",o(z)]},`${P.id}|${W}`)),t.jsxs("option",{value:`${P.id}|center`,children:[P.name," · ",o("Cả khối (nhà, tường, cửa kính)")]},`${P.id}|center`)])]}),d.target&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Chỉ một phần (tên, vd: window)")}),t.jsx("input",{"aria-label":o("Tên phần của mục tiêu"),value:d.target.name??"",onChange:P=>w({target:{...d.target,name:P.target.value.trim()?P.target.value.slice(0,60):void 0}})})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Đường bay")}),y.length<2&&t.jsx("button",{type:"button",onClick:()=>{const P=_l(j??{kind:"box",position:e.position,scale:[1,1,1]},"chest"),W=r();k([P.map(z=>+z.toFixed(2)),[+(P[0]+6).toFixed(2),P[1],+(W[2]||P[2]).toFixed(2)]])},children:o("Tạo đường bay")}),y.length>=2&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Từ")}),t.jsxs("select",{"aria-label":o("Điểm xuất phát"),value:"",onChange:P=>{const W=_(P.target.value);W&&k([W,...y.slice(1)])},children:[t.jsx("option",{value:"",children:o("Chọn đối tượng…")}),$]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Tới")}),t.jsxs("select",{"aria-label":o("Điểm đến"),value:"",onChange:P=>{const W=_(P.target.value);W&&k([...y.slice(0,-1),W])},children:[t.jsx("option",{value:"",children:o("Chọn đối tượng…")}),$]})]}),y.map((P,W)=>t.jsxs("div",{className:`shot-fx-point ${u===W?"active":""}`,children:[t.jsx("b",{role:"button",tabIndex:0,title:o("Chọn điểm để kéo trong khung 3D"),onClick:()=>m(W),onKeyDown:z=>{z.key==="Enter"&&m(W)},children:W===0?o("Đầu"):W===y.length-1?o("Cuối"):`${W+1}`}),[0,1,2].map(z=>t.jsx(gn,{"aria-label":o("Điểm {0} {1}",[W+1,"XYZ"[z]]),precision:2,step:.1,min:-1e3,max:1e3,value:P[z],onCommit:Q=>{const J=y.map(V=>[...V]);J[W][z]=Q,k(J)}},z)),t.jsx("button",{type:"button","aria-label":o("Xóa điểm {0}",[W+1]),disabled:y.length<=2,onClick:()=>k(y.filter((z,Q)=>Q!==W)),children:t.jsx(Ce.close,{})})]},W)),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",disabled:y.length>=ln.maxPathPoints,onClick:()=>{const P=y.at(-2),W=y.at(-1);k([...y.slice(0,-1),[+((P[0]+W[0])/2).toFixed(2),+((P[1]+W[1])/2+.8).toFixed(2),+((P[2]+W[2])/2).toFixed(2)],W])},children:o("Thêm điểm giữa")}),t.jsx("button",{type:"button",onClick:()=>w({path:void 0}),children:o("Xóa đường bay")})]})]})]}),t.jsx("small",{className:"shot-fx-budget",children:o("{0} hạt · giới hạn {1}/hiệu ứng",[I,ln.maxParticlesPerItem])})]})}const Vt=e=>+e.toFixed(2),Iv=[{key:"radius",step:.1},{key:"falloff",step:.1},{key:"strength",step:.5},{key:"lift",step:.05},{key:"gravity",step:.5},{key:"chunks",step:10},{key:"debris",step:.1},{key:"spin",step:.5},{key:"collapse",step:.05},{key:"shake",step:.05}],Rv=[{key:"yaw",step:5},{key:"crumble",step:.05},{key:"dust",step:.1},{key:"shake",step:.05},{key:"chunks",step:10},{key:"gravity",step:.5},{key:"debris",step:.1}],Fv={collapse:"🏚",explosion:"💥",shatter:"🪟",burning:"🔥",collapse_building:"🏢"},Pv={pancake:"Sập tại chỗ (từng tầng)",topple:"Đổ nghiêng",base:"Sập từ chân"},hu=e=>Kh.has(String(e)),Pa=e=>!!e&&e.kind==="fx"&&e.fx?.preset===Gi,du=e=>e.items.filter(n=>Pd.has(n.kind)&&!n.hidden&&!n.hold);function uu(e,n){const s=e.shots.find(x=>x.id===e.activeShot)??e.shots[0],a=e.items.find(x=>x.id===n.target),i=n.bounds??{min:[a.position[0]-.5,0,a.position[2]-.5],max:[a.position[0]+.5,1,a.position[2]+.5]},r=[0,1,2].map(x=>i.max[x]-i.min[x]),l=Vt(Math.min(6,Math.max(.6,Math.max(...r)/5))),c=hu(n.recipe),u=Vt(Math.min(Math.max(0,n.playhead),Math.max(0,s.duration-.2))),m=Vt(Math.max(.3,c?Math.min(4,s.duration-u):s.duration-u)),d=bp({target:a.id,recipe:n.recipe,seed:n.seed??Math.floor(Math.random()*1e9)+1,start:u,duration:m,params:{radius:l,...n.params}}),f=c?[Vt((i.min[0]+i.max[0])/2),Vt(i.max[1]+.6),Vt((i.min[2]+i.max[2])/2)]:[Vt(i.min[0]-l-Number(d.params.falloff)-.3),Vt((i.min[1]+i.max[1])/2),Vt((i.min[2]+i.max[2])/2)],p={...fn("fx",e.items.length),name:n.name,color:Da[n.recipe].color,position:f,fx:d};return{item:p,stage:{...e,items:[...e.items,p],shots:e.shots.map(x=>x.id===s.id?{...x,fxTiming:{...x.fxTiming,[p.id]:{start:u,duration:m}}}:x)}}}function bo(e,n,s,a,i=bt()){const r=e.shots.find(f=>f.id===e.activeShot)??e.shots[0],l=e.items.find(f=>f.id===n);if(!l)return e;const c=r.objectKeys?.[n]??[],u=Tn(l,r,s),m=c.find(f=>Math.abs(f.time-s)<1e-6),d={...m,id:m?.id??i,time:s,position:a??[...u.position],rotation:[...u.rotation],scale:[...u.scale]};return{...e,shots:e.shots.map(f=>f.id===r.id?{...f,objectKeys:{...f.objectKeys,[n]:[...c.filter(p=>p.id!==d.id),d].sort((p,x)=>p.time-x.time)}}:f)}}function yo({label:e,value:n,onChange:s,min:a,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o(e)}),t.jsx(gn,{"aria-label":o(e),precision:2,value:n,min:a,max:i,step:r,onCommit:s})]})}function $v({stage:e,selected:n,progress:s,change:a,onSelect:i,engine:r,setError:l}){ht();const c=e.shots.find(C=>C.id===e.activeShot)??e.shots[0],u=s*c.duration,m=e.items.filter(Pa),d=du(e),f=m.find(C=>C.id===n)??null,[p,x]=R.useState(()=>({target:"",recipe:"collapse"})),g=d.find(C=>C.id===n)??null,v=d.some(C=>C.id===p.target)?p.target:g?.id??d[0]?.id??"",w=()=>{if(!v)return;if(e.items.filter(S=>S.kind==="fx").length>=ln.maxItems){l?.(o("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[ln.maxItems]));return}const C=r?.objectBounds()[v]??null,M=uu(e,{target:v,recipe:p.recipe,playhead:u,bounds:C,name:`${o("Mix FX")} ${m.length+1}`});a(()=>M.stage),i(M.item.id)};return t.jsxs("div",{className:"shot-fx shot-mixfx",children:[t.jsx("p",{className:"shot-fx-hint",children:o("Khối cầu vô hình đi theo các điểm bạn đặt; nó đi qua đâu, mục tiêu vỡ ở đó. Kéo khối cầu trong khung 3D, mỗi lần thả là một key tại playhead.")}),m.length>0&&t.jsx("div",{className:"shot-list shot-fx-list",children:m.map(C=>t.jsx("div",{className:C.id===f?.id?"active":"",children:t.jsxs("button",{type:"button",onClick:()=>i(C.id),children:["💥 ",C.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",e.items.find(M=>M.id===C.fx?.target?.to)?.name??o("chưa có mục tiêu")]})]})},C.id))}),!f&&t.jsxs("fieldset",{className:"shot-mixfx-new",children:[t.jsx("legend",{children:o("Tạo Mix FX")}),d.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Mục tiêu")}),t.jsx("select",{"aria-label":o("Mục tiêu bị phá"),value:v,onChange:C=>x(M=>({...M,target:C.target.value})),children:d.map(C=>t.jsx("option",{value:C.id,children:C.name},C.id))})]}),t.jsx(mu,{value:p.recipe,onPick:C=>x(M=>({...M,recipe:C}))}),t.jsx("button",{type:"button",className:"shot-primary",onClick:w,children:o("Tạo khối cầu phá huỷ")})]}):t.jsx("p",{className:"shot-fx-empty",children:o("Thêm một model GLB, proxy hoặc hộp / tường / bục trước, rồi chọn nó làm mục tiêu.")})]}),f&&t.jsx(Ov,{item:f,stage:e,progress:s,change:a,onSelect:i,engine:r??null},f.id)]})}function mu({value:e,onPick:n}){return t.jsx("div",{className:"shot-mixfx-recipes",role:"group","aria-label":o("Công thức hiệu ứng"),children:fp.map(s=>t.jsxs("button",{type:"button","data-recipe":s,className:e===s?"active":"","aria-pressed":e===s,onClick:()=>n(s),children:[t.jsx("span",{"aria-hidden":!0,children:Fv[s]}),o(Da[s].name)]},s))})}function Ov({item:e,stage:n,progress:s,change:a,onSelect:i,engine:r}){const l=n.shots.find(k=>k.id===n.activeShot)??n.shots[0],c=e.fx,u=c.params,m=Mn(e,l),d=!!l.fxTiming?.[e.id],f=l.objectKeys?.[e.id]??[],p=du(n),x=n.items.find(k=>k.id===c.target?.to)??null,g=(k,T={})=>a(j=>({...j,items:j.items.map(L=>L.id===e.id?{...L,...T,fx:{...L.fx,...k}}:L)})),v=(k,T)=>g({params:{...u,[k]:T}}),w=k=>a(T=>({...T,shots:T.shots.map(j=>j.id===T.activeShot?{...j,fxTiming:{...j.fxTiming,[e.id]:Ar({...Mn(e,j),...k,off:!1},j.duration)}}:j)})),[C,M]=R.useState(null),S=hu(u.recipe),I=()=>{if(!x||n.items.filter(A=>A.kind==="fx").length>=ln.maxItems)return;const k=(C?.first??m.start)+.6,T=r?.objectBounds()[x.id]??null,j=n.items.filter(Pa).length,L=uu(n,{target:x.id,recipe:"collapse_building",playhead:Math.min(k,Math.max(0,l.duration-.3)),bounds:T,name:`${o("Sập toà nhà")} ${j+1}`,params:{chunks:Number(u.chunks)}}),N={...L.item,fx:{...L.item.fx,seed:c.seed}};a(()=>({...L.stage,items:L.stage.items.map(A=>A.id===N.id?N:A)})),i(N.id)};R.useEffect(()=>{const k=()=>M(r?.fx?.mixStats?.(s*l.duration).find(j=>j.id===e.id)??null);k();const T=window.setInterval(k,500);return()=>window.clearInterval(T)},[r,e.id,s,l.duration,n.revision]);const y=()=>{const k=x&&r?.objectBounds()[x.id];if(!k||l.duration<=0)return;const T=Number(u.radius)*e.scale[0]+Number(u.falloff)+.3,j=Vt((k.min[1]+k.max[1])/2),L=Vt((k.min[2]+k.max[2])/2),N=Math.min(1,m.start/l.duration),A=Math.min(1,(m.start+m.duration)/l.duration);a(O=>{const _={...O,shots:O.shots.map($=>$.id===O.activeShot?{...$,objectKeys:{...$.objectKeys,[e.id]:[]}}:$)};return bo(bo(_,e.id,N,[Vt(k.min[0]-T),j,L]),e.id,A,[Vt(k.max[0]+T),j,L])})};return t.jsxs("div",{className:"shot-fx-inspector shot-mixfx-inspector","aria-label":o("Chỉnh Mix FX"),children:[t.jsxs("h3",{children:[o("MIX FX")," ",t.jsxs("small",{className:"shot-total",children:["· ",e.name]})]}),t.jsx("input",{"aria-label":o("Tên Mix FX"),value:e.name,onChange:k=>a(T=>({...T,items:T.items.map(j=>j.id===e.id?{...j,name:k.target.value}:j)}))}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Mục tiêu")}),t.jsxs("select",{"aria-label":o("Mục tiêu bị phá"),value:x?.id??"",onChange:k=>g({target:k.target.value?{to:k.target.value,part:"center"}:void 0}),children:[!x&&t.jsx("option",{value:"",children:o("Chọn đối tượng…")}),p.map(k=>t.jsx("option",{value:k.id,children:k.name},k.id))]})]}),t.jsx(mu,{value:String(u.recipe),onPick:k=>g({params:gp(k,u)},{color:Da[k].color})}),C?.overridden&&t.jsx("p",{className:"shot-fx-hint shot-mixfx-note","data-mix":"note",children:o("Mục tiêu này đã có Mix FX “{0}” tạo trước: các Mix FX cùng mục tiêu dùng chung số mảnh và seed của nó.",[n.items.find(k=>k.id===C.lead)?.name??""])}),S?t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Sập toà nhà")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Kiểu sập")}),t.jsx("select",{"aria-label":o("Kiểu sập"),"data-mix":"mode",value:String(u.mode??"pancake"),onChange:k=>v("mode",k.target.value),children:xp.map(k=>t.jsx("option",{value:k,children:o(Pv[k])},k))})]}),Rv.filter(({key:k})=>k!=="yaw"||u.mode==="topple").map(({key:k,step:T})=>{const j=Bl.find(L=>L.key===k);return t.jsx(yo,{label:j.label??k,value:Number(u[k]??j.def),min:j.min,max:j.max,step:T,onChange:L=>v(k,k==="chunks"?Math.round(L):L)},k)})]}):t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Khối cầu & độ ảnh hưởng")}),Iv.map(({key:k,step:T})=>{const j=Bl.find(L=>L.key===k);return t.jsx(yo,{label:j.label??k,value:Number(u[k]??j.def),min:j.min,max:j.max,step:T,onChange:L=>v(k,k==="chunks"?Math.round(L):L)},k)}),t.jsxs("label",{className:"shot-field shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":o("Mất đỡ thì rơi"),"data-mix":"support",checked:u.support!=="off",onChange:k=>v("support",k.target.checked?"on":"off")}),t.jsx("span",{children:o("Mất đỡ thì rơi")})]}),t.jsxs("button",{type:"button","data-mix":"collapse-after",disabled:!x,onClick:I,children:["🏢 ",o("Thêm sập sau nổ")]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Seed & màu")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(gn,{"aria-label":o("Seed"),value:c.seed,min:0,max:2147483647,step:1,onCommit:k=>g({seed:Math.round(k)})}),t.jsxs("button",{type:"button","aria-label":o("Đổi seed ngẫu nhiên"),title:o("Đổi seed ngẫu nhiên"),onClick:()=>g({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ce.reset,{}),o("Xáo trộn")]})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Màu bụi / lửa")}),t.jsx("input",{type:"color","aria-label":o("Màu bụi / lửa"),value:e.color,onChange:k=>a(T=>({...T,items:T.items.map(j=>j.id===e.id?{...j,color:k.target.value}:j)}))})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Thời gian phá trong shot")}),d?t.jsxs(t.Fragment,{children:[t.jsx(yo,{label:"Bắt đầu (s)",value:m.start,min:0,max:Math.max(.1,l.duration),step:.1,onChange:k=>w({start:k})}),t.jsx(yo,{label:"Kéo dài (s)",value:m.duration,min:.2,max:ln.maxDuration,step:.1,onChange:k=>w({duration:k})})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>w({start:Vt(s*l.duration),duration:Vt(Math.max(.2,l.duration*(1-s)))}),children:o("Phát trong shot này")})]}),!S&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:o("Đường đi của khối cầu")}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsxs("button",{type:"button","data-mix":"add-key",onClick:()=>a(k=>bo(k,e.id,s)),children:["+◆ ",o("Thêm điểm tại playhead")]}),t.jsx("button",{type:"button","data-mix":"sweep",disabled:!x,onClick:y,children:o("Quét ngang qua mục tiêu")})]}),f.map((k,T)=>t.jsxs("div",{className:"shot-fx-point shot-mixfx-key","data-key":k.id,children:[t.jsxs("b",{children:[(k.time*l.duration).toFixed(1),"s"]}),[0,1,2].map(j=>t.jsx(gn,{"aria-label":o("Điểm {0} {1}",[T+1,"XYZ"[j]]),precision:2,step:.1,min:-1e3,max:1e3,value:k.position[j],onCommit:L=>{const N=[...k.position];N[j]=L,a(A=>bo(A,e.id,k.time,N,k.id))}},j)),t.jsx("button",{type:"button","aria-label":o("Xóa điểm {0}",[T+1]),onClick:()=>a(j=>({...j,shots:j.shots.map(L=>L.id===j.activeShot?{...L,objectKeys:{...L.objectKeys,[e.id]:(L.objectKeys?.[e.id]??[]).filter(N=>N.id!==k.id)}}:L)})),children:t.jsx(Ce.close,{})})]},k.id)),!f.length&&t.jsx("p",{className:"shot-fx-hint",children:o("Chưa có điểm: khối cầu đứng yên. Dời playhead, kéo khối cầu rồi bấm “Thêm điểm tại playhead”.")})]}),C&&t.jsxs("small",{className:"shot-fx-budget","data-mix-stats":`${C.broken}/${C.chunks}`,children:[o("{0} mảnh · {1} mảnh đã vỡ tại playhead · {2} sẽ vỡ",[C.chunks,C.broken,C.hit]),C.falling?o(" · {0} mảnh mất đỡ rơi xuống",[C.falling]):""]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",className:"shot-delete-item",onClick:()=>{a(k=>({...k,items:k.items.filter(T=>T.id!==e.id),shots:k.shots.map(T=>({...T,...T.objectKeys?.[e.id]?{objectKeys:Object.fromEntries(Object.entries(T.objectKeys).filter(([j])=>j!==e.id))}:{},...T.fxTiming?.[e.id]?{fxTiming:Object.fromEntries(Object.entries(T.fxTiming).filter(([j])=>j!==e.id))}:{}}))})),i(null)},children:o("Xóa {0}",[e.name])}),t.jsx("button",{type:"button",onClick:()=>i(null),children:o("+ Mix FX khác")})]})]})}let Nn=null,Ds,No,br,ph=null;const fh=new Map,zi=new Map;let gh=Promise.resolve(),xh=0;const bh=112;function Dv(){const e=document.createElement("canvas");e.width=e.height=64;const n=e.getContext("2d");for(let a=0;a<8;a++)for(let i=0;i<8;i++)n.fillStyle=(i+a)%2?"#3a4148":"#262b30",n.fillRect(i*8,a*8,8,8);const s=new Pr(e);return s.colorSpace=Uo,s.wrapS=s.wrapT=rd,s.repeat.set(3,3),s.magFilter=G0,s}function zv(){if(Nn)return Nn;Nn=new Ir({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),Nn.outputColorSpace=Uo,Nn.toneMapping=ad,Nn.toneMappingExposure=1.1,Nn.setClearColor(0,0),Nn.setSize(bh,bh,!1),Ds=new Rr;const e=new od(Nn);ph=e.fromScene(new md,.04).texture,e.dispose(),Ds.environment=ph;const n=new Go("#fff4e4",2.2);n.position.set(-2,3,3),Ds.add(n);const s=new ut(new Xo(4,4),new os({map:Dv()}));return s.position.set(0,0,-1.4),Ds.add(s),br=new ut(new Rn(.5,48,32)),Ds.add(br),No=new Fr(30,1,.1,20),No.position.set(0,.18,2.15),No.lookAt(0,0,0),Nn}function _v(e){const n=zv(),s=yp({preset:e},Ha,{studio:!0});if(!s)throw new Error(`unknown material ${e}`);br.material=s,n.render(Ds,No);const a=n.domElement.toDataURL("image/png");return s.dispose(),a}function Bv(e){const n=fh.get(e);if(n)return Promise.resolve(n);const s=zi.get(e);if(s)return s;if(!Oa(e))return Promise.reject(new Error(`unknown material ${e}`));const a=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof a=="number"&&xh>=a)return Promise.reject(new Error("thumbnail limit"));xh++;const i=gh.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const c=_v(e);fh.set(e,c),r(c)}catch(c){l(c)}},20))).finally(()=>zi.delete(e));return gh=i.catch(()=>{}),zi.set(e,i),i}const Ao="application/x-clipoox-material",Ca=e=>!!e&&e.kind!=="fx"&&e.kind!=="splat",va=e=>e===qs?o("Cả đối tượng"):/^part-\d+/.test(e)?o("Phần {0}",[e.slice(5)]):e;function Kv({preset:e,alt:n}){const[s,a]=R.useState(null),[i,r]=R.useState(!1),l=R.useRef(null);return R.useEffect(()=>{if(i||!l.current||typeof IntersectionObserver>"u"){i||r(!0);return}const c=new IntersectionObserver(u=>{u.some(m=>m.isIntersecting)&&(r(!0),c.disconnect())},{rootMargin:"120px"});return c.observe(l.current),()=>c.disconnect()},[i]),R.useEffect(()=>{if(!i)return;let c=!0;return Bv(e.id).then(u=>{c&&a(u)}).catch(()=>{}),()=>{c=!1}},[i,e.id]),s?t.jsx("img",{className:"shot-mat-swatch",src:s,alt:n,draggable:!1}):t.jsx("span",{ref:l,className:"shot-mat-swatch loading",role:"img","aria-label":n,style:{background:`radial-gradient(circle at 35% 30%, #ffffff55, ${e.colors[0]} 45%, #0008 100%)`}})}function Jn({label:e,value:n,range:s,step:a,onInput:i,format:r}){return t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:o(e)}),t.jsx("input",{type:"range","aria-label":o(e),min:s[0],max:s[1],step:a,value:n,onChange:l=>i(Number(l.target.value))}),t.jsx("output",{children:r?r(n):n.toFixed(2)})]})}function Hv({stage:e,selected:n,change:s,engine:a,setError:i,scope:r,setScope:l}){const c=ht(),[u,m]=R.useState(""),[d,f]=R.useState(""),[p,x]=R.useState(!1),[g,v]=R.useState([]),w=e.items.find(U=>U.id===n)??null,C=Ca(w),M=R.useMemo(()=>vp(u,u.trim()?"":d),[u,d]);R.useEffect(()=>{if(!w||!C){v([]);return}const U=()=>v(a?.materialSlots(w.id)??[]);U();const pe=setTimeout(U,400),me=setTimeout(U,1600);return()=>{clearTimeout(pe),clearTimeout(me)}},[a,w?.id,w?.model?.gcsUri,w?.look,w?.figure,e.revision,C]),R.useEffect(()=>()=>a?.setPartPicker(null),[a]),R.useEffect(()=>{x(!1),a?.setPartPicker(null)},[n,a]);const S=g.length>1,I=r.mode==="part"&&S&&r.slot&&g.some(U=>U.slot===r.slot)?r.slot:qs,y=w?.materials?.[I]??null,k=Kl(y),[T,j]=R.useState([]),L=e.items.filter(U=>U.id!==w?.id&&Ca(U)&&!U.hidden),N=T.filter(U=>L.some(pe=>pe.id===U&&!pe.locked)),A=(U,pe=w?.id,me=I,X=!0)=>{const re=e.items.find(Ee=>Ee.id===pe);if(!re||!Ca(re)){i(o("Chọn một đối tượng (hộp, model, nhân vật…) để áp vật liệu."));return}if(re.locked){i(o("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[re.name]));return}i("");const ue=X?N.filter(Ee=>Ee!==re.id):[];s(Ee=>ue.reduce((ye,ne)=>zs(ye,ne,qs,U),zs(Ee,re.id,me,U)))},O=(U,pe=w?.id,me=I)=>A({preset:U.id},pe,me),_=()=>A({mode:"tint",params:{color:"#ffffff"}}),[$,P]=R.useState(null),W=R.useRef(null),z=R.useRef(void 0),Q=()=>{clearTimeout(z.current);const U=W.current;W.current=null,U&&(P(null),s(pe=>zs(pe,U.itemId,U.slot,U.override)))};R.useEffect(()=>()=>Q(),[]);const J=`${w?.id}|${I}|${JSON.stringify(y)}`,V=$?.key===J?$.params:null,B=U=>{if(!w||!y)return;const pe={...y.params||{},...V||{},...U},me=oa(y)?{mode:"tint",params:{color:pe.color??"#ffffff",...pe.roughness!==void 0?{roughness:pe.roughness}:{},...pe.metalness!==void 0?{metalness:pe.metalness}:{}}}:{preset:y.preset,params:pe};P({key:J,params:pe}),a?.previewMaterials(w.id,jp(w.materials,I,me)),W.current={itemId:w.id,slot:I,override:me},clearTimeout(z.current),z.current=setTimeout(Q,450)},q=y&&!oa(y)?V?Kl({preset:y.preset,params:V}):k:null,D=y&&oa(y)?{...y.params,...V||{}}:null,ee=U=>{w&&(W.current=null,clearTimeout(z.current),s(pe=>zs(pe,w.id,U,null)))},Z=()=>{w&&(W.current=null,clearTimeout(z.current),s(U=>({...U,items:U.items.map(pe=>{if(pe.id!==w.id)return pe;const{materials:me,...X}=pe;return X})})))},xe=()=>{if(!(!a||!w)){if(p){a.setPartPicker(null),x(!1);return}x(!0),a.setPartPicker((U,pe)=>{x(!1);const me=e.items.find(X=>X.id===U);if(U!==w.id){me&&Ca(me)&&!me.locked&&i(o("Phần đó thuộc {0} — chọn đối tượng ấy trước.",[me.name]));return}i(""),l({mode:"part",slot:pe})})}},be=Object.entries(w?.materials||{});return t.jsxs("div",{className:"shot-mat",children:[t.jsx("div",{className:"shot-mat-target",children:w?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:w.name}),!C&&t.jsx("small",{children:o("Đối tượng này không đổi được vật liệu.")}),w.locked&&t.jsx("small",{children:o("Đang khoá")})]}):t.jsx("small",{children:o("Chọn một đối tượng trong cảnh, rồi bấm một vật liệu. Hoặc kéo vật liệu thả lên đối tượng trong khung 3D.")})}),w&&C&&S&&t.jsxs("div",{className:"shot-mat-scope",children:[t.jsxs("div",{className:"shot-seg",role:"radiogroup","aria-label":o("Áp vật liệu cho"),children:[t.jsx("button",{type:"button",role:"radio","aria-checked":r.mode==="all",className:r.mode==="all"?"active":"",onClick:()=>l({mode:"all",slot:r.slot}),children:o("Cả đối tượng")}),t.jsx("button",{type:"button",role:"radio","aria-checked":r.mode==="part",className:r.mode==="part"?"active":"",onClick:()=>l({mode:"part",slot:r.slot&&g.some(U=>U.slot===r.slot)?r.slot:g[0].slot}),children:o("Từng phần")})]}),r.mode==="part"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-mat-parts",role:"listbox","aria-label":o("Các phần của model"),children:g.map(({slot:U})=>{const pe=w.materials?.[U],me=pe?Oa(pe.preset):null;return t.jsxs("button",{type:"button",role:"option","data-slot":U,"aria-selected":I===U,className:I===U?"active":"",onClick:()=>l({mode:"part",slot:U}),children:[va(U),me?t.jsxs("small",{children:[" · ",wa(me,c)]}):oa(pe)?t.jsxs("small",{children:[" · ",o("Giữ texture")]}):null]},U)})}),t.jsxs("button",{type:"button",className:`shot-mat-pick${p?" active":""}`,"aria-pressed":p,onClick:xe,children:[t.jsx(Ce.focus,{})," ",p?o("Bấm vào một phần của model… (bấm lại để huỷ)"):o("Chọn phần trên khung 3D")]})]})]}),w&&C&&!w.locked&&t.jsx("div",{className:"shot-mat-tintbar",children:t.jsxs("button",{type:"button","data-mat":"tint",className:D?"active":"","aria-pressed":!!D,onClick:()=>D?ee(I):_(),title:o("Giữ texture gốc của phần này, chỉ đổi màu (và độ nhám / kim loại nếu muốn)"),children:["🎨 ",o("Giữ texture gốc, chỉ đổi màu")]})}),w&&C&&D&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":o("Chỉnh vật liệu"),"data-mat":"tint-panel",children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:o("Giữ texture gốc, chỉ đổi màu")}),t.jsxs("small",{children:[" · ",va(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:o("Đặt lại vật liệu gốc"),children:[t.jsx(Ce.reset,{})," ",o("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:o("Màu nhân")}),t.jsx("input",{type:"color","aria-label":o("Màu nhân"),value:D.color,onChange:U=>B({color:U.target.value})}),t.jsx("output",{children:D.color})]}),t.jsx(Jn,{label:"Độ nhám",value:D.roughness??.5,range:bs.roughness,step:.01,onInput:U=>B({roughness:U}),format:U=>D.roughness===void 0?o("gốc"):U.toFixed(2)}),t.jsx(Jn,{label:"Độ kim loại",value:D.metalness??0,range:bs.metalness,step:.01,onInput:U=>B({metalness:U}),format:U=>D.metalness===void 0?o("gốc"):U.toFixed(2)})]}),w&&C&&L.length>0&&t.jsxs("details",{className:"shot-mat-also",open:N.length>0,children:[t.jsx("summary",{children:o("Áp cho cả: {0} đối tượng khác",[N.length])}),t.jsx("div",{className:"shot-mat-also-list",role:"group","aria-label":o("Áp cho nhiều đối tượng"),children:L.map(U=>t.jsxs("label",{className:U.locked?"is-locked":"",children:[t.jsx("input",{type:"checkbox","data-also":U.id,disabled:U.locked,checked:N.includes(U.id),onChange:pe=>j(me=>pe.target.checked?[...me.filter(X=>X!==U.id),U.id]:me.filter(X=>X!==U.id))}),U.name]},U.id))}),t.jsx("small",{className:"shot-fx-hint",children:o("Bấm một vật liệu: {0} và các đối tượng đã đánh dấu đổi cùng lúc (một bước hoàn tác).",[w.name])})]}),w&&C&&y&&q&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":o("Chỉnh vật liệu"),children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:wa(q.preset,c)}),t.jsxs("small",{children:[" · ",va(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:o("Đặt lại vật liệu gốc"),children:[t.jsx(Ce.reset,{})," ",o("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:o("Màu")}),t.jsx("input",{type:"color","aria-label":o("Màu vật liệu"),value:q.color,onChange:U=>B({color:U.target.value})}),t.jsx("output",{children:q.color})]}),t.jsx(Jn,{label:"Độ nhám",value:q.roughness,range:bs.roughness,step:.01,onInput:U=>B({roughness:U})}),t.jsx(Jn,{label:"Độ kim loại",value:q.metalness,range:bs.metalness,step:.01,onInput:U=>B({metalness:U})}),!q.preset.mapless&&t.jsxs(t.Fragment,{children:[t.jsx(Jn,{label:"Cỡ vân",value:q.scale,range:[.1,5],step:.05,onInput:U=>B({scale:U}),format:U=>`×${U.toFixed(2)}`}),t.jsx(Jn,{label:"Xoay vân",value:q.rotation,range:bs.rotation,step:1,onInput:U=>B({rotation:U}),format:U=>`${Math.round(U)}°`})]}),t.jsx(Jn,{label:"Phát sáng",value:q.emissive,range:bs.emissive,step:.1,onInput:U=>B({emissive:U}),format:U=>U.toFixed(1)}),t.jsx(Jn,{label:q.preset.transmission?"Độ đục (kính)":"Độ đặc",value:q.opacity,range:bs.opacity,step:.01,onInput:U=>B({opacity:U})})]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":o("Tìm vật liệu"),placeholder:o("Tìm vật liệu… (vd: go, kinh, thep)"),value:u,onChange:U=>m(U.target.value)})}),t.jsxs("div",{className:"shot-fx-cats shot-mat-cats",role:"tablist","aria-label":o("Nhóm vật liệu"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":!d&&!u.trim(),className:!d&&!u.trim()?"active":"",onClick:()=>{f(""),m("")},children:o("Tất cả")}),_h.map(U=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===U.id&&!u.trim(),className:d===U.id&&!u.trim()?"active":"",onClick:()=>{f(U.id),m("")},children:c==="en"?U.en:U.vi},U.id))]}),t.jsxs("div",{className:"shot-mat-grid",children:[M.map(U=>{const pe=wa(U,c),me=y?.preset===U.id;return t.jsxs("button",{type:"button",className:`shot-mat-card${me?" active":""}`,"data-material":U.id,draggable:!0,"aria-pressed":me,title:w&&C?o("Áp {0} cho {1}",[pe,w.name]):pe,onDragStart:X=>{X.dataTransfer.setData(Ao,U.id),X.dataTransfer.effectAllowed="copy"},onClick:()=>O(U),children:[t.jsx(Kv,{preset:U,alt:pe}),t.jsx("span",{children:pe})]},U.id)}),!M.length&&t.jsx("p",{className:"shot-fx-empty",children:o("Không có vật liệu nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:o("Bấm để áp cho đối tượng đang chọn, hoặc kéo thả lên một đối tượng trong khung 3D. Ở chế độ Từng phần, thả lên phần nào thì áp cho phần đó.")}),w&&be.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("h3",{children:[o("Vật liệu đang dùng")," ",t.jsxs("small",{className:"shot-total",children:["· ",be.length]})]}),t.jsx("div",{className:"shot-list shot-mat-list",children:be.map(([U,pe])=>{const me=Oa(pe.preset);return t.jsxs("div",{className:U===I?"active":"",children:[t.jsxs("button",{type:"button",onClick:()=>l(U===qs?{mode:"all",slot:r.slot}:{mode:"part",slot:U}),children:[va(U),t.jsxs("small",{className:"shot-list-meta",children:[" · ",me?wa(me,c):oa(pe)?o("Giữ texture · {0}",[pe.params.color]):pe.preset]})]}),t.jsx("button",{type:"button",className:"shot-delete-item","aria-label":o("Đặt lại {0}",[va(U)]),title:o("Đặt lại vật liệu gốc"),onClick:()=>ee(U),children:t.jsx(Ce.reset,{})})]},U)})}),t.jsxs("button",{type:"button",className:"shot-mat-reset-all",onClick:Z,children:[t.jsx(Ce.reset,{})," ",o("Đặt lại tất cả vật liệu gốc")]})]})]})}function Gr({pose:e}){ht();const n=(c,u,m,d,f,p,x,g=0)=>{const v=(m+x*g*.34)*Math.PI/180,w=(m-d+x*g*.22)*Math.PI/180,C=[c+Math.sin(v)*f,u+Math.cos(v)*f];return{joint:C,end:[C[0]+Math.sin(w)*p,C[1]+Math.cos(w)*p]}},s=n(35,38,e.shoulderL,e.elbowL,21,19,-1,e.shoulderOutL),a=n(55,38,e.shoulderR,e.elbowR,21,19,1,e.shoulderOutR),i=n(40,66,e.hipL,e.kneeL,25,23,-1,e.hipOutL),r=n(50,66,e.hipR,e.kneeR,25,23,1,e.hipOutR),l=(c,u,m,d)=>t.jsxs("g",{children:[t.jsx("path",{d:`M${c} L${u} L${m}`}),t.jsx("circle",{cx:u[0],cy:u[1],r:"2.8"}),t.jsx("circle",{cx:m[0],cy:m[1],r:"3.2"})]},d);return t.jsx("svg",{className:"shot-rig-thumb",viewBox:"0 0 90 115","aria-hidden":"true",children:t.jsxs("g",{transform:`rotate(${e.lean*.25} 45 62)`,children:[l([35,38],s.joint,s.end,"la"),l([55,38],a.joint,a.end,"ra"),t.jsx("path",{className:"shot-rig-torso",d:"M34 35 Q45 29 56 35 L53 64 Q45 70 37 64Z"}),t.jsx("ellipse",{cx:"45",cy:"20",rx:"9",ry:"11",transform:`rotate(${e.head} 45 20)`}),l([40,66],i.joint,i.end,"ll"),l([50,66],r.joint,r.end,"rl")]})})}const Wv=["person","prop","box","sphere","cylinder","model"],qv=[["snap","Nhịp dứt khoát (giữ dáng)"],["anticipation","Lấy đà & dư chấn"],["exaggerate","Cường điệu tư thế"],["squash","Co giãn (squash & stretch)"],["smear","Vệt nhoè khi nhanh"]];function Gv({item:e,shot:n,playhead:s,patchItem:a,change:i}){ht();const r=kp(e.toon),l=!!r?.on,c=r??{...wp,on:!1},u=p=>a(e.id,{toon:{...c,...p}}),m=e.kind==="prop"&&e.prop?.kind==="ball",d=e.ball?.restitution??Mp.restitution,f=()=>i(p=>({...p,shots:p.shots.map(x=>x.id===n.id?{...x,ball:{...x.ball,[e.id]:[...(x.ball?.[e.id]||[]).filter(g=>g.t<s*x.duration-1e-6),{t:Math.round(s*x.duration*1e3)/1e3,kind:"launch",from:[...e.position],vel:[0,0,0]}]}}:x)}));return t.jsxs("div",{className:"shot-toon","data-testid":"shot-toon",children:[t.jsx("h3",{children:o("HOẠT HÌNH / CARTOON")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":o("Phong cách hoạt hình"),checked:l,onChange:p=>u({on:p.target.checked})}),t.jsx("span",{children:o("Phong cách hoạt hình")})]}),t.jsxs("label",{className:`shot-joint${l?"":" is-off"}`,children:[t.jsx("span",{className:"shot-toon-name",children:o("Mức cường điệu")}),t.jsxs("span",{children:[Math.round(c.amount*100),"%"]}),t.jsx("input",{"aria-label":o("Mức cường điệu"),type:"range",min:0,max:1,step:.05,value:c.amount,disabled:!l,onChange:p=>u({amount:+p.target.value})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":o("Hình nhảy cách (on twos)"),checked:c.twos,disabled:!l,onChange:p=>u({twos:p.target.checked})}),t.jsx("span",{children:o("Hình nhảy cách (on twos)")})]}),t.jsxs("details",{className:"shot-toon-more",children:[t.jsx("summary",{children:o("Chi tiết nguyên lý")}),t.jsx("div",{className:"shot-toon-flags",children:qv.map(([p,x])=>t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":o(x),checked:c[p],disabled:!l,onChange:g=>u({[p]:g.target.checked})}),t.jsx("span",{children:o(x)})]},p))})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[t.jsx("span",{className:"shot-toon-name",children:o("Độ nảy")}),t.jsxs("span",{children:[Math.round(d*100),"%"]}),t.jsx("input",{"aria-label":o("Độ nảy"),type:"range",min:.3,max:.95,step:.01,value:d,onChange:p=>a(e.id,{ball:{...e.ball,restitution:+p.target.value}})})]}),t.jsx("button",{type:"button",onClick:f,children:o("Thả bóng nảy từ đây")})]}),t.jsx("small",{className:"shot-hint",children:o("Lấy đà trước cú bật, dư chấn khi dừng, dáng giữ dứt khoát, co giãn khi bật / tiếp đất. Tính theo thời gian nên xem trước và video xuất giống hệt; key gốc không bị đổi.")})]})}const Uv=[{id:"moment",label:"Quanh khung này",hint:"Hoà vào trước và sau khung hình hiện tại"},{id:"span",label:"Cả khối động tác",hint:"Cả động tác đang phát tại playhead"},{id:"after",label:"Từ đây đến hết",hint:"Từ playhead đến cuối shot"}],es=e=>(Number(e)||0).toFixed(1),yh=()=>crypto.randomUUID(),Xv=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null;function Vv({shot:e,item:n,playhead:s,change:a,engine:i,seek:r}){const l=ht(),c=l==="en",u=e.motionEdits?.[n.id]||[],m=Xv(e.clipSpans?.[n.id],s),[d,f]=R.useState("moment"),[p,x]=R.useState(ks.default),[g,v]=R.useState(!1),[w,C]=R.useState("handR"),[M,S]=R.useState(null),I=u.find(A=>A.id===M)??null,y=(A=d)=>A==="span"&&m?{scope:"span",start:m.start,end:m.end,fade:p}:A==="after"?{scope:"after",start:s,end:s,fade:p}:{scope:A==="span"?"moment":A,start:s,end:s,fade:p},k=A=>a(O=>({...O,shots:O.shots.map(_=>_.id===e.id?{..._,motionEdits:{..._.motionEdits,[n.id]:Zh(_.motionEdits?.[n.id],A,_.duration)}}:_)})),T=A=>{a(O=>({...O,shots:O.shots.map(_=>_.id===e.id?{..._,motionEdits:{..._.motionEdits,[n.id]:(_.motionEdits?.[n.id]||[]).filter($=>$.id!==A)}}:_)})),M===A&&S(null)},j=(A,O)=>{if(I){k({...I,...A});return}const _=yh();S(_),k({id:_,...y(),label:O,...A})},L=R.useRef({reach:y,write:k,setSelId:S,setPart:C});L.current={reach:y,write:k,setSelId:S,setPart:C},R.useEffect(()=>{if(i){if(!g){i.editTool&&!i.editTool.direct&&i.setEditTool(null);return}i.setEditTool({personId:n.id,part:w,draft:(A,O)=>({id:"__drag",...L.current.reach(O==="hips"&&d==="moment"?"after":d),...A}),commit:(A,O)=>{const _=yh(),$=L.current;$.setSelId(_),$.write({id:_,...$.reach(O==="hips"&&d==="moment"?"after":d),label:o(Fo[O]),...A})},select:A=>L.current.setPart(A)})}},[i,g,n.id,w,d,p]),R.useEffect(()=>()=>{i&&!i.editTool?.direct&&i.setEditTool(null)},[i]);const N=A=>I?.stance?.[A]??0;return t.jsxs("section",{className:"shot-motion-edit","data-motion-edit":!0,children:[t.jsxs("h3",{children:[o("SỬA CHUYỂN ĐỘNG"),t.jsx("small",{children:o("{0} chỉnh",[u.length])})]}),t.jsxs("p",{className:"shot-hint",children:[m?o("Đang ở khối “{0}” {1}–{2}s",[m.label,es(m.start),es(m.end)]):o("Playhead {0}s",[es(s)])," · ",o("Chuyển động gốc giữ nguyên, tắt chỉnh là về bản gốc.")]}),t.jsx("div",{className:"shot-seg",role:"radiogroup","aria-label":o("Phạm vi chỉnh"),children:Uv.map(A=>t.jsx("button",{role:"radio","aria-checked":d===A.id,className:d===A.id?"active":"",disabled:A.id==="span"&&!m,title:o(A.hint),onClick:()=>f(A.id),children:o(A.label)},A.id))}),t.jsxs("label",{className:"shot-joint",children:[o("Độ mềm (hoà vào/ra)")," ",t.jsxs("span",{children:[p.toFixed(2),"s"]}),t.jsx("input",{"aria-label":o("Độ mềm (hoà vào/ra)"),type:"range",min:ks.min,max:1.2,step:.05,value:p,onChange:A=>x(+A.target.value)})]}),t.jsx("h4",{children:o("Kéo trên nhân vật")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:g,onChange:A=>v(A.target.checked)}),o("Hiện tay cầm để kéo tay, chân, hông")]}),g&&t.jsx("div",{className:"shot-edit-parts",children:Sp.map(A=>t.jsx("button",{"data-edit-part":A,className:w===A?"active":"",onClick:()=>C(A),children:o(Fo[A])},A))}),g&&t.jsx("small",{className:"shot-hint",children:w==="hips"?o("Kéo ngang để dời vị trí, kéo xuống để hạ trọng tâm (chân vẫn bám đất)."):o("Kéo chấm sáng: khớp vai, khuỷu, hông, gối tự xoay theo (IK).")}),t.jsx("h4",{children:o("Dáng đứng mẫu")}),t.jsx("div",{className:"shot-stance-grid",children:Cp.map(A=>t.jsx("button",{"data-stance":A.id,className:I?.preset?.id===A.id?"active":"",onClick:()=>j({preset:{id:A.id,amount:I?.preset?.amount??.7}},c?A.nameEn:A.name),children:c?A.nameEn:o(A.name)},A.id))}),I?.preset&&t.jsxs("label",{className:"shot-joint",children:[o("Độ mạnh dáng mẫu")," ",t.jsxs("span",{children:[Math.round(I.preset.amount*100),"%"]}),t.jsx("input",{"aria-label":o("Độ mạnh dáng mẫu"),type:"range",min:0,max:1,step:.05,value:I.preset.amount,onChange:A=>j({preset:{...I.preset,amount:+A.target.value}},"")})]}),t.jsx("h4",{children:o("Chỉnh nhanh")}),Np.map(A=>t.jsxs("label",{className:"shot-joint",children:[c?A.nameEn:o(A.name)," ",t.jsx("span",{children:A.max===1?`${Math.round(N(A.id)*100)}%`:`${N(A.id)}°`}),t.jsx("input",{"aria-label":c?A.nameEn:o(A.name),"data-stance-slider":A.id,type:"range",min:A.min,max:A.max,step:A.step,value:N(A.id),onChange:O=>j({stance:{...I?.stance||{},[A.id]:+O.target.value}},c?A.nameEn:A.name)})]},A.id)),t.jsxs("div",{className:"shot-edit-move",children:[[["Dời ngang (m)",0],["Dời tới / lui (m)",2]].map(([A,O])=>t.jsxs("label",{className:"shot-joint",children:[o(A)," ",t.jsx("span",{children:(I?.move?.[O]??0).toFixed(2)}),t.jsx("input",{"aria-label":o(A),type:"range",min:-2,max:2,step:.02,value:I?.move?.[O]??0,onChange:_=>{const $=[...I?.move??[0,0,0]];$[O]=+_.target.value,j({move:$},o("Vị trí"))}})]},A)),t.jsxs("label",{className:"shot-joint",children:[o("Xoay hướng")," ",t.jsxs("span",{children:[I?.turn??0,"°"]}),t.jsx("input",{"aria-label":o("Xoay hướng"),type:"range",min:-180,max:180,step:1,value:I?.turn??0,onChange:A=>j({turn:+A.target.value},o("Hướng"))})]})]}),t.jsx("h4",{children:o("Các chỉnh đã có")}),!u.length&&t.jsx("small",{className:"shot-hint",children:o("Chưa có chỉnh nào. Kéo tay cầm hoặc chọn dáng mẫu / thanh trượt để bắt đầu.")}),t.jsx("ul",{className:"shot-edit-list",children:u.map(A=>{const O=Ap(A),_=O?0:Tp(A,s);return t.jsxs("li",{className:`${A.id===M?"active":""} ${A.off?"off":""} ${O?"broken":""}`,children:[t.jsxs("button",{className:"shot-edit-pick",onClick:()=>{S(A.id===M?null:A.id),r(Number(A.start)||0)},title:O?o("Chỉnh này bị lỗi dữ liệu nên đã được bỏ qua — xoá nó và chỉnh lại"):o("Chọn chỉnh này và tua tới"),children:[t.jsxs("b",{children:[O?"⚠ ":"",A.label||o("Chỉnh")]}),t.jsx("small",{children:A.scope==="span"?`${es(A.start)}–${es(A.end)}s`:A.scope==="after"?o("từ {0}s",[es(A.start)]):`${es(A.start)}s ±${(Number(A.fade)||0).toFixed(1)}`}),t.jsx("i",{className:"shot-edit-weight",style:{width:`${Math.round(_*100)}%`},"aria-hidden":!0})]}),t.jsx("button",{title:A.off?o("Bật"):o("Tắt (xem bản gốc)"),"aria-pressed":!A.off,onClick:()=>k({...A,off:!A.off}),children:A.off?"○":"●"}),t.jsx("button",{title:o("Xoá chỉnh"),onClick:()=>T(A.id),children:"✕"})]},A.id)})}),I&&t.jsx("button",{className:"shot-edit-new",onClick:()=>S(null),children:o("+ Chỉnh mới tại {0}s",[es(s)])})]})}const vh=[{id:"moment",label:"Quanh khung này",hint:"Hoà vào trước và sau khung hình hiện tại"},{id:"span",label:"Cả khối động tác",hint:"Cả động tác đang phát tại playhead"},{id:"after",label:"Từ đây đến hết",hint:"Từ playhead đến cuối shot"},{id:"range",label:"Vùng key",hint:"Một lần chỉnh áp cho mọi key trong vùng đã chọn"},{id:"key",label:"Key tại khung này",hint:"Mỗi lần kéo sửa key tại playhead (tạo key nếu chưa có); giữa các key chuyển động tự nội suy (I: đặt key)"}],Yv=[{id:"free",icon:"✋",label:"✋ Kéo tự do",hint:"Kéo tay cầm theo mặt màn hình (phím F)"},{id:"move",icon:"✥",label:"✥ Di chuyển",hint:"Bấm một tay cầm rồi kéo mũi tên: chỉ đi theo một hướng (phím G)"},{id:"rotate",icon:"⟳",label:"⟳ Xoay",hint:"Bấm một tay cầm rồi kéo vòng xoay: khuỷu tay xoay cả cánh tay, đầu gối xoay cả chân (phím R)"}],Qv=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null,Zv=(e,n)=>!!(e.objectKeys?.[n]?.length||e.clipSpans?.[n]?.length);function Jv({engine:e,stage:n,shot:s,item:a,playhead:i,change:r,onDone:l}){ht();const c=Qv(s.clipSpans?.[a.id],i),[u,m]=R.useState(()=>Zv(s,a.id)?"moment":"after"),[d,f]=R.useState("free"),[p,x]=R.useState(()=>Math.max(0,+(i-1).toFixed(2))),[g,v]=R.useState(()=>Math.min(s.duration,+(i+1).toFixed(2))),w={start:Math.max(0,Math.min(p,g)),end:Math.min(s.duration,Math.max(p,g))},[C,M]=R.useState(!1),[S,I]=R.useState(0),[y,k]=R.useState([]),[T,j]=R.useState(null),[L,N]=R.useState(null),[A,O]=R.useState(!0),[_,$]=R.useState(!0),P=H=>H==="key"?{scope:"moment",start:i,end:i,fade:ks.default}:H==="range"&&w.end-w.start>.05?{scope:"span",start:w.start,end:w.end,fade:ks.default}:H==="range"?{scope:"moment",start:i,end:i,fade:ks.default}:H==="span"&&c?{scope:"span",start:c.start,end:c.end,fade:ks.default}:{scope:H==="span"?"moment":H,start:i,end:i,fade:ks.default},W=H=>r(se=>({...se,shots:se.shots.map(he=>he.id===s.id?{...he,motionEdits:{...he.motionEdits,[a.id]:Zh(he.motionEdits?.[a.id],H,he.duration)}}:he)})),z=i/Math.max(1e-6,s.duration),Q=(H,se)=>{const he=s.objectKeys?.[a.id];r(ce=>({...ce,shots:ce.shots.map(Pe=>Pe.id===s.id?Rp(Pe,ce.items.find(Be=>Be.id===a.id)??a,z,H??{},se):Pe)})),k(ce=>[...ce,{kind:"key",prev:he}])},J=(H,se,he=u)=>{if(he==="key"&&!H.stance&&!H.track&&!H.turn&&!H.preset){Q(H.pose,H.move);return}const ce=crypto.randomUUID();W({id:ce,...P(he),label:se,...H}),k(Pe=>[...Pe,{kind:"edit",id:ce}])},V=()=>{const H=y.at(-1);H&&(H.kind==="key"?r(se=>({...se,shots:se.shots.map(he=>he.id===s.id?{...he,objectKeys:{...he.objectKeys,[a.id]:H.prev??[]}}:he)})):r(se=>({...se,shots:se.shots.map(he=>he.id===s.id?{...he,motionEdits:{...he.motionEdits,[a.id]:(he.motionEdits?.[a.id]||[]).filter(ce=>ce.id!==H.id)}}:he)})),k(se=>se.slice(0,-1)))},B=Lp(s,a.id,z),[q,D]=R.useState(.5),ee=()=>{const H=s.objectKeys?.[a.id],se=Hl(s,n.items.find(he=>he.id===a.id)??a,z,q);se&&(r(he=>({...he,shots:he.shots.map(ce=>ce.id===s.id?se:ce)})),k(he=>[...he,{kind:"key",prev:H}]))},Z=!!Hl(s,a,z,.5),[xe,be]=R.useState(0),U=H=>{if(!e||!T||!T.startsWith("foot")||!H)return;const se=e.rollFootAt(i,a.id,T,H,he=>({id:"__drag",...P(u),...he}));se&&J(se.fields,`${o("Cuộn bàn chân")} ${H>0?"+":""}${H}°`),be(0)},pe=H=>H==="hips"&&u==="moment"?"after":u,me=R.useRef({reach:P,add:J,scopeOf:pe,setSel:j,writeKey:Q});me.current={reach:P,add:J,scopeOf:pe,setSel:j,writeKey:Q},R.useEffect(()=>{if(e)return e.setEditTool({personId:a.id,part:null,parts:Ep,direct:!0,mode:d,lockFeet:_,draft:(H,se)=>({id:"__drag",...me.current.reach(me.current.scopeOf(se)),...H}),commit:(H,se)=>{const he=fi(se);me.current.add(H,he?Ys()!=="en"?he.vi:he.en:o(Fo[se]),me.current.scopeOf(se))},select:H=>me.current.setSel(H),hover:H=>N(H)}),()=>{e.editTool?.direct&&e.setEditTool(null)}},[e,a.id,d,_]);const X=R.useRef(T);X.current=T,R.useEffect(()=>{X.current&&e?.selectPosePart(X.current)},[e,d]);const re=H=>{j(H),e?.selectPosePart(H)},ue=()=>me.current.writeKey(),Ee=R.useRef({pick:re,sel:T,insertKey:ue,breakdown:ee});Ee.current={pick:re,sel:T,insertKey:ue,breakdown:ee},R.useEffect(()=>{const H=se=>{const he=se.target;if(se.metaKey||se.ctrlKey||se.altKey||he&&(he.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(he.tagName)))return;const ce=se.key.toLowerCase(),Pe=ce==="g"?"move":ce==="r"?"rotate":ce==="f"?"free":null;if(Pe){se.preventDefault(),se.stopImmediatePropagation(),f(Pe);return}if((ce==="i"||ce==="k")&&!se.shiftKey){se.preventDefault(),se.stopImmediatePropagation(),Ee.current.insertKey();return}if(ce==="e"&&se.shiftKey){se.preventDefault(),se.stopImmediatePropagation(),Ee.current.breakdown();return}se.key==="Tab"&&(se.preventDefault(),se.stopImmediatePropagation(),Ee.current.pick(Fp(fi(Ee.current.sel??"")?.id??null,se.shiftKey?-1:1).part))};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[]);const ye=Ys()!=="en",ne=fi(L??T??"");R.useEffect(()=>{if(e)return e.setFocusLock(a.id),()=>e.setFocusLock(null)},[e,a.id]);const Ie=()=>is(n.items.find(H=>H.id===a.id)??a,s,i/Math.max(1e-6,s.duration),n.items).pose,ze=(H,se)=>{const he=Pp(Ie(),H,se);he&&Object.keys(he).length&&J({pose:he},`${o(Fo[`hand${H}`])}: ${o(gi[se].name)}`)},we=T==="handL"||T==="handR"?T.slice(-1):null,de=H=>{const se=Ie(),he=In[H],ce={};for(const[Pe,Be]of Object.entries(he))if(typeof Be=="number"&&Number.isFinite(Be)){const ot=Be-(typeof se[Pe]=="number"?se[Pe]:0);Math.abs(ot)>.01&&(ce[Pe]=Math.round(ot*100)/100)}Object.keys(ce).length&&J({pose:ce},o(H))};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-pose-banner shot-pose-bar",role:"toolbar","aria-label":o("Chỉnh dáng"),children:[t.jsx("span",{className:"shot-pose-who",title:o("Kéo các tay cầm để chỉnh dáng {0}",[a.name]),children:a.name}),t.jsx("span",{className:"shot-pose-control","aria-live":"polite",style:ne?{color:`#${Wl[ne.side].toString(16).padStart(6,"0")}`}:void 0,children:ne?`${ye?ne.vi:ne.en} · ${ne.id}`:o("Chọn một tay cầm")}),t.jsx("button",{className:A?"active":"","aria-expanded":A,"aria-label":o("Bảng điều khiển"),title:o("Bảng điều khiển: bấm tên để chọn tay cầm (Tab: tay cầm kế tiếp)"),onClick:()=>O(H=>!H),children:"🧍"}),t.jsx("select",{"aria-label":o("Phạm vi chỉnh"),title:o(vh.find(H=>H.id===u)?.hint??""),value:u,onChange:H=>m(H.target.value),children:vh.map(H=>t.jsx("option",{value:H.id,disabled:H.id==="span"&&!c,children:o(H.label)},H.id))}),u==="range"&&t.jsxs("span",{className:"shot-pose-range",role:"group","aria-label":o("Vùng key"),children:[t.jsx("input",{type:"number","aria-label":o("Vùng key từ (giây)"),title:o("Đặt đầu vùng ở playhead"),min:0,max:s.duration,step:.1,value:p,onChange:H=>x(+H.target.value),onDoubleClick:()=>x(+i.toFixed(2))}),t.jsx("span",{"aria-hidden":!0,children:"–"}),t.jsx("input",{type:"number","aria-label":o("Vùng key đến (giây)"),title:o("Đặt cuối vùng ở playhead"),min:0,max:s.duration,step:.1,value:g,onChange:H=>v(+H.target.value),onDoubleClick:()=>v(+i.toFixed(2))}),"s"]}),t.jsx("div",{className:"shot-seg shot-pose-modes",role:"radiogroup","aria-label":o("Cách chỉnh"),children:Yv.map(H=>t.jsx("button",{role:"radio","aria-checked":d===H.id,"aria-label":o(H.label),className:d===H.id?"active":"",title:`${o(H.label)} · ${o(H.hint)}`,onClick:()=>f(H.id),children:H.icon},H.id))}),we&&t.jsxs("select",{"aria-label":o("Kiểu bàn tay"),value:"",onChange:H=>{H.target.value&&ze(we,H.target.value)},children:[t.jsx("option",{value:"",children:o("Bàn tay…")}),Object.keys(gi).map(H=>t.jsx("option",{value:H,children:o(gi[H].name)},H))]}),t.jsx("button",{className:_?"active":"","aria-pressed":_,"aria-label":o("Khoá chân"),title:o("Khoá chân: kéo hông thì chân đứng yên, gối tự gập / duỗi (tắt: kéo hông dời cả người)"),onClick:()=>$(H=>!H),children:"🔒"}),t.jsx("button",{className:B?"active shot-pose-key":"shot-pose-key","aria-label":o("Đặt key"),title:o("Đặt key tư thế tại playhead (I)"),onClick:()=>Q(),children:"◆"}),t.jsx("button",{disabled:!Z,className:"shot-pose-breakdown","aria-label":o("Breakdown"),title:o("Breakdown: key chuyển tiếp giữa key trước và sau ({0}% về key sau) — Shift+E",[Math.round(q*100)]),onClick:ee,onWheel:H=>D(se=>Math.max(0,Math.min(1,+(se+(H.deltaY<0?.1:-.1)).toFixed(1)))),children:"◇"}),T?.startsWith("foot")&&t.jsxs("label",{className:"shot-pose-roll",title:o("Cuộn bàn chân: + nhón gót (kiễng chân), − kiễng mũi (tựa gót) — thả chuột để áp"),children:[t.jsx("span",{children:o("Cuộn")}),t.jsx("input",{type:"range","aria-label":o("Cuộn bàn chân"),min:-40,max:60,step:5,value:xe,onChange:H=>be(+H.target.value),onPointerUp:()=>U(xe),onKeyUp:H=>{H.key==="Enter"&&U(xe)}}),t.jsxs("b",{children:[xe>0?"+":"",xe,"°"]})]}),t.jsx("button",{className:C?"active":"","aria-expanded":C,"aria-label":o("Thư viện dáng"),title:o("Thư viện dáng"),onClick:()=>M(H=>!H),children:o("Dáng")}),t.jsx("button",{disabled:!y.length,"aria-label":o("Hoàn tác"),title:o("Bỏ lần chỉnh vừa rồi"),onClick:V,children:"↶"}),t.jsx("button",{className:"shot-primary",title:o("Xong (Esc)"),onClick:l,children:o("Xong")})]}),A&&t.jsx("div",{className:"shot-pose-picker",role:"group","aria-label":o("Bảng điều khiển"),children:Ip.map(H=>{const se=`#${Wl[H.side].toString(16).padStart(6,"0")}`,he=T===H.part;return t.jsx("button",{"data-control":H.id,"aria-pressed":he,className:`shot-pose-pick ${H.shape}${he?" active":""}`,style:{gridColumn:H.picker[0]+1,gridRow:H.picker[1]+1,borderColor:se,...he?{background:se}:{}},title:`${ye?H.vi:H.en} (${H.id})`,onMouseEnter:()=>N(H.part),onMouseLeave:()=>N(null),onClick:()=>re(H.part),children:ye?H.vi:H.en},H.id)})}),C&&t.jsxs("div",{className:"shot-pose-library",children:[t.jsx("div",{className:"shot-pose-tabs",role:"tablist",children:Po.map((H,se)=>t.jsx("button",{role:"tab","aria-selected":S===se,className:S===se?"active":"",onClick:()=>I(se),children:o(H.name)},H.name))}),t.jsx("div",{className:"shot-rig-grid",children:Po[S]?.presets.map(H=>t.jsxs("button",{title:o("Áp dáng {0} tại {1}s",[o(H),i.toFixed(1)]),onClick:()=>de(H),children:[t.jsx(Gr,{pose:In[H]}),t.jsx("span",{children:o(H)})]},H))})]})]})}const Na=e=>Ys()==="en"?e.labelEn:e.label,jh=e=>Ys()==="en"?zp(e):_p(e),kh={counter:"Quầy bếp / quầy",desk:"Bàn làm việc + ghế",table:"Bàn ăn + ghế",chair:"Ghế",door:"Cửa"},wh=["Di chuyển","Giao tiếp","Tư thế","Võ","Phản ứng trúng đòn","Thể thao","Nhảy múa","Đời thường"],_i=[...wh.filter(e=>ql.includes(e)),...ql.filter(e=>!wh.includes(e))];function pu(e,n){if(!Tr(e))return yr(e);const s=e.keys(0),a=e.duration?n%e.duration:0;if(a<=s[0].t)return s[0].pose;for(let i=0;i<s.length-1;i++)if(a<=s[i+1].t)return Kp(s[i].pose,s[i+1].pose,(a-s[i].t)/Math.max(1e-6,s[i+1].t-s[i].t),s[i+1].ease);return s[s.length-1].pose}const yr=e=>{if(e.thumb)return e.thumb;const n=e.keys(0);return n[Math.min(n.length-1,Math.floor(n.length/2))].pose},e1=()=>typeof window<"u"&&Number.isFinite(window.__CLIPOOX_THUMB_LIMIT)?Math.max(0,window.__CLIPOOX_THUMB_LIMIT):48,Ho=new Set;let vr=0;const t1=performance.now();function fu(e){if(e-Mh>=80){Mh=e;for(const n of Ho)n((e-t1)/1e3)}vr=Ho.size?requestAnimationFrame(fu):0}let Mh=0;function gu(e){return Ho.add(e),vr||(vr=requestAnimationFrame(fu)),()=>{Ho.delete(e)}}function n1({clip:e,animate:n}){const[s,a]=R.useState(()=>yr(e));return R.useEffect(()=>{if(!n){a(yr(e));return}let i=!0;e.mocap&&!Tr(e)&&Lr(e.id).catch(()=>{});const r=gu(l=>{i&&a(pu(e,l))});return()=>{i=!1,r()}},[n,e]),t.jsx(Gr,{pose:s})}function s1({person:e,clip:n}){const s=R.useRef(null),[a,i]=R.useState(!1);return R.useEffect(()=>{const r=s.current;if(!r||!n)return;let l;try{l=new Ir({canvas:r,antialias:!0,alpha:!0})}catch{return}l.setPixelRatio(Math.min(2,window.devicePixelRatio||1)),l.setSize(r.clientWidth||220,r.clientHeight||280,!1),l.outputColorSpace=Uo,l.toneMapping=U0;const c=new Rr,u=new Fr(28,(r.clientWidth||220)/(r.clientHeight||280),.1,50);c.add(new id("#e8eeff","#5e5a52",1.4));const m=new Go("#fff4e4",2.4);m.position.set(-2.5,3.5,3.5),c.add(m);const d=new ut(new X0(.9,40),new os({color:"#1d242b"}));d.rotation.x=-Math.PI/2,c.add(d),u.position.set(1.9,1.35,4.6),u.lookAt(0,.9,0);let f=null,p=!0,x=null;const g=e?.color??"#8f9aa3",v=e?.kind==="person"?e.figure:void 0,w=e?.kind==="person"?e.look:void 0,C=S=>{if(!p)return;const I=pu(n,S);if(I!==x){x=I,f&&(c.remove(f),f.traverse(k=>{k instanceof ut&&(k.geometry.dispose(),(Array.isArray(k.material)?k.material:[k.material]).forEach(T=>T.dispose()))})),f=Bp(I,g,v,w);const y=new $t().setFromObject(f).getSize(new ie).y||1.8;f.scale.multiplyScalar(1.8/Math.max(1.2,y>2.4?y:1.8)),c.add(f)}l.render(c,u)};n.mocap&&!Tr(n)&&(i(!0),Lr(n.id).then(()=>{p&&i(!1)}).catch(()=>p&&i(!1))),C(0);const M=gu(C);return()=>{p=!1,M(),f&&f.traverse(S=>{S instanceof ut&&(S.geometry.dispose(),(Array.isArray(S.material)?S.material:[S.material]).forEach(I=>I.dispose()))}),d.geometry.dispose(),d.material.dispose(),l.dispose()}},[n,e?.color,e]),t.jsxs("div",{className:"mocap-preview",children:[n?t.jsx("canvas",{ref:s,className:"mocap-preview-canvas","aria-label":o("Xem trước chuyển động trên nhân vật")}):t.jsx("div",{className:"mocap-preview-empty",children:o("Chọn một chuyển động để xem trước trên nhân vật")}),a&&t.jsx("small",{className:"shot-hint",children:o("Đang tải dữ liệu mocap…")})]})}const Bi=e=>e.meta?.pair;function a1({person:e,loop:n,mirror:s,onLoop:a,onMirror:i,onApply:r,onClose:l,playhead:c}){ht();const[u,m]=R.useState(""),[d,f]=R.useState(null),[p,x]=R.useState(null),[g,v]=R.useState(null),[w,C]=R.useState(()=>new Set),M=R.useRef(null),S=R.useRef(null);R.useEffect(()=>{S.current?.focus();const N=A=>{A.key==="Escape"&&(A.stopPropagation(),l())};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[l]);const I=R.useMemo(()=>{const N=$p(u),A=_=>(!d||_.group===d)&&$o(_.meta);if(!N)return ns.filter(A).sort((_,$)=>_i.indexOf(_.group)-_i.indexOf($.group));const O=new Map(Op(u,{limit:120}).map(_=>[_.id,_.score]));return ns.filter(_=>O.has(_.id)&&A(_)).sort((_,$)=>(O.get($.id)??0)-(O.get(_.id)??0))},[u,d]);R.useEffect(()=>{const N=M.current;if(!N||typeof IntersectionObserver>"u")return;const A=new IntersectionObserver(O=>C(_=>{const $=new Set(_);for(const P of O){const W=P.target.dataset.clip;P.isIntersecting?$.add(W):$.delete(W)}return $}),{root:N,rootMargin:"80px"});return N.querySelectorAll("[data-clip]").forEach(O=>A.observe(O)),()=>A.disconnect()},[I]);const y=R.useMemo(()=>{const N=e1();return new Set(I.filter(A=>w.has(A.id)).slice(0,N).map(A=>A.id))},[I,w]),k=ns.find(N=>N.id===p)??null,T=ns.find(N=>N.id===(g??p))??null,j=N=>[N.anchor&&N.anchor.kind!=="floor"?o(kh[N.anchor.kind]):"",...N.props.length?[o("Đạo cụ: {0}",[N.props.map(A=>o(Ma[A.prop].label)).join(", ")])]:[]].filter(Boolean).join(" · "),L=k?.meta?.src?Dp[k.meta.src.license]:null;return t.jsx("div",{className:"shot-char-overlay mocap-overlay",role:"dialog","aria-modal":"true","aria-label":o("Thư viện Mocap"),onMouseDown:N=>{N.target===N.currentTarget&&l()},children:t.jsxs("div",{className:"shot-char-panel mocap-panel",ref:S,tabIndex:-1,children:[t.jsxs("header",{children:[t.jsxs("h2",{children:[o("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:ns.filter(N=>$o(N.meta)).length})]}),t.jsx("span",{className:"shot-char-for",children:e?o("Áp dụng cho: {0}",[e.name]):""}),t.jsx("button",{className:"shot-char-close","aria-label":o("Đóng"),onClick:l,children:"×"})]}),t.jsxs("div",{className:"mocap-body",children:[t.jsxs("div",{className:"mocap-browse",children:[t.jsxs("div",{className:"shot-char-tools",children:[t.jsx("input",{className:"shot-motion-search mocap-search",type:"search",value:u,placeholder:o("Tìm chuyển động (đấm móc, ngã, nhảy salsa, cat hanh…)"),"aria-label":o("Tìm chuyển động"),onChange:N=>m(N.target.value)}),t.jsxs("div",{className:"shot-motion-chips mocap-chips",role:"group","aria-label":o("Nhóm chuyển động"),children:[t.jsx("button",{type:"button",className:d?"":"active","aria-pressed":!d,onClick:()=>f(null),children:o("Tất cả")}),_i.map(N=>t.jsx("button",{type:"button","data-group":N,className:d===N?"active":"","aria-pressed":d===N,onClick:()=>f(d===N?null:N),children:jh(N)},N))]})]}),I.length===0&&t.jsx("small",{className:"shot-hint mocap-empty",children:o('Không có chuyển động khớp "{0}"',[u])}),t.jsx("div",{className:"shot-motion-grid mocap-grid",ref:M,role:"listbox","aria-label":o("Chuyển động"),children:I.map(N=>t.jsxs("button",{type:"button",role:"option","aria-selected":p===N.id,"data-clip":N.id,className:`mocap-card ${p===N.id?"picked":""}`,title:`${Na(N)} · ${N.duration.toFixed(1)}s${j(N)?` · ${j(N)}`:""}`,onClick:()=>x(N.id),onDoubleClick:()=>r(N),onPointerEnter:()=>v(N.id),onPointerLeave:()=>v(A=>A===N.id?null:A),children:[t.jsx(n1,{clip:N,animate:y.has(N.id)||g===N.id}),t.jsx("span",{className:"mocap-card-name",children:Na(N)}),t.jsxs("span",{className:"mocap-card-meta",children:[N.duration.toFixed(1),"s",N.loop?` · ${o("↻ lặp")}`:"",N.mocap?" · mocap":"",Bi(N)?` · ${o("cặp đôi")}`:""]}),N.anchor&&N.anchor.kind!=="floor"||N.props.length?t.jsx("em",{children:[N.anchor&&N.anchor.kind!=="floor"?o(kh[N.anchor.kind]):"",N.props.length?"+"+N.props.length:""].filter(Boolean).join(" ")}):null]},N.id))})]}),t.jsxs("aside",{className:"mocap-side",children:[t.jsx(s1,{person:e,clip:T}),k?t.jsxs("div",{className:"mocap-detail",children:[t.jsx("b",{children:Na(k)}),t.jsxs("small",{children:[jh(k.group)," · ",k.duration.toFixed(1),"s",k.loop?` · ${o("↻ lặp")}`:""]}),j(k)&&t.jsx("small",{children:j(k)}),Bi(k)&&t.jsx("small",{className:"mocap-pair",children:o("Clip cặp đôi với “{0}”. Áp ở đây chỉ chạy một người; nhờ Agent để đặt cả hai (play_motion partner).",[Na(ns.find(N=>N.id===Bi(k).with)??k)])}),L&&k.meta?.src&&k.meta.src.db!=="Clipoox"&&t.jsx("small",{className:"mocap-source",children:o("Nguồn: {0} (cảnh {1}) · {2}",[L.name,k.meta.src.trial,o("miễn phí, được dùng thương mại")])})]}):t.jsx("small",{className:"shot-hint",children:o("Bấm một thẻ để chọn, bấm đúp để áp ngay.")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:n,onChange:N=>a(N.target.checked)}),o("Lặp tới hết shot (đi, chạy, đứng chờ)")]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:s,onChange:N=>i(N.target.checked)}),o("Đổi tay / chân")]}),t.jsx("button",{type:"button",className:"shot-primary mocap-apply",disabled:!k,onClick:()=>k&&r(k),children:c!=null?o("Áp từ playhead ({0}s)",[c.toFixed(1)]):o("Áp từ playhead")}),t.jsx("small",{className:"shot-hint",children:o("Chuyển động có quầy / bàn / ghế / cửa sẽ đặt nhân vật vào đúng chỗ và đưa đạo cụ vào tay.")})]})]})]})})}function o1(e){ht();const[n,s]=R.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"shot-mocap-lib-open",disabled:e.disabled,onClick:()=>s(!0),title:o("Mở thư viện chuyển động: {0} chuyển động, có mocap thật",[ns.filter(a=>$o(a.meta)).length]),children:[t.jsx(Ce.person,{})," ",o("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:ns.filter(a=>$o(a.meta)).length})]}),n&&Jh.createPortal(t.jsx(a1,{...e,onClose:()=>s(!1),onApply:a=>{s(!1),e.onApply(a)}}),document.querySelector(".shot-workspace")||document.body)]})}function xu({disabled:e,loop:n,mirror:s,onLoop:a,onMirror:i,onPlay:r,person:l,playhead:c}){return ht(),t.jsx("div",{className:"shot-motion-lib",children:t.jsx(o1,{disabled:e,loop:n,mirror:s,onLoop:a,onMirror:i,onApply:r,person:l,playhead:c})})}const i1=24;function jr(e,n="joint"){const s=new Set((e?.joints||[]).map(a=>a.name));for(let a=1;;a++){const i=`${n}${a}`.slice(0,i1);if(!s.has(i))return i}}function Sh(e,n,s,a){const i=a||jr(e);if(!e)return Wo({kind:"manual",source:"manual",joints:[{name:i,parent:null,pos:n}],seed:1});const r=[...e.joints,{name:i,parent:s&&e.joints.some(l=>l.name===s)?s:e.joints[0].name,pos:n}];return bu(e,r)}function r1(e,n){const s=e.joints.find(r=>r.name===n);if(!s)return e;const a=e.joints.filter(r=>r.name!==n).map(r=>r.parent===n?{...r,parent:s.parent}:r);if(!a.length)return null;const i=e.bones?Object.fromEntries(Object.entries(e.bones).filter(([r])=>r!==n)):void 0;return bu({...e,...i?{bones:i}:{}},a)}function l1(e,n,s){return Wo({...e,joints:e.joints.map(a=>a.name===n?{...a,pos:s}:a)})}function bu(e,n){const s=Wo({...e,joints:n});return s.kind!==e.kind?{...s,source:"manual"}:s}class c1{constructor(n,s){this.engine=n,this.ev=s,this.host=n.renderer.domElement.parentElement??n.renderer.domElement,this.host.addEventListener("pointerdown",this.onDown,!0),this.host.addEventListener("pointerup",this.onUp,!0),n.rigTool=this}mode="off";itemId=null;picked=null;host;down=null;get restFor(){return this.mode==="edit"||this.mode==="place"?this.itemId:null}get posing(){return this.mode==="pose"?this.itemId:null}dispose(){this.host.removeEventListener("pointerdown",this.onDown,!0),this.host.removeEventListener("pointerup",this.onUp,!0),this.engine.rigTool===this&&(this.engine.rigTool=null);const n=this.root();n&&uc(n),this.engine.orbit.enabled=!0}set(n,s,a){this.itemId=n,this.mode=n?s:"off",this.picked=a}root(){return this.engine.objects.children.find(n=>n.userData.id===this.itemId)?.children[0]}state(){return this.root()?.userData.rig}afterSync(){const n=this.root(),s=this.state();if(!n||(uc(n),this.mode==="off"))return;const a=this.engine.transform;if(this.mode==="place"&&a.detach(),!s)return;vg(s,this.picked),n.updateMatrixWorld(!0);const i=this.picked?s.rig.joints.findIndex(r=>r.name===this.picked):-1;if(i<0){this.mode!=="place"&&a.detach();return}if(this.mode==="edit"){const r=s.bones[i].children.find(l=>l.userData.rigJoint===this.picked);r&&(a.attach(r),a.setMode("translate"),a.setSpace("world"))}else this.mode==="pose"&&(a.attach(s.bones[i]),a.setMode("rotate"),a.setSpace("local"))}commit(n){const s=this.state(),a=this.root(),i=this.itemId;if(!s||!a||!i)return!1;if(n.userData.rigJoint&&this.mode==="edit"){const r=a.worldToLocal(n.getWorldPosition(new ie)).toArray().map(l=>Math.round(l*1e4)/1e4);return this.ev.setRig(i,l1(s.rig,n.userData.rigJoint,r)),!0}return n.userData.rigBone&&this.mode==="pose"&&this.ev.boneKey(i,n.userData.rigBone,jg(s,n.userData.rigBone,this.ev.pose(i))),!0}ray(n){const s=this.engine.renderer.domElement.getBoundingClientRect(),a=new ic;return a.layers.enable(1),a.setFromCamera(new ta((n.clientX-s.left)/s.width*2-1,-(n.clientY-s.top)/s.height*2+1),this.engine.camera),a}jointHit(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const a=[];return s.traverse(i=>{i.userData.rigJoint&&a.push(i)}),n.intersectObjects(a,!1)[0]?.object.userData.rigJoint??null}interiorPoint(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const a=[];s.traverse(f=>{f instanceof ut&&!f.userData.rigOverlay&&a.push(f)});const i=n.intersectObjects(a,!1);if(!i.length)return null;const r=i[0],l=n.ray.direction.clone(),c=new $t().setFromObject(r.object).getSize(new ie).length()+.1,u=new ic(r.point.clone().addScaledVector(l,c),l.clone().negate(),0,c-1e-4);u.layers.mask=n.layers.mask;const m=u.intersectObjects(a,!1).at(-1),d=m?r.point.clone().add(m.point).multiplyScalar(.5):r.point.clone().addScaledVector(l,.02);return s.worldToLocal(d).toArray().map(f=>Math.round(f*1e4)/1e4)}onDown=n=>{if(this.mode==="off"||n.button!==0||this.engine.transform.axis){this.down=null;return}const s=this.mode==="place"?this.jointHit(this.ray(n)):null;this.down={x:n.clientX,y:n.clientY,link:s},s&&(this.engine.orbit.enabled=!1,n.stopPropagation())};onUp=n=>{const s=this.down;if(this.down=null,!s||this.mode==="off")return;const a=this.itemId,i=this.state(),r=Math.hypot(n.clientX-s.x,n.clientY-s.y)>4;if(s.link){if(this.engine.orbit.enabled=!0,r&&a&&i){const d=this.interiorPoint(this.ray(n));if(d){const f=jr(i.rig);this.picked=f,this.ev.setRig(a,Sh(i.rig,d,s.link,f))}}else r||(this.picked=s.link,this.ev.changed());return}if(r||this.engine.transform.axis||!a)return;const l=this.ray(n),c=this.jointHit(l);if(c){this.picked=c,this.ev.changed();return}if(this.mode!=="place")return;const u=this.interiorPoint(l);if(!u)return;const m=jr(i?.rig);this.ev.setRig(a,Sh(i?.rig,u,this.picked,m)),this.picked=m}}const Ch=[["humanoid","Người","Hai tay, hai chân — khớp với thư viện chuyển động"],["quadruped","Bốn chân","Thú bốn chân, đầu hướng +Z"],["chain","Đuôi / chuỗi","Chuỗi khớp dọc cạnh dài nhất (dây, đuôi, rắn…)"],["hinge","Bản lề","Nắp hộp, cửa: phần trên xoay quanh bản lề"],["wheels","Bánh xe","Thân xe + 4 bánh xoay riêng"]],Nh=[["edit","Chỉnh khớp","Bấm khớp rồi kéo bằng gizmo di chuyển (model về tư thế gốc)"],["place","Đặt khớp","Bấm lên model để thêm khớp con của khớp đang chọn; kéo từ một khớp thả lên model để tạo xương con"],["pose","Xoay xương","Bấm khớp rồi xoay bằng vòng xoay: ghi key tại playhead"]];function h1(e){ht();const{stage:n,shot:s,selected:a,engine:i,playhead:r}=e,l=n.items.find(D=>D.id===a&&D.kind==="model"&&D.model),c=l?.rig,[u,m]=R.useState("edit"),[d,f]=R.useState(4),[p,x]=R.useState(null),[g,v]=R.useState(!1),[w,C]=R.useState(""),[M,S]=R.useState(()=>{try{return localStorage.getItem("clipoox.rig.fingers")==="1"}catch{return!1}}),I=D=>{S(D);try{localStorage.setItem("clipoox.rig.fingers",D?"1":"0")}catch{}},[,y]=R.useReducer(D=>D+1,0),k=R.useRef(null),T=R.useRef(e);T.current=e;const j=(D,ee)=>T.current.change(Z=>({...Z,items:Z.items.map(xe=>xe.id!==D?xe:ee?{...xe,rig:ee,skeleton:void 0}:(({rig:be,...U})=>U)(xe)),...ee?{}:{shots:Z.shots.map(xe=>({...xe,objectKeys:Object.fromEntries(Object.entries(xe.objectKeys||{}).map(([be,U])=>[be,be===D?U.map(pe=>(({bones:me,...X})=>X)(pe)):U]))}))}})),L=(D,ee,Z)=>T.current.change(xe=>{const be=xe.shots.find(ye=>ye.id===xe.activeShot),U=xe.items.find(ye=>ye.id===D),pe=be.objectKeys?.[D]||[],me=T.current.playhead,X=ed(pe,me,U.rig?.bones),re=(ye,ne)=>{const Ie=pe.find(we=>Math.abs(we.time-ye)<1e-6),ze=Tn(U,be,ye);return{...Ie,id:Ie?.id||bt(),time:ye,position:ze.position,rotation:ze.rotation,scale:ze.scale,bones:ne}};let ue=[...pe];if(!pe.some(ye=>ye.bones)&&me>1e-6){const ye=re(0,{...U.rig?.bones||{}});ue=[...ue.filter(ne=>ne.id!==ye.id),ye]}const Ee=re(me,{...X,[ee]:Z});return ue=[...ue.filter(ye=>ye.id!==Ee.id),Ee].sort((ye,ne)=>ye.time-ne.time),{...xe,shots:xe.shots.map(ye=>ye.id===xe.activeShot?{...ye,objectKeys:{...ye.objectKeys,[D]:ue}}:ye)}}),N=D=>T.current.change(ee=>({...ee,items:ee.items.map(Z=>Z.id===D&&Z.rig?{...Z,rig:(({bones:xe,...be})=>be)(Z.rig)}:Z),shots:ee.shots.map(Z=>Z.id!==ee.activeShot?Z:{...Z,objectKeys:{...Z.objectKeys,[D]:(Z.objectKeys?.[D]||[]).map(xe=>(({bones:be,...U})=>U)(xe))}})}));R.useEffect(()=>{if(!i)return;const D=new c1(i,{setRig:(ee,Z)=>{j(ee,Z),y()},boneKey:(ee,Z,xe)=>{L(ee,Z,xe),y()},pose:ee=>{const Z=T.current.stage,xe=Z.shots.find(U=>U.id===Z.activeShot),be=Z.items.find(U=>U.id===ee);return be?is(be,xe,T.current.playhead).pose:null},changed:()=>{y(),T.current.resync()}});return k.current=D,()=>{D.dispose(),k.current=null,T.current.resync()}},[i]),R.useEffect(()=>{const D=k.current;if(!D)return;const ee=D.itemId===l?.id&&D.mode===u&&c?.joints.some(Z=>Z.name===D.picked)?D.picked:null;D.set(l?.id??null,l?u:"off",ee),e.resync()},[i,l?.id,u,!!c]),R.useEffect(()=>kg(()=>y()),[]),R.useEffect(()=>{let D=!0;return f0().then(ee=>{D&&x(ee)}).catch(()=>{}),()=>{D=!1}},[]),e.keys.current={del:()=>{const D=k.current;if(!D||!l?.rig||!D.picked||u!=="edit"&&u!=="place")return!1;const ee=D.picked;return D.picked=null,j(l.id,r1(l.rig,ee)),y(),!0},esc:()=>{const D=k.current;return D?.picked?(D.picked=null,y(),e.resync(),!0):!1}};const A=()=>{const D=k.current?.root();return D?Cg(D):null},O=D=>{const ee=A();if(!l||!ee||ee.isEmpty()){e.setError(o("Model chưa tải xong."));return}C(""),k.current&&(k.current.picked=null);const Z=k.current?.root(),xe=D==="humanoid"&&Z?Sg(Z):null;let be=Wp(D,{min:ee.min.toArray(),max:ee.max.toArray()},{segments:d,...xe?{tips:xe}:{}});D==="humanoid"&&M&&Z&&(be=bi(be,{positions:Ai(Z).positions})),j(l.id,be),m("edit"),y()},_=()=>{const D=A();!l?.rig||!D||(j(l.id,qp(l.rig,(D.min.x+D.max.x)/2)),y())},$=async()=>{const D=k.current?.root();if(!l||!D){e.setError(o("Model chưa tải xong."));return}v(!0),C("");try{const ee=Lg(D),Z=await g0({requestId:bt(),front:ee.front,side:ee.side,name:l.name});if(!Z.humanoid||!Z.landmarks||!Z.landmarks.humanoid){C(o("AI không thấy hình người trong model này. Không bị trừ credits — hãy chọn một mẫu bên dưới (miễn phí)."));return}let xe=Gp(Z.landmarks,ee.frame);M&&(xe=bi(xe,{positions:Ai(D).positions,tips:Up(Z.landmarks,ee.frame)})),k.current&&(k.current.picked=null),j(l.id,xe),m("edit"),y(),dt.getState().toast(o("Đã gắn xương tự động · {0} credits",[Z.credits]),"ok"),Z.landmarks.facing==="away"&&C(o("Model đang quay lưng về phía trước (+Z): chuyển động sẽ đi lùi. Xoay model 180° trong file gốc để chạy đúng hướng."))}catch(ee){C(ee.message||o("Gắn xương AI gặp lỗi."))}finally{v(!1)}},P=()=>{const D=k.current?.root();!l?.rig||!D||(k.current&&(k.current.picked=null),j(l.id,xi(l.rig)?Xp(l.rig):bi(l.rig,{positions:Ai(D).positions})),y())},W=D=>{const ee=Vi.find(xe=>xe.id===D);if(!l||!ee)return;let Z=l.pose||{};for(const xe of["L","R"])Z=td(Z,xe,ee);e.patchItem(l.id,{pose:Z})},z=k.current?.state(),Q=k.current?.picked??null,J=Hp(c),V=n.items.filter(D=>D.kind==="model"&&D.model);if(!l)return t.jsx("div",{className:"shot-rig-panel",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("p",{className:"shot-rig-empty",children:o("Chọn một model GLB để gắn xương.")}),V.length?t.jsx("div",{className:"shot-rig-models",children:V.map(D=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(D.id),children:[D.name,D.rig||D.skeleton==="native"?` · ${o("đã có xương")}`:""]},D.id))}):t.jsx("small",{className:"shot-hint",children:o("Thêm model ở tab Dựng cảnh (Nhập GLB / Thư viện 3D), rồi quay lại đây.")})]})});const B=(s.objectKeys?.[l.id]||[]).filter(D=>D.bones),q=l.model?wg(l.model.gcsUri):null;return t.jsx("div",{className:"shot-rig-panel",children:t.jsxs("div",{className:"shot-panel-body",children:[V.length>1&&t.jsx("div",{className:"shot-rig-switch",role:"group","aria-label":o("Model khác"),children:V.filter(D=>D.id!==l.id).map(D=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(D.id),children:[D.name,D.rig||D.skeleton==="native"?` · ${o("đã có xương")}`:""]},D.id))}),t.jsxs("div",{className:"shot-rig-target",children:[t.jsx("b",{children:l.name}),t.jsx("small",{children:c?o("{0} khớp · {1}",[c.joints.length,J?o("xương người"):o(Ch.find(D=>D[0]===c.kind)?.[1]??"Gắn tay")]):o("Chưa có xương")})]}),(()=>{const D=i?.nativeSkeleton(l.id);return!D?.ok&&l.skeleton!=="native"?null:t.jsxs("div",{className:"shot-rig-native",children:[t.jsx("h3",{children:o("XƯƠNG TRONG FILE")}),l.skeleton==="native"?t.jsxs(t.Fragment,{children:[t.jsx("small",{className:"shot-hint",children:o("Đang dùng xương gốc của file ({0} xương) — chuyển động như trong Blender.",[D?.bones??"…"])}),t.jsx("button",{type:"button",onClick:()=>{T.current.change(ee=>({...ee,items:ee.items.map(Z=>Z.id===l.id?{...Z,skeleton:void 0}:Z)})),y()},children:o("Bỏ xương gốc")})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>{k.current&&(k.current.picked=null),T.current.change(ee=>({...ee,items:ee.items.map(Z=>Z.id===l.id?{...Z,rig:void 0,skeleton:"native"}:Z)})),y()},children:o("Dùng xương có sẵn trong file")}),t.jsx("small",{className:"shot-hint",children:o("File này đã gắn xương người ({0} xương). Dùng thẳng xương và trọng số gốc thay cho xương mẫu — mượt như trong Blender, miễn phí.",[D?.bones??0])})]})]})})(),t.jsx("h3",{children:o("TỰ ĐỘNG")}),t.jsx("button",{type:"button",className:"shot-primary shot-rig-auto",disabled:g||e.busy||p?.configured===!1,onClick:()=>void $(),title:o("AI nhìn model từ trước và bên hông, đặt khớp và tính trọng số. Chỉ tính phí khi gắn thành công."),children:g?o("Đang gắn xương…"):o("✦ Tự gắn xương · ≈{0} credits",[p?p.estimate.toFixed(2):"…"])}),t.jsx("small",{className:"shot-hint shot-rig-price",children:p?o("Tối đa {0} credits · hoàn lại nếu AI không nhận ra hình người hoặc lỗi.",[p.max.toFixed(2)]):o("Cho nhân vật hình người (2 tay, 2 chân).")}),w&&t.jsx("div",{className:"shot-rig-note",role:"status",children:w}),t.jsx("h3",{children:o("MẪU CÓ SẴN · MIỄN PHÍ")}),t.jsx("div",{className:"shot-rig-templates",children:Ch.map(([D,ee,Z])=>t.jsx("button",{type:"button","data-template":D,title:o(Z),onClick:()=>O(D),children:o(ee)},D))}),t.jsxs("label",{className:"shot-rig-check",children:[t.jsx("input",{type:"checkbox",checked:M,onChange:D=>I(D.target.checked)})," ",o("Thêm xương ngón tay (mẫu Người / AI)")]}),t.jsxs("label",{className:"shot-field shot-rig-segments",children:[o("Số đốt (đuôi / chuỗi)"),t.jsx("input",{"aria-label":o("Số đốt (đuôi / chuỗi)"),type:"number",min:Ja.chainMin,max:Ja.chainMax,value:d,onChange:D=>f(Math.max(Ja.chainMin,Math.min(Ja.chainMax,Math.round(+D.target.value)||4)))})]}),t.jsx("h3",{children:o("GẮN TAY")}),t.jsx("div",{className:"shot-rig-modes",role:"group","aria-label":o("Công cụ xương"),children:Nh.map(([D,ee,Z])=>t.jsx("button",{type:"button",className:u===D?"active":"","aria-pressed":u===D,title:o(Z),onClick:()=>m(D),children:o(ee)},D))}),t.jsx("small",{className:"shot-hint",children:o(Nh.find(D=>D[0]===u)[2])}),Q&&t.jsx("div",{className:"shot-rig-picked",children:o("Khớp: {0}",[Q])}),t.jsxs("div",{className:"shot-rig-actions",children:[t.jsx("button",{type:"button",disabled:!c,onClick:_,title:o("Chép nửa trái (−X) sang phải qua tâm model, tự đặt tên .L / .R"),children:o("⇆ Đối xứng L/R")}),t.jsx("button",{type:"button",disabled:!c||!Q||u==="pose",onClick:()=>e.keys.current?.del(),children:o("Xoá khớp")}),t.jsx("button",{type:"button",disabled:!c,onClick:()=>{l.model&&Mg(l.model.gcsUri),e.resync(),y()},children:o("Tính lại trọng số")}),t.jsx("button",{type:"button",disabled:!c,onClick:()=>{k.current&&(k.current.picked=null),j(l.id,null),y()},children:o("Bỏ xương")})]}),q?t.jsxs("div",{className:"shot-rig-progress",role:"status",children:[t.jsx("span",{children:q.done?o("Đã tính xong trọng số chạy nền · {0} đỉnh",[q.vertices.toLocaleString()]):o("Đang tính trọng số chạy nền… {0}% · {1} đỉnh",[Math.round(q.progress*100),q.vertices.toLocaleString()])}),t.jsx("progress",{max:100,value:Math.round(q.progress*100),"aria-label":o("Tiến độ tính trọng số")}),!q.done&&t.jsx("small",{className:"shot-hint",children:o("Vẫn chỉnh được cảnh trong lúc chờ; xuất video sẽ đợi xong.")})]}):z&&z.info.source!=="pending"&&t.jsx("small",{className:"shot-hint shot-rig-stats",children:o("{0} đỉnh · trọng số {1} ms{2}",[z.info.vertices.toLocaleString(),z.info.ms,(z.info.via==="worker"?o(" · chạy nền"):"")+(z.info.source==="disk"?o(" (đã lưu trên máy)"):z.info.cached?o(" (bộ nhớ đệm)"):"")])}),J&&c&&t.jsxs("div",{className:"shot-rig-fingers",children:[t.jsx("span",{children:xi(c)?o("Ngón tay: 5 ngón × 3 đốt mỗi tay"):o("Chưa có xương ngón tay")}),t.jsx("button",{type:"button",onClick:P,children:xi(c)?o("Bỏ ngón tay"):o("Thêm ngón tay")})]}),c&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:o("TẠO DÁNG & CHUYỂN ĐỘNG")}),t.jsxs("div",{className:"shot-rig-pose-keys",children:[t.jsx("button",{type:"button",onClick:()=>m("pose"),className:u==="pose"?"active":"",children:o("Xoay xương tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsx("button",{type:"button",disabled:!B.length&&!c.bones,onClick:()=>N(l.id),children:o("Đặt lại dáng xương")})]}),t.jsx("small",{className:"shot-hint",children:B.length?o("{0} key xương trên timeline.",[B.length]):o("Xoay xương ghi key ngay tại playhead (Ctrl+Z để hoàn tác).")}),J?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-rig-posekey",onClick:()=>e.addPoseKey(l.id),children:o("◇ Key tư thế tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsxs("div",{className:"shot-rig-hands",role:"group","aria-label":o("Dáng tay"),children:[t.jsx("span",{children:o("Dáng tay")}),Vi.map(D=>t.jsx("button",{type:"button","data-hand":D.id,onClick:()=>W(D.id),children:o(D.label)},D.id))]}),t.jsx("div",{className:"shot-rig-presets",children:Po[0].presets.map(D=>t.jsx("button",{type:"button",onClick:()=>e.patchItem(l.id,{pose:{...In[D]}}),children:o(D)},D))}),t.jsx(xu,{disabled:e.busy,loop:e.motionLoop,mirror:e.motionMirror,onLoop:e.onMotionLoop,onMirror:e.onMotionMirror,onPlay:D=>e.onPlayClip(l.id,D),person:l,playhead:r*s.duration})]}):t.jsx("small",{className:"shot-hint",children:o("Thư viện chuyển động cần xương người (mẫu Người hoặc AI). Xương khác: tạo dáng bằng Xoay xương.")})]})]})})}const d1={viewBox:"0 0 24 24",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},u1=()=>t.jsxs("svg",{...d1,children:[t.jsx("circle",{cx:"12",cy:"4",r:"2"}),t.jsx("path",{d:"M12 6v8M6 9l6-1 6 1M8 21l4-7 4 7"}),t.jsx("circle",{cx:"6",cy:"9",r:".9",fill:"currentColor"}),t.jsx("circle",{cx:"18",cy:"9",r:".9",fill:"currentColor"}),t.jsx("circle",{cx:"12",cy:"14",r:".9",fill:"currentColor"})]});Un.rig={apply(e,n,s){n.rig&&n.model&&Tg(e,n.rig,n.model.gcsUri,s?(a,i)=>s.trackRigJob(a,i):void 0)},pose(e,n,s,a,i,r){const l=e.userData.rig;l&&n.rig&&Ag(l,i,ed(s.objectKeys?.[n.id],a,n.rig.bones),r)},gaze(e,n,s){const a=e.userData.rig;a&&a.rig.kind==="humanoid"&&Ng(a,s)}};Un.generate=e=>e.gen?.kind==="character"?jd(e.gen.spec).root:null;function m1({shot:e,engine:n,onClose:s,onBusy:a,onReady:i,timelineTarget:r,vfx:l}){ht();const[c,u]=R.useState(0),[m,d]=R.useState(e.duration),[f,p]=R.useState(720),[x,g]=R.useState(rn(e)),[v,w]=R.useState(!1),[C,M]=R.useState(0),[S,I]=R.useState(""),[y,k]=R.useState("film"),T=R.useRef(null);R.useEffect(()=>()=>T.current?.abort(),[]);const j=Number.isFinite(c)&&Number.isFinite(m)&&c>=0&&m>c&&m<=e.duration,L=async()=>{if(!n||!l)return;const A=new AbortController;T.current=A,w(!0),a(!0),M(0),I("");try{await l.run({height:f,fps:x,motionBlur:ia[y].samples,shutter:ia[y].shutter},M,A.signal),s()}catch(O){I(A.signal.aborted?"Đã huỷ xuất video.":O.message)}finally{T.current=null,w(!1),a(!1)}},N=async A=>{if(!n||!j)return;const O=new AbortController;T.current=O,w(!0),a(!0),M(0),I("");let _;try{const $={motionBlur:ia[y].samples,shutter:ia[y].shutter};if(_=await n.exportVideo({start:c,end:m,height:f,fps:x,...$,signal:O.signal,progress:M}),A==="download"){const P=URL.createObjectURL(_.blob),W=document.createElement("a");W.href=P,W.download=`${e.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-${c}-${m}.mp4`,W.click();const z=_.cleanup;setTimeout(()=>{URL.revokeObjectURL(P),z()},6e4),_=void 0}else await i(_.blob,{start:c,end:m,height:f,fps:x,...$},A);s()}catch($){I(O.signal.aborted?"Đã huỷ xuất video.":$.message)}finally{await _?.cleanup(),T.current=null,w(!1),a(!1)}};return t.jsx("div",{className:"shot-video-overlay",children:t.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":o("Xuất video camera"),className:"shot-video-dialog",children:[t.jsx("h2",{children:o("Xuất video camera · MP4")}),t.jsx("p",{children:o("H.264, không âm thanh, đúng đường chạy và không có line/gizmo. 720p · 24 fps phù hợp làm video tham chiếu nhẹ.")}),t.jsxs("fieldset",{disabled:v,children:[t.jsxs("div",{className:"shot-path-vector",children:[t.jsxs("label",{children:[o("Từ giây"),t.jsx("input",{"aria-label":o("Video từ giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(c)?c:"",onChange:A=>u(A.target.valueAsNumber)})]}),t.jsxs("label",{children:[o("Đến giây"),t.jsx("input",{"aria-label":o("Video đến giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(m)?m:"",onChange:A=>d(A.target.valueAsNumber)})]})]}),t.jsxs("label",{children:[o("Chất lượng"),t.jsxs("select",{"aria-label":o("Độ phân giải video"),value:f,onChange:A=>p(+A.target.value),children:[t.jsx("option",{value:720,children:o("720p · Nhẹ")}),t.jsx("option",{value:1080,children:o("1080p · Chi tiết")})]})]}),t.jsxs("label",{children:[o("Khung hình/giây"),t.jsx("select",{"aria-label":o("FPS video"),value:x,onChange:A=>g(+A.target.value),children:nd.map(A=>t.jsx("option",{value:A,children:o("{0} fps",[A])},A))})]}),t.jsxs("label",{title:o("Mỗi khung hình là trung bình nhiều lần render trong lúc màn trập mở, như máy quay phim: chuyển động nhanh nhoè tự nhiên. Xuất lâu hơn."),children:[o("Nhoè chuyển động"),t.jsxs("select",{"aria-label":o("Nhoè chuyển động"),value:y,onChange:A=>k(A.target.value),children:[t.jsx("option",{value:"off",children:o("Tắt · xuất nhanh")}),t.jsx("option",{value:"film",children:o("Điện ảnh · màn trập 180°")}),t.jsx("option",{value:"strong",children:o("Mạnh · hành động nhanh")})]})]})]}),t.jsxs("p",{children:[j?o("{0} giây · {1} · khoảng {2} MB",[(m-c).toFixed(1),e.aspect,Math.ceil((m-c)*(f===1080?6:3)/8)]):o("Chọn khoảng thời gian hợp lệ trong shot."),j&&y!=="off"?" · "+o("xuất lâu hơn khoảng {0} lần",[ia[y].samples]):""]}),v&&t.jsxs(t.Fragment,{children:[t.jsx("progress",{max:100,value:C}),t.jsx("p",{children:C<100?o("Đang xuất từng frame… {0}%",[C]):o("Đang hoàn tất / lưu video…")}),t.jsx("button",{disabled:C===100,onClick:()=>T.current?.abort(),children:o("Huỷ xuất")})]}),S&&t.jsx("p",{role:"alert",children:o(S)}),!v&&l&&t.jsxs("div",{className:"shot-video-vfx",children:[t.jsx("p",{children:l.layers?o("VFX: {0} lớp hiệu ứng xuất riêng trên nền đen (sau người / trước người) rồi đặt lên clip {1}, hoà kiểu Cộng sáng — cả shot, không cần chọn đoạn.",[l.layers,l.target?`“${l.target}”`:o("gốc")]):o("Cảnh chưa có hiệu ứng nào để xuất.")}),t.jsx("button",{className:"shot-primary",disabled:!l.layers,onClick:()=>void L(),children:o("✦ Xuất lớp hiệu ứng về Timeline")})]}),!v&&t.jsxs("div",{className:"shot-video-actions",children:[t.jsx("button",{onClick:s,children:o("Đóng")}),t.jsx("button",{disabled:!j,onClick:()=>void N("download"),children:o("Tải MP4")}),t.jsx("button",{disabled:!j,className:r||l?void 0:"shot-primary",onClick:()=>void N("canvas"),children:o("Đưa video vào Canvas")}),r&&t.jsx("button",{disabled:!j,className:"shot-primary",title:r,onClick:()=>void N("timeline"),children:o("Đưa về Timeline")})]}),t.jsx("small",{children:o("Xuất MP4 không chạy model AI. Tải về hoặc đưa vào Canvas rồi dùng video làm tham chiếu ở bất kỳ đâu.")})]})})}const p1=(e,n)=>`${e} · VFX ${n==="behind"?o("sau người"):o("trước người")}`;async function f1(e,n,s,a,i={}){const r=n.shots.find(p=>p.id===n.activeShot),l=e.vfxLayers();if(!n.plate)throw new Error(o("Cảnh này không có video nền (mở từ một clip trên Timeline)."));if(!l.length)throw new Error(o("Cảnh chưa có hiệu ứng nào để xuất."));const c=dt.getState().canvasId,u=[],m=a.vfxAlpha??"auto",{vfxAlpha:d,...f}=a;for(const[p,x]of l.entries()){const g=m==="on"||m==="auto"&&await e.vfxOccludes(x),{blob:v,cleanup:w}=await e.exportVideo({...f,start:0,end:r.duration,vfx:x,alpha:g,signal:i.signal??new AbortController().signal,progress:C=>i.progress?.(Math.round((p*100+C)/l.length))});try{const C=p1(r.name,x),M=g?"webm":"mp4",{url:S,gcsUri:I}=await _s(new File([v],`${r.name}-vfx-${x}.${M}`,{type:`video/${M}`}),void 0,"video"),y=Pt()?.getNode(s);if(!y||dt.getState().canvasId!==c)throw new Error(o("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi."));const k=Pt()?.addNode("video",{url:S,gcsUri:I,label:C,duration:r.duration,ratio:r.aspect,status:"succeeded",shotSourceId:s,shotId:r.id,vfxLayer:x},{x:y.position.x+380,y:y.position.y+p*260},{sourceIds:[s]});if(!k)throw new Error(o("Không tạo được video trên Canvas"));const{width:T,height:j}=Vp(r.aspect,{short:a.height});u.push({layer:x,nodeId:k,url:S,gcsUri:I,duration:r.duration,label:C,...g?{alpha:!0,fps:a.fps,width:T,height:j}:{}})}finally{await w()}}return u}const g1=(e,n)=>[...e].sort((s,a)=>(s.layer==="behind"?0:1)-(a.layer==="behind"?0:1)).map(s=>({op:"addVfxLayer",materialId:s.nodeId,clipId:n,layer:s.layer}));function x1(e,n){const s=dt.getState(),a=n?s.clips.find(l=>l.id===n):void 0;if(!a||a.kind!=="video")return{passes:e,placed:!1};const i=e.map(l=>({id:l.nodeId,kind:"video",url:l.url,gcsUri:l.gcsUri,label:l.label,duration:l.duration,...l.alpha?{alpha:!0,fps:l.fps,width:l.width,height:l.height}:{}})),r=Yp(s.clips,g1(e,a.id),i,s.timelineTracks,s.timelineCamera);if(r.errors.length)throw new Error(r.errors[0]);return s.setClips(()=>r.clips),s.setTimelineMedia(l=>[...l,...e.filter(c=>!l.some(u=>u.source==="canvas"&&u.id===c.nodeId)).map(c=>({id:c.nodeId,source:"canvas",kind:"video",url:c.url,gcsUri:c.gcsUri,label:c.label,duration:c.duration}))]),{passes:e,placed:!0,clipId:a.id,pendingMatte:!!r.mattes?.length}}function b1({stage:e,selected:n,time:s,disabled:a,onApply:i,getBounds:r,getColliders:l,onPreview:c,embedded:u=!1}){ht();const[m,d]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.keyModel")==="gpt-5.6-sol"?"gpt-5.6-sol":"gpt-6.1-sol"}catch{return"gpt-6.1-sol"}}),[f,p]=R.useState([]),[x,g]=R.useState(""),[v,w]=R.useState(!1),[C,M]=R.useState(""),[S,I]=R.useState(null),[y,k]=R.useState(null),[T,j]=R.useState(null),[L,N]=R.useState(!1),[A,O]=R.useState(null),_=R.useRef(null),$=[...f,{role:"user",content:x.trim()}].slice(-12),P=JSON.stringify({scene:gc(e,n,s,r(),l?.()),messages:$,model:m});R.useEffect(()=>{if(j(null),!x.trim()||v)return;let q=!1;N(!0);const D=setTimeout(()=>{const ee=JSON.parse(P);x0(ee.scene,ee.messages,ee.model).then(Z=>{q||j({signature:P,credits:Z.reservedCredits})}).catch(Z=>{q||M(Z.message)}).finally(()=>{q||N(!1)})},400);return()=>{q=!0,clearTimeout(D)}},[P,x,v]);const W=R.useRef(null),z=R.useRef(!0),Q=R.useRef(!1);R.useEffect(()=>(z.current=!0,b0().then(q=>{z.current&&I(q)}).catch(()=>{}),()=>{z.current=!1}),[]),R.useEffect(()=>{W.current&&(W.current.scrollTop=W.current.scrollHeight)},[f,v,y]);const J=y&&(y.revision!==e.revision||y.shotId!==e.activeShot),V=async(q=!1)=>{if(Q.current||a||!q&&(!x.trim()||T?.signature!==P))return;const D=q?_.current:{scene:gc(e,n,s,r(),l?.()),messages:$,id:crypto.randomUUID(),revision:e.revision,shotId:e.activeShot,model:m};if(D){_.current=D,Q.current=!0,w(!0),M(""),k(null),p(D.messages),g("");try{const{plan:ee,model:Z,billing:xe}=await y0(D.scene,D.messages,D.id,D.model);if(!z.current)return;_.current=null,O(xe.credits),I({available:!0,model:Z}),p([...D.messages,{role:"assistant",content:ee.message}]),ee.tracks.length&&k({plan:ee,revision:D.revision,shotId:D.shotId})}catch(ee){z.current&&M(ee.message)}finally{Q.current=!1,z.current&&w(!1)}}},B=u?"div":"section";return t.jsxs(B,{className:u?"shot-agent-embedded":"shot-agent","aria-label":o("AI Agent 3D"),children:[t.jsxs("select",{"aria-label":o("Model AI"),value:m,disabled:v,onChange:q=>{d(q.target.value),_.current=null,M("");try{localStorage.setItem("clipoox.shot.keyModel",q.target.value)}catch{}},children:[t.jsx("option",{value:"gpt-5.6-sol",children:"GPT 5.6 Sol"}),t.jsx("option",{value:"gpt-6.1-sol",children:"GPT 6.1 Sol"})]}),t.jsxs("div",{className:"shot-agent-heading",children:[u?t.jsx("small",{children:o("Đề xuất key cho đối tượng đang chọn hoặc camera")}):t.jsxs(t.Fragment,{children:[t.jsx("b",{children:o("✦ AI Agent")}),t.jsx("small",{children:S?.model||"GPT 5.6 sol"})]}),t.jsx("button",{title:o("Xóa hội thoại"),disabled:v,onClick:()=>{p([]),k(null),M(""),_.current=null},children:"↺"})]}),t.jsxs("div",{className:"shot-agent-chat",ref:W,role:"log","aria-label":o("Hội thoại AI"),children:[!f.length&&t.jsx("p",{className:"shot-agent-intro",children:o("Mô tả chuyển động cho đối tượng đang chọn hoặc camera. AI đề xuất key để bạn áp dụng.")}),f.map((q,D)=>t.jsx("div",{className:`shot-agent-message ${q.role}`,children:q.content},D)),v&&t.jsx("p",{role:"status",children:o("Đang tạo đề xuất key…")}),C&&t.jsxs("p",{role:"alert",children:[C,_.current&&t.jsx("button",{disabled:v,onClick:()=>void V(!0),children:o("Thử lại")})]}),y&&t.jsxs("div",{className:"shot-agent-proposal",children:[t.jsxs("small",{children:[y.plan.tracks.length," ",o("track ·")," ",y.plan.tracks.reduce((q,D)=>q+D.keys.length,0)," ",o("key ·")," ",y.plan.duration,o("s")]}),J?t.jsx("p",{children:o("Cảnh đã thay đổi. Gửi lại yêu cầu để cập nhật đề xuất.")}):t.jsxs(t.Fragment,{children:[t.jsx("ul",{children:y.plan.tracks.map(q=>t.jsxs("li",{children:[q.subjectId==="camera"?"Camera":e.items.find(D=>D.id===q.subjectId)?.name,": ",q.replaceRange?o("Sửa đoạn {0}–{1}s",[q.replaceRange.start.toFixed(2),q.replaceRange.end.toFixed(2)]):o("Thêm/cập nhật {0}–{1}s",[q.keys[0].seconds.toFixed(2),q.keys.at(-1).seconds.toFixed(2)])]},q.subjectId))}),t.jsx("button",{disabled:a,onClick:()=>c(y.plan,q=>{q&&(k(null),p(D=>[...D,{role:"assistant",content:o("Đã giữ thay đổi sau khi xem thử. Có thể hoàn tác bằng Ctrl/Cmd + Z.")}]))}),children:o("Xem thử chuyển động")}),t.jsx("button",{className:"shot-primary",disabled:a,onClick:()=>{try{i(y.plan),k(null),p(q=>[...q,{role:"assistant",content:o("Đã áp dụng key. Bấm Play để xem; Ctrl/Cmd + Z để hoàn tác.")}])}catch(q){M(q.message)}},children:o("Áp dụng key")})]})]})]}),t.jsxs("form",{onSubmit:q=>{q.preventDefault(),V()},children:[t.jsx("textarea",{"aria-label":o("Mô tả key cho AI"),maxLength:4e3,rows:3,value:x,placeholder:o("Ví dụ: xe đi tới 3 mét trong 5 giây…"),onChange:q=>g(q.target.value)}),t.jsx("small",{children:T?.signature===P?o("Tạm giữ tối đa {0} credit; hoàn phần dư theo token thực tế.",[T.credits.toFixed(2)]):L&&x.trim()?o("Đang tính phí…"):o("Chỉ tính phí khi có đề xuất key. Hỏi làm rõ: miễn phí.")}),t.jsx("button",{className:"shot-primary",disabled:v||a||!x.trim()||T?.signature!==P||S?.available===!1,children:o("Tạo key")})]}),A!==null&&t.jsx("small",{children:o("Phí: {0} credit.",[A.toFixed(2)])}),S?.available===!1&&t.jsx("small",{children:o("Admin cần cấu hình API key để bật Agent.")})]})}const Ah=[["gpt-6.1-sol","GPT 6.1 Sol"],["gemini-4-argon","Gemini 4 Argon"],["claude-sonnet-5-5","Claude Sonnet 5.5"],["claude-opus-5-5","Claude Opus 5.5"],["qwen-3.8-flash","Qwen 3.8 Flash (tiết kiệm)"]],y1={mission:["Cô gái đi từ cửa tới bàn trong 4 giây rồi ngồi xuống, camera trung cảnh bám theo","Hai võ sĩ giao đấu: A đấm thẳng, B né rồi trúng cú đá tạt, camera cầm tay rung khi trúng đòn","Xe đỏ chạy qua hẻm núi, camera bám sau rồi vòng ra trước, 12 giây, dọc 9:16"],set:["Quán cà phê 6×8 m: quầy bar, 5 bàn tròn, cửa kính mặt tiền","Hẻm Sài Gòn ban đêm: nhà ống hai bên, dây điện, xe máy dựng dọc tường","Phòng khách căn hộ hiện đại: sofa chữ L, bàn trà, cửa sổ lớn"]},Th=(e,n)=>{try{return localStorage.getItem(e)||n}catch{return n}},Ki=(e,n)=>{try{localStorage.setItem(e,n)}catch{}},jn=e=>String(Math.round(e*100)/100);function v1({stage:e,disabled:n,agent:s,lock:a}){ht();const i=zh(),[r,l]=R.useState(()=>{const ne=Th("clipoox.shot.missionMode","mission");return ne==="keys"||ne==="set"?ne:"mission"}),c=ne=>[ne==="set"?"clipoox.shot.setModel2":"clipoox.shot.missionModel2","gpt-6.1-sol"],u=ne=>{const[Ie,ze]=c(ne),we=Th(Ie,ze);return Ah.some(([de])=>de===we)?we:ze},[m,d]=R.useState(()=>u(r)),[f,p]=R.useState(!1),x=ne=>{p(ne),Ki("clipoox.shot.hq","")},g=f?Sa:m,[v,w]=R.useState(""),[C,M]=R.useState(null),[S,I]=R.useState(""),y=R.useRef(null),k=R.useRef(null),T=Qp(e),j=Zp(T),[L,N]=R.useState(null),[A,O]=R.useState(!1),[_,$]=R.useState(null),P=R.useRef(null);R.useEffect(()=>{if(!_)return;const ne=ze=>{P.current?.contains(ze.target)||$(null)},Ie=ze=>{ze.key==="Escape"&&(ze.stopPropagation(),$(null))};return window.addEventListener("pointerdown",ne),window.addEventListener("keydown",Ie,!0),()=>{window.removeEventListener("pointerdown",ne),window.removeEventListener("keydown",Ie,!0)}},[_]);const[W,z]=R.useState(""),[Q,J]=R.useState(""),[V,B]=R.useState(null),q=["thinking","acting","rendering"].includes(i.phase);R.useEffect(()=>{y.current&&(y.current.scrollTop=y.current.scrollHeight)},[i.log.length]);const D=ne=>{l(ne),Ki("clipoox.shot.missionMode",ne),d(u(ne))},ee=ne=>{d(ne),Ki(c(r)[0],ne)},Z=async ne=>{if(I(""),!ne){M(null);return}if(ne.size>28e4||!["image/jpeg","image/png"].includes(ne.type)){I(o("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const Ie=await new Promise((ze,we)=>{const de=new FileReader;de.onload=()=>ze(String(de.result)),de.onerror=()=>we(de.error),de.readAsDataURL(ne)});M({name:ne.name,data:Ie})},xe=(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===g&&i.quality==="high"===f,be=A?Jp({from:Number(W),to:Number(Q)},T.duration):null,U=(ne=!1)=>{const Ie=v.trim();if(!Ie||q||n)return;w("");const ze={window:be,continueFrom:V,quality:f?"high":null};B(null),ne&&xe?i.followUp(Ie,ze):i.start(Ie,C?.data||null,g,r==="set"?"set":"shot",ze)},pe=ne=>{N(null),a&&Math.abs(ne-j)>1e-6&&a.onChange(Math.max(0,Math.min(T.duration,ne)))},me=(ne,Ie=null)=>{w(ne),B(Ie),requestAnimationFrame(()=>{const ze=k.current;ze&&(ze.focus(),ze.setSelectionRange(ne.length,ne.length))})},X=ne=>o("Giữ nguyên 0–{0}s, kéo dài shot thêm 5s, từ {0}s đến {1}s: ",[jn(ne),jn(ne+5)]),re=()=>{A||(z(jn(j)),J(jn(T.duration))),O(!A)},ue=(navigator.language||"").startsWith("vi"),Ee={thinking:o("Đang nghĩ…"),acting:o("Đang dựng trong composer…"),rendering:o("Đang render & đưa vào canvas…"),done:o("Xong"),error:o("Lỗi"),cancelled:o("Đã dừng"),capped:o("Đã dùng hết {0} credit của lượt này",[$a]),idle:""}[i.phase],ye=t.jsxs("label",{className:`shot-lock-chip shot-hq-chip${f?" on":""}`,children:[t.jsx("input",{type:"checkbox","aria-label":o("Model chất lượng cao · Opus"),checked:f,disabled:q,onChange:ne=>x(ne.target.checked)}),t.jsxs("span",{"aria-hidden":"true",children:["✦ ",o("Chất lượng cao")]})]});return t.jsxs("section",{className:"shot-agent shot-mission","aria-label":o("Mission Agent"),children:[t.jsxs("div",{className:"shot-agent-heading",children:[t.jsx("b",{children:o("✦ Mission")}),r!=="keys"&&t.jsx("select",{className:"shot-mission-model","aria-label":o("Model AI"),value:g,disabled:q||f,onChange:ne=>ee(ne.target.value),title:o("GPT 6 Astra suy luận tốt hơn, giá token cao hơn (tính theo dùng thật)"),children:Ah.map(([ne,Ie])=>t.jsx("option",{value:ne,children:o(Ie)},ne))}),r!=="keys"&&i.missionId&&!q&&t.jsx("button",{title:o("Yêu cầu mới"),onClick:()=>i.reset(),children:"↺"})]}),t.jsxs("div",{className:"shot-mission-tabs",role:"tablist",children:[t.jsx("button",{role:"tab","aria-selected":r==="mission",className:r==="mission"?"active":"",disabled:q,onClick:()=>D("mission"),children:o("Dựng shot")}),t.jsx("button",{role:"tab","aria-selected":r==="set",className:r==="set"?"active":"",disabled:q,onClick:()=>D("set"),children:o("Dựng bối cảnh")}),t.jsx("button",{role:"tab","aria-selected":r==="keys",className:r==="keys"?"active":"",disabled:q,onClick:()=>D("keys"),children:o("Key đối tượng")})]}),r==="keys"?t.jsx(b1,{embedded:!0,stage:e,selected:s.selected,time:s.time,disabled:n,getBounds:s.getBounds,getColliders:s.getColliders,onPreview:s.onPreview,onApply:s.onApply}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-mission-body",children:[i.phase==="idle"&&!i.log.length&&t.jsxs("div",{className:"shot-mission-empty",children:[t.jsx("p",{className:"shot-agent-intro",children:r==="set"?o("Mô tả địa điểm (hoặc gửi ảnh tham chiếu) → Agent dựng bối cảnh 3D đúng tỉ lệ bằng khối, đặt camera và tự xem lại. Bối cảnh dùng chung cho mọi shot. Tính theo token dùng thật."):o("Một câu → Agent dựng proxy, cho xe/nhân vật chạy, camera bám, tự kiểm tra rồi render video ref vào canvas. ≈ 0.05–0.4 credit/bước.")}),t.jsx("div",{className:"shot-mission-suggest","aria-label":o("Gợi ý"),children:y1[r==="set"?"set":"mission"].map(ne=>t.jsx("button",{type:"button",disabled:q||n,onClick:()=>w(o(ne)),children:o(ne)},ne))})]}),i.log.length>0&&t.jsxs("div",{className:"shot-agent-chat shot-mission-log",ref:y,role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[i.quality==="high"&&t.jsx("b",{className:"shot-hq-badge",children:o("Chất lượng cao · Opus")}),Ee," · ",o("bước")," ",i.step,"/",i.maxSteps," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-12).map((ne,Ie)=>t.jsx("div",{className:"shot-mission-line",children:ne},Ie)),i.sheet&&t.jsx("img",{className:"shot-mission-sheet",src:i.sheet,alt:o("Contact sheet 6 khung hình")}),i.phase==="done"&&t.jsx("div",{className:"shot-mission-facts",children:ef(e,i.facts,ue)}),i.phase==="done"&&i.purpose==="set"&&i.ready&&t.jsx("div",{className:"shot-mission-done",children:o('Bối cảnh đã có trong composer (danh sách Đối tượng). Muốn sửa tiếp: gõ bên dưới rồi bấm "Sửa / làm tiếp phiên này"; hoặc chuyển sang "Dựng shot" để thêm nhân vật và chuyển động.')}),i.phase==="done"&&i.result?.nodeId&&t.jsx("div",{className:"shot-mission-done",children:o('Video ref đã được thêm vào canvas. Bấm "← Canvas" để xem. Muốn sửa hoặc làm tiếp shot này: gõ bên dưới rồi bấm "Sửa / làm tiếp phiên này". Ưng phần đầu rồi thì khoá lại trước.')}),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:o('Lượt này đã dùng hết {0} credit nên Agent dừng lại; mọi thứ đã dựng vẫn giữ nguyên. Gõ yêu cầu bên dưới rồi bấm "Sửa / làm tiếp phiên này" để làm tiếp từ những gì đang có (thêm {0} credit).',[$a])}),i.error&&t.jsx("p",{role:"alert",children:i.error})]})]}),r==="set"&&t.jsx("div",{className:"shot-mission-lock",children:ye}),r==="mission"&&t.jsxs("div",{ref:P,className:`shot-mission-lock${j>0?" on":""}`,role:"group","aria-label":o("Khoá đoạn đã ưng"),children:[a&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:`shot-lock-chip${j>0?" on":""}`,"aria-expanded":_==="lock",title:j>0?o("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[jn(j)]):o("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên."),onClick:()=>$(_==="lock"?null:"lock"),children:["🔒 ",j>0?`0–${jn(j)}s`:o("Khoá")]}),t.jsxs("button",{type:"button",className:`shot-lock-chip${A?be?" on":" bad":""}`,"aria-expanded":_==="window",onClick:()=>$(_==="window"?null:"window"),children:["✂ ",A&&be?`${jn(be.from)}–${jn(be.to)}s`:o("Chỉ sửa đoạn")]})]}),ye,_==="lock"&&a&&t.jsxs("div",{className:"shot-lock-pop",children:[t.jsxs("div",{className:"shot-mission-lock-row",children:[t.jsxs("span",{className:"shot-mission-lock-label",children:[o("Khoá")," 0–"]}),t.jsx("input",{"aria-label":o("Khoá đến (giây)"),inputMode:"decimal",value:L??jn(j),disabled:q,onFocus:ne=>ne.target.select(),onChange:ne=>N(ne.target.value),onBlur:()=>{if(L!=null){const ne=Number(L.replace(",","."));Number.isFinite(ne)?pe(ne):N(null)}},onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),ne.target.blur()),ne.key==="Escape"&&(N(null),ne.target.blur())}}),t.jsx("span",{children:"s"}),t.jsx("button",{type:"button",disabled:q||a.playhead<=0,title:o("Agent sẽ không sửa gì trước vị trí playhead; bạn vẫn sửa tay được."),onClick:()=>pe(a.playhead),children:o("Khoá tới playhead")}),j>0&&t.jsx("button",{type:"button",disabled:q,onClick:()=>pe(0),children:o("Mở khoá")})]}),t.jsx("small",{children:j>0?o("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[jn(j)]):o("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên.")})]}),_==="window"&&t.jsxs("div",{className:"shot-lock-pop",children:[t.jsxs("label",{className:"shot-mission-window",children:[t.jsx("input",{type:"checkbox",checked:A,disabled:q,onChange:re}),t.jsx("span",{children:o("Chỉ sửa đoạn")}),A&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":o("Sửa từ (giây)"),inputMode:"decimal",value:W,disabled:q,onChange:ne=>z(ne.target.value.replace(",","."))}),t.jsx("span",{children:"–"}),t.jsx("input",{"aria-label":o("Sửa đến (giây)"),inputMode:"decimal",value:Q,disabled:q,onChange:ne=>J(ne.target.value.replace(",","."))}),t.jsx("span",{children:"s"})]})]}),A&&!be&&t.jsx("small",{role:"alert",children:o("Đoạn sửa không hợp lệ (cần dài ít nhất 0,1 giây, trong thời lượng shot).")}),t.jsx("small",{children:o("Chỉ lần chạy này: Agent chỉ sửa trong đoạn đã chọn, ngoài đoạn được giữ nguyên.")})]})]}),t.jsxs("form",{className:"shot-mission-composer",onSubmit:ne=>{ne.preventDefault(),U(!1)},children:[t.jsx("textarea",{ref:k,"aria-label":o("Mô tả shot cho Agent"),maxLength:4e3,rows:3,value:v,disabled:q||n,placeholder:xe?o("Yêu cầu mới → bấm “Chạy Agent (mới)”. Muốn sửa hoặc làm tiếp phiên vừa xong thì gõ rồi bấm “Sửa / làm tiếp phiên này”."):r==="set"?o("Ví dụ: quán cà phê 8×12 m, cửa kính mặt tiền, quầy bar bên trái, 6 bàn tròn, cầu thang lên gác lửng ở cuối"):o("Ví dụ: xe đỏ chạy qua hẻm núi, camera bám sau rồi vòng ra trước, drift 2 vòng quanh một người, 12 giây, dọc 9:16"),onChange:ne=>{w(ne.target.value),ne.target.value.trim()||B(null)}}),xe&&r==="mission"&&t.jsxs("div",{className:"shot-mission-chips","aria-label":o("Làm tiếp"),children:[t.jsx("button",{type:"button",disabled:n,onClick:()=>me(o("Sửa đoạn đã làm: ")),children:o("Sửa đoạn đã làm")}),t.jsx("button",{type:"button",disabled:n,onClick:()=>me(X(T.duration),T.duration),children:o("Làm tiếp thêm 5s")}),a&&t.jsx("button",{type:"button",disabled:n,title:o("Khoá 0–{0}s rồi viết phần tiếp theo",[jn(T.duration)]),onClick:()=>{pe(T.duration),me(X(T.duration),T.duration)},children:o("Khoá phần đã ưng rồi làm tiếp")})]}),t.jsxs("div",{className:"shot-mission-row",children:[t.jsxs("label",{className:"shot-mission-ref",children:[t.jsx("input",{type:"file",accept:"image/jpeg,image/png",hidden:!0,disabled:q,onChange:ne=>{Z(ne.target.files?.[0]),ne.target.value=""}}),t.jsx("span",{children:C?`🖼 ${C.name}`:o("+ Ảnh tham chiếu (tuỳ chọn)")})]}),C&&!q&&t.jsx("button",{type:"button",onClick:()=>M(null),children:"×"}),q?t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>i.stop(),children:o("Dừng")}):t.jsxs(t.Fragment,{children:[xe&&t.jsx("button",{type:"button",className:"shot-continue",disabled:n||!v.trim(),title:o("Sửa kết quả vừa xong hoặc làm tiếp (giữ cảnh, model và lịch sử). Không bấm thì là yêu cầu mới."),onClick:()=>U(!0),children:o("↪ Sửa / làm tiếp phiên này")}),t.jsx("button",{className:"shot-primary",disabled:n||!v.trim(),title:o("Yêu cầu mới: Agent không dùng lịch sử phiên trước"),children:o("Chạy Agent (mới)")})]})]}),S&&t.jsx("small",{role:"alert",children:S})]})]})]})}const j1=1200,k1=4e3,w1=8e3,M1=12e4;function S1(e,n,s,a){let i=!1,r=null,l=0,c=!1;const u=tf(),m=()=>typeof document<"u"&&document.hidden?w1:Date.now()-l<M1?j1:k1,d=async p=>{l=Date.now();let x;try{x=await nf(p.tool,p.args||{},e)}catch(w){x={ok:!1,error:String(w?.message||w).slice(0,500)}}const{_image:g,...v}=x;try{await j0(p.id,{tabId:u,ok:x.ok!==!1,result:sf(v),...typeof g=="string"?{image:g}:{}})}catch{}p.tool==="drive_character"&&x.ok!==!1&&typeof x.start=="number"&&s?.(x.start)},f=async()=>{if(!i){if(!c){c=!0;try{const p=a?.()||void 0,{commands:x}=await v0({tabId:u,scene:n().slice(0,120),...p?{sceneId:p}:{}});for(const g of x||[]){if(i)break;await d(g)}}catch{}finally{c=!1}}i||(r=setTimeout(()=>{f()},m()))}};return f(),()=>{i=!0,r&&clearTimeout(r)}}function C1({shot:e,patch:n,progress:s,seek:a,engine:i,selected:r,select:l}){ht();const[c,u]=R.useState(!1),m=e.cameraKeys||[],d=m.find(y=>y.id===r),f=e.cameraMode==="free",p=[...m].sort((y,k)=>y.time-k.time),x=d?af(p,p.indexOf(d)):null,g=y=>n(Yi(y)),v=(y,k)=>g(m.map(T=>T.id===y?{...T,...k}:T)),w=y=>rf(e,y),C=()=>{const y=m.find(T=>Math.abs(T.time-s)<1e-6);if(y){l(y.id);return}const k=w(s);g([...m,k]),l(k.id)};R.useEffect(()=>{if(i){if(e.motion!=="path"&&!c){i.setPathEditor(void 0);return}return i.setPathEditor({selected:r,drawing:c,select:y=>{l(y);const k=m.find(T=>T.id===y);k&&a(k.time)},move:(y,k)=>v(y,{position:k}),add:y=>{const k={...w(1),position:y},T=[...m,k].map((j,L,N)=>({...j,time:N.length>1?L/(N.length-1):0}));g(T),l(k.id),a(T.at(-1)?.time||0)}}),()=>i.setPathEditor(void 0)}},[i,e.id,e.cameraKeys,e.motion,r,c]),R.useEffect(()=>{u(!1),l(null)},[e.id]);const M=y=>{const k=lf(e,y);g(k),l(k[0].id),a(0),u(!1)},S=(y,k,T,j,L)=>t.jsxs("label",{className:"shot-path-number",children:[o(y),t.jsx(gn,{"aria-label":o(y),step:"0.1",min:j,max:L,precision:3,value:k,onCommit:T})]}),I=(y,k,T)=>t.jsx("div",{className:"shot-path-vector",children:k.map((j,L)=>t.jsx("div",{children:S(`${o(y)} ${"XYZ"[L]}`,j,N=>T(k.map((A,O)=>L===O?N:A)))},L))});return t.jsxs("section",{className:"shot-path-editor",children:[t.jsx("h3",{children:o("ĐƯỜNG CHẠY CAMERA")}),t.jsx("p",{children:o("Chọn mẫu hoặc vẽ điểm trong cảnh. Chọn điểm để kéo trục màu và chỉnh độ cao.")}),t.jsxs("div",{className:"shot-camera-mode",role:"radiogroup","aria-label":o("Hướng camera"),children:[t.jsx("button",{role:"radio","aria-checked":!f,className:f?"":"shot-primary",onClick:()=>n({cameraMode:void 0}),children:o("Bám theo (Track)")}),t.jsx("button",{role:"radio","aria-checked":f,className:f?"shot-primary":"",onClick:()=>n({cameraMode:"free"}),children:o("Tự do (Free style)")})]}),t.jsx("p",{className:"shot-camera-mode-hint",children:f?o("Camera nhìn theo hướng đi của đường; chọn từng điểm để xoay hướng nhìn tuỳ ý."):o('Camera luôn nhìn về điểm "Nhìn tới" của từng key.')}),t.jsx("div",{className:"shot-add",children:[["circle","Vòng tròn"],["spiral","Xoắn ốc"],["line","Đường thẳng"],["curve","Uốn nhẹ"]].map(([y,k])=>t.jsxs("button",{onClick:()=>M(y),children:[{circle:t.jsx(Ce.circle,{}),spiral:t.jsx(Ce.spiral,{}),line:t.jsx(Ce.line,{}),curve:t.jsx(Ce.curve,{})}[y],o(k)]},y))}),t.jsxs("button",{className:c?"shot-primary":"",onClick:()=>{u(!c),c||(g([]),l(null),a(0),i?.view(!0))},children:[t.jsx(Ce.pen,{}),c?o("✓ Xong vẽ đường").replace("✓ ",""):o("✎ Vẽ đường mới bằng điểm").replace("✎ ","")]}),c&&t.jsx("p",{children:o("Nhấp vào cảnh để nối thêm điểm. Độ cao ban đầu theo camera; kéo trục Y để nâng/hạ. Điểm mới sẽ chia đều lại thời gian.")}),t.jsxs("div",{className:"shot-add",children:[t.jsxs("button",{onClick:C,children:[t.jsx(Ce.key,{}),o("+ Key tại thời điểm này").replace("+ ","")]}),t.jsx("button",{disabled:!m.length,onClick:()=>g(m.map((y,k)=>({...y,time:m.length>1?k/(m.length-1):0}))),children:o("Chia đều thời gian")})]}),m.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:e.pathSmooth!==!1,onChange:y=>n({pathSmooth:y.target.checked})})," ",o("Đường cong mượt")]}),t.jsx("div",{className:"shot-path-keys",children:m.map((y,k)=>t.jsxs("button",{className:y.id===r?"shot-primary":"",onClick:()=>{l(y.id),a(y.time)},children:["◆ ",k+1," · ",(y.time*e.duration).toFixed(1),o("s")]},y.id))})]}),d&&t.jsxs("div",{className:"shot-path-key",children:[t.jsxs("b",{children:[o("Điểm")," ",m.indexOf(d)+1]}),t.jsx("button",{onClick:()=>l(null),children:o("Bỏ chọn điểm")}),S(o("Thời điểm key (giây)"),d.time*e.duration,y=>{const k=y/e.duration;m.some(T=>T.id!==d.id&&Math.abs(T.time-k)<1e-6)||(v(d.id,{time:k}),a(k))},0,e.duration),I("Camera",d.position,y=>v(d.id,{position:y})),!f&&I(o("Nhìn tới"),d.target,y=>v(d.id,{target:y})),f&&x&&t.jsxs("div",{className:"shot-path-aim",children:[S(o("Xoay ngang (°)"),x[0],y=>v(d.id,{aim:[y,x[1]]}),-360,360),S(o("Ngẩng / cúi (°)"),x[1],y=>v(d.id,{aim:[x[0],y]}),-85,85),t.jsx("button",{disabled:!d.aim,onClick:()=>v(d.id,{aim:void 0}),children:o("Nhìn theo hướng đi")})]}),S(o("Tiêu cự key (mm)"),d.lens,y=>v(d.id,{lens:y}),14,200),S(o("Nghiêng key (°)"),d.roll,y=>v(d.id,{roll:y})),t.jsx("button",{onClick:()=>{const y=i?.captureCamera();y&&v(d.id,{position:y.position,target:y.target,lens:y.lens,roll:y.roll,...f&&y.target&&y.position?{aim:of(new ie(y.target[0]-y.position[0],y.target[1]-y.position[1],y.target[2]-y.position[2]))}:{}})},children:o("Lấy góc đang quan sát cho key")}),t.jsx("button",{onClick:()=>{g(m.filter(y=>y.id!==d.id)),l(null)},children:o("Xoá key này")})]})]})}const yu=.5,vu=60,N1=e=>Math.min(vu,Math.max(yu,Math.round(e*100)/100));function ju(e){const n=rn(e);return{aspect:[...Gl.includes(e.aspect)?[]:[o("Seedance không nhận tỷ lệ {0}; khi gửi sẽ dùng {1}.",[e.aspect,Qi(e.aspect,Gl)])],...Aa.includes(e.aspect)?[]:[o("Ảnh thật (GPT Image) không nhận tỷ lệ {0}; sẽ dùng {1}.",[e.aspect,Qi(e.aspect,Aa)])]],duration:e.duration<4?[o("Seedance 2.5 cần tối thiểu 4 giây; video camera ngắn hơn vẫn xuất bình thường.")]:[],fps:n===24||n===30?[]:[o("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[n])]}}const Lh=e=>{const n=uf(e),s=n>=1?14:14*n,a=n>=1?14/n:14;return t.jsx("span",{className:"shot-fmt-glyph","aria-hidden":"true",style:{width:s,height:a}})};function A1({shot:e,patch:n,disabled:s}){ht();const[a,i]=R.useState(null),[r,l]=R.useState(null),c=R.useRef(null),u=rn(e),m=ju(e);R.useEffect(()=>{if(!a)return;const M=S=>{c.current?.contains(S.target)||i(null)};return document.addEventListener("pointerdown",M,!0),()=>document.removeEventListener("pointerdown",M,!0)},[a]),R.useEffect(()=>{a&&c.current?.querySelector('.shot-fmt-pop [aria-checked="true"], .shot-fmt-pop button')?.focus()},[a]);const d=M=>c.current?.querySelector(`[data-fmt="${M}"]`),f=M=>{const S=a;i(null),S&&requestAnimationFrame(()=>d(S)?.focus())},p=M=>{n(M),f()},x=M=>{if(Number.isFinite(M)){const S=N1(M);S!==e.duration&&n({duration:S})}},g=()=>{if(r!==null){const M=Number(r.replace(",","."));r.trim()!==""&&x(M),l(null)}},v=M=>{if(M.key==="Escape"&&a){M.preventDefault(),M.stopPropagation(),f();return}const S=M.target.closest(".shot-fmt-pop");if(S&&["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(M.key)){M.preventDefault();const I=[...S.querySelectorAll("button")],y=I.indexOf(M.target),k=M.key==="Home"?0:M.key==="End"?I.length-1:(y+(M.key==="ArrowDown"||M.key==="ArrowRight"?1:-1)+I.length)%I.length;I[k]?.focus()}},w=[...cf,...hf.includes(e.aspect)?[e.aspect]:[]],C=o("Thời lượng shot (giây). Bước 0,5 giây; ▾ để chọn nhanh 3/5/8/10/15 giây.");return t.jsxs("div",{className:"shot-fmt",ref:c,onKeyDown:v,children:[t.jsxs("small",{children:[Number(e.lens.toFixed(1)),o("mm ·")]}),t.jsxs("div",{className:"shot-fmt-item",children:[t.jsxs("button",{type:"button","data-fmt":"aspect",className:m.aspect.length?"warn":"",disabled:s,"aria-haspopup":"menu","aria-expanded":a==="aspect","aria-label":o("Tỷ lệ khung hình: {0}",[e.aspect]),title:[o("Tỷ lệ khung hình của shot"),...m.aspect].join(`
|
|
285
285
|
`),onClick:()=>i(a==="aspect"?null:"aspect"),children:[Lh(e.aspect),e.aspect]}),a==="aspect"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":o("Tỷ lệ khung hình"),children:[w.map(M=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.aspect===M,className:e.aspect===M?"active":"",onClick:()=>p({aspect:M}),children:[Lh(M),M]},M)),m.aspect.map(M=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",M]},M))]})]}),t.jsx("span",{className:"shot-fmt-dot","aria-hidden":"true",children:"·"}),t.jsxs("div",{className:"shot-fmt-item shot-fmt-dur",role:"group","aria-label":o("Thời lượng shot (giây)"),title:C,children:[t.jsx("button",{type:"button",disabled:s||e.duration<=yu,"aria-label":o("Giảm 0,5 giây"),title:o("Giảm 0,5 giây"),onClick:()=>x(e.duration-.5),children:"−"}),t.jsx("input",{"aria-label":o("Thời lượng shot (giây)"),title:C,inputMode:"decimal",disabled:s,className:m.duration.length?"warn":"",value:r??String(Number(e.duration.toFixed(2))),onFocus:M=>M.currentTarget.select(),onChange:M=>l(M.target.value),onBlur:g,onKeyDown:M=>{if(M.key==="Enter")M.preventDefault(),g(),M.currentTarget.blur();else if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),l(null),M.currentTarget.blur();else if(M.key==="ArrowUp"||M.key==="ArrowDown"){M.preventDefault();const S=r!==null&&Number.isFinite(Number(r.replace(",",".")))?Number(r.replace(",",".")):e.duration;l(null),x(S+(M.key==="ArrowUp"?.5:-.5))}}}),t.jsx("span",{className:"shot-fmt-unit","aria-hidden":"true",children:o("s")}),t.jsx("button",{type:"button",disabled:s||e.duration>=vu,"aria-label":o("Tăng 0,5 giây"),title:o("Tăng 0,5 giây"),onClick:()=>x(e.duration+.5),children:"+"}),t.jsx("button",{type:"button","data-fmt":"dur",className:`shot-fmt-more${m.duration.length?" warn":""}`,disabled:s,"aria-haspopup":"menu","aria-expanded":a==="dur","aria-label":o("Chọn nhanh thời lượng"),title:[o("Chọn nhanh thời lượng"),...m.duration].join(`
|
|
286
286
|
`),onClick:()=>i(a==="dur"?null:"dur"),children:"▾"}),a==="dur"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":o("Chọn nhanh thời lượng"),children:[df.map(M=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.duration===M,className:e.duration===M?"active":"",onClick:()=>p({duration:M}),children:[M," ",o("giây")]},M)),m.duration.map(M=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",M]},M))]})]}),t.jsx("span",{className:"shot-fmt-dot","aria-hidden":"true",children:"·"}),t.jsxs("div",{className:"shot-fmt-item",children:[t.jsxs("button",{type:"button","data-fmt":"fps",className:m.fps.length?"warn":"",disabled:s,"aria-haspopup":"menu","aria-expanded":a==="fps","aria-label":o("Tốc độ khung hình: {0} fps",[u]),title:[o("Tốc độ khung hình (fps) khi xuất video camera"),...m.fps].join(`
|
|
287
|
-
`),onClick:()=>i(a==="fps"?null:"fps"),children:[u,o("fps")]}),a==="fps"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":o("Tốc độ khung hình (fps)"),children:[nd.map(M=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u===M,className:u===M?"active":"",title:M===40?o("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[M]):void 0,onClick:()=>p({fps:M}),children:[M," ",o("fps")]},M)),m.fps.map(M=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",M]},M))]})]})]})}function kr(e,n,s){const a=Pt();if(!a||!e.url)return null;const i=a.nodes().find(l=>l.type==="image"&&l.data.gcsUri===e.gcsUri);if(i)return i.id;const r=a.getNode(n);return a.addNode("image",{url:e.url,gcsUri:e.gcsUri,label:e.name},r?{x:r.position.x-360,y:r.position.y+s*220}:void 0,{select:!1})}function Eh(e,n){const s=e?Pt()?.getNode(e)?.data:void 0;return s?.gcsUri&&/^gs:\/\//.test(s.gcsUri)?{gcsUri:s.gcsUri,...s.url?{url:s.url}:{},name:n}:void 0}function T1(e,n,s){let a=!1;const i=e.items.map((r,l)=>{const c=r.castId?n.cast.find(m=>m.id===r.castId):void 0;if(!c)return r;const u={...r,name:c.name,color:c.color};if(r.kind==="person"&&(u.figure=c.figure?Dt(c.figure):void 0,u.look=c.look),c.reference&&(r.reference?.nodeId?Pt()?.getNode(r.reference.nodeId)?.data?.gcsUri:void 0)!==c.reference.gcsUri){const d=kr(c.reference,s,l);d&&(u.reference={nodeId:d,url:c.reference.url||"",name:c.reference.name})}return JSON.stringify(u)!==JSON.stringify(r)&&(a=!0),u});return a?{...e,items:i}:null}function L1({stage:e,nodeId:n,selected:s,disabled:a,change:i,onError:r,onSelect:l}){ht();const[c,u]=R.useState(null),[m,d]=R.useState(null),[f,p]=R.useState(""),[x,g]=R.useState(!1),v=R.useRef(null),w=e.series;R.useEffect(()=>{if(!w?.id){d(null);return}let j=!0;return k0(w.id).then(L=>{if(j&&(d(L),v.current!==L.id)){v.current=L.id;const N=T1(e,L,n);N&&i(()=>N)}}).catch(L=>r(L.message)),()=>{j=!1}},[w?.id]),R.useEffect(()=>{!w?.id&&c===null&&w0().then(j=>u(j.series)).catch(()=>u([]))},[w?.id,c]);const C=async j=>{g(!0);try{const{id:L,updatedAt:N,...A}=j;await M0(L,A),d(j)}catch(L){r(L.message)}finally{g(!1)}},M=async()=>{const j=f.trim();if(!j)return;const L={id:bt(),name:j,cast:[],locations:[],episodes:[]};await C(L),i(N=>({...N,series:{id:L.id,name:j}})),p("")},S=async()=>{if(!m||!s||!["person","model"].includes(s.kind))return;const j=s.castId&&m.cast.some(A=>A.id===s.castId)?s.castId:bt(),L=Eh(s.reference?.nodeId,s.reference?.name||s.name),N={id:j,name:s.name.slice(0,60),color:/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#baca9e",...s.kind==="person"&&s.figure?{figure:Dt(s.figure)}:{},...s.kind==="person"&&s.look?{look:s.look}:{},...L?{reference:L}:{},...s.kind==="model"&&s.model?{model:{gcsUri:s.model.gcsUri,name:s.model.name,...s.model.height?{height:s.model.height}:{}}}:{}};await C({...m,cast:[...m.cast.filter(A=>A.id!==j),N]}),i(A=>({...A,items:A.items.map(O=>O.id===s.id?{...O,castId:j}:O)})),s.reference&&!L&&r(o("Ảnh nhận diện không phải ảnh đã tải lên / tạo trên Clipoox nên không lưu vào thư viện được."))},I=j=>{const L=e.items.length,N=j.model?{...fn("model",L),model:j.model}:{...fn("person",L),...j.figure?{figure:Dt(j.figure)}:{},...j.look?{look:j.look}:{}},A=j.reference?kr(j.reference,n,L):null,O={...N,name:j.name,color:j.color,castId:j.id,...A&&j.reference?{reference:{nodeId:A,url:j.reference.url||"",name:j.reference.name}}:{}};i(_=>({..._,items:[..._.items,O]})),l(O.id)},y=async j=>{if(!m)return;const L=e.items.find(_=>_.kind==="set"&&_.set),N=(e.styleRefs||[]).flatMap(_=>{const $=Eh(_.nodeId,_.name);return $?[$]:[]}),O={id:m.locations.find(_=>_.name===j)?.id||bt(),name:j,...L?.set?{setId:L.set.id}:{},lighting:Ta(e.lighting),...N.length?{styleRefs:N}:{}};await C({...m,locations:[...m.locations.filter(_=>_.id!==O.id),O]}),i(_=>({..._,series:{..._.series,location:O.id}}))},k=j=>{const L=(j.styleRefs||[]).flatMap((N,A)=>{const O=kr(N,n,10+A);return O?[{nodeId:O,url:N.url||"",name:N.name}]:[]});i(N=>{const A=j.setId&&N.items.some(_=>_.kind==="set"&&_.set?.id===j.setId),O=j.setId&&!A?[{...fn("set",N.items.length),name:j.name,set:{id:j.setId,name:j.name}},...N.items]:N.items;return{...N,items:O,...j.lighting?{lighting:Ta(j.lighting)}:{},...L.length?{styleRefs:L}:{},series:{...N.series,location:j.id}}})},T=async j=>{if(!m||!j.trim())return;const L={id:bt(),name:j.trim().slice(0,80)};await C({...m,episodes:[...m.episodes,L]}),i(N=>({...N,series:{...N.series,episode:L.id}}))};return w?t.jsxs("div",{className:"shot-series",children:[t.jsxs("div",{className:"shot-series-row",children:[t.jsx("b",{children:w.name}),t.jsx("button",{disabled:a,onClick:()=>i(j=>({...j,series:void 0})),children:o("Bỏ gắn")})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Tập")}),t.jsxs("select",{"aria-label":o("Tập"),value:w.episode||"",disabled:a,onChange:j=>{if(j.target.value==="+"){const L=window.prompt(o("Tên tập"),`Tập ${m.episodes.length+1}`);L&&T(L);return}i(L=>({...L,series:{...L.series,episode:j.target.value||void 0}}))},children:[t.jsx("option",{value:"",children:"—"}),m.episodes.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id)),t.jsx("option",{value:"+",children:o("+ Tập mới…")})]})]}),t.jsxs("h4",{children:[o("Dàn nhân vật")," · ",m.cast.length]}),t.jsx("ul",{className:"shot-series-list",children:m.cast.map(j=>t.jsxs("li",{children:[j.reference?.url?t.jsx("img",{src:j.reference.url,alt:""}):t.jsx("span",{className:"shot-series-dot",style:{background:j.color}}),t.jsxs("span",{children:[j.name,j.figure?t.jsxs("small",{children:[" · ",j.figure.height.toFixed(2)," m"]}):null]}),t.jsx("button",{"aria-label":o("Đưa {0} vào cảnh",[j.name]),disabled:a,onClick:()=>I(j),children:"+"})]},j.id))}),t.jsx("button",{disabled:a||x||!s||!["person","model"].includes(s.kind),onClick:()=>void S(),children:s?.castId?o("Cập nhật nhân vật vào series"):o("Lưu nhân vật đang chọn vào series")}),t.jsxs("h4",{children:[o("Bối cảnh")," · ",m.locations.length]}),t.jsx("ul",{className:"shot-series-list",children:m.locations.map(j=>t.jsxs("li",{className:w.location===j.id?"active":"",children:[t.jsx("span",{className:"shot-series-dot","aria-hidden":"true",children:"⌂"}),t.jsxs("span",{children:[j.name,j.setId?t.jsxs("small",{children:[" · ",o("có set")]}):null]}),t.jsx("button",{"aria-label":o("Áp dụng bối cảnh {0}",[j.name]),disabled:a,onClick:()=>k(j),children:o("Dùng")})]},j.id))}),t.jsx("button",{disabled:a||x,onClick:()=>{const j=window.prompt(o("Tên bối cảnh"),e.items.find(L=>L.kind==="set")?.name||`Bối cảnh ${m.locations.length+1}`);j?.trim()&&y(j.trim().slice(0,60))},children:o("Lưu bối cảnh hiện tại vào series")})]})]}):t.jsxs("div",{className:"shot-series",children:[t.jsxs("select",{"aria-label":o("Chọn series"),value:"",disabled:a||!c?.length,onChange:j=>{const L=c?.find(N=>N.id===j.target.value);L&&i(N=>({...N,series:{id:L.id,name:L.name}}))},children:[t.jsx("option",{value:"",children:c===null?o("Đang tải…"):c.length?o("Gắn shot vào series…"):o("Chưa có series")}),c?.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id))]}),t.jsxs("form",{className:"shot-series-row",onSubmit:j=>{j.preventDefault(),M()},children:[t.jsx("input",{"aria-label":o("Tên series mới"),placeholder:o('Tên series mới, ví dụ "Chuyện quán cà phê"'),maxLength:80,value:f,onChange:j=>p(j.target.value),disabled:a||x}),t.jsx("button",{disabled:a||x||!f.trim(),children:o("Tạo")})]}),t.jsx("small",{className:"shot-hint",children:o("Series giữ dàn nhân vật và bối cảnh dùng chung cho mọi shot, mọi canvas. Sửa nhân vật trong series thì mọi shot dùng nhân vật đó cập nhật theo.")})]})}function E1({x:e,y:n,items:s,canPaste:a,hiddenCount:i,blenderKeys:r,renaming:l,onBlenderKeys:c,onAction:u,onRename:m,onClose:d}){const f=R.useRef(null),[p,x]=R.useState({left:e,top:n}),[g,v]=R.useState(s[0]?.name??""),w=j=>s.length>0&&s.every(j),C=s[0]?.shading,M=j=>r?j:void 0,S=s.length?[[{action:"shade-smooth",label:"Bề mặt mượt",check:"shading",checked:w(j=>j.shading==="smooth")},{action:"shade-auto",label:"Mượt tự động (30°)",check:"shading",checked:w(j=>j.shading==="auto")},{action:"shade-flat",label:"Bề mặt phẳng",check:"shading",checked:w(j=>j.shading==="flat")},...C||s.some(j=>j.shading)?[{action:"shade-reset",label:"Bề mặt như gốc",check:"shading"}]:[]],[{action:"origin-center",label:"Đặt tâm vào giữa khối",check:"origin"},{action:"origin-bottom",label:"Đặt tâm ở đáy khối",check:"origin"},...s.some(j=>j.origin)?[{action:"origin-reset",label:"Tâm như gốc",check:"origin"}]:[]],[{action:"copy",label:"Sao chép",keys:"Ctrl+C",check:"copy"},{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"duplicate",label:"Nhân bản",keys:M("Shift+D"),check:"duplicate"},{action:"duplicate-linked",label:"Nhân bản liên kết",keys:M("Alt+D"),check:"duplicate"},...s.some(j=>j.link)?[{action:"unlink",label:"Bỏ liên kết",check:"unlink"}]:[]],[{action:"mirror-x",label:"Lật theo X",check:"mirror",checked:w(j=>(j.mirror?.[0]??1)<0)},{action:"mirror-y",label:"Lật theo Y",check:"mirror",checked:w(j=>(j.mirror?.[1]??1)<0)},{action:"mirror-z",label:"Lật theo Z",check:"mirror",checked:w(j=>(j.mirror?.[2]??1)<0)},{action:"key",label:"Thêm key",keys:"K",check:"key"},{action:"physics-drop",label:"Rơi tự nhiên…",check:"physics"}],[{action:"hide",label:"Ẩn",keys:M("H"),check:"hide"},{action:"lock",label:w(j=>j.locked)?"Mở khoá":"Khoá",check:"lock"},{action:"delete",label:"Xoá",keys:M("X"),check:"delete"}],[{action:"rig",label:"AI · Auto-Rig…",check:"rig"},{action:"rig",label:"AI · Retexture",soon:!0}]]:[[{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"select-all",label:"Chọn tất cả",keys:M("A")},{action:"box-select",label:"Chọn theo vùng",keys:M("B")},{action:"unhide-all",label:"Hiện tất cả",keys:M("Alt+H")}]],I=j=>j.soon?"Sắp có":j.action==="paste"?a?null:"Chưa sao chép đối tượng nào":j.action==="unhide-all"?i?null:"Không có đối tượng nào đang ẩn":j.check?s.some(L=>!wo(L,j.check))?null:wo(s[0],j.check):null,y=s.length!==1?"Chọn một đối tượng để đổi tên":wo(s[0],"rename");R.useLayoutEffect(()=>{const j=f.current;if(!j)return;const L=j.getBoundingClientRect();x({left:Math.max(4,Math.min(e,innerWidth-L.width-4)),top:Math.max(4,Math.min(n,innerHeight-L.height-4))})},[e,n,l]),R.useEffect(()=>{const j=f.current;if(!j)return;l?j.querySelector("input[type=text]")?.select():j.querySelector("[role=menuitem]:not([disabled])")?.focus();const L=N=>{j.contains(N.target)||d()};return document.addEventListener("mousedown",L,!0),()=>document.removeEventListener("mousedown",L,!0)},[l,d]);const k=j=>{if(j.key==="Escape"){j.preventDefault(),d();return}if(j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;j.preventDefault();const L=[...f.current.querySelectorAll("[role=menuitem]:not([disabled]),[role=menuitemcheckbox]")],N=L.indexOf(document.activeElement);L[(N+(j.key==="ArrowDown"?1:-1)+L.length)%L.length]?.focus()},T=s.length>1?o("{0} đối tượng",[s.length]):s[0]?.name;return t.jsxs("div",{className:"shot-ctxmenu",role:"menu","aria-label":o("Menu đối tượng"),ref:f,style:p,onKeyDown:k,onContextMenu:j=>j.preventDefault(),children:[T&&t.jsx("div",{className:"shot-ctxmenu-title",children:T}),l?t.jsxs("form",{className:"shot-ctxmenu-rename",onSubmit:j=>{j.preventDefault(),g.trim()&&m(g.trim().slice(0,80))},children:[t.jsx("input",{type:"text","aria-label":o("Tên mới"),value:g,maxLength:80,onChange:j=>v(j.target.value)}),t.jsx("button",{type:"submit",children:o("Đổi tên")})]}):t.jsxs(t.Fragment,{children:[s.length>0&&t.jsxs("button",{type:"button",role:"menuitem",disabled:!!y,title:y?o(y):void 0,onClick:()=>u("rename"),children:[t.jsx("span",{children:o("Đổi tên…")}),r&&t.jsx("kbd",{children:"F2"})]}),S.map((j,L)=>t.jsx("div",{className:"shot-ctxmenu-group",role:"group",children:j.map((N,A)=>{const O=I(N);return t.jsxs("button",{type:"button",role:"menuitem",disabled:!!O,title:O?o(O):void 0,"aria-checked":N.checked===void 0?void 0:N.checked,className:N.checked?"checked":"",onClick:()=>u(N.action),children:[t.jsxs("span",{children:[N.checked?"✓ ":"",o(N.label),N.soon?t.jsxs("small",{children:[" · ",o("Sắp có")]}):null]}),N.keys&&t.jsx("kbd",{children:N.keys})]},N.action+A)})},L)),t.jsxs("button",{type:"button",className:"shot-ctxmenu-keys",role:"menuitemcheckbox","aria-checked":r,onClick:()=>c(!r),children:[t.jsxs("span",{children:[r?"☑":"☐"," ",o("Phím tắt kiểu Blender")]}),t.jsx("small",{children:"G R S · Shift+D · X · H · A · B"})]})]})]})}const I1=[{id:"above",label:"Thả từ trên cao"},{id:"here",label:"Từ vị trí hiện tại"}],R1=[{id:"bouncy",label:"Nảy nhiều"},{id:"normal",label:"Vừa"},{id:"heavy",label:"Nặng"}];function F1({count:e,start:n,left:s,busy:a,onRun:i,onClose:r}){const[l,c]=R.useState({mode:"above",bounciness:"normal",duration:3}),u=R.useRef(null);R.useEffect(()=>{u.current?.querySelector("button.active")?.focus()},[]);const m=Math.min(l.duration,s);return t.jsxs("form",{ref:u,className:"shot-ctxmenu shot-drop",role:"dialog","aria-label":o("Rơi tự nhiên"),onSubmit:d=>{d.preventDefault(),!a&&s>=.25&&i(l)},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),r())},children:[t.jsx("div",{className:"shot-ctxmenu-title",children:o("Rơi tự nhiên · {0} đối tượng",[e])}),t.jsx("div",{className:"shot-seg shot-seg-2",role:"group","aria-label":o("Bắt đầu rơi"),children:I1.map(d=>t.jsx("button",{type:"button",className:l.mode===d.id?"active":"","aria-pressed":l.mode===d.id,onClick:()=>c({...l,mode:d.id}),children:o(d.label)},d.id))}),t.jsx("div",{className:"shot-seg",role:"group","aria-label":o("Độ nảy"),children:R1.map(d=>t.jsx("button",{type:"button",className:l.bounciness===d.id?"active":"","aria-pressed":l.bounciness===d.id,onClick:()=>c({...l,bounciness:d.id}),children:o(d.label)},d.id))}),t.jsxs("label",{className:"shot-drop-row",children:[o("Thời lượng")," ",t.jsxs("b",{children:[l.duration,o("s")]}),t.jsx("input",{type:"range",min:1,max:6,step:.5,value:l.duration,"aria-label":o("Thời lượng rơi"),onChange:d=>c({...l,duration:+d.target.value})})]}),t.jsx("small",{className:"shot-drop-hint",children:s<.25?o("Đầu phát đang ở cuối shot — kéo về trước rồi thử lại."):o("Từ {0}s đến {1}s · ghi thành key thường, Ctrl+Z để hoàn tác",[n.toFixed(1),(n+m).toFixed(1)])}),t.jsxs("div",{className:"shot-drop-actions",children:[t.jsx("button",{type:"button",onClick:r,children:o("Huỷ")}),t.jsx("button",{type:"submit",className:"shot-primary",disabled:a||s<.25,children:a?o("Đang mô phỏng…"):o("Mô phỏng")})]})]})}Un.plateUrl=e=>A0({gcsUri:e.gcsUri,url:e.url});const Hi=[["person","Nhân vật"],["box","Hộp"],["sphere","Cầu"],["cylinder","Trụ"],["wall","Tường"],["platform","Bục"],["floor","Sàn"]],vo=[["scene","Dựng cảnh",t.jsx(Ce.scene,{},"scene")],["objects","Đối tượng",t.jsx(Ce.objects,{},"objects")],["material","Vật liệu",t.jsx(Ce.material,{},"material")],["rigging","Rigging · gắn xương",t.jsx(u1,{},"rigging")],["modeling","Dựng model",t.jsx(wd,{},"modeling")],["camera","Camera & shot",t.jsx(Ce.camera,{},"camera")],["light","Ánh sáng cảnh",t.jsx(Ce.light,{},"light")],["shots","Danh sách shot",t.jsx(Ce.film,{},"shots")],["notes","Ghi chú 3D",t.jsx(Ce.note,{},"notes")],["series","Series",t.jsx(Ce.series,{},"series")],["fx","Hiệu ứng",t.jsx(Ce.fx,{},"fx")],["fxedit","Sửa hiệu ứng",t.jsx(Ce.pen,{},"fxedit")],["mixfx","Mix FX",t.jsx(Ce.mixfx,{},"mixfx")]],Wi={drawer:300,right:320,timeline:210},P1={person:t.jsx(Ce.person,{}),box:t.jsx(Ce.box,{}),sphere:t.jsx(Ce.sphere,{}),cylinder:t.jsx(Ce.cylinder,{}),wall:t.jsx(Ce.wall,{}),platform:t.jsx(Ce.platform,{}),floor:t.jsx(Ce.floor,{}),model:t.jsx(Ce.cube,{}),proxy:t.jsx(Ce.cube,{}),splat:t.jsx(Ce.image,{}),prop:t.jsx(Ce.key,{}),fx:t.jsx(Ce.fx,{})},To={shoulderL:"Vai trái",shoulderR:"Vai phải",elbowL:"Khuỷu trái",elbowR:"Khuỷu phải",hipL:"Hông trái",hipR:"Hông phải",kneeL:"Gối trái",kneeR:"Gối phải",head:"Hướng đầu",lean:"Nghiêng thân",shoulderOutL:"Dang vai trái",shoulderOutR:"Dang vai phải",hipOutL:"Dang hông trái",hipOutR:"Dang hông phải",wristL:"Cổ tay trái",wristR:"Cổ tay phải",ankleL:"Cổ chân trái",ankleR:"Cổ chân phải",spineTwist:"Xoay cột sống"};function Hn({label:e,value:n,onChange:s,min:a=-100,max:i=100,step:r=.1}){return ht(),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o(e)}),t.jsx(gn,{"aria-label":o(e),precision:2,value:n,min:a,max:i,step:r,onCommit:s})]})}function jo({label:e,root:n,bend:s,upper:a,lower:i,onChange:r}){ht();const l=R.useRef(null),c=d0(n,s,a,i),u=a+i,m=f=>{const p=l.current.getBoundingClientRect(),x=((f.clientX-p.left)/p.width*2-1)*u,g=((f.clientY-p.top)/p.height*2-1)*u,v=u0(x,g,a,i);r(Math.round(v.root),Math.round(v.bend))},d=f=>{f.preventDefault(),m(f);const p=g=>m(g),x=()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",x)};window.addEventListener("mousemove",p),window.addEventListener("mouseup",x)};return t.jsxs("div",{children:[t.jsx("small",{children:o(e)}),t.jsx("div",{ref:l,className:"shot-ik-pad",onMouseDown:d,children:t.jsx("i",{style:{left:`${50+c.forward/u*50}%`,top:`${50+c.down/u*50}%`}})})]})}const qi={headPitch:"Cúi / ngẩng đầu",headRoll:"Nghiêng đầu",eyeYaw:"Mắt liếc trái / phải",eyePitch:"Mắt liếc lên / xuống",blink:"Nhắm mắt",gripL:"Nắm tay trái",indexL:"Ngón trỏ trái",middleL:"Ngón giữa trái",ringL:"Ngón áp út trái",pinkyL:"Ngón út trái",thumbL:"Ngón cái trái",spreadL:"Xoè ngón tay trái",wristTwistL:"Xoay cổ tay trái",wristSideL:"Nghiêng cổ tay trái",gripR:"Nắm tay phải",indexR:"Ngón trỏ phải",middleR:"Ngón giữa phải",ringR:"Ngón áp út phải",pinkyR:"Ngón út phải",thumbR:"Ngón cái phải",spreadR:"Xoè ngón tay phải",wristTwistR:"Xoay cổ tay phải",wristSideR:"Nghiêng cổ tay phải",smile:"Biểu cảm: cười",angry:"Biểu cảm: giận dữ",surprise:"Biểu cảm: ngạc nhiên",sad:"Biểu cảm: buồn",pain:"Biểu cảm: đau"},$1=(e,n)=>{if(e[n]!==void 0)return e[n];const s=n.endsWith("L")?"L":"R",a=n.slice(0,-1);return a0.includes(a)?Math.round(o0(e,s)[a]):0},O1=(e,n,s)=>td(e,n,s);function D1(e,n){return Object.keys(To).every(s=>(e[s]||0)===(n[s]||0))}const Ih="clipoox.shot.objectClipboard",z1=e=>e.kind==="person"||e.kind==="model"&&e.skeleton==="native";function rj({nodeId:e,headless:n=!1,background:s}){ht();const[a,i]=R.useState(null),[r,l]=R.useState(!1),c=R.useRef(!1),[u,m]=R.useState(!1),[d,f]=R.useState(null),[p,x]=R.useState(!1),g=R.useRef([]),[v,w]=R.useState(!1),[C,M]=R.useState(!1),[S,I]=R.useState(!1),[y,k]=R.useState(null),[T,j]=R.useState([]),[L,N]=R.useState(!1),[A,O]=R.useState(null),[_,$]=R.useState(!1),[P,W]=R.useState(!1),[z,Q]=R.useState(()=>{const h=Pt()?.getNode(e)?.data.shotScene;if(h)return ec(tc(h));const b=mf();return b.items=b.items.map((E,F)=>({...E,name:`${o(Hi.find(([K])=>K===E.kind)?.[1]||"Model")} ${F+1}`})),b}),[J,V]=R.useState(z.items[0]?.id||null),[B,q]=R.useState([]),[D,ee]=R.useState("translate"),[Z,xe]=R.useState(()=>{try{const h=localStorage.getItem("clipoox.shot.panel");return vo.some(b=>b[0]===h)?h:null}catch{return null}}),[be,U]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.railWide")==="1"}catch{return!1}}),[pe,me]=R.useState(()=>{try{return{...Wi,...JSON.parse(localStorage.getItem("clipoox.shot.layout")||"{}")}}catch{return Wi}}),[X,re]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.tools")!=="0"}catch{return!0}}),[ue,Ee]=R.useState(!1),[ye,ne]=R.useState(pf),[Ie,ze]=R.useState(Wr),[we,de]=R.useState([]),[H,se]=R.useState(!1),[he,ce]=R.useState(""),[Pe,Be]=R.useState([]),[ot,G]=R.useState(null),[Se,le]=R.useState(!1),[$e,Le]=R.useState(1),[Te,Je]=R.useState(!1),[ke,Ue]=R.useState(0),[At,qe]=R.useState(null),[mt,kt]=R.useState({}),Xe=h=>{V(h),q([])},it=J?[J,...B.filter(h=>h!==J)]:[],xt=R.useRef(it);xt.current=it;const wt=h=>{V(h[0]??null),q(h.slice(1))},nn=(h,b=!1)=>{const E=xt.current;if(!b||!h)return wt(h?[h]:b?E:[]);wt(E.includes(h)?E.filter(F=>F!==h):[h,...E])},cn=R.useRef(nn);cn.current=nn;const[_t,rt]=R.useState(null),[Tt,Rt]=R.useState(!1),sn=R.useCallback(()=>rt(null),[]),[Sn,Ns]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.blenderKeys")!=="0"}catch{return!0}}),As=h=>{Ns(h);try{localStorage.setItem("clipoox.shot.blenderKeys",h?"1":"0")}catch{}},[Pn,an]=R.useState({on:!1}),xn=R.useRef("keys"),[oe,Ne]=R.useState(!1),[Oe,Re]=R.useState(null),[_e,Ze]=R.useState(null),[nt,et]=R.useState({mode:"all",slot:null}),Ge=R.useRef(null),Ye=R.useRef(ke);Ye.current=ke,R.useEffect(()=>{At&&J!==At&&qe(null)},[J,At]);const lt=R.useRef(null),ct=R.useRef(null),Ke=R.useRef(null),vt=R.useRef(null),je=R.useRef(null),Lt=R.useRef(null),Bt=R.useRef(null),Ae=R.useRef(z),Yt=R.useRef([]),hn=R.useRef([]),Et=dt(h=>h.saveError),Fe=dt(h=>h.saveState),pt=yi(h=>h.close);Ae.current=z;const qt=dt(h=>h.canvasId),bn=Ul(h=>h.conflict),$n=Ul(h=>h.reloading);R.useEffect(()=>n||!qt?void 0:ff(qt,e,h=>{const b=ec(tc(h));Yt.current=[],hn.current=[],Ae.current=b,Q(b)}),[qt,e,n]),gf(n?null:qt,e,()=>dt.getState().saveState!=="saved");const Me=h=>{const b=Ae.current;Yt.current.push(b),Yt.current.length>60&&Yt.current.shift(),hn.current=[];const E={...$f(b,h(b)),revision:b.revision+1};Ae.current=E,Q(E)},On={getStage:()=>Ae.current,setStage:Me,engine:()=>je.current},Ts=h=>{const{item:b,fingers:E}=Of(h,Ae.current.items.length),F=Oe?Ae.current.items.find(Y=>Y.id===Oe&&Y.kind==="person"):void 0,K=F?{...b,id:F.id,name:F.name,position:F.position,rotation:F.rotation,...F.hidden?{hidden:!0}:{}}:b;Me(Y=>({...Y,items:F?Y.items.map(ae=>ae.id===F.id?K:ae):[...Y.items,K]})),Xe(K.id),W(!1),Re(null),E&&K.rig&&mc(On,K.id,K.rig)};R.useEffect(()=>{if(!Te)return;const h=yi.getState().fitFingers;if(!(!h||h.node!==e)){yi.setState({fitFingers:null});for(const b of h.items){const E=Ae.current.items.find(F=>F.id===b);E?.rig&&mc(On,b,E.rig)}}},[Te,e]);const Vn=h=>{A&&($(!1),Ue(A.time),h&&Me(b=>Ti(b,A.plan)),A.done(h),O(null))},He=(h,b)=>{$(!1),Me(E=>Qt(E,h,b))},Qt=(h,b,E)=>{{const F=h.shots.find(ge=>ge.id===h.activeShot),K=h.items.find(ge=>ge.id===b),Y=K.kind==="fx"?K.fx?.attach:void 0;if(Y&&!(Y.hand&&Y.tip)&&(E.position||E.rotation)){if(Yh(K,F)){const ge=Ro(h,b,Ye.current,{position:E.position,yaw:E.rotation?.[1]});return E.scale?{...ge,items:ge.items.map(We=>We.id===b?{...We,scale:E.scale}:We)}:ge}return{...h,items:h.items.map(ge=>ge.id===b?{...ge,...E.scale?{scale:E.scale}:{},...E.rotation?{rotation:[ge.rotation[0],E.rotation[1],ge.rotation[2]]}:{},fx:{...ge.fx,attach:{...Y,...E.position?{offset:E.position}:{}}}}:ge)}}const ae=F.objectKeys?.[b]||[],ve=!!E.pose&&ae.some(ge=>ge.pose);if(ae.length&&(E.position||E.rotation||E.scale||ve)){const ge={...Tn(K,F,Ye.current),...E},We=ae,De=We.find(ft=>Math.abs(ft.time-Ye.current)<1e-6),Ve={...De,id:De?.id||bt(),time:Ye.current,position:ge.position,rotation:ge.rotation,scale:ge.scale,...ve?{pose:E.pose}:{}};return{...h,shots:h.shots.map(ft=>ft.id===h.activeShot?{...ft,objectKeys:{...ft.objectKeys,[b]:[...We.filter(jt=>jt.id!==Ve.id),Ve].sort((jt,yn)=>jt.time-yn.time)}}:ft)}}return K.kind==="fx"&&K.fx&&E.position&&!E.fx&&(E={...E,fx:Df(K.fx,K.position,E.position)}),{...h,items:h.items.map(ge=>ge.id===b?{...ge,...E}:ge)}}},Ft=(h,b)=>{const E={...In[b]};if(!!!Ae.current.shots.find(Y=>Y.id===Ae.current.activeShot)?.objectKeys?.[h.id]?.length&&!h.hold&&je.current){if(Si(E)==="sit"){const Y=je.current.sitSnap(h);if(Y)return He(h.id,{pose:E,...Y})}else if(Si(h.pose)==="sit"&&Si(E)==="stand")return He(h.id,{pose:E,position:je.current.standUp(h).position})}He(h.id,{pose:E})},Gt=h=>{const b=h.filter(E=>E.fix&&!E.locked);b.length&&($(!1),Me(E=>({...E,items:E.items.map(F=>{const K=b.find(Y=>Y.itemId===F.id)?.fix;return K?{...F,position:K.position,...K.rotation?{rotation:K.rotation}:{}}:F})})))},Dn=h=>{$(!1),Me(b=>{const E=b.shots.find(De=>De.id===b.activeShot),F=b.items.find(De=>De.id===h),K=E.objectKeys?.[h]||[],Y=Ye.current,ae=Tn(F,E,Y),ve=(De,Ve)=>{const ft=Tn(F,E,De),jt=K.find(yn=>Math.abs(yn.time-De)<1e-6);return{...jt,id:jt?.id||bt(),time:De,position:ft.position,rotation:ft.rotation,scale:ft.scale,pose:structuredClone(Ve)}};let ge=[...K];if(!K.some(De=>De.pose)&&Y>1e-6){const De=ve(0,F.pose);ge=[...ge.filter(Ve=>Ve.id!==De.id),De]}const We=ve(Y,ae.pose);return ge=[...ge.filter(De=>De.id!==We.id),We].sort((De,Ve)=>De.time-Ve.time),{...b,shots:b.shots.map(De=>De.id===b.activeShot?{...De,objectKeys:{...De.objectKeys,[h]:ge}}:De)}})},us=h=>{$(!1),Me(b=>{const K=(b.shots.find(Y=>Y.id===b.activeShot).objectKeys?.[h]||[]).map(Y=>Math.abs(Y.time-Ye.current)<1e-6&&Y.pose?(({pose:ae,poseEase:ve,...ge})=>ge)(Y):Y);return{...b,shots:b.shots.map(Y=>Y.id===b.activeShot?{...Y,objectKeys:{...Y.objectKeys,[h]:K}}:Y)}})},qa=(h,b)=>{$(!1),Me(E=>{const Y=(E.shots.find(ae=>ae.id===E.activeShot).objectKeys?.[h]||[]).map(ae=>Math.abs(ae.time-Ye.current)<1e-6&&ae.pose?b==="smooth"?(({poseEase:ve,...ge})=>ge)(ae):{...ae,poseEase:b}:ae);return{...E,shots:E.shots.map(ae=>ae.id===E.activeShot?{...ae,objectKeys:{...ae.objectKeys,[h]:Y}}:ae)}})},ms=R.useRef(null),[Ut,Ga]=R.useState(null),[ps,ku]=R.useState(1),[Ur,wu]=R.useState(!0),[Xr,Vr]=R.useState(!1),Mu=async h=>{if(h){ce(""),Vr(!0);try{if(h.size>60*1024*1024)throw new Error(o("File mocap tối đa 60 MB."));Ga(await zf(h.name,await h.arrayBuffer()))}catch(b){Ga(null),ce(b.message)}finally{Vr(!1)}}},Yr=async h=>{if(_e)return;$(!1),ce(""),Ze({kind:h,pct:0});const b=(E,F)=>Ze({kind:h,pct:Math.round(E/F*100)});try{const E=Ae.current;if(h==="follow"){const F=E.items.find(ve=>ve.id===J&&ve.kind==="person"),K=F??E.items.find(ve=>ve.kind==="person");if(!K)throw new Error(o("Cảnh chưa có người đứng thế để bám theo."));const{followPlate:Y}=await Wn(async()=>{const{followPlate:ve}=await import("./plateFollow-CNfi4xuP.js");return{followPlate:ve}},__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10])),ae=await Y(E,K.id,{newId:bt,progress:b});Me(()=>ae.stage),dt.getState().toast(o("{0} đã bám theo người trong video: {1}/{2} khung thấy người.",[K.name,ae.found,ae.frames]),"ok")}else{const{trackPlateCamera:F}=await Wn(async()=>{const{trackPlateCamera:Y}=await import("./plateCamera-A2E_WO_x.js");return{trackPlateCamera:Y}},__vite__mapDeps([13,2,3,1,4,5,6,7,8,9,10,14,15])),K=await F(E,{newId:bt,progress:b});Me(()=>K.stage),dt.getState().toast(K.mode==="travel"?o("Đã lấy camera từ video: camera đi {0} m, quay {1}°.",[K.travel,K.pan]):o("Đã lấy camera từ video: {0} key, quay {1}°.",[K.keys,K.pan]),"ok")}}catch(E){const F=E.message;ce(F==="no-person-in-plate"?o("Không thấy người trong video nền."):F==="camera-not-found"?o("Không bám được camera: nền quá ít chi tiết hoặc khung hình toàn vật thể chuyển động."):F)}finally{Ze(null)}},Su=async()=>{const{shotBlenderScript:h}=await Wn(async()=>{const{shotBlenderScript:F}=await import("./plateCamera-A2E_WO_x.js");return{shotBlenderScript:F}},__vite__mapDeps([13,2,3,1,4,5,6,7,8,9,10,14,15])),b=new Blob([h(Ae.current)],{type:"text/x-python"}),E=document.createElement("a");E.href=URL.createObjectURL(b),E.download=`${(fe.name||"shot").replace(/[^\w-]+/g,"_")}-camera.py`,E.click(),setTimeout(()=>URL.revokeObjectURL(E.href),4e3)},Cu=h=>{if(!Ut)return;$(!1);const b=Ae.current,E=b.items.find(De=>De.id===h),F=b.shots.find(De=>De.id===b.activeShot),K=Ye.current,Y=is(E,F,K),ae=(1-K)*F.duration*ps,ve=_f(Ut,15*ps,0,Math.min(Ut.duration,ae)).map(De=>({...De,time:De.time/ps})),ge=.93*Bf(E)*E.scale[1],We=Kf(b,h,Hf(ve,{position:Y.position,yaw:Y.rotation[1],hipHeight:ge},Ur),K,bt);if(!We.keys){ce(o("Không còn đủ thời lượng shot sau playhead để đặt mocap."));return}Me(()=>We.stage),dt.getState().toast(o("Đã áp mocap {0}: {1} key · {2}s",[Ut.name,We.keys,We.seconds]),"ok")},[Qo,Qr]=R.useState(!0),[Zo,Zr]=R.useState(!1),Jo=async(h,b)=>{if($(!1),b.mocap)try{await Lr(b.id)}catch(ae){ce(o("Không tải được dữ liệu mocap: {0}",[ae.message]));return}const E=Ae.current,F=E.shots.find(ae=>ae.id===E.activeShot),K=Ye.current,Y=Wf(E,h,b,{start:K,newId:bt,colliders:je.current?.placementColliders(),camera:F.position,loop:Qo,mirror:Zo});if(!Y.ok){ce(Y.error.startsWith("not enough")?o("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."):Y.error);return}if(!Y.keys){ce(o("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."));return}Me(()=>Y.stage),dt.getState().toast(o('Đã áp "{0}" · {1}s',[Na(b),Y.seconds])+(Y.notes.length&&Ys()==="vi"?` · ${Y.notes[0]}`:""),"ok")},Jr=(h,b,E)=>{$(!1),Me(F=>{const K=ve=>(({hold:ge,...We})=>We)(ve),Y=F.items.find(ve=>ve.id===h);let ae=F.items.map(ve=>ve.hold?.by===h&&ve.hold.hand===b?{...K(ve),position:[Y.position[0]+(b==="R"?.4:-.4),0,Y.position[2]]}:ve);if(E.startsWith("item:"))ae=ae.map(ve=>ve.id===E.slice(5)?{...ve,hold:{by:h,hand:b}}:ve);else if(E.startsWith("prop:")){const ve=E.slice(5);ae=[...ae,{...fn("prop",ae.length),name:Ma[ve].label,prop:{kind:ve},color:"#8a939b",hold:{by:h,hand:b}}]}return{...F,items:ae}})},[Nu,el]=R.useState(""),Au=()=>{$(!1);let h=[];Me(E=>{const F=qf(E);return h=F.outcomes,F.stage});const b=E=>h.filter(F=>F.result===E).length;el(h.length?o("{0} đòn · {1} trúng · {2} bị đỡ · {3} trượt",[h.length,b("head")+b("body"),b("blocked"),b("miss")])+(b("miss")?" — "+h.filter(E=>E.result==="miss").map(E=>o("{0}s thiếu {1} m",[E.time_s,E.gap_m])).join(", "):""):o('Chưa có đòn nào: đặt key tư thế kiểu "Ra đòn nhanh" giữa hai người.'))},Tu=()=>{$(!1),Me(Gf),el("")},tl=h=>{const b=Ae.current.items.find(E=>E.id===h);!b||b.locked||H||($(!1),Me(E=>({...E,items:E.items.filter(F=>F.id!==h),shots:E.shots.map(F=>({...F,objectKeys:Object.fromEntries(Object.entries(F.objectKeys||{}).filter(([K])=>K!==h)),...F.fxTiming?{fxTiming:Object.fromEntries(Object.entries(F.fxTiming).filter(([K])=>K!==h))}:{}}))})),y?.row===h&&k(null),j(E=>E.filter(F=>F.row!==h)),Xe(E=>E===h?null:E))},nl=R.useRef(""),Ua=()=>{let h=nl.current;try{h=localStorage.getItem(Ih)||h}catch{}return h?Uf(h):null},sl=()=>{const h=xt.current;if(!h.length)return;const b=h0(Ae.current,h);nl.current=b,xn.current="objects";try{localStorage.setItem(Ih,b)}catch{}},al=()=>{const h=Ua();if(!h||H)return;$(!1);let b=[];Me(E=>{const F=l0(E,h,bt);return b=F.ids,{...F.stage,items:F.stage.items.map(K=>b.includes(K.id)?c0(K):K)}}),wt(b)},Xa=h=>{const b=xt.current;if(!b.length||H)return;$(!1);let E=[];Me(F=>{const K=r0(F,b,{linked:h,newId:bt});return E=K.ids,K.stage}),E.length&&wt(E)},ei=()=>{const h=xt.current.filter(b=>!Ae.current.items.find(E=>E.id===b)?.locked);!h.length||H||($(!1),Me(b=>i0(b,h)),y&&h.includes(y.row)&&k(null),j(b=>b.filter(E=>!h.includes(E.row))),wt(xt.current.filter(b=>!h.includes(b))))},ti=(h,b,E)=>{h.length&&($(!1),Me(F=>({...F,items:F.items.map(K=>h.includes(K.id)?{...K,[b]:E}:K)})))},ol=()=>{const h=xt.current;h.length&&(ti(h,"hidden",!0),wt([]))},il=()=>ti(Ae.current.items.filter(h=>h.hidden).map(h=>h.id),"hidden",!1),rl=()=>wt(Ae.current.items.filter(h=>!h.hidden&&!h.locked).map(h=>h.id)),ni=h=>{const b=je.current,E=xt.current.filter(F=>!wo(Ae.current.items.find(K=>K.id===F),"origin"));!b||!E.length||($(!1),Me(F=>E.reduce((K,Y)=>{if(h==="reset")return Jl(K,Y,null,!0);const ae=b.builtBounds(Y),ve=K.items.find(De=>De.id===Y);if(!ae||!ve)return K;const ge=ve.origin||[0,0,0],We=[(ae.min[0]+ae.max[0])/2,h==="bottom"?ae.min[1]:(ae.min[1]+ae.max[1])/2,(ae.min[2]+ae.max[2])/2];return Jl(K,Y,We.map((De,Ve)=>De-ge[Ve]))},F)))},ll=()=>{const h=xt.current;if(h.length===1)return oi(h[0]);if(!h.length)return;const b=Ye.current;$(!1),Me(E=>{const F=E.shots.find(Y=>Y.id===E.activeShot),K={...F.objectKeys};for(const Y of h){const ae=E.items.find(Ve=>Ve.id===Y);if(!ae||ae.locked||ae.hold||ae.kind==="fx"&&ae.fx?.attach)continue;const ve=Tn(ae,F,b),ge=K[Y]||[],We=ge.find(Ve=>Math.abs(Ve.time-b)<1e-6),De={...We,id:We?.id||bt(),time:b,position:ve.position,rotation:ve.rotation,scale:ve.scale};K[Y]=[...ge.filter(Ve=>Ve.id!==De.id),De].sort((Ve,ft)=>Ve.time-ft.time)}return{...E,shots:E.shots.map(Y=>Y.id===E.activeShot?{...Y,objectKeys:K}:Y)}})},si=(h,b,E)=>{H||A||(h&&!xt.current.includes(h)&&nn(h),rt({x:b,y:E,scene:!h}))},cl=R.useRef(si);cl.current=si;const Lu=()=>{const h=lt.current?.getBoundingClientRect();rt({x:h?h.left+h.width/2-110:200,y:h?h.top+h.height/3:200,renaming:!0})},Eu=h=>{const b=xt.current;if(h==="rename"){rt(E=>E&&{...E,renaming:!0});return}switch(rt(null),h){case"shade-smooth":case"shade-auto":case"shade-flat":case"shade-reset":{const E=h==="shade-reset"?null:h.slice(6);$(!1),Me(F=>Yf(F,b,E));return}case"origin-center":return ni("center");case"origin-bottom":return ni("bottom");case"origin-reset":return ni("reset");case"copy":return sl();case"paste":return al();case"duplicate":return Xa(!1);case"duplicate-linked":return Xa(!0);case"unlink":$(!1),Me(E=>Vf(E,b));return;case"mirror-x":case"mirror-y":case"mirror-z":$(!1),Me(E=>Xf(E,b,h.slice(7)));return;case"key":return ll();case"physics-drop":$(!1),Rt(!0);return;case"hide":return ol();case"lock":return ti(b,"locked",!b.every(E=>Ae.current.items.find(F=>F.id===E)?.locked));case"delete":return ei();case"rig":{const E=b.find(F=>Ae.current.items.find(K=>K.id===F)?.kind==="model");E&&(Xe(E),zn("rigging"));return}case"select-all":return rl();case"unhide-all":return il();case"box-select":return an({on:!0})}},Iu=async h=>{const b=Ae.current,E=b.shots.find(Ve=>Ve.id===b.activeShot),F=Ye.current,K=xt.current,Y=await Wn(()=>import("./rotoMaskStore-pxpRt5Cj.js").then(Ve=>Ve.W),__vite__mapDeps([7,1,3])),ae=K.map(Ve=>b.items.find(ft=>ft.id===Ve)).filter(Ve=>!!Ve&&!Y.dropUnavailable(Ve)&&!(Ve.kind==="prop"&&Ve.prop?.kind==="ball"&&E.ball?.[Ve.id]?.length)).slice(0,Y.MAX_PHYSICS_BODIES);if(!ae.length){Rt(!1),ce(o("Không có đối tượng nào rơi được trong vùng chọn (nhân vật, hiệu ứng, sàn, đồ đang cầm hay đã khoá thì không)."));return}const ve=F,ge=Math.min(h.duration,(1-ve)*E.duration),We=je.current,De=ae.map(Ve=>Ve.id);se(!0),ce("");try{const Ve=We?.physicsShapes(De)??{},ft=(We?.placementColliders()??[]).filter(It=>!De.includes(It.itemId)),jt=Object.fromEntries(ae.map(It=>[It.id,(E.objectKeys?.[It.id]||[]).filter(Zt=>Zt.time<ve-1e-6).sort((Zt,xs)=>Zt.time-xs.time).pop()])),yn=ae.map(It=>{const Zt=Tn(It,E,ve);return{id:It.id,position:Zt.position,rotation:Zt.rotation,shape:Y.shapeKind(It),...Ve[It.id]??Y.fallbackShape(It)}}),Kt=await Y.bakeDrop({bodies:yn,statics:ft,mode:h.mode,bounciness:h.bounciness,duration:ge,start:ve*E.duration,shotDuration:E.duration,seed:De.join(","),before:jt,seam:E.lockUntil?E.lockUntil/E.duration:null}),dn=Object.fromEntries(ae.map(It=>[It.id,Tn(It,E,ve).scale]));Me(It=>Y.applyDropKeys(It,E.id,Kt.tracks,{scale:dn,newId:bt,lifted:h.mode==="above"})),Rt(!1)}catch(Ve){ce(o("Không mô phỏng được: {0}",[Ve.message]))}finally{se(!1)}},Ru=h=>{const b=h.code;return h.shiftKey&&!h.altKey&&b==="KeyD"?(Xa(!1),!0):h.altKey&&!h.shiftKey&&b==="KeyD"?(Xa(!0),!0):h.altKey&&!h.shiftKey&&b==="KeyH"?(il(),!0):h.altKey&&!h.shiftKey&&b==="KeyA"?(wt([]),!0):h.altKey||h.shiftKey?!1:b==="KeyG"||b==="KeyR"||b==="KeyS"&&!r?(ee(b==="KeyG"?"translate":b==="KeyR"?"rotate":"scale"),!0):b==="KeyX"?(Z==="rigging"&&Ge.current?.del()||ei(),!0):b==="KeyH"?(ol(),!0):b==="KeyA"?(rl(),!0):b==="KeyB"?(an({on:!0}),!0):b==="F2"&&xt.current.length===1?(Lu(),!0):!1},Va=(h=!1)=>{const b=h?hn.current:Yt.current,E=h?Yt.current:hn.current,F=b.pop();F&&(E.push(Ae.current),Ae.current=F,Q(F))};R.useEffect(()=>{au()},[]),R.useEffect(()=>{je.current?.setPlatePlaying(_)},[_]),R.useEffect(()=>{Wn(()=>import("./videoExport-l5MGvMn_.js"),__vite__mapDeps([16,2,3,1,4,5,6,7,8,9,10,17,18,19])).catch(()=>{})},[]),R.useEffect(()=>{try{je.current=new Un(lt.current,vt.current,(h,b)=>cn.current(h,b),(h,b)=>He(h,b),S0,ce,h=>C0(h).then(b=>b.recipe)),je.current.onContext=(h,b,E)=>cl.current(h,b,E),je.current.commitMany=h=>{$(!1),Me(b=>h.reduce((E,F)=>Qt(E,F.id,F.patch),b))},je.current.setCameraEditor({select:h=>{l(h&&!c.current),h&&(Xe(null),i(null),ee(b=>b==="scale"?"translate":b))},commit:h=>yt(h)}),je.current.sync(Ae.current,J),Je(!0)}catch(h){ce(`Không khởi tạo được 3D: ${h.message}`)}return()=>je.current?.dispose()},[]),R.useEffect(()=>{je.current?.sync(A?.stage||z,A?null:J,A?[]:B)},[z,J,B,A]),R.useEffect(()=>{const h={getStage:()=>Ae.current,setStage:F=>{$(!1),Me(F)},engine:()=>je.current,timelineClip:F=>dt.getState().clips.find(K=>K.id===F),undo:(F,K)=>{let Y=0;for(let ae=0;ae<K;ae++){const ve=Ae.current;if(Va(F),Ae.current===ve)break;Y++}return Y},...n?{}:{exportVideo:async F=>{const K=je.current;if(!K)throw new Error("3D chưa sẵn sàng");K.sync(Ae.current,null),se(!0),ce("");try{const{blob:Y,cleanup:ae}=await K.exportVideo({...F,signal:new AbortController().signal,progress:()=>{}});try{return Lt.current=null,Bt.current=null,await li(Y,F,"canvas"),{nodeId:Lt.current||void 0,url:Bt.current||void 0}}finally{await ae()}}finally{se(!1)}},exportVfx:async F=>{se(!0),ce("");try{return await ri(F)}finally{se(!1)}},exportFrame:F=>Yn(!0,Ae.current.shots.find(K=>K.id===Ae.current.activeShot),0,!0,F)}};if(s){sc().then(F=>Xl(!!F?.allowed)).catch(()=>{}),s({ready:()=>!!je.current,run:(F,K)=>xf(F,K,h),exportVfx:(F,K,Y)=>ri(F,K,Y)});return}if(m0(h,async()=>{const F=je.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=Ae.current,Y=K.shots.find(ae=>ae.id===K.activeShot);F.sync(K,null),se(!0),ce("");try{const ae={start:0,end:Y.duration,fps:rn(Y),height:720},{blob:ve,cleanup:ge}=await F.exportVideo({...ae,signal:new AbortController().signal,progress:()=>{}});try{return Lt.current=null,Bt.current=null,await li(ve,ae,"canvas"),{nodeId:Lt.current||void 0,url:Bt.current||void 0}}finally{await ge()}}finally{se(!1)}}),n)return()=>Vl(h);n||sc().then(F=>Xl(!!F?.allowed)).catch(()=>{});const b=bf(()=>Ae.current.shots.find(F=>F.id===Ae.current.activeShot)?.name||"3D Shot"),E=S1(h,()=>Ae.current.shots.find(F=>F.id===Ae.current.activeShot)?.name||"3D Shot",F=>{const K=Ae.current.shots.find(Y=>Y.id===Ae.current.activeShot)?.duration||1;$(!1),Ue(Math.max(0,Math.min(1,F/K))),setTimeout(()=>$(!0),50)},()=>{const F=dt.getState().canvasId;return F?`shot:${F}:${e}`:null});return()=>{b(),E(),Vl(h)}},[]),R.useEffect(()=>{Pt()?.updateNodeData(e,{shotScene:z})},[z,e]),R.useEffect(()=>{c.current=S,S&&l(!1)},[S]),R.useEffect(()=>je.current?.setCameraHidden(C),[C,Te]),R.useEffect(()=>je.current?.mode(D,ue),[D,ue,r]),R.useEffect(()=>{J&&l(!1)},[J]),R.useEffect(()=>{je.current?.setCameraSelected(r&&!J&&!A)},[r,J,A,Te]),R.useEffect(()=>{je.current&&(je.current.cameraTip=o("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"))},[Te,Ys()]),R.useEffect(()=>je.current?.setQuality(ye),[ye,Te]),R.useEffect(()=>{if(!Te||Z!=="shots"||H||A)return;let h=!0,b,E=0;const F=()=>{const K=je.current;!K||!h||K.shotThumbnails(Ae.current.shots).then(Y=>{h&&kt(Y)}).catch(Y=>{h&&++E<8?b=setTimeout(F,1500):console.warn("[shot] thumbnails failed:",Y?.message)})};return b=setTimeout(F,900),()=>{h=!1,clearTimeout(b)}},[z.revision,Te,Z,H,A]),R.useEffect(()=>je.current?.setPreviewProgress(ke),[ke]),R.useEffect(()=>{if(!Te||A)return;const h=()=>{const F=je.current,K=Ae.current;if(!F)return;const Y=K.shots.find(ve=>ve.id===K.activeShot),ae=new Set(Object.entries(Y?.objectKeys||{}).filter(([,ve])=>ve.length).map(([ve])=>ve));try{de(Qf(K,{colliders:F.placementColliders(),keyed:ae}))}catch{de([])}},b=setTimeout(h,350),E=setTimeout(h,2500);return()=>{clearTimeout(b),clearTimeout(E)}},[z.revision,Te,A]),R.useEffect(()=>{const h=b=>{if(A){b.key==="Escape"&&(b.preventDefault(),Vn(!1)),!b.target.closest(".shot-trial-controls")&&b.key!=="Tab"&&b.stopImmediatePropagation();return}if(b.target.closest(".shot-ctxmenu")||b.target.closest(".shot-playhead-handle")&&["ArrowLeft","ArrowRight","Home","End",",","."].includes(b.key))return;const E=b.target.closest(".shot-fmt");if(!(E&&(["Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(b.key)||b.key==="Escape"&&E.querySelector(".shot-fmt-pop"))||(b.stopImmediatePropagation(),b.target.closest('input,textarea,select,[contenteditable="true"],[role="textbox"]')||H))){if((b.metaKey||b.ctrlKey)&&b.key.toLowerCase()==="z")b.preventDefault(),Va(b.shiftKey);else if((b.key==="Delete"||b.key==="Backspace")&&(y||T.length)&&b.target.closest(".shot-timeline"))b.preventDefault(),jl();else if((b.key==="Delete"||b.key==="Backspace")&&b.target.closest?.(".shot-shotlist li"))b.preventDefault(),ml(b.target.closest(".shot-shotlist li").dataset.shot);else if((b.key==="Delete"||b.key==="Backspace")&&Z==="rigging"&&Ge.current?.del())b.preventDefault();else if((b.key==="Delete"||b.key==="Backspace")&&!L&&J&&!je.current?.transform.object?.userData.cameraKey)b.preventDefault(),ei();else if((b.metaKey||b.ctrlKey)&&!b.altKey&&["c","v"].includes(b.key.toLowerCase())){const K=!!b.target.closest(".shot-timeline");b.key.toLowerCase()==="c"?K||fs.length?(b.preventDefault(),bl()):it.length&&!L&&(b.preventDefault(),sl()):K||g.current.length&&(xn.current==="keys"||!Ua())?g.current.length&&(b.preventDefault(),yl()):!L&&Ua()&&(b.preventDefault(),al())}else if(!L&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&!b.shiftKey&&b.code==="KeyF")b.preventDefault(),je.current?.view();else if(Sn&&!L&&!b.metaKey&&!b.ctrlKey&&Ru(b))b.preventDefault();else if(b.altKey&&(b.code==="Comma"||b.code==="Period"))b.preventDefault(),vl(b.code==="Period"?1:-1);else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&b.key.toLowerCase()==="k"){const K=y?.row??J??(r?"camera":null);b.shiftKey?(b.preventDefault(),xl()):!y&&it.length>1?(b.preventDefault(),ll()):K&&(b.preventDefault(),oi(K))}else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&["l","i","o"].includes(b.key.toLowerCase())){b.preventDefault();const K=b.key.toLowerCase();K==="l"?m(Y=>!Y):qu(K==="i"?"in":"out")}else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&(b.key===" "||b.key===","||b.key==="."||b.key==="Home"||b.key==="End"))if(b.preventDefault(),b.key===" ")$(K=>(!K&&ke>=1&&Ue(0),!K));else{$(!1);const K=z.shots.find(ae=>ae.id===z.activeShot),Y=rn(K);Ue(b.key==="Home"?0:b.key==="End"?1:Math.max(0,Math.min(1,(Math.round(ke*K.duration*Y)+(b.key==="."?1:-1))/Y/K.duration)))}else if(r&&!L&&["w","e"].includes(b.key.toLowerCase())&&!b.metaKey&&!b.ctrlKey&&!b.altKey)b.preventDefault(),ee(b.key.toLowerCase()==="w"?"translate":"rotate");else if(b.key==="Escape"){if(At){qe(null);return}if(Pn.on){an({on:!1});return}if(_t){rt(null);return}if(Z==="rigging"&&Ge.current?.esc())return;r&&!L?l(!1):L?N(!1):Z?zn(null):pt()}}};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[pt,H,L,J,B,y,T,z,A,Z,r,ke,d,Sn,Pn.on,_t,At]);const fe=(A?.stage||z).shots.find(h=>h.id===z.activeShot),hl=z.items.find(h=>h.id===J),te=hl?Tn(hl,fe,ke):void 0;R.useEffect(()=>{H&&$(!1)},[H]),R.useEffect(()=>{$(!1),Ue(0),i(null),k(null),j([])},[z.activeShot]);const Fu=h=>{const b=Vh(h.dataTransfer.getData(gr)),E=je.current;if(!b||!E||H)return;h.preventDefault();const F=E.pointerTarget(h.clientX,h.clientY),K=Ae.current,Y=K.shots.find(ve=>ve.id===K.activeShot),ae=su(K,b,{selected:F.id??J,ground:F.ground,start:Ye.current*Y.duration,label:o(b.name),anchor:(ve,ge,We)=>E.partPointAt(Y,We,ve,ge)});if("error"in ae){ce(o("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[24]));return}ce(""),$(!1),Me(()=>ae.stage),Xe(ae.item.id),zn("fx")},Pu=h=>{const b=Oa(h.dataTransfer.getData(Ao)),E=je.current;if(!b||!E||H)return;h.preventDefault();const F=E.pointerSlot(h.clientX,h.clientY),K=F&&Ae.current.items.find(ae=>ae.id===F.id);if(!F||!K||!Ca(K)){ce(o("Thả vật liệu lên một đối tượng trong cảnh."));return}if(K.locked){ce(o("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[K.name]));return}const Y=nt.mode==="part"&&E.materialSlots(K.id).length>1;ce(""),$(!1),Me(ae=>zs(ae,K.id,Y?F.slot:"*",{preset:b.id})),Xe(K.id),Y&&et({mode:"part",slot:F.slot})},$u=Object.fromEntries(z.items.flatMap(h=>{if(h.kind!=="fx"||!h.fx)return[];const b=Mn(h,fe);return b.off?[]:[[h.id,{start:b.start,duration:b.duration}]]})),dl=yf(A?.stage||z),na=Ta(z.lighting),ul=vf(z.shots),ai=h=>Me(b=>({...b,lighting:Ta({...Ta(b.lighting),...h})})),Ls=z.notes||[],sa=z.styleRefs||[],Ou=()=>{const h=je.current;if(h){if(oe){h.setNotePlacer(null),Ne(!1);return}Ne(!0),h.setNotePlacer(b=>{Ne(!1),Me(E=>({...E,notes:[...E.notes||[],{id:bt(),text:o("Ghi chú"),position:b}].slice(0,Ql)}))})}},Du=(h,b)=>Me(E=>({...E,notes:(E.notes||[]).map(F=>F.id===h?{...F,text:b.slice(0,Zl)}:F)})),zu=h=>Me(b=>({...b,notes:(b.notes||[]).filter(E=>E.id!==h)})),ml=h=>Me(b=>{if(b.shots.length<2)return b;const E=b.shots.findIndex(K=>K.id===h);if(E<0)return b;const F=b.shots.filter(K=>K.id!==h);return{...b,shots:F,activeShot:b.activeShot===h?F[Math.min(E,F.length-1)].id:b.activeShot}}),pl=(h,b)=>Me(E=>{const F=E.shots.findIndex(ae=>ae.id===h),K=F+b;if(F<0||K<0||K>=E.shots.length)return E;const Y=[...E.shots];return[Y[F],Y[K]]=[Y[K],Y[F]],{...E,shots:Y}});R.useEffect(()=>{if(!_)return;const h=p&&d?d.in:0,b=p&&d?d.out:1;let E=0,F=performance.now(),K=ke;(K<h||K>=b)&&(K=h);const Y=jf(fe),ae=Math.max(.1,fe.duration),ve=Y?vi(fe,h*ae):0,ge=Y?vi(fe,b*ae):0;let We=Y?vi(fe,K*ae):0;const De=Ve=>{const ft=(Ve-F)/1e3;if(F=Ve,Y){if(We+=ft,We>=ge)if(u)We=ve+(We-ge)%Math.max(1e-6,ge-ve);else{je.current?.setOutputClock(null),Ue(b),$(!1);return}je.current?.setOutputClock(We),Ue(Zf(fe,We).scene/ae),E=requestAnimationFrame(De);return}if(K+=ft/ae,K>=b)if(u)K=h+(K-b)%Math.max(1e-6,b-h);else{Ue(b),$(!1);return}Ue(K),E=requestAnimationFrame(De)};return E=requestAnimationFrame(De),()=>{cancelAnimationFrame(E),je.current?.setOutputClock(null)}},[_,fe.duration,fe.timing,z.activeShot,u,p,d]);const Ya=(Pt()?.nodes()||[]).filter(h=>h.type==="image"&&h.id!==e&&h.data.url),yt=h=>{$(!1),Me(b=>({...b,shots:b.shots.map(E=>E.id===b.activeShot?{...E,...h}:E)}))},fl=h=>yt(Yi(h)),_u=(h,b)=>{const E=(h==="camera"?fe.cameraKeys:fe.objectKeys?.[h])?.find(F=>F.id===b);E&&($(!1),Ue(E.time),k({row:h,id:b}),j([]),i(h==="camera"?b:null),Xe(h==="camera"?null:h))},gl=h=>{$(!1),j(h),k(h.length===1?h[0]:null),i(h.length===1&&h[0].row==="camera"?h[0].id:null)},oi=h=>{if(h==="camera"){const b=fe.motion==="path"?fe.cameraKeys||[]:[],E=b.find(Y=>Math.abs(Y.time-ke)<1e-6),F=Fh(fe,ke),K={id:E?.id||bt(),time:ke,position:F.position,target:F.target,lens:F.lens,roll:F.roll};fl([...b.filter(Y=>Y.id!==K.id),K]),i(K.id),k({row:h,id:K.id}),Xe(null)}else{const b=z.items.find(ae=>ae.id===h);if(!b||b.locked)return;if(b.kind==="fx"&&b.fx?.attach){const ae=b.fx.attach.keyed?(fe.objectKeys?.[h]||[]).find(ge=>Math.abs(ge.time-ke)<1e-6):void 0,ve=ae?.id||bt();Me(ge=>Ro(ge,h,ke,{id:ve})),i(null),Xe(h),k({row:h,id:ve});return}const E=Tn(b,fe,ke),F=fe.objectKeys?.[h]||[],Y={id:F.find(ae=>Math.abs(ae.time-ke)<1e-6)?.id||bt(),time:ke,position:E.position,rotation:E.rotation,scale:E.scale};yt({objectKeys:{...fe.objectKeys,[h]:[...F.filter(ae=>ae.id!==Y.id),Y].sort((ae,ve)=>ae.time-ve.time)}}),i(null),Xe(h),k({row:h,id:Y.id})}},Bu=(h,b)=>Me(E=>{const F=E.items.find(ge=>ge.id===h);if(!F?.fx||F.locked||(F.fx.attach?.to??"")===b)return E;const K=F.fx.attach,Y=b?{to:b,...K?.part?{part:K.part}:{},...K?.follow?{follow:K.follow}:{}}:void 0,ae=K?.keyed?E.shots.map(ge=>ge.objectKeys?.[h]?{...ge,objectKeys:Object.fromEntries(Object.entries(ge.objectKeys).filter(([We])=>We!==h))}:ge):E.shots,ve=b?E.items.find(ge=>ge.id===b):null;return{...E,shots:ae,items:E.items.map(ge=>ge.id===h?{...ge,...!b&&K?{position:[...E.items.find(We=>We.id===K.to)?.position??ge.position]}:{},...ve?{position:[...ve.position]}:{},fx:{...F.fx,attach:Y}}:ge)}}),Ku=(h,b)=>{if(h==="camera"){b==="hidden"?M(E=>!E):I(E=>!E);return}$(!1),Me(E=>({...E,items:E.items.map(F=>F.id===h?{...F,[b]:!F[b]}:F)})),(b==="hidden"||b==="locked")&&Xe(E=>E===h&&!z.items.find(F=>F.id===h)?.[b]?null:E)},Hu=(h,b,E)=>{$(!1),Me(F=>eg(F,h,b,ke,E))},fs=T.length?T:y?[y]:[],xl=()=>{$(!1),Me(h=>tg(h,ke))},bl=()=>{g.current=ng(Ae.current,fs),w(g.current.length>0),xn.current="keys"},yl=()=>{if(!g.current.length)return;$(!1);let h=[];Me(b=>{const E=sg(b,g.current,ke);return h=E.pasted,E.stage}),h.length&&gl(h)},Wu=h=>{fs.length&&Me(b=>ag(b,fs,h))},vl=h=>{if(!fs.length)return;const b=h/(rn(fe)*fe.duration);cc(Ae.current,fs,b).moved&&($(!1),Me(E=>cc(E,fs,b).stage))},qu=h=>{const b=ke;f(E=>h==="in"?{in:b,out:E&&E.out>b?E.out:1}:{in:E&&E.in<b?E.in:0,out:b}),x(!0)},Gu=(h,b,E)=>{if(!((h==="camera"?fe.cameraKeys:fe.objectKeys?.[h])||[]).some(K=>K.id!==b&&Math.abs(K.time-E)<1e-6)){if(h==="camera")fl((fe.cameraKeys||[]).map(K=>K.id===b?{...K,time:E}:K));else{if(z.items.find(K=>K.id===h)?.locked)return;yt({objectKeys:{...fe.objectKeys,[h]:(fe.objectKeys?.[h]||[]).map(K=>K.id===b?{...K,time:E}:K).sort((K,Y)=>K.time-Y.time)}})}Ue(E)}},jl=()=>{const h=[...T,...y&&!T.some(Y=>Y.row===y.row&&Y.id===y.id)?[y]:[]];if(!h.length)return;const b=Y=>new Set(h.filter(ae=>ae.row===Y).map(ae=>ae.id)),E={...fe.objectKeys};let F=!1;for(const Y of new Set(h.map(ae=>ae.row)))if(Y!=="camera"&&!z.items.find(ae=>ae.id===Y)?.locked){const ae=b(Y);E[Y]=(E[Y]||[]).filter(ve=>!ae.has(ve.id)),F=!0}const K=h.some(Y=>Y.row==="camera")?Yi((fe.cameraKeys||[]).filter(Y=>!b("camera").has(Y.id))):{};yt({...K,...F?{objectKeys:E}:{}}),i(null),k(null),j([])},Uu=h=>{$(!1),yt(Jf(fe,h)),h!=="path"&&Ue(h==="static"?0:1)},kl=async h=>{try{const b=await N0("model",h);Be(E=>h?[...E,...b.assets]:b.assets),G(b.nextCursor)}catch(b){ce(b.message)}},Xu=async h=>{if(h){if(ce(""),!h.name.toLowerCase().endsWith(".glb")||h.size>50*1024*1024){ce("Chọn file GLB tối đa 50 MB.");return}le(!0);try{const b=new DataView(await h.slice(0,12).arrayBuffer());if(b.byteLength<12||b.getUint32(0,!0)!==1179937895||b.getUint32(4,!0)!==2)throw new Error("File không phải GLB 2.0 hợp lệ");const E=await h.arrayBuffer(),F=new DataView(E);if(F.byteLength<20||F.getUint32(8,!0)!==E.byteLength||F.getUint32(16,!0)!==1313821514)throw new Error("Cấu trúc GLB không hợp lệ");const K=F.getUint32(12,!0);if(20+K>E.byteLength)throw new Error("File GLB bị thiếu dữ liệu");const Y=JSON.parse(new TextDecoder().decode(new Uint8Array(E,20,K)));if([...Y.buffers||[],...Y.images||[]].some(ge=>ge.uri&&!ge.uri.startsWith("data:")))throw new Error("Hãy xuất GLB với texture và dữ liệu nhúng trong file.");const{gcsUri:ae}=await _s(new File([h],h.name,{type:"model/gltf-binary"})),ve={...fn("model",Ae.current.items.length),name:h.name,model:{gcsUri:ae,name:h.name}};Me(ge=>({...ge,items:[...ge.items,ve]})),Xe(ve.id)}catch(b){ce(b.message)}finally{le(!1)}}},wl=(h,b)=>{const E={...fn("splat",Ae.current.items.length),name:h,position:[0,0,0],color:"#9aa3a8",splat:b};Me(F=>({...F,items:[...F.items,E]})),Xe(E.id)},Vu=async h=>{if(!h)return;ce("");const b=h.name.split(".").pop()?.toLowerCase()||"";if(!e0.includes(b)||h.size>t0){ce(o("Chọn file bản quét .spz, .ply, .splat, .ksplat hoặc .sog tối đa 300 MB."));return}le(!0);try{const{gcsUri:E}=await _s(new File([h],h.name,{type:"application/x-gaussian-splat"}));wl(h.name.replace(/\.[^.]+$/,""),{name:h.name,gcsUri:E,source:"scan",flip:!0})}catch(E){ce(E.message)}finally{le(!1)}},ii=(Pt()?.nodes()||[]).filter(h=>h.type==="world"&&typeof h.data.splatUrl=="string"),Yu=h=>{const b=Array.from({length:h==="person"?$e:1},(E,F)=>({...fn(h,z.items.length+F),name:`${o(Hi.find(([K])=>K===h)?.[1]||"Model")} ${z.items.length+F+1}`}));Me(E=>({...E,items:[...E.items,...b]})),Xe(b[0].id)};async function ri(h,b,E){const F=je.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=structuredClone(Ae.current);F.sync(K,null);const Y=await f1(F,K,e,h,{signal:E,progress:b}),ae=x1(Y,K.plate?.timelineClipId);return Lt.current=Y.at(-1)?.nodeId||null,Bt.current=Y.at(-1)?.url||null,ae}async function li(h,b,E){const F=structuredClone(Ae.current),K=F.shots.find(jt=>jt.id===F.activeShot),Y=dt.getState().canvasId,ae=new File([h],`${K.name}-camera.mp4`,{type:"video/mp4"}),{url:ve,gcsUri:ge}=await _s(ae,void 0,"video");Bt.current=ve;const We=Pt()?.getNode(e);if(!We||dt.getState().canvasId!==Y)throw new Error("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi.");const De=b.end-b.start,Ve=`Use the attached 3D previs video as the camera-motion and spatial-layout reference. Preserve its camera trajectory, framing, lens perspective and timing over ${De} seconds. Preserve the subject movements and their spatial relationships shown in the reference. Replace the previs appearance with the intended final visual style; do not copy editor helpers. The reference contains no audio. Describe the desired final appearance here.`,ft=Pt()?.addNode("video",{url:ve,gcsUri:ge,label:`${K.name} · Camera ref`,duration:De,ratio:K.aspect,status:"succeeded",shotSourceId:e,shotId:K.id,shotRevision:F.revision,cameraVideo:{...b},prompt:Ve},{x:We.position.x+380,y:We.position.y},{sourceIds:[e]});if(Lt.current=ft||null,E==="timeline"){if(!ft)throw new Error("Không tạo được video trên Canvas");const jt=dt.getState(),yn=We.data?.timelineClipId,Kt=jt.clips.find(Zt=>Zt.id===yn);if(!Kt)throw new Error("Clip 3D gốc không còn trên Timeline. Video đã lưu vào Canvas.");if(jt.timelineTracks[Kt.track]?.locked)throw new Error("Track đã khóa. Video đã lưu vào Canvas.");const dn=Kt.kind==="model"?Kt:Kt.from3D?.clip,It={id:crypto.randomUUID(),nodeId:ft,track:Kt.track,start:Kt.start,duration:Math.max(1/30,Math.min(Kt.duration,Math.floor(De*30)/30)),sourceDuration:De,inPoint:0,volume:1,url:ve,gcsUri:ge,kind:"video",label:`${Kt.label.replace(/ · 3D$/,"")} · 3D`,...Kt.zIndex!==void 0?{zIndex:Kt.zIndex}:{},...dn?{from3D:{shotNodeId:e,clip:dn}}:{}};jt.setClips(Zt=>Zt.map(xs=>xs.id===Kt.id?It:xs)),jt.setTimelineMedia(Zt=>Zt.some(xs=>xs.source==="canvas"&&xs.id===ft)?Zt:[...Zt,{id:ft,source:"canvas",kind:"video",url:ve,gcsUri:ge,label:It.label,duration:De}]),Pt()?.updateNodeData(e,{timelineClipId:It.id}),pt(),jt.setView("timeline"),jt.toast(o("Đã đưa video 3D về Timeline, thay đúng chỗ clip model"),"ok");return}dt.getState().toast(o("Đã lưu video camera vào Canvas và tài sản của bạn"),"ok")}async function Yn(h,b=Ae.current.shots.find(ae=>ae.id===Ae.current.activeShot),E=0,F=!0,K=0,Y=""){if(!je.current)return;F&&se(!0),ce("");const ae=dt.getState().canvasId,ve=structuredClone(Ae.current);ve.activeShot=b.id;const ge=b,We=Ae.current.activeShot;try{We!==ge.id&&je.current.sync(ve,J);const De=await je.current.exportPng(K),Ve=`${ge.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}${Y.replace(/\s+/g,"-")}.png`;if(h){const{url:ft,gcsUri:jt}=await _s(new File([De],Ve,{type:"image/png"})),yn=Pt()?.getNode(e);if(dt.getState().canvasId!==ae)throw new Error("Canvas đã thay đổi; ảnh chưa được chèn");if(!yn)throw new Error("Cảnh gốc không còn tồn tại");const Kt=Pt()?.addNode("image",{url:ft,gcsUri:jt,label:`${ge.name}${Y}`,ratio:ge.aspect,prompt:ki(ve),shotSourceId:e,shotId:ge.id,shotRevision:ve.revision,sceneVersion:ve.version,characterReferences:ve.items.filter(dn=>dn.kind==="person"&&dn.reference).map(dn=>dn.reference),cameraMotion:{pathSmooth:ge.pathSmooth,type:ge.motion,duration:ge.duration,endPosition:ge.endPosition,endTarget:ge.endTarget,endLens:ge.endLens},cameraFrame:K},{x:yn.position.x+380,y:yn.position.y+E*280},{sourceIds:[e,...ve.items.flatMap(dn=>dn.reference?.nodeId?[dn.reference.nodeId]:[])]});return dt.getState().toast(o("Đã đưa ảnh shot vào Canvas"),"ok"),Kt}else{const ft=URL.createObjectURL(De),jt=document.createElement("a");jt.href=ft,jt.download=Ve,jt.click(),setTimeout(()=>URL.revokeObjectURL(ft),1e3)}}catch(De){if(ce(De.message),!F)throw De}finally{We!==ge.id&&je.current.sync(Ae.current,J),F&&se(!1)}}async function Qu(){if(fe.motion!=="static"){se(!0),ce("");try{const h=await Yn(!0,fe,0,!1,0," · Start"),b=await Yn(!0,fe,1,!1,1," · End");h&&b&&(Pt()?.updateNodeData(h,{pairedShotNodeId:b}),Pt()?.updateNodeData(b,{pairedShotNodeId:h})),dt.getState().toast(o("Đã tạo cặp Start/End cho Seedance"),"ok")}catch(h){ce(h.message)}finally{je.current?.sync(Ae.current,J),se(!1)}}}async function Zu(){let h=!1;se(!0),ce("");try{Aa.includes(fe.aspect)||dt.getState().toast(ju(fe).aspect.at(-1)||"","error");const b=await Yn(!0,fe,0,!1,ke," · Previs");if(!b)return;const E=[b,...Ae.current.items.flatMap(K=>K.reference?.nodeId?[K.reference.nodeId]:[]),...(Ae.current.styleRefs||[]).map(K=>K.nodeId)],F=Pt()?.getNode(e);h=!0,pt(),dt.getState().openComposer({mode:"image",generator:"openai:gpt-image",refs:Array.from(new Set(E)),prompt:n0(Ae.current),count:1,aspectRatio:Aa.includes(fe.aspect)?fe.aspect:Qi(fe.aspect,Aa),resolution:"2K",quality:"high",anchor:F?{x:F.position.x+760,y:F.position.y}:null}),dt.getState().toast(o("Khung previs đã sẵn sàng để tạo ảnh thật"),"ok")}catch(b){ce(b.message)}finally{h||je.current?.sync(Ae.current,J),se(!1)}}async function Ju(){if(je.current){se(!0),ce("");try{const h=await je.current.exportPng(ke,!0),b=URL.createObjectURL(h),E=document.createElement("a");E.href=b,E.download=`${fe.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-ghi-chu.png`,E.click(),setTimeout(()=>URL.revokeObjectURL(b),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}async function em(){se(!0),ce("");try{for(let h=0;h<Ae.current.shots.length;h++)await Yn(!0,Ae.current.shots[h],h,!1);dt.getState().toast(o("Đã xuất {0} shot vào Canvas",[Ae.current.shots.length]),"ok")}catch(h){ce(h.message)}finally{se(!1)}}async function tm(){if(je.current){se(!0);try{const h=Ae.current.shots.find(K=>K.id===Ae.current.activeShot),b=await je.current.exportDepth(ke),E=URL.createObjectURL(b),F=document.createElement("a");F.href=E,F.download=`${h.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-depth.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(E),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}async function nm(){if(je.current){se(!0);try{const h=Ae.current.shots.find(K=>K.id===Ae.current.activeShot),b=await je.current.exportPoseMask(ke),E=URL.createObjectURL(b),F=document.createElement("a");F.href=E,F.download=`${h.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-pose-mask.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(E),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}const gs=(h,b,E,F=-100)=>t.jsxs("div",{className:"shot-vector",children:[t.jsx("small",{children:o(h)}),b.map((K,Y)=>t.jsx(Hn,{label:`${o(h)} ${["X","Y","Z"][Y]}`,value:K,min:F,onChange:ae=>{const ve=[...b];ve[Y]=ae,E(ve)}},Y))]});R.useEffect(()=>{try{localStorage.setItem("clipoox.shot.layout",JSON.stringify(pe))}catch{}},[pe]);const zn=h=>{xe(h);try{localStorage.setItem("clipoox.shot.panel",h||"")}catch{}},sm=h=>zn(Z===h?null:h),Ml=h=>{U(h);try{localStorage.setItem("clipoox.shot.railWide",h?"1":"0")}catch{}},[Qa,aa]=R.useState(null),Sl=h=>{const b=h.target.closest("button"),E=b?.querySelector(".lbl");if(!b||!E||getComputedStyle(E).display!=="none"){aa(null);return}const F=b.getBoundingClientRect(),K=h.currentTarget.getBoundingClientRect().right,Y=b.getAttribute("aria-label")||"";aa(ae=>ae&&ae.label===Y&&ae.top===F.top+F.height/2?ae:{label:Y,left:K+8,top:F.top+F.height/2})},am=()=>{me(Wi),Ml(!1);try{localStorage.removeItem("clipoox.shot.layout")}catch{}},ci=(h,b)=>{if(h.button!==0)return;h.preventDefault();const E=h.currentTarget,F={x:h.clientX,y:h.clientY,value:pe[b]},K=h.pointerId;E.setPointerCapture(K),E.classList.add("dragging");const Y=ge=>b==="timeline"?Math.max(120,Math.min(window.innerHeight*.55,ge)):b==="drawer"?Math.max(240,Math.min(window.innerWidth*.2,ge)):Math.max(260,Math.min(window.innerWidth*.22,ge)),ae=ge=>{const We=b==="timeline"?F.y-ge.clientY:b==="drawer"?ge.clientX-F.x:F.x-ge.clientX;me(De=>({...De,[b]:Math.round(Y(F.value+We))}))},ve=()=>{E.removeEventListener("pointermove",ae),E.removeEventListener("pointerup",ve),E.removeEventListener("pointercancel",ve),E.classList.remove("dragging")};E.addEventListener("pointermove",ae),E.addEventListener("pointerup",ve),E.addEventListener("pointercancel",ve)};return t.jsxs("div",{className:"shot-workspace",role:"dialog","aria-modal":"true","aria-label":o("3D Shot Composer"),children:[Tt&&t.jsx(F1,{count:it.length,start:ke*fe.duration,left:(1-ke)*fe.duration,busy:H,onRun:h=>{Iu(h)},onClose:()=>Rt(!1)}),_t&&t.jsx(E1,{x:_t.x,y:_t.y,renaming:!!_t.renaming,items:_t.scene?[]:it.map(h=>z.items.find(b=>b.id===h)).filter(Boolean),canPaste:!!Ua(),hiddenCount:z.items.filter(h=>h.hidden).length,blenderKeys:Sn,onBlenderKeys:As,onAction:Eu,onRename:h=>{const b=it[0];rt(null),b&&He(b,{name:h})},onClose:sn}),Pn.on&&(()=>{const h=lt.current?.getBoundingClientRect(),b=Pn.from,E=Pn.to;if(!h)return null;const F=K=>{if(!b)return;const Y=E&&Math.hypot(E[0]-b[0],E[1]-b[1])>3?je.current?.objectsInRect(b[0],b[1],K.clientX,K.clientY)??[]:[];wt(K.shiftKey?[...xt.current,...Y.filter(ae=>!xt.current.includes(ae))]:Y),an({on:!1})};return t.jsxs("div",{className:"shot-boxsel",role:"presentation","aria-label":o("Kéo để chọn theo vùng"),style:{left:h.left,top:h.top,width:h.width,height:h.height},onMouseDown:K=>{K.button===0&&an({on:!0,from:[K.clientX,K.clientY],to:[K.clientX,K.clientY]})},onMouseMove:K=>{b&&an({on:!0,from:b,to:[K.clientX,K.clientY]})},onMouseUp:F,onContextMenu:K=>{K.preventDefault(),an({on:!1})},children:[t.jsx("span",{className:"shot-boxsel-hint",children:o("Kéo để chọn theo vùng · Shift: chọn thêm · Esc: thôi")}),b&&E&&t.jsx("i",{style:{left:Math.min(b[0],E[0])-h.left,top:Math.min(b[1],E[1])-h.top,width:Math.abs(E[0]-b[0]),height:Math.abs(E[1]-b[1])}})]})})(),L&&t.jsx(m1,{shot:fe,engine:je.current||null,onClose:()=>N(!1),onBusy:se,onReady:li,timelineTarget:(()=>{const h=Pt()?.getNode(e)?.data?.timelineClipId;return typeof h=="string"?dt.getState().clips.find(b=>b.id===h)?.label:void 0})(),vfx:z.plate?{layers:new Set(z.items.filter(h=>h.kind==="fx"&&!h.hidden).map(Qh)).size,target:dt.getState().clips.find(h=>h.id===z.plate?.timelineClipId)?.label,run:async(h,b,E)=>{const F=await ri(h,b,E),K=dt.getState();if(!F.placed){K.toast(o("Đã lưu {0} video hiệu ứng vào Canvas. Clip gốc không có trên Timeline đang mở: thêm bằng tay hoặc mở lại Timeline đó.",[F.passes.length]),"info");return}pt(),K.setView("timeline"),K.toast(F.pendingMatte?o("Đã đặt {0} lớp hiệu ứng lên Timeline. Timeline đang tách người để đặt lớp sau người ra sau.",[F.passes.length]):o("Đã đặt {0} lớp hiệu ứng lên Timeline.",[F.passes.length]),"ok")}}:void 0}),t.jsxs("header",{children:[t.jsxs("button",{disabled:H,onClick:pt,children:[t.jsx(Ce.back,{}),o("← Canvas").replace("← ","")]}),t.jsxs("strong",{children:[o("3D Shot Composer"),t.jsx("em",{children:o("BETA")})]}),t.jsx("span",{className:"shot-save","data-save-state":Fe,title:Fe==="error"&&Et?Et:void 0,children:Fe==="saved"?o("Đã lưu"):Fe==="error"?t.jsxs(t.Fragment,{children:[o("Lỗi lưu — đã giữ bản trên máy này"),Et&&t.jsx("small",{className:"shot-save-why",children:Et}),t.jsx("button",{type:"button",className:"shot-save-retry",onClick:()=>dt.getState().retrySave(),children:o("Thử lại")})]}):o("Đang lưu…")}),t.jsx("button",{"aria-label":o("Hoàn tác"),title:o("Hoàn tác (⌘Z)"),disabled:!Yt.current.length||H,onClick:()=>Va(),children:t.jsx(Ce.undo,{})}),t.jsx("button",{"aria-label":o("Làm lại"),title:o("Làm lại (⇧⌘Z)"),disabled:!hn.current.length||H,onClick:()=>Va(!0),children:t.jsx(Ce.redo,{})}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Yn(!1,fe,0,!0,ke)},title:o("Tải PNG"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:o("Tải PNG")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te,onClick:tm,title:o("Depth map"),children:[t.jsx(Ce.depth,{}),t.jsx("span",{className:"lbl",children:o("Depth map")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te,onClick:nm,title:o("Pose mask"),children:[t.jsx(Ce.mask,{}),t.jsx("span",{className:"lbl",children:o("Pose mask")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te||z.shots.length<2,onClick:em,title:o("Xuất tất cả shot"),children:[t.jsx(Ce.layers,{}),t.jsx("span",{className:"lbl",children:o("Xuất tất cả shot")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te||fe.motion==="static",onClick:Qu,title:o("Start + End"),children:[t.jsx(Ce.frames,{}),t.jsx("span",{className:"lbl",children:o("Start + End")})]}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Zu()},title:o("Biến khung xám thành ảnh thật (giữ nguyên bố cục)"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:o("Ảnh thật")})]}),t.jsxs("button",{className:"shot-primary",disabled:H||!Te,onClick:()=>{$(!1),N(!0)},title:o("Xuất MP4"),children:[t.jsx(Ce.video,{}),o("Xuất MP4")]}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Yn(!0,fe,0,!0,ke)},children:[t.jsx(Ce.plus,{}),H?o("Đang xuất…"):o("Đưa vào Canvas")]})]}),bn&&bn.canvasId===qt&&bn.nodeId===e&&t.jsxs("div",{className:"shot-sync-bar",role:"alert",children:[t.jsx("span",{"aria-hidden":!0,children:"⟳"}),t.jsxs("div",{className:"grow",children:[t.jsx("b",{children:kf(bn.by)?o("Cảnh 3D này có phiên bản mới từ trợ lý AI của bạn."):o("Cảnh 3D này có phiên bản mới.")})," ",o("Bạn cũng có thay đổi chưa lưu ở đây — chọn bản muốn giữ.")]}),t.jsx("button",{className:"primary",disabled:$n,onClick:()=>void wf(bn.canvasId,bn.nodeId).then(()=>dt.getState().toast(o("Đã tải phiên bản mới nhất của cảnh 3D."),"ok")),children:o("Tải phiên bản mới")}),t.jsx("button",{disabled:$n,onClick:Mf,children:o("Giữ bản của tôi")})]}),he&&t.jsx("div",{className:"shot-error",role:"alert",children:o(he)}),P&&t.jsx(Sf,{characters:P==="characters",onClose:()=>{W(!1),Re(null)},onSelect:Ts}),A&&t.jsx("div",{className:"shot-trial-shield",role:"dialog","aria-label":o("Xem thử đề xuất AI"),children:t.jsxs("div",{className:"shot-trial-controls",children:[t.jsx("b",{children:o("Xem thử · chưa lưu")}),t.jsx("button",{onClick:()=>{ke>=1&&Ue(0),$(!_)},children:_?o("Tạm dừng"):o("Phát lại")}),t.jsx("input",{"aria-label":o("Thời gian xem thử"),type:"range",min:0,max:1,step:1e-4,value:ke,onChange:h=>{$(!1),Ue(+h.target.value)}}),t.jsxs("span",{children:[(ke*fe.duration).toFixed(2),o("s")]}),t.jsx("button",{onClick:()=>Vn(!1),children:o("Bỏ bản xem thử")}),t.jsx("button",{className:"shot-primary",onClick:()=>Vn(!0),children:o("Giữ thay đổi")})]})}),t.jsxs("div",{className:`shot-layout ${Z?"has-drawer":""} ${be?"rail-wide":""}`,style:{"--drawer-w":`${pe.drawer}px`,"--right-w":`${pe.right}px`},children:[t.jsxs("nav",{className:"shot-rail","aria-label":o("Công cụ dựng cảnh"),onMouseOver:Sl,onFocus:Sl,onMouseLeave:()=>aa(null),onBlur:()=>aa(null),onScroll:()=>aa(null),children:[vo.map(([h,b,E])=>t.jsxs("button",{type:"button",className:Z===h?"active":"","aria-pressed":Z===h,"aria-label":o(b),onClick:()=>sm(h),children:[E,t.jsx("span",{className:"lbl",children:o(b)}),h==="objects"&&t.jsx("small",{className:"shot-rail-count",children:z.items.length}),h==="shots"&&z.shots.length>1&&t.jsx("small",{className:"shot-rail-count",children:z.shots.length}),h==="notes"&&Ls.length>0&&t.jsx("small",{className:"shot-rail-count",children:Ls.length})]},h)),t.jsx("span",{className:"shot-rail-gap"}),t.jsxs("button",{type:"button","aria-label":be?o("Thu gọn thanh công cụ"):o("Mở rộng thanh công cụ"),onClick:()=>Ml(!be),children:[be?t.jsx(Ce.collapse,{}):t.jsx(Ce.expand,{}),t.jsx("span",{className:"lbl",children:o("Thu gọn")})]}),t.jsxs("button",{type:"button","aria-label":o("Khôi phục bố cục"),onClick:am,children:[t.jsx(Ce.reset,{}),t.jsx("span",{className:"lbl",children:o("Khôi phục bố cục")})]})]}),Qa&&Jh.createPortal(t.jsx("span",{className:"shot-rail-tip",role:"tooltip",style:{left:Qa.left,top:Qa.top},children:Qa.label}),document.querySelector(".shot-workspace")||document.body),Z&&t.jsxs("aside",{className:"shot-drawer shot-inspector","aria-label":o(vo.find(h=>h[0]===Z)[1]),children:[t.jsxs("div",{className:"shot-drawer-head",children:[t.jsxs("h3",{children:[o(vo.find(h=>h[0]===Z)[1]),Z==="objects"?t.jsxs("small",{className:"shot-total",children:[" · ",z.items.length]}):Z==="shots"?t.jsxs("small",{className:"shot-total",children:[" · ",z.shots.length," · ",ji(ul.at(-1)?.end||0)]}):Z==="notes"?t.jsxs("small",{className:"shot-total",children:[" · ",Ls.length]}):Z==="series"&&z.series?t.jsxs("small",{className:"shot-total",children:[" · ",z.series.name]}):null]}),t.jsx("button",{type:"button",className:"shot-drawer-close","aria-label":o("Đóng bảng"),title:o("Đóng bảng (Esc)"),onClick:()=>zn(null),children:t.jsx(Ce.close,{})})]}),t.jsxs("div",{className:"shot-drawer-body shot-inspector-scroll",tabIndex:0,children:[Z==="scene"&&t.jsx("div",{className:"shot-scene-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsxs("div",{className:"shot-add",children:[t.jsx("input",{ref:ct,type:"file",accept:".glb",hidden:!0,onChange:h=>{Xu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{onClick:()=>W("all"),children:[t.jsx(Ce.library,{}),o("Kho 3D chung")]}),t.jsxs("button",{onClick:()=>void kl(),children:[t.jsx(Ce.user,{}),o("Model của tôi")]}),Pe.length>0&&t.jsxs("select",{"aria-label":o("Model 3D đã lưu"),value:"",onChange:h=>{const b=Pe.find(F=>F.id===h.target.value);if(!b)return;const E={...fn("model",Ae.current.items.length),name:b.name,model:{gcsUri:b.gcsUri,name:b.name}};Me(F=>({...F,items:[...F.items,E]})),Xe(E.id)},children:[t.jsx("option",{value:"",children:o("Chọn model đã lưu…")}),Pe.map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))]}),ot&&t.jsx("button",{onClick:()=>void kl(ot),children:o("Thêm model đã lưu")}),t.jsxs("button",{disabled:Se,onClick:()=>ct.current?.click(),children:[t.jsx(Ce.cube,{}),Se?o("Đang tải…"):"Model GLB"]}),t.jsx("input",{ref:Ke,type:"file",accept:".spz,.ply,.splat,.ksplat,.sog",hidden:!0,onChange:h=>{Vu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{disabled:Se,title:o("Bản quét 3D địa điểm thật từ app điện thoại (Scaniverse, Polycam, Luma…)"),onClick:()=>Ke.current?.click(),children:[t.jsx(Ce.image,{}),o("Bối cảnh thật")]}),ii.length>0&&t.jsxs("select",{"aria-label":o("Dùng 3D World trên Canvas"),value:"",onChange:h=>{const b=ii.find(F=>F.id===h.target.value);if(!b)return;const E=b.data;wl(E.label||"3D World",{name:E.label||"3D World",url:E.splatUrl,source:"world",flip:!0,...E.worldId?{worldId:E.worldId}:{}})},children:[t.jsx("option",{value:"",children:o("Dùng 3D World trên Canvas…")}),ii.map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"3D World")},h.id))]}),Hi.map(([h,b])=>t.jsxs("button",{disabled:H,onClick:()=>Yu(h),children:[P1[h],o(b)]},h))]}),t.jsx(Hn,{label:"Số người mỗi lần thêm",value:$e,min:1,max:50,step:1,onChange:h=>Le(Math.floor(h))})]})}),Z==="fx"&&t.jsx(Tv,{onEdit:()=>zn("fxedit"),onPlayClip:(h,b)=>{Jo(h,b)},stage:z,selected:J,playhead:ke*fe.duration,change:Me,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],anchor:(h,b,E)=>je.current?.partPointAt(fe,E,h,b)??null,engine:je.current,setError:ce}),Z==="material"&&t.jsx(Hv,{stage:z,selected:J,change:Me,engine:je.current,setError:ce,scope:nt,setScope:et}),Z==="rigging"&&t.jsx(h1,{stage:z,shot:fe,selected:J,engine:Te?je.current:null,playhead:ke,busy:H,change:Me,patchItem:He,onSelect:Xe,resync:()=>je.current?.sync(Ae.current,J),setError:ce,addPoseKey:Dn,onPlayClip:Jo,motionLoop:Qo,motionMirror:Zo,onMotionLoop:Qr,onMotionMirror:Zr,keys:Ge}),Z==="fxedit"&&t.jsx(Lv,{stage:z,selected:J,playhead:ke*fe.duration,change:Me,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],engine:je.current}),Z==="mixfx"&&t.jsx($v,{stage:z,selected:J,progress:ke,change:Me,onSelect:Xe,engine:je.current,setError:ce}),Z==="modeling"&&t.jsx(fx,{stage:z,selected:J,change:Me,getStage:()=>Ae.current,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],engine:je.current,setError:ce}),Z==="objects"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-objects-section",children:[t.jsx("div",{className:"shot-charlib",children:t.jsxs("button",{type:"button",className:"shot-charlib-btn",onClick:()=>W("characters"),title:o("Nhân vật có xương: thêm vào cảnh là chạy mocap / chuyển động ngay"),children:[t.jsx(Ce.person,{}),t.jsx("span",{children:o("Thư viện nhân vật")})]})}),t.jsx("div",{className:"shot-list",children:z.items.map(h=>t.jsxs("div",{className:J===h.id?"active":B.includes(h.id)?"picked":"",onContextMenu:b=>{b.preventDefault(),si(h.id,b.clientX,b.clientY)},children:[t.jsxs("button",{"aria-pressed":it.includes(h.id),title:o("Shift/Ctrl+click: chọn thêm · chuột phải: menu"),onClick:b=>nn(h.id,b.shiftKey||b.ctrlKey||b.metaKey),children:[h.kind==="person"?"♙":h.kind==="set"?"⌂":"◇"," ",h.name,h.kind==="set"&&h.set?.parts?t.jsxs("small",{className:"shot-list-meta",children:[" · ",h.set.parts," ",o("khối")]}):null]}),t.jsx("button",{title:h.hidden?o("Hiện"):o("Ẩn"),onClick:()=>He(h.id,{hidden:!h.hidden}),children:h.hidden?"○":"●"}),t.jsx("button",{title:h.locked?o("Mở khóa"):o("Khóa"),onClick:()=>He(h.id,{locked:!h.locked}),children:h.locked?"▣":"□"}),t.jsx("button",{className:"shot-delete-item","aria-label":o("Xóa {0}",[h.name]),title:h.locked?o("Mở khóa đối tượng trước khi xóa"):o("Xóa {0} (Delete)",[h.name]),disabled:H||h.locked,onClick:()=>tl(h.id),children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:t.jsx("path",{d:"M4 6h16M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7m4-7v7"})})})]},h.id))})]}),te&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:o("CHỈNH ĐỐI TƯỢNG")}),t.jsxs("fieldset",{disabled:te.locked||H,children:[t.jsx("input",{"aria-label":o("Tên đối tượng"),value:te.name,onChange:h=>He(te.id,{name:h.target.value})}),t.jsxs("label",{className:"shot-field",children:[o("Màu"),t.jsx("input",{"aria-label":o("Màu đối tượng"),type:"color",value:te.color,onChange:h=>He(te.id,{color:h.target.value})})]}),t.jsxs("select",{"aria-label":o("Đặt lên bề mặt"),value:"",onChange:h=>{h.target.value&&je.current?.placeOnSurface(h.target.value)},children:[t.jsx("option",{value:"",children:o("Đặt lên bề mặt…")}),t.jsx("option",{value:"ground",children:o("Mặt đất")}),z.items.filter(h=>h.kind!=="person"&&h.id!==te.id&&!h.hidden).map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))]}),gs(o("Vị trí"),te.position,h=>He(te.id,{position:h})),gs("Xoay °",te.rotation,h=>He(te.id,{rotation:h}),-360),gs(o("Tỷ lệ"),te.scale,h=>He(te.id,{scale:h}),.05),te.kind==="model"&&te.model&&t.jsxs("div",{className:"shot-model-size",children:[t.jsx(Hn,{label:"Chiều cao thật (m)",value:Number((je.current?.modelHeight(te)??2).toFixed(2)),min:.02,max:500,step:.01,onChange:h=>He(te.id,{model:{...te.model,height:h}})}),t.jsx("small",{className:"shot-hint",children:te.model.height?o("Kích thước thật"):o("Tự động: cạnh dài nhất 2 m")}),te.model.height&&t.jsx("button",{onClick:()=>{const{height:h,...b}=te.model;He(te.id,{model:b})},children:o("Về tự động")})]}),te.hold&&(()=>{const h=z.items.find(b=>b.id===te.hold.by);return t.jsxs("div",{className:"shot-held",children:[t.jsx("small",{className:"shot-hint",children:o("Đang được {0} cầm ở {1}",[h?.name||"?",te.hold.hand==="R"?o("tay phải"):o("tay trái")])}),t.jsx("button",{onClick:()=>h&&Jr(h.id,te.hold.hand,""),children:o("Thả xuống")})]})})(),te.kind==="splat"&&te.splat&&(()=>{const h=je.current?.splatExtent(te.splat);return t.jsxs("div",{className:"shot-splat",children:[t.jsx("h3",{children:o("BỐI CẢNH THẬT")}),t.jsxs("small",{className:"shot-hint",children:[te.splat.source==="world"?o("3D World do AI tạo"):o("Bản quét địa điểm thật"),h?` · ${(h.max[0]-h.min[0]).toFixed(1)} × ${(h.max[2]-h.min[2]).toFixed(1)} m`:` · ${o("đang tải…")}`]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:te.splat.flip!==!1,onChange:b=>{const E={...te.splat,flip:b.target.checked},F=je.current?.splatExtent(E);He(te.id,F?{splat:{...E,bounds:{min:F.min,max:F.max},floor:F.floor},position:[te.position[0],-F.floor*te.scale[1],te.position[2]]}:{splat:E})}}),o("Lật trục (file quét kiểu OpenCV)")]}),t.jsx(Hn,{label:"Tỷ lệ bản quét",value:te.scale[0],min:.05,step:.05,onChange:b=>He(te.id,{scale:[b,b,b]})}),t.jsx("button",{disabled:!h,onClick:()=>{h&&He(te.id,{position:[te.position[0],-h.floor*te.scale[1],te.position[2]],splat:{...te.splat,bounds:{min:h.min,max:h.max},floor:h.floor}})},children:o("Căn sàn về mặt đất")}),t.jsx("small",{className:"shot-hint",children:o('Người và camera đặt thẳng trong bối cảnh. Ảnh và video AI giữ nguyên kiến trúc, đồ đạc của bản quét. Sai hướng thì bật/tắt "Lật trục" rồi căn sàn lại.')})]})})(),Wv.includes(te.kind)&&t.jsx(Gv,{item:z.items.find(h=>h.id===te.id)??te,shot:fe,playhead:ke,patchItem:He,change:Me}),te.kind==="person"&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:o("NHẬN DIỆN NHÂN VẬT")}),t.jsxs("select",{"aria-label":o("Ảnh tham chiếu nhân vật"),value:te.reference?.nodeId||"",onChange:h=>{const b=Ya.find(F=>F.id===h.target.value),E=b?.data;He(te.id,{reference:b&&E?.url?{nodeId:b.id,url:E.url,name:E.label||"Character reference"}:null})},children:[t.jsx("option",{value:"",children:o("Không dùng ảnh nhận diện")}),Ya.map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"Image")},h.id))]}),te.reference&&t.jsx("img",{className:"shot-character-ref",src:te.reference.url,alt:te.reference.name}),t.jsx("h3",{children:o("NHÂN VẬT")}),t.jsx("button",{type:"button",className:"shot-char-open",title:o("Thay người này bằng một nhân vật có xương trong kho (giữ vị trí và chuyển động)"),onClick:()=>{Re(te.id),W("characters")},children:o("Chọn nhân vật từ thư viện…")}),te.look||te.figure&&["legs","shoulders","hips","chest","waist","weight","muscle","posture","skin","face"].some(h=>te.figure[h]!==void 0)?t.jsx("button",{type:"button",onClick:()=>He(te.id,{figure:te.figure?{height:te.figure.height,head:te.figure.head,build:te.figure.build}:void 0,look:void 0,character:void 0}),children:o("Về mannequin trơn")}):null,t.jsx("h3",{children:o("VÓC DÁNG")}),t.jsx("div",{className:"shot-add shot-figure-presets",children:Cf.map(h=>{const b=Dt(te.figure);return t.jsx("button",{className:b.height===h.figure.height&&b.head===h.figure.head&&b.build===h.figure.build?"active":"",onClick:()=>He(te.id,{figure:{...h.figure}}),children:o(h.name)},h.name)})}),t.jsx(Hn,{label:"Chiều cao (m)",value:Dt(te.figure).height,min:.3,max:3,step:.01,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),height:h})})}),t.jsxs("label",{className:"shot-joint",children:[o("Cỡ đầu")," ",t.jsxs("span",{children:[Dt(te.figure).head.toFixed(2),"×"]}),t.jsx("input",{"aria-label":o("Cỡ đầu"),type:"range",min:.7,max:2,step:.05,value:Dt(te.figure).head,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),head:+h.target.value})})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Vai / hông")," ",t.jsxs("span",{children:[Dt(te.figure).build.toFixed(2),"×"]}),t.jsx("input",{"aria-label":o("Vai / hông"),type:"range",min:.6,max:1.6,step:.05,value:Dt(te.figure).build,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),build:+h.target.value})})})]}),t.jsx("h3",{children:o("ĐẠO CỤ TRÊN TAY")}),t.jsxs("div",{className:"shot-props",children:[["R","L"].map(h=>{const b=z.items.find(F=>F.hold?.by===te.id&&F.hold.hand===h),E=z.items.filter(F=>F.id!==te.id&&!["person","splat","set","floor","wall"].includes(F.kind)&&!(F.hold&&F.hold.by!==te.id));return t.jsxs("div",{className:"shot-prop-hand",children:[t.jsxs("label",{className:"shot-field",children:[h==="R"?o("Tay phải"):o("Tay trái"),t.jsxs("select",{"aria-label":h==="R"?o("Đạo cụ tay phải"):o("Đạo cụ tay trái"),value:b?`item:${b.id}`:"",onChange:F=>Jr(te.id,h,F.target.value),children:[t.jsx("option",{value:"",children:o("— Tay không —")}),b&&t.jsx("option",{value:`item:${b.id}`,children:b.name}),t.jsx("optgroup",{label:o("Đạo cụ dựng sẵn"),children:Nf.map(F=>t.jsx("option",{value:`prop:${F}`,children:o(Ma[F].label)},F))}),E.filter(F=>F.id!==b?.id).length>0&&t.jsx("optgroup",{label:o("Vật trong cảnh"),children:E.filter(F=>F.id!==b?.id).map(F=>t.jsx("option",{value:`item:${F.id}`,children:F.name},F.id))})]})]}),b&&t.jsxs("label",{className:"shot-joint",children:[o("Gập cổ tay")," ",t.jsxs("span",{children:[b.hold.tilt??(b.prop?Ma[b.prop.kind].tilt??0:0),"°"]}),t.jsx("input",{"aria-label":o("Gập cổ tay"),type:"range",min:-90,max:90,step:5,value:b.hold.tilt??(b.prop?Ma[b.prop.kind].tilt??0:0),onChange:F=>Me(K=>({...K,items:K.items.map(Y=>Y.id===b.id?{...Y,hold:{...Y.hold,tilt:+F.target.value}}:Y)}))})]}),b&&t.jsxs("label",{className:"shot-joint",children:[o("Xoay quanh cổ tay")," ",t.jsxs("span",{children:[b.hold.angle??0,"°"]}),t.jsx("input",{"aria-label":o("Xoay đạo cụ quanh cổ tay"),type:"range",min:-180,max:180,step:5,value:b.hold.angle??0,onChange:F=>Me(K=>({...K,items:K.items.map(Y=>Y.id===b.id?{...Y,hold:{...Y.hold,angle:+F.target.value}}:Y)}))})]})]},h)}),t.jsx("small",{className:"shot-hint",children:o("Đạo cụ đi theo cẳng tay qua mọi tư thế, dáng đi, cú đánh. Kiếm, gậy, dao nối dài tầm đánh khi tính trúng đòn.")})]}),t.jsx("h3",{children:o("CHUYỂN ĐỘNG NGƯỜI")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:te.gait!=="off",onChange:h=>He(te.id,{gait:h.target.checked?"auto":"off"})}),o("Tự bước đi / chạy khi di chuyển")]}),(()=>{const h=fe.objectKeys?.[te.id]||[],b=h.filter(F=>F.pose),E=b.find(F=>Math.abs(F.time-ke)<1e-6);return t.jsxs("div",{className:"shot-pose-keys",children:[t.jsx("button",{className:E?"active":"",onClick:()=>Dn(te.id),children:E?o("◆ Cập nhật key tư thế · {0}s",[(ke*fe.duration).toFixed(1)]):o("◇ Key tư thế tại {0}s",[(ke*fe.duration).toFixed(1)])}),E&&t.jsx("button",{onClick:()=>us(te.id),children:o("Bỏ key tư thế")}),E&&t.jsxs("label",{className:"shot-pose-ease",children:[o("Kiểu chuyển vào key")," ",t.jsx("select",{"aria-label":o("Kiểu chuyển vào key"),value:E.poseEase||"smooth",onChange:F=>qa(te.id,F.target.value),children:Af.map(F=>t.jsx("option",{value:F.id,children:o(F.label)},F.id))})]}),t.jsx("small",{className:"shot-hint",children:b.length?o("{0} key tư thế · chỉnh khớp/rig tại key sẽ ghi vào key đó; giữa các key tư thế chuyển mượt.",[b.length]):o("Đặt key ở nhiều thời điểm (đứng → ngồi → giơ tay…) để tư thế chuyển động theo thời gian.")})]})})(),t.jsx(Vv,{shot:fe,item:te,playhead:ke*fe.duration,change:Me,engine:je.current,seek:h=>{$(!1),Ue(Math.max(0,Math.min(1,h/fe.duration)))}}),t.jsx(xu,{disabled:H,loop:Qo,mirror:Zo,onLoop:Qr,onMirror:Zr,onPlay:h=>{Jo(te.id,h)},person:te,playhead:ke*fe.duration}),t.jsxs("div",{className:"shot-mocap",children:[t.jsx("input",{ref:ms,type:"file",accept:".bvh,.fbx,.glb",hidden:!0,onChange:h=>{Mu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{disabled:Xr||H,onClick:()=>ms.current?.click(),title:o("Chuyển động người thật: Mixamo (.fbx), CMU (.bvh) hoặc GLB có animation"),children:[t.jsx(Ce.person,{}),Xr?o("Đang đọc…"):o("Nhập mocap (.bvh · .fbx · .glb)")]}),Ut&&t.jsxs("div",{className:"shot-mocap-card",children:[t.jsx("b",{children:Ut.name}),t.jsxs("small",{children:[Ut.duration.toFixed(1),o("s · khung xương người ✓")]}),t.jsxs("label",{className:"shot-field",children:[o("Tốc độ"),t.jsx("select",{"aria-label":o("Tốc độ mocap"),value:ps,onChange:h=>ku(+h.target.value),children:[.5,.75,1,1.25,1.5,2].map(h=>t.jsxs("option",{value:h,children:[h,"×"]},h))})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:Ur,onChange:h=>wu(h.target.checked)}),o("Di chuyển theo mocap (đi, chạy, nhảy)")]}),t.jsx("small",{className:"shot-hint",children:o("Bắt đầu tại {0}s · dùng {1}s (phần dài hơn shot bị cắt)",[(ke*fe.duration).toFixed(1),Math.min(Ut.duration/ps,(1-ke)*fe.duration).toFixed(1)])}),t.jsx("button",{className:"shot-primary",disabled:H,onClick:()=>Cu(te.id),children:o("Áp dụng cho {0}",[te.name])})]}),Tf(z,te.id)&&t.jsx("button",{onClick:()=>{$(!1),Me(h=>s0(h,te.id))},children:o("Xoá mocap của {0}",[te.name])})]}),t.jsxs("div",{className:"shot-hits",children:[t.jsx("button",{onClick:Au,children:o("⚡ Tự tạo phản ứng trúng đòn")}),Lf(fe)&&t.jsx("button",{onClick:Tu,children:o("Xoá phản ứng tự động")}),t.jsx("small",{className:"shot-hint",children:Nu||o('Đòn = key tư thế kiểu "Ra đòn nhanh". Trúng thì người kia tự bật ra; key Đỡ đòn / Né cúi / Ngả né trước cú đánh để đỡ hoặc né.')})]}),t.jsxs("h3",{children:[o("RIG PRESETS"),t.jsx("button",{className:"shot-pose-mirror",title:o("Lật tư thế trái ↔ phải"),onClick:()=>He(te.id,{pose:Ef(te.pose)}),children:o("⇆ Lật trái/phải")})]}),t.jsx("div",{className:"shot-rig-library",children:Po.map(h=>t.jsxs("section",{children:[t.jsxs("header",{children:[t.jsx("span",{children:o(h.name)}),t.jsxs("small",{children:[h.presets.length," ",o("rig")]})]}),t.jsx("div",{className:"shot-rig-grid",children:h.presets.map(b=>t.jsxs("button",{className:D1(te.pose,In[b])?"active":"",title:o("Áp dụng rig {0}",[b]),onClick:()=>Ft(te,b),children:[t.jsx(Gr,{pose:In[b]}),t.jsx("span",{children:o(b)})]},b))})]},o(h.name)))}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Thư viện pose cá nhân")}),t.jsxs("div",{className:"shot-pose-library",children:[z.poseLibrary.map(h=>t.jsxs("div",{children:[t.jsx("button",{onClick:()=>He(te.id,{pose:{...h.pose}}),children:h.name}),t.jsx("button",{"aria-label":o("Xóa {0}",[h.name]),onClick:()=>Me(b=>({...b,poseLibrary:b.poseLibrary.filter(E=>E.id!==h.id)})),children:o("×")})]},h.id)),t.jsx("button",{onClick:()=>{const h=window.prompt(o("Tên pose"),`Pose ${z.poseLibrary.length+1}`)?.trim();h&&Me(b=>({...b,poseLibrary:[...b.poseLibrary,{id:bt(),name:h,pose:structuredClone(te.pose)}]}))},children:o("+ Lưu pose hiện tại")})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Kéo tay/chân IK")}),t.jsxs("div",{className:"shot-ik-grid",children:[t.jsx(jo,{label:"Tay trái",root:te.pose.shoulderL,bend:te.pose.elbowL,upper:.29,lower:.27,onChange:(h,b)=>He(te.id,{pose:{...te.pose,shoulderL:h,elbowL:b}})}),t.jsx(jo,{label:"Tay phải",root:te.pose.shoulderR,bend:te.pose.elbowR,upper:.29,lower:.27,onChange:(h,b)=>He(te.id,{pose:{...te.pose,shoulderR:h,elbowR:b}})}),t.jsx(jo,{label:"Chân trái",root:te.pose.hipL,bend:te.pose.kneeL,upper:.43,lower:.4,onChange:(h,b)=>He(te.id,{pose:{...te.pose,hipL:h,kneeL:b}})}),t.jsx(jo,{label:"Chân phải",root:te.pose.hipR,bend:te.pose.kneeR,upper:.43,lower:.4,onChange:(h,b)=>He(te.id,{pose:{...te.pose,hipR:h,kneeR:b}})})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Chỉnh từng khớp")}),Object.keys(To).map(h=>t.jsxs("label",{className:"shot-joint",children:[o(To[h])," ",t.jsxs("span",{children:[te.pose[h]||0,"°"]}),t.jsx("input",{"aria-label":o(To[h]),type:"range",min:h.startsWith("knee")||h.startsWith("elbow")?0:-120,max:150,value:te.pose[h]||0,onChange:b=>He(te.id,{pose:{...te.pose,[h]:+b.target.value}})})]},h))]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Tay · đầu · mắt")}),t.jsx("div",{className:"shot-hand-shapes",children:["R","L"].map(h=>t.jsxs("div",{children:[t.jsx("small",{children:h==="R"?o("Tay phải"):o("Tay trái")}),t.jsx("span",{children:Vi.map(b=>t.jsx("button",{type:"button",className:If(te.pose,h,b)?"active":"",onClick:()=>He(te.id,{pose:O1(te.pose,h,b)}),children:o(b.label)},b.id))})]},h))}),t.jsxs("label",{className:"shot-field",children:[o("Mắt nhìn"),t.jsxs("select",{"aria-label":o("Mắt nhìn"),value:te.gaze||"",onChange:h=>He(te.id,{gaze:h.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Theo tư thế")}),t.jsx("option",{value:"camera",children:o("Nhìn vào camera")}),z.items.filter(h=>h.id!==te.id&&h.kind!=="splat"&&h.kind!=="set").map(h=>t.jsx("option",{value:h.id,children:o("Nhìn {0}",[h.name])},h.id))]})]}),Object.keys(qi).map(h=>{const[b,E,F]=Rf[h],K=$1(te.pose,h);return t.jsxs("label",{className:"shot-joint",children:[o(qi[h])," ",t.jsxs("span",{children:[K,F]}),t.jsx("input",{"aria-label":o(qi[h]),type:"range",min:b,max:E,value:K,disabled:(h==="eyeYaw"||h==="eyePitch")&&!!te.gaze,onChange:Y=>He(te.id,{pose:{...te.pose,[h]:+Y.target.value}})})]},h)})]})]}),t.jsx("button",{onClick:()=>{const h={...structuredClone(te),id:bt(),name:`${te.name} copy`,position:[te.position[0]+1,...te.position.slice(1)]};Me(b=>({...b,items:[...b.items,h]})),Xe(h.id)},children:o("Nhân bản")}),t.jsx("button",{onClick:()=>{tl(te.id)},children:o("Xóa đối tượng")})]})]})]}),Z==="camera"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":o("Tên shot"),value:fe.name,onChange:h=>yt({name:h.target.value})}),t.jsxs("div",{className:"shot-camera-gizmo",role:"group","aria-label":o("Chỉnh camera trong cảnh 3D"),children:[t.jsxs("button",{type:"button",className:r?"active":"","aria-pressed":r,disabled:S,title:o("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"),onClick:()=>{Xe(null),i(null),l(!r),ee(h=>h==="scale"?"translate":h)},children:[t.jsx(Ce.camera,{}),o("Chọn camera")]}),r&&["translate","rotate"].map(h=>t.jsxs("button",{type:"button",className:(D==="rotate"?"rotate":"translate")===h?"active":"","aria-pressed":(D==="rotate"?"rotate":"translate")===h,title:o(h==="translate"?"Di chuyển camera (W)":"Xoay camera (E): vòng xanh dương = nghiêng"),onClick:()=>ee(h),children:[h==="translate"?t.jsx(Ce.move,{}):t.jsx(Ce.rotate,{}),o(h==="translate"?"Di chuyển":"Xoay")]},h))]}),t.jsx("textarea",{className:"shot-note","aria-label":o("Ghi chú đạo diễn cho shot"),placeholder:o("Ghi chú đạo diễn: hành động, cảm xúc, điểm nhấn… (đưa vào prompt)"),maxLength:500,rows:2,value:fe.note||"",onChange:h=>yt({note:h.target.value})}),t.jsxs("div",{className:"shot-row",children:[t.jsx("select",{"aria-label":o("Tỷ lệ ảnh"),value:fe.aspect,onChange:h=>yt({aspect:h.target.value}),children:["16:9","9:16","1:1","21:9","4:3","2.39:1"].map(h=>t.jsx("option",{children:h},h))}),fe.motion!=="path"&&t.jsx(Hn,{label:"Lens mm",value:fe.lens,min:14,max:200,step:1,onChange:h=>yt({lens:h})})]}),t.jsxs("label",{className:"shot-field",children:[o("Thời lượng camera (giây)"),t.jsx(gn,{"aria-label":o("Thời lượng camera (giây)"),min:.1,step:"0.1",value:fe.duration,onCommit:h=>yt({duration:h})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Rung cầm tay")," ",t.jsxs("span",{children:[Math.round((fe.handheld||0)*100),"%"]}),t.jsx("input",{"aria-label":o("Rung cầm tay"),type:"range",min:0,max:1,step:.05,value:fe.handheld||0,onChange:h=>yt({handheld:+h.target.value||void 0})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:fe.impactShake!==!1,onChange:h=>{const b=h.target.checked;yt(b?{impactShake:void 0}:{impactShake:!1,impacts:void 0})}}),o("Rung camera khi trúng đòn")]}),t.jsx(C1,{shot:fe,patch:yt,progress:ke,seek:h=>{$(!1),Ue(h)},engine:je.current||null,selected:a,select:h=>{i(h),k(h?{row:"camera",id:h}:null)}}),fe.motion==="path"&&t.jsx("button",{disabled:H||!Te||!fe.cameraKeys?.length,onClick:async()=>{$(!1),se(!0),ce("");try{for(const[h,b]of(fe.cameraKeys||[]).entries())await Yn(!0,fe,h,!1,b.time,` · Key ${h+1} · ${(b.time*fe.duration).toFixed(1)}s`)}catch(h){ce(h.message)}finally{se(!1)}},children:o("Xuất các key thành ảnh tham chiếu")}),t.jsx("h3",{children:o("CHUYỂN ĐỘNG NHANH")}),t.jsxs("select",{"aria-label":o("Chuyển động camera"),value:fe.motion,onChange:h=>Uu(h.target.value),children:[t.jsx("option",{value:"path",disabled:!fe.cameraKeys?.length,children:o("Đường chạy keyframe")}),t.jsx("option",{value:"static",children:o("Đứng yên")}),t.jsx("option",{value:"dolly-in",children:o("Dolly in")}),t.jsx("option",{value:"dolly-out",children:o("Dolly out")}),t.jsx("option",{value:"truck-left",children:o("Truck trái")}),t.jsx("option",{value:"truck-right",children:o("Truck phải")}),t.jsx("option",{value:"crane-up",children:o("Crane lên")}),t.jsx("option",{value:"crane-down",children:o("Crane xuống")}),t.jsx("option",{value:"orbit-left",children:o("Orbit trái")}),t.jsx("option",{value:"orbit-right",children:o("Orbit phải")}),t.jsx("option",{value:"custom",children:o("Tùy chỉnh")})]}),fe.motion!=="static"&&fe.motion!=="path"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[o("Xem chuyển động")," ",t.jsxs("span",{children:[Math.round(ke*100),"%"]}),t.jsx("input",{"aria-label":o("Tiến trình camera"),type:"range",min:0,max:100,value:ke*100,onChange:h=>Ue(+h.target.value/100)})]}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Camera kết thúc")}),gs(o("Vị trí cuối"),fe.endPosition,h=>yt({endPosition:h,motion:"custom"})),gs(o("Điểm nhìn cuối"),fe.endTarget,h=>yt({endTarget:h,motion:"custom"})),t.jsx(Hn,{label:"Lens cuối mm",value:fe.endLens,min:14,max:200,step:1,onChange:h=>yt({endLens:h,motion:"custom"})})]})]}),t.jsxs("fieldset",{disabled:fe.motion==="path",style:{display:fe.motion==="path"?"none":void 0},children:[t.jsx("button",{onClick:()=>yt(je.current?.captureCamera()||{}),children:o("Dùng góc quan sát làm camera")}),t.jsx("div",{className:"shot-add",children:["Toàn","Trung","Cận","Thấp","Cao","Qua vai"].map((h,b)=>t.jsx("button",{onClick:()=>{const E=te?.position||[0,0,0];yt({position:[[3,2,6],[0,1.5,3],[0,1.7,1.2],[1,.3,3],[2,5,3],[.5,1.7,-1.5]][b].map((K,Y)=>K+E[Y]),target:[E[0],E[1]+(b===2?1.65:1.2),E[2]],roll:0})},children:o(h)},h))}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Thông số camera")}),gs(o("Vị trí máy"),fe.position,h=>yt({position:h})),gs(o("Điểm nhìn"),fe.target,h=>yt({target:h})),t.jsx(Hn,{label:"Nghiêng máy °",value:fe.roll,min:-180,max:180,step:1,onChange:h=>yt({roll:h})}),t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(h=>{const b=h.shots.filter(E=>E.id!==h.activeShot);return{...h,shots:b,activeShot:b[0].id}}),children:o("Xóa camera này")})]})]}),fe.motion==="path"&&t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(h=>{const b=h.shots.filter(E=>E.id!==h.activeShot);return{...h,shots:b,activeShot:b[0].id}}),children:o("Xóa camera đường chạy")}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Prompt bố cục")}),t.jsx("textarea",{"aria-label":o("Prompt bố cục"),readOnly:!0,value:ki(z),rows:8}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(ki(z)).then(()=>dt.getState().toast(o("Đã copy prompt"),"ok")).catch(()=>ce("Không truy cập được clipboard; hãy chọn và copy nội dung.")),children:o("Copy prompt")})]})]}),Z==="light"&&t.jsx("div",{className:"shot-light-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("select",{"aria-label":o("Thời điểm trong ngày"),value:na.time,onChange:h=>{const b=h.target.value;ai({time:b,elevation:Yl[b].elevation})},children:Ff.map(h=>t.jsx("option",{value:h,children:o(Yl[h].label)},h))}),t.jsxs("label",{className:"shot-joint",children:[o("Hướng mặt trời")," ",t.jsxs("span",{children:[Math.round(na.azimuth),"°"]}),t.jsx("input",{"aria-label":o("Hướng mặt trời"),type:"range",min:0,max:359,value:Math.round(na.azimuth),onChange:h=>ai({azimuth:+h.target.value})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Độ cao mặt trời")," ",t.jsxs("span",{children:[Math.round(na.elevation),"°"]}),t.jsx("input",{"aria-label":o("Độ cao mặt trời"),type:"range",min:1,max:89,value:Math.round(na.elevation),onChange:h=>ai({elevation:+h.target.value})})]}),t.jsx("small",{className:"shot-hint",children:o("Dùng chung cho mọi shot của cảnh, để hướng sáng không lệch giữa các góc máy.")}),t.jsxs("label",{className:"shot-field shot-style-refs",children:[t.jsxs("span",{children:[o("Ảnh phong cách bối cảnh")," · ",sa.length,"/",wi]}),t.jsxs("select",{"aria-label":o("Thêm ảnh phong cách bối cảnh"),value:"",disabled:sa.length>=wi,onChange:h=>{const b=Ya.find(F=>F.id===h.target.value),E=b?.data;b&&E?.url&&Me(F=>({...F,styleRefs:[...(F.styleRefs||[]).filter(K=>K.nodeId!==b.id),{nodeId:b.id,url:E.url,name:E.label||"Location look"}].slice(0,wi)}))},children:[t.jsx("option",{value:"",children:o("+ Chọn ảnh trên canvas…")}),Ya.filter(h=>!sa.some(b=>b.nodeId===h.id)).map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"Image")},h.id))]})]}),sa.length>0&&t.jsx("div",{className:"shot-style-strip",children:sa.map(h=>t.jsxs("span",{children:[t.jsx("img",{src:h.url,alt:h.name}),t.jsx("button",{"aria-label":o("Bỏ {0}",[h.name]),onClick:()=>Me(b=>({...b,styleRefs:(b.styleRefs||[]).filter(E=>E.nodeId!==h.nodeId)})),children:"×"})]},h.nodeId))}),t.jsx("small",{className:"shot-hint",children:o("Khoá chất liệu, màu và đồ đạc của bối cảnh cho mọi shot khi tạo ảnh thật và video.")})]})}),Z==="shots"&&t.jsx("div",{className:"shot-shots-section",children:t.jsx("ol",{className:"shot-shotlist",children:z.shots.map((h,b)=>{const E=ul[b];return t.jsxs("li",{"data-shot":h.id,className:h.id===z.activeShot?"active":"",children:[t.jsxs("button",{className:"shot-shotlist-pick","aria-label":o("Chọn {0}",[h.name]),"aria-current":h.id===z.activeShot,disabled:!!A,onClick:()=>Me(F=>({...F,activeShot:h.id})),children:[mt[h.id]?t.jsx("img",{src:mt[h.id],alt:""}):t.jsx("span",{className:"shot-thumb-empty","aria-hidden":"true"}),t.jsxs("span",{className:"shot-shotlist-meta",children:[t.jsx("b",{children:h.name}),t.jsxs("small",{children:[ji(E.start),"–",ji(E.end)," · ",Number(h.lens.toFixed(1)),"mm"]}),h.note?.trim()&&t.jsx("small",{className:"shot-shotlist-note",children:h.note.trim()})]})]}),t.jsxs("span",{className:"shot-shotlist-order",children:[t.jsx("button",{"aria-label":o("Đưa {0} lên",[h.name]),disabled:b===0||!!A,onClick:()=>pl(h.id,-1),children:"↑"}),t.jsx("button",{"aria-label":o("Đưa {0} xuống",[h.name]),disabled:b===z.shots.length-1||!!A,onClick:()=>pl(h.id,1),children:"↓"})]}),t.jsx("button",{className:"shot-shotlist-delete","aria-label":o("Xóa {0}",[h.name]),title:z.shots.length<2?o("Cảnh cần ít nhất một shot"):o("Xóa {0} (hoàn tác bằng ⌘Z)",[h.name]),disabled:z.shots.length<2||!!A,onClick:()=>ml(h.id),children:t.jsx(Ce.trash,{})})]},h.id)})})}),Z==="notes"&&t.jsx("div",{className:"shot-notes-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("button",{className:oe?"active":"","aria-pressed":oe,disabled:!Te||Ls.length>=Ql,onClick:Ou,children:oe?o("Bấm vào cảnh để ghim… (bấm lại để huỷ)"):o("+ Ghim ghi chú vào cảnh")}),t.jsx("ol",{className:"shot-note-list",children:Ls.map((h,b)=>t.jsxs("li",{children:[t.jsx("span",{children:b+1}),t.jsx("input",{"aria-label":o("Ghi chú {0}",[b+1]),value:h.text,maxLength:Zl,onChange:E=>Du(h.id,E.target.value)}),t.jsx("button",{"aria-label":o("Xoá ghi chú {0}",[b+1]),onClick:()=>zu(h.id),children:"×"})]},h.id))}),Ls.length>0&&t.jsx("button",{disabled:H||!Te,onClick:()=>void Ju(),children:o("Tải PNG có ghi chú")}),t.jsx("small",{className:"shot-hint",children:o("Ghi chú gắn vào vị trí trong không gian 3D nên đúng chỗ ở mọi góc máy; chỉ hiện trong khung dựng, được đưa vào prompt và bản PNG có ghi chú.")})]})}),Z==="series"&&t.jsx("div",{className:"shot-series-section",children:t.jsx("div",{className:"shot-panel-body",children:t.jsx(L1,{stage:z,nodeId:e,selected:z.items.find(h=>h.id===J)||null,disabled:H||!!A,change:Me,onError:ce,onSelect:Xe})})})]}),t.jsx("div",{className:"shot-resize shot-resize-x",role:"separator","aria-orientation":"vertical","aria-label":o("Kéo để đổi độ rộng bảng công cụ"),onPointerDown:h=>ci(h,"drawer")})]}),t.jsxs("main",{className:"shot-center",children:[t.jsxs("div",{className:"shot-monitor",children:[t.jsxs("div",{className:`shot-topbar ${X?"":"collapsed"}`,children:[t.jsxs("div",{className:"shot-shot-switcher",children:[t.jsx("select",{"aria-label":o("Chọn shot"),value:fe.id,onChange:h=>Me(b=>({...b,activeShot:h.target.value})),children:z.shots.map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))}),t.jsxs("button",{onClick:()=>{const h={...structuredClone(fe),id:bt(),name:`Shot ${z.shots.length+1}`};Me(b=>({...b,shots:[...b.shots,h],activeShot:h.id}))},children:[t.jsx(Ce.save,{}),t.jsx("span",{className:"lbl",children:o("+ Lưu góc mới").replace("+ ","")})]}),t.jsx(A1,{shot:fe,patch:yt,disabled:H||!!A})]}),t.jsxs("div",{className:"shot-viewtools",hidden:!X,children:[D==="scale"&&te&&!te.locked&&t.jsx(Hn,{label:"Tỷ lệ đồng đều",value:te.scale[0],min:.05,step:ue?.1:.05,onChange:h=>He(te.id,{scale:te.scale.map(b=>b*h/te.scale[0])})}),t.jsxs("span",{className:"shot-tools-hint",children:[D==="scale"?o("Kéo ô vuông trên trục để đổi kích thước."):"",ue?o(" Bước: 1 m · 15° · tỷ lệ 0,1"):""]}),["translate","rotate","scale"].map((h,b)=>t.jsxs("button",{className:h===D?"active":"",title:o(["Di chuyển","Xoay","Kích thước"][b]),onClick:()=>ee(h),children:[[t.jsx(Ce.move,{},"m"),t.jsx(Ce.rotate,{},"r"),t.jsx(Ce.scale,{},"s")][b],t.jsx("span",{className:"lbl",children:o(["Di chuyển","Xoay","Kích thước"][b])})]},h)),t.jsxs("button",{className:ue?"active":"",title:ue?o("Bám lưới: Bật"):o("Bám lưới: Tắt"),onClick:()=>Ee(!ue),children:[t.jsx(Ce.snap,{}),t.jsx("span",{className:"lbl",children:ue?o("Bám lưới: Bật"):o("Bám lưới: Tắt")})]}),t.jsxs("button",{className:ye==="high"?"active":"","aria-pressed":ye==="high",title:ye==="high"?o("Chất lượng cao: bóng mềm, AO, bloom. Bấm để chuyển sang Nháp (nhanh hơn). Xuất video/ảnh luôn dùng Chất lượng cao."):o("Nháp: nhanh, cho máy yếu. Bấm để bật Chất lượng cao. Xuất video/ảnh luôn dùng Chất lượng cao."),onClick:()=>ne(ye==="high"?"draft":"high"),children:[t.jsx(Ce.cinema,{}),t.jsx("span",{className:"lbl",children:ye==="high"?o("Chất lượng cao"):o("Nháp")})]}),t.jsxs("button",{className:Ie?"active":"","aria-pressed":Ie,title:Ie?o("Nhân vật người thật vẽ chất lượng cao (thân mượt, mặt, tóc, quần áo). Bấm để vẽ nhẹ hơn cho máy yếu. Người thường là mannequin; chọn nhân vật trong thư viện để thành người thật."):o("Máy yếu: nhân vật người thật vẽ bản nhẹ. Bấm để bật chất lượng cao."),onClick:()=>{const h=!Ie;Oy(h),ze(h)},children:[t.jsx(Ce.person,{}),t.jsx("span",{className:"lbl",children:Ie?o("Người thật"):o("Mannequin")})]}),t.jsxs("button",{title:o("Từ trên xuống"),onClick:()=>je.current?.view(!0),children:[t.jsx(Ce.top,{}),t.jsx("span",{className:"lbl",children:o("Từ trên xuống")})]}),t.jsxs("button",{title:o("Tập trung (F)"),"aria-keyshortcuts":"F",onClick:()=>je.current?.view(),children:[t.jsx(Ce.focus,{}),t.jsx("span",{className:"lbl",children:o("Tập trung")})]})]}),t.jsx("button",{className:"shot-tools-toggle","aria-expanded":X,title:X?o("Thu gọn công cụ"):o("Mở công cụ"),onClick:()=>{const h=!X;re(h);try{localStorage.setItem("clipoox.shot.tools",h?"1":"0")}catch{}},children:X?t.jsx(Ce.chevUp,{}):t.jsx(Ce.chevDown,{})})]}),t.jsx("div",{className:"shot-viewport",ref:lt,onDragOver:h=>{(h.dataTransfer.types.includes(gr)||h.dataTransfer.types.includes(Ao))&&(h.preventDefault(),h.dataTransfer.dropEffect="copy")},onDrop:h=>{h.dataTransfer.types.includes(Ao)?Pu(h):Fu(h)}}),t.jsx("span",{className:"shot-viewlabel",children:o("GÓC QUAN SÁT · không đổi camera xuất ảnh")}),te&&z1(te)&&!A&&(At===te.id?t.jsx(Jv,{engine:Te?je.current:null,stage:z,shot:fe,item:te,playhead:ke*fe.duration,change:Me,onDone:()=>qe(null)}):t.jsxs("button",{type:"button",className:"shot-pose-chip",title:o("Kéo trực tiếp các khớp trên nhân vật (đầu, ngực, khuỷu, tay, hông, gối, chân)"),onClick:()=>{$(!1),qe(te.id)},children:[t.jsx(Ce.person,{}),o("Chỉnh dáng")]})),te&&Z!==(Pa(te)?"mixfx":te.kind==="fx"?"fxedit":"objects")&&t.jsxs("button",{type:"button",className:"shot-edit-chip",onClick:()=>zn(Pa(te)?"mixfx":te.kind==="fx"?"fxedit":"objects"),children:[t.jsx(Ce.pen,{}),o("Chỉnh {0}",[te.name])]})]}),t.jsx("div",{className:"shot-resize shot-resize-y",role:"separator","aria-orientation":"horizontal","aria-label":o("Kéo để đổi chiều cao timeline"),onPointerDown:h=>ci(h,"timeline")}),t.jsx(Mx,{loop:u,onLoop:()=>m(h=>!h),range:d,rangeOn:p,onRangeOn:()=>x(h=>!h),onEnd:()=>{$(!1),Ue(1)},onKeyAll:xl,onCopy:bl,onPaste:yl,canPaste:v,onEase:Wu,onNudge:vl,stage:z,cameraActive:r,cameraHidden:C,cameraLocked:S,onToggle:Ku,onProp:Hu,height:pe.timeline,onHeight:h=>me(b=>({...b,timeline:h})),shot:fe,items:z.items,fxBars:$u,onParent:Bu,onFxTiming:(h,b)=>Me(E=>({...E,shots:E.shots.map(F=>F.id===E.activeShot?{...F,fxTiming:{...F.fxTiming,[h]:Ar({...Mn(E.items.find(K=>K.id===h),F),...b,off:!1},F.duration)}}:F)})),time:ke,playing:_,selected:y,picked:T,onPick:gl,onSeek:h=>{$(!1),Ue(h)},onPlay:()=>{!_&&ke>=1&&Ue(0),$(!_)},onRow:h=>{i(null),k(null),j([]),Xe(h==="camera"?null:h),l(h==="camera"&&!S);{const b=z.items.find(E=>E.id===h);Pa(b)?zn("mixfx"):b?.kind==="fx"&&zn("fxedit")}},onSelect:_u,onAdd:oi,onMove:Gu,onDelete:jl})]}),t.jsxs("aside",{className:"shot-right",children:[t.jsx("div",{className:"shot-resize shot-resize-x shot-resize-left",role:"separator","aria-orientation":"vertical","aria-label":o("Kéo để đổi độ rộng cột xem trước"),onPointerDown:h=>ci(h,"right")}),t.jsxs("section",{className:"shot-preview-pinned",children:[t.jsx("h3",{children:o("KHUNG CAMERA")}),t.jsx("div",{className:"shot-preview",style:{aspectRatio:Mi(fe.aspect).join(" / "),width:`min(100%, ${30*Mi(fe.aspect)[0]/Mi(fe.aspect)[1]}dvh)`},ref:vt}),t.jsxs("div",{className:"shot-camera-player",children:[t.jsx("button",{"aria-label":_?o("Tạm dừng camera"):o("Phát camera"),onClick:()=>{!_&&ke>=1&&Ue(0),$(!_)},children:o(_?"Ⅱ Pause":"▶ Play")}),t.jsx("button",{"aria-label":o("Về đầu"),onClick:()=>{$(!1),Ue(0)},children:"↤"}),t.jsxs("span",{children:[(ke*fe.duration).toFixed(1)," / ",fe.duration,o("s")]}),t.jsx("input",{"aria-label":o("Thời gian camera"),type:"range",min:0,max:1,step:1e-4,value:ke,onChange:h=>{$(!1),Ue(+h.target.value)}})]}),z.plate&&t.jsxs("div",{className:"shot-plate-row",title:o("Video quay thật phía sau camera: chỉ để canh hiệu ứng. Khi xuất VFX, hiệu ứng ra riêng trên nền đen."),children:[t.jsxs("span",{children:["🎬 ",z.plate.label]}),t.jsxs("label",{children:[t.jsx("input",{type:"checkbox","aria-label":o("Hiện video nền"),checked:!z.plate.hidden,onChange:h=>{const b=h.target.checked;Me(E=>E.plate?{...E,plate:{...E.plate,hidden:!b}}:E)}}),o("Hiện video nền")]})]}),z.plate&&t.jsxs("div",{className:"shot-plate-tools",children:[t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e||H,title:o("Người đứng thế đi theo người trong video (vị trí, khoảng cách, hướng, tay chân): hiệu ứng gắn vào nó sẽ bám theo người thật."),onClick:()=>void Yr("follow"),children:_e?.kind==="follow"?o("Đang đọc người… {0}%",[_e.pct]):o("🧍 Bám theo người")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e||H,title:o("Camera của cảnh xoay / lia / zoom giống camera đã quay video."),onClick:()=>void Yr("camera"),children:_e?.kind==="camera"?o("Đang track camera… {0}%",[_e.pct]):o("🎥 Lấy camera từ video")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e,title:o("Tải camera của shot thành script Python cho Blender, để dựng hiệu ứng khớp với video."),onClick:()=>void Su(),children:o("⬇ Camera cho Blender")})]}),we.length>0&&t.jsxs("div",{className:"shot-placement",role:"status","aria-label":o("Cảnh báo vị trí nhân vật"),children:[t.jsx("ul",{children:we.map(h=>t.jsxs("li",{children:[t.jsxs("span",{children:["⚠ ",h.type==="floating"?o("{0} lơ lửng {1} m so với mặt đỡ",[h.name,String(h.amount)]):h.type==="sinking"?o("{0} chìm {1} m dưới mặt đỡ",[h.name,String(h.amount)]):h.type==="no_seat"?h.seat?o("{0} ngồi lơ lửng — có thể ngồi lên “{1}”",[h.name,h.seat]):o("{0} ngồi mà không có chỗ ngồi gần",[h.name]):o("{0} đang xuyên vào {1}",[h.name,(h.with||[]).join(", ")])]}),h.fix&&!h.locked&&t.jsx("button",{onClick:()=>Gt([h]),children:h.type==="intersect"?o("Đẩy ra chỗ trống"):h.type==="no_seat"?o("Ngồi lên ghế gần nhất"):o("Đặt xuống mặt đỡ")})]},h.itemId+h.type))}),we.filter(h=>h.fix&&!h.locked).length>1&&t.jsx("button",{className:"shot-placement-all",onClick:()=>Gt(we),children:o("Sửa tất cả ({0})",[String(we.filter(h=>h.fix&&!h.locked).length)])})]}),dl.length>0&&t.jsx("ul",{className:"shot-warnings",role:"status","aria-label":o("Cảnh báo liền mạch"),children:dl.map(h=>t.jsxs("li",{children:["⚠ ",o(h)]},h))})]}),t.jsx("section",{className:"shot-agent-card",children:t.jsx(v1,{stage:z,disabled:H||L||!!A,lock:{playhead:Math.round(ke*fe.duration*rn(fe))/rn(fe),onChange:h=>yt({lockUntil:Pf(h,fe.duration)||void 0})},agent:{selected:J,time:ke,getBounds:()=>je.current?.objectBounds()||{},getColliders:()=>je.current?.placementColliders()||[],onPreview:(h,b)=>{$(!1);const E=Ti(Ae.current,h);O({stage:E,plan:h,time:ke,done:b}),Ue(Math.min(...h.tracks.map(F=>F.keys[0].seconds))/h.duration),$(!0)},onApply:h=>{$(!1),Me(b=>Ti(b,h)),Ue(0),i(null),k(null)}}})})]})]})]})}export{rj as default};
|
|
287
|
+
`),onClick:()=>i(a==="fps"?null:"fps"),children:[u,o("fps")]}),a==="fps"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":o("Tốc độ khung hình (fps)"),children:[nd.map(M=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u===M,className:u===M?"active":"",title:M===40?o("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[M]):void 0,onClick:()=>p({fps:M}),children:[M," ",o("fps")]},M)),m.fps.map(M=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",M]},M))]})]})]})}function kr(e,n,s){const a=Pt();if(!a||!e.url)return null;const i=a.nodes().find(l=>l.type==="image"&&l.data.gcsUri===e.gcsUri);if(i)return i.id;const r=a.getNode(n);return a.addNode("image",{url:e.url,gcsUri:e.gcsUri,label:e.name},r?{x:r.position.x-360,y:r.position.y+s*220}:void 0,{select:!1})}function Eh(e,n){const s=e?Pt()?.getNode(e)?.data:void 0;return s?.gcsUri&&/^gs:\/\//.test(s.gcsUri)?{gcsUri:s.gcsUri,...s.url?{url:s.url}:{},name:n}:void 0}function T1(e,n,s){let a=!1;const i=e.items.map((r,l)=>{const c=r.castId?n.cast.find(m=>m.id===r.castId):void 0;if(!c)return r;const u={...r,name:c.name,color:c.color};if(r.kind==="person"&&(u.figure=c.figure?Dt(c.figure):void 0,u.look=c.look),c.reference&&(r.reference?.nodeId?Pt()?.getNode(r.reference.nodeId)?.data?.gcsUri:void 0)!==c.reference.gcsUri){const d=kr(c.reference,s,l);d&&(u.reference={nodeId:d,url:c.reference.url||"",name:c.reference.name})}return JSON.stringify(u)!==JSON.stringify(r)&&(a=!0),u});return a?{...e,items:i}:null}function L1({stage:e,nodeId:n,selected:s,disabled:a,change:i,onError:r,onSelect:l}){ht();const[c,u]=R.useState(null),[m,d]=R.useState(null),[f,p]=R.useState(""),[x,g]=R.useState(!1),v=R.useRef(null),w=e.series;R.useEffect(()=>{if(!w?.id){d(null);return}let j=!0;return k0(w.id).then(L=>{if(j&&(d(L),v.current!==L.id)){v.current=L.id;const N=T1(e,L,n);N&&i(()=>N)}}).catch(L=>r(L.message)),()=>{j=!1}},[w?.id]),R.useEffect(()=>{!w?.id&&c===null&&w0().then(j=>u(j.series)).catch(()=>u([]))},[w?.id,c]);const C=async j=>{g(!0);try{const{id:L,updatedAt:N,...A}=j;await M0(L,A),d(j)}catch(L){r(L.message)}finally{g(!1)}},M=async()=>{const j=f.trim();if(!j)return;const L={id:bt(),name:j,cast:[],locations:[],episodes:[]};await C(L),i(N=>({...N,series:{id:L.id,name:j}})),p("")},S=async()=>{if(!m||!s||!["person","model"].includes(s.kind))return;const j=s.castId&&m.cast.some(A=>A.id===s.castId)?s.castId:bt(),L=Eh(s.reference?.nodeId,s.reference?.name||s.name),N={id:j,name:s.name.slice(0,60),color:/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#baca9e",...s.kind==="person"&&s.figure?{figure:Dt(s.figure)}:{},...s.kind==="person"&&s.look?{look:s.look}:{},...L?{reference:L}:{},...s.kind==="model"&&s.model?{model:{gcsUri:s.model.gcsUri,name:s.model.name,...s.model.height?{height:s.model.height}:{}}}:{}};await C({...m,cast:[...m.cast.filter(A=>A.id!==j),N]}),i(A=>({...A,items:A.items.map(O=>O.id===s.id?{...O,castId:j}:O)})),s.reference&&!L&&r(o("Ảnh nhận diện không phải ảnh đã tải lên / tạo trên Clipoox nên không lưu vào thư viện được."))},I=j=>{const L=e.items.length,N=j.model?{...fn("model",L),model:j.model}:{...fn("person",L),...j.figure?{figure:Dt(j.figure)}:{},...j.look?{look:j.look}:{}},A=j.reference?kr(j.reference,n,L):null,O={...N,name:j.name,color:j.color,castId:j.id,...A&&j.reference?{reference:{nodeId:A,url:j.reference.url||"",name:j.reference.name}}:{}};i(_=>({..._,items:[..._.items,O]})),l(O.id)},y=async j=>{if(!m)return;const L=e.items.find(_=>_.kind==="set"&&_.set),N=(e.styleRefs||[]).flatMap(_=>{const $=Eh(_.nodeId,_.name);return $?[$]:[]}),O={id:m.locations.find(_=>_.name===j)?.id||bt(),name:j,...L?.set?{setId:L.set.id}:{},lighting:Ta(e.lighting),...N.length?{styleRefs:N}:{}};await C({...m,locations:[...m.locations.filter(_=>_.id!==O.id),O]}),i(_=>({..._,series:{..._.series,location:O.id}}))},k=j=>{const L=(j.styleRefs||[]).flatMap((N,A)=>{const O=kr(N,n,10+A);return O?[{nodeId:O,url:N.url||"",name:N.name}]:[]});i(N=>{const A=j.setId&&N.items.some(_=>_.kind==="set"&&_.set?.id===j.setId),O=j.setId&&!A?[{...fn("set",N.items.length),name:j.name,set:{id:j.setId,name:j.name}},...N.items]:N.items;return{...N,items:O,...j.lighting?{lighting:Ta(j.lighting)}:{},...L.length?{styleRefs:L}:{},series:{...N.series,location:j.id}}})},T=async j=>{if(!m||!j.trim())return;const L={id:bt(),name:j.trim().slice(0,80)};await C({...m,episodes:[...m.episodes,L]}),i(N=>({...N,series:{...N.series,episode:L.id}}))};return w?t.jsxs("div",{className:"shot-series",children:[t.jsxs("div",{className:"shot-series-row",children:[t.jsx("b",{children:w.name}),t.jsx("button",{disabled:a,onClick:()=>i(j=>({...j,series:void 0})),children:o("Bỏ gắn")})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o("Tập")}),t.jsxs("select",{"aria-label":o("Tập"),value:w.episode||"",disabled:a,onChange:j=>{if(j.target.value==="+"){const L=window.prompt(o("Tên tập"),`Tập ${m.episodes.length+1}`);L&&T(L);return}i(L=>({...L,series:{...L.series,episode:j.target.value||void 0}}))},children:[t.jsx("option",{value:"",children:"—"}),m.episodes.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id)),t.jsx("option",{value:"+",children:o("+ Tập mới…")})]})]}),t.jsxs("h4",{children:[o("Dàn nhân vật")," · ",m.cast.length]}),t.jsx("ul",{className:"shot-series-list",children:m.cast.map(j=>t.jsxs("li",{children:[j.reference?.url?t.jsx("img",{src:j.reference.url,alt:""}):t.jsx("span",{className:"shot-series-dot",style:{background:j.color}}),t.jsxs("span",{children:[j.name,j.figure?t.jsxs("small",{children:[" · ",j.figure.height.toFixed(2)," m"]}):null]}),t.jsx("button",{"aria-label":o("Đưa {0} vào cảnh",[j.name]),disabled:a,onClick:()=>I(j),children:"+"})]},j.id))}),t.jsx("button",{disabled:a||x||!s||!["person","model"].includes(s.kind),onClick:()=>void S(),children:s?.castId?o("Cập nhật nhân vật vào series"):o("Lưu nhân vật đang chọn vào series")}),t.jsxs("h4",{children:[o("Bối cảnh")," · ",m.locations.length]}),t.jsx("ul",{className:"shot-series-list",children:m.locations.map(j=>t.jsxs("li",{className:w.location===j.id?"active":"",children:[t.jsx("span",{className:"shot-series-dot","aria-hidden":"true",children:"⌂"}),t.jsxs("span",{children:[j.name,j.setId?t.jsxs("small",{children:[" · ",o("có set")]}):null]}),t.jsx("button",{"aria-label":o("Áp dụng bối cảnh {0}",[j.name]),disabled:a,onClick:()=>k(j),children:o("Dùng")})]},j.id))}),t.jsx("button",{disabled:a||x,onClick:()=>{const j=window.prompt(o("Tên bối cảnh"),e.items.find(L=>L.kind==="set")?.name||`Bối cảnh ${m.locations.length+1}`);j?.trim()&&y(j.trim().slice(0,60))},children:o("Lưu bối cảnh hiện tại vào series")})]})]}):t.jsxs("div",{className:"shot-series",children:[t.jsxs("select",{"aria-label":o("Chọn series"),value:"",disabled:a||!c?.length,onChange:j=>{const L=c?.find(N=>N.id===j.target.value);L&&i(N=>({...N,series:{id:L.id,name:L.name}}))},children:[t.jsx("option",{value:"",children:c===null?o("Đang tải…"):c.length?o("Gắn shot vào series…"):o("Chưa có series")}),c?.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id))]}),t.jsxs("form",{className:"shot-series-row",onSubmit:j=>{j.preventDefault(),M()},children:[t.jsx("input",{"aria-label":o("Tên series mới"),placeholder:o('Tên series mới, ví dụ "Chuyện quán cà phê"'),maxLength:80,value:f,onChange:j=>p(j.target.value),disabled:a||x}),t.jsx("button",{disabled:a||x||!f.trim(),children:o("Tạo")})]}),t.jsx("small",{className:"shot-hint",children:o("Series giữ dàn nhân vật và bối cảnh dùng chung cho mọi shot, mọi canvas. Sửa nhân vật trong series thì mọi shot dùng nhân vật đó cập nhật theo.")})]})}function E1({x:e,y:n,items:s,canPaste:a,hiddenCount:i,blenderKeys:r,renaming:l,onBlenderKeys:c,onAction:u,onRename:m,onClose:d}){const f=R.useRef(null),[p,x]=R.useState({left:e,top:n}),[g,v]=R.useState(s[0]?.name??""),w=j=>s.length>0&&s.every(j),C=s[0]?.shading,M=j=>r?j:void 0,S=s.length?[[{action:"shade-smooth",label:"Bề mặt mượt",check:"shading",checked:w(j=>j.shading==="smooth")},{action:"shade-auto",label:"Mượt tự động (30°)",check:"shading",checked:w(j=>j.shading==="auto")},{action:"shade-flat",label:"Bề mặt phẳng",check:"shading",checked:w(j=>j.shading==="flat")},...C||s.some(j=>j.shading)?[{action:"shade-reset",label:"Bề mặt như gốc",check:"shading"}]:[]],[{action:"origin-center",label:"Đặt tâm vào giữa khối",check:"origin"},{action:"origin-bottom",label:"Đặt tâm ở đáy khối",check:"origin"},...s.some(j=>j.origin)?[{action:"origin-reset",label:"Tâm như gốc",check:"origin"}]:[]],[{action:"copy",label:"Sao chép",keys:"Ctrl+C",check:"copy"},{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"duplicate",label:"Nhân bản",keys:M("Shift+D"),check:"duplicate"},{action:"duplicate-linked",label:"Nhân bản liên kết",keys:M("Alt+D"),check:"duplicate"},...s.some(j=>j.link)?[{action:"unlink",label:"Bỏ liên kết",check:"unlink"}]:[]],[{action:"mirror-x",label:"Lật theo X",check:"mirror",checked:w(j=>(j.mirror?.[0]??1)<0)},{action:"mirror-y",label:"Lật theo Y",check:"mirror",checked:w(j=>(j.mirror?.[1]??1)<0)},{action:"mirror-z",label:"Lật theo Z",check:"mirror",checked:w(j=>(j.mirror?.[2]??1)<0)},{action:"key",label:"Thêm key",keys:"K",check:"key"},{action:"physics-drop",label:"Rơi tự nhiên…",check:"physics"}],[{action:"hide",label:"Ẩn",keys:M("H"),check:"hide"},{action:"lock",label:w(j=>j.locked)?"Mở khoá":"Khoá",check:"lock"},{action:"delete",label:"Xoá",keys:M("X"),check:"delete"}],[{action:"rig",label:"AI · Auto-Rig…",check:"rig"},{action:"rig",label:"AI · Retexture",soon:!0}]]:[[{action:"paste",label:"Dán",keys:"Ctrl+V"},{action:"select-all",label:"Chọn tất cả",keys:M("A")},{action:"box-select",label:"Chọn theo vùng",keys:M("B")},{action:"unhide-all",label:"Hiện tất cả",keys:M("Alt+H")}]],I=j=>j.soon?"Sắp có":j.action==="paste"?a?null:"Chưa sao chép đối tượng nào":j.action==="unhide-all"?i?null:"Không có đối tượng nào đang ẩn":j.check?s.some(L=>!wo(L,j.check))?null:wo(s[0],j.check):null,y=s.length!==1?"Chọn một đối tượng để đổi tên":wo(s[0],"rename");R.useLayoutEffect(()=>{const j=f.current;if(!j)return;const L=j.getBoundingClientRect();x({left:Math.max(4,Math.min(e,innerWidth-L.width-4)),top:Math.max(4,Math.min(n,innerHeight-L.height-4))})},[e,n,l]),R.useEffect(()=>{const j=f.current;if(!j)return;l?j.querySelector("input[type=text]")?.select():j.querySelector("[role=menuitem]:not([disabled])")?.focus();const L=N=>{j.contains(N.target)||d()};return document.addEventListener("mousedown",L,!0),()=>document.removeEventListener("mousedown",L,!0)},[l,d]);const k=j=>{if(j.key==="Escape"){j.preventDefault(),d();return}if(j.key!=="ArrowDown"&&j.key!=="ArrowUp")return;j.preventDefault();const L=[...f.current.querySelectorAll("[role=menuitem]:not([disabled]),[role=menuitemcheckbox]")],N=L.indexOf(document.activeElement);L[(N+(j.key==="ArrowDown"?1:-1)+L.length)%L.length]?.focus()},T=s.length>1?o("{0} đối tượng",[s.length]):s[0]?.name;return t.jsxs("div",{className:"shot-ctxmenu",role:"menu","aria-label":o("Menu đối tượng"),ref:f,style:p,onKeyDown:k,onContextMenu:j=>j.preventDefault(),children:[T&&t.jsx("div",{className:"shot-ctxmenu-title",children:T}),l?t.jsxs("form",{className:"shot-ctxmenu-rename",onSubmit:j=>{j.preventDefault(),g.trim()&&m(g.trim().slice(0,80))},children:[t.jsx("input",{type:"text","aria-label":o("Tên mới"),value:g,maxLength:80,onChange:j=>v(j.target.value)}),t.jsx("button",{type:"submit",children:o("Đổi tên")})]}):t.jsxs(t.Fragment,{children:[s.length>0&&t.jsxs("button",{type:"button",role:"menuitem",disabled:!!y,title:y?o(y):void 0,onClick:()=>u("rename"),children:[t.jsx("span",{children:o("Đổi tên…")}),r&&t.jsx("kbd",{children:"F2"})]}),S.map((j,L)=>t.jsx("div",{className:"shot-ctxmenu-group",role:"group",children:j.map((N,A)=>{const O=I(N);return t.jsxs("button",{type:"button",role:"menuitem",disabled:!!O,title:O?o(O):void 0,"aria-checked":N.checked===void 0?void 0:N.checked,className:N.checked?"checked":"",onClick:()=>u(N.action),children:[t.jsxs("span",{children:[N.checked?"✓ ":"",o(N.label),N.soon?t.jsxs("small",{children:[" · ",o("Sắp có")]}):null]}),N.keys&&t.jsx("kbd",{children:N.keys})]},N.action+A)})},L)),t.jsxs("button",{type:"button",className:"shot-ctxmenu-keys",role:"menuitemcheckbox","aria-checked":r,onClick:()=>c(!r),children:[t.jsxs("span",{children:[r?"☑":"☐"," ",o("Phím tắt kiểu Blender")]}),t.jsx("small",{children:"G R S · Shift+D · X · H · A · B"})]})]})]})}const I1=[{id:"above",label:"Thả từ trên cao"},{id:"here",label:"Từ vị trí hiện tại"}],R1=[{id:"bouncy",label:"Nảy nhiều"},{id:"normal",label:"Vừa"},{id:"heavy",label:"Nặng"}];function F1({count:e,start:n,left:s,busy:a,onRun:i,onClose:r}){const[l,c]=R.useState({mode:"above",bounciness:"normal",duration:3}),u=R.useRef(null);R.useEffect(()=>{u.current?.querySelector("button.active")?.focus()},[]);const m=Math.min(l.duration,s);return t.jsxs("form",{ref:u,className:"shot-ctxmenu shot-drop",role:"dialog","aria-label":o("Rơi tự nhiên"),onSubmit:d=>{d.preventDefault(),!a&&s>=.25&&i(l)},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),r())},children:[t.jsx("div",{className:"shot-ctxmenu-title",children:o("Rơi tự nhiên · {0} đối tượng",[e])}),t.jsx("div",{className:"shot-seg shot-seg-2",role:"group","aria-label":o("Bắt đầu rơi"),children:I1.map(d=>t.jsx("button",{type:"button",className:l.mode===d.id?"active":"","aria-pressed":l.mode===d.id,onClick:()=>c({...l,mode:d.id}),children:o(d.label)},d.id))}),t.jsx("div",{className:"shot-seg",role:"group","aria-label":o("Độ nảy"),children:R1.map(d=>t.jsx("button",{type:"button",className:l.bounciness===d.id?"active":"","aria-pressed":l.bounciness===d.id,onClick:()=>c({...l,bounciness:d.id}),children:o(d.label)},d.id))}),t.jsxs("label",{className:"shot-drop-row",children:[o("Thời lượng")," ",t.jsxs("b",{children:[l.duration,o("s")]}),t.jsx("input",{type:"range",min:1,max:6,step:.5,value:l.duration,"aria-label":o("Thời lượng rơi"),onChange:d=>c({...l,duration:+d.target.value})})]}),t.jsx("small",{className:"shot-drop-hint",children:s<.25?o("Đầu phát đang ở cuối shot — kéo về trước rồi thử lại."):o("Từ {0}s đến {1}s · ghi thành key thường, Ctrl+Z để hoàn tác",[n.toFixed(1),(n+m).toFixed(1)])}),t.jsxs("div",{className:"shot-drop-actions",children:[t.jsx("button",{type:"button",onClick:r,children:o("Huỷ")}),t.jsx("button",{type:"submit",className:"shot-primary",disabled:a||s<.25,children:a?o("Đang mô phỏng…"):o("Mô phỏng")})]})]})}Un.plateUrl=e=>A0({gcsUri:e.gcsUri,url:e.url});const Hi=[["person","Nhân vật"],["box","Hộp"],["sphere","Cầu"],["cylinder","Trụ"],["wall","Tường"],["platform","Bục"],["floor","Sàn"]],vo=[["scene","Dựng cảnh",t.jsx(Ce.scene,{},"scene")],["objects","Đối tượng",t.jsx(Ce.objects,{},"objects")],["material","Vật liệu",t.jsx(Ce.material,{},"material")],["rigging","Rigging · gắn xương",t.jsx(u1,{},"rigging")],["modeling","Dựng model",t.jsx(wd,{},"modeling")],["camera","Camera & shot",t.jsx(Ce.camera,{},"camera")],["light","Ánh sáng cảnh",t.jsx(Ce.light,{},"light")],["shots","Danh sách shot",t.jsx(Ce.film,{},"shots")],["notes","Ghi chú 3D",t.jsx(Ce.note,{},"notes")],["series","Series",t.jsx(Ce.series,{},"series")],["fx","Hiệu ứng",t.jsx(Ce.fx,{},"fx")],["fxedit","Sửa hiệu ứng",t.jsx(Ce.pen,{},"fxedit")],["mixfx","Mix FX",t.jsx(Ce.mixfx,{},"mixfx")]],Wi={drawer:300,right:320,timeline:210},P1={person:t.jsx(Ce.person,{}),box:t.jsx(Ce.box,{}),sphere:t.jsx(Ce.sphere,{}),cylinder:t.jsx(Ce.cylinder,{}),wall:t.jsx(Ce.wall,{}),platform:t.jsx(Ce.platform,{}),floor:t.jsx(Ce.floor,{}),model:t.jsx(Ce.cube,{}),proxy:t.jsx(Ce.cube,{}),splat:t.jsx(Ce.image,{}),prop:t.jsx(Ce.key,{}),fx:t.jsx(Ce.fx,{})},To={shoulderL:"Vai trái",shoulderR:"Vai phải",elbowL:"Khuỷu trái",elbowR:"Khuỷu phải",hipL:"Hông trái",hipR:"Hông phải",kneeL:"Gối trái",kneeR:"Gối phải",head:"Hướng đầu",lean:"Nghiêng thân",shoulderOutL:"Dang vai trái",shoulderOutR:"Dang vai phải",hipOutL:"Dang hông trái",hipOutR:"Dang hông phải",wristL:"Cổ tay trái",wristR:"Cổ tay phải",ankleL:"Cổ chân trái",ankleR:"Cổ chân phải",spineTwist:"Xoay cột sống"};function Hn({label:e,value:n,onChange:s,min:a=-100,max:i=100,step:r=.1}){return ht(),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:o(e)}),t.jsx(gn,{"aria-label":o(e),precision:2,value:n,min:a,max:i,step:r,onCommit:s})]})}function jo({label:e,root:n,bend:s,upper:a,lower:i,onChange:r}){ht();const l=R.useRef(null),c=d0(n,s,a,i),u=a+i,m=f=>{const p=l.current.getBoundingClientRect(),x=((f.clientX-p.left)/p.width*2-1)*u,g=((f.clientY-p.top)/p.height*2-1)*u,v=u0(x,g,a,i);r(Math.round(v.root),Math.round(v.bend))},d=f=>{f.preventDefault(),m(f);const p=g=>m(g),x=()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",x)};window.addEventListener("mousemove",p),window.addEventListener("mouseup",x)};return t.jsxs("div",{children:[t.jsx("small",{children:o(e)}),t.jsx("div",{ref:l,className:"shot-ik-pad",onMouseDown:d,children:t.jsx("i",{style:{left:`${50+c.forward/u*50}%`,top:`${50+c.down/u*50}%`}})})]})}const qi={headPitch:"Cúi / ngẩng đầu",headRoll:"Nghiêng đầu",eyeYaw:"Mắt liếc trái / phải",eyePitch:"Mắt liếc lên / xuống",blink:"Nhắm mắt",gripL:"Nắm tay trái",indexL:"Ngón trỏ trái",middleL:"Ngón giữa trái",ringL:"Ngón áp út trái",pinkyL:"Ngón út trái",thumbL:"Ngón cái trái",spreadL:"Xoè ngón tay trái",wristTwistL:"Xoay cổ tay trái",wristSideL:"Nghiêng cổ tay trái",gripR:"Nắm tay phải",indexR:"Ngón trỏ phải",middleR:"Ngón giữa phải",ringR:"Ngón áp út phải",pinkyR:"Ngón út phải",thumbR:"Ngón cái phải",spreadR:"Xoè ngón tay phải",wristTwistR:"Xoay cổ tay phải",wristSideR:"Nghiêng cổ tay phải",smile:"Biểu cảm: cười",angry:"Biểu cảm: giận dữ",surprise:"Biểu cảm: ngạc nhiên",sad:"Biểu cảm: buồn",pain:"Biểu cảm: đau"},$1=(e,n)=>{if(e[n]!==void 0)return e[n];const s=n.endsWith("L")?"L":"R",a=n.slice(0,-1);return a0.includes(a)?Math.round(o0(e,s)[a]):0},O1=(e,n,s)=>td(e,n,s);function D1(e,n){return Object.keys(To).every(s=>(e[s]||0)===(n[s]||0))}const Ih="clipoox.shot.objectClipboard",z1=e=>e.kind==="person"||e.kind==="model"&&e.skeleton==="native";function rj({nodeId:e,headless:n=!1,background:s}){ht();const[a,i]=R.useState(null),[r,l]=R.useState(!1),c=R.useRef(!1),[u,m]=R.useState(!1),[d,f]=R.useState(null),[p,x]=R.useState(!1),g=R.useRef([]),[v,w]=R.useState(!1),[C,M]=R.useState(!1),[S,I]=R.useState(!1),[y,k]=R.useState(null),[T,j]=R.useState([]),[L,N]=R.useState(!1),[A,O]=R.useState(null),[_,$]=R.useState(!1),[P,W]=R.useState(!1),[z,Q]=R.useState(()=>{const h=Pt()?.getNode(e)?.data.shotScene;if(h)return ec(tc(h));const b=mf();return b.items=b.items.map((E,F)=>({...E,name:`${o(Hi.find(([K])=>K===E.kind)?.[1]||"Model")} ${F+1}`})),b}),[J,V]=R.useState(z.items[0]?.id||null),[B,q]=R.useState([]),[D,ee]=R.useState("translate"),[Z,xe]=R.useState(()=>{try{const h=localStorage.getItem("clipoox.shot.panel");return vo.some(b=>b[0]===h)?h:null}catch{return null}}),[be,U]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.railWide")==="1"}catch{return!1}}),[pe,me]=R.useState(()=>{try{return{...Wi,...JSON.parse(localStorage.getItem("clipoox.shot.layout")||"{}")}}catch{return Wi}}),[X,re]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.tools")!=="0"}catch{return!0}}),[ue,Ee]=R.useState(!1),[ye,ne]=R.useState(pf),[Ie,ze]=R.useState(Wr),[we,de]=R.useState([]),[H,se]=R.useState(!1),[he,ce]=R.useState(""),[Pe,Be]=R.useState([]),[ot,G]=R.useState(null),[Se,le]=R.useState(!1),[$e,Le]=R.useState(1),[Te,Je]=R.useState(!1),[ke,Ue]=R.useState(0),[At,qe]=R.useState(null),[mt,kt]=R.useState({}),Xe=h=>{V(h),q([])},it=J?[J,...B.filter(h=>h!==J)]:[],xt=R.useRef(it);xt.current=it;const wt=h=>{V(h[0]??null),q(h.slice(1))},nn=(h,b=!1)=>{const E=xt.current;if(!b||!h)return wt(h?[h]:b?E:[]);wt(E.includes(h)?E.filter(F=>F!==h):[h,...E])},cn=R.useRef(nn);cn.current=nn;const[_t,rt]=R.useState(null),[Tt,Rt]=R.useState(!1),sn=R.useCallback(()=>rt(null),[]),[Sn,Ns]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.blenderKeys")!=="0"}catch{return!0}}),As=h=>{Ns(h);try{localStorage.setItem("clipoox.shot.blenderKeys",h?"1":"0")}catch{}},[Pn,an]=R.useState({on:!1}),xn=R.useRef("keys"),[oe,Ne]=R.useState(!1),[Oe,Re]=R.useState(null),[_e,Ze]=R.useState(null),[nt,et]=R.useState({mode:"all",slot:null}),Ge=R.useRef(null),Ye=R.useRef(ke);Ye.current=ke,R.useEffect(()=>{At&&J!==At&&qe(null)},[J,At]);const lt=R.useRef(null),ct=R.useRef(null),Ke=R.useRef(null),vt=R.useRef(null),je=R.useRef(null),Lt=R.useRef(null),Bt=R.useRef(null),Ae=R.useRef(z),Yt=R.useRef([]),hn=R.useRef([]),Et=dt(h=>h.saveError),Fe=dt(h=>h.saveState),pt=yi(h=>h.close);Ae.current=z;const qt=dt(h=>h.canvasId),bn=Ul(h=>h.conflict),$n=Ul(h=>h.reloading);R.useEffect(()=>n||!qt?void 0:ff(qt,e,h=>{const b=ec(tc(h));Yt.current=[],hn.current=[],Ae.current=b,Q(b)}),[qt,e,n]),gf(n?null:qt,e,()=>dt.getState().saveState!=="saved");const Me=h=>{const b=Ae.current;Yt.current.push(b),Yt.current.length>60&&Yt.current.shift(),hn.current=[];const E={...$f(b,h(b)),revision:b.revision+1};Ae.current=E,Q(E)},On={getStage:()=>Ae.current,setStage:Me,engine:()=>je.current},Ts=h=>{const{item:b,fingers:E}=Of(h,Ae.current.items.length),F=Oe?Ae.current.items.find(Y=>Y.id===Oe&&Y.kind==="person"):void 0,K=F?{...b,id:F.id,name:F.name,position:F.position,rotation:F.rotation,...F.hidden?{hidden:!0}:{}}:b;Me(Y=>({...Y,items:F?Y.items.map(ae=>ae.id===F.id?K:ae):[...Y.items,K]})),Xe(K.id),W(!1),Re(null),E&&K.rig&&mc(On,K.id,K.rig)};R.useEffect(()=>{if(!Te)return;const h=yi.getState().fitFingers;if(!(!h||h.node!==e)){yi.setState({fitFingers:null});for(const b of h.items){const E=Ae.current.items.find(F=>F.id===b);E?.rig&&mc(On,b,E.rig)}}},[Te,e]);const Vn=h=>{A&&($(!1),Ue(A.time),h&&Me(b=>Ti(b,A.plan)),A.done(h),O(null))},He=(h,b)=>{$(!1),Me(E=>Qt(E,h,b))},Qt=(h,b,E)=>{{const F=h.shots.find(ge=>ge.id===h.activeShot),K=h.items.find(ge=>ge.id===b),Y=K.kind==="fx"?K.fx?.attach:void 0;if(Y&&!(Y.hand&&Y.tip)&&(E.position||E.rotation)){if(Yh(K,F)){const ge=Ro(h,b,Ye.current,{position:E.position,yaw:E.rotation?.[1]});return E.scale?{...ge,items:ge.items.map(We=>We.id===b?{...We,scale:E.scale}:We)}:ge}return{...h,items:h.items.map(ge=>ge.id===b?{...ge,...E.scale?{scale:E.scale}:{},...E.rotation?{rotation:[ge.rotation[0],E.rotation[1],ge.rotation[2]]}:{},fx:{...ge.fx,attach:{...Y,...E.position?{offset:E.position}:{}}}}:ge)}}const ae=F.objectKeys?.[b]||[],ve=!!E.pose&&ae.some(ge=>ge.pose);if(ae.length&&(E.position||E.rotation||E.scale||ve)){const ge={...Tn(K,F,Ye.current),...E},We=ae,De=We.find(ft=>Math.abs(ft.time-Ye.current)<1e-6),Ve={...De,id:De?.id||bt(),time:Ye.current,position:ge.position,rotation:ge.rotation,scale:ge.scale,...ve?{pose:E.pose}:{}};return{...h,shots:h.shots.map(ft=>ft.id===h.activeShot?{...ft,objectKeys:{...ft.objectKeys,[b]:[...We.filter(jt=>jt.id!==Ve.id),Ve].sort((jt,yn)=>jt.time-yn.time)}}:ft)}}return K.kind==="fx"&&K.fx&&E.position&&!E.fx&&(E={...E,fx:Df(K.fx,K.position,E.position)}),{...h,items:h.items.map(ge=>ge.id===b?{...ge,...E}:ge)}}},Ft=(h,b)=>{const E={...In[b]};if(!!!Ae.current.shots.find(Y=>Y.id===Ae.current.activeShot)?.objectKeys?.[h.id]?.length&&!h.hold&&je.current){if(Si(E)==="sit"){const Y=je.current.sitSnap(h);if(Y)return He(h.id,{pose:E,...Y})}else if(Si(h.pose)==="sit"&&Si(E)==="stand")return He(h.id,{pose:E,position:je.current.standUp(h).position})}He(h.id,{pose:E})},Gt=h=>{const b=h.filter(E=>E.fix&&!E.locked);b.length&&($(!1),Me(E=>({...E,items:E.items.map(F=>{const K=b.find(Y=>Y.itemId===F.id)?.fix;return K?{...F,position:K.position,...K.rotation?{rotation:K.rotation}:{}}:F})})))},Dn=h=>{$(!1),Me(b=>{const E=b.shots.find(De=>De.id===b.activeShot),F=b.items.find(De=>De.id===h),K=E.objectKeys?.[h]||[],Y=Ye.current,ae=Tn(F,E,Y),ve=(De,Ve)=>{const ft=Tn(F,E,De),jt=K.find(yn=>Math.abs(yn.time-De)<1e-6);return{...jt,id:jt?.id||bt(),time:De,position:ft.position,rotation:ft.rotation,scale:ft.scale,pose:structuredClone(Ve)}};let ge=[...K];if(!K.some(De=>De.pose)&&Y>1e-6){const De=ve(0,F.pose);ge=[...ge.filter(Ve=>Ve.id!==De.id),De]}const We=ve(Y,ae.pose);return ge=[...ge.filter(De=>De.id!==We.id),We].sort((De,Ve)=>De.time-Ve.time),{...b,shots:b.shots.map(De=>De.id===b.activeShot?{...De,objectKeys:{...De.objectKeys,[h]:ge}}:De)}})},us=h=>{$(!1),Me(b=>{const K=(b.shots.find(Y=>Y.id===b.activeShot).objectKeys?.[h]||[]).map(Y=>Math.abs(Y.time-Ye.current)<1e-6&&Y.pose?(({pose:ae,poseEase:ve,...ge})=>ge)(Y):Y);return{...b,shots:b.shots.map(Y=>Y.id===b.activeShot?{...Y,objectKeys:{...Y.objectKeys,[h]:K}}:Y)}})},qa=(h,b)=>{$(!1),Me(E=>{const Y=(E.shots.find(ae=>ae.id===E.activeShot).objectKeys?.[h]||[]).map(ae=>Math.abs(ae.time-Ye.current)<1e-6&&ae.pose?b==="smooth"?(({poseEase:ve,...ge})=>ge)(ae):{...ae,poseEase:b}:ae);return{...E,shots:E.shots.map(ae=>ae.id===E.activeShot?{...ae,objectKeys:{...ae.objectKeys,[h]:Y}}:ae)}})},ms=R.useRef(null),[Ut,Ga]=R.useState(null),[ps,ku]=R.useState(1),[Ur,wu]=R.useState(!0),[Xr,Vr]=R.useState(!1),Mu=async h=>{if(h){ce(""),Vr(!0);try{if(h.size>60*1024*1024)throw new Error(o("File mocap tối đa 60 MB."));Ga(await zf(h.name,await h.arrayBuffer()))}catch(b){Ga(null),ce(b.message)}finally{Vr(!1)}}},Yr=async h=>{if(_e)return;$(!1),ce(""),Ze({kind:h,pct:0});const b=(E,F)=>Ze({kind:h,pct:Math.round(E/F*100)});try{const E=Ae.current;if(h==="follow"){const F=E.items.find(ve=>ve.id===J&&ve.kind==="person"),K=F??E.items.find(ve=>ve.kind==="person");if(!K)throw new Error(o("Cảnh chưa có người đứng thế để bám theo."));const{followPlate:Y}=await Wn(async()=>{const{followPlate:ve}=await import("./plateFollow-B9_QTgvo.js");return{followPlate:ve}},__vite__mapDeps([12,1,2,3,4,5,6,7,8,9,10])),ae=await Y(E,K.id,{newId:bt,progress:b});Me(()=>ae.stage),dt.getState().toast(o("{0} đã bám theo người trong video: {1}/{2} khung thấy người.",[K.name,ae.found,ae.frames]),"ok")}else{const{trackPlateCamera:F}=await Wn(async()=>{const{trackPlateCamera:Y}=await import("./plateCamera-C96L5GKm.js");return{trackPlateCamera:Y}},__vite__mapDeps([13,2,3,1,4,5,6,7,8,9,10,14,15])),K=await F(E,{newId:bt,progress:b});Me(()=>K.stage),dt.getState().toast(K.mode==="travel"?o("Đã lấy camera từ video: camera đi {0} m, quay {1}°.",[K.travel,K.pan]):o("Đã lấy camera từ video: {0} key, quay {1}°.",[K.keys,K.pan]),"ok")}}catch(E){const F=E.message;ce(F==="no-person-in-plate"?o("Không thấy người trong video nền."):F==="camera-not-found"?o("Không bám được camera: nền quá ít chi tiết hoặc khung hình toàn vật thể chuyển động."):F)}finally{Ze(null)}},Su=async()=>{const{shotBlenderScript:h}=await Wn(async()=>{const{shotBlenderScript:F}=await import("./plateCamera-C96L5GKm.js");return{shotBlenderScript:F}},__vite__mapDeps([13,2,3,1,4,5,6,7,8,9,10,14,15])),b=new Blob([h(Ae.current)],{type:"text/x-python"}),E=document.createElement("a");E.href=URL.createObjectURL(b),E.download=`${(fe.name||"shot").replace(/[^\w-]+/g,"_")}-camera.py`,E.click(),setTimeout(()=>URL.revokeObjectURL(E.href),4e3)},Cu=h=>{if(!Ut)return;$(!1);const b=Ae.current,E=b.items.find(De=>De.id===h),F=b.shots.find(De=>De.id===b.activeShot),K=Ye.current,Y=is(E,F,K),ae=(1-K)*F.duration*ps,ve=_f(Ut,15*ps,0,Math.min(Ut.duration,ae)).map(De=>({...De,time:De.time/ps})),ge=.93*Bf(E)*E.scale[1],We=Kf(b,h,Hf(ve,{position:Y.position,yaw:Y.rotation[1],hipHeight:ge},Ur),K,bt);if(!We.keys){ce(o("Không còn đủ thời lượng shot sau playhead để đặt mocap."));return}Me(()=>We.stage),dt.getState().toast(o("Đã áp mocap {0}: {1} key · {2}s",[Ut.name,We.keys,We.seconds]),"ok")},[Qo,Qr]=R.useState(!0),[Zo,Zr]=R.useState(!1),Jo=async(h,b)=>{if($(!1),b.mocap)try{await Lr(b.id)}catch(ae){ce(o("Không tải được dữ liệu mocap: {0}",[ae.message]));return}const E=Ae.current,F=E.shots.find(ae=>ae.id===E.activeShot),K=Ye.current,Y=Wf(E,h,b,{start:K,newId:bt,colliders:je.current?.placementColliders(),camera:F.position,loop:Qo,mirror:Zo});if(!Y.ok){ce(Y.error.startsWith("not enough")?o("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."):Y.error);return}if(!Y.keys){ce(o("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."));return}Me(()=>Y.stage),dt.getState().toast(o('Đã áp "{0}" · {1}s',[Na(b),Y.seconds])+(Y.notes.length&&Ys()==="vi"?` · ${Y.notes[0]}`:""),"ok")},Jr=(h,b,E)=>{$(!1),Me(F=>{const K=ve=>(({hold:ge,...We})=>We)(ve),Y=F.items.find(ve=>ve.id===h);let ae=F.items.map(ve=>ve.hold?.by===h&&ve.hold.hand===b?{...K(ve),position:[Y.position[0]+(b==="R"?.4:-.4),0,Y.position[2]]}:ve);if(E.startsWith("item:"))ae=ae.map(ve=>ve.id===E.slice(5)?{...ve,hold:{by:h,hand:b}}:ve);else if(E.startsWith("prop:")){const ve=E.slice(5);ae=[...ae,{...fn("prop",ae.length),name:Ma[ve].label,prop:{kind:ve},color:"#8a939b",hold:{by:h,hand:b}}]}return{...F,items:ae}})},[Nu,el]=R.useState(""),Au=()=>{$(!1);let h=[];Me(E=>{const F=qf(E);return h=F.outcomes,F.stage});const b=E=>h.filter(F=>F.result===E).length;el(h.length?o("{0} đòn · {1} trúng · {2} bị đỡ · {3} trượt",[h.length,b("head")+b("body"),b("blocked"),b("miss")])+(b("miss")?" — "+h.filter(E=>E.result==="miss").map(E=>o("{0}s thiếu {1} m",[E.time_s,E.gap_m])).join(", "):""):o('Chưa có đòn nào: đặt key tư thế kiểu "Ra đòn nhanh" giữa hai người.'))},Tu=()=>{$(!1),Me(Gf),el("")},tl=h=>{const b=Ae.current.items.find(E=>E.id===h);!b||b.locked||H||($(!1),Me(E=>({...E,items:E.items.filter(F=>F.id!==h),shots:E.shots.map(F=>({...F,objectKeys:Object.fromEntries(Object.entries(F.objectKeys||{}).filter(([K])=>K!==h)),...F.fxTiming?{fxTiming:Object.fromEntries(Object.entries(F.fxTiming).filter(([K])=>K!==h))}:{}}))})),y?.row===h&&k(null),j(E=>E.filter(F=>F.row!==h)),Xe(E=>E===h?null:E))},nl=R.useRef(""),Ua=()=>{let h=nl.current;try{h=localStorage.getItem(Ih)||h}catch{}return h?Uf(h):null},sl=()=>{const h=xt.current;if(!h.length)return;const b=h0(Ae.current,h);nl.current=b,xn.current="objects";try{localStorage.setItem(Ih,b)}catch{}},al=()=>{const h=Ua();if(!h||H)return;$(!1);let b=[];Me(E=>{const F=l0(E,h,bt);return b=F.ids,{...F.stage,items:F.stage.items.map(K=>b.includes(K.id)?c0(K):K)}}),wt(b)},Xa=h=>{const b=xt.current;if(!b.length||H)return;$(!1);let E=[];Me(F=>{const K=r0(F,b,{linked:h,newId:bt});return E=K.ids,K.stage}),E.length&&wt(E)},ei=()=>{const h=xt.current.filter(b=>!Ae.current.items.find(E=>E.id===b)?.locked);!h.length||H||($(!1),Me(b=>i0(b,h)),y&&h.includes(y.row)&&k(null),j(b=>b.filter(E=>!h.includes(E.row))),wt(xt.current.filter(b=>!h.includes(b))))},ti=(h,b,E)=>{h.length&&($(!1),Me(F=>({...F,items:F.items.map(K=>h.includes(K.id)?{...K,[b]:E}:K)})))},ol=()=>{const h=xt.current;h.length&&(ti(h,"hidden",!0),wt([]))},il=()=>ti(Ae.current.items.filter(h=>h.hidden).map(h=>h.id),"hidden",!1),rl=()=>wt(Ae.current.items.filter(h=>!h.hidden&&!h.locked).map(h=>h.id)),ni=h=>{const b=je.current,E=xt.current.filter(F=>!wo(Ae.current.items.find(K=>K.id===F),"origin"));!b||!E.length||($(!1),Me(F=>E.reduce((K,Y)=>{if(h==="reset")return Jl(K,Y,null,!0);const ae=b.builtBounds(Y),ve=K.items.find(De=>De.id===Y);if(!ae||!ve)return K;const ge=ve.origin||[0,0,0],We=[(ae.min[0]+ae.max[0])/2,h==="bottom"?ae.min[1]:(ae.min[1]+ae.max[1])/2,(ae.min[2]+ae.max[2])/2];return Jl(K,Y,We.map((De,Ve)=>De-ge[Ve]))},F)))},ll=()=>{const h=xt.current;if(h.length===1)return oi(h[0]);if(!h.length)return;const b=Ye.current;$(!1),Me(E=>{const F=E.shots.find(Y=>Y.id===E.activeShot),K={...F.objectKeys};for(const Y of h){const ae=E.items.find(Ve=>Ve.id===Y);if(!ae||ae.locked||ae.hold||ae.kind==="fx"&&ae.fx?.attach)continue;const ve=Tn(ae,F,b),ge=K[Y]||[],We=ge.find(Ve=>Math.abs(Ve.time-b)<1e-6),De={...We,id:We?.id||bt(),time:b,position:ve.position,rotation:ve.rotation,scale:ve.scale};K[Y]=[...ge.filter(Ve=>Ve.id!==De.id),De].sort((Ve,ft)=>Ve.time-ft.time)}return{...E,shots:E.shots.map(Y=>Y.id===E.activeShot?{...Y,objectKeys:K}:Y)}})},si=(h,b,E)=>{H||A||(h&&!xt.current.includes(h)&&nn(h),rt({x:b,y:E,scene:!h}))},cl=R.useRef(si);cl.current=si;const Lu=()=>{const h=lt.current?.getBoundingClientRect();rt({x:h?h.left+h.width/2-110:200,y:h?h.top+h.height/3:200,renaming:!0})},Eu=h=>{const b=xt.current;if(h==="rename"){rt(E=>E&&{...E,renaming:!0});return}switch(rt(null),h){case"shade-smooth":case"shade-auto":case"shade-flat":case"shade-reset":{const E=h==="shade-reset"?null:h.slice(6);$(!1),Me(F=>Yf(F,b,E));return}case"origin-center":return ni("center");case"origin-bottom":return ni("bottom");case"origin-reset":return ni("reset");case"copy":return sl();case"paste":return al();case"duplicate":return Xa(!1);case"duplicate-linked":return Xa(!0);case"unlink":$(!1),Me(E=>Vf(E,b));return;case"mirror-x":case"mirror-y":case"mirror-z":$(!1),Me(E=>Xf(E,b,h.slice(7)));return;case"key":return ll();case"physics-drop":$(!1),Rt(!0);return;case"hide":return ol();case"lock":return ti(b,"locked",!b.every(E=>Ae.current.items.find(F=>F.id===E)?.locked));case"delete":return ei();case"rig":{const E=b.find(F=>Ae.current.items.find(K=>K.id===F)?.kind==="model");E&&(Xe(E),zn("rigging"));return}case"select-all":return rl();case"unhide-all":return il();case"box-select":return an({on:!0})}},Iu=async h=>{const b=Ae.current,E=b.shots.find(Ve=>Ve.id===b.activeShot),F=Ye.current,K=xt.current,Y=await Wn(()=>import("./rotoMaskStore-DIi45swK.js").then(Ve=>Ve.W),__vite__mapDeps([7,1,3])),ae=K.map(Ve=>b.items.find(ft=>ft.id===Ve)).filter(Ve=>!!Ve&&!Y.dropUnavailable(Ve)&&!(Ve.kind==="prop"&&Ve.prop?.kind==="ball"&&E.ball?.[Ve.id]?.length)).slice(0,Y.MAX_PHYSICS_BODIES);if(!ae.length){Rt(!1),ce(o("Không có đối tượng nào rơi được trong vùng chọn (nhân vật, hiệu ứng, sàn, đồ đang cầm hay đã khoá thì không)."));return}const ve=F,ge=Math.min(h.duration,(1-ve)*E.duration),We=je.current,De=ae.map(Ve=>Ve.id);se(!0),ce("");try{const Ve=We?.physicsShapes(De)??{},ft=(We?.placementColliders()??[]).filter(It=>!De.includes(It.itemId)),jt=Object.fromEntries(ae.map(It=>[It.id,(E.objectKeys?.[It.id]||[]).filter(Zt=>Zt.time<ve-1e-6).sort((Zt,xs)=>Zt.time-xs.time).pop()])),yn=ae.map(It=>{const Zt=Tn(It,E,ve);return{id:It.id,position:Zt.position,rotation:Zt.rotation,shape:Y.shapeKind(It),...Ve[It.id]??Y.fallbackShape(It)}}),Kt=await Y.bakeDrop({bodies:yn,statics:ft,mode:h.mode,bounciness:h.bounciness,duration:ge,start:ve*E.duration,shotDuration:E.duration,seed:De.join(","),before:jt,seam:E.lockUntil?E.lockUntil/E.duration:null}),dn=Object.fromEntries(ae.map(It=>[It.id,Tn(It,E,ve).scale]));Me(It=>Y.applyDropKeys(It,E.id,Kt.tracks,{scale:dn,newId:bt,lifted:h.mode==="above"})),Rt(!1)}catch(Ve){ce(o("Không mô phỏng được: {0}",[Ve.message]))}finally{se(!1)}},Ru=h=>{const b=h.code;return h.shiftKey&&!h.altKey&&b==="KeyD"?(Xa(!1),!0):h.altKey&&!h.shiftKey&&b==="KeyD"?(Xa(!0),!0):h.altKey&&!h.shiftKey&&b==="KeyH"?(il(),!0):h.altKey&&!h.shiftKey&&b==="KeyA"?(wt([]),!0):h.altKey||h.shiftKey?!1:b==="KeyG"||b==="KeyR"||b==="KeyS"&&!r?(ee(b==="KeyG"?"translate":b==="KeyR"?"rotate":"scale"),!0):b==="KeyX"?(Z==="rigging"&&Ge.current?.del()||ei(),!0):b==="KeyH"?(ol(),!0):b==="KeyA"?(rl(),!0):b==="KeyB"?(an({on:!0}),!0):b==="F2"&&xt.current.length===1?(Lu(),!0):!1},Va=(h=!1)=>{const b=h?hn.current:Yt.current,E=h?Yt.current:hn.current,F=b.pop();F&&(E.push(Ae.current),Ae.current=F,Q(F))};R.useEffect(()=>{au()},[]),R.useEffect(()=>{je.current?.setPlatePlaying(_)},[_]),R.useEffect(()=>{Wn(()=>import("./videoExport-z5WjM0hw.js"),__vite__mapDeps([16,2,3,1,4,5,6,7,8,9,10,17,18,19])).catch(()=>{})},[]),R.useEffect(()=>{try{je.current=new Un(lt.current,vt.current,(h,b)=>cn.current(h,b),(h,b)=>He(h,b),S0,ce,h=>C0(h).then(b=>b.recipe)),je.current.onContext=(h,b,E)=>cl.current(h,b,E),je.current.commitMany=h=>{$(!1),Me(b=>h.reduce((E,F)=>Qt(E,F.id,F.patch),b))},je.current.setCameraEditor({select:h=>{l(h&&!c.current),h&&(Xe(null),i(null),ee(b=>b==="scale"?"translate":b))},commit:h=>yt(h)}),je.current.sync(Ae.current,J),Je(!0)}catch(h){ce(`Không khởi tạo được 3D: ${h.message}`)}return()=>je.current?.dispose()},[]),R.useEffect(()=>{je.current?.sync(A?.stage||z,A?null:J,A?[]:B)},[z,J,B,A]),R.useEffect(()=>{const h={getStage:()=>Ae.current,setStage:F=>{$(!1),Me(F)},engine:()=>je.current,timelineClip:F=>dt.getState().clips.find(K=>K.id===F),undo:(F,K)=>{let Y=0;for(let ae=0;ae<K;ae++){const ve=Ae.current;if(Va(F),Ae.current===ve)break;Y++}return Y},...n?{}:{exportVideo:async F=>{const K=je.current;if(!K)throw new Error("3D chưa sẵn sàng");K.sync(Ae.current,null),se(!0),ce("");try{const{blob:Y,cleanup:ae}=await K.exportVideo({...F,signal:new AbortController().signal,progress:()=>{}});try{return Lt.current=null,Bt.current=null,await li(Y,F,"canvas"),{nodeId:Lt.current||void 0,url:Bt.current||void 0}}finally{await ae()}}finally{se(!1)}},exportVfx:async F=>{se(!0),ce("");try{return await ri(F)}finally{se(!1)}},exportFrame:F=>Yn(!0,Ae.current.shots.find(K=>K.id===Ae.current.activeShot),0,!0,F)}};if(s){sc().then(F=>Xl(!!F?.allowed)).catch(()=>{}),s({ready:()=>!!je.current,run:(F,K)=>xf(F,K,h),exportVfx:(F,K,Y)=>ri(F,K,Y)});return}if(m0(h,async()=>{const F=je.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=Ae.current,Y=K.shots.find(ae=>ae.id===K.activeShot);F.sync(K,null),se(!0),ce("");try{const ae={start:0,end:Y.duration,fps:rn(Y),height:720},{blob:ve,cleanup:ge}=await F.exportVideo({...ae,signal:new AbortController().signal,progress:()=>{}});try{return Lt.current=null,Bt.current=null,await li(ve,ae,"canvas"),{nodeId:Lt.current||void 0,url:Bt.current||void 0}}finally{await ge()}}finally{se(!1)}}),n)return()=>Vl(h);n||sc().then(F=>Xl(!!F?.allowed)).catch(()=>{});const b=bf(()=>Ae.current.shots.find(F=>F.id===Ae.current.activeShot)?.name||"3D Shot"),E=S1(h,()=>Ae.current.shots.find(F=>F.id===Ae.current.activeShot)?.name||"3D Shot",F=>{const K=Ae.current.shots.find(Y=>Y.id===Ae.current.activeShot)?.duration||1;$(!1),Ue(Math.max(0,Math.min(1,F/K))),setTimeout(()=>$(!0),50)},()=>{const F=dt.getState().canvasId;return F?`shot:${F}:${e}`:null});return()=>{b(),E(),Vl(h)}},[]),R.useEffect(()=>{Pt()?.updateNodeData(e,{shotScene:z})},[z,e]),R.useEffect(()=>{c.current=S,S&&l(!1)},[S]),R.useEffect(()=>je.current?.setCameraHidden(C),[C,Te]),R.useEffect(()=>je.current?.mode(D,ue),[D,ue,r]),R.useEffect(()=>{J&&l(!1)},[J]),R.useEffect(()=>{je.current?.setCameraSelected(r&&!J&&!A)},[r,J,A,Te]),R.useEffect(()=>{je.current&&(je.current.cameraTip=o("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"))},[Te,Ys()]),R.useEffect(()=>je.current?.setQuality(ye),[ye,Te]),R.useEffect(()=>{if(!Te||Z!=="shots"||H||A)return;let h=!0,b,E=0;const F=()=>{const K=je.current;!K||!h||K.shotThumbnails(Ae.current.shots).then(Y=>{h&&kt(Y)}).catch(Y=>{h&&++E<8?b=setTimeout(F,1500):console.warn("[shot] thumbnails failed:",Y?.message)})};return b=setTimeout(F,900),()=>{h=!1,clearTimeout(b)}},[z.revision,Te,Z,H,A]),R.useEffect(()=>je.current?.setPreviewProgress(ke),[ke]),R.useEffect(()=>{if(!Te||A)return;const h=()=>{const F=je.current,K=Ae.current;if(!F)return;const Y=K.shots.find(ve=>ve.id===K.activeShot),ae=new Set(Object.entries(Y?.objectKeys||{}).filter(([,ve])=>ve.length).map(([ve])=>ve));try{de(Qf(K,{colliders:F.placementColliders(),keyed:ae}))}catch{de([])}},b=setTimeout(h,350),E=setTimeout(h,2500);return()=>{clearTimeout(b),clearTimeout(E)}},[z.revision,Te,A]),R.useEffect(()=>{const h=b=>{if(A){b.key==="Escape"&&(b.preventDefault(),Vn(!1)),!b.target.closest(".shot-trial-controls")&&b.key!=="Tab"&&b.stopImmediatePropagation();return}if(b.target.closest(".shot-ctxmenu")||b.target.closest(".shot-playhead-handle")&&["ArrowLeft","ArrowRight","Home","End",",","."].includes(b.key))return;const E=b.target.closest(".shot-fmt");if(!(E&&(["Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(b.key)||b.key==="Escape"&&E.querySelector(".shot-fmt-pop"))||(b.stopImmediatePropagation(),b.target.closest('input,textarea,select,[contenteditable="true"],[role="textbox"]')||H))){if((b.metaKey||b.ctrlKey)&&b.key.toLowerCase()==="z")b.preventDefault(),Va(b.shiftKey);else if((b.key==="Delete"||b.key==="Backspace")&&(y||T.length)&&b.target.closest(".shot-timeline"))b.preventDefault(),jl();else if((b.key==="Delete"||b.key==="Backspace")&&b.target.closest?.(".shot-shotlist li"))b.preventDefault(),ml(b.target.closest(".shot-shotlist li").dataset.shot);else if((b.key==="Delete"||b.key==="Backspace")&&Z==="rigging"&&Ge.current?.del())b.preventDefault();else if((b.key==="Delete"||b.key==="Backspace")&&!L&&J&&!je.current?.transform.object?.userData.cameraKey)b.preventDefault(),ei();else if((b.metaKey||b.ctrlKey)&&!b.altKey&&["c","v"].includes(b.key.toLowerCase())){const K=!!b.target.closest(".shot-timeline");b.key.toLowerCase()==="c"?K||fs.length?(b.preventDefault(),bl()):it.length&&!L&&(b.preventDefault(),sl()):K||g.current.length&&(xn.current==="keys"||!Ua())?g.current.length&&(b.preventDefault(),yl()):!L&&Ua()&&(b.preventDefault(),al())}else if(!L&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&!b.shiftKey&&b.code==="KeyF")b.preventDefault(),je.current?.view();else if(Sn&&!L&&!b.metaKey&&!b.ctrlKey&&Ru(b))b.preventDefault();else if(b.altKey&&(b.code==="Comma"||b.code==="Period"))b.preventDefault(),vl(b.code==="Period"?1:-1);else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&b.key.toLowerCase()==="k"){const K=y?.row??J??(r?"camera":null);b.shiftKey?(b.preventDefault(),xl()):!y&&it.length>1?(b.preventDefault(),ll()):K&&(b.preventDefault(),oi(K))}else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&["l","i","o"].includes(b.key.toLowerCase())){b.preventDefault();const K=b.key.toLowerCase();K==="l"?m(Y=>!Y):qu(K==="i"?"in":"out")}else if(!b.metaKey&&!b.ctrlKey&&!b.altKey&&!L&&(b.key===" "||b.key===","||b.key==="."||b.key==="Home"||b.key==="End"))if(b.preventDefault(),b.key===" ")$(K=>(!K&&ke>=1&&Ue(0),!K));else{$(!1);const K=z.shots.find(ae=>ae.id===z.activeShot),Y=rn(K);Ue(b.key==="Home"?0:b.key==="End"?1:Math.max(0,Math.min(1,(Math.round(ke*K.duration*Y)+(b.key==="."?1:-1))/Y/K.duration)))}else if(r&&!L&&["w","e"].includes(b.key.toLowerCase())&&!b.metaKey&&!b.ctrlKey&&!b.altKey)b.preventDefault(),ee(b.key.toLowerCase()==="w"?"translate":"rotate");else if(b.key==="Escape"){if(At){qe(null);return}if(Pn.on){an({on:!1});return}if(_t){rt(null);return}if(Z==="rigging"&&Ge.current?.esc())return;r&&!L?l(!1):L?N(!1):Z?zn(null):pt()}}};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[pt,H,L,J,B,y,T,z,A,Z,r,ke,d,Sn,Pn.on,_t,At]);const fe=(A?.stage||z).shots.find(h=>h.id===z.activeShot),hl=z.items.find(h=>h.id===J),te=hl?Tn(hl,fe,ke):void 0;R.useEffect(()=>{H&&$(!1)},[H]),R.useEffect(()=>{$(!1),Ue(0),i(null),k(null),j([])},[z.activeShot]);const Fu=h=>{const b=Vh(h.dataTransfer.getData(gr)),E=je.current;if(!b||!E||H)return;h.preventDefault();const F=E.pointerTarget(h.clientX,h.clientY),K=Ae.current,Y=K.shots.find(ve=>ve.id===K.activeShot),ae=su(K,b,{selected:F.id??J,ground:F.ground,start:Ye.current*Y.duration,label:o(b.name),anchor:(ve,ge,We)=>E.partPointAt(Y,We,ve,ge)});if("error"in ae){ce(o("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[24]));return}ce(""),$(!1),Me(()=>ae.stage),Xe(ae.item.id),zn("fx")},Pu=h=>{const b=Oa(h.dataTransfer.getData(Ao)),E=je.current;if(!b||!E||H)return;h.preventDefault();const F=E.pointerSlot(h.clientX,h.clientY),K=F&&Ae.current.items.find(ae=>ae.id===F.id);if(!F||!K||!Ca(K)){ce(o("Thả vật liệu lên một đối tượng trong cảnh."));return}if(K.locked){ce(o("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[K.name]));return}const Y=nt.mode==="part"&&E.materialSlots(K.id).length>1;ce(""),$(!1),Me(ae=>zs(ae,K.id,Y?F.slot:"*",{preset:b.id})),Xe(K.id),Y&&et({mode:"part",slot:F.slot})},$u=Object.fromEntries(z.items.flatMap(h=>{if(h.kind!=="fx"||!h.fx)return[];const b=Mn(h,fe);return b.off?[]:[[h.id,{start:b.start,duration:b.duration}]]})),dl=yf(A?.stage||z),na=Ta(z.lighting),ul=vf(z.shots),ai=h=>Me(b=>({...b,lighting:Ta({...Ta(b.lighting),...h})})),Ls=z.notes||[],sa=z.styleRefs||[],Ou=()=>{const h=je.current;if(h){if(oe){h.setNotePlacer(null),Ne(!1);return}Ne(!0),h.setNotePlacer(b=>{Ne(!1),Me(E=>({...E,notes:[...E.notes||[],{id:bt(),text:o("Ghi chú"),position:b}].slice(0,Ql)}))})}},Du=(h,b)=>Me(E=>({...E,notes:(E.notes||[]).map(F=>F.id===h?{...F,text:b.slice(0,Zl)}:F)})),zu=h=>Me(b=>({...b,notes:(b.notes||[]).filter(E=>E.id!==h)})),ml=h=>Me(b=>{if(b.shots.length<2)return b;const E=b.shots.findIndex(K=>K.id===h);if(E<0)return b;const F=b.shots.filter(K=>K.id!==h);return{...b,shots:F,activeShot:b.activeShot===h?F[Math.min(E,F.length-1)].id:b.activeShot}}),pl=(h,b)=>Me(E=>{const F=E.shots.findIndex(ae=>ae.id===h),K=F+b;if(F<0||K<0||K>=E.shots.length)return E;const Y=[...E.shots];return[Y[F],Y[K]]=[Y[K],Y[F]],{...E,shots:Y}});R.useEffect(()=>{if(!_)return;const h=p&&d?d.in:0,b=p&&d?d.out:1;let E=0,F=performance.now(),K=ke;(K<h||K>=b)&&(K=h);const Y=jf(fe),ae=Math.max(.1,fe.duration),ve=Y?vi(fe,h*ae):0,ge=Y?vi(fe,b*ae):0;let We=Y?vi(fe,K*ae):0;const De=Ve=>{const ft=(Ve-F)/1e3;if(F=Ve,Y){if(We+=ft,We>=ge)if(u)We=ve+(We-ge)%Math.max(1e-6,ge-ve);else{je.current?.setOutputClock(null),Ue(b),$(!1);return}je.current?.setOutputClock(We),Ue(Zf(fe,We).scene/ae),E=requestAnimationFrame(De);return}if(K+=ft/ae,K>=b)if(u)K=h+(K-b)%Math.max(1e-6,b-h);else{Ue(b),$(!1);return}Ue(K),E=requestAnimationFrame(De)};return E=requestAnimationFrame(De),()=>{cancelAnimationFrame(E),je.current?.setOutputClock(null)}},[_,fe.duration,fe.timing,z.activeShot,u,p,d]);const Ya=(Pt()?.nodes()||[]).filter(h=>h.type==="image"&&h.id!==e&&h.data.url),yt=h=>{$(!1),Me(b=>({...b,shots:b.shots.map(E=>E.id===b.activeShot?{...E,...h}:E)}))},fl=h=>yt(Yi(h)),_u=(h,b)=>{const E=(h==="camera"?fe.cameraKeys:fe.objectKeys?.[h])?.find(F=>F.id===b);E&&($(!1),Ue(E.time),k({row:h,id:b}),j([]),i(h==="camera"?b:null),Xe(h==="camera"?null:h))},gl=h=>{$(!1),j(h),k(h.length===1?h[0]:null),i(h.length===1&&h[0].row==="camera"?h[0].id:null)},oi=h=>{if(h==="camera"){const b=fe.motion==="path"?fe.cameraKeys||[]:[],E=b.find(Y=>Math.abs(Y.time-ke)<1e-6),F=Fh(fe,ke),K={id:E?.id||bt(),time:ke,position:F.position,target:F.target,lens:F.lens,roll:F.roll};fl([...b.filter(Y=>Y.id!==K.id),K]),i(K.id),k({row:h,id:K.id}),Xe(null)}else{const b=z.items.find(ae=>ae.id===h);if(!b||b.locked)return;if(b.kind==="fx"&&b.fx?.attach){const ae=b.fx.attach.keyed?(fe.objectKeys?.[h]||[]).find(ge=>Math.abs(ge.time-ke)<1e-6):void 0,ve=ae?.id||bt();Me(ge=>Ro(ge,h,ke,{id:ve})),i(null),Xe(h),k({row:h,id:ve});return}const E=Tn(b,fe,ke),F=fe.objectKeys?.[h]||[],Y={id:F.find(ae=>Math.abs(ae.time-ke)<1e-6)?.id||bt(),time:ke,position:E.position,rotation:E.rotation,scale:E.scale};yt({objectKeys:{...fe.objectKeys,[h]:[...F.filter(ae=>ae.id!==Y.id),Y].sort((ae,ve)=>ae.time-ve.time)}}),i(null),Xe(h),k({row:h,id:Y.id})}},Bu=(h,b)=>Me(E=>{const F=E.items.find(ge=>ge.id===h);if(!F?.fx||F.locked||(F.fx.attach?.to??"")===b)return E;const K=F.fx.attach,Y=b?{to:b,...K?.part?{part:K.part}:{},...K?.follow?{follow:K.follow}:{}}:void 0,ae=K?.keyed?E.shots.map(ge=>ge.objectKeys?.[h]?{...ge,objectKeys:Object.fromEntries(Object.entries(ge.objectKeys).filter(([We])=>We!==h))}:ge):E.shots,ve=b?E.items.find(ge=>ge.id===b):null;return{...E,shots:ae,items:E.items.map(ge=>ge.id===h?{...ge,...!b&&K?{position:[...E.items.find(We=>We.id===K.to)?.position??ge.position]}:{},...ve?{position:[...ve.position]}:{},fx:{...F.fx,attach:Y}}:ge)}}),Ku=(h,b)=>{if(h==="camera"){b==="hidden"?M(E=>!E):I(E=>!E);return}$(!1),Me(E=>({...E,items:E.items.map(F=>F.id===h?{...F,[b]:!F[b]}:F)})),(b==="hidden"||b==="locked")&&Xe(E=>E===h&&!z.items.find(F=>F.id===h)?.[b]?null:E)},Hu=(h,b,E)=>{$(!1),Me(F=>eg(F,h,b,ke,E))},fs=T.length?T:y?[y]:[],xl=()=>{$(!1),Me(h=>tg(h,ke))},bl=()=>{g.current=ng(Ae.current,fs),w(g.current.length>0),xn.current="keys"},yl=()=>{if(!g.current.length)return;$(!1);let h=[];Me(b=>{const E=sg(b,g.current,ke);return h=E.pasted,E.stage}),h.length&&gl(h)},Wu=h=>{fs.length&&Me(b=>ag(b,fs,h))},vl=h=>{if(!fs.length)return;const b=h/(rn(fe)*fe.duration);cc(Ae.current,fs,b).moved&&($(!1),Me(E=>cc(E,fs,b).stage))},qu=h=>{const b=ke;f(E=>h==="in"?{in:b,out:E&&E.out>b?E.out:1}:{in:E&&E.in<b?E.in:0,out:b}),x(!0)},Gu=(h,b,E)=>{if(!((h==="camera"?fe.cameraKeys:fe.objectKeys?.[h])||[]).some(K=>K.id!==b&&Math.abs(K.time-E)<1e-6)){if(h==="camera")fl((fe.cameraKeys||[]).map(K=>K.id===b?{...K,time:E}:K));else{if(z.items.find(K=>K.id===h)?.locked)return;yt({objectKeys:{...fe.objectKeys,[h]:(fe.objectKeys?.[h]||[]).map(K=>K.id===b?{...K,time:E}:K).sort((K,Y)=>K.time-Y.time)}})}Ue(E)}},jl=()=>{const h=[...T,...y&&!T.some(Y=>Y.row===y.row&&Y.id===y.id)?[y]:[]];if(!h.length)return;const b=Y=>new Set(h.filter(ae=>ae.row===Y).map(ae=>ae.id)),E={...fe.objectKeys};let F=!1;for(const Y of new Set(h.map(ae=>ae.row)))if(Y!=="camera"&&!z.items.find(ae=>ae.id===Y)?.locked){const ae=b(Y);E[Y]=(E[Y]||[]).filter(ve=>!ae.has(ve.id)),F=!0}const K=h.some(Y=>Y.row==="camera")?Yi((fe.cameraKeys||[]).filter(Y=>!b("camera").has(Y.id))):{};yt({...K,...F?{objectKeys:E}:{}}),i(null),k(null),j([])},Uu=h=>{$(!1),yt(Jf(fe,h)),h!=="path"&&Ue(h==="static"?0:1)},kl=async h=>{try{const b=await N0("model",h);Be(E=>h?[...E,...b.assets]:b.assets),G(b.nextCursor)}catch(b){ce(b.message)}},Xu=async h=>{if(h){if(ce(""),!h.name.toLowerCase().endsWith(".glb")||h.size>50*1024*1024){ce("Chọn file GLB tối đa 50 MB.");return}le(!0);try{const b=new DataView(await h.slice(0,12).arrayBuffer());if(b.byteLength<12||b.getUint32(0,!0)!==1179937895||b.getUint32(4,!0)!==2)throw new Error("File không phải GLB 2.0 hợp lệ");const E=await h.arrayBuffer(),F=new DataView(E);if(F.byteLength<20||F.getUint32(8,!0)!==E.byteLength||F.getUint32(16,!0)!==1313821514)throw new Error("Cấu trúc GLB không hợp lệ");const K=F.getUint32(12,!0);if(20+K>E.byteLength)throw new Error("File GLB bị thiếu dữ liệu");const Y=JSON.parse(new TextDecoder().decode(new Uint8Array(E,20,K)));if([...Y.buffers||[],...Y.images||[]].some(ge=>ge.uri&&!ge.uri.startsWith("data:")))throw new Error("Hãy xuất GLB với texture và dữ liệu nhúng trong file.");const{gcsUri:ae}=await _s(new File([h],h.name,{type:"model/gltf-binary"})),ve={...fn("model",Ae.current.items.length),name:h.name,model:{gcsUri:ae,name:h.name}};Me(ge=>({...ge,items:[...ge.items,ve]})),Xe(ve.id)}catch(b){ce(b.message)}finally{le(!1)}}},wl=(h,b)=>{const E={...fn("splat",Ae.current.items.length),name:h,position:[0,0,0],color:"#9aa3a8",splat:b};Me(F=>({...F,items:[...F.items,E]})),Xe(E.id)},Vu=async h=>{if(!h)return;ce("");const b=h.name.split(".").pop()?.toLowerCase()||"";if(!e0.includes(b)||h.size>t0){ce(o("Chọn file bản quét .spz, .ply, .splat, .ksplat hoặc .sog tối đa 300 MB."));return}le(!0);try{const{gcsUri:E}=await _s(new File([h],h.name,{type:"application/x-gaussian-splat"}));wl(h.name.replace(/\.[^.]+$/,""),{name:h.name,gcsUri:E,source:"scan",flip:!0})}catch(E){ce(E.message)}finally{le(!1)}},ii=(Pt()?.nodes()||[]).filter(h=>h.type==="world"&&typeof h.data.splatUrl=="string"),Yu=h=>{const b=Array.from({length:h==="person"?$e:1},(E,F)=>({...fn(h,z.items.length+F),name:`${o(Hi.find(([K])=>K===h)?.[1]||"Model")} ${z.items.length+F+1}`}));Me(E=>({...E,items:[...E.items,...b]})),Xe(b[0].id)};async function ri(h,b,E){const F=je.current;if(!F)throw new Error("3D chưa sẵn sàng");const K=structuredClone(Ae.current);F.sync(K,null);const Y=await f1(F,K,e,h,{signal:E,progress:b}),ae=x1(Y,K.plate?.timelineClipId);return Lt.current=Y.at(-1)?.nodeId||null,Bt.current=Y.at(-1)?.url||null,ae}async function li(h,b,E){const F=structuredClone(Ae.current),K=F.shots.find(jt=>jt.id===F.activeShot),Y=dt.getState().canvasId,ae=new File([h],`${K.name}-camera.mp4`,{type:"video/mp4"}),{url:ve,gcsUri:ge}=await _s(ae,void 0,"video");Bt.current=ve;const We=Pt()?.getNode(e);if(!We||dt.getState().canvasId!==Y)throw new Error("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi.");const De=b.end-b.start,Ve=`Use the attached 3D previs video as the camera-motion and spatial-layout reference. Preserve its camera trajectory, framing, lens perspective and timing over ${De} seconds. Preserve the subject movements and their spatial relationships shown in the reference. Replace the previs appearance with the intended final visual style; do not copy editor helpers. The reference contains no audio. Describe the desired final appearance here.`,ft=Pt()?.addNode("video",{url:ve,gcsUri:ge,label:`${K.name} · Camera ref`,duration:De,ratio:K.aspect,status:"succeeded",shotSourceId:e,shotId:K.id,shotRevision:F.revision,cameraVideo:{...b},prompt:Ve},{x:We.position.x+380,y:We.position.y},{sourceIds:[e]});if(Lt.current=ft||null,E==="timeline"){if(!ft)throw new Error("Không tạo được video trên Canvas");const jt=dt.getState(),yn=We.data?.timelineClipId,Kt=jt.clips.find(Zt=>Zt.id===yn);if(!Kt)throw new Error("Clip 3D gốc không còn trên Timeline. Video đã lưu vào Canvas.");if(jt.timelineTracks[Kt.track]?.locked)throw new Error("Track đã khóa. Video đã lưu vào Canvas.");const dn=Kt.kind==="model"?Kt:Kt.from3D?.clip,It={id:crypto.randomUUID(),nodeId:ft,track:Kt.track,start:Kt.start,duration:Math.max(1/30,Math.min(Kt.duration,Math.floor(De*30)/30)),sourceDuration:De,inPoint:0,volume:1,url:ve,gcsUri:ge,kind:"video",label:`${Kt.label.replace(/ · 3D$/,"")} · 3D`,...Kt.zIndex!==void 0?{zIndex:Kt.zIndex}:{},...dn?{from3D:{shotNodeId:e,clip:dn}}:{}};jt.setClips(Zt=>Zt.map(xs=>xs.id===Kt.id?It:xs)),jt.setTimelineMedia(Zt=>Zt.some(xs=>xs.source==="canvas"&&xs.id===ft)?Zt:[...Zt,{id:ft,source:"canvas",kind:"video",url:ve,gcsUri:ge,label:It.label,duration:De}]),Pt()?.updateNodeData(e,{timelineClipId:It.id}),pt(),jt.setView("timeline"),jt.toast(o("Đã đưa video 3D về Timeline, thay đúng chỗ clip model"),"ok");return}dt.getState().toast(o("Đã lưu video camera vào Canvas và tài sản của bạn"),"ok")}async function Yn(h,b=Ae.current.shots.find(ae=>ae.id===Ae.current.activeShot),E=0,F=!0,K=0,Y=""){if(!je.current)return;F&&se(!0),ce("");const ae=dt.getState().canvasId,ve=structuredClone(Ae.current);ve.activeShot=b.id;const ge=b,We=Ae.current.activeShot;try{We!==ge.id&&je.current.sync(ve,J);const De=await je.current.exportPng(K),Ve=`${ge.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}${Y.replace(/\s+/g,"-")}.png`;if(h){const{url:ft,gcsUri:jt}=await _s(new File([De],Ve,{type:"image/png"})),yn=Pt()?.getNode(e);if(dt.getState().canvasId!==ae)throw new Error("Canvas đã thay đổi; ảnh chưa được chèn");if(!yn)throw new Error("Cảnh gốc không còn tồn tại");const Kt=Pt()?.addNode("image",{url:ft,gcsUri:jt,label:`${ge.name}${Y}`,ratio:ge.aspect,prompt:ki(ve),shotSourceId:e,shotId:ge.id,shotRevision:ve.revision,sceneVersion:ve.version,characterReferences:ve.items.filter(dn=>dn.kind==="person"&&dn.reference).map(dn=>dn.reference),cameraMotion:{pathSmooth:ge.pathSmooth,type:ge.motion,duration:ge.duration,endPosition:ge.endPosition,endTarget:ge.endTarget,endLens:ge.endLens},cameraFrame:K},{x:yn.position.x+380,y:yn.position.y+E*280},{sourceIds:[e,...ve.items.flatMap(dn=>dn.reference?.nodeId?[dn.reference.nodeId]:[])]});return dt.getState().toast(o("Đã đưa ảnh shot vào Canvas"),"ok"),Kt}else{const ft=URL.createObjectURL(De),jt=document.createElement("a");jt.href=ft,jt.download=Ve,jt.click(),setTimeout(()=>URL.revokeObjectURL(ft),1e3)}}catch(De){if(ce(De.message),!F)throw De}finally{We!==ge.id&&je.current.sync(Ae.current,J),F&&se(!1)}}async function Qu(){if(fe.motion!=="static"){se(!0),ce("");try{const h=await Yn(!0,fe,0,!1,0," · Start"),b=await Yn(!0,fe,1,!1,1," · End");h&&b&&(Pt()?.updateNodeData(h,{pairedShotNodeId:b}),Pt()?.updateNodeData(b,{pairedShotNodeId:h})),dt.getState().toast(o("Đã tạo cặp Start/End cho Seedance"),"ok")}catch(h){ce(h.message)}finally{je.current?.sync(Ae.current,J),se(!1)}}}async function Zu(){let h=!1;se(!0),ce("");try{Aa.includes(fe.aspect)||dt.getState().toast(ju(fe).aspect.at(-1)||"","error");const b=await Yn(!0,fe,0,!1,ke," · Previs");if(!b)return;const E=[b,...Ae.current.items.flatMap(K=>K.reference?.nodeId?[K.reference.nodeId]:[]),...(Ae.current.styleRefs||[]).map(K=>K.nodeId)],F=Pt()?.getNode(e);h=!0,pt(),dt.getState().openComposer({mode:"image",generator:"openai:gpt-image",refs:Array.from(new Set(E)),prompt:n0(Ae.current),count:1,aspectRatio:Aa.includes(fe.aspect)?fe.aspect:Qi(fe.aspect,Aa),resolution:"2K",quality:"high",anchor:F?{x:F.position.x+760,y:F.position.y}:null}),dt.getState().toast(o("Khung previs đã sẵn sàng để tạo ảnh thật"),"ok")}catch(b){ce(b.message)}finally{h||je.current?.sync(Ae.current,J),se(!1)}}async function Ju(){if(je.current){se(!0),ce("");try{const h=await je.current.exportPng(ke,!0),b=URL.createObjectURL(h),E=document.createElement("a");E.href=b,E.download=`${fe.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-ghi-chu.png`,E.click(),setTimeout(()=>URL.revokeObjectURL(b),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}async function em(){se(!0),ce("");try{for(let h=0;h<Ae.current.shots.length;h++)await Yn(!0,Ae.current.shots[h],h,!1);dt.getState().toast(o("Đã xuất {0} shot vào Canvas",[Ae.current.shots.length]),"ok")}catch(h){ce(h.message)}finally{se(!1)}}async function tm(){if(je.current){se(!0);try{const h=Ae.current.shots.find(K=>K.id===Ae.current.activeShot),b=await je.current.exportDepth(ke),E=URL.createObjectURL(b),F=document.createElement("a");F.href=E,F.download=`${h.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-depth.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(E),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}async function nm(){if(je.current){se(!0);try{const h=Ae.current.shots.find(K=>K.id===Ae.current.activeShot),b=await je.current.exportPoseMask(ke),E=URL.createObjectURL(b),F=document.createElement("a");F.href=E,F.download=`${h.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-pose-mask.png`,F.click(),setTimeout(()=>URL.revokeObjectURL(E),1e3)}catch(h){ce(h.message)}finally{se(!1)}}}const gs=(h,b,E,F=-100)=>t.jsxs("div",{className:"shot-vector",children:[t.jsx("small",{children:o(h)}),b.map((K,Y)=>t.jsx(Hn,{label:`${o(h)} ${["X","Y","Z"][Y]}`,value:K,min:F,onChange:ae=>{const ve=[...b];ve[Y]=ae,E(ve)}},Y))]});R.useEffect(()=>{try{localStorage.setItem("clipoox.shot.layout",JSON.stringify(pe))}catch{}},[pe]);const zn=h=>{xe(h);try{localStorage.setItem("clipoox.shot.panel",h||"")}catch{}},sm=h=>zn(Z===h?null:h),Ml=h=>{U(h);try{localStorage.setItem("clipoox.shot.railWide",h?"1":"0")}catch{}},[Qa,aa]=R.useState(null),Sl=h=>{const b=h.target.closest("button"),E=b?.querySelector(".lbl");if(!b||!E||getComputedStyle(E).display!=="none"){aa(null);return}const F=b.getBoundingClientRect(),K=h.currentTarget.getBoundingClientRect().right,Y=b.getAttribute("aria-label")||"";aa(ae=>ae&&ae.label===Y&&ae.top===F.top+F.height/2?ae:{label:Y,left:K+8,top:F.top+F.height/2})},am=()=>{me(Wi),Ml(!1);try{localStorage.removeItem("clipoox.shot.layout")}catch{}},ci=(h,b)=>{if(h.button!==0)return;h.preventDefault();const E=h.currentTarget,F={x:h.clientX,y:h.clientY,value:pe[b]},K=h.pointerId;E.setPointerCapture(K),E.classList.add("dragging");const Y=ge=>b==="timeline"?Math.max(120,Math.min(window.innerHeight*.55,ge)):b==="drawer"?Math.max(240,Math.min(window.innerWidth*.2,ge)):Math.max(260,Math.min(window.innerWidth*.22,ge)),ae=ge=>{const We=b==="timeline"?F.y-ge.clientY:b==="drawer"?ge.clientX-F.x:F.x-ge.clientX;me(De=>({...De,[b]:Math.round(Y(F.value+We))}))},ve=()=>{E.removeEventListener("pointermove",ae),E.removeEventListener("pointerup",ve),E.removeEventListener("pointercancel",ve),E.classList.remove("dragging")};E.addEventListener("pointermove",ae),E.addEventListener("pointerup",ve),E.addEventListener("pointercancel",ve)};return t.jsxs("div",{className:"shot-workspace",role:"dialog","aria-modal":"true","aria-label":o("3D Shot Composer"),children:[Tt&&t.jsx(F1,{count:it.length,start:ke*fe.duration,left:(1-ke)*fe.duration,busy:H,onRun:h=>{Iu(h)},onClose:()=>Rt(!1)}),_t&&t.jsx(E1,{x:_t.x,y:_t.y,renaming:!!_t.renaming,items:_t.scene?[]:it.map(h=>z.items.find(b=>b.id===h)).filter(Boolean),canPaste:!!Ua(),hiddenCount:z.items.filter(h=>h.hidden).length,blenderKeys:Sn,onBlenderKeys:As,onAction:Eu,onRename:h=>{const b=it[0];rt(null),b&&He(b,{name:h})},onClose:sn}),Pn.on&&(()=>{const h=lt.current?.getBoundingClientRect(),b=Pn.from,E=Pn.to;if(!h)return null;const F=K=>{if(!b)return;const Y=E&&Math.hypot(E[0]-b[0],E[1]-b[1])>3?je.current?.objectsInRect(b[0],b[1],K.clientX,K.clientY)??[]:[];wt(K.shiftKey?[...xt.current,...Y.filter(ae=>!xt.current.includes(ae))]:Y),an({on:!1})};return t.jsxs("div",{className:"shot-boxsel",role:"presentation","aria-label":o("Kéo để chọn theo vùng"),style:{left:h.left,top:h.top,width:h.width,height:h.height},onMouseDown:K=>{K.button===0&&an({on:!0,from:[K.clientX,K.clientY],to:[K.clientX,K.clientY]})},onMouseMove:K=>{b&&an({on:!0,from:b,to:[K.clientX,K.clientY]})},onMouseUp:F,onContextMenu:K=>{K.preventDefault(),an({on:!1})},children:[t.jsx("span",{className:"shot-boxsel-hint",children:o("Kéo để chọn theo vùng · Shift: chọn thêm · Esc: thôi")}),b&&E&&t.jsx("i",{style:{left:Math.min(b[0],E[0])-h.left,top:Math.min(b[1],E[1])-h.top,width:Math.abs(E[0]-b[0]),height:Math.abs(E[1]-b[1])}})]})})(),L&&t.jsx(m1,{shot:fe,engine:je.current||null,onClose:()=>N(!1),onBusy:se,onReady:li,timelineTarget:(()=>{const h=Pt()?.getNode(e)?.data?.timelineClipId;return typeof h=="string"?dt.getState().clips.find(b=>b.id===h)?.label:void 0})(),vfx:z.plate?{layers:new Set(z.items.filter(h=>h.kind==="fx"&&!h.hidden).map(Qh)).size,target:dt.getState().clips.find(h=>h.id===z.plate?.timelineClipId)?.label,run:async(h,b,E)=>{const F=await ri(h,b,E),K=dt.getState();if(!F.placed){K.toast(o("Đã lưu {0} video hiệu ứng vào Canvas. Clip gốc không có trên Timeline đang mở: thêm bằng tay hoặc mở lại Timeline đó.",[F.passes.length]),"info");return}pt(),K.setView("timeline"),K.toast(F.pendingMatte?o("Đã đặt {0} lớp hiệu ứng lên Timeline. Timeline đang tách người để đặt lớp sau người ra sau.",[F.passes.length]):o("Đã đặt {0} lớp hiệu ứng lên Timeline.",[F.passes.length]),"ok")}}:void 0}),t.jsxs("header",{children:[t.jsxs("button",{disabled:H,onClick:pt,children:[t.jsx(Ce.back,{}),o("← Canvas").replace("← ","")]}),t.jsxs("strong",{children:[o("3D Shot Composer"),t.jsx("em",{children:o("BETA")})]}),t.jsx("span",{className:"shot-save","data-save-state":Fe,title:Fe==="error"&&Et?Et:void 0,children:Fe==="saved"?o("Đã lưu"):Fe==="error"?t.jsxs(t.Fragment,{children:[o("Lỗi lưu — đã giữ bản trên máy này"),Et&&t.jsx("small",{className:"shot-save-why",children:Et}),t.jsx("button",{type:"button",className:"shot-save-retry",onClick:()=>dt.getState().retrySave(),children:o("Thử lại")})]}):o("Đang lưu…")}),t.jsx("button",{"aria-label":o("Hoàn tác"),title:o("Hoàn tác (⌘Z)"),disabled:!Yt.current.length||H,onClick:()=>Va(),children:t.jsx(Ce.undo,{})}),t.jsx("button",{"aria-label":o("Làm lại"),title:o("Làm lại (⇧⌘Z)"),disabled:!hn.current.length||H,onClick:()=>Va(!0),children:t.jsx(Ce.redo,{})}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Yn(!1,fe,0,!0,ke)},title:o("Tải PNG"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:o("Tải PNG")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te,onClick:tm,title:o("Depth map"),children:[t.jsx(Ce.depth,{}),t.jsx("span",{className:"lbl",children:o("Depth map")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te,onClick:nm,title:o("Pose mask"),children:[t.jsx(Ce.mask,{}),t.jsx("span",{className:"lbl",children:o("Pose mask")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te||z.shots.length<2,onClick:em,title:o("Xuất tất cả shot"),children:[t.jsx(Ce.layers,{}),t.jsx("span",{className:"lbl",children:o("Xuất tất cả shot")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:H||!Te||fe.motion==="static",onClick:Qu,title:o("Start + End"),children:[t.jsx(Ce.frames,{}),t.jsx("span",{className:"lbl",children:o("Start + End")})]}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Zu()},title:o("Biến khung xám thành ảnh thật (giữ nguyên bố cục)"),children:[t.jsx(Ce.image,{}),t.jsx("span",{className:"lbl",children:o("Ảnh thật")})]}),t.jsxs("button",{className:"shot-primary",disabled:H||!Te,onClick:()=>{$(!1),N(!0)},title:o("Xuất MP4"),children:[t.jsx(Ce.video,{}),o("Xuất MP4")]}),t.jsxs("button",{disabled:H||!Te,onClick:()=>{$(!1),Yn(!0,fe,0,!0,ke)},children:[t.jsx(Ce.plus,{}),H?o("Đang xuất…"):o("Đưa vào Canvas")]})]}),bn&&bn.canvasId===qt&&bn.nodeId===e&&t.jsxs("div",{className:"shot-sync-bar",role:"alert",children:[t.jsx("span",{"aria-hidden":!0,children:"⟳"}),t.jsxs("div",{className:"grow",children:[t.jsx("b",{children:kf(bn.by)?o("Cảnh 3D này có phiên bản mới từ trợ lý AI của bạn."):o("Cảnh 3D này có phiên bản mới.")})," ",o("Bạn cũng có thay đổi chưa lưu ở đây — chọn bản muốn giữ.")]}),t.jsx("button",{className:"primary",disabled:$n,onClick:()=>void wf(bn.canvasId,bn.nodeId).then(()=>dt.getState().toast(o("Đã tải phiên bản mới nhất của cảnh 3D."),"ok")),children:o("Tải phiên bản mới")}),t.jsx("button",{disabled:$n,onClick:Mf,children:o("Giữ bản của tôi")})]}),he&&t.jsx("div",{className:"shot-error",role:"alert",children:o(he)}),P&&t.jsx(Sf,{characters:P==="characters",onClose:()=>{W(!1),Re(null)},onSelect:Ts}),A&&t.jsx("div",{className:"shot-trial-shield",role:"dialog","aria-label":o("Xem thử đề xuất AI"),children:t.jsxs("div",{className:"shot-trial-controls",children:[t.jsx("b",{children:o("Xem thử · chưa lưu")}),t.jsx("button",{onClick:()=>{ke>=1&&Ue(0),$(!_)},children:_?o("Tạm dừng"):o("Phát lại")}),t.jsx("input",{"aria-label":o("Thời gian xem thử"),type:"range",min:0,max:1,step:1e-4,value:ke,onChange:h=>{$(!1),Ue(+h.target.value)}}),t.jsxs("span",{children:[(ke*fe.duration).toFixed(2),o("s")]}),t.jsx("button",{onClick:()=>Vn(!1),children:o("Bỏ bản xem thử")}),t.jsx("button",{className:"shot-primary",onClick:()=>Vn(!0),children:o("Giữ thay đổi")})]})}),t.jsxs("div",{className:`shot-layout ${Z?"has-drawer":""} ${be?"rail-wide":""}`,style:{"--drawer-w":`${pe.drawer}px`,"--right-w":`${pe.right}px`},children:[t.jsxs("nav",{className:"shot-rail","aria-label":o("Công cụ dựng cảnh"),onMouseOver:Sl,onFocus:Sl,onMouseLeave:()=>aa(null),onBlur:()=>aa(null),onScroll:()=>aa(null),children:[vo.map(([h,b,E])=>t.jsxs("button",{type:"button",className:Z===h?"active":"","aria-pressed":Z===h,"aria-label":o(b),onClick:()=>sm(h),children:[E,t.jsx("span",{className:"lbl",children:o(b)}),h==="objects"&&t.jsx("small",{className:"shot-rail-count",children:z.items.length}),h==="shots"&&z.shots.length>1&&t.jsx("small",{className:"shot-rail-count",children:z.shots.length}),h==="notes"&&Ls.length>0&&t.jsx("small",{className:"shot-rail-count",children:Ls.length})]},h)),t.jsx("span",{className:"shot-rail-gap"}),t.jsxs("button",{type:"button","aria-label":be?o("Thu gọn thanh công cụ"):o("Mở rộng thanh công cụ"),onClick:()=>Ml(!be),children:[be?t.jsx(Ce.collapse,{}):t.jsx(Ce.expand,{}),t.jsx("span",{className:"lbl",children:o("Thu gọn")})]}),t.jsxs("button",{type:"button","aria-label":o("Khôi phục bố cục"),onClick:am,children:[t.jsx(Ce.reset,{}),t.jsx("span",{className:"lbl",children:o("Khôi phục bố cục")})]})]}),Qa&&Jh.createPortal(t.jsx("span",{className:"shot-rail-tip",role:"tooltip",style:{left:Qa.left,top:Qa.top},children:Qa.label}),document.querySelector(".shot-workspace")||document.body),Z&&t.jsxs("aside",{className:"shot-drawer shot-inspector","aria-label":o(vo.find(h=>h[0]===Z)[1]),children:[t.jsxs("div",{className:"shot-drawer-head",children:[t.jsxs("h3",{children:[o(vo.find(h=>h[0]===Z)[1]),Z==="objects"?t.jsxs("small",{className:"shot-total",children:[" · ",z.items.length]}):Z==="shots"?t.jsxs("small",{className:"shot-total",children:[" · ",z.shots.length," · ",ji(ul.at(-1)?.end||0)]}):Z==="notes"?t.jsxs("small",{className:"shot-total",children:[" · ",Ls.length]}):Z==="series"&&z.series?t.jsxs("small",{className:"shot-total",children:[" · ",z.series.name]}):null]}),t.jsx("button",{type:"button",className:"shot-drawer-close","aria-label":o("Đóng bảng"),title:o("Đóng bảng (Esc)"),onClick:()=>zn(null),children:t.jsx(Ce.close,{})})]}),t.jsxs("div",{className:"shot-drawer-body shot-inspector-scroll",tabIndex:0,children:[Z==="scene"&&t.jsx("div",{className:"shot-scene-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsxs("div",{className:"shot-add",children:[t.jsx("input",{ref:ct,type:"file",accept:".glb",hidden:!0,onChange:h=>{Xu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{onClick:()=>W("all"),children:[t.jsx(Ce.library,{}),o("Kho 3D chung")]}),t.jsxs("button",{onClick:()=>void kl(),children:[t.jsx(Ce.user,{}),o("Model của tôi")]}),Pe.length>0&&t.jsxs("select",{"aria-label":o("Model 3D đã lưu"),value:"",onChange:h=>{const b=Pe.find(F=>F.id===h.target.value);if(!b)return;const E={...fn("model",Ae.current.items.length),name:b.name,model:{gcsUri:b.gcsUri,name:b.name}};Me(F=>({...F,items:[...F.items,E]})),Xe(E.id)},children:[t.jsx("option",{value:"",children:o("Chọn model đã lưu…")}),Pe.map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))]}),ot&&t.jsx("button",{onClick:()=>void kl(ot),children:o("Thêm model đã lưu")}),t.jsxs("button",{disabled:Se,onClick:()=>ct.current?.click(),children:[t.jsx(Ce.cube,{}),Se?o("Đang tải…"):"Model GLB"]}),t.jsx("input",{ref:Ke,type:"file",accept:".spz,.ply,.splat,.ksplat,.sog",hidden:!0,onChange:h=>{Vu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{disabled:Se,title:o("Bản quét 3D địa điểm thật từ app điện thoại (Scaniverse, Polycam, Luma…)"),onClick:()=>Ke.current?.click(),children:[t.jsx(Ce.image,{}),o("Bối cảnh thật")]}),ii.length>0&&t.jsxs("select",{"aria-label":o("Dùng 3D World trên Canvas"),value:"",onChange:h=>{const b=ii.find(F=>F.id===h.target.value);if(!b)return;const E=b.data;wl(E.label||"3D World",{name:E.label||"3D World",url:E.splatUrl,source:"world",flip:!0,...E.worldId?{worldId:E.worldId}:{}})},children:[t.jsx("option",{value:"",children:o("Dùng 3D World trên Canvas…")}),ii.map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"3D World")},h.id))]}),Hi.map(([h,b])=>t.jsxs("button",{disabled:H,onClick:()=>Yu(h),children:[P1[h],o(b)]},h))]}),t.jsx(Hn,{label:"Số người mỗi lần thêm",value:$e,min:1,max:50,step:1,onChange:h=>Le(Math.floor(h))})]})}),Z==="fx"&&t.jsx(Tv,{onEdit:()=>zn("fxedit"),onPlayClip:(h,b)=>{Jo(h,b)},stage:z,selected:J,playhead:ke*fe.duration,change:Me,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],anchor:(h,b,E)=>je.current?.partPointAt(fe,E,h,b)??null,engine:je.current,setError:ce}),Z==="material"&&t.jsx(Hv,{stage:z,selected:J,change:Me,engine:je.current,setError:ce,scope:nt,setScope:et}),Z==="rigging"&&t.jsx(h1,{stage:z,shot:fe,selected:J,engine:Te?je.current:null,playhead:ke,busy:H,change:Me,patchItem:He,onSelect:Xe,resync:()=>je.current?.sync(Ae.current,J),setError:ce,addPoseKey:Dn,onPlayClip:Jo,motionLoop:Qo,motionMirror:Zo,onMotionLoop:Qr,onMotionMirror:Zr,keys:Ge}),Z==="fxedit"&&t.jsx(Lv,{stage:z,selected:J,playhead:ke*fe.duration,change:Me,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],engine:je.current}),Z==="mixfx"&&t.jsx($v,{stage:z,selected:J,progress:ke,change:Me,onSelect:Xe,engine:je.current,setError:ce}),Z==="modeling"&&t.jsx(fx,{stage:z,selected:J,change:Me,getStage:()=>Ae.current,onSelect:Xe,ground:()=>je.current?.groundAtScreenCentre()??[0,0,0],engine:je.current,setError:ce}),Z==="objects"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-objects-section",children:[t.jsx("div",{className:"shot-charlib",children:t.jsxs("button",{type:"button",className:"shot-charlib-btn",onClick:()=>W("characters"),title:o("Nhân vật có xương: thêm vào cảnh là chạy mocap / chuyển động ngay"),children:[t.jsx(Ce.person,{}),t.jsx("span",{children:o("Thư viện nhân vật")})]})}),t.jsx("div",{className:"shot-list",children:z.items.map(h=>t.jsxs("div",{className:J===h.id?"active":B.includes(h.id)?"picked":"",onContextMenu:b=>{b.preventDefault(),si(h.id,b.clientX,b.clientY)},children:[t.jsxs("button",{"aria-pressed":it.includes(h.id),title:o("Shift/Ctrl+click: chọn thêm · chuột phải: menu"),onClick:b=>nn(h.id,b.shiftKey||b.ctrlKey||b.metaKey),children:[h.kind==="person"?"♙":h.kind==="set"?"⌂":"◇"," ",h.name,h.kind==="set"&&h.set?.parts?t.jsxs("small",{className:"shot-list-meta",children:[" · ",h.set.parts," ",o("khối")]}):null]}),t.jsx("button",{title:h.hidden?o("Hiện"):o("Ẩn"),onClick:()=>He(h.id,{hidden:!h.hidden}),children:h.hidden?"○":"●"}),t.jsx("button",{title:h.locked?o("Mở khóa"):o("Khóa"),onClick:()=>He(h.id,{locked:!h.locked}),children:h.locked?"▣":"□"}),t.jsx("button",{className:"shot-delete-item","aria-label":o("Xóa {0}",[h.name]),title:h.locked?o("Mở khóa đối tượng trước khi xóa"):o("Xóa {0} (Delete)",[h.name]),disabled:H||h.locked,onClick:()=>tl(h.id),children:t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:t.jsx("path",{d:"M4 6h16M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7m4-7v7"})})})]},h.id))})]}),te&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:o("CHỈNH ĐỐI TƯỢNG")}),t.jsxs("fieldset",{disabled:te.locked||H,children:[t.jsx("input",{"aria-label":o("Tên đối tượng"),value:te.name,onChange:h=>He(te.id,{name:h.target.value})}),t.jsxs("label",{className:"shot-field",children:[o("Màu"),t.jsx("input",{"aria-label":o("Màu đối tượng"),type:"color",value:te.color,onChange:h=>He(te.id,{color:h.target.value})})]}),t.jsxs("select",{"aria-label":o("Đặt lên bề mặt"),value:"",onChange:h=>{h.target.value&&je.current?.placeOnSurface(h.target.value)},children:[t.jsx("option",{value:"",children:o("Đặt lên bề mặt…")}),t.jsx("option",{value:"ground",children:o("Mặt đất")}),z.items.filter(h=>h.kind!=="person"&&h.id!==te.id&&!h.hidden).map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))]}),gs(o("Vị trí"),te.position,h=>He(te.id,{position:h})),gs("Xoay °",te.rotation,h=>He(te.id,{rotation:h}),-360),gs(o("Tỷ lệ"),te.scale,h=>He(te.id,{scale:h}),.05),te.kind==="model"&&te.model&&t.jsxs("div",{className:"shot-model-size",children:[t.jsx(Hn,{label:"Chiều cao thật (m)",value:Number((je.current?.modelHeight(te)??2).toFixed(2)),min:.02,max:500,step:.01,onChange:h=>He(te.id,{model:{...te.model,height:h}})}),t.jsx("small",{className:"shot-hint",children:te.model.height?o("Kích thước thật"):o("Tự động: cạnh dài nhất 2 m")}),te.model.height&&t.jsx("button",{onClick:()=>{const{height:h,...b}=te.model;He(te.id,{model:b})},children:o("Về tự động")})]}),te.hold&&(()=>{const h=z.items.find(b=>b.id===te.hold.by);return t.jsxs("div",{className:"shot-held",children:[t.jsx("small",{className:"shot-hint",children:o("Đang được {0} cầm ở {1}",[h?.name||"?",te.hold.hand==="R"?o("tay phải"):o("tay trái")])}),t.jsx("button",{onClick:()=>h&&Jr(h.id,te.hold.hand,""),children:o("Thả xuống")})]})})(),te.kind==="splat"&&te.splat&&(()=>{const h=je.current?.splatExtent(te.splat);return t.jsxs("div",{className:"shot-splat",children:[t.jsx("h3",{children:o("BỐI CẢNH THẬT")}),t.jsxs("small",{className:"shot-hint",children:[te.splat.source==="world"?o("3D World do AI tạo"):o("Bản quét địa điểm thật"),h?` · ${(h.max[0]-h.min[0]).toFixed(1)} × ${(h.max[2]-h.min[2]).toFixed(1)} m`:` · ${o("đang tải…")}`]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:te.splat.flip!==!1,onChange:b=>{const E={...te.splat,flip:b.target.checked},F=je.current?.splatExtent(E);He(te.id,F?{splat:{...E,bounds:{min:F.min,max:F.max},floor:F.floor},position:[te.position[0],-F.floor*te.scale[1],te.position[2]]}:{splat:E})}}),o("Lật trục (file quét kiểu OpenCV)")]}),t.jsx(Hn,{label:"Tỷ lệ bản quét",value:te.scale[0],min:.05,step:.05,onChange:b=>He(te.id,{scale:[b,b,b]})}),t.jsx("button",{disabled:!h,onClick:()=>{h&&He(te.id,{position:[te.position[0],-h.floor*te.scale[1],te.position[2]],splat:{...te.splat,bounds:{min:h.min,max:h.max},floor:h.floor}})},children:o("Căn sàn về mặt đất")}),t.jsx("small",{className:"shot-hint",children:o('Người và camera đặt thẳng trong bối cảnh. Ảnh và video AI giữ nguyên kiến trúc, đồ đạc của bản quét. Sai hướng thì bật/tắt "Lật trục" rồi căn sàn lại.')})]})})(),Wv.includes(te.kind)&&t.jsx(Gv,{item:z.items.find(h=>h.id===te.id)??te,shot:fe,playhead:ke,patchItem:He,change:Me}),te.kind==="person"&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:o("NHẬN DIỆN NHÂN VẬT")}),t.jsxs("select",{"aria-label":o("Ảnh tham chiếu nhân vật"),value:te.reference?.nodeId||"",onChange:h=>{const b=Ya.find(F=>F.id===h.target.value),E=b?.data;He(te.id,{reference:b&&E?.url?{nodeId:b.id,url:E.url,name:E.label||"Character reference"}:null})},children:[t.jsx("option",{value:"",children:o("Không dùng ảnh nhận diện")}),Ya.map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"Image")},h.id))]}),te.reference&&t.jsx("img",{className:"shot-character-ref",src:te.reference.url,alt:te.reference.name}),t.jsx("h3",{children:o("NHÂN VẬT")}),t.jsx("button",{type:"button",className:"shot-char-open",title:o("Thay người này bằng một nhân vật có xương trong kho (giữ vị trí và chuyển động)"),onClick:()=>{Re(te.id),W("characters")},children:o("Chọn nhân vật từ thư viện…")}),te.look||te.figure&&["legs","shoulders","hips","chest","waist","weight","muscle","posture","skin","face"].some(h=>te.figure[h]!==void 0)?t.jsx("button",{type:"button",onClick:()=>He(te.id,{figure:te.figure?{height:te.figure.height,head:te.figure.head,build:te.figure.build}:void 0,look:void 0,character:void 0}),children:o("Về mannequin trơn")}):null,t.jsx("h3",{children:o("VÓC DÁNG")}),t.jsx("div",{className:"shot-add shot-figure-presets",children:Cf.map(h=>{const b=Dt(te.figure);return t.jsx("button",{className:b.height===h.figure.height&&b.head===h.figure.head&&b.build===h.figure.build?"active":"",onClick:()=>He(te.id,{figure:{...h.figure}}),children:o(h.name)},h.name)})}),t.jsx(Hn,{label:"Chiều cao (m)",value:Dt(te.figure).height,min:.3,max:3,step:.01,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),height:h})})}),t.jsxs("label",{className:"shot-joint",children:[o("Cỡ đầu")," ",t.jsxs("span",{children:[Dt(te.figure).head.toFixed(2),"×"]}),t.jsx("input",{"aria-label":o("Cỡ đầu"),type:"range",min:.7,max:2,step:.05,value:Dt(te.figure).head,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),head:+h.target.value})})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Vai / hông")," ",t.jsxs("span",{children:[Dt(te.figure).build.toFixed(2),"×"]}),t.jsx("input",{"aria-label":o("Vai / hông"),type:"range",min:.6,max:1.6,step:.05,value:Dt(te.figure).build,onChange:h=>He(te.id,{figure:Dt({...Dt(te.figure),build:+h.target.value})})})]}),t.jsx("h3",{children:o("ĐẠO CỤ TRÊN TAY")}),t.jsxs("div",{className:"shot-props",children:[["R","L"].map(h=>{const b=z.items.find(F=>F.hold?.by===te.id&&F.hold.hand===h),E=z.items.filter(F=>F.id!==te.id&&!["person","splat","set","floor","wall"].includes(F.kind)&&!(F.hold&&F.hold.by!==te.id));return t.jsxs("div",{className:"shot-prop-hand",children:[t.jsxs("label",{className:"shot-field",children:[h==="R"?o("Tay phải"):o("Tay trái"),t.jsxs("select",{"aria-label":h==="R"?o("Đạo cụ tay phải"):o("Đạo cụ tay trái"),value:b?`item:${b.id}`:"",onChange:F=>Jr(te.id,h,F.target.value),children:[t.jsx("option",{value:"",children:o("— Tay không —")}),b&&t.jsx("option",{value:`item:${b.id}`,children:b.name}),t.jsx("optgroup",{label:o("Đạo cụ dựng sẵn"),children:Nf.map(F=>t.jsx("option",{value:`prop:${F}`,children:o(Ma[F].label)},F))}),E.filter(F=>F.id!==b?.id).length>0&&t.jsx("optgroup",{label:o("Vật trong cảnh"),children:E.filter(F=>F.id!==b?.id).map(F=>t.jsx("option",{value:`item:${F.id}`,children:F.name},F.id))})]})]}),b&&t.jsxs("label",{className:"shot-joint",children:[o("Gập cổ tay")," ",t.jsxs("span",{children:[b.hold.tilt??(b.prop?Ma[b.prop.kind].tilt??0:0),"°"]}),t.jsx("input",{"aria-label":o("Gập cổ tay"),type:"range",min:-90,max:90,step:5,value:b.hold.tilt??(b.prop?Ma[b.prop.kind].tilt??0:0),onChange:F=>Me(K=>({...K,items:K.items.map(Y=>Y.id===b.id?{...Y,hold:{...Y.hold,tilt:+F.target.value}}:Y)}))})]}),b&&t.jsxs("label",{className:"shot-joint",children:[o("Xoay quanh cổ tay")," ",t.jsxs("span",{children:[b.hold.angle??0,"°"]}),t.jsx("input",{"aria-label":o("Xoay đạo cụ quanh cổ tay"),type:"range",min:-180,max:180,step:5,value:b.hold.angle??0,onChange:F=>Me(K=>({...K,items:K.items.map(Y=>Y.id===b.id?{...Y,hold:{...Y.hold,angle:+F.target.value}}:Y)}))})]})]},h)}),t.jsx("small",{className:"shot-hint",children:o("Đạo cụ đi theo cẳng tay qua mọi tư thế, dáng đi, cú đánh. Kiếm, gậy, dao nối dài tầm đánh khi tính trúng đòn.")})]}),t.jsx("h3",{children:o("CHUYỂN ĐỘNG NGƯỜI")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:te.gait!=="off",onChange:h=>He(te.id,{gait:h.target.checked?"auto":"off"})}),o("Tự bước đi / chạy khi di chuyển")]}),(()=>{const h=fe.objectKeys?.[te.id]||[],b=h.filter(F=>F.pose),E=b.find(F=>Math.abs(F.time-ke)<1e-6);return t.jsxs("div",{className:"shot-pose-keys",children:[t.jsx("button",{className:E?"active":"",onClick:()=>Dn(te.id),children:E?o("◆ Cập nhật key tư thế · {0}s",[(ke*fe.duration).toFixed(1)]):o("◇ Key tư thế tại {0}s",[(ke*fe.duration).toFixed(1)])}),E&&t.jsx("button",{onClick:()=>us(te.id),children:o("Bỏ key tư thế")}),E&&t.jsxs("label",{className:"shot-pose-ease",children:[o("Kiểu chuyển vào key")," ",t.jsx("select",{"aria-label":o("Kiểu chuyển vào key"),value:E.poseEase||"smooth",onChange:F=>qa(te.id,F.target.value),children:Af.map(F=>t.jsx("option",{value:F.id,children:o(F.label)},F.id))})]}),t.jsx("small",{className:"shot-hint",children:b.length?o("{0} key tư thế · chỉnh khớp/rig tại key sẽ ghi vào key đó; giữa các key tư thế chuyển mượt.",[b.length]):o("Đặt key ở nhiều thời điểm (đứng → ngồi → giơ tay…) để tư thế chuyển động theo thời gian.")})]})})(),t.jsx(Vv,{shot:fe,item:te,playhead:ke*fe.duration,change:Me,engine:je.current,seek:h=>{$(!1),Ue(Math.max(0,Math.min(1,h/fe.duration)))}}),t.jsx(xu,{disabled:H,loop:Qo,mirror:Zo,onLoop:Qr,onMirror:Zr,onPlay:h=>{Jo(te.id,h)},person:te,playhead:ke*fe.duration}),t.jsxs("div",{className:"shot-mocap",children:[t.jsx("input",{ref:ms,type:"file",accept:".bvh,.fbx,.glb",hidden:!0,onChange:h=>{Mu(h.target.files?.[0]),h.target.value=""}}),t.jsxs("button",{disabled:Xr||H,onClick:()=>ms.current?.click(),title:o("Chuyển động người thật: Mixamo (.fbx), CMU (.bvh) hoặc GLB có animation"),children:[t.jsx(Ce.person,{}),Xr?o("Đang đọc…"):o("Nhập mocap (.bvh · .fbx · .glb)")]}),Ut&&t.jsxs("div",{className:"shot-mocap-card",children:[t.jsx("b",{children:Ut.name}),t.jsxs("small",{children:[Ut.duration.toFixed(1),o("s · khung xương người ✓")]}),t.jsxs("label",{className:"shot-field",children:[o("Tốc độ"),t.jsx("select",{"aria-label":o("Tốc độ mocap"),value:ps,onChange:h=>ku(+h.target.value),children:[.5,.75,1,1.25,1.5,2].map(h=>t.jsxs("option",{value:h,children:[h,"×"]},h))})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:Ur,onChange:h=>wu(h.target.checked)}),o("Di chuyển theo mocap (đi, chạy, nhảy)")]}),t.jsx("small",{className:"shot-hint",children:o("Bắt đầu tại {0}s · dùng {1}s (phần dài hơn shot bị cắt)",[(ke*fe.duration).toFixed(1),Math.min(Ut.duration/ps,(1-ke)*fe.duration).toFixed(1)])}),t.jsx("button",{className:"shot-primary",disabled:H,onClick:()=>Cu(te.id),children:o("Áp dụng cho {0}",[te.name])})]}),Tf(z,te.id)&&t.jsx("button",{onClick:()=>{$(!1),Me(h=>s0(h,te.id))},children:o("Xoá mocap của {0}",[te.name])})]}),t.jsxs("div",{className:"shot-hits",children:[t.jsx("button",{onClick:Au,children:o("⚡ Tự tạo phản ứng trúng đòn")}),Lf(fe)&&t.jsx("button",{onClick:Tu,children:o("Xoá phản ứng tự động")}),t.jsx("small",{className:"shot-hint",children:Nu||o('Đòn = key tư thế kiểu "Ra đòn nhanh". Trúng thì người kia tự bật ra; key Đỡ đòn / Né cúi / Ngả né trước cú đánh để đỡ hoặc né.')})]}),t.jsxs("h3",{children:[o("RIG PRESETS"),t.jsx("button",{className:"shot-pose-mirror",title:o("Lật tư thế trái ↔ phải"),onClick:()=>He(te.id,{pose:Ef(te.pose)}),children:o("⇆ Lật trái/phải")})]}),t.jsx("div",{className:"shot-rig-library",children:Po.map(h=>t.jsxs("section",{children:[t.jsxs("header",{children:[t.jsx("span",{children:o(h.name)}),t.jsxs("small",{children:[h.presets.length," ",o("rig")]})]}),t.jsx("div",{className:"shot-rig-grid",children:h.presets.map(b=>t.jsxs("button",{className:D1(te.pose,In[b])?"active":"",title:o("Áp dụng rig {0}",[b]),onClick:()=>Ft(te,b),children:[t.jsx(Gr,{pose:In[b]}),t.jsx("span",{children:o(b)})]},b))})]},o(h.name)))}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Thư viện pose cá nhân")}),t.jsxs("div",{className:"shot-pose-library",children:[z.poseLibrary.map(h=>t.jsxs("div",{children:[t.jsx("button",{onClick:()=>He(te.id,{pose:{...h.pose}}),children:h.name}),t.jsx("button",{"aria-label":o("Xóa {0}",[h.name]),onClick:()=>Me(b=>({...b,poseLibrary:b.poseLibrary.filter(E=>E.id!==h.id)})),children:o("×")})]},h.id)),t.jsx("button",{onClick:()=>{const h=window.prompt(o("Tên pose"),`Pose ${z.poseLibrary.length+1}`)?.trim();h&&Me(b=>({...b,poseLibrary:[...b.poseLibrary,{id:bt(),name:h,pose:structuredClone(te.pose)}]}))},children:o("+ Lưu pose hiện tại")})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Kéo tay/chân IK")}),t.jsxs("div",{className:"shot-ik-grid",children:[t.jsx(jo,{label:"Tay trái",root:te.pose.shoulderL,bend:te.pose.elbowL,upper:.29,lower:.27,onChange:(h,b)=>He(te.id,{pose:{...te.pose,shoulderL:h,elbowL:b}})}),t.jsx(jo,{label:"Tay phải",root:te.pose.shoulderR,bend:te.pose.elbowR,upper:.29,lower:.27,onChange:(h,b)=>He(te.id,{pose:{...te.pose,shoulderR:h,elbowR:b}})}),t.jsx(jo,{label:"Chân trái",root:te.pose.hipL,bend:te.pose.kneeL,upper:.43,lower:.4,onChange:(h,b)=>He(te.id,{pose:{...te.pose,hipL:h,kneeL:b}})}),t.jsx(jo,{label:"Chân phải",root:te.pose.hipR,bend:te.pose.kneeR,upper:.43,lower:.4,onChange:(h,b)=>He(te.id,{pose:{...te.pose,hipR:h,kneeR:b}})})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Chỉnh từng khớp")}),Object.keys(To).map(h=>t.jsxs("label",{className:"shot-joint",children:[o(To[h])," ",t.jsxs("span",{children:[te.pose[h]||0,"°"]}),t.jsx("input",{"aria-label":o(To[h]),type:"range",min:h.startsWith("knee")||h.startsWith("elbow")?0:-120,max:150,value:te.pose[h]||0,onChange:b=>He(te.id,{pose:{...te.pose,[h]:+b.target.value}})})]},h))]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:o("Tay · đầu · mắt")}),t.jsx("div",{className:"shot-hand-shapes",children:["R","L"].map(h=>t.jsxs("div",{children:[t.jsx("small",{children:h==="R"?o("Tay phải"):o("Tay trái")}),t.jsx("span",{children:Vi.map(b=>t.jsx("button",{type:"button",className:If(te.pose,h,b)?"active":"",onClick:()=>He(te.id,{pose:O1(te.pose,h,b)}),children:o(b.label)},b.id))})]},h))}),t.jsxs("label",{className:"shot-field",children:[o("Mắt nhìn"),t.jsxs("select",{"aria-label":o("Mắt nhìn"),value:te.gaze||"",onChange:h=>He(te.id,{gaze:h.target.value||void 0}),children:[t.jsx("option",{value:"",children:o("Theo tư thế")}),t.jsx("option",{value:"camera",children:o("Nhìn vào camera")}),z.items.filter(h=>h.id!==te.id&&h.kind!=="splat"&&h.kind!=="set").map(h=>t.jsx("option",{value:h.id,children:o("Nhìn {0}",[h.name])},h.id))]})]}),Object.keys(qi).map(h=>{const[b,E,F]=Rf[h],K=$1(te.pose,h);return t.jsxs("label",{className:"shot-joint",children:[o(qi[h])," ",t.jsxs("span",{children:[K,F]}),t.jsx("input",{"aria-label":o(qi[h]),type:"range",min:b,max:E,value:K,disabled:(h==="eyeYaw"||h==="eyePitch")&&!!te.gaze,onChange:Y=>He(te.id,{pose:{...te.pose,[h]:+Y.target.value}})})]},h)})]})]}),t.jsx("button",{onClick:()=>{const h={...structuredClone(te),id:bt(),name:`${te.name} copy`,position:[te.position[0]+1,...te.position.slice(1)]};Me(b=>({...b,items:[...b.items,h]})),Xe(h.id)},children:o("Nhân bản")}),t.jsx("button",{onClick:()=>{tl(te.id)},children:o("Xóa đối tượng")})]})]})]}),Z==="camera"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":o("Tên shot"),value:fe.name,onChange:h=>yt({name:h.target.value})}),t.jsxs("div",{className:"shot-camera-gizmo",role:"group","aria-label":o("Chỉnh camera trong cảnh 3D"),children:[t.jsxs("button",{type:"button",className:r?"active":"","aria-pressed":r,disabled:S,title:o("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"),onClick:()=>{Xe(null),i(null),l(!r),ee(h=>h==="scale"?"translate":h)},children:[t.jsx(Ce.camera,{}),o("Chọn camera")]}),r&&["translate","rotate"].map(h=>t.jsxs("button",{type:"button",className:(D==="rotate"?"rotate":"translate")===h?"active":"","aria-pressed":(D==="rotate"?"rotate":"translate")===h,title:o(h==="translate"?"Di chuyển camera (W)":"Xoay camera (E): vòng xanh dương = nghiêng"),onClick:()=>ee(h),children:[h==="translate"?t.jsx(Ce.move,{}):t.jsx(Ce.rotate,{}),o(h==="translate"?"Di chuyển":"Xoay")]},h))]}),t.jsx("textarea",{className:"shot-note","aria-label":o("Ghi chú đạo diễn cho shot"),placeholder:o("Ghi chú đạo diễn: hành động, cảm xúc, điểm nhấn… (đưa vào prompt)"),maxLength:500,rows:2,value:fe.note||"",onChange:h=>yt({note:h.target.value})}),t.jsxs("div",{className:"shot-row",children:[t.jsx("select",{"aria-label":o("Tỷ lệ ảnh"),value:fe.aspect,onChange:h=>yt({aspect:h.target.value}),children:["16:9","9:16","1:1","21:9","4:3","2.39:1"].map(h=>t.jsx("option",{children:h},h))}),fe.motion!=="path"&&t.jsx(Hn,{label:"Lens mm",value:fe.lens,min:14,max:200,step:1,onChange:h=>yt({lens:h})})]}),t.jsxs("label",{className:"shot-field",children:[o("Thời lượng camera (giây)"),t.jsx(gn,{"aria-label":o("Thời lượng camera (giây)"),min:.1,step:"0.1",value:fe.duration,onCommit:h=>yt({duration:h})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Rung cầm tay")," ",t.jsxs("span",{children:[Math.round((fe.handheld||0)*100),"%"]}),t.jsx("input",{"aria-label":o("Rung cầm tay"),type:"range",min:0,max:1,step:.05,value:fe.handheld||0,onChange:h=>yt({handheld:+h.target.value||void 0})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:fe.impactShake!==!1,onChange:h=>{const b=h.target.checked;yt(b?{impactShake:void 0}:{impactShake:!1,impacts:void 0})}}),o("Rung camera khi trúng đòn")]}),t.jsx(C1,{shot:fe,patch:yt,progress:ke,seek:h=>{$(!1),Ue(h)},engine:je.current||null,selected:a,select:h=>{i(h),k(h?{row:"camera",id:h}:null)}}),fe.motion==="path"&&t.jsx("button",{disabled:H||!Te||!fe.cameraKeys?.length,onClick:async()=>{$(!1),se(!0),ce("");try{for(const[h,b]of(fe.cameraKeys||[]).entries())await Yn(!0,fe,h,!1,b.time,` · Key ${h+1} · ${(b.time*fe.duration).toFixed(1)}s`)}catch(h){ce(h.message)}finally{se(!1)}},children:o("Xuất các key thành ảnh tham chiếu")}),t.jsx("h3",{children:o("CHUYỂN ĐỘNG NHANH")}),t.jsxs("select",{"aria-label":o("Chuyển động camera"),value:fe.motion,onChange:h=>Uu(h.target.value),children:[t.jsx("option",{value:"path",disabled:!fe.cameraKeys?.length,children:o("Đường chạy keyframe")}),t.jsx("option",{value:"static",children:o("Đứng yên")}),t.jsx("option",{value:"dolly-in",children:o("Dolly in")}),t.jsx("option",{value:"dolly-out",children:o("Dolly out")}),t.jsx("option",{value:"truck-left",children:o("Truck trái")}),t.jsx("option",{value:"truck-right",children:o("Truck phải")}),t.jsx("option",{value:"crane-up",children:o("Crane lên")}),t.jsx("option",{value:"crane-down",children:o("Crane xuống")}),t.jsx("option",{value:"orbit-left",children:o("Orbit trái")}),t.jsx("option",{value:"orbit-right",children:o("Orbit phải")}),t.jsx("option",{value:"custom",children:o("Tùy chỉnh")})]}),fe.motion!=="static"&&fe.motion!=="path"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[o("Xem chuyển động")," ",t.jsxs("span",{children:[Math.round(ke*100),"%"]}),t.jsx("input",{"aria-label":o("Tiến trình camera"),type:"range",min:0,max:100,value:ke*100,onChange:h=>Ue(+h.target.value/100)})]}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Camera kết thúc")}),gs(o("Vị trí cuối"),fe.endPosition,h=>yt({endPosition:h,motion:"custom"})),gs(o("Điểm nhìn cuối"),fe.endTarget,h=>yt({endTarget:h,motion:"custom"})),t.jsx(Hn,{label:"Lens cuối mm",value:fe.endLens,min:14,max:200,step:1,onChange:h=>yt({endLens:h,motion:"custom"})})]})]}),t.jsxs("fieldset",{disabled:fe.motion==="path",style:{display:fe.motion==="path"?"none":void 0},children:[t.jsx("button",{onClick:()=>yt(je.current?.captureCamera()||{}),children:o("Dùng góc quan sát làm camera")}),t.jsx("div",{className:"shot-add",children:["Toàn","Trung","Cận","Thấp","Cao","Qua vai"].map((h,b)=>t.jsx("button",{onClick:()=>{const E=te?.position||[0,0,0];yt({position:[[3,2,6],[0,1.5,3],[0,1.7,1.2],[1,.3,3],[2,5,3],[.5,1.7,-1.5]][b].map((K,Y)=>K+E[Y]),target:[E[0],E[1]+(b===2?1.65:1.2),E[2]],roll:0})},children:o(h)},h))}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Thông số camera")}),gs(o("Vị trí máy"),fe.position,h=>yt({position:h})),gs(o("Điểm nhìn"),fe.target,h=>yt({target:h})),t.jsx(Hn,{label:"Nghiêng máy °",value:fe.roll,min:-180,max:180,step:1,onChange:h=>yt({roll:h})}),t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(h=>{const b=h.shots.filter(E=>E.id!==h.activeShot);return{...h,shots:b,activeShot:b[0].id}}),children:o("Xóa camera này")})]})]}),fe.motion==="path"&&t.jsx("button",{disabled:z.shots.length<2,onClick:()=>Me(h=>{const b=h.shots.filter(E=>E.id!==h.activeShot);return{...h,shots:b,activeShot:b[0].id}}),children:o("Xóa camera đường chạy")}),t.jsxs("details",{children:[t.jsx("summary",{children:o("Prompt bố cục")}),t.jsx("textarea",{"aria-label":o("Prompt bố cục"),readOnly:!0,value:ki(z),rows:8}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(ki(z)).then(()=>dt.getState().toast(o("Đã copy prompt"),"ok")).catch(()=>ce("Không truy cập được clipboard; hãy chọn và copy nội dung.")),children:o("Copy prompt")})]})]}),Z==="light"&&t.jsx("div",{className:"shot-light-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("select",{"aria-label":o("Thời điểm trong ngày"),value:na.time,onChange:h=>{const b=h.target.value;ai({time:b,elevation:Yl[b].elevation})},children:Ff.map(h=>t.jsx("option",{value:h,children:o(Yl[h].label)},h))}),t.jsxs("label",{className:"shot-joint",children:[o("Hướng mặt trời")," ",t.jsxs("span",{children:[Math.round(na.azimuth),"°"]}),t.jsx("input",{"aria-label":o("Hướng mặt trời"),type:"range",min:0,max:359,value:Math.round(na.azimuth),onChange:h=>ai({azimuth:+h.target.value})})]}),t.jsxs("label",{className:"shot-joint",children:[o("Độ cao mặt trời")," ",t.jsxs("span",{children:[Math.round(na.elevation),"°"]}),t.jsx("input",{"aria-label":o("Độ cao mặt trời"),type:"range",min:1,max:89,value:Math.round(na.elevation),onChange:h=>ai({elevation:+h.target.value})})]}),t.jsx("small",{className:"shot-hint",children:o("Dùng chung cho mọi shot của cảnh, để hướng sáng không lệch giữa các góc máy.")}),t.jsxs("label",{className:"shot-field shot-style-refs",children:[t.jsxs("span",{children:[o("Ảnh phong cách bối cảnh")," · ",sa.length,"/",wi]}),t.jsxs("select",{"aria-label":o("Thêm ảnh phong cách bối cảnh"),value:"",disabled:sa.length>=wi,onChange:h=>{const b=Ya.find(F=>F.id===h.target.value),E=b?.data;b&&E?.url&&Me(F=>({...F,styleRefs:[...(F.styleRefs||[]).filter(K=>K.nodeId!==b.id),{nodeId:b.id,url:E.url,name:E.label||"Location look"}].slice(0,wi)}))},children:[t.jsx("option",{value:"",children:o("+ Chọn ảnh trên canvas…")}),Ya.filter(h=>!sa.some(b=>b.nodeId===h.id)).map(h=>t.jsx("option",{value:h.id,children:String(h.data.label||"Image")},h.id))]})]}),sa.length>0&&t.jsx("div",{className:"shot-style-strip",children:sa.map(h=>t.jsxs("span",{children:[t.jsx("img",{src:h.url,alt:h.name}),t.jsx("button",{"aria-label":o("Bỏ {0}",[h.name]),onClick:()=>Me(b=>({...b,styleRefs:(b.styleRefs||[]).filter(E=>E.nodeId!==h.nodeId)})),children:"×"})]},h.nodeId))}),t.jsx("small",{className:"shot-hint",children:o("Khoá chất liệu, màu và đồ đạc của bối cảnh cho mọi shot khi tạo ảnh thật và video.")})]})}),Z==="shots"&&t.jsx("div",{className:"shot-shots-section",children:t.jsx("ol",{className:"shot-shotlist",children:z.shots.map((h,b)=>{const E=ul[b];return t.jsxs("li",{"data-shot":h.id,className:h.id===z.activeShot?"active":"",children:[t.jsxs("button",{className:"shot-shotlist-pick","aria-label":o("Chọn {0}",[h.name]),"aria-current":h.id===z.activeShot,disabled:!!A,onClick:()=>Me(F=>({...F,activeShot:h.id})),children:[mt[h.id]?t.jsx("img",{src:mt[h.id],alt:""}):t.jsx("span",{className:"shot-thumb-empty","aria-hidden":"true"}),t.jsxs("span",{className:"shot-shotlist-meta",children:[t.jsx("b",{children:h.name}),t.jsxs("small",{children:[ji(E.start),"–",ji(E.end)," · ",Number(h.lens.toFixed(1)),"mm"]}),h.note?.trim()&&t.jsx("small",{className:"shot-shotlist-note",children:h.note.trim()})]})]}),t.jsxs("span",{className:"shot-shotlist-order",children:[t.jsx("button",{"aria-label":o("Đưa {0} lên",[h.name]),disabled:b===0||!!A,onClick:()=>pl(h.id,-1),children:"↑"}),t.jsx("button",{"aria-label":o("Đưa {0} xuống",[h.name]),disabled:b===z.shots.length-1||!!A,onClick:()=>pl(h.id,1),children:"↓"})]}),t.jsx("button",{className:"shot-shotlist-delete","aria-label":o("Xóa {0}",[h.name]),title:z.shots.length<2?o("Cảnh cần ít nhất một shot"):o("Xóa {0} (hoàn tác bằng ⌘Z)",[h.name]),disabled:z.shots.length<2||!!A,onClick:()=>ml(h.id),children:t.jsx(Ce.trash,{})})]},h.id)})})}),Z==="notes"&&t.jsx("div",{className:"shot-notes-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("button",{className:oe?"active":"","aria-pressed":oe,disabled:!Te||Ls.length>=Ql,onClick:Ou,children:oe?o("Bấm vào cảnh để ghim… (bấm lại để huỷ)"):o("+ Ghim ghi chú vào cảnh")}),t.jsx("ol",{className:"shot-note-list",children:Ls.map((h,b)=>t.jsxs("li",{children:[t.jsx("span",{children:b+1}),t.jsx("input",{"aria-label":o("Ghi chú {0}",[b+1]),value:h.text,maxLength:Zl,onChange:E=>Du(h.id,E.target.value)}),t.jsx("button",{"aria-label":o("Xoá ghi chú {0}",[b+1]),onClick:()=>zu(h.id),children:"×"})]},h.id))}),Ls.length>0&&t.jsx("button",{disabled:H||!Te,onClick:()=>void Ju(),children:o("Tải PNG có ghi chú")}),t.jsx("small",{className:"shot-hint",children:o("Ghi chú gắn vào vị trí trong không gian 3D nên đúng chỗ ở mọi góc máy; chỉ hiện trong khung dựng, được đưa vào prompt và bản PNG có ghi chú.")})]})}),Z==="series"&&t.jsx("div",{className:"shot-series-section",children:t.jsx("div",{className:"shot-panel-body",children:t.jsx(L1,{stage:z,nodeId:e,selected:z.items.find(h=>h.id===J)||null,disabled:H||!!A,change:Me,onError:ce,onSelect:Xe})})})]}),t.jsx("div",{className:"shot-resize shot-resize-x",role:"separator","aria-orientation":"vertical","aria-label":o("Kéo để đổi độ rộng bảng công cụ"),onPointerDown:h=>ci(h,"drawer")})]}),t.jsxs("main",{className:"shot-center",children:[t.jsxs("div",{className:"shot-monitor",children:[t.jsxs("div",{className:`shot-topbar ${X?"":"collapsed"}`,children:[t.jsxs("div",{className:"shot-shot-switcher",children:[t.jsx("select",{"aria-label":o("Chọn shot"),value:fe.id,onChange:h=>Me(b=>({...b,activeShot:h.target.value})),children:z.shots.map(h=>t.jsx("option",{value:h.id,children:h.name},h.id))}),t.jsxs("button",{onClick:()=>{const h={...structuredClone(fe),id:bt(),name:`Shot ${z.shots.length+1}`};Me(b=>({...b,shots:[...b.shots,h],activeShot:h.id}))},children:[t.jsx(Ce.save,{}),t.jsx("span",{className:"lbl",children:o("+ Lưu góc mới").replace("+ ","")})]}),t.jsx(A1,{shot:fe,patch:yt,disabled:H||!!A})]}),t.jsxs("div",{className:"shot-viewtools",hidden:!X,children:[D==="scale"&&te&&!te.locked&&t.jsx(Hn,{label:"Tỷ lệ đồng đều",value:te.scale[0],min:.05,step:ue?.1:.05,onChange:h=>He(te.id,{scale:te.scale.map(b=>b*h/te.scale[0])})}),t.jsxs("span",{className:"shot-tools-hint",children:[D==="scale"?o("Kéo ô vuông trên trục để đổi kích thước."):"",ue?o(" Bước: 1 m · 15° · tỷ lệ 0,1"):""]}),["translate","rotate","scale"].map((h,b)=>t.jsxs("button",{className:h===D?"active":"",title:o(["Di chuyển","Xoay","Kích thước"][b]),onClick:()=>ee(h),children:[[t.jsx(Ce.move,{},"m"),t.jsx(Ce.rotate,{},"r"),t.jsx(Ce.scale,{},"s")][b],t.jsx("span",{className:"lbl",children:o(["Di chuyển","Xoay","Kích thước"][b])})]},h)),t.jsxs("button",{className:ue?"active":"",title:ue?o("Bám lưới: Bật"):o("Bám lưới: Tắt"),onClick:()=>Ee(!ue),children:[t.jsx(Ce.snap,{}),t.jsx("span",{className:"lbl",children:ue?o("Bám lưới: Bật"):o("Bám lưới: Tắt")})]}),t.jsxs("button",{className:ye==="high"?"active":"","aria-pressed":ye==="high",title:ye==="high"?o("Chất lượng cao: bóng mềm, AO, bloom. Bấm để chuyển sang Nháp (nhanh hơn). Xuất video/ảnh luôn dùng Chất lượng cao."):o("Nháp: nhanh, cho máy yếu. Bấm để bật Chất lượng cao. Xuất video/ảnh luôn dùng Chất lượng cao."),onClick:()=>ne(ye==="high"?"draft":"high"),children:[t.jsx(Ce.cinema,{}),t.jsx("span",{className:"lbl",children:ye==="high"?o("Chất lượng cao"):o("Nháp")})]}),t.jsxs("button",{className:Ie?"active":"","aria-pressed":Ie,title:Ie?o("Nhân vật người thật vẽ chất lượng cao (thân mượt, mặt, tóc, quần áo). Bấm để vẽ nhẹ hơn cho máy yếu. Người thường là mannequin; chọn nhân vật trong thư viện để thành người thật."):o("Máy yếu: nhân vật người thật vẽ bản nhẹ. Bấm để bật chất lượng cao."),onClick:()=>{const h=!Ie;Oy(h),ze(h)},children:[t.jsx(Ce.person,{}),t.jsx("span",{className:"lbl",children:Ie?o("Người thật"):o("Mannequin")})]}),t.jsxs("button",{title:o("Từ trên xuống"),onClick:()=>je.current?.view(!0),children:[t.jsx(Ce.top,{}),t.jsx("span",{className:"lbl",children:o("Từ trên xuống")})]}),t.jsxs("button",{title:o("Tập trung (F)"),"aria-keyshortcuts":"F",onClick:()=>je.current?.view(),children:[t.jsx(Ce.focus,{}),t.jsx("span",{className:"lbl",children:o("Tập trung")})]})]}),t.jsx("button",{className:"shot-tools-toggle","aria-expanded":X,title:X?o("Thu gọn công cụ"):o("Mở công cụ"),onClick:()=>{const h=!X;re(h);try{localStorage.setItem("clipoox.shot.tools",h?"1":"0")}catch{}},children:X?t.jsx(Ce.chevUp,{}):t.jsx(Ce.chevDown,{})})]}),t.jsx("div",{className:"shot-viewport",ref:lt,onDragOver:h=>{(h.dataTransfer.types.includes(gr)||h.dataTransfer.types.includes(Ao))&&(h.preventDefault(),h.dataTransfer.dropEffect="copy")},onDrop:h=>{h.dataTransfer.types.includes(Ao)?Pu(h):Fu(h)}}),t.jsx("span",{className:"shot-viewlabel",children:o("GÓC QUAN SÁT · không đổi camera xuất ảnh")}),te&&z1(te)&&!A&&(At===te.id?t.jsx(Jv,{engine:Te?je.current:null,stage:z,shot:fe,item:te,playhead:ke*fe.duration,change:Me,onDone:()=>qe(null)}):t.jsxs("button",{type:"button",className:"shot-pose-chip",title:o("Kéo trực tiếp các khớp trên nhân vật (đầu, ngực, khuỷu, tay, hông, gối, chân)"),onClick:()=>{$(!1),qe(te.id)},children:[t.jsx(Ce.person,{}),o("Chỉnh dáng")]})),te&&Z!==(Pa(te)?"mixfx":te.kind==="fx"?"fxedit":"objects")&&t.jsxs("button",{type:"button",className:"shot-edit-chip",onClick:()=>zn(Pa(te)?"mixfx":te.kind==="fx"?"fxedit":"objects"),children:[t.jsx(Ce.pen,{}),o("Chỉnh {0}",[te.name])]})]}),t.jsx("div",{className:"shot-resize shot-resize-y",role:"separator","aria-orientation":"horizontal","aria-label":o("Kéo để đổi chiều cao timeline"),onPointerDown:h=>ci(h,"timeline")}),t.jsx(Mx,{loop:u,onLoop:()=>m(h=>!h),range:d,rangeOn:p,onRangeOn:()=>x(h=>!h),onEnd:()=>{$(!1),Ue(1)},onKeyAll:xl,onCopy:bl,onPaste:yl,canPaste:v,onEase:Wu,onNudge:vl,stage:z,cameraActive:r,cameraHidden:C,cameraLocked:S,onToggle:Ku,onProp:Hu,height:pe.timeline,onHeight:h=>me(b=>({...b,timeline:h})),shot:fe,items:z.items,fxBars:$u,onParent:Bu,onFxTiming:(h,b)=>Me(E=>({...E,shots:E.shots.map(F=>F.id===E.activeShot?{...F,fxTiming:{...F.fxTiming,[h]:Ar({...Mn(E.items.find(K=>K.id===h),F),...b,off:!1},F.duration)}}:F)})),time:ke,playing:_,selected:y,picked:T,onPick:gl,onSeek:h=>{$(!1),Ue(h)},onPlay:()=>{!_&&ke>=1&&Ue(0),$(!_)},onRow:h=>{i(null),k(null),j([]),Xe(h==="camera"?null:h),l(h==="camera"&&!S);{const b=z.items.find(E=>E.id===h);Pa(b)?zn("mixfx"):b?.kind==="fx"&&zn("fxedit")}},onSelect:_u,onAdd:oi,onMove:Gu,onDelete:jl})]}),t.jsxs("aside",{className:"shot-right",children:[t.jsx("div",{className:"shot-resize shot-resize-x shot-resize-left",role:"separator","aria-orientation":"vertical","aria-label":o("Kéo để đổi độ rộng cột xem trước"),onPointerDown:h=>ci(h,"right")}),t.jsxs("section",{className:"shot-preview-pinned",children:[t.jsx("h3",{children:o("KHUNG CAMERA")}),t.jsx("div",{className:"shot-preview",style:{aspectRatio:Mi(fe.aspect).join(" / "),width:`min(100%, ${30*Mi(fe.aspect)[0]/Mi(fe.aspect)[1]}dvh)`},ref:vt}),t.jsxs("div",{className:"shot-camera-player",children:[t.jsx("button",{"aria-label":_?o("Tạm dừng camera"):o("Phát camera"),onClick:()=>{!_&&ke>=1&&Ue(0),$(!_)},children:o(_?"Ⅱ Pause":"▶ Play")}),t.jsx("button",{"aria-label":o("Về đầu"),onClick:()=>{$(!1),Ue(0)},children:"↤"}),t.jsxs("span",{children:[(ke*fe.duration).toFixed(1)," / ",fe.duration,o("s")]}),t.jsx("input",{"aria-label":o("Thời gian camera"),type:"range",min:0,max:1,step:1e-4,value:ke,onChange:h=>{$(!1),Ue(+h.target.value)}})]}),z.plate&&t.jsxs("div",{className:"shot-plate-row",title:o("Video quay thật phía sau camera: chỉ để canh hiệu ứng. Khi xuất VFX, hiệu ứng ra riêng trên nền đen."),children:[t.jsxs("span",{children:["🎬 ",z.plate.label]}),t.jsxs("label",{children:[t.jsx("input",{type:"checkbox","aria-label":o("Hiện video nền"),checked:!z.plate.hidden,onChange:h=>{const b=h.target.checked;Me(E=>E.plate?{...E,plate:{...E.plate,hidden:!b}}:E)}}),o("Hiện video nền")]})]}),z.plate&&t.jsxs("div",{className:"shot-plate-tools",children:[t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e||H,title:o("Người đứng thế đi theo người trong video (vị trí, khoảng cách, hướng, tay chân): hiệu ứng gắn vào nó sẽ bám theo người thật."),onClick:()=>void Yr("follow"),children:_e?.kind==="follow"?o("Đang đọc người… {0}%",[_e.pct]):o("🧍 Bám theo người")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e||H,title:o("Camera của cảnh xoay / lia / zoom giống camera đã quay video."),onClick:()=>void Yr("camera"),children:_e?.kind==="camera"?o("Đang track camera… {0}%",[_e.pct]):o("🎥 Lấy camera từ video")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!_e,title:o("Tải camera của shot thành script Python cho Blender, để dựng hiệu ứng khớp với video."),onClick:()=>void Su(),children:o("⬇ Camera cho Blender")})]}),we.length>0&&t.jsxs("div",{className:"shot-placement",role:"status","aria-label":o("Cảnh báo vị trí nhân vật"),children:[t.jsx("ul",{children:we.map(h=>t.jsxs("li",{children:[t.jsxs("span",{children:["⚠ ",h.type==="floating"?o("{0} lơ lửng {1} m so với mặt đỡ",[h.name,String(h.amount)]):h.type==="sinking"?o("{0} chìm {1} m dưới mặt đỡ",[h.name,String(h.amount)]):h.type==="no_seat"?h.seat?o("{0} ngồi lơ lửng — có thể ngồi lên “{1}”",[h.name,h.seat]):o("{0} ngồi mà không có chỗ ngồi gần",[h.name]):o("{0} đang xuyên vào {1}",[h.name,(h.with||[]).join(", ")])]}),h.fix&&!h.locked&&t.jsx("button",{onClick:()=>Gt([h]),children:h.type==="intersect"?o("Đẩy ra chỗ trống"):h.type==="no_seat"?o("Ngồi lên ghế gần nhất"):o("Đặt xuống mặt đỡ")})]},h.itemId+h.type))}),we.filter(h=>h.fix&&!h.locked).length>1&&t.jsx("button",{className:"shot-placement-all",onClick:()=>Gt(we),children:o("Sửa tất cả ({0})",[String(we.filter(h=>h.fix&&!h.locked).length)])})]}),dl.length>0&&t.jsx("ul",{className:"shot-warnings",role:"status","aria-label":o("Cảnh báo liền mạch"),children:dl.map(h=>t.jsxs("li",{children:["⚠ ",o(h)]},h))})]}),t.jsx("section",{className:"shot-agent-card",children:t.jsx(v1,{stage:z,disabled:H||L||!!A,lock:{playhead:Math.round(ke*fe.duration*rn(fe))/rn(fe),onChange:h=>yt({lockUntil:Pf(h,fe.duration)||void 0})},agent:{selected:J,time:ke,getBounds:()=>je.current?.objectBounds()||{},getColliders:()=>je.current?.placementColliders()||[],onPreview:(h,b)=>{$(!1);const E=Ti(Ae.current,h);O({stage:E,plan:h,time:ke,done:b}),Ue(Math.min(...h.tracks.map(F=>F.keys[0].seconds))/h.duration),$(!0)},onApply:h=>{$(!1),Me(b=>Ti(b,h)),Ue(0),i(null),k(null)}}})})]})]})]})}export{rj as default};
|