clipoox-render 0.4.5 → 0.4.6

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.
Files changed (115) hide show
  1. package/package.json +1 -1
  2. package/scripts/render-local.mjs +999 -779
  3. package/web/assets/{FxEmbed-DbfuM8Yo.js → FxEmbed-ROS6C_HI.js} +1 -1
  4. package/web/assets/{MotionEmbed-CBQ-8Tzh.js → MotionEmbed-E2hCysi-.js} +1 -1
  5. package/web/assets/{PluginStore-OOEx0lP5.js → PluginStore-CwUSpwPp.js} +1 -1
  6. package/web/assets/{ShotComposer-Cng515xa.js → ShotComposer-DLxWpdYH.js} +8 -8
  7. package/web/assets/{TemplateEmbed-hjwM2b0o.js → TemplateEmbed-qG1AXdtf.js} +1 -1
  8. package/web/assets/{TimelinePlugins-D-NakABP.js → TimelinePlugins-CB1b6-Cb.js} +3 -3
  9. package/web/assets/{TimelineShotFx-D3kGhHN3.js → TimelineShotFx-CyHTgJHj.js} +2 -2
  10. package/web/assets/{TransitionEmbed-DR26yI3a.js → TransitionEmbed-Dym9P7--.js} +1 -1
  11. package/web/assets/{Whiteboard-BhxY0D0Z.js → Whiteboard-BdGjJZXW.js} +1 -1
  12. package/web/assets/{aerial-BisYSXzG.js → aerial-yLD_gDzw.js} +2 -2
  13. package/web/assets/{agentTools-CPFQeiDP.js → agentTools-B7g6tXTR.js} +2 -2
  14. package/web/assets/{aiInbetween-AOOM1e6p.js → aiInbetween-6eKDYbYS.js} +2 -2
  15. package/web/assets/{analyzerRun-Dtp2o7gT.js → analyzerRun-Cr-_79RH.js} +1 -1
  16. package/web/assets/{analyzerSandbox-BG_3Cea1.js → analyzerSandbox-N92T6amg.js} +1 -1
  17. package/web/assets/{api-BFN7blbw.js → api-Dnl2uaKO.js} +3 -3
  18. package/web/assets/auraTrack-C8eAEIWQ.js +1 -0
  19. package/web/assets/{breakthrough-0qFpZW-V.js → breakthrough-DSiuVwEX.js} +2 -2
  20. package/web/assets/{cameraPresets-eK3mP7qb.js → cameraPresets-Cfn7qhXK.js} +1 -1
  21. package/web/assets/{cameraTracker-BAQHuTV-.js → cameraTracker-DHdF8Zqx.js} +5 -5
  22. package/web/assets/{captionLayout-CWPcbid-.js → captionLayout-cckQ7p-t.js} +1 -1
  23. package/web/assets/{clientExport-DvpTTndR.js → clientExport-pkLbOmEF.js} +1 -1
  24. package/web/assets/{clientJobs-CIrYTMpn.js → clientJobs-CcsLDqFM.js} +2 -2
  25. package/web/assets/{depthEstimate-B7D7cGCl.js → depthEstimate-Cav4MmQ1.js} +1 -1
  26. package/web/assets/{directorTools-CJD4Huqk.js → directorTools-DMsatulF.js} +1 -1
  27. package/web/assets/{distortFrames-BLt1icUb.js → distortFrames-D_v-aSVO.js} +2 -2
  28. package/web/assets/{distortGL-BA5molk-.js → distortGL-vhnBRB59.js} +1 -1
  29. package/web/assets/domino-DBrinEUu.js +1 -0
  30. package/web/assets/{editTools-NKLsWZD1.js → editTools-BNnAvCw-.js} +1 -1
  31. package/web/assets/{engine-DioUF2mX.js → engine-Co-ivzlQ.js} +1 -1
  32. package/web/assets/{exportGlb-BOdI9cVS.js → exportGlb-D3PrWUvi.js} +1 -1
  33. package/web/assets/{faceTracker-D7CbF-qX.js → faceTracker-ClR-lS6Y.js} +1 -1
  34. package/web/assets/fightDirector-BlpVAURl.js +1 -0
  35. package/web/assets/{fightDrama-DIPcRKnc.js → fightDrama-BK0QidpM.js} +2 -2
  36. package/web/assets/{focusTool-vfabPqQ5.js → focusTool-sVOb2GGS.js} +1 -1
  37. package/web/assets/{frameSink-DYs2gTzq.js → frameSink-CSRqCnwI.js} +3 -3
  38. package/web/assets/{glTransitionSources.generated-DM5sRMX2.js → glTransitionSources.generated-q0H-ZbnZ.js} +2 -2
  39. package/web/assets/{gpuCompose-DbnZuelB.js → gpuCompose-B5bgbHdQ.js} +1 -1
  40. package/web/assets/{gpuExport-CQ7ZhpsX.js → gpuExport-oA2mUsdm.js} +7 -7
  41. package/web/assets/{handMatte-DIbMuqCu.js → handMatte-Dj2taFoC.js} +1 -1
  42. package/web/assets/handTracker-c6_rvuwA.js +2 -0
  43. package/web/assets/i18n-C9zFX25m.js +3 -0
  44. package/web/assets/{index-BfrDwjDI.js → index-Ds_8isyf.js} +1 -1
  45. package/web/assets/{layer-worker-DK67WH1a.js → layer-worker-ClVZG6ZW.js} +3 -3
  46. package/web/assets/library-BK0QVG4O.js +1 -0
  47. package/web/assets/{lottieLayer-C2YbiXhK.js → lottieLayer-Cv8ub9f6.js} +1 -1
  48. package/web/assets/{main-B27kf5aL.css → main-B_MAOvi6.css} +1 -1
  49. package/web/assets/{main-BKatDoGw.js → main-CwrkBJ63.js} +104 -104
  50. package/web/assets/{mapBake-C-G7WpFM.js → mapBake-DtQboFIX.js} +1 -1
  51. package/web/assets/{maskTrack-LMrwm5ub.js → maskTrack-D4QZfMWc.js} +1 -1
  52. package/web/assets/{matteFixRun-B38CbeEt.js → matteFixRun-CytaeRzS.js} +1 -1
  53. package/web/assets/{objectLocate-CKi3OTnL.js → objectLocate-XuAcemlO.js} +1 -1
  54. package/web/assets/{objectSegmenter-CziPuM61.js → objectSegmenter-D66spD7o.js} +1 -1
  55. package/web/assets/{objectTrack.worker-b7DJ-ub6.js → objectTrack.worker-BZS6WZ6l.js} +547 -327
  56. package/web/assets/{pathTracer-bqau16sX.js → pathTracer-DykgPkkh.js} +2 -2
  57. package/web/assets/{pendingMatte-CQb7jPg1.js → pendingMatte-BWBIWajI.js} +2 -2
  58. package/web/assets/{personAi-CQntGDqK.js → personAi-EhBknW6X.js} +2 -2
  59. package/web/assets/{personHq-B1c0QVJT.js → personHq-Ca351o06.js} +2 -2
  60. package/web/assets/{plateCamera-D7iLiNBy.js → plateCamera-BcdXD1uI.js} +1 -1
  61. package/web/assets/{plateCameraMatch-BM88dx-a.js → plateCameraMatch-GPZl1fQQ.js} +2 -2
  62. package/web/assets/{plateFollow-4iGUDTu1.js → plateFollow-CJUilsNV.js} +2 -2
  63. package/web/assets/{plateMatte-zTyuHHqh.js → plateMatte-CoEoVjxZ.js} +2 -2
  64. package/web/assets/{pluginAutomation-DSg-sYLF.js → pluginAutomation-DAPHWZPN.js} +1 -1
  65. package/web/assets/{poseTracker-DZl8l2qS.js → poseTracker-CzEKvJph.js} +1 -1
  66. package/web/assets/{productTools-B-jh8ukh.js → productTools-ce-zyZO0.js} +2 -2
  67. package/web/assets/remote-8XzEAnAJ.js +974 -0
  68. package/web/assets/{rigTrack-XaMj1yaH.js → rigTrack-DMyqb0pb.js} +1 -1
  69. package/web/assets/{rotoMaskStore-DdpmT9C3.js → rotoMaskStore-pE1AIt3I.js} +1 -1
  70. package/web/assets/{rotoMatte-i-cJTYmK.js → rotoMatte-7b7Ow64f.js} +1 -1
  71. package/web/assets/{rotoscope-DqRSWmHR.js → rotoscope-BUqNTKLd.js} +1 -1
  72. package/web/assets/{sceneTrack-DIPzBmMK.js → sceneTrack-CA21MCOP.js} +1 -1
  73. package/web/assets/{sceneTrack-Bbov7zET.js → sceneTrack-DlAH5s74.js} +1 -1
  74. package/web/assets/{sceneTrack.worker-Bav9h0pv.js → sceneTrack.worker-COlhlHRe.js} +547 -327
  75. package/web/assets/{shot-worker-m-q77W9f.js → shot-worker-DL1ZoIym.js} +1 -1
  76. package/web/assets/{shotFxAgent-DIMS7BGA.js → shotFxAgent-DqngnGFb.js} +1 -1
  77. package/web/assets/{skin-DrUzJE1u.js → skin-xFScwS3T.js} +1 -1
  78. package/web/assets/{spark.module-Y1SEI8Xz.js → spark.module-DjaIF6J1.js} +1 -1
  79. package/web/assets/{spellDuel-DNnyQDVr.js → spellDuel-BYNtnE8f.js} +2 -2
  80. package/web/assets/{store-GFMJzaWS.js → store-CpqHUcA2.js} +1 -1
  81. package/web/assets/{surfaceLight-C--moyc9.js → surfaceLight-C7YI9SV8.js} +1 -1
  82. package/web/assets/{surfacePin-B4-1UqXD.js → surfacePin-CzpUj1Cw.js} +2 -2
  83. package/web/assets/{textAnimators-BVXTl8bU.js → textAnimators-B9vO_hbP.js} +1 -1
  84. package/web/assets/{thumb-CTfDJgLp.js → thumb-BTFsBS1u.js} +1 -1
  85. package/web/assets/{timeline3d-Dn7PqmEe.js → timeline3d-DrFaMPPB.js} +2 -2
  86. package/web/assets/{timeline3dExport-DCOr6ARB.js → timeline3dExport-Uo0S0CR0.js} +1 -1
  87. package/web/assets/{timelineComp-Dx_kED5V.js → timelineComp-i-zdaoB2.js} +1 -1
  88. package/web/assets/timelineOps-DSSaDsU2.js +525 -0
  89. package/web/assets/{timelineProps-eYgO6gs5.js → timelineProps-0v-s69pw.js} +1 -1
  90. package/web/assets/{timelineText-RKyRP988.js → timelineText-DurRhyuh.js} +1 -1
  91. package/web/assets/{titleArt-CUtA0C3I.js → titleArt-CnC0A7x7.js} +3 -3
  92. package/web/assets/{titleFrameBudget-X7HLSDre.js → titleFrameBudget-DsM0V482.js} +801 -581
  93. package/web/assets/{titleFrames-aMG7HdVe.js → titleFrames-C8kvflgT.js} +1 -1
  94. package/web/assets/{tool-DpFjybaq.js → tool-D1FpErrX.js} +1 -1
  95. package/web/assets/{tools-CeOU0p13.js → tools-DIvrRu-5.js} +1 -1
  96. package/web/assets/toonTools-D9MNdRty.js +2 -0
  97. package/web/assets/{trackAnchor-hAOtEhKO.js → trackAnchor-XvUuvkWP.js} +1 -1
  98. package/web/assets/{userFonts-1kuRjWOo.js → userFonts-Djka6RJX.js} +1 -1
  99. package/web/assets/{vfxAlpha-DxS5-QwY.js → vfxAlpha-B-JzzRI1.js} +1 -1
  100. package/web/assets/vfxBackground-b053ziDK.js +2 -0
  101. package/web/assets/{videoExport-Cg4B2Nyh.js → videoExport-NN-QijHd.js} +1 -1
  102. package/web/assets/{views-CUXyRb9x.js → views-RQBs4zva.js} +1 -1
  103. package/web/assets/{weaponDuel-nFECu9nk.js → weaponDuel-DKAEYJjO.js} +1 -1
  104. package/web/assets/{windowFrames-1wAkkWnv.js → windowFrames-DhhJLIs-.js} +1 -1
  105. package/web/layer-worker.html +3 -3
  106. package/web/shot-worker.html +23 -23
  107. package/web/assets/auraTrack-D_gxHNVe.js +0 -1
  108. package/web/assets/fightDirector-CYP8jxo8.js +0 -1
  109. package/web/assets/handTracker-DY_g5Xmg.js +0 -2
  110. package/web/assets/i18n-BJppIrtF.js +0 -3
  111. package/web/assets/library-B6KsZUKq.js +0 -1
  112. package/web/assets/remote-DJd9xWjn.js +0 -963
  113. package/web/assets/timelineOps-afzSo188.js +0 -525
  114. package/web/assets/toonTools-DLmo37Z_.js +0 -2
  115. package/web/assets/vfxBackground-CYpaQaTa.js +0 -2
@@ -1,6 +1,6 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/productTools-B-jh8ukh.js","assets/titleFrameBudget-X7HLSDre.js","assets/remote-DJd9xWjn.js","assets/index-CKtv7gGE.js","assets/i18n-BJppIrtF.js","assets/api-BFN7blbw.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/store-GFMJzaWS.js","assets/rotoMaskStore-DdpmT9C3.js","assets/sceneTrack-Bbov7zET.js","assets/timelineOps-afzSo188.js","assets/cameraTracker-BAQHuTV-.js","assets/textAnimators-BVXTl8bU.js","assets/timelineComp-Dx_kED5V.js","assets/rigTrack-XaMj1yaH.js","assets/clientJobs-CuuUyhEy.js","assets/exportGlb-BOdI9cVS.js","assets/aiInbetween-AOOM1e6p.js","assets/pathTracer-bqau16sX.js","assets/plateFollow-4iGUDTu1.js","assets/plateCamera-D7iLiNBy.js","assets/plateMatte-zTyuHHqh.js","assets/rotoMatte-i-cJTYmK.js","assets/videoExport-Cg4B2Nyh.js","assets/motionBlur-uAm030t9.js","assets/id3-arvEpAg7.js","assets/output-p-Q7qous.js"])))=>i.map(i=>d[i]);
2
- import{_ as fn}from"./titleFrameBudget-X7HLSDre.js";import{a1 as qa,a2 as nt,a3 as Ys,a4 as ps,a5 as Sm,a6 as Vh,a7 as Yh,a8 as gs,a9 as vt,aa as Kn,b as Mn,ab as Qh,ac as Cm,ad as Ol,ae as Lr,af as Wt,ag as Zh,ah as Nm,ai as Na,aj as Yo,ak as Am,al as Jh,am as Tm,j as t,an as Lm,ao as Po,ap as Em,aq as Im,ar as Rm,as as ed,at as Fm,au as Pm,av as Ka,aw as td,ax as Aa,ay as nd,az as $m,aA as _l,aB as Dm,aC as Om,aD as xi,aE as Ds,aF as Ha,aG as Qs,aH as Gs,aI as zl,aJ as Bl,aK as Kl,aL as sd,aM as _m,aN as Ta,aO as gn,I as Ne,N as Sn,R as Os,aP as bi,aQ as Hl,aR as Wl,aS as zm,aT as Gl,aU as Rn,aV as Bm,aW as Km,aX as Hm,aY as $o,aZ as Wm,a_ as ad,a$ as Wa,b0 as ql,b1 as Gm,b2 as No,b3 as od,b4 as qm,b5 as Um,b6 as Xm,b7 as Vm,b8 as Ym,b9 as Qm,ba as Do,bb as Zm,bc as Jm,bd as Ji,be as xn,bf as er,bg as tr,bh as ep,bi as Ul,bj as tp,bk as np,bl as sp,bm as ap,bn as ss,bo as Er,bp as op,bq as Xl,br as Qo,bs as id,bt as Ga,bu as ip,bv as rd,bw as ld,bx as yi,by as Wn,bz as Zs,bA as rp,bB as cd,bC as vi,bD as _s,bE as lp,bF as cp,bG as hd,bH as Ir,bI as hp,bJ as dp,bK as Rr,bL as Vl,bM as up,bN as mp,F as pp,bO as fp,a0 as gp,bP as xp,bQ as bp,bR as yp,bS as vp,bT as jp,bU as Fr,bV as dd,bW as kp,bX as so,bY as wp,bZ as Mp,b_ as Sp,b$ as Cp,c0 as Np,c1 as Ap,c2 as Tp,c3 as Lp,c4 as Ep,c5 as Yl,c6 as Ql,c7 as ji,c8 as Ip,c9 as Rp,ca as Fp,cb as ud,cc as md,cd as pd,ce as Oo,cf as Zl,cg as Pr,ch as Pp,ci as $p,cj as Dp,ck as Jl,cl as Op,cm as _n,cn as _p,co as zp,cp as ec,cq as da,cr as Ns,cs as Bp,ct as Kp,cu as Hp,cv as Wp,cw as Es,cx as Gp,cy as qp,cz as Up,cA as Xp,cB as Vp,cC as fd,cD as _o,cE as Yp,cF as tc,cG as Qp,cH as ki,cI as nc,cJ as wi,cK as Zp,cL as zo,cM as Jp,cN as ef,cO as tf,cP as us,cQ as Bo,r as gd,cR as nf,cS as sf,cT as af,cU as sc,cV as of,cW as rf,cX as $r,cY as Dr,cZ as La,c_ as lf,c$ as cf,d0 as hf,d1 as ao,d2 as Mi,d3 as nr,d4 as xd,d5 as df,d6 as Si,d7 as uf,d8 as mf,d9 as pf,da as ff,db as bd,dc as yd,a as _t,dd as gf,de as xf,df as bf,dg as yf,dh as vf,Q as jf,W as kf,X as wf,di as Mf,dj as Sf,dk as sr,dl as Cf,dm as Nf,dn as Af,dp as Tf,dq as Lf,dr as ac,ds as ar,dt as Fa,du as Ef,dv as Pa,dw as oc,dx as If,dy as Ko,dz as Ao,n as Rf,dA as Ff,u as Ci,dB as ic,dC as Pf,dD as $f,Y as rc,dE as Df,dF as lc,dG as Of,dH as _f,dI as zf,dJ as Bf,dK as Ni,q as Kf,dL as Hf,dM as Wf,dN as Gf,dO as Ai,dP as qf,dQ as Uf,dR as Xf,dS as Vf,dT as Yf,dU as Qf,dV as Zf,dW as Jf,dX as Ti,dY as e0,dZ as cc,d_ as t0,d$ as n0,e0 as hc,e1 as s0,e2 as a0,e3 as Li,e4 as dc,e5 as uc,e6 as Ei,e7 as o0,e8 as i0,e9 as r0,ea as l0,eb as Ii,ec as c0,ed as h0,ee as d0,ef as u0,eg as m0,eh as p0,ei as f0,ej as g0,ek as x0,el as b0,em as y0,en as v0,eo as j0,ep as k0,eq as w0,er as M0,es as S0,et as C0,eu as N0,ev as A0,ew as T0,ex as L0,ey as E0,ez as I0,eA as R0,eB as F0,eC as P0,eD as $0,eE as mc,eF as D0,eG as O0,eH as pc,eI as fc,eJ as _0}from"./remote-DJd9xWjn.js";import{u as ct,t as a,g as na}from"./i18n-BJppIrtF.js";import{r as R}from"./index-CKtv7gGE.js";import{Mesh as ut,SkinnedMesh as Or,Box3 as zt,Vector3 as oe,Matrix4 as At,Group as rn,Uint16BufferAttribute as vd,Float32BufferAttribute as Bt,BufferGeometry as Tt,BufferAttribute as Pt,MathUtils as zn,DirectionalLight as Zo,WebGLRenderer as _r,SRGBColorSpace as Jo,AgXToneMapping as jd,PCFSoftShadowMap as z0,Scene as zr,PMREMGenerator as kd,HemisphereLight as wd,PlaneGeometry as ei,ShadowMaterial as B0,PerspectiveCamera as Br,InstancedMesh as qs,DataTexture as K0,RGBAFormat as H0,RepeatWrapping as Md,LinearFilter as gc,CanvasTexture as Kr,NoColorSpace as Sd,LinearMipmapLinearFilter as Cd,InstancedBufferAttribute as or,DynamicDrawUsage as sa,MeshStandardMaterial as ns,ShaderMaterial as Ua,Color as Ue,DoubleSide as ys,AdditiveBlending as Hr,LinearSRGBColorSpace as xs,CapsuleGeometry as Nd,ConeGeometry as W0,CylinderGeometry as vs,TorusGeometry as Wr,SphereGeometry as Hn,BoxGeometry as Xa,MeshPhysicalMaterial as Ps,Vector2 as ra,LatheGeometry as Ad,FrontSide as Va,Quaternion as Qe,Vector4 as Is,InstancedInterleavedBuffer as Td,InterleavedBufferAttribute as En,InstancedBufferGeometry as G0,OneMinusSrcAlphaFactor as q0,OneFactor as U0,AddEquation as X0,CustomBlending as V0,NormalBlending as Y0,DetachedBindMode as Q0,OctahedronGeometry as ir,MeshBasicMaterial as fs,Line as Ri,LineBasicMaterial as xc,PointLight as Z0,Euler as rr,Bone as $a,Uint8BufferAttribute as bs,ShaderChunk as J0,Sphere as eg,LOD as tg,Skeleton as Fi,Object3D as ng,NearestFilter as sg,ACESFilmicToneMapping as ag,CircleGeometry as og,Raycaster as bc}from"./three.module-Bx43vjkH.js";import{bu as ig,u as Us,bv as yc,bw as rg,bx as lg,by as cg,bz as hg,bA as dg,bB as ug,bC as mg,bD as pg,bE as fg,bF as gg,ap as xg,bG as bg,bH as vc,Z as yg,s as vg}from"./api-BFN7blbw.js";import{R as Ld}from"./RoomEnvironment-Dmv_G5ka.js";import{i as jc,p as kc,g as jg,e as kg}from"./tool-DpFjybaq.js";import{rowProps as wg,rowKeyed as Mg,readProp as Sg,writeProp as Cg,keyAllAt as Ng,copyKeys as Ag,pasteKeys as Tg,easeKeys as Lg,nudgeKeys as wc}from"./timelineProps-eYgO6gs5.js";import{b as Eg,c as Ig,A as Rg,d as Mc,a as Fg,t as Pg}from"./thumb-CTfDJgLp.js";import{f as $g,p as Dg}from"./shotFxAgent-DIMS7BGA.js";import{a as Ed}from"./gltfLoader-U0Eebg7v.js";import{p as Og,C as _g,a as zg,b as Bg,c as Sc}from"./cameraPresets-eK3mP7qb.js";import{m as Kg}from"./rigTrack-XaMj1yaH.js";import{D as Hg,s as Wg}from"./weaponDuel-nFECu9nk.js";import{u as dt}from"./store-GFMJzaWS.js";import{r as Cc,a as Gg,b as qg,o as Ug,w as Xg,c as Vg,d as Yg,e as Pi,f as Qg,g as Zg,p as Jg,h as ex}from"./skin-DrUzJE1u.js";import{renderRigViews as tx}from"./views-CUXyRb9x.js";import{M as ua}from"./motionBlur-uAm030t9.js";import{o as nx}from"./timelineOps-afzSo188.js";import{fitLibraryFingers as Nc}from"./library-B6KsZUKq.js";import"./rotoMaskStore-DdpmT9C3.js";import"./sceneTrack-Bbov7zET.js";import"./cameraTracker-BAQHuTV-.js";import"./textAnimators-BVXTl8bU.js";import"./timelineComp-Dx_kED5V.js";import"./clientJobs-CuuUyhEy.js";function sx(e,n,s){const o=[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:o,h:i,min:o.map((r,l)=>r-i[l]),max:o.map((r,l)=>r+i[l])}}function ax(e,{cell:n=1}={}){const s=e.length,o=Array.from({length:s},()=>[]),i=Array.from({length:s},()=>[]),r=e.reduce((k,C)=>Math.min(k,C.min[1]),1/0),l=e.reduce((k,C)=>Math.max(k,C.max[1]),-1/0),h=Math.max(.03,n*.2),u=Math.max(.02,n*.06),m=e.map(k=>k.min[1]<=r+h);for(let k=0;k<s;k++){const C=e[k],S=(C.min[1]+C.max[1])/2,I=(C.max[1]-C.min[1])/2;for(let j=k+1;j<s;j++){const M=e[j],T=[0,1,2].map(A=>Math.min(C.max[A],M.max[A])-Math.max(C.min[A],M.min[A]));if(T[0]<-u||T[2]<-u||T[1]<-h)continue;const w=(M.min[1]+M.max[1])/2,E=(M.max[1]-M.min[1])/2,N=w-S;if(Math.abs(N)>.3*(I+E)){const A=N>0?M:C,O=H=>T[H]/Math.max(.001,A.max[H]-A.min[H]);if(O(0)<.45||O(2)<.45)continue;N>0?o[k].push(j):o[j].push(k)}else i[k].push(j),i[j].push(k)}}const d=new Uint8Array(s).fill(1);let f=lr({ups:o,side:i,ground:m},d,null);const p=Math.max(.05,n*.25);for(let k=0;k<3;k++){let C=!1;for(let S=0;S<s;S++){if(Number.isFinite(f[S]))continue;const I=e[S],j=(I.min[1]+I.max[1])/2,M=(I.max[1]-I.min[1])/2;for(let T=0;T<s;T++){if(T===S||i[S].includes(T)||o[S].includes(T)||o[T].includes(S))continue;const w=e[T];if(![0,1,2].every(A=>Math.min(I.max[A],w.max[A])-Math.max(I.min[A],w.min[A])>=-p))continue;const E=(w.min[1]+w.max[1])/2-j,N=(w.max[1]-w.min[1])/2;Math.abs(E)>.3*(M+N)?E>0?o[S].push(T):o[T].push(S):(i[S].push(T),i[T].push(S)),C=!0}}if(!C)break;f=lr({ups:o,side:i,ground:m},d,null)}const b=e.map(k=>[k.min[0],k.max[0],k.min[2],k.max[2]]),g=e.map(k=>[(k.min[0]+k.max[0])/2,(k.min[2]+k.max[2])/2]),v={n:s,ups:o,side:i,ground:m,need0:f,base:r,top:l,foot:b,plan:g,cell:n,tops:e.map(k=>k.max[1]),slender0:0},y=[...Array(s).keys()].filter(k=>Number.isFinite(f[k]));return v.slender0=y.length?Fd(v,y):0,v.stable0=ix(v,d,0),v}function ox(e,n){if(!e.adj){e.adj=Array.from({length:e.n},(s,o)=>[...e.ups[o],...e.side[o]]);for(let s=0;s<e.n;s++)for(const o of e.ups[s])e.adj[o].push(s)}return e.adj[n]}function Id(e,n){const s=new Int32Array(e.n).fill(-1),o=[];for(let i=0;i<e.n;i++){if(!n[i]||s[i]>=0)continue;const r=[i];s[i]=o.length;for(let l=0;l<r.length;l++)for(const h of ox(e,r[l]))n[h]&&s[h]<0&&(s[h]=o.length,r.push(h));o.push(r)}return o}function Rd(e,n){let s=1/0,o=-1/0,i=1/0,r=-1/0,l=0;for(const h of n){if(!e.ground[h])continue;l++;const u=e.foot[h];s=Math.min(s,u[0]),o=Math.max(o,u[1]),i=Math.min(i,u[2]),r=Math.max(r,u[3])}return{x0:s,x1:o,z0:i,z1:r,ng:l}}function Fd(e,n){const s=Rd(e,n),o=(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*o):0}function Pd(e,n,s,o){const i=Rd(e,n),r=i.ng;if(!r||n.length-r<2)return!0;let l=0,h=0;for(const m of n)l+=e.plan[m][0],h+=e.plan[m][1];l/=n.length,h/=n.length;const u=(e.cell??1)*.5*(1+s);return l<i.x0-u||l>i.x1+u||h<i.z0-u||h>i.z1+u||e.tops&&Fd(e,n)>Math.max(4,2*(e.slender0??0))*(1+.25*s)?!1:r/n.length>=o*(.3/(1+s))}function $d(e){let n=0,s=0;for(let o=0;o<e.n;o++)Number.isFinite(e.need0[o])&&(s++,e.ground[o]&&n++);return s?n/s:0}function ix(e,n,s){const o=$d(e);return Id(e,n).every(i=>Pd(e,i,s,o))}function lr(e,n,s){const o=n.length,i=new Float64Array(o).fill(1/0),r=[];for(let l=0;l<o;l++)n[l]&&e.ground[l]&&(i[l]=0,r.push(l));for(let l=0;l<r.length;l++){const h=r[l],u=i[h],m=u+1;for(const d of e.ups[h])n[d]&&i[d]>0&&(i[d]=0,r.push(d));for(const d of e.side[h])n[d]&&i[d]>m&&(!s||m<=s[d])&&(i[d]=m,r.push(d))}return i}const rx=e=>e>=.8?0:e>=.4?1:2;function lx(e,n,{slack:s=0,seed:o=1,centres:i}={}){const r=e.n,l=new Array(r).fill(null),h=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=qa(o|0,7717,5),f=[],p=e.stable0!==!1&&!!e.foot,b=p?$d(e):0;for(let v=0;v<r;v++)Number.isFinite(n[v])&&f.push({t:n[v],i:v});f.sort((v,y)=>v.t-y.t||v.i-y.i);let g=0;for(;g<f.length;){const v=f[g].t,y=[];for(;g<f.length&&f[g].t<=v+1e-9;){const S=f[g++];h[S.i]&&(h[S.i]=0,y.push(S.i))}if(!y.length)continue;const k=lr(e,h,u),C=i?nt.mul(y.reduce((S,I)=>nt.add(S,i[I]),[0,0,0]),1/y.length):null;for(let S=0;S<r;S++){if(!h[S]||!Number.isFinite(e.need0[S])||k[S]<=u[S])continue;h[S]=0;const I=i?Ys((i[S][1]-e.base)/m):.5,j=v+.05+.13*I+.07*ps(d,S,1);l[S]={t:j,from:C}}if(p){for(const S of Id(e,h))if(!Pd(e,S,s,b))for(const I of S){if(e.ground[I])continue;h[I]=0;const j=i?Ys((i[I][1]-e.base)/m):.5;l[I]={t:v+.08+.15*j+.07*ps(d,I,1),from:C}}}}return l}function cx(e,n,{base:s=0,cell:o=1}={}){const i=Math.max(.05,o*.25),r=new Map,l=(d,f)=>`${d},${f}`,h=(d,f,p,b,g)=>{const v=[];for(let y=Math.floor((d-p*g)/i);y<=Math.floor((d+p*g)/i);y++)for(let k=Math.floor((f-b*g)/i);k<=Math.floor((f+b*g)/i);k++)v.push(l(y,k));return v};for(const d of n)for(const f of h(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,o*.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 b of d.dirs??[[1,0,0]])for(let g=0;g<=8;g++){const v=d.x+b[0]*m*g,y=d.z+b[2]*m*g,k=h(v,y,d.hx,d.hz,.6),C=k.reduce((I,j)=>Math.max(I,r.get(j)??s),s),S=C+.45*m*g;(!p||S<p.score-1e-9)&&(p={x:v,z:y,y:Math.min(d.top,C+f),foot:k,score:S})}u.set(d.i,{x:p.x,z:p.z,y:p.y});for(const b of p.foot)r.set(b,Math.max(r.get(b)??s,p.y+f*.9))}return u}function hx(e,n,s,{gravity:o=9.8,seed:i=1,crumble:r=.6}={}){if(!e||!(s>=e.t))return null;const l=s-e.t,h=Math.max(.5,o),u=Math.max(0,e.p0[1]-e.land),m=Math.sqrt(2*u/h),d=Math.min(l,m),f=m>1e-6?d/m:1,p=Sm(u,0,h,l,.12),b=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*b,v=e.p0[2]+(e.to[1]-e.p0[2])*f+e.dir[2]*.4*b,y=qa(i|0,n,4441),k=(.25+.9*ps(y,1,1))*(.4+.6*r),C=nt.norm([e.dir[2]+(ps(y,2,1)-.5)*.3,0,-e.dir[0]+(ps(y,3,1)-.5)*.3]),S=k*Vh(0,1,f)+(l>m?.15*k*b:0);return{pos:[g,e.land+p.y,v],axis:Number.isFinite(C[0])?C:[1,0,0],angle:S,landed:l>=m}}function dx(e,n,s,{base:o=0,cell:i=1,seed:r=1,centre:l=null}={}){const h=qa(r|0,3301,7),u=[],m=n.map((f,p)=>{if(!f)return null;const b=e[p],g=f.from??b.c,v=[g[0]-b.c[0],0,g[2]-b.c[2]],y=Math.hypot(v[0],v[2]),k=ps(h,p,1)*Math.PI*2,C=(ps(h,p,2)-.5)*.9,S=y>1e-4?nt.norm([v[0]/y+Math.cos(k)*.25,0,v[2]/y+Math.sin(k)*.25]):[Math.cos(k),0,Math.sin(k)],I=l?[b.c[0]-l[0],0,b.c[2]-l[2]]:[Math.cos(k+1),0,Math.sin(k+1)],j=Math.hypot(I[0],I[2]),M=j>1e-4?[I[0]/j,0,I[2]/j]:[Math.cos(k+1),0,Math.sin(k+1)],T=(w,E)=>[w[0]*Math.cos(E)-w[2]*Math.sin(E),0,w[0]*Math.sin(E)+w[2]*Math.cos(E)];return u.push({i:p,t:f.t,x:b.c[0],z:b.c[2],hx:b.h[0],hz:b.h[2],hy:Math.min(b.h[1],Math.max(b.h[0],b.h[2])*1.2),top:b.c[1],dirs:[S,T(M,C),T(M,C+.8),T(M,C-.8)]}),{t:f.t,p0:[...b.c],dir:S,to:[b.c[0],b.c[2]],land:o,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 cx(u,d,{base:o,cell:i}))m[f]&&(m[f].land=p.y,m[f].to=[p.x,p.z]);return m}function ux(e,{mode:n="pancake",start:s=0,duration:o=4,yaw:i=0,crumble:r=.6,seed:l=1,cell:h=1,gone:u=null,gravity:m=9.8}={}){const d=e.reduce((w,E)=>Math.min(w,E.min[1]),1/0),f=e.reduce((w,E)=>Math.max(w,E.max[1]),-1/0),p=Math.max(.3,o),b=Math.max(.1,f-d),g=.17+.13*(1-r),v=[0,2].map(w=>e.reduce((E,N)=>Math.min(E,N.min[w]),1/0)),y=[0,2].map(w=>e.reduce((E,N)=>Math.max(E,N.max[w]),-1/0)),k=[(v[0]+y[0])/2,d,(v[1]+y[1])/2],C=i*Math.PI/180,S=[Math.sin(C),0,Math.cos(C)],I=e.reduce((w,E)=>Math.max(w,...[0,1].flatMap(N=>[0,1].map(A=>(N?E.max[0]:E.min[0])*S[0]+(A?E.max[2]:E.min[2])*S[2]))),-1/0)-(k[0]*S[0]+k[2]*S[2]),j=[k[0]+S[0]*I,d,k[2]+S[2]*I],M=[S[2],0,-S[0]],T={mode:px.has(n)?n:"pancake",t0:s,D:p,base:d,top:f,H:b,c:g,centre:k,pivot:j,dir:S,axis:M,ext:I,seed:l|0,crumble:r,cell:h};if(T.mode==="pancake"){const w=.008333333333333333,E=Math.max(.5,m),N=Math.max(.3,h),A=Math.max(.3,h*1.5),O=e.map($=>`${Math.floor($.c[0]/A)},${Math.floor($.c[2]/A)}`),H=new Map;e.forEach(($,W)=>{const z=O[W];H.has(z)||H.set(z,[]),H.get(z).push(W)});const D=new Map;for(const[$,W]of H){const z=[f];let Y=f,J=0;for(let V=1;Y>d&&V<7200;V++){const K=s+V*w,G=Ys((K-s)/p),_=b*1.6*Math.pow(Math.max(G,.02),.6)/p;J=W.some(Q=>e[Q].c[1]<=Y&&e[Q].c[1]>=Y-N&&!(u&&u[Q]<=K))?Math.max(_,J+E*.6*w):J+E*w,Y=Math.max(d,Y-J*w),z.push(Y)}D.set($,z)}T.fronts=D,T.colOf=O,T.dt=w,T.starts=e.map(($,W)=>{const z=D.get(O[W]),Y=z.findIndex(J=>J<$.c[1]);return s+(Y<0?z.length:Y)*w})}else T.starts=e.map(()=>s);return T}const mx=(e,n,s)=>{const o=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>=o.length-1?o[o.length-1]:o[r]+(o[r+1]-o[r])*(i-r)},px=new Set(["pancake","topple","base"]),fx=(e,n,s)=>{const o=Math.cos(s),i=Math.sin(s),r=nt.dot(n,e),l=nt.cross(n,e);return[e[0]*o+l[0]*i+n[0]*r*(1-o),e[1]*o+l[1]*i+n[1]*r*(1-o),e[2]*o+l[2]*i+n[2]*r*(1-o)]};function Ac(e,n,s,o){if(!e||!(o>=e.starts[s]))return null;const i=qa(e.seed,s,6067),r=g=>ps(i,g,1),l=Ys((o-e.t0)/e.D),h=e.crumble,u=e.base+Math.min(n.h[1],Math.max(n.h[0],n.h[2]))*.55,m=nt.norm([n.c[0]-e.centre[0]+(r(1)-.5)*.6,0,n.c[2]-e.centre[2]+(r(2)-.5)*.6]),d=nt.norm([r(3)-.5,(r(4)-.5)*.4,r(5)-.5]);if(e.mode==="topple"){const g=Math.PI/2*l*l,v=nt.sub(n.c,e.pivot),y=nt.add(e.pivot,fx(v,e.axis,g)),k=Math.max(0,o-(e.t0+e.D)),C=(1-Math.exp(-2.5*k))/2.5,S=Vh(.55,1,l),I=h*e.cell*(.4+1.2*r(6)),j=nt.add(nt.mul(e.dir,(.8+2.2*r(7))*h*C*2),nt.mul(m,I*S*.5+h*C*r(8))),M=nt.add(y,j);return M[1]=Math.max(u,M[1]),{pos:M,axis:e.axis,angle:g,extra:{axis:d,angle:h*(S*.6+C*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=Ys((g-v)/Math.max(.2,e.cell*2)))}else{const g=mx(e,s,o),v=n.c[1];f=g>=v?v:g+(v-g)*e.c;const y=e.base+(v-e.base)*e.c;p=v-y>1e-6?Ys((v-f)/(v-y)):1}f=Math.max(u,f);const b=(.15+1.1*h)*e.cell*(.5+r(10))*p;return{pos:[n.c[0]+m[0]*b,f,n.c[2]+m[2]*b],axis:d,angle:p*(.15+1.1*h)*(.3+r(11))}}function gx(e,{blasts:n=[],collapses:s=[],falls:o=[]}={}){const i=new Array(e).fill(null),r=(l,h)=>{(!i[l]||h.t<i[l].t-1e-9||Math.abs(h.t-i[l].t)<=1e-9&&Tc[h.kind]<Tc[i[l].kind])&&(i[l]=h)};for(const l of n)for(let h=0;h<e;h++){const u=l.hits[h];u&&r(h,{kind:"hit",e:l.e,t:u.t})}for(let l=0;l<e;l++)o[l]&&r(l,{kind:"fall",e:-1,t:o[l].t});for(const l of s)for(let h=0;h<e;h++)r(h,{kind:"collapse",e:l.e,t:l.plan.starts[h]});return i}const Tc={hit:0,fall:1,collapse:2};function xx(e,n){const s=new Float64Array(e).fill(1/0);for(const o of n)for(let i=0;i<e;i++){const r=o.hits[i];r&&r.t<s[i]&&(s[i]=r.t)}return s}function bx(e){const n=Math.floor(e.length/3);if(n<4)return null;const s=j=>[e[j*3],e[j*3+1],e[j*3+2]];let o=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let j=0;j<n;j++)for(let M=0;M<3;M++)o[M]=Math.min(o[M],e[j*3+M]),i[M]=Math.max(i[M],e[j*3+M]);const r=Math.max(1e-9,...i.map((j,M)=>j-o[M])),l=r*1e-7;let h=0;for(let j=1;j<n;j++)e[j*3]<e[h*3]&&(h=j);let u=-1,m=0;for(let j=0;j<n;j++){const M=nt.dist(s(j),s(h));M>m+l&&(m=M,u=j)}if(u<0)return null;let d=-1,f=0;const p=nt.sub(s(u),s(h));for(let j=0;j<n;j++){const M=nt.len(nt.cross(p,nt.sub(s(j),s(h))));M>f+l*r&&(f=M,d=j)}if(d<0)return null;const b=nt.cross(p,nt.sub(s(d),s(h)));let g=-1,v=0;for(let j=0;j<n;j++){const M=Math.abs(nt.dot(b,nt.sub(s(j),s(h))));M>v+l*r*r&&(v=M,g=j)}if(g<0||v<l*r*r*10)return null;const y=[],k=(j,M,T)=>{const w=nt.cross(nt.sub(s(M),s(j)),nt.sub(s(T),s(j))),E=nt.len(w)||1,N=nt.mul(w,1/E);return{v:[j,M,T],n:N,d:nt.dot(N,s(j)),alive:!0}},C=nt.mul(nt.add(nt.add(s(h),s(u)),nt.add(s(d),s(g))),.25);for(const[j,M,T]of[[h,u,d],[h,u,g],[h,d,g],[u,d,g]]){let w=k(j,M,T);nt.dot(w.n,C)-w.d>0&&(w=k(j,T,M)),y.push(w)}const S=new Set([h,u,d,g]);for(let j=0;j<n;j++){if(S.has(j))continue;const M=s(j),T=[];for(const E of y)E.alive&&nt.dot(E.n,M)-E.d>l&&T.push(E);if(!T.length)continue;const w=new Map;for(const E of T){E.alive=!1;for(let N=0;N<3;N++){const A=E.v[N],O=E.v[(N+1)%3],H=`${O},${A}`;w.has(H)?w.delete(H):w.set(`${A},${O}`,[A,O])}}for(const[E,N]of w.values())y.push(k(E,N,j))}const I=[];for(const j of y)j.alive&&I.push(...j.v);return I.length?I:null}function yx(e,n,s,o=48){const i=Math.floor(e.length/3),r=Math.max(1,Math.ceil(i/o)),l=[],h=nt.norm(n),u=nt.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]+h[0]*u,d[1]+h[1]*u,d[2]+h[2]*u)}return l}const zs=e=>Array.isArray(e)&&e.length===3&&e.every(n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=1e6),jn=e=>{throw new Error(e)};function vx(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))&&jn("Đề xuất AI không hợp lệ."),(!Number.isFinite(e.duration)||e.duration<n.duration||e.duration>1e7)&&jn("Thời lượng đề xuất không hợp lệ.");for(const o of e.additions||[])(!o||o.kind!=="box"||typeof o.id!="string"||!/^agent-block-[a-zA-Z0-9_-]{1,96}$/.test(o.id)||n.items.some(i=>i.id===o.id)||!zs(o.position)||!zs(o.scale)||o.scale.some(i=>i<.1||i>100)||typeof o.name!="string"||o.name.length>80)&&jn("Khối Agent không hợp lệ.");const s=new Set;for(const o of e.tracks){s.has(o.subjectId)&&jn("AI trả về track trùng lặp."),s.add(o.subjectId);const i=n.items.find(l=>l.id===o.subjectId);if(o.subjectId!=="camera"&&(!i||i.locked)&&jn("Đối tượng không tồn tại hoặc đã khóa."),(!Array.isArray(o.keys)||!o.keys.length||o.keys.length>200)&&jn("Số key không hợp lệ."),o.replaceRange!=null){const l=o.replaceRange;(!Number.isFinite(l.start)||!Number.isFinite(l.end)||l.start<0||l.end<=l.start||l.end>e.duration||o.keys[0].seconds!==l.start||o.keys.at(-1).seconds!==l.end)&&jn("Đoạn sửa phải có key ở cả hai đầu."),o.keys.some(h=>h.seconds<l.start||h.seconds>l.end)&&jn("Key nằm ngoài đoạn sửa.")}let r=-1;for(const l of o.keys)(!Number.isFinite(l.seconds)||l.seconds<0||l.seconds>e.duration||l.seconds<=r||!zs(l.position))&&jn("Thời điểm hoặc vị trí key không hợp lệ."),r=l.seconds,o.subjectId==="camera"?(!zs(l.target)||!Number.isFinite(l.lens)||l.lens<14||l.lens>200||!Number.isFinite(l.roll)||Math.abs(l.roll)>36e3||l.position.every((h,u)=>Math.abs(h-l.target[u])<1e-8))&&jn("Thông số camera không hợp lệ."):(!zs(l.rotation)||!zs(l.scale)||l.scale.some(h=>h<.01||h>1e3))&&jn("Góc xoay hoặc kích thước không hợp lệ."),l.pose!==void 0&&!["Ngồi","Đứng"].includes(l.pose)&&jn("Tư thế key không hợp lệ.")}return e}function Lc(e,n,s,o={},i=[]){const r=e.shots.find(h=>h.id===e.activeShot),l=Yh(r,s);return{placement:{camera:r.position,colliders:i.slice(0,400).map(h=>({id:h.id,itemId:h.itemId,name:h.name,kind:h.kind,min:h.min.map(u=>Math.round(u*1e3)/1e3),max:h.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(h=>({...h,seconds:h.time*r.duration}))||[]},items:e.items.map(h=>{const u=gs(h,r,s),m=o[h.id],d=[...r.objectKeys?.[h.id]||[]].sort((b,g)=>b.time-g.time),f=d.slice(1).map((b,g)=>{const v=d[g],y=(b.time-v.time)*r.duration,k=Math.hypot(...b.position.map((C,S)=>C-v.position[S]));return{start:v.time*r.duration,end:b.time*r.duration,distance:k,speed:y>0?k/y:null}}),p=Object.entries(o).filter(([b])=>b!==h.id).map(([b,g])=>{const v=m?u.position[0]-m.min[0]:.5,y=m?m.max[0]-u.position[0]:.5,k=m?u.position[2]-m.min[2]:.5,C=m?m.max[2]-u.position[2]:.5,S=(g.min[0]+g.max[0])/2,I=(g.min[2]+g.max[2])/2,j=[[g.min[0]-y-.3,u.position[1],I],[g.max[0]+v+.3,u.position[1],I],[S,u.position[1],g.min[2]-C-.3],[S,u.position[1],g.max[2]+k+.3]];return{targetId:b,worldAxisPoints:j,nearest:j.reduce((M,T)=>Math.hypot(T[0]-u.position[0],T[2]-u.position[2])<Math.hypot(M[0]-u.position[0],M[2]-u.position[2])?T:M)}});return{motionProfile:m?.motionProfile||null,segments:f,bounds:m||null,approachPoints:p.slice(0,6),baseTransform:{position:h.position,rotation:h.rotation,scale:h.scale},...h.kind==="person"?{pose:{hipL:h.pose.hipL,hipR:h.pose.hipR,kneeL:h.pose.kneeL,kneeR:h.pose.kneeR,lean:h.pose.lean},...h.figure?{figure:h.figure}:{}}:{},...h.kind==="set"&&h.set?{set:{id:h.set.id}}:{},id:h.id,name:h.name,kind:h.kind,locked:h.locked,hidden:h.hidden,position:u.position,rotation:u.rotation,scale:u.scale,keys:r.objectKeys?.[h.id]?.map(b=>({...b,seconds:b.time*r.duration}))||[]}})}}function $i(e,n){const s=e.shots.find(l=>l.id===e.activeShot);vx(n,{duration:s.duration,items:e.items});const o=s.duration/n.duration,i={...s,duration:n.duration,objectKeys:Object.fromEntries(Object.entries(s.objectKeys||{}).map(([l,h])=>[l,h.map(u=>({...u,time:u.time*o}))])),cameraKeys:s.cameraKeys?.map(l=>({...l,time:l.time*o})),...s.focus?.keys?{focus:{...s.focus,keys:s.focus.keys.map(l=>({...l,time:Math.min(1,l.time*o)}))}}:{}};for(const l of n.tracks){const h=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:vt(),time:f.seconds/n.duration,position:f.position,target:f.target,lens:f.lens,roll:f.roll}));i.cameraKeys=[...(i.cameraKeys||[]).filter(f=>h(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:vt(),time:m.seconds/n.duration,position:m.position,rotation:m.rotation,scale:m.scale,...m.stance?{stance:m.stance}:{},...m.pose&&Kn[m.pose]?{pose:{...Kn[m.pose]}}:{}}));i.objectKeys[l.subjectId]=[...(i.objectKeys[l.subjectId]||[]).filter(m=>h(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,h)=>({...Mn("box",e.items.length+h),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 Da=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}}),Ls=Object.freeze({width:[.85,1.2],length:[.85,1.2],eyes:[.7,1.4]}),Ec=e=>!!e&&typeof e=="object"&&!Array.isArray(e),jx=/^#[0-9a-fA-F]{6}$/,rs=(e,n)=>{throw Object.assign(new Error(`${e}: ${n}`),{status:400})};function To(e={}){Ec(e)||rs("character","object");for(const u of Object.keys(e))["preset","figure","look","face","color"].includes(u)||rs("character",`unknown field "${u}"`);const n=e.preset!=null?Qh(String(e.preset)):null;e.preset!=null&&!n&&rs("character.preset","unknown character preset");const s={height:1.75,face:"simple",...n?.figure??{},...e.figure!=null?Cm(e.figure,"character.figure"):{}},o=Ol({...n?.look??{},...e.look!=null?Ol(e.look,"character.look"):{}},"character.look");e.color!==void 0&&!(typeof e.color=="string"&&jx.test(e.color))&&rs("character.color","#rrggbb");const i=(e.color??s.skin??n?.color??Lr[2]).toLowerCase();s.skin||(s.skin=i);const r=e.face??{};Ec(r)||rs("character.face","object");for(const u of Object.keys(r))["preset","width","length","eyes"].includes(u)||rs("character.face",`unknown field "${u}"`);r.preset!==void 0&&!Da[r.preset]&&rs("character.face.preset",Object.keys(Da).join("|"));const l=Da[r.preset??"oval"],h={preset:r.preset??"oval"};for(const[u,[m,d]]of Object.entries(Ls)){const f=r[u]===void 0?l[u]:r[u];(typeof f!="number"||!Number.isFinite(f))&&rs(`character.face.${u}`,`number ${m}..${d}`),h[u]=+Math.min(d,Math.max(m,f)).toFixed(3)}return{...n?{preset:n.id}:{},figure:s,look:o,color:i,face:h}}function kx(e){const n=JSON.stringify(e);let s=2166136261;for(let o=0;o<n.length;o++)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}const wx=e=>`gen:character:${kx(e)}`,cr={torso:"torso",head:"head",eyes:"head",eyeL:"head",eyeR:"head"};for(const e of["L","R"])Object.assign(cr,{[`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 Mx(){return{...Object.fromEntries(Object.entries(Kn.Đứ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 Sx(e){const n=Wt({height:1.8,head:1,build:1,...e.figure}),s=Zh(Mx(),e.color,n,e.look);s.scale.setScalar(n.height/Nm(n));const o=s.getObjectByName("head"),i=s.getObjectByName("eyes");o&&o.scale.set(o.scale.x*e.face.width,o.scale.y*e.face.length,o.scale.z*(e.face.width+1)/2),i&&i.scale.setScalar(e.face.eyes),s.updateMatrixWorld(!0);const r=M=>{for(let T=M;T;T=T.parent)if(cr[T.name])return cr[T.name];return"torso"},l=M=>s.getObjectByName(M).getWorldPosition(new oe),h=[];s.traverse(M=>{if(!(M instanceof ut)||!M.visible||!M.geometry.getAttribute("position"))return;let T=!1;for(let E=M;E;E=E.parent)E.visible||(T=!0);if(T)return;if(M instanceof Or){h.push(Nx(M));return}const w=M.geometry.clone();w.morphAttributes={};for(const E of Object.keys(w.attributes))E!=="position"&&E!=="normal"&&E!=="uv"&&w.deleteAttribute(E);w.applyMatrix4(M.matrixWorld),h.push({geo:w,material:M.material,joint:r(M),name:M.name||r(M)})});const u=new zt,m=new Map;for(const M of h){if(M.geo.computeBoundingBox(),u.union(M.geo.boundingBox),M.weights){const w=M.geo.getAttribute("position"),E=new oe;for(let N=0;N<w.count;N++){const A=Na[M.weights.index[N*4]][0],O=m.get(A)??new zt;O.expandByPoint(E.fromBufferAttribute(w,N)),m.set(A,O)}continue}const T=m.get(M.joint)??new zt;T.union(M.geo.boundingBox),m.set(M.joint,T)}const d={};for(const[M]of Na)s.getObjectByName(M)&&(d[M]=l(M));d.headTop=new oe(d.head.x,m.get("head").max.y,d.head.z);for(const M of["L","R"]){const T=m.get(`wrist${M}`)??new zt().setFromCenterAndSize(d[`wrist${M}`],new oe(.05,.2,.05));d[`handTip${M}`]=new oe(d[`wrist${M}`].x,T.min.y,d[`wrist${M}`].z);const w=m.get(`foot${M}`)??new zt().setFromCenterAndSize(d[`foot${M}`],new oe(.1,.1,.25));d[`toe${M}`]=new oe(d[`foot${M}`].x,w.min.y,w.max.z)}const f=u.getSize(new oe),p=2/Math.max(f.x,f.y,f.z),b=u.getCenter(new oe),g=new At().makeScale(p,p,p).multiply(new At().makeTranslation(-b.x,-u.min.y,-b.z)),v=M=>Math.round(M*1e4)/1e4,y=Na.map(([M,T])=>({name:M,parent:T,pos:d[M].clone().applyMatrix4(g).toArray().map(v)})),k=Yo({kind:"humanoid",source:"template",joints:y,seed:1}),C=new Map(k.joints.map((M,T)=>[M.name,T])),S=Am(k),I=new rn;let j=0;for(const M of h){M.geo.applyMatrix4(g);const T=M.geo.getAttribute("position").count,w=C.get(M.joint)??0,E=new Uint16Array(T*4),N=new Float32Array(T*4);if(M.weights)for(let O=0;O<T*4;O++)E[O]=C.get(Na[M.weights.index[O]][0])??0,N[O]=M.weights.weight[O];else for(let O=0;O<T;O++)E[O*4]=w,N[O*4]=1;M.geo.setAttribute("skinIndex",new vd(E,4)),M.geo.setAttribute("skinWeight",new Bt(N,4)),M.geo.userData.rigWeights=S,M.geo.computeBoundingBox(),M.geo.computeBoundingSphere();const A=new ut(M.geo,M.material);A.name=M.name,A.castShadow=!0,A.receiveShadow=!0,I.add(A),j+=T}return I.userData.normalizedHeight=f.y*p,{root:I,rig:k,normalizedHeight:f.y*p,height:+f.y.toFixed(4),vertices:j}}const Dd=new Map(Na.map(([e],n)=>[e,n]));function Cx(e){if(Dd.has(e))return[[e,1]];const n=/^(arm|fore|wrist|thigh|shin|foot)Half([LR])$/.exec(e);if(n){const o={arm:"torso",fore:"arm",wrist:"fore",thigh:"torso",shin:"thigh",foot:"shin"},i=o[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 Nx(e){const n=e.geometry,s=n.getAttribute("position").count,o=new Float32Array(s*3),i=new oe,r=n.getAttribute("skinIndex"),l=n.getAttribute("skinWeight"),h=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),o[f*3]=i.x,o[f*3+1]=i.y,o[f*3+2]=i.z;const p=new Map;for(let v=0;v<4;v++){const y=l.getComponent(f,v);if(y)for(const[k,C]of Cx(h[r.getComponent(f,v)]??"torso")){const S=Dd.get(k)??0;p.set(S,(p.get(S)??0)+y*C)}}const b=[...p].sort((v,y)=>y[1]-v[1]).slice(0,4),g=b.reduce((v,y)=>v+y[1],0)||1;b.forEach(([v,y],k)=>{u[f*4+k]=v,m[f*4+k]=y/g})}const d=new Tt;return d.setAttribute("position",new Pt(o,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 Hs=new Map;function Od(e){const n=JSON.stringify(e);let s=Hs.get(n);if(!s)for(s=Sx(e),Hs.set(n,s);Hs.size>16;)Hs.delete(Hs.keys().next().value);return s}function _d(){Hs.clear()}const Ic=e=>Array.isArray(e)&&e.length===3&&e.every(n=>Number.isFinite(Number(n)))?e.map(Number):null;function Di(e,n){const s=e.getStage(),o=String(n.name||"Nhân vật").trim().slice(0,60)||"Nhân vật",i=s.items.find(f=>f.name===o&&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]])),b=n.face;r=To(n.preset!=null||!f?{...n.preset!=null?{preset:n.preset}:{},...p}:{figure:{...f.figure,...n.figure||{}},look:{...f.look,...n.look||{}},face:b?.preset?b:{...f.face,...b||{}},color:n.color??f.color})}catch(f){return{ok:!1,error:f.message}}const l=Od(r),h=l.height,u={model:{gcsUri:wx(r),name:`${o}.character`,height:h},gen:{kind:"character",spec:r},rig:l.rig,color:r.color,...Ic(n.position)?{position:Ic(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=Jh(s,{kind:"model",name:o,...u});m=f.id,e.setStage(p=>({...p,items:[...p.items,f]}))}const d=l.rig.joints.filter(f=>!Tm(l.rig.joints,f)).map(f=>f.name);return{ok:!0,name:o,id:m,rebuilt:!!i,height_m:h,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 Ax=[{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}],Tx=[{key:"width",vi:"Mặt rộng",lo:Ls.width[0],hi:Ls.width[1],step:.01},{key:"length",vi:"Mặt dài",lo:Ls.length[0],hi:Ls.length[1],step:.01},{key:"eyes",vi:"Mắt to",lo:Ls.eyes[0],hi:Ls.eyes[1],step:.01}];function Lx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=ct(),l=C=>r==="en"?C.en:C.vi,[h,u]=R.useState(()=>To({preset:"office-f"})),m=(n?.gen?.kind==="character"?n.gen.spec:null)??h,d=R.useRef(void 0),f=C=>{let S;try{S=To({figure:{...m.figure,...C.figure||{}},look:C.look??m.look,face:{...m.face,...C.face||{}},color:C.color??m.color})}catch(I){i(I.message);return}if(!n){u(S);return}window.clearTimeout(d.current),d.current=window.setTimeout(()=>{const I=Di(e,{name:n.name,figure:S.figure,look:S.look,face:S.face,color:S.color});I.ok||i(String(I.error))},250)},p=C=>{if(!Qh(C))return;if(!n){u(To({preset:C}));return}const I=Di(e,{name:n.name,preset:C});I.ok||i(String(I.error))},b=()=>{const C=Di(e,{name:Ex(e,a("Nhân vật")),figure:m.figure,look:m.look,face:m.face,color:m.color,position:s()});C.ok&&C.id?o(C.id):i(String(C.error))},g=m.figure,v=(C,S,I)=>t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(C.vi)}),t.jsx("input",{type:"range","aria-label":a(C.vi),min:C.lo,max:C.hi,step:C.step,value:S,onChange:j=>I(+j.target.value)}),t.jsx("input",{type:"number","aria-label":`${a(C.vi)} (${a("số")})`,min:C.lo,max:C.hi,step:C.step,value:S,onChange:j=>{const M=+j.target.value;Number.isFinite(M)&&I(Math.min(C.hi,Math.max(C.lo,M)))}})]},C.key),y=m.look,k=(C,S,I,j)=>{const M=y[C];return t.jsxs("div",{className:"shot-char-piece",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(j)}),t.jsxs("select",{"aria-label":a(j),value:M?String(M[I]):"",onChange:T=>{const w=T.target.value,E={...m.look};w?E[C]={...M||{color:C==="hair"?"#2a211b":"#4a6fa5"},[I]:w}:delete E[C],f({look:E})},children:[t.jsx("option",{value:"",children:a("Không")}),Object.entries(S).map(([T,w])=>t.jsx("option",{value:T,children:l(w)},T))]})]}),M&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Màu {0}",[a(j).toLowerCase()])}),t.jsx("input",{type:"color","aria-label":a("Màu {0}",[a(j).toLowerCase()]),value:M.color,onChange:T=>f({look:{...m.look,[C]:{...M,color:T.target.value}}})})]})]},C)};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:a("Nhân vật mới")]}),t.jsx("small",{className:"muted",children:n?a("Đang sửa: thay đổi dựng lại ngay, đã gắn xương người."):a("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:a("Mẫu nhân vật")}),t.jsxs("select",{"aria-label":a("Mẫu nhân vật"),value:m.preset??"",onChange:C=>p(C.target.value),children:[t.jsx("option",{value:"",children:a("Tự chỉnh")}),Lm.map(C=>t.jsx("option",{value:C.id,children:l(C.name)},C.id))]})]}),t.jsx("h4",{children:a("Dáng người")}),Ax.map(C=>v(C,Number(g[C.key]??(C.key==="height"?1.75:C.key==="shoulders"||C.key==="hips"?1:C.key==="sex"?+Po(g).fem.toFixed(2):C.key==="age"?Po(g).age:0)),S=>f({figure:{[C.key]:S}}))),t.jsx("div",{className:"shot-char-skins",role:"group","aria-label":a("Màu da"),children:Lr.map(C=>t.jsx("button",{type:"button","aria-label":C,"aria-pressed":m.color===C,className:m.color===C?"on":"",style:{background:C},onClick:()=>f({color:C,figure:{skin:C}})},C))}),t.jsx("h4",{children:a("Khuôn mặt")}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Kiểu mặt")}),t.jsx("select",{"aria-label":a("Kiểu mặt"),value:m.face.preset,onChange:C=>{const S=Da[C.target.value];f({face:{preset:C.target.value,width:S.width,length:S.length,eyes:S.eyes}})},children:Object.entries(Da).map(([C,S])=>t.jsx("option",{value:C,children:l(S)},C))})]}),Tx.map(C=>v(C,m.face[C.key],S=>f({face:{[C.key]:S}}))),t.jsx("h4",{children:a("Tóc & trang phục")}),k("hair",Em,"style","Tóc"),k("top",Im,"type","Áo"),k("bottom",Rm,"type","Quần / váy"),!n&&t.jsx("button",{className:"pill-btn primary",onClick:b,children:a("+ Tạo nhân vật (đã gắn xương)")}),n&&t.jsx("small",{className:"muted",children:a("Mở tab Rigging để xoay xương, hoặc dùng thư viện chuyển động như với ma-nơ-canh.")})]})}function Ex(e,n){const s=e.getStage();let o=n,i=2;for(;s.items.some(r=>r.name===o);)o=`${n} ${i++}`;return o}let kn=null,Bn,ds,Rc=null,Xs;const Fc=new Map,Oi=new Map;let Pc=Promise.resolve(),$c=0;const Dc=160,Oc=120;function Ix(){if(kn)return kn;kn=new _r({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),kn.outputColorSpace=Jo,kn.toneMapping=jd,kn.toneMappingExposure=1.15,kn.shadowMap.enabled=!0,kn.shadowMap.type=z0,kn.setClearColor(0,0),kn.setSize(Dc,Oc,!1),Bn=new zr;const e=new kd(kn);Rc=e.fromScene(new Ld,.04).texture,e.dispose(),Bn.environment=Rc,Bn.environmentIntensity=.7,Bn.add(new wd("#e8eeff","#5d5a55",.9));const n=new Zo("#fff4e4",2.4);return n.castShadow=!0,n.shadow.mapSize.set(512,512),n.shadow.bias=-4e-4,Bn.add(n,n.target),Xs=new ut(new ei(1,1),new B0({opacity:.32})),Xs.rotation.x=-Math.PI/2,Xs.receiveShadow=!0,Bn.add(Xs),ds=new Br(28,Dc/Oc,.05,2e3),kn}function Rx(e){const n=new zt,s=new At;return e.updateMatrixWorld(!0),e.traverse(o=>{if(o instanceof qs){const i=o.geometry.boundingBox??(o.geometry.computeBoundingBox(),o.geometry.boundingBox);for(let r=0;r<o.count;r++)o.getMatrixAt(r,s),n.union(i.clone().applyMatrix4(s).applyMatrix4(o.matrixWorld))}else o instanceof ut&&n.union(new zt().setFromObject(o))}),n}function Fx(e){const n=Ix(),s=Fm(Pm(e).recipe);Bn.add(s);try{const o=Rx(s);if(o.isEmpty())throw new Error(`empty model ${e}`);const i=o.getSize(new oe),r=o.getCenter(new oe),l=Math.max(.05,i.length()/2),h=zn.degToRad(ds.fov)/2,u=l/Math.sin(h)*.98,m=new oe(.62,.42,1).normalize();ds.position.copy(r).addScaledVector(m,u),ds.near=u/100,ds.far=u*4,ds.updateProjectionMatrix(),ds.lookAt(r),Xs.position.set(r.x,o.min.y+.001,r.z),Xs.scale.setScalar(l*6);const d=Bn.children.find(p=>p instanceof Zo);d.position.copy(r).add(new oe(-.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(Bn,ds),n.domElement.toDataURL("image/png")}finally{Bn.remove(s),s.traverse(o=>{o instanceof ut&&(o.geometry.dispose(),o.material.dispose())})}}function Px(e){const n=Fc.get(e);if(n)return Promise.resolve(n);const s=Oi.get(e);if(s)return s;if(!ed(e))return Promise.reject(new Error(`unknown model kit ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&$c>=o)return Promise.reject(new Error("thumbnail limit"));$c++;const i=Pc.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=Fx(e);Fc.set(e,h),r(h)}catch(h){l(h)}},16))).finally(()=>Oi.delete(e));return Pc=i.catch(()=>{}),Oi.set(e,i),i}const Ea="claude-opus-5-5",_c=e=>`${Math.round(e/1e3).toLocaleString("vi-VN")}k đ`;function oo({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:a("Ướ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),_c(e.vnd.low),_c(e.vnd.high),Ka])}):t.jsx("small",{className:"shot-hq-quote",children:a("Đang ước tính chi phí…")})}const zc=[["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 $x({host:e,item:n,onSelect:s,setError:o}){ct();const i=td(),[r,l]=R.useState(""),[h,u]=R.useState(""),[m,d]=R.useState("real"),[f,p]=R.useState(null),[b,g]=R.useState(null),[v,y]=R.useState(null),[k,C]=R.useState(""),[S,I]=R.useState(""),[j,M]=R.useState(!1),T=R.useRef(void 0),w=jc(n)&&n.gen?.kind==="code"?n.gen:null,E=["thinking","acting","rendering"].includes(i.phase),N=i.purpose==="model"&&(i.log.length>0||E),A=[...e.getStage().items].reverse().find(V=>jc(V));R.useEffect(()=>{g(null),y(null),C("")},[n?.id]);const O=async V=>{C("");try{g(await ig(Ea,V)),y(V)}catch(K){C(K.message)}},H=async V=>{if(!V){p(null);return}if(V.size>28e4||!["image/jpeg","image/png"].includes(V.type)){o(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const K=await new Promise((G,_)=>{const ee=new FileReader;ee.onload=()=>G(String(ee.result)),ee.onerror=()=>_(ee.error),ee.readAsDataURL(V)});p({name:V.name,data:K})},D=()=>{const V=r.trim();if(!V||E)return;const K=zc.find(_=>_[0]===m),G=`${V}
3
- Style: ${K[2]}.${h.trim()?` Real size: ${h.trim()}.`:""}${f?" Match the attached reference photo.":""}`;i.start(G,f?.data||null,Ea,"model",{quality:"high"}),g(null),y(null)},$=()=>{const V=S.trim();if(!V||!w||E)return;const K=`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===Ea&&i.quality==="high"?i.followUp(K):i.start(K,null,Ea,"model",{quality:"high"}),I(""),g(null),y(null)},W=(V,K)=>{if(!w||!n)return;const G={...w.code.params,[V]:K};e.setStage(_=>({..._,items:_.items.map(ee=>ee.id===n.id&&ee.gen?.kind==="code"?{...ee,gen:{...ee.gen,code:{...ee.gen.code,params:G}}}:ee)})),window.clearTimeout(T.current),T.current=window.setTimeout(()=>{kc(e,{name:n.name,params:G,views:!1}).then(_=>{_.ok||o(String(_.error))})},250)},z=async()=>{if(!(!w||!n)){M(!0);try{const V=await kc(e,{name:n.name,seed:w.code.seed%2147483e3+1,views:!1});V.ok||o(String(V.error))}finally{M(!1)}}},Y=async()=>{if(!(!w||!n)){M(!0);try{const V=await jg(w.code),K=URL.createObjectURL(V),G=document.createElement("a");G.href=K,G.download=`${n.name.replace(/[^\p{L}\p{N}_-]+/gu,"_")||"model"}.glb`,G.click(),window.setTimeout(()=>URL.revokeObjectURL(K),4e3)}catch(V){o(V.message)}finally{M(!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:a("Chất lượng cao · Opus")}),E?a("Đang dựng…"):i.phase==="capped"?a("Đã dùng hết {0} credit của lượt này",[Ka]):i.phase==="done"?a("Xong"):i.phase==="error"?a("Lỗi"):i.phase==="cancelled"?a("Đã dừng"):""," · ",a("bước")," ",i.step," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-6).map((V,K)=>t.jsx("div",{className:"shot-mission-line",children:V},K)),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:a('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).',[Ka])}),i.error&&t.jsx("p",{role:"alert",children:i.error}),E&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>i.stop(),children:a("Dừng")}),!E&&!w&&A&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(A.id),children:a("Chỉnh model vừa dựng: {0}",[A.name])})]});return w&&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:a("Model dựng bằng code · Opus")})]}),w.prompt&&t.jsx("small",{className:"muted shot-hq-prompt",children:w.prompt}),(w.schema||[]).length>0?t.jsx("div",{className:"shot-model-params",children:(w.schema||[]).map(V=>t.jsx(Dx,{p:V,value:w.code.params[V.key]??V.default,onChange:K=>W(V.key,K)},V.key))}):t.jsx("small",{className:"muted",children:a("Model này không có thanh trượt tham số.")}),t.jsx("small",{className:"muted",children:a("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:j,onClick:()=>void z(),children:a("Biến thể khác (0 credit)")}),t.jsx("button",{type:"button",className:"pill-btn thin",disabled:j,onClick:()=>void Y(),children:a("Tải .glb")})]}),t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:a("Sửa bằng lời (AI · Opus)")}),t.jsx("textarea",{rows:3,maxLength:1500,value:S,disabled:E,placeholder:a("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"&&b?t.jsx(oo,{quote:b}):k?t.jsx(oo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:E||!S.trim(),onClick:()=>void O("edit"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:E||!S.trim()||v!=="edit",title:v!=="edit"?a("Xem ước tính chi phí trước"):"",onClick:$,children:a("Sửa (≈ {0}–{1} cr)",[b?.credits.low.toFixed(1)??"?",b?.credits.high.toFixed(1)??"?"])})]}),J,t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(null),children:a("+ 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:a("Mô tả model")}),t.jsx("textarea",{rows:4,maxLength:3e3,value:r,disabled:E,placeholder:a("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:a("Kích thước thật (tuỳ chọn)")}),t.jsx("input",{value:h,maxLength:80,disabled:E,placeholder:a("vd: cao 12 cm"),onChange:V=>u(V.target.value)})]}),t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:a("Phong cách")}),t.jsx("select",{value:m,disabled:E,onChange:V=>d(V.target.value),children:zc.map(([V,K])=>t.jsx("option",{value:V,children:a(K)},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:E,onChange:V=>{H(V.target.files?.[0]),V.target.value=""}}),t.jsx("span",{children:f?`🖼 ${f.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),f&&!E&&t.jsx("button",{type:"button",onClick:()=>p(null),children:"×"})]}),v==="build"&&b?t.jsx(oo,{quote:b}):k?t.jsx(oo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:E||!r.trim(),onClick:()=>void O("build"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:E||!r.trim()||v!=="build",title:v!=="build"?a("Xem ước tính chi phí trước"):"",onClick:D,children:a("Dựng (≈ {0}–{1} cr)",[b?.credits.low.toFixed(1)??"?",b?.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:o=>s(Number(o.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:o=>s(o.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:o=>s(o.target.value),children:e.options.map(o=>t.jsx("option",{value:o,children:o},o))})]}):t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"color",value:String(n),onChange:o=>s(o.target.value)}),t.jsx("output",{children:String(n)})]})}function Ox({host:e,item:n,ground:s,onSelect:o,setError:i}){ct();const[r,l]=R.useState("Sản phẩm"),[h,u]=R.useState(""),[m,d]=R.useState(null),[f,p]=R.useState(null),[b,g]=R.useState([]),[v,y]=R.useState(""),[k,C]=R.useState(null),S=async(N,A)=>{if(N){if(!/^image\/(png|jpeg|webp)$/.test(N.type)){i(a("Ảnh phải là PNG, JPG hoặc WEBP."));return}y(a("Đang tải ảnh lên…"));try{const O=await Us(N,void 0,"image");A({name:N.name,url:O.url})}catch(O){i(O.message)}finally{y("")}}},I=N=>Number(String(N).replace(",","."))/100,j=async()=>{if(!m){i(a("Chọn ảnh chính diện của sản phẩm."));return}if(!(I(h)>0)){i(a("Nhập chiều cao thật của sản phẩm (cm)."));return}y(a("Đang dựng sản phẩm…")),C(null);try{const{modelProduct:N}=await fn(async()=>{const{modelProduct:O}=await import("./productTools-B-jh8ukh.js");return{modelProduct:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),A=await N({image:m.url,...f?{back_image:f.url}:{},height_m:I(h),name:r.trim()||"Sản phẩm",position:s(),labels:b.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&&o(String(A.id)):i(String(A.error))}finally{y("")}},M=async()=>{if(n){y(a("Đang xuất GLB…"));try{const{saveGlb:N}=await fn(async()=>{const{saveGlb:O}=await import("./productTools-B-jh8ukh.js");return{saveGlb:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),A=await N({name:n.name},e);A.ok?C({file:String(A.file),url:String(A.url)}):i(String(A.error))}finally{y("")}}},T=async()=>{if(n?.set){y(a("Đang xuất GLB…"));try{const{recipeGlb:N}=await fn(async()=>{const{recipeGlb:W}=await import("./exportGlb-BOdI9cVS.js");return{recipeGlb:W}},__vite__mapDeps([17,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),{loadSetOf:A}=await fn(async()=>{const{loadSetOf:W}=await import("./remote-DJd9xWjn.js").then(z=>z.fO);return{loadSetOf:W}},__vite__mapDeps([2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16])),O=e.engine()?.setRecipe(n.set.id)??await A(e)(n.set.id),H=await N(O),D=document.createElement("a"),$=URL.createObjectURL(H);D.href=$,D.download=`${n.name}.glb`,D.click(),setTimeout(()=>URL.revokeObjectURL($),5e3)}catch(N){i(N.message)}finally{y("")}}},w=(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:H=>void S(H.target.files?.[0],O)}),A?t.jsx("img",{src:A.url,alt:""}):t.jsx("em",{children:a("Chưa chọn")})]}),E=(N,A)=>g(O=>O.map(H=>H.key===N?{...H,...A}:H));return t.jsxs("div",{className:"shot-product",children:[t.jsx("p",{className:"shot-product-hint",children:a("Ả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:a("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:a("Chiều cao thật (cm)")}),t.jsx("input",{inputMode:"decimal",value:h,placeholder:"29",onChange:N=>u(N.target.value)})]}),w(a("Ảnh chính diện"),m,d),w(a("Ảnh mặt sau (không bắt buộc)"),f,p),t.jsxs("div",{className:"shot-product-labels",children:[t.jsx("b",{children:a("File thiết kế nhãn / bao bì")}),b.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&&E(N.key,{url:O.url,name:O.name}))}),t.jsxs("label",{children:[a("Đáy nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.bottom,onChange:A=>E(N.key,{bottom:A.target.value})})]}),t.jsxs("label",{children:[a("Cao nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.height,onChange:A=>E(N.key,{height:A.target.value})})]}),t.jsxs("label",{children:[a("Mặt"),t.jsxs("select",{value:N.side,onChange:A=>E(N.key,{side:A.target.value}),children:[t.jsx("option",{value:"0",children:a("Trước")}),t.jsx("option",{value:"180",children:a("Sau")})]})]}),t.jsxs("label",{children:[a("Bề mặt"),t.jsxs("select",{value:N.finish,onChange:A=>E(N.key,{finish:A.target.value}),children:[t.jsx("option",{value:"matte",children:a("Giấy mờ")}),t.jsx("option",{value:"gloss",children:a("Bóng")}),t.jsx("option",{value:"foil",children:a("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:["+ ",a("Thêm nhãn")]})]}),t.jsx("button",{type:"button",className:"shot-product-build",disabled:!!v,onClick:()=>void j(),children:a("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 M(),children:a("Lưu GLB vào Tài sản của tôi")}),t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void T(),children:a("Tải .glb")}),k&&t.jsxs("span",{children:[a("Đã lưu")," ",k.file]})]}),v&&t.jsx("p",{className:"shot-product-busy",children:v})]})}function zd(){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 Bc={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"]},_x=[.01,.05,.1,.25,.5],zx={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 Bx(e){const{stage:n,selected:s}=e,o=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,h]=R.useState(r?"ai":i?"character":o?.set?.kit?.id===Aa?"hand":"library");R.useEffect(()=>{o?.set?.kit&&h(o.set.kit.id===Aa?"hand":"library")},[o?.id,o?.set?.kit?.id]),R.useEffect(()=>{i&&h("character")},[i?.id]),R.useEffect(()=>{r&&h("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":a("Dựng model"),children:[t.jsx("div",{className:"shot-model-tabs",role:"tablist",children:["library","hand",...nd()||i?["character"]:[],"product"].map(m=>t.jsx("button",{role:"tab","aria-selected":l===m,className:l===m?"on":"",onClick:()=>h(m),children:m==="library"?a("Thư viện model"):m==="hand"?a("Dựng tay"):m==="character"?a("Nhân vật"):a("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:()=>h("ai"),children:["✦ ",a("AI chất lượng cao")]}),l==="library"?t.jsx(Kx,{...e,host:u,item:o?.set?.kit&&o.set.kit.id!==Aa?o:void 0}):l==="hand"?t.jsx(Vx,{...e,item:o?.set?.kit?.id===Aa?o:void 0}):l==="character"?t.jsx(Lx,{host:u,item:i,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):l==="product"?t.jsx(Ox,{host:u,item:o,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):t.jsx($x,{host:u,item:r,ground:e.ground,onSelect:e.onSelect,setError:e.setError}),o&&l!=="character"&&l!=="ai"&&l!=="product"&&t.jsx(Gx,{item:o,change:e.change})]})}function Kx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=ct(),l=w=>r==="en"?w.en:w.vi,[h,u]=R.useState("all"),[m,d]=R.useState(""),[f,p]=R.useState(null),[b,g]=R.useState({}),[v,y]=R.useState(!1),k=n?.set?.kit,C=ed(k?.id??f??""),S=k?k.params:b,I=R.useRef(void 0),j=(w,E)=>{if(!C)return;const N={...S,[w]:E};if(!k){g(N);return}window.clearTimeout(I.current),I.current=window.setTimeout(()=>{zl(e,{kit:C.id,params:N,name:n.name}).then(A=>{A.ok||i(String(A.error))})},280)},M=async()=>{if(C){y(!0);try{const w=await zl(e,{kit:C.id,params:b,name:Kd(e.getStage(),l(C)),position:s()});w.ok?o(String(w.id)):i(String(w.error))}catch(w){i(w.message)}finally{y(!1)}}},T=R.useMemo(()=>$m(m,h),[m,h]);return C?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:()=>{k&&o(null),p(null)},children:["← ",a("Thư viện")]}),t.jsx(Kc,{id:C.id,alt:l(C),small:!0}),t.jsx("strong",{children:l(C)}),k&&t.jsx("small",{className:"muted",children:a("Đang sửa: {0}",[n.name])})]}),t.jsx("div",{className:"shot-model-params",children:C.params.map(w=>t.jsx(Hx,{spec:w,value:S[w.key]??_l(C.id)[w.key],locale:r,onChange:E=>j(w.key,E)},w.key))}),!k&&t.jsx("button",{className:"pill-btn primary",disabled:v,onClick:()=>void M(),children:v?a("Đang dựng model…"):a("Thêm vào cảnh")}),t.jsx("small",{className:"muted",children:k?a("Thay đổi được dựng lại ngay trên cảnh. Kích thước tính bằng mét thật."):a("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":a("Tìm model"),placeholder:a("Tìm: nhà phố, sofa, ô tô…"),value:m,onChange:w=>d(w.target.value)}),t.jsx("div",{className:"shot-model-groups",role:"group","aria-label":a("Nhóm model"),children:[{id:"all",vi:"Tất cả",en:"All"},...Dm].map(w=>t.jsx("button",{className:`pill-btn thin${h===w.id?" on":""}`,"aria-pressed":h===w.id,onClick:()=>u(w.id),children:l(w)},w.id))}),t.jsxs("div",{className:"shot-model-grid",children:[T.map(w=>t.jsxs("button",{className:"shot-model-card","aria-label":`${a("Chọn model")} ${l(w)}`,onClick:()=>{p(w.id),g(_l(w.id))},children:[t.jsx(Kc,{id:w.id,alt:""}),t.jsx("strong",{children:l(w)}),t.jsxs("small",{children:[w.params.length," ",a("tham số")]})]},w.id)),!T.length&&t.jsx("p",{className:"muted",children:a("Không có model nào khớp.")})]})]})}function Kc({id:e,alt:n,small:s}){const[o,i]=R.useState(null),[r,l]=R.useState(!1),h=R.useRef(null);R.useEffect(()=>{if(r||!h.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(h.current),()=>m.disconnect()},[r]),R.useEffect(()=>{if(!r)return;let m=!0;return i(null),Px(e).then(d=>{m&&i(d)}).catch(()=>{}),()=>{m=!1}},[r,e]);const u=`shot-model-thumb${s?" small":""}`;return o?t.jsx("img",{className:u,src:o,alt:n,draggable:!1,"data-kit":e}):t.jsx("span",{ref:h,className:`${u} loading`,role:n?"img":void 0,"aria-label":n||void 0,"aria-hidden":n?void 0:!0,children:t.jsx(zd,{})})}function Hx({spec:e,value:n,locale:s,onChange:o}){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=>o(+l.target.value)}),t.jsx("input",{type:"number","aria-label":`${i} (${a("số")})`,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>{const h=+l.target.value;Number.isFinite(h)&&o(Math.min(e.max,Math.max(e.min,h)))}})]})}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=>o(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=>o(r.target.value),children:e.allowed.map(r=>t.jsx("option",{value:r,children:Wx(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=>o(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=>o(r.target.value)})]})}const Wx=(e,n)=>Bc[e]?Bc[e][n==="en"?1:0]:e;function Bd({value:e,onChange:n,label:s,none:o}){const i=ct();return t.jsxs("select",{"aria-label":s,value:e,onChange:r=>n(r.target.value),children:[o&&t.jsx("option",{value:"",children:o}),sd.map(r=>t.jsx("optgroup",{label:i==="en"?r.en:r.vi,children:_m.filter(l=>l.cat===r.id).map(l=>t.jsx("option",{value:l.id,children:Ta(l,i==="en"?"en":"vi")},l.id))},r.id))]})}function Gx({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:a("Vật liệu cả model")}),t.jsx(Bd,{label:a("Vật liệu cả model"),value:s,none:a("Theo từng khối"),onChange:o=>n(i=>Gs(i,e.id,Qs,o?{preset:o}:null))})]})}function Kd(e,n){let s=n,o=2;for(;e.items.some(i=>i.name===s);)s=`${n} ${o++}`;return s}const Hc={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"}})},qx=[["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"]],Ux={union:"Hợp (gộp vào)",subtract:"Trừ (khoét)",intersect:"Giao (giữ phần chung)"},Xx={union:"gộp vào",subtract:"khoét",intersect:"giao với"};function Vx({stage:e,change:n,engine:s,onSelect:o,ground:i,setError:r,item:l}){const h=ct(),[u,m]=R.useState(null),[d,f]=R.useState(0),[p,b]=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),y=(N,A=l)=>{if(!A?.set)return;let O;try{O=Bl(N)}catch(D){r(D.message);return}m(O),s?.cacheSet(A.set.id,O);const H=Kl(O);n(D=>({...D,items:D.items.map($=>$.id===A.id?{...$,set:{...$.set,parts:O.parts.length,min:H.min,max:H.max}}:$)})),window.clearTimeout(v.current),v.current=window.setTimeout(()=>{yc(A.set.id,A.name,O).catch(D=>r(D.message))},400)},k=async()=>{const N=crypto.randomUUID(),A=Kd(e,a("Model tự dựng")),O=Bl({v:1,parts:[Hc.box()]});try{await yc(N,A,O)}catch($){r($.message);return}s?.cacheSet(N,O);const H=Kl(O),D=Jh(e,{kind:"set",name:A,color:"#9aa3a8",position:i(),set:{id:N,name:A,parts:1,min:H.min,max:H.max,kit:{id:Aa,params:{}}}});n($=>({...$,items:[...$.items,D]})),o(D.id)};if(!l||!u)return t.jsxs("div",{className:"shot-model-hand-empty",children:[t.jsx("p",{className:"muted",children:a("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 k(),children:a("+ Tạo model mới")}),l&&!u&&t.jsx("p",{className:"muted",children:a("Đang tải model…")})]});const C=u.parts,S=C[Math.min(d,C.length-1)],I=N=>+(Math.round(N/p)*p).toFixed(3),j=N=>y({...u,parts:C.map((A,O)=>O===d?{...A,...N}:A)}),M=N=>{const A=Hc[N]();y({...u,parts:[...C,A]}),f(C.length)},T=(N,A,O,H=-500)=>t.jsxs("div",{className:"shot-model-vec",children:[t.jsx("span",{children:N}),["X","Y","Z"].map((D,$)=>t.jsx("input",{type:"number",step:p,"aria-label":`${N} ${D}`,value:A[$],onChange:W=>{const z=+W.target.value;if(!Number.isFinite(z))return;const Y=[...A];Y[$]=Math.max(H,I(z)),O(Y)}},D))]}),w=N=>{const A=(N.outline||[]).map(H=>H[0]),O=(N.outline||[]).map(H=>H[1]);return[+(Math.max(...A)-Math.min(...A)).toFixed(3),+(Math.max(...O)-Math.min(...O)).toFixed(3),N.depth||.2]},E=(N,A)=>{const[O,H]=w(N),D=A[0]/(O||1),$=A[1]/(H||1),W=z=>z.map(([Y,J])=>[+(Y*D).toFixed(3),+(J*$).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:[C.length," ",a("khối")]}),t.jsxs("label",{className:"shot-model-snap",children:[a("Bước lưới"),t.jsx("select",{"aria-label":a("Bước lưới"),value:p,onChange:N=>b(+N.target.value),children:_x.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":a("Thêm khối"),children:qx.map(([N,A])=>t.jsxs("button",{className:"pill-btn thin",onClick:()=>M(N),children:["+ ",a(A)]},N))}),t.jsx("ul",{className:"shot-model-parts","aria-label":a("Các khối"),children:C.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:zx[N.shape]?.[h==="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:a("Tên khối")}),t.jsx("input",{"aria-label":a("Tên khối"),maxLength:40,value:S.name||"",onChange:N=>j({name:N.target.value.slice(0,40)})})]}),S.shape==="extrude"?T(a("Rộng / cao / dày (m)"),w(S),N=>j(E(S,N)),.005):T(a("Kích thước (m)"),S.size||[1,1,1],N=>j({size:N.map(A=>Math.max(.005,A))}),.005),T(a("Vị trí (m)"),S.position,N=>j({position:N})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Xoay quanh trục đứng (°)")}),t.jsx("input",{type:"number","aria-label":a("Xoay quanh trục đứng (°)"),step:15,value:S.rotation[1],onChange:N=>{const A=+N.target.value;Number.isFinite(A)&&j({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:a("Số bậc")}),t.jsx("input",{type:"number","aria-label":a("Số bậc"),min:2,max:80,value:S.steps||10,onChange:N=>j({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:a("Phép khối")}),t.jsxs("select",{"aria-label":a("Phép khối"),value:S.op||"",onChange:N=>{const A=N.target.value||void 0;j(A?{op:A}:{op:void 0,target:void 0})},children:[t.jsx("option",{value:"",children:a("Khối thường")}),Om.map(N=>t.jsx("option",{value:N,children:a(Ux[N])},N))]})]}),S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Tác động lên")}),t.jsxs("select",{"aria-label":a("Tác động lên"),value:S.target||"",onChange:N=>j({target:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Khối liền trước")}),C.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:xi(C,d)>=0?a("Khối này không hiện; nó {0} “{1}”.",[a(Xx[S.op]),C[xi(C,d)].name||C[xi(C,d)].shape]):a("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:a("Vật liệu")}),t.jsx(Bd,{label:a("Vật liệu"),value:Ds(S)?.preset??"painted_wood",onChange:N=>j({look:{preset:N,...Ds(S)?.params?.color?{params:{color:Ds(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:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu khối"),value:Ds(S)?.params?.color||Ha(Ds(S)?.preset??"")?.colors[0]||"#cccccc",onChange:N=>{const A=Ds(S)??{preset:"painted_wood"};j({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:a("Bo cạnh (m)")}),t.jsx("input",{type:"number","aria-label":a("Bo cạnh (m)"),min:0,max:.5,step:.005,value:S.bevel??0,onChange:N=>j({bevel:Math.max(0,Math.min(.5,+N.target.value||0))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Nhân bản (số bản)")}),t.jsx("input",{type:"number","aria-label":a("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));j({repeat:A>1?{count:A,offset:S.repeat?.offset??[1,0,0],yaw:S.repeat?.yaw??0}:void 0})}})]}),S.repeat&&T(a("Khoảng cách bản sao (m)"),S.repeat.offset,N=>j({repeat:{...S.repeat,offset:N}})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Đối xứng")}),t.jsxs("select",{"aria-label":a("Đối xứng"),value:S.mirror||"",onChange:N=>j({mirror:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Không")}),t.jsx("option",{value:"x",children:a("Trái – phải (X)")}),t.jsx("option",{value:"z",children:a("Trước – sau (Z)")}),t.jsx("option",{value:"xz",children:a("Cả hai")})]})]}),t.jsxs("div",{className:"shot-model-actions",children:[t.jsx("button",{className:"pill-btn thin",onClick:()=>{y({...u,parts:[...C,{...S,name:`${S.name||S.shape} 2`,position:[I(S.position[0]+.5),S.position[1],S.position[2]]}]}),f(C.length)},children:a("Nhân đôi khối")}),t.jsx("button",{className:"pill-btn thin",disabled:C.length<2,onClick:()=>{y({...u,parts:C.filter((N,A)=>A!==d)}),f(Math.max(0,d-1))},children:a("Xoá khối")})]})]})]})}function Yx({loop:e,onLoop:n,range:s,rangeOn:o,onRangeOn:i,onEnd:r,onKeyAll:l,onCopy:h,onPaste:u,canPaste:m,onEase:d,onNudge:f,stage:p,cameraActive:b,cameraHidden:g,cameraLocked:v,onToggle:y,onProp:k,shot:C,items:S,time:I,fxBars:j,onFxTiming:M,onParent:T,playing:w,selected:E,picked:N=[],onPick:A,onSeek:O,onPlay:H,onRow:D,onSelect:$,onAdd:W,onMove:z,onDelete:Y,height:J,onHeight:V}){ct();const[K,G]=R.useState(1),[_,ee]=R.useState(220),Q=J??_,ve=F=>{ee(F),V?.(F)},[xe,q]=R.useState(null),[ue,pe]=R.useState({}),[U,le]=R.useState(!0),ce=R.useRef(void 0),Le=R.useRef(null),[je,ie]=R.useState(null),Me=(F,te)=>N.some(Z=>Z.row===F&&Z.id===te),Ee=(F,te,Z)=>{if(F.button!==0||!Le.current)return;F.preventDefault(),ce.current?.();const re=Le.current,me=re.parentElement,Pe=re.getBoundingClientRect(),ye=F.clientX-Pe.left,rt=F.clientY-Pe.top,It=F.pointerId,qt=F.shiftKey,Xe=()=>{const mt=re.getBoundingClientRect();return[mt.left+ye,mt.top+rt]};re.setPointerCapture(It);let lt=!1;const jt=(mt,Rt)=>{const[Yt,ln]=Xe(),Qt=Math.min(Yt,mt),xt=Math.max(Yt,mt),cn=Math.min(ln,Rt),Ft=Math.max(ln,Rt),Zt=qt?[...N]:[];return re.querySelectorAll(".shot-time-key:not([disabled]),.shot-prop-key[data-key]").forEach(bn=>{const Gn=bn.getBoundingClientRect(),ae=Gn.left+Gn.width/2,ke=Gn.top+Gn.height/2;ae>=Qt&&ae<=xt&&ke>=cn&&ke<=Ft&&!Zt.some(Oe=>Oe.row===bn.dataset.row&&Oe.id===bn.dataset.key)&&Zt.push({row:bn.dataset.row,id:bn.dataset.key})}),Zt};let St=[F.clientX,F.clientY],gt=0;const at=()=>{const[mt,Rt]=Xe(),[Yt,ln]=St,Qt=re.getBoundingClientRect();ie({x:Math.min(mt,Yt)-Qt.left,y:Math.min(Rt,ln)-Qt.top,w:Math.abs(Yt-mt),h:Math.abs(ln-Rt)}),A?.(jt(Yt,ln))},tn=()=>{if(gt=0,!lt||!me)return;const mt=me.getBoundingClientRect(),Rt=St[1],Yt=Rt<mt.top+28?-Math.ceil((mt.top+28-Rt)/3):Rt>mt.bottom-16?Math.ceil((Rt-mt.bottom+16)/3):0;if(!Yt)return;const ln=me.scrollTop;me.scrollTop+=Yt,me.scrollTop!==ln&&(at(),gt=requestAnimationFrame(tn))},Ie=mt=>{if(mt.pointerId!==It)return;const[Rt,Yt]=Xe();!lt&&Math.hypot(mt.clientX-Rt,mt.clientY-Yt)<4||(lt=!0,St=[mt.clientX,mt.clientY],at(),gt||(gt=requestAnimationFrame(tn)))},ot=()=>{gt&&cancelAnimationFrame(gt),gt=0,re.removeEventListener("pointermove",Ie),re.removeEventListener("pointerup",nn),re.removeEventListener("pointercancel",ot),re.hasPointerCapture(It)&&re.releasePointerCapture(It),ie(null)},nn=mt=>{if(ot(),lt)A?.(jt(mt.clientX,mt.clientY));else{D(te);const Rt=Z.getBoundingClientRect();O(Math.max(0,Math.min(1,(mt.clientX-Rt.left)/Rt.width)))}};ce.current=ot,re.addEventListener("pointermove",Ie),re.addEventListener("pointerup",nn),re.addEventListener("pointercancel",ot)};R.useEffect(()=>()=>ce.current?.(),[]);const[Se,he]=R.useState(null),be=(F,te,Z,re)=>{const me=j?.[te];if(F.button!==0||!me||!M)return;F.preventDefault(),F.stopPropagation(),ce.current?.();const Pe=F.currentTarget,ye=F.pointerId,rt=F.clientX,It=re.getBoundingClientRect().width,qt=C.duration,Xe=.2;Pe.setPointerCapture(ye);let lt={id:te,start:me.start,duration:me.duration};const jt=tn=>Math.round(tn*20)/20,St=tn=>{if(tn.pointerId!==ye)return;const Ie=(tn.clientX-rt)/It*qt;if(Z==="move")lt={id:te,start:jt(Math.max(0,Math.min(qt-Xe,me.start+Ie))),duration:me.duration};else if(Z==="start"){const ot=me.start+me.duration,nn=jt(Math.max(0,Math.min(ot-Xe,me.start+Ie)));lt={id:te,start:nn,duration:+(ot-nn).toFixed(2)}}else lt={id:te,start:me.start,duration:jt(Math.max(Xe,me.duration+Ie))};he(lt)},gt=()=>{Pe.removeEventListener("pointermove",St),Pe.removeEventListener("pointerup",at),Pe.removeEventListener("pointercancel",gt),Pe.hasPointerCapture(ye)&&Pe.releasePointerCapture(ye),he(null)},at=()=>{gt(),(lt.start!==me.start||lt.duration!==me.duration)&&M(te,{start:lt.start,duration:lt.duration})};ce.current=gt,Pe.addEventListener("pointermove",St),Pe.addEventListener("pointerup",at),Pe.addEventListener("pointercancel",gt)},Fe=[{id:"camera",kind:"camera",name:"📷 Camera",locked:!!v,hidden:!!g,keys:C.motion==="path"?C.cameraKeys||[]:[]},...S.map(F=>({id:F.id,kind:F.kind==="fx"?"fx":F.kind==="person"?"person":"object",name:F.kind==="fx"?`✦ ${F.name}`:F.name,locked:F.locked,hidden:F.hidden,keys:C.objectKeys?.[F.id]||[],fx:F.kind==="fx",parent:F.fx?.attach?.to??""}))],Te=S.filter(F=>F.kind!=="fx"&&!F.hidden),_e=(E?Fe.filter(F=>F.id===E.row):Fe).flatMap(F=>F.keys.map(te=>te.time)).sort((F,te)=>F-te),ze=F=>{const te=F>0?_e.find(Z=>Z>I+1e-4):[..._e].reverse().find(Z=>Z<I-1e-4);te!==void 0&&O(te)},Be=(F,te)=>{if(F.button!==0)return;F.preventDefault(),F.stopPropagation(),ce.current?.();const Z=F.pointerId;te.setPointerCapture(Z);const re=rt=>{const It=te.getBoundingClientRect(),qt=Math.max(0,Math.min(1,(rt.clientX-It.left)/It.width)),Xe=gn(C);O(Math.min(1,Math.round(qt*C.duration*Xe)/Xe/C.duration))},me=rt=>{rt.pointerId===Z&&re(rt)},Pe=()=>{te.removeEventListener("pointermove",me),te.removeEventListener("pointerup",ye),te.removeEventListener("pointercancel",Pe),te.removeEventListener("lostpointercapture",Pe),te.hasPointerCapture(Z)&&te.releasePointerCapture(Z)},ye=rt=>{re(rt),Pe()};ce.current=Pe,te.addEventListener("pointermove",me),te.addEventListener("pointerup",ye),te.addEventListener("pointercancel",Pe),te.addEventListener("lostpointercapture",Pe),re(F)},Ze=(F,te,Z,re)=>{F.preventDefault(),F.stopPropagation(),$(te,Z);const me=re.getBoundingClientRect();let Pe;const ye=qt=>{if(Pe=Math.max(0,Math.min(1,(qt.clientX-me.left)/me.width)),U){const Xe=gn(C);Pe=Math.min(1,Math.round(Pe*C.duration*Xe)/Xe/C.duration);const lt=Fe.flatMap(jt=>jt.keys.filter(St=>!(jt.id===te&&St.id===Z)).map(St=>St.time)).find(jt=>Math.abs(jt-Pe)*me.width<6);lt!==void 0&&(Pe=lt)}q({row:te,id:Z,time:Pe})},rt=()=>{window.removeEventListener("mousemove",ye),window.removeEventListener("mouseup",It),q(null)},It=()=>{rt(),Pe!==void 0&&z(te,Z,Pe)};ce.current?.(),ce.current=rt,window.addEventListener("mousemove",ye),window.addEventListener("mouseup",It)};return t.jsxs("section",{className:"shot-timeline","aria-label":a("Timeline keyframe"),style:{height:Q},children:[t.jsx("div",{className:"shot-timeline-tools",children:(()=>{const F=gn(C),te=C.duration,Z=I*te,re=ye=>{const rt=Math.floor(ye/60),It=ye-rt*60;return`${String(rt).padStart(2,"0")}:${It.toFixed(2).padStart(5,"0")}`},me=ye=>{O(Math.max(0,Math.min(1,(Math.round(Z*F)+ye)/F/te)))},Pe=N.length?!1:!E||Fe.find(ye=>ye.id===E.row)?.locked;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-tc",children:[t.jsxs("span",{children:[re(Z)," / ",re(te)]}),t.jsx("small",{children:a("Khung {0} / {1} · {2} fps",[Math.round(Z*F),Math.round(te*F),F])})]}),t.jsxs("div",{className:"shot-transport",role:"group","aria-label":a("Điều khiển phát"),children:[t.jsx("button",{className:"shot-tp-btn",onClick:()=>O(0),"aria-label":a("Về đầu"),title:a("Về đầu")+" (Home)",children:t.jsx(Ne.skipStart,{})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>me(-1),disabled:Z<=1e-6,"aria-label":a("Lùi 1 khung hình"),title:a("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:H,"aria-label":w?a("Tạm dừng"):a("Phát"),title:(w?a("Tạm dừng"):a("Phát"))+" (Space)",children:w?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:()=>me(1),disabled:Z>=te-1e-6,"aria-label":a("Tới 1 khung hình"),title:a("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":a("Phát lặp"),title:a("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:Pe,onClick:Y,"aria-label":N.length>1?a("Xoá {0} key",[N.length]):a("Xoá key"),title:N.length>1?a("Xoá {0} key",[N.length]):a("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:[a("Zoom")," ",t.jsx("input",{"aria-label":a("Zoom timeline"),type:"range",min:1,max:8,step:.5,value:K,onChange:ye=>G(+ye.target.value)})]}),t.jsxs("label",{children:[a("Cao")," ",t.jsx("input",{"aria-label":a("Chiều cao timeline"),type:"range",min:140,max:360,step:20,value:Q,onChange:ye=>ve(+ye.target.value)})]})]})]})})()}),t.jsx("div",{className:"shot-edit-bar",role:"toolbar","aria-label":a("Công cụ keyframe"),children:(()=>{const F=N.length?N:E?[E]:[],te=F.length>0,Z=E?.row,re=(Xe,lt)=>lt?`${a(Xe)} (${lt})`:a(Xe),me=(Xe,lt,jt,St,gt={})=>t.jsx("button",{type:"button",className:`shot-edit-btn${gt.on?" on":""}`,"data-tool":Xe,"aria-label":a(jt),"aria-pressed":gt.on===void 0?void 0:gt.on,title:re(jt,gt.key),disabled:gt.disabled||!St,onClick:St,children:lt},Xe),Pe=Xe=>t.jsx("i",{className:"shot-edit-sep","aria-hidden":!0},Xe),ye=Xe=>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:Xe}),rt=(Xe,lt,jt)=>me("ease-"+Xe,ye(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M3 17h14M3 3v14"}),t.jsx("path",{d:jt})]})),lt,()=>d?.(Xe),{disabled:!te||!d}),It=()=>{G(1),requestAnimationFrame(()=>{const Xe=Le.current?.parentElement;Xe&&(Xe.scrollLeft=0)})},qt=()=>{const Xe=Fe.flatMap(gt=>gt.keys.filter(at=>F.some(tn=>tn.row===gt.id&&tn.id===at.id)).map(at=>at.time)),lt=Math.min(...Xe),jt=Math.max(...Xe),St=Math.min(8,Math.max(1,.8/Math.max(.02,jt-lt)));G(St),requestAnimationFrame(()=>{const gt=Le.current?.parentElement;gt&&(gt.scrollLeft=Math.max(0,(lt-.05/St)*gt.clientWidth*St))})};return t.jsxs(t.Fragment,{children:[me("add",Os.key,"Thêm key trên hàng đang chọn",Z?()=>W(Z):void 0,{key:"K",disabled:!Z}),me("key-all",ye(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"}),me("key-prev",ye(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",_e.some(Xe=>Xe<I-1e-4)?()=>ze(-1):void 0),me("key-next",ye(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",_e.some(Xe=>Xe>I+1e-4)?()=>ze(1):void 0),Pe("s1"),me("copy",Os.copy,"Copy các key đang chọn",te?h:void 0,{key:"⌘C",disabled:!te}),me("paste",Os.paste,"Dán key tại playhead (giữ khoảng cách)",u,{key:"⌘V",disabled:!m}),Pe("s2"),rt("linear","Easing: Tuyến tính","M3 17 17 3"),rt("in","Easing: Vào chậm (ease in)","M3 17C10 17 14 12 17 3"),rt("snap","Easing: Ra chậm (ease out)","M3 17C6 8 10 3 17 3"),rt("smooth","Easing: Vào và ra chậm (ease in-out)","M3 17C10 17 10 3 17 3"),rt("hold","Easing: Giữ nguyên (hold)","M3 17h7V3h7"),Pe("s3"),me("nudge-back",ye(t.jsx("path",{d:"m12 5-5 5 5 5M16 4v12"})),"Dịch key lùi 1 khung hình",te?()=>f?.(-1):void 0,{key:"Alt+,",disabled:!te}),me("nudge-fwd",ye(t.jsx("path",{d:"m8 5 5 5-5 5M4 4v12"})),"Dịch key tới 1 khung hình",te?()=>f?.(1):void 0,{key:"Alt+.",disabled:!te}),Pe("s4"),me("range",ye(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:!!o,disabled:!s}),me("snap",Os.magnet,"Bám khung hình và key khác khi kéo key",()=>le(Xe=>!Xe),{on:U}),Pe("s5"),me("zoom-fit",Os.fit,"Thu phóng vừa cả shot",It),me("zoom-sel",Os.zoomIn,"Thu phóng vào các key đang chọn",te?qt:void 0,{disabled:!te}),me("end",ye(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:Le,style:{width:`${K*100}%`},children:[je&&t.jsx("div",{className:"shot-marquee",style:{left:je.x,top:je.y,width:je.w,height:je.h}}),t.jsxs("div",{className:"shot-time-row shot-ruler-row",children:[t.jsx("div",{className:"shot-track-name",children:a("Đối tượng")}),t.jsxs("div",{className:"shot-time-ruler",onPointerDown:F=>Be(F,F.currentTarget),children:[(C.lockUntil??0)>0&&t.jsx("div",{className:"shot-lock-band",role:"img",style:{width:`${Math.min(1,C.lockUntil/C.duration)*100}%`},"aria-label":a("Đã khoá 0–{0}s cho Agent",[String(Math.round(Math.min(C.lockUntil,C.duration)*100)/100)]),title:a("Agent không sửa phần này"),children:t.jsx("span",{children:"🔒"})}),s&&t.jsx("div",{className:`shot-range${o?" 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":a("Vị trí phát timeline"),"aria-valuemin":0,"aria-valuemax":C.duration,"aria-valuenow":Number((I*C.duration).toFixed(2)),style:{left:`${I*100}%`},onKeyDown:F=>{const te=F.shiftKey?1:.1,Z=1/gn(C);["ArrowLeft","ArrowRight","Home","End",",","."].includes(F.key)&&(F.preventDefault(),O(F.key==="Home"?0:F.key==="End"?1:F.key===","||F.key==="."?Math.max(0,Math.min(1,Math.round(I*C.duration/Z+(F.key==="."?1:-1))*Z/C.duration)):Math.max(0,Math.min(1,I+(F.key==="ArrowRight"?te:-te)/C.duration))))}}),Array.from({length:11},(F,te)=>t.jsxs("span",{style:{left:`${te*10}%`},children:[Number((C.duration*te/10).toFixed(2)),a("s")]},te))]})]}),Fe.map(F=>{const te=p&&ue[F.id]?wg(p,F.id):[];return t.jsxs(R.Fragment,{children:[t.jsxs("div",{className:`shot-time-row${F.id==="camera"&&b?" camera-active":""}${F.hidden?" is-hidden":""}${F.locked?" is-locked":""}`,children:[t.jsxs("div",{className:"shot-track-name",children:[y&&t.jsx("button",{className:`shot-row-eye${F.hidden?" off":""}`,"aria-pressed":!F.hidden,"aria-label":F.hidden?a("Hiện {0}",[F.name]):a("Ẩn {0}",[F.name]),title:F.id==="camera"?F.hidden?a("Hiện camera trong khung nhìn"):a("Ẩn camera khỏi khung nhìn (không ảnh hưởng ảnh xuất)"):F.hidden?a("Hiện trong cảnh và khi xuất"):a("Ẩn khỏi cảnh và khi xuất"),onClick:()=>y(F.id,"hidden"),children:F.hidden?"◌":"◉"}),p&&t.jsx("button",{className:`shot-row-keys${F.keys.length?" keyed":""}${ue[F.id]?" open":""}`,"aria-expanded":!!ue[F.id],"aria-label":a("Thuộc tính {0}",[F.name]),title:a("Mở / đóng các thuộc tính keyframe"),onClick:()=>pe(Z=>({...Z,[F.id]:!Z[F.id]})),children:"◆"}),y&&t.jsx("button",{className:`shot-row-lock${F.locked?" on":""}`,"aria-pressed":F.locked,"aria-label":F.locked?a("Mở khoá {0}",[F.name]):a("Khoá {0}",[F.name]),title:F.locked?a("Mở khoá: cho chọn và kéo"):a("Khoá: không chọn, không kéo, không sửa key"),onClick:()=>y(F.id,"locked"),children:F.locked?"🔒":"🔓"}),t.jsx("button",{className:"shot-row-name",title:F.name,onClick:()=>{F.locked||D(F.id)},children:F.name}),"fx"in F&&F.fx&&T&&t.jsxs("select",{className:"shot-track-parent","aria-label":a("Parent của {0}",[F.name]),title:a("Parent: hiệu ứng đi theo đối tượng này"),disabled:F.locked,value:F.parent,onChange:Z=>T(F.id,Z.target.value),children:[t.jsx("option",{value:"",children:a("Tự do")}),Te.map(Z=>t.jsxs("option",{value:Z.id,children:["🔗 ",Z.name]},Z.id))]}),t.jsx("button",{"aria-label":a("Thêm key {0}",[F.name]),disabled:F.locked,onClick:()=>W(F.id),children:"+◆"})]}),t.jsxs("div",{className:"shot-key-track","data-row":F.id,onPointerDown:Z=>{Z.target.closest(".shot-time-key")||Ee(Z,F.id,Z.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),(C.clipSpans?.[F.id]||[]).map(Z=>t.jsx("div",{className:"shot-clip-block","data-clip-block":Z.clip,style:{left:`${Z.start/C.duration*100}%`,width:`${Math.max(.5,(Math.min(C.duration,Z.end)-Z.start)/C.duration*100)}%`},title:`${Z.label} · ${Z.start.toFixed(1)}–${Z.end.toFixed(1)}s`,children:t.jsx("span",{children:Z.label})},Z.id)),(C.motionEdits?.[F.id]||[]).map(Z=>t.jsx("div",{className:`shot-edit-mark${Z.off?" off":""}`,"data-edit-mark":!0,style:{left:`${Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade))/C.duration*100}%`,width:`${((Z.scope==="after"?C.duration:Z.end+(Z.scope==="span"?0:Z.fade))-Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade)))/C.duration*100}%`},title:`${Z.label||a("Chỉnh")} · ${(Number(Z.start)||0).toFixed(1)}s`},Z.id)),j?.[F.id]&&(()=>{const Z=Se?.id===F.id?Se:j[F.id],re=!!M&&!F.locked,me=Pe=>Pe.currentTarget.closest(".shot-key-track");return t.jsx("div",{className:`shot-fx-bar${F.hidden||F.locked?" dim":""}${re?" editable":""}${Se?.id===F.id?" dragging":""}`,"data-fx-bar":F.id,title:a("Hiệu ứng: {0}s → {1}s · kéo để dời, kéo mép để đổi độ dài",[Z.start.toFixed(2),(Z.start+Z.duration).toFixed(2)]),style:{left:`${Math.min(100,Z.start/C.duration*100)}%`,width:`${Math.max(.6,Math.min(100-Z.start/C.duration*100,Z.duration/C.duration*100))}%`},onPointerDown:re?Pe=>be(Pe,F.id,"move",me(Pe)):void 0,children:re&&t.jsxs(t.Fragment,{children:[t.jsx("i",{className:"shot-fx-edge start","aria-hidden":!0,onPointerDown:Pe=>be(Pe,F.id,"start",me(Pe))}),t.jsx("i",{className:"shot-fx-edge end","aria-hidden":!0,onPointerDown:Pe=>be(Pe,F.id,"end",me(Pe))})]})})})(),!j?.[F.id]&&F.kind!=="fx"&&t.jsx("div",{className:`shot-dur-bar kind-${F.kind}${F.hidden||F.locked?" dim":""}`,"data-dur":F.id,title:F.kind==="camera"?a("Camera chạy suốt shot: 0s → {0}s",[C.duration]):a("Có mặt suốt shot: 0s → {0}s",[C.duration]),style:{left:"0%",width:"100%"}}),F.keys.map((Z,re)=>t.jsx("button",{"aria-label":`Key ${re+1} ${F.name}`,title:a("{0}s · kéo để đổi thời điểm",[(Z.time*C.duration).toFixed(2)]),disabled:F.locked,"data-row":F.id,"data-key":Z.id,className:`shot-time-key ${"pose"in Z&&Z.pose?"pose":""} ${E?.row===F.id&&E.id===Z.id||Me(F.id,Z.id)?"active":""}`,style:{left:`${(xe?.id===Z.id&&xe.row===F.id?xe.time:Z.time)*100}%`},onClick:me=>{me.detail===0&&$(F.id,Z.id)},onMouseDown:me=>{if(me.shiftKey||me.metaKey||me.ctrlKey){me.preventDefault(),me.stopPropagation();const Pe=Me(F.id,Z.id),ye=N.length?N:E?[E]:[];A?.(Pe?ye.filter(rt=>!(rt.row===F.id&&rt.id===Z.id)):[...ye,{row:F.id,id:Z.id}]);return}Ze(me,F.id,Z.id,me.currentTarget.parentElement)},children:"◆"},Z.id))]})]}),te.map(Z=>{const re=Mg(C,F.id);return t.jsxs("div",{className:"shot-time-row shot-prop-row","data-prop":`${F.id}:${Z.id}`,children:[t.jsxs("div",{className:"shot-track-name",children:[t.jsx("span",{className:`shot-stopwatch${re?" keyed":""}`,role:"img","aria-label":re?a("Đã có key"):a("Chưa có key"),title:re?a("Thuộc tính đã có key: sửa số sẽ ghi key tại playhead"):a("Chưa có key: sửa số đổi giá trị cố định"),children:"⏱"}),t.jsxs("label",{className:"shot-prop-label",children:[a(Z.label),t.jsx(Sn,{"aria-label":`${a(Z.label)} · ${F.name}`,className:"shot-prop-number",step:Z.step,min:Z.min,max:Z.max,precision:3,disabled:F.locked,value:Sg(p,F.id,Z.id,I),onCommit:me=>k?.(F.id,Z.id,me)})]}),t.jsx("button",{className:"shot-prop-add","aria-label":`${a("Thêm key")} ${a(Z.label)} · ${F.name}`,title:a("Thêm key tại playhead"),disabled:F.locked,onClick:()=>W(F.id),children:"◆"})]}),t.jsxs("div",{className:"shot-key-track shot-prop-track",onPointerDown:me=>{F.locked||Ee(me,F.id,me.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),F.keys.map(me=>t.jsx("i",{"data-row":F.locked?void 0:F.id,"data-key":F.locked?void 0:me.id,className:`shot-prop-key${Me(F.id,me.id)||E?.row===F.id&&E.id===me.id?" active":""}`,style:{left:`${me.time*100}%`}},me.id))]})]},Z.id)})]},F.id)})]})})]})}let ls=null;function Qx(){return ls||(ls=new Kr(Ig()),ls.colorSpace=Sd,ls.anisotropy=4,ls.generateMipmaps=!0,ls.minFilter=Cd,ls)}const Wc=new Map;function Zx(e){let n=Wc.get(e);return n||(n=new Kr(Eg(e)),n.colorSpace=Sd,n.anisotropy=8,n.generateMipmaps=!0,n.minFilter=Cd,Wc.set(e,n)),n}let Yn=null;function Jx(){if(Yn)return Yn;const e=128,n=new Uint8Array(e*e*4),s=r=>{const l=new Float32Array(r*r);let h=1013904223+r;for(let u=0;u<l.length;u++)h=Math.imul(h,1664525)+1013904223>>>0,l[u]=h/4294967296;return l},o=[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 h=0,u=.5,m=0;for(const{g:p,v:b}of o){const g=l/e*p,v=r/e*p,y=Math.floor(g),k=Math.floor(v),C=i(g-y),S=i(v-k),I=(T,w)=>b[w%p*p+T%p],j=I(y,k)+(I(y+1,k)-I(y,k))*C,M=I(y,k+1)+(I(y+1,k+1)-I(y,k+1))*C;h+=(j+(M-j)*S)*u,m+=u,u*=.5}const d=(r*e+l)*4,f=Math.round(h/m*255);n[d]=n[d+1]=n[d+2]=f,n[d+3]=255}return Yn=new K0(n,e,e,H0),Yn.wrapS=Yn.wrapT=Md,Yn.magFilter=gc,Yn.minFilter=gc,Yn.needsUpdate=!0,Yn}const eb=Symbol.for("clipoox.shot.fxSoftDepth"),tb=e=>e[eb]??null,Gr={uOcclude:{value:0}},Gc={day:.22,golden:.16,overcast:.2,night:.03},Oa={blade:.78,width:.034,thick:.0075,grip:.19};function qc(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 Uc(e=0){const{blade:n,width:s,thick:o}=Oa,i=[[0,.86,1],[.06,1,1],[.7,.96,.9],[.84,.74,.72],[.94,.4,.5],[1,.02,.15]],r=qc(1,1).length,l=[],h=[];i.forEach(([m,d,f])=>{for(const[p,b]of qc(s*d+e,o*f+e*.5))l.push(p,m*n,b)});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,b=(m+1)*r+d,g=(m+1)*r+(d+1)%r;h.push(f,b,p,p,b,g)}const u=new Tt;return u.setAttribute("position",new Bt(l,3)),u.setIndex(h),u.computeVertexNormals(),u}function nb(){const e=[],n=new Nd(.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 W0(.0125,.03,10);r.rotateZ(-i*Math.PI/2),r.translate(i*.086,.012,0),e.push(r)}const s=new vs(.016,.02,.026,14);s.translate(0,-.016,0),e.push(s);const o=Hd(e);return e.forEach(i=>i.dispose()),o}function sb(){const e=[],n=new vs(.0125,.0125,Oa.grip,12);n.translate(0,-.03-Oa.grip/2,0),e.push(n);for(let i=0;i<5;i++){const r=new Wr(.0132,.0028,6,14);r.rotateX(Math.PI/2),r.translate(0,-.05-i*.034,0),e.push(r)}const s=new Hn(.0235,14,10);s.translate(0,-.03-Oa.grip-.012,0),e.push(s);const o=Hd(e);return e.forEach(i=>i.dispose()),o}function Hd(e){const n=[],s=[],o=[],i=[];let r=0;for(const h of e){const u=h.getAttribute("position"),m=h.getAttribute("normal"),d=h.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)),o.push(d?d.getX(f):0,d?d.getY(f):0);if(h.index)for(let f=0;f<h.index.count;f++)i.push(r+h.index.getX(f));else for(let f=0;f<u.count;f++)i.push(r+f);r+=u.count}const l=new Tt;return l.setAttribute("position",new Bt(n,3)),l.setAttribute("normal",new Bt(s,3)),l.setAttribute("uv",new Bt(o,2)),l.setIndex(i),l}const ab=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/productTools-ce-zyZO0.js","assets/titleFrameBudget-DsM0V482.js","assets/remote-8XzEAnAJ.js","assets/index-CKtv7gGE.js","assets/i18n-C9zFX25m.js","assets/api-Dnl2uaKO.js","assets/three.module-Bx43vjkH.js","assets/gltfLoader-U0Eebg7v.js","assets/store-CpqHUcA2.js","assets/rotoMaskStore-pE1AIt3I.js","assets/sceneTrack-DlAH5s74.js","assets/timelineOps-DSSaDsU2.js","assets/cameraTracker-DHdF8Zqx.js","assets/textAnimators-B9vO_hbP.js","assets/timelineComp-i-zdaoB2.js","assets/rigTrack-DMyqb0pb.js","assets/clientJobs-CuuUyhEy.js","assets/exportGlb-D3PrWUvi.js","assets/aiInbetween-6eKDYbYS.js","assets/pathTracer-DykgPkkh.js","assets/plateFollow-CJUilsNV.js","assets/plateCamera-BcdXD1uI.js","assets/plateMatte-CoEoVjxZ.js","assets/rotoMatte-7b7Ow64f.js","assets/videoExport-NN-QijHd.js","assets/motionBlur-uAm030t9.js","assets/id3-arvEpAg7.js","assets/output-p-Q7qous.js"])))=>i.map(i=>d[i]);
2
+ import{_ as fn}from"./titleFrameBudget-DsM0V482.js";import{a1 as qa,a2 as nt,a3 as Ys,a4 as ps,a5 as Sm,a6 as Vh,a7 as Yh,a8 as gs,a9 as vt,aa as Kn,b as Mn,ab as Qh,ac as Cm,ad as Ol,ae as Lr,af as Wt,ag as Zh,ah as Nm,ai as Na,aj as Yo,ak as Am,al as Jh,am as Tm,j as t,an as Lm,ao as Po,ap as Em,aq as Im,ar as Rm,as as ed,at as Fm,au as Pm,av as Ka,aw as td,ax as Aa,ay as nd,az as $m,aA as _l,aB as Dm,aC as Om,aD as xi,aE as Ds,aF as Ha,aG as Qs,aH as Gs,aI as zl,aJ as Bl,aK as Kl,aL as sd,aM as _m,aN as Ta,aO as gn,I as Ne,N as Sn,R as Os,aP as bi,aQ as Hl,aR as Wl,aS as zm,aT as Gl,aU as Fn,aV as Bm,aW as Km,aX as Hm,aY as $o,aZ as Wm,a_ as ad,a$ as Wa,b0 as ql,b1 as Gm,b2 as No,b3 as od,b4 as qm,b5 as Um,b6 as Xm,b7 as Vm,b8 as Ym,b9 as Qm,ba as Do,bb as Zm,bc as Jm,bd as Ji,be as xn,bf as er,bg as tr,bh as ep,bi as Ul,bj as tp,bk as np,bl as sp,bm as ap,bn as ss,bo as Er,bp as op,bq as Xl,br as Qo,bs as id,bt as Ga,bu as ip,bv as rd,bw as ld,bx as yi,by as Wn,bz as Zs,bA as rp,bB as cd,bC as vi,bD as _s,bE as lp,bF as cp,bG as hd,bH as Ir,bI as hp,bJ as dp,bK as Rr,bL as Vl,bM as up,bN as mp,F as pp,bO as fp,a0 as gp,bP as xp,bQ as bp,bR as yp,bS as vp,bT as jp,bU as Fr,bV as dd,bW as kp,bX as so,bY as wp,bZ as Mp,b_ as Sp,b$ as Cp,c0 as Np,c1 as Ap,c2 as Tp,c3 as Lp,c4 as Ep,c5 as Yl,c6 as Ql,c7 as ji,c8 as Ip,c9 as Rp,ca as Fp,cb as ud,cc as md,cd as pd,ce as Oo,cf as Zl,cg as Pr,ch as Pp,ci as $p,cj as Dp,ck as Jl,cl as Op,cm as _n,cn as _p,co as zp,cp as ec,cq as da,cr as Ns,cs as Bp,ct as Kp,cu as Hp,cv as Wp,cw as Es,cx as Gp,cy as qp,cz as Up,cA as Xp,cB as Vp,cC as fd,cD as _o,cE as Yp,cF as tc,cG as Qp,cH as ki,cI as nc,cJ as wi,cK as Zp,cL as zo,cM as Jp,cN as ef,cO as tf,cP as us,cQ as Bo,r as gd,cR as nf,cS as sf,cT as af,cU as sc,cV as of,cW as rf,cX as $r,cY as Dr,cZ as La,c_ as lf,c$ as cf,d0 as hf,d1 as ao,d2 as Mi,d3 as nr,d4 as xd,d5 as df,d6 as Si,d7 as uf,d8 as mf,d9 as pf,da as ff,db as bd,dc as yd,a as _t,dd as gf,de as xf,df as bf,dg as yf,dh as vf,Q as jf,W as kf,X as wf,di as Mf,dj as Sf,dk as sr,dl as Cf,dm as Nf,dn as Af,dp as Tf,dq as Lf,dr as ac,ds as ar,dt as Fa,du as Ef,dv as Pa,dw as oc,dx as If,dy as Ko,dz as Ao,n as Rf,dA as Ff,u as Ci,dB as ic,dC as Pf,dD as $f,Y as rc,dE as Df,dF as lc,dG as Of,dH as _f,dI as zf,dJ as Bf,dK as Ni,q as Kf,dL as Hf,dM as Wf,dN as Gf,dO as Ai,dP as qf,dQ as Uf,dR as Xf,dS as Vf,dT as Yf,dU as Qf,dV as Zf,dW as Jf,dX as Ti,dY as e0,dZ as cc,d_ as t0,d$ as n0,e0 as hc,e1 as s0,e2 as a0,e3 as Li,e4 as dc,e5 as uc,e6 as Ei,e7 as o0,e8 as i0,e9 as r0,ea as l0,eb as Ii,ec as c0,ed as h0,ee as d0,ef as u0,eg as m0,eh as p0,ei as f0,ej as g0,ek as x0,el as b0,em as y0,en as v0,eo as j0,ep as k0,eq as w0,er as M0,es as S0,et as C0,eu as N0,ev as A0,ew as T0,ex as L0,ey as E0,ez as I0,eA as R0,eB as F0,eC as P0,eD as $0,eE as mc,eF as D0,eG as O0,eH as pc,eI as fc,eJ as _0}from"./remote-8XzEAnAJ.js";import{u as ct,t as a,g as na}from"./i18n-C9zFX25m.js";import{r as R}from"./index-CKtv7gGE.js";import{Mesh as ut,SkinnedMesh as Or,Box3 as zt,Vector3 as oe,Matrix4 as At,Group as rn,Uint16BufferAttribute as vd,Float32BufferAttribute as Bt,BufferGeometry as Tt,BufferAttribute as Pt,MathUtils as zn,DirectionalLight as Zo,WebGLRenderer as _r,SRGBColorSpace as Jo,AgXToneMapping as jd,PCFSoftShadowMap as z0,Scene as zr,PMREMGenerator as kd,HemisphereLight as wd,PlaneGeometry as ei,ShadowMaterial as B0,PerspectiveCamera as Br,InstancedMesh as qs,DataTexture as K0,RGBAFormat as H0,RepeatWrapping as Md,LinearFilter as gc,CanvasTexture as Kr,NoColorSpace as Sd,LinearMipmapLinearFilter as Cd,InstancedBufferAttribute as or,DynamicDrawUsage as sa,MeshStandardMaterial as ns,ShaderMaterial as Ua,Color as Ue,DoubleSide as ys,AdditiveBlending as Hr,LinearSRGBColorSpace as xs,CapsuleGeometry as Nd,ConeGeometry as W0,CylinderGeometry as vs,TorusGeometry as Wr,SphereGeometry as Hn,BoxGeometry as Xa,MeshPhysicalMaterial as Ps,Vector2 as ra,LatheGeometry as Ad,FrontSide as Va,Quaternion as Qe,Vector4 as Is,InstancedInterleavedBuffer as Td,InterleavedBufferAttribute as In,InstancedBufferGeometry as G0,OneMinusSrcAlphaFactor as q0,OneFactor as U0,AddEquation as X0,CustomBlending as V0,NormalBlending as Y0,DetachedBindMode as Q0,OctahedronGeometry as ir,MeshBasicMaterial as fs,Line as Ri,LineBasicMaterial as xc,PointLight as Z0,Euler as rr,Bone as $a,Uint8BufferAttribute as bs,ShaderChunk as J0,Sphere as eg,LOD as tg,Skeleton as Fi,Object3D as ng,NearestFilter as sg,ACESFilmicToneMapping as ag,CircleGeometry as og,Raycaster as bc}from"./three.module-Bx43vjkH.js";import{bu as ig,u as Us,bv as yc,bw as rg,bx as lg,by as cg,bz as hg,bA as dg,bB as ug,bC as mg,bD as pg,bE as fg,bF as gg,ap as xg,bG as bg,bH as vc,Z as yg,s as vg}from"./api-Dnl2uaKO.js";import{R as Ld}from"./RoomEnvironment-Dmv_G5ka.js";import{i as jc,p as kc,g as jg,e as kg}from"./tool-D1FpErrX.js";import{rowProps as wg,rowKeyed as Mg,readProp as Sg,writeProp as Cg,keyAllAt as Ng,copyKeys as Ag,pasteKeys as Tg,easeKeys as Lg,nudgeKeys as wc}from"./timelineProps-0v-s69pw.js";import{b as Eg,c as Ig,A as Rg,d as Mc,a as Fg,t as Pg}from"./thumb-BTFsBS1u.js";import{f as $g,p as Dg}from"./shotFxAgent-DqngnGFb.js";import{a as Ed}from"./gltfLoader-U0Eebg7v.js";import{p as Og,C as _g,a as zg,b as Bg,c as Sc}from"./cameraPresets-Cfn7qhXK.js";import{m as Kg}from"./rigTrack-DMyqb0pb.js";import{D as Hg,s as Wg}from"./weaponDuel-DKAEYJjO.js";import{u as dt}from"./store-CpqHUcA2.js";import{r as Cc,a as Gg,b as qg,o as Ug,w as Xg,c as Vg,d as Yg,e as Pi,f as Qg,g as Zg,p as Jg,h as ex}from"./skin-xFScwS3T.js";import{renderRigViews as tx}from"./views-RQBs4zva.js";import{M as ua}from"./motionBlur-uAm030t9.js";import{t as nx}from"./timelineOps-DSSaDsU2.js";import{fitLibraryFingers as Nc}from"./library-BK0QVG4O.js";import"./rotoMaskStore-pE1AIt3I.js";import"./sceneTrack-DlAH5s74.js";import"./cameraTracker-DHdF8Zqx.js";import"./textAnimators-B9vO_hbP.js";import"./timelineComp-i-zdaoB2.js";import"./clientJobs-CuuUyhEy.js";function sx(e,n,s){const o=[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:o,h:i,min:o.map((r,l)=>r-i[l]),max:o.map((r,l)=>r+i[l])}}function ax(e,{cell:n=1}={}){const s=e.length,o=Array.from({length:s},()=>[]),i=Array.from({length:s},()=>[]),r=e.reduce((k,C)=>Math.min(k,C.min[1]),1/0),l=e.reduce((k,C)=>Math.max(k,C.max[1]),-1/0),h=Math.max(.03,n*.2),u=Math.max(.02,n*.06),m=e.map(k=>k.min[1]<=r+h);for(let k=0;k<s;k++){const C=e[k],S=(C.min[1]+C.max[1])/2,I=(C.max[1]-C.min[1])/2;for(let j=k+1;j<s;j++){const M=e[j],T=[0,1,2].map(A=>Math.min(C.max[A],M.max[A])-Math.max(C.min[A],M.min[A]));if(T[0]<-u||T[2]<-u||T[1]<-h)continue;const w=(M.min[1]+M.max[1])/2,E=(M.max[1]-M.min[1])/2,N=w-S;if(Math.abs(N)>.3*(I+E)){const A=N>0?M:C,O=H=>T[H]/Math.max(.001,A.max[H]-A.min[H]);if(O(0)<.45||O(2)<.45)continue;N>0?o[k].push(j):o[j].push(k)}else i[k].push(j),i[j].push(k)}}const d=new Uint8Array(s).fill(1);let f=lr({ups:o,side:i,ground:m},d,null);const p=Math.max(.05,n*.25);for(let k=0;k<3;k++){let C=!1;for(let S=0;S<s;S++){if(Number.isFinite(f[S]))continue;const I=e[S],j=(I.min[1]+I.max[1])/2,M=(I.max[1]-I.min[1])/2;for(let T=0;T<s;T++){if(T===S||i[S].includes(T)||o[S].includes(T)||o[T].includes(S))continue;const w=e[T];if(![0,1,2].every(A=>Math.min(I.max[A],w.max[A])-Math.max(I.min[A],w.min[A])>=-p))continue;const E=(w.min[1]+w.max[1])/2-j,N=(w.max[1]-w.min[1])/2;Math.abs(E)>.3*(M+N)?E>0?o[S].push(T):o[T].push(S):(i[S].push(T),i[T].push(S)),C=!0}}if(!C)break;f=lr({ups:o,side:i,ground:m},d,null)}const b=e.map(k=>[k.min[0],k.max[0],k.min[2],k.max[2]]),g=e.map(k=>[(k.min[0]+k.max[0])/2,(k.min[2]+k.max[2])/2]),v={n:s,ups:o,side:i,ground:m,need0:f,base:r,top:l,foot:b,plan:g,cell:n,tops:e.map(k=>k.max[1]),slender0:0},y=[...Array(s).keys()].filter(k=>Number.isFinite(f[k]));return v.slender0=y.length?Fd(v,y):0,v.stable0=ix(v,d,0),v}function ox(e,n){if(!e.adj){e.adj=Array.from({length:e.n},(s,o)=>[...e.ups[o],...e.side[o]]);for(let s=0;s<e.n;s++)for(const o of e.ups[s])e.adj[o].push(s)}return e.adj[n]}function Id(e,n){const s=new Int32Array(e.n).fill(-1),o=[];for(let i=0;i<e.n;i++){if(!n[i]||s[i]>=0)continue;const r=[i];s[i]=o.length;for(let l=0;l<r.length;l++)for(const h of ox(e,r[l]))n[h]&&s[h]<0&&(s[h]=o.length,r.push(h));o.push(r)}return o}function Rd(e,n){let s=1/0,o=-1/0,i=1/0,r=-1/0,l=0;for(const h of n){if(!e.ground[h])continue;l++;const u=e.foot[h];s=Math.min(s,u[0]),o=Math.max(o,u[1]),i=Math.min(i,u[2]),r=Math.max(r,u[3])}return{x0:s,x1:o,z0:i,z1:r,ng:l}}function Fd(e,n){const s=Rd(e,n),o=(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*o):0}function Pd(e,n,s,o){const i=Rd(e,n),r=i.ng;if(!r||n.length-r<2)return!0;let l=0,h=0;for(const m of n)l+=e.plan[m][0],h+=e.plan[m][1];l/=n.length,h/=n.length;const u=(e.cell??1)*.5*(1+s);return l<i.x0-u||l>i.x1+u||h<i.z0-u||h>i.z1+u||e.tops&&Fd(e,n)>Math.max(4,2*(e.slender0??0))*(1+.25*s)?!1:r/n.length>=o*(.3/(1+s))}function $d(e){let n=0,s=0;for(let o=0;o<e.n;o++)Number.isFinite(e.need0[o])&&(s++,e.ground[o]&&n++);return s?n/s:0}function ix(e,n,s){const o=$d(e);return Id(e,n).every(i=>Pd(e,i,s,o))}function lr(e,n,s){const o=n.length,i=new Float64Array(o).fill(1/0),r=[];for(let l=0;l<o;l++)n[l]&&e.ground[l]&&(i[l]=0,r.push(l));for(let l=0;l<r.length;l++){const h=r[l],u=i[h],m=u+1;for(const d of e.ups[h])n[d]&&i[d]>0&&(i[d]=0,r.push(d));for(const d of e.side[h])n[d]&&i[d]>m&&(!s||m<=s[d])&&(i[d]=m,r.push(d))}return i}const rx=e=>e>=.8?0:e>=.4?1:2;function lx(e,n,{slack:s=0,seed:o=1,centres:i}={}){const r=e.n,l=new Array(r).fill(null),h=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=qa(o|0,7717,5),f=[],p=e.stable0!==!1&&!!e.foot,b=p?$d(e):0;for(let v=0;v<r;v++)Number.isFinite(n[v])&&f.push({t:n[v],i:v});f.sort((v,y)=>v.t-y.t||v.i-y.i);let g=0;for(;g<f.length;){const v=f[g].t,y=[];for(;g<f.length&&f[g].t<=v+1e-9;){const S=f[g++];h[S.i]&&(h[S.i]=0,y.push(S.i))}if(!y.length)continue;const k=lr(e,h,u),C=i?nt.mul(y.reduce((S,I)=>nt.add(S,i[I]),[0,0,0]),1/y.length):null;for(let S=0;S<r;S++){if(!h[S]||!Number.isFinite(e.need0[S])||k[S]<=u[S])continue;h[S]=0;const I=i?Ys((i[S][1]-e.base)/m):.5,j=v+.05+.13*I+.07*ps(d,S,1);l[S]={t:j,from:C}}if(p){for(const S of Id(e,h))if(!Pd(e,S,s,b))for(const I of S){if(e.ground[I])continue;h[I]=0;const j=i?Ys((i[I][1]-e.base)/m):.5;l[I]={t:v+.08+.15*j+.07*ps(d,I,1),from:C}}}}return l}function cx(e,n,{base:s=0,cell:o=1}={}){const i=Math.max(.05,o*.25),r=new Map,l=(d,f)=>`${d},${f}`,h=(d,f,p,b,g)=>{const v=[];for(let y=Math.floor((d-p*g)/i);y<=Math.floor((d+p*g)/i);y++)for(let k=Math.floor((f-b*g)/i);k<=Math.floor((f+b*g)/i);k++)v.push(l(y,k));return v};for(const d of n)for(const f of h(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,o*.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 b of d.dirs??[[1,0,0]])for(let g=0;g<=8;g++){const v=d.x+b[0]*m*g,y=d.z+b[2]*m*g,k=h(v,y,d.hx,d.hz,.6),C=k.reduce((I,j)=>Math.max(I,r.get(j)??s),s),S=C+.45*m*g;(!p||S<p.score-1e-9)&&(p={x:v,z:y,y:Math.min(d.top,C+f),foot:k,score:S})}u.set(d.i,{x:p.x,z:p.z,y:p.y});for(const b of p.foot)r.set(b,Math.max(r.get(b)??s,p.y+f*.9))}return u}function hx(e,n,s,{gravity:o=9.8,seed:i=1,crumble:r=.6}={}){if(!e||!(s>=e.t))return null;const l=s-e.t,h=Math.max(.5,o),u=Math.max(0,e.p0[1]-e.land),m=Math.sqrt(2*u/h),d=Math.min(l,m),f=m>1e-6?d/m:1,p=Sm(u,0,h,l,.12),b=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*b,v=e.p0[2]+(e.to[1]-e.p0[2])*f+e.dir[2]*.4*b,y=qa(i|0,n,4441),k=(.25+.9*ps(y,1,1))*(.4+.6*r),C=nt.norm([e.dir[2]+(ps(y,2,1)-.5)*.3,0,-e.dir[0]+(ps(y,3,1)-.5)*.3]),S=k*Vh(0,1,f)+(l>m?.15*k*b:0);return{pos:[g,e.land+p.y,v],axis:Number.isFinite(C[0])?C:[1,0,0],angle:S,landed:l>=m}}function dx(e,n,s,{base:o=0,cell:i=1,seed:r=1,centre:l=null}={}){const h=qa(r|0,3301,7),u=[],m=n.map((f,p)=>{if(!f)return null;const b=e[p],g=f.from??b.c,v=[g[0]-b.c[0],0,g[2]-b.c[2]],y=Math.hypot(v[0],v[2]),k=ps(h,p,1)*Math.PI*2,C=(ps(h,p,2)-.5)*.9,S=y>1e-4?nt.norm([v[0]/y+Math.cos(k)*.25,0,v[2]/y+Math.sin(k)*.25]):[Math.cos(k),0,Math.sin(k)],I=l?[b.c[0]-l[0],0,b.c[2]-l[2]]:[Math.cos(k+1),0,Math.sin(k+1)],j=Math.hypot(I[0],I[2]),M=j>1e-4?[I[0]/j,0,I[2]/j]:[Math.cos(k+1),0,Math.sin(k+1)],T=(w,E)=>[w[0]*Math.cos(E)-w[2]*Math.sin(E),0,w[0]*Math.sin(E)+w[2]*Math.cos(E)];return u.push({i:p,t:f.t,x:b.c[0],z:b.c[2],hx:b.h[0],hz:b.h[2],hy:Math.min(b.h[1],Math.max(b.h[0],b.h[2])*1.2),top:b.c[1],dirs:[S,T(M,C),T(M,C+.8),T(M,C-.8)]}),{t:f.t,p0:[...b.c],dir:S,to:[b.c[0],b.c[2]],land:o,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 cx(u,d,{base:o,cell:i}))m[f]&&(m[f].land=p.y,m[f].to=[p.x,p.z]);return m}function ux(e,{mode:n="pancake",start:s=0,duration:o=4,yaw:i=0,crumble:r=.6,seed:l=1,cell:h=1,gone:u=null,gravity:m=9.8}={}){const d=e.reduce((w,E)=>Math.min(w,E.min[1]),1/0),f=e.reduce((w,E)=>Math.max(w,E.max[1]),-1/0),p=Math.max(.3,o),b=Math.max(.1,f-d),g=.17+.13*(1-r),v=[0,2].map(w=>e.reduce((E,N)=>Math.min(E,N.min[w]),1/0)),y=[0,2].map(w=>e.reduce((E,N)=>Math.max(E,N.max[w]),-1/0)),k=[(v[0]+y[0])/2,d,(v[1]+y[1])/2],C=i*Math.PI/180,S=[Math.sin(C),0,Math.cos(C)],I=e.reduce((w,E)=>Math.max(w,...[0,1].flatMap(N=>[0,1].map(A=>(N?E.max[0]:E.min[0])*S[0]+(A?E.max[2]:E.min[2])*S[2]))),-1/0)-(k[0]*S[0]+k[2]*S[2]),j=[k[0]+S[0]*I,d,k[2]+S[2]*I],M=[S[2],0,-S[0]],T={mode:px.has(n)?n:"pancake",t0:s,D:p,base:d,top:f,H:b,c:g,centre:k,pivot:j,dir:S,axis:M,ext:I,seed:l|0,crumble:r,cell:h};if(T.mode==="pancake"){const w=.008333333333333333,E=Math.max(.5,m),N=Math.max(.3,h),A=Math.max(.3,h*1.5),O=e.map($=>`${Math.floor($.c[0]/A)},${Math.floor($.c[2]/A)}`),H=new Map;e.forEach(($,W)=>{const z=O[W];H.has(z)||H.set(z,[]),H.get(z).push(W)});const D=new Map;for(const[$,W]of H){const z=[f];let Y=f,J=0;for(let V=1;Y>d&&V<7200;V++){const K=s+V*w,G=Ys((K-s)/p),_=b*1.6*Math.pow(Math.max(G,.02),.6)/p;J=W.some(Q=>e[Q].c[1]<=Y&&e[Q].c[1]>=Y-N&&!(u&&u[Q]<=K))?Math.max(_,J+E*.6*w):J+E*w,Y=Math.max(d,Y-J*w),z.push(Y)}D.set($,z)}T.fronts=D,T.colOf=O,T.dt=w,T.starts=e.map(($,W)=>{const z=D.get(O[W]),Y=z.findIndex(J=>J<$.c[1]);return s+(Y<0?z.length:Y)*w})}else T.starts=e.map(()=>s);return T}const mx=(e,n,s)=>{const o=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>=o.length-1?o[o.length-1]:o[r]+(o[r+1]-o[r])*(i-r)},px=new Set(["pancake","topple","base"]),fx=(e,n,s)=>{const o=Math.cos(s),i=Math.sin(s),r=nt.dot(n,e),l=nt.cross(n,e);return[e[0]*o+l[0]*i+n[0]*r*(1-o),e[1]*o+l[1]*i+n[1]*r*(1-o),e[2]*o+l[2]*i+n[2]*r*(1-o)]};function Ac(e,n,s,o){if(!e||!(o>=e.starts[s]))return null;const i=qa(e.seed,s,6067),r=g=>ps(i,g,1),l=Ys((o-e.t0)/e.D),h=e.crumble,u=e.base+Math.min(n.h[1],Math.max(n.h[0],n.h[2]))*.55,m=nt.norm([n.c[0]-e.centre[0]+(r(1)-.5)*.6,0,n.c[2]-e.centre[2]+(r(2)-.5)*.6]),d=nt.norm([r(3)-.5,(r(4)-.5)*.4,r(5)-.5]);if(e.mode==="topple"){const g=Math.PI/2*l*l,v=nt.sub(n.c,e.pivot),y=nt.add(e.pivot,fx(v,e.axis,g)),k=Math.max(0,o-(e.t0+e.D)),C=(1-Math.exp(-2.5*k))/2.5,S=Vh(.55,1,l),I=h*e.cell*(.4+1.2*r(6)),j=nt.add(nt.mul(e.dir,(.8+2.2*r(7))*h*C*2),nt.mul(m,I*S*.5+h*C*r(8))),M=nt.add(y,j);return M[1]=Math.max(u,M[1]),{pos:M,axis:e.axis,angle:g,extra:{axis:d,angle:h*(S*.6+C*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=Ys((g-v)/Math.max(.2,e.cell*2)))}else{const g=mx(e,s,o),v=n.c[1];f=g>=v?v:g+(v-g)*e.c;const y=e.base+(v-e.base)*e.c;p=v-y>1e-6?Ys((v-f)/(v-y)):1}f=Math.max(u,f);const b=(.15+1.1*h)*e.cell*(.5+r(10))*p;return{pos:[n.c[0]+m[0]*b,f,n.c[2]+m[2]*b],axis:d,angle:p*(.15+1.1*h)*(.3+r(11))}}function gx(e,{blasts:n=[],collapses:s=[],falls:o=[]}={}){const i=new Array(e).fill(null),r=(l,h)=>{(!i[l]||h.t<i[l].t-1e-9||Math.abs(h.t-i[l].t)<=1e-9&&Tc[h.kind]<Tc[i[l].kind])&&(i[l]=h)};for(const l of n)for(let h=0;h<e;h++){const u=l.hits[h];u&&r(h,{kind:"hit",e:l.e,t:u.t})}for(let l=0;l<e;l++)o[l]&&r(l,{kind:"fall",e:-1,t:o[l].t});for(const l of s)for(let h=0;h<e;h++)r(h,{kind:"collapse",e:l.e,t:l.plan.starts[h]});return i}const Tc={hit:0,fall:1,collapse:2};function xx(e,n){const s=new Float64Array(e).fill(1/0);for(const o of n)for(let i=0;i<e;i++){const r=o.hits[i];r&&r.t<s[i]&&(s[i]=r.t)}return s}function bx(e){const n=Math.floor(e.length/3);if(n<4)return null;const s=j=>[e[j*3],e[j*3+1],e[j*3+2]];let o=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let j=0;j<n;j++)for(let M=0;M<3;M++)o[M]=Math.min(o[M],e[j*3+M]),i[M]=Math.max(i[M],e[j*3+M]);const r=Math.max(1e-9,...i.map((j,M)=>j-o[M])),l=r*1e-7;let h=0;for(let j=1;j<n;j++)e[j*3]<e[h*3]&&(h=j);let u=-1,m=0;for(let j=0;j<n;j++){const M=nt.dist(s(j),s(h));M>m+l&&(m=M,u=j)}if(u<0)return null;let d=-1,f=0;const p=nt.sub(s(u),s(h));for(let j=0;j<n;j++){const M=nt.len(nt.cross(p,nt.sub(s(j),s(h))));M>f+l*r&&(f=M,d=j)}if(d<0)return null;const b=nt.cross(p,nt.sub(s(d),s(h)));let g=-1,v=0;for(let j=0;j<n;j++){const M=Math.abs(nt.dot(b,nt.sub(s(j),s(h))));M>v+l*r*r&&(v=M,g=j)}if(g<0||v<l*r*r*10)return null;const y=[],k=(j,M,T)=>{const w=nt.cross(nt.sub(s(M),s(j)),nt.sub(s(T),s(j))),E=nt.len(w)||1,N=nt.mul(w,1/E);return{v:[j,M,T],n:N,d:nt.dot(N,s(j)),alive:!0}},C=nt.mul(nt.add(nt.add(s(h),s(u)),nt.add(s(d),s(g))),.25);for(const[j,M,T]of[[h,u,d],[h,u,g],[h,d,g],[u,d,g]]){let w=k(j,M,T);nt.dot(w.n,C)-w.d>0&&(w=k(j,T,M)),y.push(w)}const S=new Set([h,u,d,g]);for(let j=0;j<n;j++){if(S.has(j))continue;const M=s(j),T=[];for(const E of y)E.alive&&nt.dot(E.n,M)-E.d>l&&T.push(E);if(!T.length)continue;const w=new Map;for(const E of T){E.alive=!1;for(let N=0;N<3;N++){const A=E.v[N],O=E.v[(N+1)%3],H=`${O},${A}`;w.has(H)?w.delete(H):w.set(`${A},${O}`,[A,O])}}for(const[E,N]of w.values())y.push(k(E,N,j))}const I=[];for(const j of y)j.alive&&I.push(...j.v);return I.length?I:null}function yx(e,n,s,o=48){const i=Math.floor(e.length/3),r=Math.max(1,Math.ceil(i/o)),l=[],h=nt.norm(n),u=nt.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]+h[0]*u,d[1]+h[1]*u,d[2]+h[2]*u)}return l}const zs=e=>Array.isArray(e)&&e.length===3&&e.every(n=>typeof n=="number"&&Number.isFinite(n)&&Math.abs(n)<=1e6),jn=e=>{throw new Error(e)};function vx(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))&&jn("Đề xuất AI không hợp lệ."),(!Number.isFinite(e.duration)||e.duration<n.duration||e.duration>1e7)&&jn("Thời lượng đề xuất không hợp lệ.");for(const o of e.additions||[])(!o||o.kind!=="box"||typeof o.id!="string"||!/^agent-block-[a-zA-Z0-9_-]{1,96}$/.test(o.id)||n.items.some(i=>i.id===o.id)||!zs(o.position)||!zs(o.scale)||o.scale.some(i=>i<.1||i>100)||typeof o.name!="string"||o.name.length>80)&&jn("Khối Agent không hợp lệ.");const s=new Set;for(const o of e.tracks){s.has(o.subjectId)&&jn("AI trả về track trùng lặp."),s.add(o.subjectId);const i=n.items.find(l=>l.id===o.subjectId);if(o.subjectId!=="camera"&&(!i||i.locked)&&jn("Đối tượng không tồn tại hoặc đã khóa."),(!Array.isArray(o.keys)||!o.keys.length||o.keys.length>200)&&jn("Số key không hợp lệ."),o.replaceRange!=null){const l=o.replaceRange;(!Number.isFinite(l.start)||!Number.isFinite(l.end)||l.start<0||l.end<=l.start||l.end>e.duration||o.keys[0].seconds!==l.start||o.keys.at(-1).seconds!==l.end)&&jn("Đoạn sửa phải có key ở cả hai đầu."),o.keys.some(h=>h.seconds<l.start||h.seconds>l.end)&&jn("Key nằm ngoài đoạn sửa.")}let r=-1;for(const l of o.keys)(!Number.isFinite(l.seconds)||l.seconds<0||l.seconds>e.duration||l.seconds<=r||!zs(l.position))&&jn("Thời điểm hoặc vị trí key không hợp lệ."),r=l.seconds,o.subjectId==="camera"?(!zs(l.target)||!Number.isFinite(l.lens)||l.lens<14||l.lens>200||!Number.isFinite(l.roll)||Math.abs(l.roll)>36e3||l.position.every((h,u)=>Math.abs(h-l.target[u])<1e-8))&&jn("Thông số camera không hợp lệ."):(!zs(l.rotation)||!zs(l.scale)||l.scale.some(h=>h<.01||h>1e3))&&jn("Góc xoay hoặc kích thước không hợp lệ."),l.pose!==void 0&&!["Ngồi","Đứng"].includes(l.pose)&&jn("Tư thế key không hợp lệ.")}return e}function Lc(e,n,s,o={},i=[]){const r=e.shots.find(h=>h.id===e.activeShot),l=Yh(r,s);return{placement:{camera:r.position,colliders:i.slice(0,400).map(h=>({id:h.id,itemId:h.itemId,name:h.name,kind:h.kind,min:h.min.map(u=>Math.round(u*1e3)/1e3),max:h.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(h=>({...h,seconds:h.time*r.duration}))||[]},items:e.items.map(h=>{const u=gs(h,r,s),m=o[h.id],d=[...r.objectKeys?.[h.id]||[]].sort((b,g)=>b.time-g.time),f=d.slice(1).map((b,g)=>{const v=d[g],y=(b.time-v.time)*r.duration,k=Math.hypot(...b.position.map((C,S)=>C-v.position[S]));return{start:v.time*r.duration,end:b.time*r.duration,distance:k,speed:y>0?k/y:null}}),p=Object.entries(o).filter(([b])=>b!==h.id).map(([b,g])=>{const v=m?u.position[0]-m.min[0]:.5,y=m?m.max[0]-u.position[0]:.5,k=m?u.position[2]-m.min[2]:.5,C=m?m.max[2]-u.position[2]:.5,S=(g.min[0]+g.max[0])/2,I=(g.min[2]+g.max[2])/2,j=[[g.min[0]-y-.3,u.position[1],I],[g.max[0]+v+.3,u.position[1],I],[S,u.position[1],g.min[2]-C-.3],[S,u.position[1],g.max[2]+k+.3]];return{targetId:b,worldAxisPoints:j,nearest:j.reduce((M,T)=>Math.hypot(T[0]-u.position[0],T[2]-u.position[2])<Math.hypot(M[0]-u.position[0],M[2]-u.position[2])?T:M)}});return{motionProfile:m?.motionProfile||null,segments:f,bounds:m||null,approachPoints:p.slice(0,6),baseTransform:{position:h.position,rotation:h.rotation,scale:h.scale},...h.kind==="person"?{pose:{hipL:h.pose.hipL,hipR:h.pose.hipR,kneeL:h.pose.kneeL,kneeR:h.pose.kneeR,lean:h.pose.lean},...h.figure?{figure:h.figure}:{}}:{},...h.kind==="set"&&h.set?{set:{id:h.set.id}}:{},id:h.id,name:h.name,kind:h.kind,locked:h.locked,hidden:h.hidden,position:u.position,rotation:u.rotation,scale:u.scale,keys:r.objectKeys?.[h.id]?.map(b=>({...b,seconds:b.time*r.duration}))||[]}})}}function $i(e,n){const s=e.shots.find(l=>l.id===e.activeShot);vx(n,{duration:s.duration,items:e.items});const o=s.duration/n.duration,i={...s,duration:n.duration,objectKeys:Object.fromEntries(Object.entries(s.objectKeys||{}).map(([l,h])=>[l,h.map(u=>({...u,time:u.time*o}))])),cameraKeys:s.cameraKeys?.map(l=>({...l,time:l.time*o})),...s.focus?.keys?{focus:{...s.focus,keys:s.focus.keys.map(l=>({...l,time:Math.min(1,l.time*o)}))}}:{}};for(const l of n.tracks){const h=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:vt(),time:f.seconds/n.duration,position:f.position,target:f.target,lens:f.lens,roll:f.roll}));i.cameraKeys=[...(i.cameraKeys||[]).filter(f=>h(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:vt(),time:m.seconds/n.duration,position:m.position,rotation:m.rotation,scale:m.scale,...m.stance?{stance:m.stance}:{},...m.pose&&Kn[m.pose]?{pose:{...Kn[m.pose]}}:{}}));i.objectKeys[l.subjectId]=[...(i.objectKeys[l.subjectId]||[]).filter(m=>h(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,h)=>({...Mn("box",e.items.length+h),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 Da=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}}),Ls=Object.freeze({width:[.85,1.2],length:[.85,1.2],eyes:[.7,1.4]}),Ec=e=>!!e&&typeof e=="object"&&!Array.isArray(e),jx=/^#[0-9a-fA-F]{6}$/,rs=(e,n)=>{throw Object.assign(new Error(`${e}: ${n}`),{status:400})};function To(e={}){Ec(e)||rs("character","object");for(const u of Object.keys(e))["preset","figure","look","face","color"].includes(u)||rs("character",`unknown field "${u}"`);const n=e.preset!=null?Qh(String(e.preset)):null;e.preset!=null&&!n&&rs("character.preset","unknown character preset");const s={height:1.75,face:"simple",...n?.figure??{},...e.figure!=null?Cm(e.figure,"character.figure"):{}},o=Ol({...n?.look??{},...e.look!=null?Ol(e.look,"character.look"):{}},"character.look");e.color!==void 0&&!(typeof e.color=="string"&&jx.test(e.color))&&rs("character.color","#rrggbb");const i=(e.color??s.skin??n?.color??Lr[2]).toLowerCase();s.skin||(s.skin=i);const r=e.face??{};Ec(r)||rs("character.face","object");for(const u of Object.keys(r))["preset","width","length","eyes"].includes(u)||rs("character.face",`unknown field "${u}"`);r.preset!==void 0&&!Da[r.preset]&&rs("character.face.preset",Object.keys(Da).join("|"));const l=Da[r.preset??"oval"],h={preset:r.preset??"oval"};for(const[u,[m,d]]of Object.entries(Ls)){const f=r[u]===void 0?l[u]:r[u];(typeof f!="number"||!Number.isFinite(f))&&rs(`character.face.${u}`,`number ${m}..${d}`),h[u]=+Math.min(d,Math.max(m,f)).toFixed(3)}return{...n?{preset:n.id}:{},figure:s,look:o,color:i,face:h}}function kx(e){const n=JSON.stringify(e);let s=2166136261;for(let o=0;o<n.length;o++)s^=n.charCodeAt(o),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}const wx=e=>`gen:character:${kx(e)}`,cr={torso:"torso",head:"head",eyes:"head",eyeL:"head",eyeR:"head"};for(const e of["L","R"])Object.assign(cr,{[`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 Mx(){return{...Object.fromEntries(Object.entries(Kn.Đứ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 Sx(e){const n=Wt({height:1.8,head:1,build:1,...e.figure}),s=Zh(Mx(),e.color,n,e.look);s.scale.setScalar(n.height/Nm(n));const o=s.getObjectByName("head"),i=s.getObjectByName("eyes");o&&o.scale.set(o.scale.x*e.face.width,o.scale.y*e.face.length,o.scale.z*(e.face.width+1)/2),i&&i.scale.setScalar(e.face.eyes),s.updateMatrixWorld(!0);const r=M=>{for(let T=M;T;T=T.parent)if(cr[T.name])return cr[T.name];return"torso"},l=M=>s.getObjectByName(M).getWorldPosition(new oe),h=[];s.traverse(M=>{if(!(M instanceof ut)||!M.visible||!M.geometry.getAttribute("position"))return;let T=!1;for(let E=M;E;E=E.parent)E.visible||(T=!0);if(T)return;if(M instanceof Or){h.push(Nx(M));return}const w=M.geometry.clone();w.morphAttributes={};for(const E of Object.keys(w.attributes))E!=="position"&&E!=="normal"&&E!=="uv"&&w.deleteAttribute(E);w.applyMatrix4(M.matrixWorld),h.push({geo:w,material:M.material,joint:r(M),name:M.name||r(M)})});const u=new zt,m=new Map;for(const M of h){if(M.geo.computeBoundingBox(),u.union(M.geo.boundingBox),M.weights){const w=M.geo.getAttribute("position"),E=new oe;for(let N=0;N<w.count;N++){const A=Na[M.weights.index[N*4]][0],O=m.get(A)??new zt;O.expandByPoint(E.fromBufferAttribute(w,N)),m.set(A,O)}continue}const T=m.get(M.joint)??new zt;T.union(M.geo.boundingBox),m.set(M.joint,T)}const d={};for(const[M]of Na)s.getObjectByName(M)&&(d[M]=l(M));d.headTop=new oe(d.head.x,m.get("head").max.y,d.head.z);for(const M of["L","R"]){const T=m.get(`wrist${M}`)??new zt().setFromCenterAndSize(d[`wrist${M}`],new oe(.05,.2,.05));d[`handTip${M}`]=new oe(d[`wrist${M}`].x,T.min.y,d[`wrist${M}`].z);const w=m.get(`foot${M}`)??new zt().setFromCenterAndSize(d[`foot${M}`],new oe(.1,.1,.25));d[`toe${M}`]=new oe(d[`foot${M}`].x,w.min.y,w.max.z)}const f=u.getSize(new oe),p=2/Math.max(f.x,f.y,f.z),b=u.getCenter(new oe),g=new At().makeScale(p,p,p).multiply(new At().makeTranslation(-b.x,-u.min.y,-b.z)),v=M=>Math.round(M*1e4)/1e4,y=Na.map(([M,T])=>({name:M,parent:T,pos:d[M].clone().applyMatrix4(g).toArray().map(v)})),k=Yo({kind:"humanoid",source:"template",joints:y,seed:1}),C=new Map(k.joints.map((M,T)=>[M.name,T])),S=Am(k),I=new rn;let j=0;for(const M of h){M.geo.applyMatrix4(g);const T=M.geo.getAttribute("position").count,w=C.get(M.joint)??0,E=new Uint16Array(T*4),N=new Float32Array(T*4);if(M.weights)for(let O=0;O<T*4;O++)E[O]=C.get(Na[M.weights.index[O]][0])??0,N[O]=M.weights.weight[O];else for(let O=0;O<T;O++)E[O*4]=w,N[O*4]=1;M.geo.setAttribute("skinIndex",new vd(E,4)),M.geo.setAttribute("skinWeight",new Bt(N,4)),M.geo.userData.rigWeights=S,M.geo.computeBoundingBox(),M.geo.computeBoundingSphere();const A=new ut(M.geo,M.material);A.name=M.name,A.castShadow=!0,A.receiveShadow=!0,I.add(A),j+=T}return I.userData.normalizedHeight=f.y*p,{root:I,rig:k,normalizedHeight:f.y*p,height:+f.y.toFixed(4),vertices:j}}const Dd=new Map(Na.map(([e],n)=>[e,n]));function Cx(e){if(Dd.has(e))return[[e,1]];const n=/^(arm|fore|wrist|thigh|shin|foot)Half([LR])$/.exec(e);if(n){const o={arm:"torso",fore:"arm",wrist:"fore",thigh:"torso",shin:"thigh",foot:"shin"},i=o[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 Nx(e){const n=e.geometry,s=n.getAttribute("position").count,o=new Float32Array(s*3),i=new oe,r=n.getAttribute("skinIndex"),l=n.getAttribute("skinWeight"),h=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),o[f*3]=i.x,o[f*3+1]=i.y,o[f*3+2]=i.z;const p=new Map;for(let v=0;v<4;v++){const y=l.getComponent(f,v);if(y)for(const[k,C]of Cx(h[r.getComponent(f,v)]??"torso")){const S=Dd.get(k)??0;p.set(S,(p.get(S)??0)+y*C)}}const b=[...p].sort((v,y)=>y[1]-v[1]).slice(0,4),g=b.reduce((v,y)=>v+y[1],0)||1;b.forEach(([v,y],k)=>{u[f*4+k]=v,m[f*4+k]=y/g})}const d=new Tt;return d.setAttribute("position",new Pt(o,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 Hs=new Map;function Od(e){const n=JSON.stringify(e);let s=Hs.get(n);if(!s)for(s=Sx(e),Hs.set(n,s);Hs.size>16;)Hs.delete(Hs.keys().next().value);return s}function _d(){Hs.clear()}const Ic=e=>Array.isArray(e)&&e.length===3&&e.every(n=>Number.isFinite(Number(n)))?e.map(Number):null;function Di(e,n){const s=e.getStage(),o=String(n.name||"Nhân vật").trim().slice(0,60)||"Nhân vật",i=s.items.find(f=>f.name===o&&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]])),b=n.face;r=To(n.preset!=null||!f?{...n.preset!=null?{preset:n.preset}:{},...p}:{figure:{...f.figure,...n.figure||{}},look:{...f.look,...n.look||{}},face:b?.preset?b:{...f.face,...b||{}},color:n.color??f.color})}catch(f){return{ok:!1,error:f.message}}const l=Od(r),h=l.height,u={model:{gcsUri:wx(r),name:`${o}.character`,height:h},gen:{kind:"character",spec:r},rig:l.rig,color:r.color,...Ic(n.position)?{position:Ic(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=Jh(s,{kind:"model",name:o,...u});m=f.id,e.setStage(p=>({...p,items:[...p.items,f]}))}const d=l.rig.joints.filter(f=>!Tm(l.rig.joints,f)).map(f=>f.name);return{ok:!0,name:o,id:m,rebuilt:!!i,height_m:h,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 Ax=[{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}],Tx=[{key:"width",vi:"Mặt rộng",lo:Ls.width[0],hi:Ls.width[1],step:.01},{key:"length",vi:"Mặt dài",lo:Ls.length[0],hi:Ls.length[1],step:.01},{key:"eyes",vi:"Mắt to",lo:Ls.eyes[0],hi:Ls.eyes[1],step:.01}];function Lx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=ct(),l=C=>r==="en"?C.en:C.vi,[h,u]=R.useState(()=>To({preset:"office-f"})),m=(n?.gen?.kind==="character"?n.gen.spec:null)??h,d=R.useRef(void 0),f=C=>{let S;try{S=To({figure:{...m.figure,...C.figure||{}},look:C.look??m.look,face:{...m.face,...C.face||{}},color:C.color??m.color})}catch(I){i(I.message);return}if(!n){u(S);return}window.clearTimeout(d.current),d.current=window.setTimeout(()=>{const I=Di(e,{name:n.name,figure:S.figure,look:S.look,face:S.face,color:S.color});I.ok||i(String(I.error))},250)},p=C=>{if(!Qh(C))return;if(!n){u(To({preset:C}));return}const I=Di(e,{name:n.name,preset:C});I.ok||i(String(I.error))},b=()=>{const C=Di(e,{name:Ex(e,a("Nhân vật")),figure:m.figure,look:m.look,face:m.face,color:m.color,position:s()});C.ok&&C.id?o(C.id):i(String(C.error))},g=m.figure,v=(C,S,I)=>t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(C.vi)}),t.jsx("input",{type:"range","aria-label":a(C.vi),min:C.lo,max:C.hi,step:C.step,value:S,onChange:j=>I(+j.target.value)}),t.jsx("input",{type:"number","aria-label":`${a(C.vi)} (${a("số")})`,min:C.lo,max:C.hi,step:C.step,value:S,onChange:j=>{const M=+j.target.value;Number.isFinite(M)&&I(Math.min(C.hi,Math.max(C.lo,M)))}})]},C.key),y=m.look,k=(C,S,I,j)=>{const M=y[C];return t.jsxs("div",{className:"shot-char-piece",children:[t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a(j)}),t.jsxs("select",{"aria-label":a(j),value:M?String(M[I]):"",onChange:T=>{const w=T.target.value,E={...m.look};w?E[C]={...M||{color:C==="hair"?"#2a211b":"#4a6fa5"},[I]:w}:delete E[C],f({look:E})},children:[t.jsx("option",{value:"",children:a("Không")}),Object.entries(S).map(([T,w])=>t.jsx("option",{value:T,children:l(w)},T))]})]}),M&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Màu {0}",[a(j).toLowerCase()])}),t.jsx("input",{type:"color","aria-label":a("Màu {0}",[a(j).toLowerCase()]),value:M.color,onChange:T=>f({look:{...m.look,[C]:{...M,color:T.target.value}}})})]})]},C)};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:a("Nhân vật mới")]}),t.jsx("small",{className:"muted",children:n?a("Đang sửa: thay đổi dựng lại ngay, đã gắn xương người."):a("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:a("Mẫu nhân vật")}),t.jsxs("select",{"aria-label":a("Mẫu nhân vật"),value:m.preset??"",onChange:C=>p(C.target.value),children:[t.jsx("option",{value:"",children:a("Tự chỉnh")}),Lm.map(C=>t.jsx("option",{value:C.id,children:l(C.name)},C.id))]})]}),t.jsx("h4",{children:a("Dáng người")}),Ax.map(C=>v(C,Number(g[C.key]??(C.key==="height"?1.75:C.key==="shoulders"||C.key==="hips"?1:C.key==="sex"?+Po(g).fem.toFixed(2):C.key==="age"?Po(g).age:0)),S=>f({figure:{[C.key]:S}}))),t.jsx("div",{className:"shot-char-skins",role:"group","aria-label":a("Màu da"),children:Lr.map(C=>t.jsx("button",{type:"button","aria-label":C,"aria-pressed":m.color===C,className:m.color===C?"on":"",style:{background:C},onClick:()=>f({color:C,figure:{skin:C}})},C))}),t.jsx("h4",{children:a("Khuôn mặt")}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Kiểu mặt")}),t.jsx("select",{"aria-label":a("Kiểu mặt"),value:m.face.preset,onChange:C=>{const S=Da[C.target.value];f({face:{preset:C.target.value,width:S.width,length:S.length,eyes:S.eyes}})},children:Object.entries(Da).map(([C,S])=>t.jsx("option",{value:C,children:l(S)},C))})]}),Tx.map(C=>v(C,m.face[C.key],S=>f({face:{[C.key]:S}}))),t.jsx("h4",{children:a("Tóc & trang phục")}),k("hair",Em,"style","Tóc"),k("top",Im,"type","Áo"),k("bottom",Rm,"type","Quần / váy"),!n&&t.jsx("button",{className:"pill-btn primary",onClick:b,children:a("+ Tạo nhân vật (đã gắn xương)")}),n&&t.jsx("small",{className:"muted",children:a("Mở tab Rigging để xoay xương, hoặc dùng thư viện chuyển động như với ma-nơ-canh.")})]})}function Ex(e,n){const s=e.getStage();let o=n,i=2;for(;s.items.some(r=>r.name===o);)o=`${n} ${i++}`;return o}let kn=null,Bn,ds,Rc=null,Xs;const Fc=new Map,Oi=new Map;let Pc=Promise.resolve(),$c=0;const Dc=160,Oc=120;function Ix(){if(kn)return kn;kn=new _r({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),kn.outputColorSpace=Jo,kn.toneMapping=jd,kn.toneMappingExposure=1.15,kn.shadowMap.enabled=!0,kn.shadowMap.type=z0,kn.setClearColor(0,0),kn.setSize(Dc,Oc,!1),Bn=new zr;const e=new kd(kn);Rc=e.fromScene(new Ld,.04).texture,e.dispose(),Bn.environment=Rc,Bn.environmentIntensity=.7,Bn.add(new wd("#e8eeff","#5d5a55",.9));const n=new Zo("#fff4e4",2.4);return n.castShadow=!0,n.shadow.mapSize.set(512,512),n.shadow.bias=-4e-4,Bn.add(n,n.target),Xs=new ut(new ei(1,1),new B0({opacity:.32})),Xs.rotation.x=-Math.PI/2,Xs.receiveShadow=!0,Bn.add(Xs),ds=new Br(28,Dc/Oc,.05,2e3),kn}function Rx(e){const n=new zt,s=new At;return e.updateMatrixWorld(!0),e.traverse(o=>{if(o instanceof qs){const i=o.geometry.boundingBox??(o.geometry.computeBoundingBox(),o.geometry.boundingBox);for(let r=0;r<o.count;r++)o.getMatrixAt(r,s),n.union(i.clone().applyMatrix4(s).applyMatrix4(o.matrixWorld))}else o instanceof ut&&n.union(new zt().setFromObject(o))}),n}function Fx(e){const n=Ix(),s=Fm(Pm(e).recipe);Bn.add(s);try{const o=Rx(s);if(o.isEmpty())throw new Error(`empty model ${e}`);const i=o.getSize(new oe),r=o.getCenter(new oe),l=Math.max(.05,i.length()/2),h=zn.degToRad(ds.fov)/2,u=l/Math.sin(h)*.98,m=new oe(.62,.42,1).normalize();ds.position.copy(r).addScaledVector(m,u),ds.near=u/100,ds.far=u*4,ds.updateProjectionMatrix(),ds.lookAt(r),Xs.position.set(r.x,o.min.y+.001,r.z),Xs.scale.setScalar(l*6);const d=Bn.children.find(p=>p instanceof Zo);d.position.copy(r).add(new oe(-.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(Bn,ds),n.domElement.toDataURL("image/png")}finally{Bn.remove(s),s.traverse(o=>{o instanceof ut&&(o.geometry.dispose(),o.material.dispose())})}}function Px(e){const n=Fc.get(e);if(n)return Promise.resolve(n);const s=Oi.get(e);if(s)return s;if(!ed(e))return Promise.reject(new Error(`unknown model kit ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&$c>=o)return Promise.reject(new Error("thumbnail limit"));$c++;const i=Pc.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=Fx(e);Fc.set(e,h),r(h)}catch(h){l(h)}},16))).finally(()=>Oi.delete(e));return Pc=i.catch(()=>{}),Oi.set(e,i),i}const Ea="claude-opus-5-5",_c=e=>`${Math.round(e/1e3).toLocaleString("vi-VN")}k đ`;function oo({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:a("Ướ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),_c(e.vnd.low),_c(e.vnd.high),Ka])}):t.jsx("small",{className:"shot-hq-quote",children:a("Đang ước tính chi phí…")})}const zc=[["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 $x({host:e,item:n,onSelect:s,setError:o}){ct();const i=td(),[r,l]=R.useState(""),[h,u]=R.useState(""),[m,d]=R.useState("real"),[f,p]=R.useState(null),[b,g]=R.useState(null),[v,y]=R.useState(null),[k,C]=R.useState(""),[S,I]=R.useState(""),[j,M]=R.useState(!1),T=R.useRef(void 0),w=jc(n)&&n.gen?.kind==="code"?n.gen:null,E=["thinking","acting","rendering"].includes(i.phase),N=i.purpose==="model"&&(i.log.length>0||E),A=[...e.getStage().items].reverse().find(V=>jc(V));R.useEffect(()=>{g(null),y(null),C("")},[n?.id]);const O=async V=>{C("");try{g(await ig(Ea,V)),y(V)}catch(K){C(K.message)}},H=async V=>{if(!V){p(null);return}if(V.size>28e4||!["image/jpeg","image/png"].includes(V.type)){o(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const K=await new Promise((G,_)=>{const ee=new FileReader;ee.onload=()=>G(String(ee.result)),ee.onerror=()=>_(ee.error),ee.readAsDataURL(V)});p({name:V.name,data:K})},D=()=>{const V=r.trim();if(!V||E)return;const K=zc.find(_=>_[0]===m),G=`${V}
3
+ Style: ${K[2]}.${h.trim()?` Real size: ${h.trim()}.`:""}${f?" Match the attached reference photo.":""}`;i.start(G,f?.data||null,Ea,"model",{quality:"high"}),g(null),y(null)},$=()=>{const V=S.trim();if(!V||!w||E)return;const K=`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===Ea&&i.quality==="high"?i.followUp(K):i.start(K,null,Ea,"model",{quality:"high"}),I(""),g(null),y(null)},W=(V,K)=>{if(!w||!n)return;const G={...w.code.params,[V]:K};e.setStage(_=>({..._,items:_.items.map(ee=>ee.id===n.id&&ee.gen?.kind==="code"?{...ee,gen:{...ee.gen,code:{...ee.gen.code,params:G}}}:ee)})),window.clearTimeout(T.current),T.current=window.setTimeout(()=>{kc(e,{name:n.name,params:G,views:!1}).then(_=>{_.ok||o(String(_.error))})},250)},z=async()=>{if(!(!w||!n)){M(!0);try{const V=await kc(e,{name:n.name,seed:w.code.seed%2147483e3+1,views:!1});V.ok||o(String(V.error))}finally{M(!1)}}},Y=async()=>{if(!(!w||!n)){M(!0);try{const V=await jg(w.code),K=URL.createObjectURL(V),G=document.createElement("a");G.href=K,G.download=`${n.name.replace(/[^\p{L}\p{N}_-]+/gu,"_")||"model"}.glb`,G.click(),window.setTimeout(()=>URL.revokeObjectURL(K),4e3)}catch(V){o(V.message)}finally{M(!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:a("Chất lượng cao · Opus")}),E?a("Đang dựng…"):i.phase==="capped"?a("Đã dùng hết {0} credit của lượt này",[Ka]):i.phase==="done"?a("Xong"):i.phase==="error"?a("Lỗi"):i.phase==="cancelled"?a("Đã dừng"):""," · ",a("bước")," ",i.step," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-6).map((V,K)=>t.jsx("div",{className:"shot-mission-line",children:V},K)),i.phase==="capped"&&t.jsx("div",{className:"shot-mission-done",role:"status",children:a('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).',[Ka])}),i.error&&t.jsx("p",{role:"alert",children:i.error}),E&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>i.stop(),children:a("Dừng")}),!E&&!w&&A&&t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(A.id),children:a("Chỉnh model vừa dựng: {0}",[A.name])})]});return w&&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:a("Model dựng bằng code · Opus")})]}),w.prompt&&t.jsx("small",{className:"muted shot-hq-prompt",children:w.prompt}),(w.schema||[]).length>0?t.jsx("div",{className:"shot-model-params",children:(w.schema||[]).map(V=>t.jsx(Dx,{p:V,value:w.code.params[V.key]??V.default,onChange:K=>W(V.key,K)},V.key))}):t.jsx("small",{className:"muted",children:a("Model này không có thanh trượt tham số.")}),t.jsx("small",{className:"muted",children:a("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:j,onClick:()=>void z(),children:a("Biến thể khác (0 credit)")}),t.jsx("button",{type:"button",className:"pill-btn thin",disabled:j,onClick:()=>void Y(),children:a("Tải .glb")})]}),t.jsxs("label",{className:"shot-hq-field",children:[t.jsx("span",{children:a("Sửa bằng lời (AI · Opus)")}),t.jsx("textarea",{rows:3,maxLength:1500,value:S,disabled:E,placeholder:a("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"&&b?t.jsx(oo,{quote:b}):k?t.jsx(oo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:E||!S.trim(),onClick:()=>void O("edit"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:E||!S.trim()||v!=="edit",title:v!=="edit"?a("Xem ước tính chi phí trước"):"",onClick:$,children:a("Sửa (≈ {0}–{1} cr)",[b?.credits.low.toFixed(1)??"?",b?.credits.high.toFixed(1)??"?"])})]}),J,t.jsx("button",{type:"button",className:"pill-btn thin",onClick:()=>s(null),children:a("+ 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:a("Mô tả model")}),t.jsx("textarea",{rows:4,maxLength:3e3,value:r,disabled:E,placeholder:a("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:a("Kích thước thật (tuỳ chọn)")}),t.jsx("input",{value:h,maxLength:80,disabled:E,placeholder:a("vd: cao 12 cm"),onChange:V=>u(V.target.value)})]}),t.jsxs("label",{className:"shot-hq-field small",children:[t.jsx("span",{children:a("Phong cách")}),t.jsx("select",{value:m,disabled:E,onChange:V=>d(V.target.value),children:zc.map(([V,K])=>t.jsx("option",{value:V,children:a(K)},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:E,onChange:V=>{H(V.target.files?.[0]),V.target.value=""}}),t.jsx("span",{children:f?`🖼 ${f.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),f&&!E&&t.jsx("button",{type:"button",onClick:()=>p(null),children:"×"})]}),v==="build"&&b?t.jsx(oo,{quote:b}):k?t.jsx(oo,{quote:null,error:k}):null,t.jsxs("div",{className:"shot-hq-row",children:[t.jsx("button",{type:"button",className:"pill-btn thin",disabled:E||!r.trim(),onClick:()=>void O("build"),children:a("Ước tính chi phí")}),t.jsx("button",{type:"button",className:"pill-btn primary",disabled:E||!r.trim()||v!=="build",title:v!=="build"?a("Xem ước tính chi phí trước"):"",onClick:D,children:a("Dựng (≈ {0}–{1} cr)",[b?.credits.low.toFixed(1)??"?",b?.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:o=>s(Number(o.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:o=>s(o.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:o=>s(o.target.value),children:e.options.map(o=>t.jsx("option",{value:o,children:o},o))})]}):t.jsxs("label",{className:"shot-hq-param",children:[t.jsx("span",{children:e.label}),t.jsx("input",{type:"color",value:String(n),onChange:o=>s(o.target.value)}),t.jsx("output",{children:String(n)})]})}function Ox({host:e,item:n,ground:s,onSelect:o,setError:i}){ct();const[r,l]=R.useState("Sản phẩm"),[h,u]=R.useState(""),[m,d]=R.useState(null),[f,p]=R.useState(null),[b,g]=R.useState([]),[v,y]=R.useState(""),[k,C]=R.useState(null),S=async(N,A)=>{if(N){if(!/^image\/(png|jpeg|webp)$/.test(N.type)){i(a("Ảnh phải là PNG, JPG hoặc WEBP."));return}y(a("Đang tải ảnh lên…"));try{const O=await Us(N,void 0,"image");A({name:N.name,url:O.url})}catch(O){i(O.message)}finally{y("")}}},I=N=>Number(String(N).replace(",","."))/100,j=async()=>{if(!m){i(a("Chọn ảnh chính diện của sản phẩm."));return}if(!(I(h)>0)){i(a("Nhập chiều cao thật của sản phẩm (cm)."));return}y(a("Đang dựng sản phẩm…")),C(null);try{const{modelProduct:N}=await fn(async()=>{const{modelProduct:O}=await import("./productTools-ce-zyZO0.js");return{modelProduct:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),A=await N({image:m.url,...f?{back_image:f.url}:{},height_m:I(h),name:r.trim()||"Sản phẩm",position:s(),labels:b.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&&o(String(A.id)):i(String(A.error))}finally{y("")}},M=async()=>{if(n){y(a("Đang xuất GLB…"));try{const{saveGlb:N}=await fn(async()=>{const{saveGlb:O}=await import("./productTools-ce-zyZO0.js");return{saveGlb:O}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),A=await N({name:n.name},e);A.ok?C({file:String(A.file),url:String(A.url)}):i(String(A.error))}finally{y("")}}},T=async()=>{if(n?.set){y(a("Đang xuất GLB…"));try{const{recipeGlb:N}=await fn(async()=>{const{recipeGlb:W}=await import("./exportGlb-D3PrWUvi.js");return{recipeGlb:W}},__vite__mapDeps([17,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),{loadSetOf:A}=await fn(async()=>{const{loadSetOf:W}=await import("./remote-8XzEAnAJ.js").then(z=>z.fO);return{loadSetOf:W}},__vite__mapDeps([2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16])),O=e.engine()?.setRecipe(n.set.id)??await A(e)(n.set.id),H=await N(O),D=document.createElement("a"),$=URL.createObjectURL(H);D.href=$,D.download=`${n.name}.glb`,D.click(),setTimeout(()=>URL.revokeObjectURL($),5e3)}catch(N){i(N.message)}finally{y("")}}},w=(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:H=>void S(H.target.files?.[0],O)}),A?t.jsx("img",{src:A.url,alt:""}):t.jsx("em",{children:a("Chưa chọn")})]}),E=(N,A)=>g(O=>O.map(H=>H.key===N?{...H,...A}:H));return t.jsxs("div",{className:"shot-product",children:[t.jsx("p",{className:"shot-product-hint",children:a("Ả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:a("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:a("Chiều cao thật (cm)")}),t.jsx("input",{inputMode:"decimal",value:h,placeholder:"29",onChange:N=>u(N.target.value)})]}),w(a("Ảnh chính diện"),m,d),w(a("Ảnh mặt sau (không bắt buộc)"),f,p),t.jsxs("div",{className:"shot-product-labels",children:[t.jsx("b",{children:a("File thiết kế nhãn / bao bì")}),b.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&&E(N.key,{url:O.url,name:O.name}))}),t.jsxs("label",{children:[a("Đáy nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.bottom,onChange:A=>E(N.key,{bottom:A.target.value})})]}),t.jsxs("label",{children:[a("Cao nhãn (cm)"),t.jsx("input",{inputMode:"decimal",value:N.height,onChange:A=>E(N.key,{height:A.target.value})})]}),t.jsxs("label",{children:[a("Mặt"),t.jsxs("select",{value:N.side,onChange:A=>E(N.key,{side:A.target.value}),children:[t.jsx("option",{value:"0",children:a("Trước")}),t.jsx("option",{value:"180",children:a("Sau")})]})]}),t.jsxs("label",{children:[a("Bề mặt"),t.jsxs("select",{value:N.finish,onChange:A=>E(N.key,{finish:A.target.value}),children:[t.jsx("option",{value:"matte",children:a("Giấy mờ")}),t.jsx("option",{value:"gloss",children:a("Bóng")}),t.jsx("option",{value:"foil",children:a("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:["+ ",a("Thêm nhãn")]})]}),t.jsx("button",{type:"button",className:"shot-product-build",disabled:!!v,onClick:()=>void j(),children:a("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 M(),children:a("Lưu GLB vào Tài sản của tôi")}),t.jsx("button",{type:"button",disabled:!!v,onClick:()=>void T(),children:a("Tải .glb")}),k&&t.jsxs("span",{children:[a("Đã lưu")," ",k.file]})]}),v&&t.jsx("p",{className:"shot-product-busy",children:v})]})}function zd(){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 Bc={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"]},_x=[.01,.05,.1,.25,.5],zx={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 Bx(e){const{stage:n,selected:s}=e,o=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,h]=R.useState(r?"ai":i?"character":o?.set?.kit?.id===Aa?"hand":"library");R.useEffect(()=>{o?.set?.kit&&h(o.set.kit.id===Aa?"hand":"library")},[o?.id,o?.set?.kit?.id]),R.useEffect(()=>{i&&h("character")},[i?.id]),R.useEffect(()=>{r&&h("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":a("Dựng model"),children:[t.jsx("div",{className:"shot-model-tabs",role:"tablist",children:["library","hand",...nd()||i?["character"]:[],"product"].map(m=>t.jsx("button",{role:"tab","aria-selected":l===m,className:l===m?"on":"",onClick:()=>h(m),children:m==="library"?a("Thư viện model"):m==="hand"?a("Dựng tay"):m==="character"?a("Nhân vật"):a("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:()=>h("ai"),children:["✦ ",a("AI chất lượng cao")]}),l==="library"?t.jsx(Kx,{...e,host:u,item:o?.set?.kit&&o.set.kit.id!==Aa?o:void 0}):l==="hand"?t.jsx(Vx,{...e,item:o?.set?.kit?.id===Aa?o:void 0}):l==="character"?t.jsx(Lx,{host:u,item:i,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):l==="product"?t.jsx(Ox,{host:u,item:o,ground:e.ground,onSelect:e.onSelect,setError:e.setError}):t.jsx($x,{host:u,item:r,ground:e.ground,onSelect:e.onSelect,setError:e.setError}),o&&l!=="character"&&l!=="ai"&&l!=="product"&&t.jsx(Gx,{item:o,change:e.change})]})}function Kx({host:e,item:n,ground:s,onSelect:o,setError:i}){const r=ct(),l=w=>r==="en"?w.en:w.vi,[h,u]=R.useState("all"),[m,d]=R.useState(""),[f,p]=R.useState(null),[b,g]=R.useState({}),[v,y]=R.useState(!1),k=n?.set?.kit,C=ed(k?.id??f??""),S=k?k.params:b,I=R.useRef(void 0),j=(w,E)=>{if(!C)return;const N={...S,[w]:E};if(!k){g(N);return}window.clearTimeout(I.current),I.current=window.setTimeout(()=>{zl(e,{kit:C.id,params:N,name:n.name}).then(A=>{A.ok||i(String(A.error))})},280)},M=async()=>{if(C){y(!0);try{const w=await zl(e,{kit:C.id,params:b,name:Kd(e.getStage(),l(C)),position:s()});w.ok?o(String(w.id)):i(String(w.error))}catch(w){i(w.message)}finally{y(!1)}}},T=R.useMemo(()=>$m(m,h),[m,h]);return C?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:()=>{k&&o(null),p(null)},children:["← ",a("Thư viện")]}),t.jsx(Kc,{id:C.id,alt:l(C),small:!0}),t.jsx("strong",{children:l(C)}),k&&t.jsx("small",{className:"muted",children:a("Đang sửa: {0}",[n.name])})]}),t.jsx("div",{className:"shot-model-params",children:C.params.map(w=>t.jsx(Hx,{spec:w,value:S[w.key]??_l(C.id)[w.key],locale:r,onChange:E=>j(w.key,E)},w.key))}),!k&&t.jsx("button",{className:"pill-btn primary",disabled:v,onClick:()=>void M(),children:v?a("Đang dựng model…"):a("Thêm vào cảnh")}),t.jsx("small",{className:"muted",children:k?a("Thay đổi được dựng lại ngay trên cảnh. Kích thước tính bằng mét thật."):a("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":a("Tìm model"),placeholder:a("Tìm: nhà phố, sofa, ô tô…"),value:m,onChange:w=>d(w.target.value)}),t.jsx("div",{className:"shot-model-groups",role:"group","aria-label":a("Nhóm model"),children:[{id:"all",vi:"Tất cả",en:"All"},...Dm].map(w=>t.jsx("button",{className:`pill-btn thin${h===w.id?" on":""}`,"aria-pressed":h===w.id,onClick:()=>u(w.id),children:l(w)},w.id))}),t.jsxs("div",{className:"shot-model-grid",children:[T.map(w=>t.jsxs("button",{className:"shot-model-card","aria-label":`${a("Chọn model")} ${l(w)}`,onClick:()=>{p(w.id),g(_l(w.id))},children:[t.jsx(Kc,{id:w.id,alt:""}),t.jsx("strong",{children:l(w)}),t.jsxs("small",{children:[w.params.length," ",a("tham số")]})]},w.id)),!T.length&&t.jsx("p",{className:"muted",children:a("Không có model nào khớp.")})]})]})}function Kc({id:e,alt:n,small:s}){const[o,i]=R.useState(null),[r,l]=R.useState(!1),h=R.useRef(null);R.useEffect(()=>{if(r||!h.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(h.current),()=>m.disconnect()},[r]),R.useEffect(()=>{if(!r)return;let m=!0;return i(null),Px(e).then(d=>{m&&i(d)}).catch(()=>{}),()=>{m=!1}},[r,e]);const u=`shot-model-thumb${s?" small":""}`;return o?t.jsx("img",{className:u,src:o,alt:n,draggable:!1,"data-kit":e}):t.jsx("span",{ref:h,className:`${u} loading`,role:n?"img":void 0,"aria-label":n||void 0,"aria-hidden":n?void 0:!0,children:t.jsx(zd,{})})}function Hx({spec:e,value:n,locale:s,onChange:o}){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=>o(+l.target.value)}),t.jsx("input",{type:"number","aria-label":`${i} (${a("số")})`,min:e.min,max:e.max,step:e.step,value:r,onChange:l=>{const h=+l.target.value;Number.isFinite(h)&&o(Math.min(e.max,Math.max(e.min,h)))}})]})}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=>o(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=>o(r.target.value),children:e.allowed.map(r=>t.jsx("option",{value:r,children:Wx(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=>o(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=>o(r.target.value)})]})}const Wx=(e,n)=>Bc[e]?Bc[e][n==="en"?1:0]:e;function Bd({value:e,onChange:n,label:s,none:o}){const i=ct();return t.jsxs("select",{"aria-label":s,value:e,onChange:r=>n(r.target.value),children:[o&&t.jsx("option",{value:"",children:o}),sd.map(r=>t.jsx("optgroup",{label:i==="en"?r.en:r.vi,children:_m.filter(l=>l.cat===r.id).map(l=>t.jsx("option",{value:l.id,children:Ta(l,i==="en"?"en":"vi")},l.id))},r.id))]})}function Gx({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:a("Vật liệu cả model")}),t.jsx(Bd,{label:a("Vật liệu cả model"),value:s,none:a("Theo từng khối"),onChange:o=>n(i=>Gs(i,e.id,Qs,o?{preset:o}:null))})]})}function Kd(e,n){let s=n,o=2;for(;e.items.some(i=>i.name===s);)s=`${n} ${o++}`;return s}const Hc={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"}})},qx=[["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"]],Ux={union:"Hợp (gộp vào)",subtract:"Trừ (khoét)",intersect:"Giao (giữ phần chung)"},Xx={union:"gộp vào",subtract:"khoét",intersect:"giao với"};function Vx({stage:e,change:n,engine:s,onSelect:o,ground:i,setError:r,item:l}){const h=ct(),[u,m]=R.useState(null),[d,f]=R.useState(0),[p,b]=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),y=(N,A=l)=>{if(!A?.set)return;let O;try{O=Bl(N)}catch(D){r(D.message);return}m(O),s?.cacheSet(A.set.id,O);const H=Kl(O);n(D=>({...D,items:D.items.map($=>$.id===A.id?{...$,set:{...$.set,parts:O.parts.length,min:H.min,max:H.max}}:$)})),window.clearTimeout(v.current),v.current=window.setTimeout(()=>{yc(A.set.id,A.name,O).catch(D=>r(D.message))},400)},k=async()=>{const N=crypto.randomUUID(),A=Kd(e,a("Model tự dựng")),O=Bl({v:1,parts:[Hc.box()]});try{await yc(N,A,O)}catch($){r($.message);return}s?.cacheSet(N,O);const H=Kl(O),D=Jh(e,{kind:"set",name:A,color:"#9aa3a8",position:i(),set:{id:N,name:A,parts:1,min:H.min,max:H.max,kit:{id:Aa,params:{}}}});n($=>({...$,items:[...$.items,D]})),o(D.id)};if(!l||!u)return t.jsxs("div",{className:"shot-model-hand-empty",children:[t.jsx("p",{className:"muted",children:a("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 k(),children:a("+ Tạo model mới")}),l&&!u&&t.jsx("p",{className:"muted",children:a("Đang tải model…")})]});const C=u.parts,S=C[Math.min(d,C.length-1)],I=N=>+(Math.round(N/p)*p).toFixed(3),j=N=>y({...u,parts:C.map((A,O)=>O===d?{...A,...N}:A)}),M=N=>{const A=Hc[N]();y({...u,parts:[...C,A]}),f(C.length)},T=(N,A,O,H=-500)=>t.jsxs("div",{className:"shot-model-vec",children:[t.jsx("span",{children:N}),["X","Y","Z"].map((D,$)=>t.jsx("input",{type:"number",step:p,"aria-label":`${N} ${D}`,value:A[$],onChange:W=>{const z=+W.target.value;if(!Number.isFinite(z))return;const Y=[...A];Y[$]=Math.max(H,I(z)),O(Y)}},D))]}),w=N=>{const A=(N.outline||[]).map(H=>H[0]),O=(N.outline||[]).map(H=>H[1]);return[+(Math.max(...A)-Math.min(...A)).toFixed(3),+(Math.max(...O)-Math.min(...O)).toFixed(3),N.depth||.2]},E=(N,A)=>{const[O,H]=w(N),D=A[0]/(O||1),$=A[1]/(H||1),W=z=>z.map(([Y,J])=>[+(Y*D).toFixed(3),+(J*$).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:[C.length," ",a("khối")]}),t.jsxs("label",{className:"shot-model-snap",children:[a("Bước lưới"),t.jsx("select",{"aria-label":a("Bước lưới"),value:p,onChange:N=>b(+N.target.value),children:_x.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":a("Thêm khối"),children:qx.map(([N,A])=>t.jsxs("button",{className:"pill-btn thin",onClick:()=>M(N),children:["+ ",a(A)]},N))}),t.jsx("ul",{className:"shot-model-parts","aria-label":a("Các khối"),children:C.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:zx[N.shape]?.[h==="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:a("Tên khối")}),t.jsx("input",{"aria-label":a("Tên khối"),maxLength:40,value:S.name||"",onChange:N=>j({name:N.target.value.slice(0,40)})})]}),S.shape==="extrude"?T(a("Rộng / cao / dày (m)"),w(S),N=>j(E(S,N)),.005):T(a("Kích thước (m)"),S.size||[1,1,1],N=>j({size:N.map(A=>Math.max(.005,A))}),.005),T(a("Vị trí (m)"),S.position,N=>j({position:N})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Xoay quanh trục đứng (°)")}),t.jsx("input",{type:"number","aria-label":a("Xoay quanh trục đứng (°)"),step:15,value:S.rotation[1],onChange:N=>{const A=+N.target.value;Number.isFinite(A)&&j({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:a("Số bậc")}),t.jsx("input",{type:"number","aria-label":a("Số bậc"),min:2,max:80,value:S.steps||10,onChange:N=>j({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:a("Phép khối")}),t.jsxs("select",{"aria-label":a("Phép khối"),value:S.op||"",onChange:N=>{const A=N.target.value||void 0;j(A?{op:A}:{op:void 0,target:void 0})},children:[t.jsx("option",{value:"",children:a("Khối thường")}),Om.map(N=>t.jsx("option",{value:N,children:a(Ux[N])},N))]})]}),S.op&&t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Tác động lên")}),t.jsxs("select",{"aria-label":a("Tác động lên"),value:S.target||"",onChange:N=>j({target:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Khối liền trước")}),C.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:xi(C,d)>=0?a("Khối này không hiện; nó {0} “{1}”.",[a(Xx[S.op]),C[xi(C,d)].name||C[xi(C,d)].shape]):a("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:a("Vật liệu")}),t.jsx(Bd,{label:a("Vật liệu"),value:Ds(S)?.preset??"painted_wood",onChange:N=>j({look:{preset:N,...Ds(S)?.params?.color?{params:{color:Ds(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:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu khối"),value:Ds(S)?.params?.color||Ha(Ds(S)?.preset??"")?.colors[0]||"#cccccc",onChange:N=>{const A=Ds(S)??{preset:"painted_wood"};j({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:a("Bo cạnh (m)")}),t.jsx("input",{type:"number","aria-label":a("Bo cạnh (m)"),min:0,max:.5,step:.005,value:S.bevel??0,onChange:N=>j({bevel:Math.max(0,Math.min(.5,+N.target.value||0))})})]}),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Nhân bản (số bản)")}),t.jsx("input",{type:"number","aria-label":a("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));j({repeat:A>1?{count:A,offset:S.repeat?.offset??[1,0,0],yaw:S.repeat?.yaw??0}:void 0})}})]}),S.repeat&&T(a("Khoảng cách bản sao (m)"),S.repeat.offset,N=>j({repeat:{...S.repeat,offset:N}})),t.jsxs("label",{className:"shot-model-param",children:[t.jsx("span",{children:a("Đối xứng")}),t.jsxs("select",{"aria-label":a("Đối xứng"),value:S.mirror||"",onChange:N=>j({mirror:N.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Không")}),t.jsx("option",{value:"x",children:a("Trái – phải (X)")}),t.jsx("option",{value:"z",children:a("Trước – sau (Z)")}),t.jsx("option",{value:"xz",children:a("Cả hai")})]})]}),t.jsxs("div",{className:"shot-model-actions",children:[t.jsx("button",{className:"pill-btn thin",onClick:()=>{y({...u,parts:[...C,{...S,name:`${S.name||S.shape} 2`,position:[I(S.position[0]+.5),S.position[1],S.position[2]]}]}),f(C.length)},children:a("Nhân đôi khối")}),t.jsx("button",{className:"pill-btn thin",disabled:C.length<2,onClick:()=>{y({...u,parts:C.filter((N,A)=>A!==d)}),f(Math.max(0,d-1))},children:a("Xoá khối")})]})]})]})}function Yx({loop:e,onLoop:n,range:s,rangeOn:o,onRangeOn:i,onEnd:r,onKeyAll:l,onCopy:h,onPaste:u,canPaste:m,onEase:d,onNudge:f,stage:p,cameraActive:b,cameraHidden:g,cameraLocked:v,onToggle:y,onProp:k,shot:C,items:S,time:I,fxBars:j,onFxTiming:M,onParent:T,playing:w,selected:E,picked:N=[],onPick:A,onSeek:O,onPlay:H,onRow:D,onSelect:$,onAdd:W,onMove:z,onDelete:Y,height:J,onHeight:V}){ct();const[K,G]=R.useState(1),[_,ee]=R.useState(220),Q=J??_,ve=F=>{ee(F),V?.(F)},[xe,q]=R.useState(null),[ue,pe]=R.useState({}),[U,le]=R.useState(!0),ce=R.useRef(void 0),Le=R.useRef(null),[je,ie]=R.useState(null),Me=(F,te)=>N.some(Z=>Z.row===F&&Z.id===te),Ee=(F,te,Z)=>{if(F.button!==0||!Le.current)return;F.preventDefault(),ce.current?.();const re=Le.current,me=re.parentElement,Pe=re.getBoundingClientRect(),ye=F.clientX-Pe.left,rt=F.clientY-Pe.top,It=F.pointerId,qt=F.shiftKey,Xe=()=>{const mt=re.getBoundingClientRect();return[mt.left+ye,mt.top+rt]};re.setPointerCapture(It);let lt=!1;const jt=(mt,Rt)=>{const[Yt,ln]=Xe(),Qt=Math.min(Yt,mt),xt=Math.max(Yt,mt),cn=Math.min(ln,Rt),Ft=Math.max(ln,Rt),Zt=qt?[...N]:[];return re.querySelectorAll(".shot-time-key:not([disabled]),.shot-prop-key[data-key]").forEach(bn=>{const Gn=bn.getBoundingClientRect(),ae=Gn.left+Gn.width/2,ke=Gn.top+Gn.height/2;ae>=Qt&&ae<=xt&&ke>=cn&&ke<=Ft&&!Zt.some(Oe=>Oe.row===bn.dataset.row&&Oe.id===bn.dataset.key)&&Zt.push({row:bn.dataset.row,id:bn.dataset.key})}),Zt};let Ct=[F.clientX,F.clientY],gt=0;const at=()=>{const[mt,Rt]=Xe(),[Yt,ln]=Ct,Qt=re.getBoundingClientRect();ie({x:Math.min(mt,Yt)-Qt.left,y:Math.min(Rt,ln)-Qt.top,w:Math.abs(Yt-mt),h:Math.abs(ln-Rt)}),A?.(jt(Yt,ln))},tn=()=>{if(gt=0,!lt||!me)return;const mt=me.getBoundingClientRect(),Rt=Ct[1],Yt=Rt<mt.top+28?-Math.ceil((mt.top+28-Rt)/3):Rt>mt.bottom-16?Math.ceil((Rt-mt.bottom+16)/3):0;if(!Yt)return;const ln=me.scrollTop;me.scrollTop+=Yt,me.scrollTop!==ln&&(at(),gt=requestAnimationFrame(tn))},Ie=mt=>{if(mt.pointerId!==It)return;const[Rt,Yt]=Xe();!lt&&Math.hypot(mt.clientX-Rt,mt.clientY-Yt)<4||(lt=!0,Ct=[mt.clientX,mt.clientY],at(),gt||(gt=requestAnimationFrame(tn)))},ot=()=>{gt&&cancelAnimationFrame(gt),gt=0,re.removeEventListener("pointermove",Ie),re.removeEventListener("pointerup",nn),re.removeEventListener("pointercancel",ot),re.hasPointerCapture(It)&&re.releasePointerCapture(It),ie(null)},nn=mt=>{if(ot(),lt)A?.(jt(mt.clientX,mt.clientY));else{D(te);const Rt=Z.getBoundingClientRect();O(Math.max(0,Math.min(1,(mt.clientX-Rt.left)/Rt.width)))}};ce.current=ot,re.addEventListener("pointermove",Ie),re.addEventListener("pointerup",nn),re.addEventListener("pointercancel",ot)};R.useEffect(()=>()=>ce.current?.(),[]);const[Se,he]=R.useState(null),be=(F,te,Z,re)=>{const me=j?.[te];if(F.button!==0||!me||!M)return;F.preventDefault(),F.stopPropagation(),ce.current?.();const Pe=F.currentTarget,ye=F.pointerId,rt=F.clientX,It=re.getBoundingClientRect().width,qt=C.duration,Xe=.2;Pe.setPointerCapture(ye);let lt={id:te,start:me.start,duration:me.duration};const jt=tn=>Math.round(tn*20)/20,Ct=tn=>{if(tn.pointerId!==ye)return;const Ie=(tn.clientX-rt)/It*qt;if(Z==="move")lt={id:te,start:jt(Math.max(0,Math.min(qt-Xe,me.start+Ie))),duration:me.duration};else if(Z==="start"){const ot=me.start+me.duration,nn=jt(Math.max(0,Math.min(ot-Xe,me.start+Ie)));lt={id:te,start:nn,duration:+(ot-nn).toFixed(2)}}else lt={id:te,start:me.start,duration:jt(Math.max(Xe,me.duration+Ie))};he(lt)},gt=()=>{Pe.removeEventListener("pointermove",Ct),Pe.removeEventListener("pointerup",at),Pe.removeEventListener("pointercancel",gt),Pe.hasPointerCapture(ye)&&Pe.releasePointerCapture(ye),he(null)},at=()=>{gt(),(lt.start!==me.start||lt.duration!==me.duration)&&M(te,{start:lt.start,duration:lt.duration})};ce.current=gt,Pe.addEventListener("pointermove",Ct),Pe.addEventListener("pointerup",at),Pe.addEventListener("pointercancel",gt)},Fe=[{id:"camera",kind:"camera",name:"📷 Camera",locked:!!v,hidden:!!g,keys:C.motion==="path"?C.cameraKeys||[]:[]},...S.map(F=>({id:F.id,kind:F.kind==="fx"?"fx":F.kind==="person"?"person":"object",name:F.kind==="fx"?`✦ ${F.name}`:F.name,locked:F.locked,hidden:F.hidden,keys:C.objectKeys?.[F.id]||[],fx:F.kind==="fx",parent:F.fx?.attach?.to??""}))],Te=S.filter(F=>F.kind!=="fx"&&!F.hidden),_e=(E?Fe.filter(F=>F.id===E.row):Fe).flatMap(F=>F.keys.map(te=>te.time)).sort((F,te)=>F-te),ze=F=>{const te=F>0?_e.find(Z=>Z>I+1e-4):[..._e].reverse().find(Z=>Z<I-1e-4);te!==void 0&&O(te)},Be=(F,te)=>{if(F.button!==0)return;F.preventDefault(),F.stopPropagation(),ce.current?.();const Z=F.pointerId;te.setPointerCapture(Z);const re=rt=>{const It=te.getBoundingClientRect(),qt=Math.max(0,Math.min(1,(rt.clientX-It.left)/It.width)),Xe=gn(C);O(Math.min(1,Math.round(qt*C.duration*Xe)/Xe/C.duration))},me=rt=>{rt.pointerId===Z&&re(rt)},Pe=()=>{te.removeEventListener("pointermove",me),te.removeEventListener("pointerup",ye),te.removeEventListener("pointercancel",Pe),te.removeEventListener("lostpointercapture",Pe),te.hasPointerCapture(Z)&&te.releasePointerCapture(Z)},ye=rt=>{re(rt),Pe()};ce.current=Pe,te.addEventListener("pointermove",me),te.addEventListener("pointerup",ye),te.addEventListener("pointercancel",Pe),te.addEventListener("lostpointercapture",Pe),re(F)},Ze=(F,te,Z,re)=>{F.preventDefault(),F.stopPropagation(),$(te,Z);const me=re.getBoundingClientRect();let Pe;const ye=qt=>{if(Pe=Math.max(0,Math.min(1,(qt.clientX-me.left)/me.width)),U){const Xe=gn(C);Pe=Math.min(1,Math.round(Pe*C.duration*Xe)/Xe/C.duration);const lt=Fe.flatMap(jt=>jt.keys.filter(Ct=>!(jt.id===te&&Ct.id===Z)).map(Ct=>Ct.time)).find(jt=>Math.abs(jt-Pe)*me.width<6);lt!==void 0&&(Pe=lt)}q({row:te,id:Z,time:Pe})},rt=()=>{window.removeEventListener("mousemove",ye),window.removeEventListener("mouseup",It),q(null)},It=()=>{rt(),Pe!==void 0&&z(te,Z,Pe)};ce.current?.(),ce.current=rt,window.addEventListener("mousemove",ye),window.addEventListener("mouseup",It)};return t.jsxs("section",{className:"shot-timeline","aria-label":a("Timeline keyframe"),style:{height:Q},children:[t.jsx("div",{className:"shot-timeline-tools",children:(()=>{const F=gn(C),te=C.duration,Z=I*te,re=ye=>{const rt=Math.floor(ye/60),It=ye-rt*60;return`${String(rt).padStart(2,"0")}:${It.toFixed(2).padStart(5,"0")}`},me=ye=>{O(Math.max(0,Math.min(1,(Math.round(Z*F)+ye)/F/te)))},Pe=N.length?!1:!E||Fe.find(ye=>ye.id===E.row)?.locked;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-tc",children:[t.jsxs("span",{children:[re(Z)," / ",re(te)]}),t.jsx("small",{children:a("Khung {0} / {1} · {2} fps",[Math.round(Z*F),Math.round(te*F),F])})]}),t.jsxs("div",{className:"shot-transport",role:"group","aria-label":a("Điều khiển phát"),children:[t.jsx("button",{className:"shot-tp-btn",onClick:()=>O(0),"aria-label":a("Về đầu"),title:a("Về đầu")+" (Home)",children:t.jsx(Ne.skipStart,{})}),t.jsx("button",{className:"shot-tp-btn",onClick:()=>me(-1),disabled:Z<=1e-6,"aria-label":a("Lùi 1 khung hình"),title:a("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:H,"aria-label":w?a("Tạm dừng"):a("Phát"),title:(w?a("Tạm dừng"):a("Phát"))+" (Space)",children:w?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:()=>me(1),disabled:Z>=te-1e-6,"aria-label":a("Tới 1 khung hình"),title:a("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":a("Phát lặp"),title:a("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:Pe,onClick:Y,"aria-label":N.length>1?a("Xoá {0} key",[N.length]):a("Xoá key"),title:N.length>1?a("Xoá {0} key",[N.length]):a("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:[a("Zoom")," ",t.jsx("input",{"aria-label":a("Zoom timeline"),type:"range",min:1,max:8,step:.5,value:K,onChange:ye=>G(+ye.target.value)})]}),t.jsxs("label",{children:[a("Cao")," ",t.jsx("input",{"aria-label":a("Chiều cao timeline"),type:"range",min:140,max:360,step:20,value:Q,onChange:ye=>ve(+ye.target.value)})]})]})]})})()}),t.jsx("div",{className:"shot-edit-bar",role:"toolbar","aria-label":a("Công cụ keyframe"),children:(()=>{const F=N.length?N:E?[E]:[],te=F.length>0,Z=E?.row,re=(Xe,lt)=>lt?`${a(Xe)} (${lt})`:a(Xe),me=(Xe,lt,jt,Ct,gt={})=>t.jsx("button",{type:"button",className:`shot-edit-btn${gt.on?" on":""}`,"data-tool":Xe,"aria-label":a(jt),"aria-pressed":gt.on===void 0?void 0:gt.on,title:re(jt,gt.key),disabled:gt.disabled||!Ct,onClick:Ct,children:lt},Xe),Pe=Xe=>t.jsx("i",{className:"shot-edit-sep","aria-hidden":!0},Xe),ye=Xe=>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:Xe}),rt=(Xe,lt,jt)=>me("ease-"+Xe,ye(t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M3 17h14M3 3v14"}),t.jsx("path",{d:jt})]})),lt,()=>d?.(Xe),{disabled:!te||!d}),It=()=>{G(1),requestAnimationFrame(()=>{const Xe=Le.current?.parentElement;Xe&&(Xe.scrollLeft=0)})},qt=()=>{const Xe=Fe.flatMap(gt=>gt.keys.filter(at=>F.some(tn=>tn.row===gt.id&&tn.id===at.id)).map(at=>at.time)),lt=Math.min(...Xe),jt=Math.max(...Xe),Ct=Math.min(8,Math.max(1,.8/Math.max(.02,jt-lt)));G(Ct),requestAnimationFrame(()=>{const gt=Le.current?.parentElement;gt&&(gt.scrollLeft=Math.max(0,(lt-.05/Ct)*gt.clientWidth*Ct))})};return t.jsxs(t.Fragment,{children:[me("add",Os.key,"Thêm key trên hàng đang chọn",Z?()=>W(Z):void 0,{key:"K",disabled:!Z}),me("key-all",ye(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"}),me("key-prev",ye(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",_e.some(Xe=>Xe<I-1e-4)?()=>ze(-1):void 0),me("key-next",ye(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",_e.some(Xe=>Xe>I+1e-4)?()=>ze(1):void 0),Pe("s1"),me("copy",Os.copy,"Copy các key đang chọn",te?h:void 0,{key:"⌘C",disabled:!te}),me("paste",Os.paste,"Dán key tại playhead (giữ khoảng cách)",u,{key:"⌘V",disabled:!m}),Pe("s2"),rt("linear","Easing: Tuyến tính","M3 17 17 3"),rt("in","Easing: Vào chậm (ease in)","M3 17C10 17 14 12 17 3"),rt("snap","Easing: Ra chậm (ease out)","M3 17C6 8 10 3 17 3"),rt("smooth","Easing: Vào và ra chậm (ease in-out)","M3 17C10 17 10 3 17 3"),rt("hold","Easing: Giữ nguyên (hold)","M3 17h7V3h7"),Pe("s3"),me("nudge-back",ye(t.jsx("path",{d:"m12 5-5 5 5 5M16 4v12"})),"Dịch key lùi 1 khung hình",te?()=>f?.(-1):void 0,{key:"Alt+,",disabled:!te}),me("nudge-fwd",ye(t.jsx("path",{d:"m8 5 5 5-5 5M4 4v12"})),"Dịch key tới 1 khung hình",te?()=>f?.(1):void 0,{key:"Alt+.",disabled:!te}),Pe("s4"),me("range",ye(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:!!o,disabled:!s}),me("snap",Os.magnet,"Bám khung hình và key khác khi kéo key",()=>le(Xe=>!Xe),{on:U}),Pe("s5"),me("zoom-fit",Os.fit,"Thu phóng vừa cả shot",It),me("zoom-sel",Os.zoomIn,"Thu phóng vào các key đang chọn",te?qt:void 0,{disabled:!te}),me("end",ye(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:Le,style:{width:`${K*100}%`},children:[je&&t.jsx("div",{className:"shot-marquee",style:{left:je.x,top:je.y,width:je.w,height:je.h}}),t.jsxs("div",{className:"shot-time-row shot-ruler-row",children:[t.jsx("div",{className:"shot-track-name",children:a("Đối tượng")}),t.jsxs("div",{className:"shot-time-ruler",onPointerDown:F=>Be(F,F.currentTarget),children:[(C.lockUntil??0)>0&&t.jsx("div",{className:"shot-lock-band",role:"img",style:{width:`${Math.min(1,C.lockUntil/C.duration)*100}%`},"aria-label":a("Đã khoá 0–{0}s cho Agent",[String(Math.round(Math.min(C.lockUntil,C.duration)*100)/100)]),title:a("Agent không sửa phần này"),children:t.jsx("span",{children:"🔒"})}),s&&t.jsx("div",{className:`shot-range${o?" 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":a("Vị trí phát timeline"),"aria-valuemin":0,"aria-valuemax":C.duration,"aria-valuenow":Number((I*C.duration).toFixed(2)),style:{left:`${I*100}%`},onKeyDown:F=>{const te=F.shiftKey?1:.1,Z=1/gn(C);["ArrowLeft","ArrowRight","Home","End",",","."].includes(F.key)&&(F.preventDefault(),O(F.key==="Home"?0:F.key==="End"?1:F.key===","||F.key==="."?Math.max(0,Math.min(1,Math.round(I*C.duration/Z+(F.key==="."?1:-1))*Z/C.duration)):Math.max(0,Math.min(1,I+(F.key==="ArrowRight"?te:-te)/C.duration))))}}),Array.from({length:11},(F,te)=>t.jsxs("span",{style:{left:`${te*10}%`},children:[Number((C.duration*te/10).toFixed(2)),a("s")]},te))]})]}),Fe.map(F=>{const te=p&&ue[F.id]?wg(p,F.id):[];return t.jsxs(R.Fragment,{children:[t.jsxs("div",{className:`shot-time-row${F.id==="camera"&&b?" camera-active":""}${F.hidden?" is-hidden":""}${F.locked?" is-locked":""}`,children:[t.jsxs("div",{className:"shot-track-name",children:[y&&t.jsx("button",{className:`shot-row-eye${F.hidden?" off":""}`,"aria-pressed":!F.hidden,"aria-label":F.hidden?a("Hiện {0}",[F.name]):a("Ẩn {0}",[F.name]),title:F.id==="camera"?F.hidden?a("Hiện camera trong khung nhìn"):a("Ẩn camera khỏi khung nhìn (không ảnh hưởng ảnh xuất)"):F.hidden?a("Hiện trong cảnh và khi xuất"):a("Ẩn khỏi cảnh và khi xuất"),onClick:()=>y(F.id,"hidden"),children:F.hidden?"◌":"◉"}),p&&t.jsx("button",{className:`shot-row-keys${F.keys.length?" keyed":""}${ue[F.id]?" open":""}`,"aria-expanded":!!ue[F.id],"aria-label":a("Thuộc tính {0}",[F.name]),title:a("Mở / đóng các thuộc tính keyframe"),onClick:()=>pe(Z=>({...Z,[F.id]:!Z[F.id]})),children:"◆"}),y&&t.jsx("button",{className:`shot-row-lock${F.locked?" on":""}`,"aria-pressed":F.locked,"aria-label":F.locked?a("Mở khoá {0}",[F.name]):a("Khoá {0}",[F.name]),title:F.locked?a("Mở khoá: cho chọn và kéo"):a("Khoá: không chọn, không kéo, không sửa key"),onClick:()=>y(F.id,"locked"),children:F.locked?"🔒":"🔓"}),t.jsx("button",{className:"shot-row-name",title:F.name,onClick:()=>{F.locked||D(F.id)},children:F.name}),"fx"in F&&F.fx&&T&&t.jsxs("select",{className:"shot-track-parent","aria-label":a("Parent của {0}",[F.name]),title:a("Parent: hiệu ứng đi theo đối tượng này"),disabled:F.locked,value:F.parent,onChange:Z=>T(F.id,Z.target.value),children:[t.jsx("option",{value:"",children:a("Tự do")}),Te.map(Z=>t.jsxs("option",{value:Z.id,children:["🔗 ",Z.name]},Z.id))]}),t.jsx("button",{"aria-label":a("Thêm key {0}",[F.name]),disabled:F.locked,onClick:()=>W(F.id),children:"+◆"})]}),t.jsxs("div",{className:"shot-key-track","data-row":F.id,onPointerDown:Z=>{Z.target.closest(".shot-time-key")||Ee(Z,F.id,Z.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),(C.clipSpans?.[F.id]||[]).map(Z=>t.jsx("div",{className:"shot-clip-block","data-clip-block":Z.clip,style:{left:`${Z.start/C.duration*100}%`,width:`${Math.max(.5,(Math.min(C.duration,Z.end)-Z.start)/C.duration*100)}%`},title:`${Z.label} · ${Z.start.toFixed(1)}–${Z.end.toFixed(1)}s`,children:t.jsx("span",{children:Z.label})},Z.id)),(C.motionEdits?.[F.id]||[]).map(Z=>t.jsx("div",{className:`shot-edit-mark${Z.off?" off":""}`,"data-edit-mark":!0,style:{left:`${Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade))/C.duration*100}%`,width:`${((Z.scope==="after"?C.duration:Z.end+(Z.scope==="span"?0:Z.fade))-Math.max(0,Z.start-(Z.scope==="span"?0:Z.fade)))/C.duration*100}%`},title:`${Z.label||a("Chỉnh")} · ${(Number(Z.start)||0).toFixed(1)}s`},Z.id)),j?.[F.id]&&(()=>{const Z=Se?.id===F.id?Se:j[F.id],re=!!M&&!F.locked,me=Pe=>Pe.currentTarget.closest(".shot-key-track");return t.jsx("div",{className:`shot-fx-bar${F.hidden||F.locked?" dim":""}${re?" editable":""}${Se?.id===F.id?" dragging":""}`,"data-fx-bar":F.id,title:a("Hiệu ứng: {0}s → {1}s · kéo để dời, kéo mép để đổi độ dài",[Z.start.toFixed(2),(Z.start+Z.duration).toFixed(2)]),style:{left:`${Math.min(100,Z.start/C.duration*100)}%`,width:`${Math.max(.6,Math.min(100-Z.start/C.duration*100,Z.duration/C.duration*100))}%`},onPointerDown:re?Pe=>be(Pe,F.id,"move",me(Pe)):void 0,children:re&&t.jsxs(t.Fragment,{children:[t.jsx("i",{className:"shot-fx-edge start","aria-hidden":!0,onPointerDown:Pe=>be(Pe,F.id,"start",me(Pe))}),t.jsx("i",{className:"shot-fx-edge end","aria-hidden":!0,onPointerDown:Pe=>be(Pe,F.id,"end",me(Pe))})]})})})(),!j?.[F.id]&&F.kind!=="fx"&&t.jsx("div",{className:`shot-dur-bar kind-${F.kind}${F.hidden||F.locked?" dim":""}`,"data-dur":F.id,title:F.kind==="camera"?a("Camera chạy suốt shot: 0s → {0}s",[C.duration]):a("Có mặt suốt shot: 0s → {0}s",[C.duration]),style:{left:"0%",width:"100%"}}),F.keys.map((Z,re)=>t.jsx("button",{"aria-label":`Key ${re+1} ${F.name}`,title:a("{0}s · kéo để đổi thời điểm",[(Z.time*C.duration).toFixed(2)]),disabled:F.locked,"data-row":F.id,"data-key":Z.id,className:`shot-time-key ${"pose"in Z&&Z.pose?"pose":""} ${E?.row===F.id&&E.id===Z.id||Me(F.id,Z.id)?"active":""}`,style:{left:`${(xe?.id===Z.id&&xe.row===F.id?xe.time:Z.time)*100}%`},onClick:me=>{me.detail===0&&$(F.id,Z.id)},onMouseDown:me=>{if(me.shiftKey||me.metaKey||me.ctrlKey){me.preventDefault(),me.stopPropagation();const Pe=Me(F.id,Z.id),ye=N.length?N:E?[E]:[];A?.(Pe?ye.filter(rt=>!(rt.row===F.id&&rt.id===Z.id)):[...ye,{row:F.id,id:Z.id}]);return}Ze(me,F.id,Z.id,me.currentTarget.parentElement)},children:"◆"},Z.id))]})]}),te.map(Z=>{const re=Mg(C,F.id);return t.jsxs("div",{className:"shot-time-row shot-prop-row","data-prop":`${F.id}:${Z.id}`,children:[t.jsxs("div",{className:"shot-track-name",children:[t.jsx("span",{className:`shot-stopwatch${re?" keyed":""}`,role:"img","aria-label":re?a("Đã có key"):a("Chưa có key"),title:re?a("Thuộc tính đã có key: sửa số sẽ ghi key tại playhead"):a("Chưa có key: sửa số đổi giá trị cố định"),children:"⏱"}),t.jsxs("label",{className:"shot-prop-label",children:[a(Z.label),t.jsx(Sn,{"aria-label":`${a(Z.label)} · ${F.name}`,className:"shot-prop-number",step:Z.step,min:Z.min,max:Z.max,precision:3,disabled:F.locked,value:Sg(p,F.id,Z.id,I),onCommit:me=>k?.(F.id,Z.id,me)})]}),t.jsx("button",{className:"shot-prop-add","aria-label":`${a("Thêm key")} ${a(Z.label)} · ${F.name}`,title:a("Thêm key tại playhead"),disabled:F.locked,onClick:()=>W(F.id),children:"◆"})]}),t.jsxs("div",{className:"shot-key-track shot-prop-track",onPointerDown:me=>{F.locked||Ee(me,F.id,me.currentTarget)},children:[t.jsx("div",{className:"shot-time-playhead",style:{left:`${I*100}%`}}),F.keys.map(me=>t.jsx("i",{"data-row":F.locked?void 0:F.id,"data-key":F.locked?void 0:me.id,className:`shot-prop-key${Me(F.id,me.id)||E?.row===F.id&&E.id===me.id?" active":""}`,style:{left:`${me.time*100}%`}},me.id))]})]},Z.id)})]},F.id)})]})})]})}let ls=null;function Qx(){return ls||(ls=new Kr(Ig()),ls.colorSpace=Sd,ls.anisotropy=4,ls.generateMipmaps=!0,ls.minFilter=Cd,ls)}const Wc=new Map;function Zx(e){let n=Wc.get(e);return n||(n=new Kr(Eg(e)),n.colorSpace=Sd,n.anisotropy=8,n.generateMipmaps=!0,n.minFilter=Cd,Wc.set(e,n)),n}let Yn=null;function Jx(){if(Yn)return Yn;const e=128,n=new Uint8Array(e*e*4),s=r=>{const l=new Float32Array(r*r);let h=1013904223+r;for(let u=0;u<l.length;u++)h=Math.imul(h,1664525)+1013904223>>>0,l[u]=h/4294967296;return l},o=[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 h=0,u=.5,m=0;for(const{g:p,v:b}of o){const g=l/e*p,v=r/e*p,y=Math.floor(g),k=Math.floor(v),C=i(g-y),S=i(v-k),I=(T,w)=>b[w%p*p+T%p],j=I(y,k)+(I(y+1,k)-I(y,k))*C,M=I(y,k+1)+(I(y+1,k+1)-I(y,k+1))*C;h+=(j+(M-j)*S)*u,m+=u,u*=.5}const d=(r*e+l)*4,f=Math.round(h/m*255);n[d]=n[d+1]=n[d+2]=f,n[d+3]=255}return Yn=new K0(n,e,e,H0),Yn.wrapS=Yn.wrapT=Md,Yn.magFilter=gc,Yn.minFilter=gc,Yn.needsUpdate=!0,Yn}const eb=Symbol.for("clipoox.shot.fxSoftDepth"),tb=e=>e[eb]??null,Gr={uOcclude:{value:0}},Gc={day:.22,golden:.16,overcast:.2,night:.03},Oa={blade:.78,width:.034,thick:.0075,grip:.19};function qc(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 Uc(e=0){const{blade:n,width:s,thick:o}=Oa,i=[[0,.86,1],[.06,1,1],[.7,.96,.9],[.84,.74,.72],[.94,.4,.5],[1,.02,.15]],r=qc(1,1).length,l=[],h=[];i.forEach(([m,d,f])=>{for(const[p,b]of qc(s*d+e,o*f+e*.5))l.push(p,m*n,b)});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,b=(m+1)*r+d,g=(m+1)*r+(d+1)%r;h.push(f,b,p,p,b,g)}const u=new Tt;return u.setAttribute("position",new Bt(l,3)),u.setIndex(h),u.computeVertexNormals(),u}function nb(){const e=[],n=new Nd(.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 W0(.0125,.03,10);r.rotateZ(-i*Math.PI/2),r.translate(i*.086,.012,0),e.push(r)}const s=new vs(.016,.02,.026,14);s.translate(0,-.016,0),e.push(s);const o=Hd(e);return e.forEach(i=>i.dispose()),o}function sb(){const e=[],n=new vs(.0125,.0125,Oa.grip,12);n.translate(0,-.03-Oa.grip/2,0),e.push(n);for(let i=0;i<5;i++){const r=new Wr(.0132,.0028,6,14);r.rotateX(Math.PI/2),r.translate(0,-.05-i*.034,0),e.push(r)}const s=new Hn(.0235,14,10);s.translate(0,-.03-Oa.grip-.012,0),e.push(s);const o=Hd(e);return e.forEach(i=>i.dispose()),o}function Hd(e){const n=[],s=[],o=[],i=[];let r=0;for(const h of e){const u=h.getAttribute("position"),m=h.getAttribute("normal"),d=h.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)),o.push(d?d.getX(f):0,d?d.getY(f):0);if(h.index)for(let f=0;f<h.index.count;f++)i.push(r+h.index.getX(f));else for(let f=0;f<u.count;f++)i.push(r+f);r+=u.count}const l=new Tt;return l.setAttribute("position",new Bt(n,3)),l.setAttribute("normal",new Bt(s,3)),l.setAttribute("uv",new Bt(o,2)),l.setIndex(i),l}const ab=`
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);
@@ -163,7 +163,7 @@ void main(){
163
163
  #ifdef GLOW
164
164
  gl_FragColor = vec4(gl_FragColor.rgb * a * (1.0 + 1.5 * uOcclude), a * uOcclude);
165
165
  #endif
166
- }`;function Gd(){const e=new G0,n=new ei(1,1);return e.setAttribute("position",n.getAttribute("position")),e.setAttribute("uv",n.getAttribute("uv")),e.setIndex(n.getIndex()),e}const hr={cam:0,flat:1,plane:2},qd=e=>e?{blending:V0,blendEquation:X0,blendSrc:U0,blendDst:q0,defines:{GLOW:1}}:{blending:Y0};function yb(e,n,s){const o=tb(n),i=e.uniforms,r=s,l=i.uFacing.value;if(!o||!r.isPerspectiveCamera||l===hr.flat||l===hr.plane){i.uSoftOn.value=0;return}i.uSoftOn.value=1,i.uDepth.value=o.texture,i.uDepthSize.value.set(o.width,o.height),i.uNear.value=r.near,i.uFar.value=r.far}const vb=200,ni=(e,n)=>n?e+vb:e;function Ud(e,n){const s=Gd(),o=new Td(new Float32Array(e.max*bi),bi,1);o.setUsage(sa),s.setAttribute("iPos",new En(o,3,0)),s.setAttribute("iSize",new En(o,2,3)),s.setAttribute("iRot",new En(o,1,5)),s.setAttribute("iColor",new En(o,4,6)),s.setAttribute("iDir",new En(o,3,10)),s.setAttribute("iSprite",new En(o,1,13)),s.instanceCount=0;const i=e.tex!=="atlas",r=e.mat,l=r?.ramp&&r.ramp.length>=2?r.ramp:null,h=[0,1,2,3].map(v=>l?new oe(...l[Math.min(l.length-1,Math.round(v*(l.length-1)/3))]):new oe),u=new Ua({vertexShader:xb,fragmentShader:bb,transparent:!0,depthWrite:!1,side:ys,...qd(e.blend==="add"),uniforms:{uMap:{value:i?Zx(e.tex):Qx()},uGrid:{value:i?1:Rg},uWhole:{value:i?1:0},uFacing:{value:e.facing??hr.cam},uOcclude:Gr.uOcclude,uRampOn:{value:l?1:0},uRamp:{value:h},uDissolve:{value:Math.max(0,Math.min(1,r?.dissolve??0))},uNoiseK:{value:r?.noise??.9},uNoise:{value:Jx()},uSoftOn:{value:0},uDepth:{value:null},uDepthSize:{value:new ra(1,1)},uNear:{value:.1},uFar:{value:1e3},uSoftDist:{value:.35}}});e.blend!=="add"&&(u.polygonOffset=!1);const m=new ut(s,u);m.frustumCulled=!1,m.renderOrder=ni(n,e.blend==="add"),qr(m);let d=0,f=1;const p=()=>{s.instanceCount=Math.floor(d*f+(d>0&&d*f<1?1:0)),m.visible=s.instanceCount>0},b=e.sort?new Float32Array(e.max*bi):null,g=[0,0,0];return m.onBeforeRender=(v,y,k)=>{yb(u,v,k),!(!b||d<2)&&(k.getWorldPosition(io),g[0]=io.x,g[1]=io.y,g[2]=io.z,zm(o.array,d,g,b),o.needsUpdate=!0)},{object:m,update(v,y){return d=e.eval(v,y,o.array),o.needsUpdate=d>0,p(),d},setShare(v){f=v,p()},hide(){d=0,m.visible=!1},dispose(){s.dispose(),u.dispose()}}}const jb=`
166
+ }`;function Gd(){const e=new G0,n=new ei(1,1);return e.setAttribute("position",n.getAttribute("position")),e.setAttribute("uv",n.getAttribute("uv")),e.setIndex(n.getIndex()),e}const hr={cam:0,flat:1,plane:2},qd=e=>e?{blending:V0,blendEquation:X0,blendSrc:U0,blendDst:q0,defines:{GLOW:1}}:{blending:Y0};function yb(e,n,s){const o=tb(n),i=e.uniforms,r=s,l=i.uFacing.value;if(!o||!r.isPerspectiveCamera||l===hr.flat||l===hr.plane){i.uSoftOn.value=0;return}i.uSoftOn.value=1,i.uDepth.value=o.texture,i.uDepthSize.value.set(o.width,o.height),i.uNear.value=r.near,i.uFar.value=r.far}const vb=200,ni=(e,n)=>n?e+vb:e;function Ud(e,n){const s=Gd(),o=new Td(new Float32Array(e.max*bi),bi,1);o.setUsage(sa),s.setAttribute("iPos",new In(o,3,0)),s.setAttribute("iSize",new In(o,2,3)),s.setAttribute("iRot",new In(o,1,5)),s.setAttribute("iColor",new In(o,4,6)),s.setAttribute("iDir",new In(o,3,10)),s.setAttribute("iSprite",new In(o,1,13)),s.instanceCount=0;const i=e.tex!=="atlas",r=e.mat,l=r?.ramp&&r.ramp.length>=2?r.ramp:null,h=[0,1,2,3].map(v=>l?new oe(...l[Math.min(l.length-1,Math.round(v*(l.length-1)/3))]):new oe),u=new Ua({vertexShader:xb,fragmentShader:bb,transparent:!0,depthWrite:!1,side:ys,...qd(e.blend==="add"),uniforms:{uMap:{value:i?Zx(e.tex):Qx()},uGrid:{value:i?1:Rg},uWhole:{value:i?1:0},uFacing:{value:e.facing??hr.cam},uOcclude:Gr.uOcclude,uRampOn:{value:l?1:0},uRamp:{value:h},uDissolve:{value:Math.max(0,Math.min(1,r?.dissolve??0))},uNoiseK:{value:r?.noise??.9},uNoise:{value:Jx()},uSoftOn:{value:0},uDepth:{value:null},uDepthSize:{value:new ra(1,1)},uNear:{value:.1},uFar:{value:1e3},uSoftDist:{value:.35}}});e.blend!=="add"&&(u.polygonOffset=!1);const m=new ut(s,u);m.frustumCulled=!1,m.renderOrder=ni(n,e.blend==="add"),qr(m);let d=0,f=1;const p=()=>{s.instanceCount=Math.floor(d*f+(d>0&&d*f<1?1:0)),m.visible=s.instanceCount>0},b=e.sort?new Float32Array(e.max*bi):null,g=[0,0,0];return m.onBeforeRender=(v,y,k)=>{yb(u,v,k),!(!b||d<2)&&(k.getWorldPosition(io),g[0]=io.x,g[1]=io.y,g[2]=io.z,zm(o.array,d,g,b),o.needsUpdate=!0)},{object:m,update(v,y){return d=e.eval(v,y,o.array),o.needsUpdate=d>0,p(),d},setShare(v){f=v,p()},hide(){d=0,m.visible=!1},dispose(){s.dispose(),u.dispose()}}}const jb=`
167
167
  attribute vec3 iA; attribute vec3 iB; attribute vec2 iW; attribute vec4 iCA; attribute vec4 iCB;
168
168
  uniform float uExt; varying vec2 vUv; varying vec4 vColor; varying float vAlong;
169
169
  void main(){
@@ -188,7 +188,7 @@ void main(){
188
188
  #ifdef GLOW
189
189
  gl_FragColor = vec4(gl_FragColor.rgb * a * (1.0 + 1.5 * uOcclude), a * uOcclude);
190
190
  #endif
191
- }`;function Xd(e,n){const s=Gd(),o=new Td(new Float32Array(e.max*Gl),Gl,1);o.setUsage(sa),s.setAttribute("iA",new En(o,3,0)),s.setAttribute("iB",new En(o,3,3)),s.setAttribute("iW",new En(o,2,6)),s.setAttribute("iCA",new En(o,4,8)),s.setAttribute("iCB",new En(o,4,12)),s.instanceCount=0;const i=new Ua({vertexShader:jb,fragmentShader:kb,transparent:!0,depthWrite:!1,side:ys,...qd(e.blend!=="alpha"),uniforms:{uExt:{value:e.soft!==void 0?.5:.15},uSoft:{value:e.soft??0},uOcclude:Gr.uOcclude}}),r=new ut(s,i);r.frustumCulled=!1,r.renderOrder=ni(n,e.blend!=="alpha"),qr(r);let l=0,h=1;const u=()=>{s.instanceCount=Math.floor(l*(h<1?Math.max(h,.7):1)),r.visible=s.instanceCount>0};return{object:r,update(m,d){return l=e.eval(m,d,o.array),o.needsUpdate=l>0,u(),l},setShare(m){h=m,u()},hide(){l=0,r.visible=!1},dispose(){s.dispose(),i.dispose()}}}function wb(e,n){const s=ib(e.max);s.setColor(n);let o=0;const i=()=>{for(const r of s.meshes)r.count=o;s.glow.count=o,s.group.visible=o>0};return{object:s.group,update(r,l){return o=e.eval(r,l,s.matrix.array,s.glowAttr.array),s.matrix.needsUpdate=o>0,s.glowAttr.needsUpdate=o>0,i(),o},setShare(){},hide(){o=0,i()},dispose(){s.dispose()}}}function Vd(e){const n=ub(e.geo,e.max);let s=0,o=1;const i=()=>{n.mesh.count=e.thin?Math.floor(s*o):s,n.mesh.visible=n.mesh.count>0};return{object:n.mesh,update(r,l){return s=e.eval(r,l,n.mesh.instanceMatrix.array,n.mesh.instanceColor.array),n.mesh.instanceMatrix.needsUpdate=s>0,n.mesh.instanceColor.needsUpdate=s>0,i(),s},setShare(r){o=r,i()},hide(){s=0,i()},dispose(){n.dispose()}}}const Mb=`
191
+ }`;function Xd(e,n){const s=Gd(),o=new Td(new Float32Array(e.max*Gl),Gl,1);o.setUsage(sa),s.setAttribute("iA",new In(o,3,0)),s.setAttribute("iB",new In(o,3,3)),s.setAttribute("iW",new In(o,2,6)),s.setAttribute("iCA",new In(o,4,8)),s.setAttribute("iCB",new In(o,4,12)),s.instanceCount=0;const i=new Ua({vertexShader:jb,fragmentShader:kb,transparent:!0,depthWrite:!1,side:ys,...qd(e.blend!=="alpha"),uniforms:{uExt:{value:e.soft!==void 0?.5:.15},uSoft:{value:e.soft??0},uOcclude:Gr.uOcclude}}),r=new ut(s,i);r.frustumCulled=!1,r.renderOrder=ni(n,e.blend!=="alpha"),qr(r);let l=0,h=1;const u=()=>{s.instanceCount=Math.floor(l*(h<1?Math.max(h,.7):1)),r.visible=s.instanceCount>0};return{object:r,update(m,d){return l=e.eval(m,d,o.array),o.needsUpdate=l>0,u(),l},setShare(m){h=m,u()},hide(){l=0,r.visible=!1},dispose(){s.dispose(),i.dispose()}}}function wb(e,n){const s=ib(e.max);s.setColor(n);let o=0;const i=()=>{for(const r of s.meshes)r.count=o;s.glow.count=o,s.group.visible=o>0};return{object:s.group,update(r,l){return o=e.eval(r,l,s.matrix.array,s.glowAttr.array),s.matrix.needsUpdate=o>0,s.glowAttr.needsUpdate=o>0,i(),o},setShare(){},hide(){o=0,i()},dispose(){s.dispose()}}}function Vd(e){const n=ub(e.geo,e.max);let s=0,o=1;const i=()=>{n.mesh.count=e.thin?Math.floor(s*o):s,n.mesh.visible=n.mesh.count>0};return{object:n.mesh,update(r,l){return s=e.eval(r,l,n.mesh.instanceMatrix.array,n.mesh.instanceColor.array),n.mesh.instanceMatrix.needsUpdate=s>0,n.mesh.instanceColor.needsUpdate=s>0,i(),s},setShare(r){o=r,i()},hide(){s=0,i()},dispose(){n.dispose()}}}const Mb=`
192
192
  uniform vec2 uR; varying vec3 vObj; varying vec3 vN; varying vec3 vV; varying float vY; varying float vAng;
193
193
  void main(){
194
194
  vec3 p = position;
@@ -280,8 +280,8 @@ void main(){
280
280
  gl_FragColor = vec4(col, a);
281
281
  #include <tonemapping_fragment>
282
282
  #include <colorspace_fragment>
283
- }`;function Qd(e,n){const s=[];e.traverse(i=>{i.isMesh&&i.visible&&!i.userData.fxMarker&&s.push(i)});const o=s.filter(i=>i.isSkinnedMesh);n.makeEmpty();for(const i of o.length?o:s)n.expandByObject(i,!0);return n}let Tb=null;const Lb=()=>Tb??=Object.assign(Zh(Kn["Thiền định"],"#d8dde6",void 0),{name:"fx-ghost-stand-in"}),Eb=e=>{e.isLine=!0};function Ib(e,n,s){const o=new rn;o.name="fx-ghost";const i=new Ua({vertexShader:Nb,fragmentShader:Ab,transparent:!0,depthWrite:!1,blending:Hr,side:Va,uniforms:{uColor:{value:new Ue},uCore:{value:new Ue},uAlpha:{value:0},uTime:{value:0},uBase:{value:0},uHeight:{value:1},uReveal:{value:1},uCut:{value:0},uStars:{value:1},uScale:{value:1},uFlow:{value:1}}});let r=[],l=null,h=-1,u=null,m=0,d=!1;const f=new At,p=new At,b=new oe,g=new oe,v=new zt,y=()=>{for(const S of r)o.remove(S.copy);r=[],l=null,h=-1},k=S=>{const I=[];return S.traverse(j=>{j.isMesh&&j.visible&&!j.userData.fxMarker&&!j.isLine&&j.layers.isEnabled(0)&&I.push(j)}),I},C=(S,I)=>{y();for(const j of I){let M;if(j.isSkinnedMesh){const T=j,w=new Or(T.geometry,i);w.bindMode=Q0,w.bind(T.skeleton,T.bindMatrix),w.updateMatrixWorld=()=>{},w.updateWorldMatrix=()=>{},M=w}else M=new ut(j.geometry,i);M.matrixAutoUpdate=!1,M.matrixWorldAutoUpdate=!1,M.frustumCulled=!1,M.castShadow=!1,M.receiveShadow=!1,M.renderOrder=ni(n,!0),Eb(M),o.add(M),r.push({src:j,copy:M})}l=S,h=I.length};return{object:o,update(S,I){const j=e.eval(S,I);let M=s();if(!j||j.alpha<=.002)return o.visible=!1,0;M||(M=Lb(),M.position.set(I.origin[0],I.origin[1],I.origin[2]),M.rotation.set(0,I.yaw,0),M.scale.setScalar(I.size)),M.updateWorldMatrix(!0,!0);const T=k(M);if((l!==M||T.length!==h)&&C(M,T),!r.length||((l!==u||Math.abs(S-m)>.25||!d)&&(Qd(M,v),u=l,m=S,d=!v.isEmpty()),!d))return o.visible=!1,0;b.set((v.min.x+v.max.x)/2,v.min.y,(v.min.z+v.max.z)/2),g.set(j.offset[0],j.offset[1],j.offset[2]),f.makeTranslation(b.x+g.x,b.y+g.y,b.z+g.z).multiply(p.makeRotationY(j.turn??0)).multiply(p.makeScale(j.scale,j.scale,j.scale)).multiply(p.makeTranslation(-b.x,-b.y,-b.z));for(const{src:A,copy:O}of r)O.matrixWorld.multiplyMatrices(f,A.matrixWorld),O.isSkinnedMesh&&O.bindMatrixInverse.copy(A.matrixWorld).invert(),O.visible=A.visible;const w=b.y+g.y,E=Math.max(.2,(v.max.y-v.min.y)*j.scale),N=i.uniforms;return N.uColor.value.setRGB(j.color[0]*j.color[3],j.color[1]*j.color[3],j.color[2]*j.color[3],xs),N.uCore.value.setRGB(j.core[0],j.core[1],j.core[2],xs),N.uAlpha.value=j.alpha,N.uTime.value=S,N.uBase.value=w,N.uHeight.value=E,N.uReveal.value=j.reveal,N.uCut.value=j.cut,N.uStars.value=j.stars,N.uScale.value=j.scale,N.uFlow.value=j.flow,o.visible=!0,r.length},setShare(){},hide(){o.visible=!1},dispose(){y(),i.dispose()}}}const Rb=new Set(["box","wall","platform","floor"]),Zd=new Set(["model","proxy","box","wall","platform","floor","sphere","cylinder","set","prop"]),Fb=1500,zi=8,ma=new Map,Xc=()=>{},Pb=new ns({color:"#7d766b",roughness:1,metalness:0,name:"mix-rubble"});function $b(e,n,s){const o=e.kind==="model"?`${e.model?.gcsUri}|${e.model?.height??""}`:e.kind==="proxy"?JSON.stringify(e.proxy):e.kind==="set"?e.set?.id:e.kind==="prop"?e.prop?.kind:"";return`${e.id}|${e.kind}|${o}|${e.scale.map(i=>i.toFixed(3)).join(",")}|${Math.round(n)}|${s}`}function Jd(e){const n=[];return e.traverse(s=>{s instanceof ut&&!s.userData.fxMarker&&n.push(s)}),n}function Db(e,n){const s=n.clone().multiply(e.matrixWorld),o=e;if(!o.isInstancedMesh)return[s];const i=[],r=new At;for(let l=0;l<o.count;l++)o.getMatrixAt(l,r),i.push(s.clone().multiply(r));return i}const dr=e=>Array.isArray(e.material)?e.material:[e.material];function Ob(e,n,s,o){const i=yx(e,s,o),r=bx(i);if(!r)return null;const l=i.length/3,h=i.reduce((p,b,g)=>g%3===0?p+i[g]:p,0)/l,u=i.reduce((p,b,g)=>g%3===1?p+i[g]:p,0)/l,m=i.reduce((p,b,g)=>g%3===2?p+i[g]:p,0)/l,d=new Float32Array(r.length*3);r.forEach((p,b)=>{d[b*3]=h+(i[p*3]-h)*.97,d[b*3+1]=u+(i[p*3+1]-u)*.97,d[b*3+2]=m+(i[p*3+2]-m)*.97});const f=new Tt;return f.setAttribute("position",new Pt(d,3)),f.computeVertexNormals(),f.computeBoundingSphere(),f}function _b(e,n,s,o){const i=$b(n,s,o),r=ma.get(i);if(r)return r;const l=performance.now(),h=n.scale.map(g=>Math.max(.001,Math.abs(g))),u=[];let m=1,d=0,f=0;const p=Rb.has(n.kind);if(p){const g=qm(h,s,o);m=Math.cbrt(h[0]*h[1]*h[2]/Math.max(1,g.length));for(const v of g){const y=v.s.map((S,I)=>S/h[I]),k=v.c.map((S,I)=>S/h[I]),C=new Xa(y[0],y[1],y[2]).translate(k[0],k[1],k[2]);C.clearGroups(),C.addGroup(0,C.index.count,0),u.push({geo:C,core:null,c:k,h:y.map(S=>S/2)})}d=1,f=g.length*12}else{e.updateMatrixWorld(!0);const g=e.matrixWorld.clone().invert(),v=[],y=[];for(const D of Jd(e)){let $=D.geometry;$.getAttribute("position")&&!$.getAttribute("normal")&&($=$.clone(),$.computeVertexNormals());const W=$.getAttribute("position"),z=$.getAttribute("normal"),Y=$.getAttribute("uv"),J=$.index;if(!W){d+=dr(D).length;continue}const V=(G,_)=>{const ee=new Float32Array(G.count*_);for(let Q=0;Q<G.count;Q++)ee[Q*_]=G.getX(Q),ee[Q*_+1]=G.getY(Q),_>2&&(ee[Q*_+2]=G.getZ(Q));return ee},K=Um({pos:V(W,3),nor:z?V(z,3):null,uv:Y?V(Y,2):null,index:J?J.array:null,groups:Array.isArray(D.material)&&$.groups.length?$.groups:null},Db(D,g).map(G=>G.elements),d);v.push(K.verts),y.push(K.slots),d+=dr(D).length}let k=new Float32Array(v.reduce((D,$)=>D+$.length,0)),C=0;for(const D of v)k.set(D,C),C+=D.length;let S=new Int32Array(y.reduce((D,$)=>D+$.length,0));C=0;for(const D of y)S.set(D,C),C+=D.length;if(f=S.length,!f)return{key:i,cells:[],cell:1,slots:d,ms:0,tris:0,solid:p};const I=[1/0,1/0,1/0],j=[-1/0,-1/0,-1/0];for(let D=0;D<k.length;D+=zi)for(let $=0;$<3;$++){const W=k[D+$]*h[$];W<I[$]&&(I[$]=W),W>j[$]&&(j[$]=W)}const M=[0,1,2].map(D=>Math.max(.05,j[D]-I[D]));m=Math.cbrt(M[0]*M[1]*M[2]/Math.max(1,s));const T=Xm(k,zi,S,m*.7,Zm,h);k=T.verts,S=T.slots,f=T.tris;const w=new Float32Array(f*3);for(let D=0;D<f;D++)for(let $=0;$<3;$++)w[D*3+$]=(k[D*24+$]+k[D*24+8+$]+k[D*24+16+$])/3*h[$];const E=Vm(I,j.map((D,$)=>Math.max(D,I[$]+.05)),s,o),N=Ym(w,E),A=[0,1,2].map(D=>(I[D]+j[D])/2/h[D]),O=(h[0]+h[1]+h[2])/3,H=Array.from({length:E.count},()=>[]);for(let D=0;D<f;D++)H[N[D]].push(D);for(const D of H){if(!D.length)continue;D.sort((Q,ve)=>S[Q]-S[ve]||Q-ve);const $=new Float32Array(D.length*9),W=new Float32Array(D.length*9),z=new Float32Array(D.length*6),Y=[1/0,1/0,1/0],J=[-1/0,-1/0,-1/0],V=new Tt;let K=0,G=S[D[0]];D.forEach((Q,ve)=>{S[Q]!==G&&(V.addGroup(K*3,(ve-K)*3,G),K=ve,G=S[Q]);for(let xe=0;xe<3;xe++){const q=(Q*3+xe)*zi,ue=(ve*3+xe)*3;for(let pe=0;pe<3;pe++){const U=k[q+pe];$[ue+pe]=U,W[ue+pe]=k[q+3+pe],U<Y[pe]&&(Y[pe]=U),U>J[pe]&&(J[pe]=U)}z[(ve*3+xe)*2]=k[q+6],z[(ve*3+xe)*2+1]=k[q+7]}}),V.addGroup(K*3,(D.length-K)*3,G),V.setAttribute("position",new Pt($,3)),V.setAttribute("normal",new Pt(W,3)),V.setAttribute("uv",new Pt(z,2)),V.computeBoundingSphere();const _=[0,1,2].map(Q=>(Y[Q]+J[Q])/2),ee=Ob($,_,[A[0]-_[0],A[1]-_[1],A[2]-_[2]],m*.22/O);u.push({geo:V,core:ee,c:_,h:[0,1,2].map(Q=>Math.max(.01,(J[Q]-Y[Q])/2))})}}const b={key:i,cells:u,cell:Math.max(.05,m),slots:d,ms:performance.now()-l,tris:f,solid:p};for(ma.set(i,b);ma.size>6;){const[g,v]=ma.entries().next().value;ma.delete(g),v.cells.forEach(y=>{y.geo.dispose(),y.core?.dispose()})}return b}function zb(e,n){return e.k==="particles"?Ud(e,10+n):e.k==="segments"?Xd(e,10+n):e.k==="props"?Vd(e):e.k==="shell"?Yd(e,10+n):null}const Qn=(e,n)=>typeof e=="number"&&Number.isFinite(e)?e:n,pa=e=>od.has(String(e.fx?.params?.recipe));function Bb(e,n,s,o){const i=e.fx?.attach,r=i&&n?.items.find(l=>l.id===i.to);return i&&r?Qm(gs(r,s,o),Do(e,s,o).position,i):[...gs(e,s,o).position]}class Kb{constructor(n){this.host=n,this.group.name="mix-fx"}group=new rn;effs=new Map;groups=new Map;stage=null;share=1;m=new At;r=new At;v=new oe;rev=0;marker(n){const s=n.fx?.params??{},o=Number(s.radius??1.5),i=Number(s.falloff??0),r=new rn,l=new ut(new ir(pa(n)?.3:.18),new fs({color:n.color,depthTest:!1,transparent:!0,opacity:.9}));if(l.renderOrder=999,!pa(n)){const h=new ut(new Hn(o,28,18),new fs({color:n.color,wireframe:!0,transparent:!0,opacity:.5,depthTest:!1})),u=new ut(new Hn(o+i,24,14),new fs({color:n.color,transparent:!0,opacity:.07,depthWrite:!1,depthTest:!1,side:ys}));h.raycast=Xc,u.raycast=Xc,h.renderOrder=u.renderOrder=999,h.userData.mixSphere=!0,r.add(u,h)}return r.add(l),r.traverse(h=>h.layers.set(1)),r.userData.fxMarker=!0,r}sync(n,s){this.stage=n;const o=new Set(s.map(r=>r.id));for(const[r,l]of this.effs)o.has(r)||(this.dropBursts(l.bursts),this.effs.delete(r));for(const r of this.groups.values())this.unbind(r),this.dropBursts(r.bursts);this.groups.clear();const i=new Map;for(const r of s){const h=this.effs.get(r.id)??{item:r,hits:[],samples:[],plan:null,burstKey:"",bursts:[]};h.item=r,this.effs.set(r.id,h);const u=n.items.find(d=>d.id===r.fx?.target?.to&&d.id!==r.id&&Zd.has(d.kind)&&!d.hidden);if(!u){this.dropBursts(h.bursts),h.burstKey="";continue}const m=i.get(u.id)??{target:u,effs:[]};m.effs.push(h),i.set(u.id,m)}for(const[r,{target:l,effs:h}]of i){const u=this.host.object(r);if(!u)continue;const m=h[0].item.fx,d=Number(m.params.chunks),f=m.seed,p=_b(u,l,d,f),b=h.slice(1).some(k=>Math.round(Number(k.item.fx.params.chunks))!==Math.round(d)||k.item.fx.seed!==f),g=Jd(u),v=g.flatMap(dr),y={id:r,target:l,root:u,frac:p,effs:h,note:b?h[0].item.id:null,meshes:[],cores:[],originals:g,planFor:null,planKey:"",matrices:[],rest:0,boxes:[],graph:null,graphKey:"",entries:[],falls:[],burstKey:"",bursts:[]};y.meshes=p.cells.map((k,C)=>{const S=new ut(k.geo,v.length?v:[new ns({color:l.color})]);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk ${C}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),y.cores=p.cells.map((k,C)=>{if(!k.core)return null;const S=new ut(k.core,Pb);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk core ${C}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),this.groups.set(r,y)}for(const r of this.effs.values())[...this.groups.values()].some(l=>l.effs.includes(r))||(this.dropBursts(r.bursts),r.burstKey="")}unbind(n){for(const s of n.meshes)this.group.remove(s);for(const s of n.cores)s&&this.group.remove(s);for(const s of n.originals)s.visible=!0;n.meshes=[],n.cores=[],n.originals=[]}dropBursts(n){for(const s of n)for(const o of s.layers)o.dispose(),this.group.remove(o.object);n.length=0}ensure(n,s){if(n.planFor===s)return;n.planFor=s;const o=n.target,i=gn(s),r=Math.max(.1,s.duration),l=Math.max(1/i,r/Fb),h=n.effs.map(w=>Rn(w.item,s)),u=n.effs.map(w=>{const E=w.item.fx?.attach,N=E&&this.stage?.items.find(A=>A.id===E.to);return N?[N.position,N.rotation,N.scale,s.objectKeys?.[N.id]]:null}),m=JSON.stringify([n.effs.map(w=>[w.item.fx,w.item.position,w.item.scale,s.objectKeys?.[w.item.id]]),u,h,o.position,o.rotation,o.scale,s.objectKeys?.[o.id],r,l,n.frac.key]);if(m===n.planKey)return;n.planKey=m,this.rev++;const d=n.frac.cells,f=d.length,p=n.effs[0].item.fx,b=p.params,g=[];for(let w=0;;w++){const E=Math.min(r,w*l);if(g.push(E),E>=r)break}const v=g.map(w=>{const E=gs(o,s,w/r);return Bm(E.position,E.rotation,E.scale)});n.matrices=v.map(w=>new At().fromArray(w));const y=b.support!=="off",k=[];n.effs.forEach((w,E)=>{const N=w.item.fx.params,A=h[E];w.plan=null,w.hits=[],w.samples=[],!(A.off||pa(w.item))&&(w.samples=g.map((O,H)=>({t:O,c:Bb(w.item,this.stage,s,O/r),r:Number(N.radius)*Math.max(.05,Math.abs(w.item.fx?.attach?w.item.scale[0]:gs(w.item,s,O/r).scale[0])),m:v[H]})),w.hits=Km(d,w.samples,{falloff:Number(N.falloff),start:A.start,end:A.start+A.duration,collapse:y?0:Number(N.collapse),cell:n.frac.cell,seed:w.item.fx.seed}),k.push({e:E,hits:w.hits}))});const C=Math.min(...h.filter(w=>!w.off).map(w=>w.start),r);n.rest=Hm(g.map(w=>({t:w})),C),n.boxes=d.map(w=>sx(v[n.rest],w.c,w.h));const S=(()=>{const w=[0,2].map(N=>Math.min(...n.boxes.map(A=>A.min[N]))),E=[0,2].map(N=>Math.max(...n.boxes.map(A=>A.max[N])));return[(w[0]+E[0])/2,0,(w[1]+E[1])/2]})(),I=n.effs.some((w,E)=>!h[E].off&&pa(w.item));n.falls=new Array(f).fill(null);const j=xx(f,k);if(y&&k.length){const w=`${n.frac.key}|${n.rest}|${v[n.rest].map(A=>A.toFixed(4)).join(",")}`;(n.graphKey!==w||!n.graph)&&(n.graph=ax(n.boxes,{cell:n.frac.cell}),n.graphKey=w);const E=lx(n.graph,j,{slack:rx(Qn(b.collapse,.85)),seed:p.seed,centres:n.boxes.map(A=>A.c)}),N=I?[]:[...Array(f).keys()].filter(A=>!Number.isFinite(j[A])&&!E[A]);n.falls=dx(n.boxes,E,N,{base:n.graph.base,cell:n.frac.cell,seed:p.seed,centre:S})}const M=Float64Array.from(j,(w,E)=>Math.min(w,n.falls[E]?.t??1/0)),T=[];n.effs.forEach((w,E)=>{const N=w.item.fx.params,A=h[E];A.off||!pa(w.item)||(w.plan=ux(n.boxes,{mode:String(N.mode),start:A.start,duration:A.duration,yaw:Qn(N.yaw,0),crumble:Qn(N.crumble,.6),seed:w.item.fx.seed,cell:n.frac.cell,gone:M,gravity:Qn(N.gravity,9.8)}),T.push({e:E,plan:w.plan}))}),n.entries=gx(f,{blasts:k,collapses:T,falls:n.falls}),this.ensureBursts(n,s)}makeBurst(n,s,o,i,r,l,h,u,m,d,f={}){if(!$o[n.preset])return null;const p=n.fill?Math.max(n.duration,d.duration-o):n.duration,b={preset:n.preset,intensity:Math.min(3,u),seed:qa(i|0,l,r+7)%1e9,duration:p,loop:!1,params:{...Wm(n.preset),...n.params,...f}},g=[],v=[];for(const[y,k]of ad(b,{color:h,size:m}).entries()){if(k.k==="light"){v.push(k);continue}const C=zb(k,y);C&&(C.hide(),C.setShare(this.share),g.push(C),this.group.add(C.object))}return{t:o,at:s,dur:p,tail:$o[n.preset].tail??0,layers:g,lights:v,size:m}}ensureBursts(n,s){const o=Math.min(4,Math.max(.6,n.frac.cell*1.3));for(const d of n.effs){const f=d.item.fx,p=f.params,b=Wa[p.recipe]??Wa.collapse,g=Number(p.debris);Rn(d.item,s);let v=[];if(d.plan){const k=d.plan,C=[Math.max(...n.boxes.map(I=>I.max[0]))-Math.min(...n.boxes.map(I=>I.min[0])),Math.max(...n.boxes.map(I=>I.max[2]))-Math.min(...n.boxes.map(I=>I.min[2]))];v=[{t:k.t0,at:[k.centre[0],k.base,k.centre[2]],base:!0}];const S=g<=.01?0:Math.max(1,Math.round(b.maxBursts*Math.min(1,.35+g*.55)));for(let I=0;I<S;I++){const j=I/Math.max(1,S)*Math.PI*2+.6;v.push({t:k.t0+k.D*(.3+.6*(I/Math.max(1,S))),at:[k.centre[0]+Math.cos(j)*C[0]*.45,k.base,k.centre[2]+Math.sin(j)*C[1]*.45]})}}else{const k=g<=.01?0:Math.max(1,Math.round(b.maxBursts*Math.min(1,.35+g*.55)));v=ql(d.hits,k)}const y=JSON.stringify([v.map(k=>[+k.t.toFixed(3),...k.at.map(C=>+C.toFixed(2))]),p.recipe,p.dust,g,d.item.color,f.seed,s.duration,o,f.intensity,n.boxes.length]);y!==d.burstKey&&(this.dropBursts(d.bursts),d.burstKey=y,v.forEach((k,C)=>b.bursts.forEach((S,I)=>{const j=S.at==="base";if(j!==!!k.base)return;const M=j?[0,1,2].map(E=>Math.max(...n.boxes.map(N=>N.max[E]))-Math.min(...n.boxes.map(N=>N.min[E]))):null,T=M?{width:Math.max(2,M[0]*1.6),height:Math.max(2,M[1]),depth:Math.max(2,M[2]*1.6),dust:Qn(p.dust,1),spread:d.plan?.D??3}:{},w=this.makeBurst(S,k.at,k.t,f.seed,I,C,d.item.color,(.55+.6*g)*f.intensity,j?1:o,s,T);w&&d.bursts.push(w)})))}const i=n.effs[0].item,l=n.falls.map((d,f)=>d?{f:d,i:f}:null).filter(Boolean).map(({f:d,i:f})=>({t:d.t+Math.sqrt(2*Math.max(0,d.p0[1]-d.land)/Math.max(.5,Number(i.fx.params.gravity))),at:[d.to[0],d.land,d.to[1]],i:f})).sort((d,f)=>d.t-f.t||d.i-f.i),h=Math.min(3,l.length),u=[];for(let d=0;d<h;d++){const f=l.slice(Math.floor(d*l.length/h),Math.floor((d+1)*l.length/h));f.length&&u.push({t:f[0].t,at:Hb(f.map(p=>p.at))})}const m=JSON.stringify([u.map(d=>[+d.t.toFixed(3),...d.at.map(f=>+f.toFixed(2))]),i.color,i.fx.seed,s.duration,o]);m!==n.burstKey&&(this.dropBursts(n.bursts),n.burstKey=m,u.forEach((d,f)=>{const p=this.makeBurst({preset:"va_cham",params:{kind:"dust"},duration:1.4},[d.at[0],Math.max(0,d.at[1]),d.at[2]],d.t,i.fx.seed,3,f+50,"#b59a7a",1,o*1.4,s);p&&n.bursts.push(p)}))}impacts(n){const s=[],o=Math.max(.1,n.duration),i=(r,l)=>{const h=r/o;l>.01&&h>=0&&h<=1&&s.push({time:+h.toFixed(4),strength:Math.min(1,l)})};for(const r of this.groups.values()){this.ensure(r,n);for(const u of r.effs){const m=Qn(u.item.fx.params.shake,.5);if(!(m<=.01))if(u.plan){const d=u.plan;i(d.t0+.05,m*.45),i(d.t0+d.D*.4,m),i(d.t0+d.D*.75,m*.85),i(d.t0+d.D,m*(d.mode==="topple"?1:.6))}else ql(u.hits,3).forEach((d,f)=>i(d.t,m*(f===0?1:.6)))}const l=Qn(r.effs[0].item.fx.params.shake,.5),h=r.falls.reduce((u,m)=>m&&m.t<u?m.t:u,1/0);Number.isFinite(h)&&l>.01&&i(h+.35,l*.45)}return s.sort((r,l)=>r.time-l.time||l.strength-r.strength)}update(n,s){const o=[],i=r=>{for(const l of r){const h=s-l.t;if(h<0||h>l.dur+l.tail){l.layers.forEach(m=>m.hide());continue}const u=No(l.at,0,l.size);u.target=l.at,u.light=1,u.volume=null;for(const m of l.layers)m.update(h,u);for(const m of l.lights){const d=m.eval(h,u);d&&d.intensity>.01&&o.push({pos:d.pos,color:d.color,intensity:d.intensity})}}};for(const r of this.groups.values()){if(!r.effs.some(d=>!Rn(d.item,n).off)||!r.frac.cells.length){for(const d of r.originals)d.visible=!0;for(const d of r.meshes)d.visible=!1;for(const d of r.cores)d&&(d.visible=!1);for(const d of r.effs)d.bursts.forEach(f=>f.layers.forEach(p=>p.hide()));r.bursts.forEach(d=>d.layers.forEach(f=>f.hide()));continue}this.ensure(r,n);for(const d of r.originals)d.visible=!1;r.root.updateWorldMatrix(!0,!1);const h=r.root.matrixWorld,u=r.effs[0].item.fx.params,m={gravity:Qn(u.gravity,9.8),seed:r.effs[0].item.fx.seed,crumble:Qn(u.crumble,.6)};r.meshes.forEach((d,f)=>{const p=r.entries[f],b=r.cores[f];let g=null,v=null,y=r.rest;if(p?.kind==="hit"){const k=r.effs[p.e],C=k.hits[f],S=k.item.fx.params;g=Gm(C,f,s,{strength:Number(S.strength),lift:Number(S.lift),gravity:Number(S.gravity),spin:Number(S.spin),seed:k.item.fx.seed}),v=C.p0,y=C.s}else if(p?.kind==="fall"){const k=r.falls[f];g=hx(k,f,s,m),v=k.p0}else p?.kind==="collapse"&&(g=Ac(r.effs[p.e].plan,r.boxes[f],f,s),v=r.boxes[f].c);d.visible=!0,!g||!v?(d.matrix.copy(h),b&&(b.visible=!1)):(this.m.copy(r.matrices[y]),this.m.premultiply(this.r.makeTranslation(-v[0],-v[1],-v[2])),this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.axis[0],g.axis[1],g.axis[2]),g.angle)),g.extra&&this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.extra.axis[0],g.extra.axis[1],g.extra.axis[2]).normalize(),g.extra.angle)),this.m.premultiply(this.r.makeTranslation(g.pos[0],g.pos[1],g.pos[2])),d.matrix.copy(this.m),b&&(b.visible=!0,b.matrix.copy(this.m),b.matrixWorldNeedsUpdate=!0)),d.matrixWorldNeedsUpdate=!0});for(const d of r.effs)i(d.bursts);i(r.bursts)}return o}setShare(n){this.share=n;for(const s of this.effs.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n));for(const s of this.groups.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n))}pick(n){const s=this.group.children.filter(i=>i.visible&&i.userData.mixTarget);if(!s.length)return null;this.group.updateMatrixWorld(!0);const o=n.intersectObjects(s,!1)[0];return o?{id:String(o.object.userData.mixTarget),distance:o.distance}:null}groupOf(n){for(const s of this.groups.values())if(s.effs.some(o=>o.item.id===n))return s;return null}stats(n){return[...this.effs.values()].map(s=>{const o=this.groupOf(s.item.id),i=o?o.effs.indexOf(s):-1,r=o?o.entries.filter((l,h)=>l&&n>=l.t&&(l.kind!=="collapse"||Ac(o.effs[l.e].plan,o.boxes[h],h,n))).length:0;return{id:s.item.id,target:o?.id??null,chunks:o?.frac.cells.length??0,tris:o?.frac.tris??0,ms:Math.round(o?.frac.ms??0),broken:r,hit:s.hits.filter(Boolean).length,bursts:s.bursts.length,falling:o?o.entries.filter(l=>l?.kind==="fall").length:0,own:o?o.entries.filter(l=>l&&l.e===i).length:0,cores:o?o.cores.filter(Boolean).length:0,first:s.hits.reduce((l,h)=>h&&(l===null||h.t<l)?h.t:l,null),lead:o?.effs[0].item.id??null,overridden:!!o&&i>0&&o.note!==null}})}chunkCentres(n){const s=this.groupOf(n);return s?s.meshes.map((o,i)=>{const r=s.frac.cells[i].c,l=new oe(r[0],r[1],r[2]).applyMatrix4(o.matrix);return[l.x,l.y,l.z]}):[]}visibleCounts(n){const s=this.groupOf(n);return s?{chunks:s.meshes.filter(o=>o.visible).length,cells:s.frac.cells.length,originals:s.originals.filter(o=>o.visible).length,meshes:this.group.children.filter(o=>o.userData.mixTarget===s.id&&o.isMesh&&!o.name.includes("core")&&o.visible).length}:null}dispose(){for(const n of this.groups.values())this.unbind(n),this.dropBursts(n.bursts);for(const n of this.effs.values())this.dropBursts(n.bursts);this.groups.clear(),this.effs.clear(),this.group.parent?.remove(this.group)}}function Hb(e){const n=e.reduce((s,o)=>[s[0]+o[0],s[1]+o[1],s[2]+o[2]],[0,0,0]);return[n[0]/e.length,n[1]/e.length,n[2]/e.length]}const Wb=Math.PI/180,Gb=xn.maxLights,qb={day:1,golden:.8,overcast:.85,night:.22};class Ub{constructor(n,s){this.host=s,this.group.name="fx",this.mix=new Kb(s),n.add(this.group,this.pathGroup,this.mix.group)}group=new rn;insts=new Map;lights=[];share=1;heat=[];light={fill:0,color:[1,1,1],pos:null,sources:[]};stage;only=null;pathGroup=new rn;mix;syncPath(n,s){this.pathGroup.traverse(h=>{(h instanceof ut||h instanceof Ri)&&(h.geometry.dispose(),h.material.dispose())}),this.pathGroup.clear();const o=s&&n.items.find(h=>h.id===s.itemId),i=o?.fx?.path;if(!s||!i||i.length<2)return;const r=Jm(i),l=new Ri(new Tt().setFromPoints(Array.from({length:48},(h,u)=>new oe(...r.at(u/47)))),new xc({color:"#b8df78",depthTest:!1,transparent:!0,opacity:.9}));l.renderOrder=998,l.layers.set(1),this.pathGroup.add(l),i.forEach((h,u)=>{const m=new ut(new Hn(.1,14,10),new fs({color:u===s.selected?"#ffad52":u===0?"#7fe9ff":"#b8df78",depthTest:!1}));m.position.set(...h),m.userData.fxPoint=u,m.renderOrder=999,m.layers.set(1),this.pathGroup.add(m)})}pathHandles(){return this.pathGroup.children.filter(n=>n.userData.fxPoint!==void 0)}setFilter(n){this.only=n}get active(){return this.insts.size>0}marker(n){if(n.fx?.preset===Ji)return this.mix.marker(n);const s=new rn,o=new ut(new ir(.13),new fs({color:n.color,wireframe:!0,depthTest:!1,transparent:!0,opacity:.9})),i=new ut(new ir(.06),new fs({color:n.color,depthTest:!1,transparent:!0,opacity:.85})),r=new Ri(new Tt().setFromPoints([new oe(0,0,0),new oe(0,-.4,0)]),new xc({color:n.color,depthTest:!1,transparent:!0,opacity:.45}));return o.renderOrder=i.renderOrder=r.renderOrder=999,s.add(o,i,r),s.traverse(l=>l.layers.set(1)),s.userData.fxMarker=!0,s.position.y=0,s}sync(n){this.stage=n;const s=new Map;let o=0,i=0;for(const r of n.items){if(r.kind!=="fx"||!r.fx||r.hidden)continue;if(++i>xn.maxItems)break;const l=er(r.fx);if(!l.fx)continue;const h=tr(l.fx);h>xn.maxParticlesPerItem||o+h>xn.maxTotalParticles||(o+=h,s.set(r.id,r))}for(const[r,l]of this.insts)s.has(r)||this.drop(r,l);for(const[r,l]of s){const h=this.sizeOf(l,n),u=JSON.stringify([l.fx,l.color,h]),m=this.insts.get(r);if(m?.key===u){m.item=l;continue}m&&this.drop(r,m),this.insts.set(r,this.build(l,h,u))}this.mix.sync(n,[...s.values()].filter(r=>r.fx?.preset===Ji)),this.ensureLights()}sizeOf(n,s){const o=Math.max(.1,n.scale[0]),i=n.fx?.attach&&s.items.find(r=>r.id===n.fx.attach.to);return o*(i?this.host.figureScale(i)*Math.max(.1,i.scale[1]):1)}build(n,s,o){const i=er(n.fx).fx,r=ad(i,{color:n.color,size:s}),l=new rn;l.name=`fx:${n.name}`;const h=[],u=[],m=[],d=r.length?Vb(n.color):[.3,.8,1];return r.forEach((f,p)=>{if(f.k==="light"){u.push(f);return}if(f.k==="heat"){m.push(f);return}const b=f.k==="particles"?Ud(f,10+p):f.k==="segments"?Xd(f,10+p):f.k==="swords"?wb(f,d):f.k==="props"?Vd(f):f.k==="water"?gb(f,5+p):f.k==="ghost"?Ib(f,10+p,()=>n.fx?.attach?this.host.object(n.fx.attach.to):void 0):Yd(f,10+p);b.hide(),b.setShare(this.share),h.push(b),l.add(b.object)}),l.visible=!1,this.group.add(l),{item:n,key:o,layers:h,defs:r,tail:ep(i.preset),group:l,lights:u,heats:m,budget:tr(i),share:this.share}}drop(n,s){s.layers.forEach(o=>o.dispose()),this.group.remove(s.group),this.insts.delete(n)}ensureLights(){if(this.insts.size&&!this.lights.length)for(let n=0;n<Gb;n++){const s=new Z0(16777215,0,0,2);s.visible=!0,this.lights.push(s),this.group.add(s)}if(!this.insts.size&&this.lights.length){for(const n of this.lights)this.group.remove(n),n.dispose();this.lights=[]}}frameOf(n,s,o,i,r=0){const l=n.fx?.attach,h=l&&this.host.object(l.to);if(!l||!h)return No([o.position.x,o.position.y,o.position.z],o.rotation.y,s);h.updateWorldMatrix(!0,!1);const u=Do(n,i??{},r),m=u.yaw*Wb,d=(l.follow==="position"?0:h.rotation.y)+m,f=new oe(...u.position);let p;if(l.hand&&l.tip){const b=this.stage?.items.find(v=>v.hold?.by===l.to&&v.hold.hand===l.hand&&v.prop&&!v.hidden),g=Ul(h,l.hand);if(b?.prop&&b.hold&&g.frame){const v=tp(g.frame,b.prop.kind,b.hold.angle??0,b.hold.tilt,g.fist),y=v.tip.clone().sub(v.grip);return No([v.tip.x,v.tip.y,v.tip.z],Math.atan2(y.x,y.z),s)}}if(l.hand){o.userData.fxOffsetYaw=d,o.userData.fxOffsetScale=1;const b=Ul(h,l.hand);p=b.frame?b.frame.localToWorld(b.fist.clone()):h.getWorldPosition(new oe).add(new oe(l.hand==="R"?-.3:.3,1,.3)),p.add(f.applyAxisAngle(new oe(0,1,0),d))}else{const b=h.getWorldPosition(new oe),g=l.part?h.getObjectByName("head")?.getWorldPosition(new oe):void 0,v=g&&l.part==="head"?g:g?b.clone().lerp(g,.74):b;o.userData.fxOffsetYaw=l.follow==="position"?0:h.rotation.y,o.userData.fxOffsetScale=h.scale.x||1,p=v.add(f.multiply(h.scale).applyAxisAngle(new oe(0,1,0),l.follow==="position"?0:h.rotation.y))}return No([p.x,p.y,p.z],d,s)}hidden=new Set;hideTargets(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return[];if(!s.name)return[o];const i=s.name.toLowerCase(),r=[];return o.traverse(l=>{l instanceof ut&&l.name.toLowerCase().includes(i)&&r.push(l)}),r}volumeOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to),i=s&&this.stage?.items.find(m=>m.id===s.to);if(!s||!o||!i)return null;o.updateWorldMatrix(!0,!0);const r=m=>[m.r,m.g,m.b];if(s.name){const m=s.name.toLowerCase(),d=new zt;let f=null;if(o.traverse(g=>{if(g instanceof ut&&g.name.toLowerCase().includes(m)){d.expandByObject(g);const v=Array.isArray(g.material)?g.material[0]:g.material;!f&&v.color&&(f=r(v.color))}}),d.isEmpty())return null;const p=d.getSize(new oe),b=d.getCenter(new oe);return p.x>=p.z?{size:[p.x,p.y,p.z],base:[b.x,d.min.y,b.z],yaw:0,color:f??r(new Ue(i.color))}:{size:[p.z,p.y,p.x],base:[b.x,d.min.y,b.z],yaw:Math.PI/2,color:f??r(new Ue(i.color))}}if(i.kind==="proxy"&&i.proxy){const m=i.proxy.dims,d=o.scale,f=o.getWorldPosition(new oe);return{size:[m[0]*d.x,m[1]*d.y,m[2]*d.z],base:[f.x,f.y,f.z],yaw:o.rotation.y,color:r(new Ue(i.color))}}const l=new zt().setFromObject(o);if(l.isEmpty())return null;const h=l.getSize(new oe),u=l.getCenter(new oe);return{size:[h.x,h.y,h.z],base:[u.x,l.min.y,u.z],yaw:0,color:r(new Ue(i.color))}}targetOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return null;o.updateWorldMatrix(!0,!0);const i=o.getWorldPosition(new oe),r=this.stage?.items.find(m=>m.id===s.to)?.kind==="person";if(s.part==="feet")return[i.x,i.y,i.z];const l=r?o.getObjectByName("head")?.getWorldPosition(new oe):null;if(s.part==="head"&&l)return[l.x,l.y+.1,l.z];if(r&&l){const m=i.clone().lerp(l,.74);return[m.x,m.y,m.z]}const h=new zt().setFromObject(o);if(h.isEmpty())return[i.x,i.y+1,i.z];const u=h.getCenter(new oe);return[u.x,u.y,u.z]}headOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;let i=o.getObjectByName("head");if(i||o.traverse(l=>{!i&&/head/i.test(l.name)&&!/top|end|scale|ref|_end|nub/i.test(l.name)&&(i=l)}),i){const l=i.getWorldPosition(new oe);return[l.x,l.y,l.z]}const r=new zt().setFromObject(o);return r.isEmpty()?null:[(r.min.x+r.max.x)/2,r.max.y-(r.max.y-r.min.y)*.08,(r.min.z+r.max.z)/2]}feetBox=new zt;feetOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;const i=Qd(o,this.feetBox);return i.isEmpty()?null:[(i.min.x+i.max.x)/2,i.min.y,(i.min.z+i.max.z)/2]}offsetAfterDrag(n,s,o,i){const r=this.stage?.items.find(p=>p.id===n),l=this.host.object(n);if(!r?.fx?.attach||!l?.userData.fxAttached)return null;const h=Do(r,s,o),u=l.userData.fxOffsetYaw??0,m=l.userData.fxOffsetScale??1,d=new oe(l.position.x-i.position[0],l.position.y-i.position[1],l.position.z-i.position[2]).applyAxisAngle(new oe(0,1,0),-u).divideScalar(m),f=p=>+p.toFixed(3);return{position:[f(h.position[0]+d.x),f(h.position[1]+d.y),f(h.position[2]+d.z)],rotation:[0,f(h.yaw+zn.radToDeg(l.rotation.y-i.yaw)),0]}}impacts(n,s){const o=np(n.items,s),i=this.mix.impacts(s);return i.length?[...o,...i]:o}get impactsRev(){return this.mix.rev}pickChunk(n){return this.mix.pick(n)}mixStats(n){return this.mix.stats(n)}update(n,s,o){if(!this.stage)return;const i=[],r=new Set;this.heat=[],Gr.uOcclude.value=Gc[this.stage.lighting?.time??"day"]??Gc.day;for(const l of this.insts.values()){const h=this.host.object(l.item.id);h&&h.traverse(k=>{k.userData.fxMarker&&(k.visible=o)});const u=Rn(l.item,n),m=h?sp(u,s,l.tail):null,d=$o[l.item.fx.preset]?.hides===!0;if(d&&!u.off&&s>=u.start)for(const k of this.hideTargets(l.item))r.add(k);if(m===null||!h||this.only&&!this.only(l.item)){l.group.visible=!1,l.layers.forEach(k=>k.hide());continue}l.group.visible=!0;const f=this.sizeOf(l.item,this.stage),p=this.frameOf(l.item,f,h,n,n.duration>0?s/n.duration:0);p.target=this.targetOf(l.item),p.head=this.headOf(l.item);const b=l.defs.some(k=>k.k==="ghost");p.feet=b?this.feetOf(l.item):null;const g=b&&l.item.fx?.attach&&!l.item.fx.attach.hand&&!l.item.fx.attach.part?this.host.object(l.item.fx.attach.to):void 0;p.shift=g?(()=>{const k=g.getWorldPosition(new oe);return[p.origin[0]-k.x,p.origin[1]-k.y,p.origin[2]-k.z]})():null,p.volume=d?this.volumeOf(l.item):null,p.light=qb[this.stage.lighting?.time??"day"]??1,o&&h.children[0]?.userData.fxMarker;for(const k of l.layers)k.update(m,p);for(const k of l.lights){const C=k.eval(m,p);C&&(C.intensity>.01||(C.fill??0)>.01)&&i.push({pos:C.pos,color:C.color,intensity:C.intensity,fill:C.fill??Vc(C.intensity)})}for(const k of l.heats){const C=k.eval(m,p);C&&C.amount>.01&&this.heat.push(C)}const v=h.children.find(k=>k.userData.fxMarker),y=l.item.fx?.attach;h.userData.fxAttached=!!y&&!(y.hand&&y.tip),y&&!h.userData.fxDragging&&(h.position.set(...p.origin),h.rotation.set(0,p.yaw,0),h.updateMatrixWorld(!0)),v&&v.position.set(0,0,0)}for(const l of this.hidden)r.has(l)||(l.visible=!0);for(const l of r)l.visible=!1;this.hidden=r,i.push(...this.mix.update(n,s).map(l=>({...l,fill:Vc(l.intensity)}))),i.sort((l,h)=>h.intensity-l.intensity),this.light=Xb(i),this.lights.forEach((l,h)=>{const u=i[h];u?(l.position.set(...u.pos),l.color.setRGB(u.color[0],u.color[1],u.color[2],xs),l.intensity=u.intensity):l.intensity=0})}setQuality(n){const s=n==="draft"?ap:1;if(s!==this.share){this.share=s;for(const o of this.insts.values())o.layers.forEach(i=>i.setShare(s));this.mix.setShare(s)}}dispose(){for(const[n,s]of[...this.insts])this.drop(n,s);this.mix.dispose();for(const n of this.lights)n.dispose();this.lights=[],this.pathGroup.clear(),this.group.parent?.remove(this.group,this.pathGroup)}stats(){return[...this.insts.values()].map(n=>({id:n.item.id,name:n.item.name,visible:n.group.visible,budget:n.budget}))}}const Vc=e=>Math.max(0,e-24)/220;function Xb(e){let n=0,s=0,o=[1,1,1],i=null;for(const l of e)n+=l.fill,l.fill>s&&(s=l.fill,o=l.color,i=l.pos);const r=e.filter(l=>l.intensity>.5).slice(0,4).map(l=>({pos:l.pos,color:l.color,intensity:l.intensity}));return{fill:Math.min(2,n),color:o,pos:i,sources:r}}function Vb(e){const n=new Ue(e);return[n.r,n.g,n.b]}ss.fxFactory=(e,n)=>new Ub(e,n);ss.fxPrompt=e=>$g(e.items,e.shots.find(n=>n.id===e.activeShot)??e.shots[0]);ss.codeModel=e=>e.gen?.kind!=="code"?Promise.reject(new Error("not a code model")):kg(e.gen.code);const eu={corner:[.01836,-.09969,.15467],upper:[0,-.09717,.1634],lower:[0,-.11192,.15558],cheek:[.03455,-.07455,.11851],browIn:[.01285,-.00904,.14251],browMid:[.02998,-.00104,.13851],browOut:[.04568,-.00704,.12451],nostril:[.011,-.07855,.1674],lidLow:[.02855,-.04704,.13651],chin:[0,-.14492,.14958]},Nt=!0,ft=(e,n=e,s=e)=>[e,n,s];function tu(e){const n=g=>[Math.abs(g[0]),g[1],g[2]],s=n(e.corner),o=n(e.cheek),i=n(e.browIn),r=n(e.browMid),l=n(e.browOut),h=n(e.nostril),u=n(e.lidLow),m=e.upper,d=e.lower,f=e.chin,p=[(h[0]+s[0])/2+.008,(h[1]+s[1])/2,(h[2]+s[2])/2-.006],b=[r[0],r[1]+.022,r[2]-.006];return{smile:[[s,ft(.024,.022,.018),[.0042,.005,-.0028],Nt],[p,ft(.014,.016,.014),[.0014,.0026,.0014],Nt],[o,ft(.022,.018,.02),[.001,.0034,.002],Nt],[u,ft(.012,.008,.01),[0,.0012,4e-4],Nt],[m,ft(.014,.006,.01),[0,.0011,-4e-4]],[d,ft(.014,.006,.01),[0,-5e-4,-6e-4]]],angry:[[i,ft(.014,.011,.012),[-.0024,-.0032,.0012],Nt],[r,ft(.014,.011,.012),[-8e-4,-.0018,6e-4],Nt],[h,ft(.008),[.0011,7e-4,0],Nt],[s,ft(.013,.011,.012),[-8e-4,-.0014,0],Nt],[m,ft(.011,.006,.009),[0,-5e-4,3e-4]],[d,ft(.011,.006,.009),[0,7e-4,4e-4]],[f,ft(.016,.012,.012),[0,.001,6e-4]]],surprise:[[i,ft(.016,.013,.014),[0,.0042,4e-4],Nt],[r,ft(.017,.014,.014),[0,.005,3e-4],Nt],[l,ft(.015,.013,.013),[0,.0036,0],Nt],[b,ft(.03,.016,.02),[0,.0014,0],Nt],[s,ft(.012,.01,.011),[-.0013,-5e-4,2e-4],Nt]],sad:[[i,ft(.013,.011,.012),[5e-4,.0036,5e-4],Nt],[l,ft(.013,.011,.012),[0,-.0018,0],Nt],[s,ft(.016,.016,.014),[-6e-4,-.0046,-6e-4],Nt],[d,ft(.011,.006,.009),[0,.0011,9e-4]],[f,ft(.016,.012,.012),[0,.0014,8e-4]]],pain:[[i,ft(.013,.011,.012),[-.002,-9e-4,9e-4],Nt],[r,ft(.014,.011,.012),[0,-.0022,5e-4],Nt],[o,ft(.02,.016,.018),[7e-4,.0032,.0014],Nt],[s,ft(.018,.016,.014),[.0044,-.0012,-.0024],Nt],[m,ft(.012,.006,.009),[0,.0019,3e-4]],[h,ft(.009),[9e-4,.0013,0],Nt],[u,ft(.011,.008,.01),[0,.0014,5e-4],Nt]]}}let nu=tu(eu);function Yb(e){nu=tu(e??eu)}const Qb=e=>e>=1?0:(1-e)**4*(1+4*e);function Zb(e,n,s,o,i,r=1){for(const[l,h,u,m]of nu[e])for(const d of m?[1,-1]:[1]){const f=Math.hypot((n-l[0]*d)/h[0],(s-l[1])/h[1],(o-l[2])/h[2]);if(f>=1)continue;const p=Qb(f)*r;i[0]+=u[0]*d*p,i[1]+=u[1]*p,i[2]+=u[2]*p}}function su(e,n,s){const o=e.length/3,i=[];for(const r of Er){const l=new Float32Array(o*3),h=[0,0,0];for(let u=0;u<o;u++){const m=s?s(u):1;m<=0||(h[0]=h[1]=h[2]=0,Zb(r,e[u*3]-n[0],e[u*3+1]-n[1],e[u*3+2]-n[2],h,m),l[u*3]=h[0],l[u*3+1]=h[1],l[u*3+2]=h[2])}i.push(l)}return i}let Js=null,fa=null;const ur=new Set;function Jb(e){const n=new Uint8Array(e,0,8);if(String.fromCharCode(...n.slice(0,4))!=="HQB1")throw new Error("HQ character asset: bad magic");const s=new DataView(e).getUint32(4,!0),o=JSON.parse(new TextDecoder().decode(new Uint8Array(e,8,s)));if(o.version!==Xl)throw new Error(`HQ character asset: version ${o.version}, expected ${Xl}`);const i=8+s+((8+s)%4?4-(8+s)%4:0),r=p=>new Float32Array(e,i+p.at,p.n),l=p=>new Uint8Array(e,i+p.at,p.n),h=p=>new Uint16Array(e,i+p.at,p.n),u=p=>new Uint32Array(e,i+p.at,p.n),m=p=>new Int16Array(e,i+p.at,p.n),d=o.lods.map(p=>({vertices:p.vertices,triangles:p.triangles,position:r(p.position),index:p.index32?u(p.index):h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),region:l(p.region),morphs:p.morphs.map(b=>({data:m(b),scale:b.scale}))})),f=new Map;for(const p of o.hair)f.set(p.id,{id:p.id,kind:p.kind,position:r(p.position),index:h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),flow:r(p.flow),bones:p.chains.bones,chains:p.chains.chains});return{version:o.version,license:o.license,bones:o.bones,regions:o.regions,morphs:o.morphs,lods:d,hair:f,bind:o.bind,face:o.face,sources:o.sources??[],bytes:e.byteLength}}function ey(e){Js=Jb(e),Yb(Js.face.landmarks);for(const n of[...ur])n();return Js}const Ur=()=>Js;function ty(e){return Js?Promise.resolve(Js):fa||(fa=fetch(`/${op}`).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.arrayBuffer()}).then(ey).catch(s=>{throw fa=null,s}),fa)}function au(e){return ur.add(e),()=>{ur.delete(e)}}const As=zn.degToRad,Yc=new Qe,ny=new Qe;new rr;function sy(e){const n=ld(e),s=Math.min(1,Math.max(0,(e.blink||0)/100));let o=0,i=0,r=0;for(const l of Er)o+=yi[l].lidU*n[l],i+=yi[l].lidD*n[l],r+=yi[l].jaw*n[l];return o=o-(e.eyePitch||0)*.45,o=o+(46-o)*s,i=i+(4-i)*s,{lidU:Math.max(-14,Math.min(46,o)),lidD:Math.max(-6,Math.min(14,i)),jaw:Math.max(0,Math.min(22,r))}}function Xr(e,n,s={}){const o=new rn,i=new Map;for(const h of Qo(e,n,s)){const u=new $a;u.name=h.name,(h.parent?i.get(h.parent):o).add(u),i.set(h.name,u)}const r=new $a;r.name="pelvis",i.get("torso").add(r),i.set("pelvis",r);for(const[h,,u]of id){const m=new $a;m.name=h,i.get(u).parent.add(m),i.set(h,m)}const l={root:o,body:i.get("torso"),bones:i};return Ho(l,e,n,s),l}function Ho(e,n,s,o={}){const{bones:i}=e;for(const u of Qo(n,s,o)){const m=i.get(u.name);m.position.set(u.p[0],u.p[1],u.p[2]),m.rotation.set(As(u.r[0]),As(u.r[1]),As(u.r[2]),u.order),m.scale.setScalar(u.s)}const r=o.bind?{lidU:0,lidD:0,jaw:0}:sy(s);for(const u of["L","R"])i.get(`lidU${u}`).rotation.set(As(r.lidU),0,0),i.get(`lidD${u}`).rotation.set(As(-r.lidD),0,0);i.get("jaw").rotation.set(As(r.jaw),0,0);const l=o.bind?0:(s.lean||0)+Ga(n).torsoLean,h=i.get("pelvis");h.position.set(0,ip,0),h.rotation.set(As(-rd*l),0,0),h.scale.setScalar(1);for(const[u,m,d]of id){const f=i.get(d),p=i.get(u);p.position.copy(f.position),Yc.copy(m==="pelvis"?h.quaternion:ny.identity()),p.quaternion.copy(Yc).slerp(f.quaternion,.5),p.scale.setScalar(1+(f.scale.x-1)*.5)}}const ga=new Map,ou=e=>(e.userData.shared=!0,e.userData.realDispose=e.dispose.bind(e),e.dispose=()=>{},e);function ay(e,n){return e.morphs.map(s=>{const o=n[s.param]??s.from,i=(o-s.from)/(s.to-s.from);return i>0?Math.min(i,1.6):0})}function as(e){const n=e.bind.head;return[n[0]+Zs[0],n[1]+Zs[1],n[2]+Zs[2]]}function oy(e){const n=e.face.stats,s=.079/n.half,o=.13/(n.crown-n.eye),i=.202/(n.front-n.back);return new At().makeTranslation(0,n.eye-.026/o,n.back+.117/i).multiply(new At().makeScale(1/s,1/o,1/i))}function iy(e,n,s=0){const o=e.lods[s],i=Float32Array.from(o.position);ay(e,n).forEach((h,u)=>{if(!h)return;const m=o.morphs[u],d=h*m.scale;for(let f=0;f<i.length;f++)i[f]+=m.data[f]*d}),n.fem>.3&&ry(e,o,i,Math.min(1,(n.fem-.3)/.4),s);const l=iu(n.fem);if(l>0){const h=lu(e,o),u=[0,0,0];for(let m=0;m<o.vertices;m++){const d=h(m);d&&(ru(e,i[m*3],i[m*3+1],i[m*3+2],l*d,u),i[m*3]+=u[0],i[m*3+1]+=u[1],i[m*3+2]+=u[2])}}return i}const iu=e=>Math.min(1,Math.max(0,(e-.3)/.4));function ru(e,n,s,o,i,r){if(r[0]=r[1]=r[2]=0,!i)return r;const l=as(e),h=e.face.landmarks,u=n-l[0],m=s-l[1],d=o-l[2],f=(C,S,I)=>{const j=Math.min(1,Math.max(0,(I-C)/(S-C)));return j*j*(3-2*j)},p=h.mouthY,b=(h.upper[2]+h.lower[2])/2,g=Math.exp(-((u/.03)**2+((m-p)/.02)**2))*f(b-.035,b-.012,d);r[0]-=u*.1*g,r[1]-=(m-p)*.55*g,r[2]-=.009*g;const v=h.nostril[1]+.004,y=Math.exp(-((u/.024)**2+((m-v)/.022)**2))*f(h.cheek[2]-.005,h.nostril[2]-.02,d);r[0]-=u*.22*y,r[2]-=.003*y;const k=f(h.cheek[1]+.025,h.chin[1],m)*(1-f(h.chin[1]-.01,h.chin[1]-.045,m))*f(-.05,.05,d);return r[0]-=u*.16*k,r[0]*=i,r[1]*=i,r[2]*=i,r}function ry(e,n,s,o,i){const r=s.length/3,l=e.bind.torso,h=e.bones.indexOf("torso"),u=(K,G,_)=>{const ee=Math.min(1,Math.max(0,(_-K)/(G-K)));return ee*ee*(3-2*ee)},m=new Float32Array(r);for(let K=0;K<r;K++){let G=0;for(let ve=0;ve<4;ve++)n.skinIndex[K*4+ve]===h&&(G+=n.skinWeight[K*4+ve]/255);if(G<=0)continue;const _=s[K*3],ee=s[K*3+1]-l[1],Q=s[K*3+2]-l[2];m[K]=o*Math.min(1,G*1.5)*u(.1,.18,ee)*(1-u(.4,.48,ee))*u(0,.05,Q)*(1-u(.15,.21,Math.abs(_)))}const d=new Int32Array(r),f=new Map;for(let K=0;K<r;K++){const G=`${Math.round(s[K*3]*1e4)}|${Math.round(s[K*3+1]*1e4)}|${Math.round(s[K*3+2]*1e4)}`,_=f.get(G);_===void 0?(f.set(G,K),d[K]=K):(d[K]=_,m[_]=Math.max(m[_],m[K]))}for(let K=0;K<r;K++)m[K]=m[d[K]];const p=Array.from({length:r},()=>[]);for(let K=0;K<n.index.length;K+=3)for(let G=0;G<3;G++){const _=d[n.index[K+G]],ee=d[n.index[K+(G+1)%3]];_!==ee&&(m[_]||m[ee])&&(p[_].push(ee),p[ee].push(_))}let b=0,g=0,v=-1;for(let K=0;K<r;K++)m[K]>.5&&Math.abs(s[K*3])>.03&&s[K*3+2]>v&&(v=s[K*3+2],b=Math.abs(s[K*3]),g=s[K*3+1]);const y=K=>m[K]>0&&((Math.abs(s[K*3])-b)/.1)**2+((s[K*3+1]-g)/.11)**2<1,k=[],C=new Uint8Array(r),S=new Set;for(let K=0;K<r;K++)d[K]===K&&p[K].length&&y(K)&&(k.push(K),C[K]=1);for(const K of k)for(const G of p[K])C[G]||S.add(G);const I=[...S],j=Array.from({length:4},()=>[0,0,0,0,0]);for(const K of I){const G=s[K*3+1]-l[1],_=[1,G,G*G,-(s[K*3]**2)],ee=s[K*3+2];for(let Q=0;Q<4;Q++){for(let ve=0;ve<4;ve++)j[Q][ve]+=_[Q]*_[ve];j[Q][4]+=_[Q]*ee}}for(let K=0;K<4;K++)j[K][K]+=1e-6;for(let K=0;K<4;K++)for(let G=K+1;G<4;G++){const _=j[G][K]/j[K][K];for(let ee=K;ee<5;ee++)j[G][ee]-=_*j[K][ee]}const M=[0,0,0,0];for(let K=3;K>=0;K--){let G=j[K][4];for(let _=K+1;_<4;_++)G-=j[K][_]*M[_];M[K]=G/j[K][K]}const T=Math.max(0,M[3]),w=new Float32Array(r);for(let K=0;K<r;K++)w[K]=s[K*3+2]+T*s[K*3]**2;for(let K=0;K<(i===0?1500:400);K++)for(const G of k){let _=0;for(const ee of p[G])_+=w[ee];w[G]=_/p[G].length}for(let K=0;K<r;K++)w[K]=w[d[K]]-T*s[K*3]**2;let E=0,N=0,A=0,O=0;for(const K of k){const G=s[K*3+2]-w[K];if(G<=0||m[K]<.6)continue;O=Math.max(O,G);const _=G*G*G;E+=Math.abs(s[K*3])*_,N+=s[K*3+1]*_,A+=_}if(!A||O<.004)return;const H=.5*(E/A),D=N/A+.012,$=O*.6,W=.07+.3*O,z=W*.9,Y=W*1.2,J=(K,G)=>{const _=G-D,ee=K-H,Q=_/(_<0?z:Y),ve=(ee/W)**2+Q**2;if(ve>=1)return 0;const xe=Q>0?Q/Math.sqrt(ve+1e-9):0;return $*(1-ve)**(.7+1.5*xe*xe)},V=(K,G,_)=>{const ee=Math.max(0,_-Math.abs(K-G))/_;return Math.max(K,G)+ee*ee*_*.25*Math.min(1,Math.min(K,G)/(.3*$))};for(let K=0;K<r;K++){const G=m[K];if(!G)continue;const _=s[K*3],ee=s[K*3+1],Q=V(J(_,ee),J(-_,ee),.03);s[K*3+2]+=(w[K]+Q-s[K*3+2])*G}}function lu(e,n){const s=["head","jaw","headHalf"].map(o=>e.bones.indexOf(o));return o=>{let i=0;for(let r=0;r<4;r++)s.includes(n.skinIndex[o*4+r])&&(i+=n.skinWeight[o*4+r]/255);return Math.min(1,i*1.15)}}function js(e,n,s=0){const o=`${s}|${Wn(n)}`;let i=ga.get(o);if(i)return i;ga.size>48&&(ga.forEach(u=>u.userData.realDispose()),ga.clear());const r=e.lods[s];i=new Tt;const l=iy(e,n,s);i.setAttribute("position",new Pt(l,3)),i.setIndex(new Pt(r.index,1)),i.setAttribute("skinIndex",new bs(r.skinIndex,4)),i.setAttribute("skinWeight",new bs(r.skinWeight,4,!0)),i.computeVertexNormals();const h=lu(e,r);return i.morphAttributes.position=su(l,as(e),h).map(u=>new Pt(u,3)),i.morphTargetsRelative=!0,i.userData.region=r.region,i.userData.lod=s,i.computeBoundingBox(),i.computeBoundingSphere(),ou(i),ga.set(o,i),i}const xa=new Map;function ly(e,n,s,o){const i=js(e,n,s),r=`${s}|${Wn(n)}|${o.skin}|${o.buzz??""}|${o.stubble??""}`;let l=xa.get(r);if(l)return l;xa.size>64&&(xa.forEach(T=>T.userData.realDispose()),xa.clear()),l=new Tt;for(const T of Object.keys(i.attributes))l.setAttribute(T,i.getAttribute(T));l.setIndex(i.getIndex()),l.morphAttributes=i.morphAttributes,l.morphTargetsRelative=!0,l.boundingBox=i.boundingBox,l.boundingSphere=i.boundingSphere,l.userData={...i.userData};const h=i.userData.region,u=i.getAttribute("position"),m=u.count,d=new Float32Array(m*3),f=new Ue(o.skin),p=as(e),b=o.buzz?new Ue(o.buzz):null,g=o.stubble?new Ue(o.stubble):null,v=e.regions,y=e.face.landmarks,k=v.indexOf("lips"),C=v.indexOf("tip"),S=v.indexOf("ear"),I=v.indexOf("nose"),j=v.indexOf("scalp"),M=v.indexOf("stubble");for(let T=0;T<m;T++){let w=1,E=1,N=1;const A=h[T],O=u.getX(T)-p[0],H=u.getY(T)-p[1],D=u.getZ(T)-p[2];if(A===k){const W=Math.max(0,1-Math.abs(H-y.mouthY)/.0022)*Math.max(0,1-Math.abs(O)/(Math.abs(y.corner[0])+.004));w=.9-.4*W,E=.62-.3*W,N=.62-.3*W}(A===S||A===I)&&(w=1,E=.94,N=.92);const $=Math.max(0,1-((Math.abs(O)-Math.abs(y.cheek[0]))**2+(H-y.cheek[1])**2+(D-y.cheek[2])**2)/6e-4);$>0&&(E*=1-.05*$,N*=1-.05*$),A===C&&(w*=1.06),b&&A===j&&(w=w*(1-.85)+b.r/Math.max(.02,f.r)*.85,E=E*(1-.85)+b.g/Math.max(.02,f.g)*.85,N=N*(1-.85)+b.b/Math.max(.02,f.b)*.85),g&&A===M&&(w=w*(1-.4)+g.r/Math.max(.02,f.r)*.4,E=E*(1-.4)+g.g/Math.max(.02,f.g)*.4,N=N*(1-.4)+g.b/Math.max(.02,f.b)*.4),d[T*3]=w,d[T*3+1]=E,d[T*3+2]=N}return l.setAttribute("color",new Pt(d,3)),ou(l),xa.set(r,l),l}const Qc=new Map,cy=(e,n)=>{let s=Qc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Qc.set(e,s)),s},hy=rp.eyeR;function dy(e){return cy(`eye|${e}`,()=>{const n=[0,.09,.16,.2,.27,.36,.44,.5,.53,.58,.75,1,1.35,1.75,2.2,2.7,Math.PI],s=28,o=[],i=[],r=[],l=new Ue(e),h=l.clone().multiplyScalar(.45),u=new Ue("#e9e4dc"),m=new Ue("#0c0a09"),d=l.clone().multiplyScalar(.25);n.forEach((p,b)=>{const g=p<.5?.0011*Math.cos(p/.5*Math.PI/2):0,v=hy+g,y=p<.17?m:p<.42?l.clone().lerp(h,Math.max(0,(.42-p)/.25)*.6):p<.5?d:p<.55?d.clone().lerp(u,.6):u.clone().lerp(new Ue("#e8cfc6"),Math.max(0,p-1.2)/2);for(let k=0;k<=s;k++){const C=k/s*Math.PI*2;o.push(v*Math.sin(p)*Math.cos(C),v*Math.sin(p)*Math.sin(C),v*Math.cos(p)),i.push(y.r,y.g,y.b)}if(b)for(let k=0;k<s;k++){const C=(b-1)*(s+1)+k,S=C+s+1;r.push(C,S,C+1,C+1,S,S+1)}});const f=new Tt;return f.setAttribute("position",new Bt(o,3)),f.setAttribute("color",new Bt(i,3)),f.setIndex(r),f.computeVertexNormals(),f})}const Zc=new Map,Ya=(e,n)=>{let s=Zc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Zc.set(e,s)),s},Jc="reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );",uy=`float hqWrap = saturate( ( dot( geometryNormal, directLight.direction ) + 0.5 ) / 1.5 );
284
- reflectedLight.directDiffuse += ( irradiance + directLight.color * max( 0.0, hqWrap - dotNL ) * vec3( 0.9, 0.36, 0.24 ) ) * BRDF_Lambert( material.diffuseContribution );`;function my(e){return e.onBeforeCompile=n=>{const s=J0.lights_physical_pars_fragment;s.includes(Jc)&&(n.fragmentShader=n.fragmentShader.replace("#include <lights_physical_pars_fragment>",s.replace(Jc,uy)))},e.customProgramCacheKey=()=>"hq-skin-sss-v1",e}function py(e,n=!0){return Ya(`skin|${e}|${n}`,()=>{const s=new Ue(e),o=my(new Ps({color:s,roughness:.52,metalness:0,sheen:.35,sheenRoughness:.45,sheenColor:s.clone().lerp(new Ue("#ffd9c8"),.5),specularIntensity:.55,vertexColors:n}));return o.name="skin",o})}function fy(e){return Ya(`hair|${e}`,()=>{const n=new Ue(e),s=new Ps({color:n,roughness:.42,metalness:0,sheen:.55,sheenRoughness:.35,sheenColor:n.clone().lerp(new Ue("#ffffff"),.35),anisotropy:.75,specularIntensity:.7,side:ys});return s.name="hair",s})}function gy(e){return Ya(`facial|${e}`,()=>{const n=new Ue(e),s=new Ps({color:"#ffffff",vertexColors:!0,alphaHash:!0,roughness:.7,metalness:0,sheen:.25,sheenRoughness:.6,sheenColor:n.clone().lerp(new Ue("#ffffff"),.2),anisotropy:.5,specularIntensity:.3});return s.name="beard",s})}function xy(){return Ya("eye",()=>{const e=new Ps({vertexColors:!0,roughness:.18,clearcoat:1,clearcoatRoughness:.04});return e.name="eyes",e})}function Bi(e,n,s=.6,o=Va){return Ya(`plain|${e}|${n}|${s}|${o}`,()=>{const i=new ns({color:n,roughness:s,side:o});return i.name=e,i})}const eh=[],th=new At,mr=new oe,ba=new oe,nh=new oe;function by(e,n=5,s=.16){let o=e.userData.samples;if(o)return o;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 o=Uint32Array.from(r),e.userData.samples=o,o}function aa(e,n,s,o=!1){const i=e.geometry,r=e.skeleton,l=o?Array.from({length:i.getAttribute("position").count},(d,f)=>f):by(i),h=i.getAttribute("position"),u=i.getAttribute("skinIndex"),m=i.getAttribute("skinWeight");th.copy((s??e).matrixWorld).invert();for(let d=0;d<r.bones.length;d++)(eh[d]??=new At).multiplyMatrices(r.bones[d].matrixWorld,r.boneInverses[d]).premultiply(th);for(const d of l){mr.fromBufferAttribute(h,d),ba.set(0,0,0);for(let f=0;f<4;f++){const p=m.getComponent(d,f);p&&(nh.copy(mr).applyMatrix4(eh[u.getComponent(d,f)]),ba.addScaledVector(nh,p))}n(ba.x,ba.y,ba.z,d)}}function yy(e){return e.computeBoundingBox=function(){const n=(this.boundingBox??=new zt).makeEmpty();aa(this,(s,o,i)=>{n.expandByPoint(mr.set(s,o,i))}),n.expandByScalar(.004)},e.computeBoundingSphere=function(){this.boundingBox||this.computeBoundingBox(),this.boundingBox.getBoundingSphere(this.boundingSphere??=new eg)},e}const an=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)};function vy(e,n){const s=e.face.landmarks,o=e.regions,i=o.indexOf("lips"),r=o.indexOf("stubble"),l=Math.abs(s.corner[0])+.007,h=s.upper[1]+.0025,u=s.nostril[1]-.004,m=(p,b,g,v)=>{const y=Math.abs(p),k=an(.35,1,y/l),C=u-.009*k,S=h-.0045*k-.004*k*k,I=an(0,.0022,b-S)*an(0,.0028,C-b)*an(0,.004,l-y)*an(.11,.13,g);return v===i?I*an(.8,1,y/l):I},d=(p,b,g,v)=>{const y=Math.abs(p),k=.019-.006*an(s.lower[1]-.01,s.lower[1]-.003,b),C=an(0,.003,s.lower[1]-.0045-b)*an(0,.006,b-(s.chin[1]-.016))*an(0,.004,k-y)*an(.1,.125,g);return v===i?0:C},f=(p,b,g,v)=>(v===i?0:v===r?1:0)||m(p,b,g,v);return n==="goatee"?{zone:d,th:p=>.0042*Math.pow(p,.6)}:n==="beard"?{zone:f,th:(p,b,g)=>(.0032+.002*an(s.mouthY,s.chin[1],g))*Math.pow(p,.7)}:{zone:m,th:(p,b)=>(.0032+.001*(1-an(0,.02,Math.abs(b))))*Math.pow(p,.55)}}const ro=new Map;function jy(e,n,s,o){const i=`${Wn(n)}|${s}|${o}`;let r=ro.get(i);if(r)return r;const l=js(e,n,0),h=l.getAttribute("position"),u=l.getAttribute("normal"),m=l.getIndex(),d=as(e),f=l.userData.region,p=h.count,{zone:b,th:g}=vy(e,s),v=new Float32Array(p);for(let Y=0;Y<p;Y++){const J=h.getX(Y)-d[0],V=h.getY(Y)-d[1],K=h.getZ(Y)-d[2];V>.02||V<-.2||K<0||(v[Y]=b(J,V,K,f[Y]))}const y=Array.from({length:p},()=>[]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),K=m.getX(Y+2);(v[J]||v[V]||v[K])&&(y[J].push(V,K),y[V].push(J,K),y[K].push(J,V))}for(let Y=0;Y<2;Y++){const J=Float32Array.from(v);for(let V=0;V<p;V++){if(!y[V].length)continue;let K=0;for(const G of y[V])K+=J[G];J[V]>0&&(v[V]=Math.min(J[V],.5*J[V]+.5*(K/y[V].length)))}}const k=new Int32Array(p).fill(-1),C=[],S=[],I=Y=>(k[Y]<0&&(k[Y]=S.length,S.push(Y)),k[Y]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),K=m.getX(Y+2);Math.max(v[J],v[V],v[K])<.04||C.push(I(J),I(V),I(K))}if(!C.length)return null;const j=S.length,M=new Float32Array(j*3),T=new Float32Array(j*4),w=new Float32Array(j*4),E=new Uint8Array(j*4),N=new Uint8Array(j*4),A=l.getAttribute("skinIndex"),O=l.getAttribute("skinWeight"),H=new Ue(o),D=H.clone().lerp(new Ue("#8a6a4e"),.22),$=H.clone().multiplyScalar(.7),W=l.morphAttributes.position||[],z=W.map(()=>new Float32Array(j*3));return S.forEach((Y,J)=>{const V=h.getX(Y)-d[0],K=h.getY(Y)-d[1],G=v[Y],_=g(G,V,K)+3e-4;M[J*3]=h.getX(Y)+u.getX(Y)*_,M[J*3+1]=h.getY(Y)+u.getY(Y)*_,M[J*3+2]=h.getZ(Y)+u.getZ(Y)*_;const ee=.5+.5*Math.sin(V*2300+Math.sin(K*900)*2.2)*Math.sin(V*870-K*610),Q=$.clone().lerp(D,Math.pow(ee,2.5)*.85);T[J*4]=Q.r,T[J*4+1]=Q.g,T[J*4+2]=Q.b,T[J*4+3]=an(.04,.55,G);const ve=Math.sign(V)*.55,xe=Math.hypot(ve,1,.25);w[J*4]=ve/xe,w[J*4+1]=-1/xe,w[J*4+2]=.25/xe,w[J*4+3]=1;for(let q=0;q<4;q++)E[J*4+q]=A.getComponent(Y,q),N[J*4+q]=Math.round(O.getComponent(Y,q)*(O.normalized?255:1));z.forEach((q,ue)=>{const pe=W[ue];q[J*3]=pe.getX(Y),q[J*3+1]=pe.getY(Y),q[J*3+2]=pe.getZ(Y)})}),r=new Tt,r.setAttribute("position",new Pt(M,3)),r.setAttribute("color",new Pt(T,4)),r.setAttribute("tangent",new Pt(w,4)),r.setAttribute("skinIndex",new bs(E,4)),r.setAttribute("skinWeight",new bs(N,4,!0)),r.setIndex(C),r.computeVertexNormals(),r.morphAttributes.position=z.map(Y=>new Pt(Y,3)),r.morphTargetsRelative=!0,r.userData.shared=!0,r.userData.facialHair={type:s,triangles:C.length/3,maxLift:Math.max(...S.map((Y,J)=>Math.hypot(M[J*3]-h.getX(Y),M[J*3+1]-h.getY(Y),M[J*3+2]-h.getZ(Y))))},r.dispose=()=>{},ro.size>32&&ro.clear(),ro.set(i,r),r}const ky=cd,$n=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},In=Math.PI*2;function wy(e){const n=e.face.stats,s=e.face.landmarks,o=n.eye+.02;return{cy:o,cz:(n.front+n.back)/2,ax:n.half*1.04,ay:n.crown-o,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 Vs=(e,n,s)=>Math.atan2(n,s-e.cz),Wo=(e,n,s,o)=>Math.hypot(n/e.ax,(s-e.cy)/e.ay,(o-e.cz)/e.az);function Fs(e,n,s,o){const i=(o-e.cy)/(n*e.ay),r=n*Math.sqrt(Math.max(0,1-i*i));return[e.ax*r*Math.sin(s),o,e.cz+e.az*r*Math.cos(s)]}const Bs=(e,n)=>s=>n+(e-n)*(.5+.5*Math.cos(s)),sh=new WeakMap;function Lo(e){let n=sh.get(e);if(n)return n;const s=e.lods[0],o=as(e),i=["head","jaw","lidUL","lidUR","lidDL","lidDR"].map(h=>e.bones.indexOf(h)),r=[];for(let h=0;h<s.vertices;h++){let u=0;for(let m=0;m<4;m++)i.includes(s.skinIndex[h*4+m])&&(u+=s.skinWeight[h*4+m]/255);u>=.5&&r.push(s.position[h*3]-o[0],s.position[h*3+1]-o[1],s.position[h*3+2]-o[2])}const l=new Map;for(const[h,u]of e.hair)u.kind==="hair"&&l.set(h,u.position.map((m,d)=>m-o[d%3]));return n={skin:Float32Array.from(r),hair:l},sh.set(e,n),n}const ah=new WeakMap;function My(e,n){let s=ah.get(e);if(s)return s;const o=e.lods[0],i=as(e),r=["torso","pelvis","headHalf"].map(f=>e.bones.indexOf(f)),l=48,h=-.36,u=.01,m=30,d=new Float32Array(l*m);for(let f=0;f<o.vertices;f++){if(!r.includes(o.skinIndex[f*4]))continue;const p=o.position[f*3]-i[0],b=o.position[f*3+1]-i[1],g=o.position[f*3+2]-i[2],v=Math.round((b-h)/u);if(v<0||v>=m)continue;const y=(Math.round(Math.atan2(p,g-n)/In*l)%l+l)%l;d[v*l+y]=Math.max(d[v*l+y],Math.hypot(p,g-n))}for(let f=0;f<3;f++){const p=d.slice();for(let b=0;b<m;b++)for(let g=0;g<l;g++)d[b*l+g]=Math.max(p[b*l+g],p[b*l+(g+1)%l],p[b*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 b=0;b<m;b++)for(let g=0;g<l;g++)d[b*l+g]=.5*p[b*l+g]+.25*(p[b*l+(g+1)%l]+p[b*l+(g+l-1)%l])}return s=(f,p)=>{const b=(f/In*l+l*4)%l,g=Math.floor(b),v=b-g,y=Math.min(m-1,Math.max(0,Math.round((p-h)/u)));return d[y*l+g]*(1-v)+d[y*l+(g+1)%l]*v},ah.set(e,s),s}function Ts(e,n,s,o,i=.004,r=.0025){const l=Lo(e),h=(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],b=l.skin[d+2];p>s(Vs(n,f,b))-.004&&(u=Math.max(u,Wo(n,f,p,b)+i/h))}const m=o?l.hair.get(o):void 0;if(m)for(let d=0;d<m.length;d+=3){const f=m[d],p=m[d+1],b=m[d+2],g=s(Vs(n,f,b));p>g-.006&&p<g+.012&&(u=Math.max(u,Wo(n,f,p,b)+r/h))}return u}function ms(e,n,s,o,i=!1){const r=[],l=[],h=s?e:e+1;for(const p of[0,1])for(let b=0;b<=n;b++)for(let g=0;g<h;g++)r.push(...o(g/e,b/n,p));const u=(p,b,g)=>p*h*(n+1)+g*h+(s?b%e:b),m=(p,b,g)=>i?l.push(p,g,b):l.push(p,b,g);for(let p=0;p<n;p++)for(let b=0;b<e;b++){const g=T=>[u(T,b,p),u(T,b+1,p),u(T,b+1,p+1),u(T,b,p+1)],[v,y,k,C]=g(0),[S,I,j,M]=g(1);m(v,y,k),m(v,k,C),m(S,j,I),m(S,M,j)}const d=(p,b)=>{const g=u(0,...p),v=u(0,...b),y=u(1,...p),k=u(1,...b);m(g,y,k),m(g,k,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 Tt;return f.setAttribute("position",new Bt(r,3)),f.setIndex(l),f}function Zn(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 h=i.getIndex();for(let u=0;u<h.count;u++)s.push(h.getX(u)+r);i.dispose()}const o=new Tt;return o.setAttribute("position",new Bt(n,3)),o.setIndex(s),o.computeVertexNormals(),o}function oh(e,n,s,o,i,r){const l=(e.ax+e.az)/2;return ms(96,20,!0,(h,u,m)=>{const d=h*In,f=m?n:n+s/l,p=o(d),b=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,y=Fs(e,f,d,Math.min(b,e.cy+f*e.ay*Math.sin(v)));if(r){const k=r(d,u);y[0]*=k,y[2]=e.cz+(y[2]-e.cz)*k}return!m&&i&&(y[1]+=i(y)),y})}function ya(e,n,s,o,i,r,l,h,u=!1){const m=(e.ax+e.az)/2,d=n+.6*h/m;return ms(u?72:40,8,u,(f,p,b)=>{const g=o+(i-o)*f,v=s(g),y=Fs(e,d,g,v),k=Math.sin(g)/e.ax,C=Math.cos(g)/e.az,S=Math.hypot(k,C),I=-.003+(r(g)+.003)*p;return[y[0]+k/S*I,v-l(g,Math.max(0,I))-(b?h:0),y[2]+C/S*I]},!0)}function lo(e,n,s,o,i,r,l={}){const h=(e.ax+e.az)/2,u=22,m=14;return ms(64,u,!0,(d,f,p)=>{const b=d*In,g=s(b),v=Fs(e,n+(p?0:r/h),b,g),y=v[0],k=v[2]-e.cz;if(f*u<=m){const M=f*u/m,T=i(M)*(l.pleats?.(b,M)??1);return[y*T,g+(o-(p?r:0)-g)*M,e.cz+k*T]}const C=1-(f*u-m)/(u-m),S=i(1)*C*(l.pleats?.(b,1)??1),I=y*S,j=k*S;return[I,o-(p?r:0)-(l.dent?.(I,j)??0)*(1-C*C),e.cz+j]})}function Ki(e,n,s,o,i,r,l=.0015){const h=(e.ax+e.az)/2;return ms(64,2,!0,(u,m,d)=>{const f=u*In,p=s(f),b=Fs(e,n+(d?0:l/h),f,p),g=o+(i-o)*m,v=r(g);return[b[0]*v,p+g,e.cz+(b[2]-e.cz)*v]})}function Sy(e,n,s=[14,10]){const o=new Hn(1,s[0],s[1]);return o.scale(...e),o.translate(...n),o.deleteAttribute("uv"),o.deleteAttribute("normal"),o}function Cy(e){const n=e.brow;return{cap:Bs(n+.02,e.eye+.008),helmet:Bs(n+.024,e.eye+.016),police:Bs(n+.022,e.eye+.012),fedora:Bs(n+.026,e.eye+.02),chef:Bs(n+.024,e.eye+.018),ancient:Bs(n+.028,e.eye+.022)}}function Ny(e,n,s){const o=wy(e),i=Cy(o),r=(o.ax+o.az)/2,l=h=>(u,m,d)=>m>h(Vs(o,u,d))-.003;switch(n){case"cap":{const h=i.cap,u=Ts(e,o,h,void 0),m=Math.min(Ts(e,o,h,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=ya(o,m+.02,h,-.8,.8,g=>.075*Math.pow(Math.max(0,1-(g/.8)**2),.4),(g,v)=>.12*v*v+.05*(g/.8)**2*$n(0,.05,v),.004),b=o.cy+(m+d/r)*o.ay;return{main:Zn([oh(o,m,d,h,void 0,f),p]),trim:Sy([.008,.004,.008],[0,b+.0015,o.cz]),cut:(g,v,y)=>{const k=Vs(o,g,y);return v>h(k)-.003-.035*Math.max(0,Math.cos(k))}}}case"helmet":{const h=i.helmet,u=Ts(e,o,h,s,.02,.012),m=.005,d=p=>.007*Math.exp(-((p[0]/.014)**2))*$n(o.cy,o.cy+o.ay*.6,p[1]),f=ya(o,u+m/r,h,0,In,p=>.018+.028*Math.max(0,Math.cos(p))**2,(p,b)=>.25*b*b,.004,!0);return{main:Zn([oh(o,u,m,h,d),f]),cut:l(h)}}case"police":{const h=i.police,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.068,d=lo(o,u,h,m,p=>1+.17*$n(.4,1,p),.003),f=ya(o,u+.004/r,h,-1.05,1.05,p=>.05*Math.pow(Math.max(0,1-(p/1.05)**2),.6),(p,b)=>.3*b,.003);return{main:Zn([d,f]),trim:Ki(o,u+.002/r,h,.004,.02,()=>1),cut:l(h)}}case"fedora":{const h=i.fedora,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.09,d=lo(o,u,h,m,p=>1-.07*p,.003,{dent:p=>.016*Math.exp(-((p/.022)**2)),pleats:(p,b)=>1-.05*$n(.6,1,b)*Math.max(0,Math.cos(p))**4}),f=ya(o,u+.003/r,h,0,In,p=>.055+.008*Math.cos(p)**2,(p,b)=>.18*b*b*Math.cos(p)**2-.3*b*b*Math.sin(p)**2,.003,!0);return{main:Zn([d,f]),trim:Ki(o,u+.0035/r,h,.002,.022,p=>1-.07*(p/.09)),cut:l(h)}}case"chef":{const h=i.chef,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.17;return{main:lo(o,u,h,m,f=>f<.42?1.01:1.01+.3*Math.sin(Math.min(1,(f-.42)/.4)*Math.PI/2)-.12*$n(.85,1,f),.003,{pleats:(f,p)=>1+.03*$n(.42,.6,p)*Math.sin(f*16)}),cut:l(h)}}case"ancient":{const h=i.ancient,u=Ts(e,o,h,s,.006),m=Math.max(h(0),h(Math.PI))+.085,d=lo(o,u,h,m,g=>1+.04*g,.003,{dent:(g,v)=>-.012*Math.exp(-((g/.05)**2+((v-o.cz)/.06)**2))}),f=h(Math.PI)+.055,p=o.cz-o.az*u*.7,b=[-1,1].map(g=>{const v=new vs(1,1,1,20);return v.rotateX(Math.PI/2),v.scale(.055,.017,.003),v.rotateZ(g*.22),v.translate(g*(o.ax*u+.045),f,p),v.deleteAttribute("uv"),v.deleteAttribute("normal"),v});return{main:Zn([d,...b]),trim:Ki(o,u+.0035/r,h,.002,.018,()=>1),cut:l(h)}}case"nonla":{const m=Lo(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]-o.cz)*.15/.235+.008);const p=ms(56,10,!0,(g,v,y)=>{const k=g*In,C=.235*v,S=f-.15*v-(y?.003:0);return[C*Math.sin(k),S,o.cz+C*Math.cos(k)]},!0),b=new Wr(.235,.0035,6,56);return b.rotateX(Math.PI/2),b.translate(0,f-.15-.0015,o.cz),b.deleteAttribute("uv"),b.deleteAttribute("normal"),{main:Zn([p]),trim:Zn([b]),cut:null}}case"moto":{const h={...o,cy:o.eye-.004,ay:o.crown-o.eye+.004,ax:o.ax*1.1},u=g=>$n(1.25,1.05,Math.abs(g)),m=g=>-.118+.012*Math.cos(g)**2+(o.brow+.016+.118)*u(g),d=Lo(e);let f=1;for(let g=0;g<d.skin.length;g+=3){const v=d.skin[g],y=d.skin[g+1],k=d.skin[g+2];y>m(Vs(h,v,k))-.01&&(f=Math.max(f,Wo(h,v,y,k)+.025/r))}const p=ms(96,18,!0,(g,v,y)=>{const k=g*In-Math.PI,C=y?f:f+.006/r,S=m(k),I=Math.asin(Math.max(-1,Math.min(1,(S-h.cy)/(C*h.ay)))),j=I+(Math.PI/2-I)*v;return Fs(h,C,k,h.cy+C*h.ay*Math.sin(j))}),b=ya(h,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:Zn([p,b]),cut:"hide"}}case"hijab":{const h={...o,cy:o.eye-.035,ay:o.crown-o.eye+.035,ax:o.ax*1.12,az:o.az*1.04},u=e.face.landmarks,m=u.chin[1],d=S=>$n(1,.82,Math.abs(S)),f=S=>m-.012+(o.brow+.03-m+.012)*d(S)-.05*$n(1.4,2.6,Math.abs(S)),p=Lo(e);let b=1;for(let S=0;S<p.skin.length;S+=3){const I=p.skin[S],j=p.skin[S+1],M=p.skin[S+2],T=Vs(h,I,M);j>f(T)-.004&&d(T)<.98&&(b=Math.max(b,Wo(h,I,j,M)+.008/r))}const g=ms(96,18,!0,(S,I,j)=>{const M=S*In-Math.PI,T=j?b:b+.003/r,w=f(M),E=Math.asin(Math.max(-1,Math.min(1,(w-h.cy)/(T*h.ay)))),N=E+(Math.PI/2-E)*I;return Fs(h,T,M,h.cy+T*h.ay*Math.sin(N))}),v=S=>Math.min(m+.004,f(S)+.02),y=-.27,k=My(e,o.cz),C=ms(72,12,!0,(S,I,j)=>{const M=S*In-Math.PI,T=v(M),w=Fs(h,b+.004/r,M,T),E=T+(y-T)*I,N=Math.hypot(w[0],w[2]-o.cz),A=Math.max(N*(1+.5*I*I),(k(M,E)+.012)*$n(0,.4,I))-(j?.003:0);return[Math.sin(M)*A,E,o.cz+Math.cos(M)*A]});return{main:Zn([g,C]),cut:"hide"}}}return null}const va=new Map;function cu(e,n,s){const o=`${e.bytes}|${n}|${s??""}`;if(!va.has(o)){va.size>48&&va.clear();const i=Ny(e,n,s);for(const r of[i?.main,i?.trim])r&&(r.computeVertexNormals(),r.userData.shared=!0,r.dispose=()=>{});va.set(o,i)}return va.get(o)}function Ay(e,n,s){return cu(e,n,s)?.cut??null}const ih=(e,n)=>"#"+new Ue(e).lerp(new Ue(n>0?"#ffffff":"#000000"),Math.abs(n)).getHexString(),Ty=e=>{const n=new Ue(e);return n.r*.3+n.g*.59+n.b*.11>.5?ih(e,-.55):ih(e,.65)},co={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 Ly(e,n,s){const o=cu(e,n.type,s);if(!o)return[];const i=[{geometry:o.main,mat:(co[n.type]??co.cap)(n.color),slot:"hat"}],r=n.type==="cap"?n.color:n.color2??(n.type==="police"?"#d8b64a":Ty(n.color));return o.trim&&i.push({geometry:o.trim,mat:n.type==="police"||n.type==="ancient"?`sol:${r}:0.35:0.6`:(co[n.type]??co.cap)(r),slot:"hat"}),i}const ho=new Map,Hi=new Map;function Ey(e,n){let s=Hi.get(n.id);if(s!==void 0)return s;const o=e.morphs.findIndex(p=>p.name==="femFace"),i=e.lods[0];if(o<0)return Hi.set(n.id,null),null;const r=i.morphs[o],l=i.position,h=n.position,u=h.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 b=0;b<3;b++)m[b]=Math.min(m[b],h[p*3+b]),d[b]=Math.max(d[b],h[p*3+b]);const f=[];for(let p=0;p<i.vertices;p++)[0,1,2].every(b=>l[p*3+b]>m[b]-.015&&l[p*3+b]<d[b]+.015)&&f.push(p);s=new Float32Array(u*3);for(let p=0;p<u;p++){let b=-1,g=1/0;for(const v of f){const y=(l[v*3]-h[p*3])**2+(l[v*3+1]-h[p*3+1])**2+(l[v*3+2]-h[p*3+2])**2;y<g&&(g=y,b=v)}if(b>=0)for(let v=0;v<3;v++)s[p*3+v]=r.data[b*3+v]*r.scale}return Hi.set(n.id,s),s}function Iy(e,n){const s=as(e),o=Float32Array.from(n),i=(l,h,u,m)=>{const d=l<h?(l-h+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<o.length;l+=3){const h=o[l]-s[0],u=Math.abs(h);if(u<.05)continue;const m=i(o[l+1]-s[1],-.072,-.016,.015)*i(o[l+2]-s[2],.025,.075,.02),d=.091+(u-.072)*.3;m>0&&u<d&&(o[l]=s[0]+Math.sign(h)*(u+(d-u)*m),r=!0)}return r?o:null}function Ry(e,n,s,o,i=0){const r=i>0&&(n.kind==="brows"||n.kind==="teeth"||n.kind==="lashes")?Ey(e,n):null,l=r?Math.round(i*100)/100:0,h=`${n.id}|${o}|${l}`;let u=ho.get(h);if(u)return u;ho.size>96&&ho.clear();const m=r?n.position.map((y,k)=>y+r[k]*l):n.position,d=r?iu(l):0;if(d>0){const y=[0,0,0];for(let k=0;k<m.length;k+=3)ru(e,m[k],m[k+1],m[k+2],d,y),m[k]+=y[0],m[k+1]+=y[1],m[k+2]+=y[2]}const f=n.kind==="hair"?Iy(e,n.position):null;u=new Tt,u.setAttribute("position",new Pt(f??m,3)),u.setAttribute("skinIndex",new bs(n.skinIndex,4)),u.setAttribute("skinWeight",new bs(n.skinWeight,4,!0));const p=n.position.length/3,b=new Float32Array(p*4);for(let y=0;y<p;y++)b[y*4]=n.flow[y*3],b[y*4+1]=n.flow[y*3+1],b[y*4+2]=n.flow[y*3+2],b[y*4+3]=1;u.setAttribute("tangent",new Pt(b,4));const g=as(e);let v=n.index;if(typeof s=="function"){const y=[],k=C=>s(m[C*3]-g[0],m[C*3+1]-g[1],m[C*3+2]-g[2]);for(let C=0;C<n.index.length;C+=3)k(n.index[C])&&k(n.index[C+1])&&k(n.index[C+2])||y.push(n.index[C],n.index[C+1],n.index[C+2]);v=y}return u.setIndex(Array.from(v)),u.computeVertexNormals(),(n.kind==="beard"||n.kind==="brows")&&(u.morphAttributes.position=su(m,g).map(y=>new Pt(y,3)),u.morphTargetsRelative=!0),u.userData.shared=!0,u.dispose=()=>{},ho.set(h,u),u}function Fy(e,n,s,o){const i=[],r=s.hat?Ay(e,s.hat.type,s.hair?.style):null,l=s.hat?`hat:${s.hat.type}`:"",h=s.hair?.color??"#2a211b",u=(f,p,b,g)=>{const v=e.hair.get(f);if(!v||g==="hide")return;const y=n.bones.get("head"),k=new Map,C=v.chains.length?{kind:"hair",anchor:"head",chains:[]}:null;for(const[S,I]of v.chains.entries()){let j=y,M=[-Zs[0],-Zs[1],-Zs[2]];const T=[],w=[];I.forEach((E,N)=>{const A=new $a;A.name=E.name,A.position.set(E.at[0]-M[0],E.at[1]-M[1],E.at[2]-M[2]),j.add(A),n.bones.set(E.name,A),T.push(A);const O=as(e);k.set(E.name,new At().makeTranslation(-(O[0]+E.at[0]),-(O[1]+E.at[1]),-(O[2]+E.at[2])));const H=I[N+1];w.push(H?new oe(H.at[0]-E.at[0],H.at[1]-E.at[1],H.at[2]-E.at[2]):w[N-1]?.clone()??new oe(0,-.08,0)),j=A,M=E.at}),C.chains.push({bones:T,rest:w,kind:"hair",stiffness:f==="long"?.55:.4,collide:!0,side:S})}i.push({geometry:Ry(e,v,g,g?l:"",o.fem),material:typeof p=="string"?fy(p):p,slot:b,bones:v.bones,inverses:k,chains:C,near:v.kind==="lashes"||v.kind==="teeth"||v.kind==="brows"})},m=s.hair?.style;if(m&&m!=="none"&&m!=="buzz"&&u(m,h,"hair",r),u("brows",Py(s.hair&&s.hair.style!=="none"?h:s.beard?.color??"#2a211b",o.skin),"hair",null),s.beard&&s.beard.type!=="none"){const f=jy(e,o,s.beard.type,s.beard.color);f&&i.push({geometry:f,material:gy(s.beard.color),slot:"beard",bones:[...ky],inverses:new Map,chains:null,near:!1})}u("lashes",Bi("lashes","#17110d",.75,ys),"lashes",null);const d=Bi("teeth","#e6dfd2",.3);return u("teeth-upper",d,"teeth",null),u("teeth-lower",d,"teeth",null),u("tongue",Bi("tongue","#a5525a",.45),"mouth",null),i}function Py(e,n="#c9956f"){const s=new Ue(e);return"#"+(s.getHSL({h:0,s:0,l:0}).l>.7?s.multiplyScalar(.75):s.lerp(new Ue(n),.1)).getHexString()}const Vt=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},ja=-.1,Go={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}}},wn={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}}},qo={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}}},$y=e=>!!e.top||!!(e.outer&&qo[e.outer.type]),Dy=e=>!!e.bottom||!!(e.top&&Go[e.top.type]?.loose&&Go[e.top.type].loose.length>.4)||!!(e.outer&&qo[e.outer.type]?.loose),Oy=e=>e.fabric??hp[e.type]??"cotton",st={torso:0,arm:1,hand:2,leg:3,foot:4,head:5},uo=new Map;function Vr(e,n,s){const o=e.lods[n],i=`${n}|${Wn(s)}`;let r=uo.get(i);if(r)return r;uo.size>48&&uo.clear();const l=hd(Qo({...s,head:1,posture:0},Ir,{bind:!0})),h=new Proxy(e.bind,{get:(f,p)=>l.get(p)?.t??f[p]}),u=o.vertices,m=js(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,b)=>{const g=[b[0]-p[0],b[1]-p[1],b[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]],b=p[0]<0?"L":"R",g=e.bones[o.skinIndex[f*4]];r.cat[f]=/^(arm|fore)/.test(g)?st.arm:/^(wrist|thumb|index|middle|ring|pinky)/.test(g)?st.hand:/^(thigh|shin)/.test(g)?st.leg:/^foot/.test(g)?st.foot:/^(head|jaw|lid)/.test(g)?st.head:st.torso,r.yt[f]=p[1]-h.torso[1],r.x[f]=p[0],r.z[f]=p[2];const v=h[`arm${b}`],y=h[`fore${b}`],k=h[`wrist${b}`];let C=d(p,v,y);C>1&&(C=1+d(p,y,k),C>2&&(C=2+Math.hypot(p[0]-k[0],p[1]-k[1],p[2]-k[2])/.19)),r.armT[f]=C;const S=h[`thigh${b}`],I=h[`shin${b}`],j=h[`foot${b}`];let M=d(p,S,I);M>1&&(M=1+d(p,I,j)),r.legT[f]=M,r.footY[f]=p[1]-j[1],r.cat[f]===st.foot&&(r.sole=Math.max(r.sole,-r.footY[f]))}return uo.set(i,r),r}function _y(e,n,s){const o=Vt(-.015,.05,s),i=Math.abs(n);switch(e){case"crew":return .565-.045*o*Math.max(0,1-(i/.07)**2);case"collar":return .6-.065*o*Math.max(0,1-i/.035);case"v":return .565-.13*o*Math.max(0,1-i/.08);case"deepv":return .57-.24*o*Math.max(0,1-i/.1);case"scoop":return .53-.1*o*Math.max(0,1-(i/.11)**2);case"high":return .62-.02*o}}function rh(e,n,s=.134){return o=>{const i=e.cat[o];if(i===st.head||i===st.foot)return-1;if(i===st.arm||i===st.hand)return n.sleeve<0?Math.min(-.01,s-Math.abs(e.x[o])):(n.sleeve-e.armT[o])*.29;let r=Math.min(e.yt[o]-n.hem,_y(n.neck,e.x[o],e.z[o])-e.yt[o]);return n.sleeve<0&&(r=Math.min(r,s-Math.abs(e.x[o])+2.5*Math.max(0,.3-e.yt[o]))),r}}function zy(e,n){return s=>{const o=e.cat[s];if(o===st.head||o===st.arm||o===st.hand)return-1;const i=n.waist-e.yt[s];return o===st.torso?i:Math.min(i,(n.leg-e.legT[s])*.43)}}const ka=new Map;function By(e,n,s,o){const{out:i,nv:r,idx:l}=o,h=new Map,u=new Map;for(let O=0;O<l.length;O+=3)for(let H=0;H<3;H++){const D=l[O+H],$=l[O+(H+1)%3],W=Math.min(D,$)*r+Math.max(D,$);h.set(W,(h.get(W)??0)+1),u.set(W,[D,$])}const m=new Map;for(const[O,H]of h)if(H===1){const[D,$]=u.get(O);m.set($,D)}let d=1+s.hem,f=null;const p=new Set;for(const O of m.keys()){if(p.has(O))continue;const H=[];let D=O;for(;!p.has(D)&&m.has(D);)p.add(D),H.push(D),D=m.get(D);if(H.length<12)continue;const $=H.map(z=>i[z*3+1]),W=H.map(z=>i[z*3]);if(Math.max(...$.map(z=>Math.abs(z-d)))<.05&&Math.min(...W)<-.05&&Math.max(...W)>.05){f=H;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 b=120,g=.01,v=Math.ceil(s.length/g)+2,y=new Float32Array(b*v);for(let O=0;O<s.cat.length;O++){const H=s.cat[O];if(H===st.arm||H===st.hand||H===st.head)continue;const D=n[O*3+1],$=Math.round((d-D)/g);if($<0||$>=v)continue;const W=n[O*3],z=n[O*3+2],Y=(Math.round(Math.atan2(W,z)/(Math.PI*2)*b)%b+b)%b;y[$*b+Y]=Math.max(y[$*b+Y],Math.hypot(W,z))}for(let O=0;O<v;O++)for(let H=0;H<4;H++){const D=y.slice(O*b,(O+1)*b);for(let $=0;$<b;$++)y[O*b+$]=Math.max(D[$],(D[($+1)%b]+D[($+b-1)%b])/2*.998)}{const O=y.slice(),H=(D,$)=>D<0||D>=v?0:O[D*b+($+b)%b];for(let D=0;D<v;D++)for(let $=0;$<b;$++){let W=0;for(let z=-1;z<=1;z++)for(let Y=-1;Y<=1;Y++)W=Math.max(W,H(D+z,$+Y));y[D*b+$]=W}}const k=(O,H)=>{const D=(O/(Math.PI*2)*b+b*4)%b,$=Math.floor(D),W=D-$,z=Math.min(v-1,Math.max(0,Math.round(H/g)));return y[z*b+$]*(1-W)+y[z*b+($+1)%b]*W},C=e.bones.indexOf("pelvis"),S=e.bones.indexOf("thighHalfL"),I=e.bones.indexOf("thighHalfR"),j=e.bones.indexOf("thighL"),M=e.bones.indexOf("thighR"),T=f.length,w=Math.max(3,Math.round(s.length/.012)),E=[...i],N=f.map(O=>Math.hypot(i[O*3],i[O*3+2]));let A=f.slice();for(let O=1;O<=w;O++){const H=s.length*O/w,D=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]);D.push(Math.max(N[W]-s.tuck*(s.length/w),k(Y,H)+o.th[z]+.004+.01*Math.min(1,H/.012)))}for(let W=0;W<3;W++){const z=D.slice();for(let Y=0;Y<T;Y++)D[Y]=Math.max(z[Y],(z[(Y+1)%T]+z[(Y+T-1)%T])/2)}const $=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]),J=D[W]*(1+s.flare*H),V=E.length/3;E.push(Math.sin(Y)*J,d-H,Math.cos(Y)*J),o.base.push(Math.sin(Y)*(J-o.th[z]),d-H,Math.cos(Y)*(J-o.th[z])),o.nrm.push(Math.sin(Y),0,Math.cos(Y)),o.th.push(o.th[z]);const K=Math.min(1,H/.03),G=i[z*3],_=Vt(.015,.07,Math.abs(G)),ee=.45*_,Q=(Math.cos(Y)>0?.55:.3)*Vt(.1,.7,Math.abs(Math.cos(Y))),ve=Vt(-.04,.04,G),xe=new Map;for(let U=0;U<4;U++){const le=o.sw[z*4+U];le&&xe.set(o.si[z*4+U],(xe.get(o.si[z*4+U])??0)+le*(1-K))}xe.set(C,(xe.get(C)??0)+K*(1-ee-Q));const q=G<0?S:I;if(xe.set(q,(xe.get(q)??0)+K*ee),Q>0)for(const[U,le]of[[j,1-ve],[M,ve]])le>0&&xe.set(U,(xe.get(U)??0)+K*Q*le);const ue=[...xe].sort((U,le)=>le[1]-U[1]).slice(0,4);let pe=0;for(const[,U]of ue)pe+=U;for(let U=0;U<4;U++)o.si.push(ue[U]?.[0]??0),o.sw.push(ue[U]?ue[U][1]/pe:0);o.col.length&&o.col.push(o.col[z*3],o.col[z*3+1],o.col[z*3+2]),$.push(V),N[W]=D[W]}for(let W=0;W<T;W++){const z=A[W],Y=A[(W+1)%T],J=$[W],V=$[(W+1)%T];l.push(z,Y,V,z,V,J)}A=$}return{out:Float32Array.from(E),nv:E.length/3}}function Ky(e,n,s,o,i,r,l={}){const h=`${s}|${Wn(n)}|${o}`;let u=ka.get(h);if(u)return u;ka.size>96&&(ka.forEach(U=>U.geometry.userData.realDispose?.()),ka.clear());const m=e.lods[s],d=js(e,n,s),f=d.getAttribute("position").array,p=d.getAttribute("normal").array,b=m.vertices,g=new Float32Array(b),v=new Uint8Array(b);for(let U=0;U<b;U++){let le=i(U);Math.abs(le)<.0012&&(le=le>=0?.0012:-.0012),g[U]=le,le>.028&&(v[U]=1)}const y=[],k=[],C=[],S=[],I=[],j=[],M=[],T=new Int32Array(b).fill(-1),w=new Map,E=U=>{const le=new Map;for(let ce=0;ce<4;ce++){const Le=m.skinWeight[U*4+ce];Le&&le.set(m.skinIndex[U*4+ce],Le/255)}return le},N=(U,le,ce,Le,je)=>{const ie=k.length/3;k.push(U[0],U[1],U[2]),y.push(le[0],le[1],le[2]),C.push(Le);const Me=[...ce].sort((Se,he)=>he[1]-Se[1]).slice(0,4);let Ee=0;for(const[,Se]of Me)Ee+=Se;for(let Se=0;Se<4;Se++)S.push(Me[Se]?.[0]??0),I.push(Me[Se]?Me[Se][1]/Ee:0);return je&&j.push(...je),ie},A=U=>(T[U]<0&&(T[U]=N([f[U*3],f[U*3+1],f[U*3+2]],[p[U*3],p[U*3+1],p[U*3+2]],E(U),r(U),l.colors?.(U))),T[U]),O=(U,le)=>{const ce=U<le?U*b+le:le*b+U;let Le=w.get(ce);if(Le!==void 0)return Le;const je=g[U]/(g[U]-g[le]),ie=(Fe,Te)=>Fe[U*3+Te]+(Fe[le*3+Te]-Fe[U*3+Te])*je,Me=E(U),Ee=E(le),Se=new Map;for(const[Fe,Te]of Me)Se.set(Fe,Te*(1-je));for(const[Fe,Te]of Ee)Se.set(Fe,(Se.get(Fe)??0)+Te*je);const he=l.colors?.(U),be=l.colors?.(le);return Le=N([ie(f,0),ie(f,1),ie(f,2)],[ie(p,0),ie(p,1),ie(p,2)],Se,r(U)*(1-je)+r(le)*je,he&&be?[he[0]*(1-je)+be[0]*je,he[1]*(1-je)+be[1]*je,he[2]*(1-je)+be[2]*je]:void 0),w.set(ce,Le),Le},H=m.index;for(let U=0;U<H.length;U+=3){const le=[H[U],H[U+1],H[U+2]],ce=le.map(Se=>g[Se]>0),Le=ce.filter(Boolean).length;if(!Le)continue;if(Le===3){M.push(A(le[0]),A(le[1]),A(le[2]));continue}let je=0;Le===1?je=ce.indexOf(!0):je=ce.indexOf(!1);const ie=le[je],Me=le[(je+1)%3],Ee=le[(je+2)%3];if(Le===1)M.push(A(ie),O(ie,Me),O(ie,Ee));else{const Se=O(ie,Me),he=O(ie,Ee);M.push(Se,A(Me),A(Ee),Se,A(Ee),he)}}let D=k.length/3;const $=Array.from({length:D},()=>[]);for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3];$[ce].push(Le),$[Le].push(ce)}if(l.smoothBase){const U=l.smoothBaseAbove,le=l.smoothBaseLift,ce=Se=>U==null?1:Vt(U,U+.1,k[Se*3+1])*Vt(.15,.45,y[Se*3+2]),Le=Float64Array.from({length:D},(Se,he)=>ce(he)),je=Float64Array.from({length:D},(Se,he)=>le==null?0:1-Vt(le,le+.1,k[he*3+1])),ie=Se=>{const he=Float64Array.from(k);for(let be=0;be<D;be++){if(!$[be].length||!Le[be])continue;let Fe=0,Te=0,_e=0;for(const re of $[be])Fe+=k[re*3],Te+=k[re*3+1],_e+=k[re*3+2];const ze=1/$[be].length,Be=Se*Le[be];let Ze=(Fe*ze-k[be*3])*Be,F=(Te*ze-k[be*3+1])*Be,te=(_e*ze-k[be*3+2])*Be;const Z=Ze*y[be*3]+F*y[be*3+1]+te*y[be*3+2];Z<0&&je[be]&&(Ze-=y[be*3]*Z*je[be],F-=y[be*3+1]*Z*je[be],te-=y[be*3+2]*Z*je[be]),he[be*3]=k[be*3]+Ze,he[be*3+1]=k[be*3+1]+F,he[be*3+2]=k[be*3+2]+te}for(let be=0;be<he.length;be++)k[be]=he[be]};for(let Se=0;Se<l.smoothBase;Se++)ie(.5);const Me=new Tt;Me.setAttribute("position",new Bt(k,3)),Me.setIndex(M),Me.computeVertexNormals();const Ee=Me.getAttribute("normal");for(let Se=0;Se<D;Se++)y[Se*3]=Ee.getX(Se),y[Se*3+1]=Ee.getY(Se),y[Se*3+2]=Ee.getZ(Se);Me.dispose()}let W=new Float32Array(D*3);for(let U=0;U<D;U++)for(let le=0;le<3;le++)W[U*3+le]=k[U*3+le]+y[U*3+le]*C[U];const z=l.smooth??4,Y=new Map;for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3],je=Math.min(ce,Le)*D+Math.max(ce,Le);Y.set(je,(Y.get(je)??0)+1)}const J=Array.from({length:D},()=>[]);for(const[U,le]of Y)if(le===1){const ce=Math.floor(U/D),Le=U%D;J[ce].push(Le),J[Le].push(ce)}for(let U=0;U<z+8;U++){const le=Float32Array.from(W);for(let ce=0;ce<D;ce++){const Le=J[ce].length?J[ce]:$[ce];if(!Le.length||U>=z&&!J[ce].length)continue;let je=0,ie=0,Me=0;for(const Se of Le)je+=W[Se*3],ie+=W[Se*3+1],Me+=W[Se*3+2];const Ee=1/Le.length;le[ce*3]=W[ce*3]*.5+je*Ee*.5,le[ce*3+1]=W[ce*3+1]*.5+ie*Ee*.5,le[ce*3+2]=W[ce*3+2]*.5+Me*Ee*.5}for(let ce=0;ce<D;ce++){const Le=le[ce*3]-k[ce*3],je=le[ce*3+1]-k[ce*3+1],ie=le[ce*3+2]-k[ce*3+2],Me=Le*y[ce*3]+je*y[ce*3+1]+ie*y[ce*3+2],Ee=C[ce]*.85;if(Me<Ee)for(let Se=0;Se<3;Se++)le[ce*3+Se]+=y[ce*3+Se]*(Ee-Me)}W.set(le)}if(l.band){const U=By(e,f,l.band,{out:W,base:k,nrm:y,th:C,si:S,sw:I,col:j,idx:M,nv:D});U&&(W=U.out,D=U.nv)}if(l.sole)for(let U=0;U<D;U++){const le=W[U*3+1];if(le<l.sole.y+.02){const ce=Vt(l.sole.y+.02,l.sole.y-.005,le);W[U*3+1]=le-l.sole.th*ce,W[U*3+1]<l.sole.y-l.sole.th&&(W[U*3+1]=l.sole.y-l.sole.th)}}const V=new Map;for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3],je=Math.min(ce,Le)*D+Math.max(ce,Le);V.has(je)?V.delete(je):V.set(je,[ce,Le])}const K=[],G=new Map,_=U=>{let le=G.get(U);return le===void 0&&(le=D+K.length/3,K.push(k[U*3]+y[U*3]*C[U]*.12,k[U*3+1]+y[U*3+1]*C[U]*.12,k[U*3+2]+y[U*3+2]*C[U]*.12),G.set(U,le)),le};for(const[U,le]of V.values()){const ce=_(U),Le=_(le);M.push(le,U,ce,le,ce,Le)}const ee=D+K.length/3,Q=[...G.keys()],ve=new Float32Array(ee*3);ve.set(W),ve.set(K,D*3);const xe=new Uint8Array(ee*4),q=new Float32Array(ee*4),ue=j.length?new Float32Array(ee*3):null;xe.set(S),q.set(I),ue?.set(j),Q.forEach((U,le)=>{for(let ce=0;ce<4;ce++)xe[(D+le)*4+ce]=S[U*4+ce],q[(D+le)*4+ce]=I[U*4+ce];if(ue)for(let ce=0;ce<3;ce++)ue[(D+le)*3+ce]=j[U*3+ce]});const pe=new Tt;return pe.setAttribute("position",new Pt(ve,3)),pe.setAttribute("skinIndex",new bs(xe,4)),pe.setAttribute("skinWeight",new Pt(q,4)),ue&&pe.setAttribute("color",new Pt(ue,3)),pe.setIndex(M),pe.computeVertexNormals(),pe.userData.shared=!0,pe.userData.realDispose=pe.dispose.bind(pe),pe.dispose=()=>{},u={geometry:pe,covered:v},ka.set(h,u),u}const _a=8;function hu(e,n,s=_a){const o=Math.hypot(e[0],e[1],e[2])||1,i=e[0]/o,r=e[1]/o,l=e[2]/o;let h=1-i*i,u=-i*r,m=-i*l;const d=Math.hypot(h,u,m);d<1e-4?(h=-l*i,u=-l*r,m=1-l*l):(h/=d,u/=d,m/=d);const f=r*m-l*u,p=l*h-i*m,b=i*u-r*h,g=Math.atan2(n[0]*f+n[1]*p+n[2]*b,n[0]*h+n[1]*u+n[2]*m);return(Math.round(g/(Math.PI*2)*s)%s+s)%s}const mo=new Map;function Hy(e,n){const s=Wn(n);let o=mo.get(s);if(o)return o;const i=Vr(e,0,n),r=js(e,n,0).getAttribute("position").array,l=hd(Qo({...n,head:1,posture:0},Ir,{bind:!0})),h=12,u=_a;o={L:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)},R:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)}};for(const m of["L","R"])for(const[d,f,p]of[["thigh",`thigh${m}`,`shin${m}`],["shin",`shin${m}`,`foot${m}`]]){const b=l.get(f).t,g=l.get(p).t,v=[g[0]-b[0],g[1]-b[1],g[2]-b[2]],y=v[0]**2+v[1]**2+v[2]**2,k=o[m][d];for(let S=0;S<i.cat.length;S++){const I=d==="thigh"&&i.cat[S]===st.torso&&r[S*3+1]<b[1]+.02&&r[S*3+2]<b[2]+.02;if(i.cat[S]!==st.leg&&!I||Math.sign(r[S*3])!==(m==="L"?-1:1))continue;const j=[r[S*3]-b[0],r[S*3+1]-b[1],r[S*3+2]-b[2]],M=(j[0]*v[0]+j[1]*v[1]+j[2]*v[2])/y,T=I?Math.max(0,M):M;if(T<0||T>(I?.35:1)||I&&M<-.12)continue;const w=[j[0]-v[0]*T,j[1]-v[1]*T,j[2]-v[2]*T],E=Math.hypot(w[0],w[1],w[2]);if(E>(d==="thigh"&&T<.4&&w[2]<0?.18:.12))continue;const N=Math.min(h-1,Math.floor(T*h)),A=hu(v,w,u);k[N*u+A]=Math.max(k[N*u+A],E)}const C=k.slice();for(let S=0;S<h;S++)for(let I=0;I<u;I++){let j=0;for(const M of[S-1,S,S+1])for(const T of[I-1,I,I+1])M<0||M>=h||(j=Math.max(j,C[M*u+(T+u)%u]));k[S*u+I]=j}for(let S=0;S<h;S++)for(let I=0;I<u;I++)k[S*u+I]||(k[S*u+I]=S?k[(S-1)*u+I]:.06)}return mo.size>48&&mo.clear(),mo.set(s,o),o}const lh=new Map;function Wy(e,n,s,o,i,r){const l=`${s}|${Wn(n)}|${JSON.stringify(o)}|${i}|${r}`;let h=lh.get(l);if(h)return h;const u=js(e,n,s),m=u.getAttribute("position"),d=Vr(e,s,n),f=e.bind,p=r==="cape",b=p?"torso":"pelvis",g=f.torso[1]+o.top,v=72,y=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==st.torso&&d.cat[V]!==st.leg&&!(p&&d.cat[V]===st.arm&&d.armT[V]<.15)||Math.abs(m.getY(V)-g)>.025)continue;const K=m.getX(V),G=m.getZ(V),_=Math.atan2(K,G),ee=(Math.round(_/(Math.PI*2)*v)%v+v)%v;y[ee]=Math.max(y[ee],Math.hypot(K,G))}const k=o.panels==="apron"?.34:.2,C=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==st.torso&&!(k>.2&&d.cat[V]===st.leg))continue;const K=g-m.getY(V);if(K<0||K>k)continue;const G=m.getX(V),_=m.getZ(V),ee=Math.atan2(G,_),Q=(Math.round(ee/(Math.PI*2)*v)%v+v)%v;C[Q]=Math.max(C[Q],Math.hypot(G,_))}for(let V=0;V<3;V++){const K=Float32Array.from(y),G=Float32Array.from(C);for(let _=0;_<v;_++)y[_]=Math.max(K[_],(K[(_+v-1)%v]+K[(_+1)%v])/2),C[_]=Math.max(G[_],(G[(_+v-1)%v]+G[(_+1)%v])/2)}const S=V=>{const K=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(K),_=K-G;return C[G%v]*(1-_)+C[(G+1)%v]*_+.014+i*.006},I=V=>{const K=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(K),_=K-G;return y[G%v]*(1-_)+y[(G+1)%v]*_+.008+i*.006},j=(()=>{if(!p)return()=>0;const V=Math.ceil((o.length+.1)/.02),K=new Float32Array(V);for(let G=0;G<m.count;G++){if(d.cat[G]!==st.torso&&d.cat[G]!==st.leg)continue;const _=Math.floor((g-m.getY(G))/.02),ee=m.getZ(G);_<0||_>=V||ee>=0||Math.abs(m.getX(G))>.16||(K[_]=Math.max(K[_],-ee))}for(let G=1;G<V;G++)K[G]=Math.max(K[G],K[G-1]);return G=>{const _=g-G,ee=Math.max(0,Math.min(V-1,Math.floor(_/.02)));return K[ee]+.012+(o.clear??0)*Math.min(1,Math.max(0,(_-.35)/Math.max(.1,o.length-.35)))}})(),M=V=>p?.07*Math.sin(V)**2:0,T=V=>r==="cape"?I(V):Math.max(I(V),S(V)),w=V=>Math.max(T(V)*1.04,I(V)*o.flare),E=p?[[Math.PI*.55,Math.PI*1.45]]:o.panels==="aodai"?[[-.95,.95],[Math.PI-1.3,Math.PI+1.3]]:o.panels==="apron"?[[-1.1,1.1]]:o.open?[[o.open*Math.PI/180,Math.PI*2-o.open*Math.PI/180]]:[[0,Math.PI*2]],N=!p&&!o.panels&&!o.open,A=[],O=[],H=[],D=[],$=[],W=[],z=4,Y=Math.max(16,Math.round(o.length/.022));p?f.torso[1]:f.torso[1]-.07;for(const[V,K]of E){const G=K-V,_=Math.max(2,Math.round((o.chains??12)*G/(Math.PI*2))+(N?0:1)),ee=Math.max(8,Math.round(56*G/(Math.PI*2))),Q=$.length;for(let xe=0;xe<_;xe++){const q=N?V+G*xe/_:V+G*xe/(_-1),ue=I(q),pe=[Math.sin(q)*ue,g-M(q),Math.cos(q)*ue],U=(p?ue*o.flare:w(q))+(p?.03:0),le=[Math.sin(q)*U,g-o.length,Math.cos(q)*U];p&&(le[2]=Math.min(le[2],-.12-.02*Math.abs(Math.sin(q)),Math.cos(q)*j(le[1])));const ce=[(le[0]-pe[0])/z,(le[1]-pe[1])/z,(le[2]-pe[2])/z];$.push({at:pe,dirs:Array.from({length:z},()=>ce),seg:xe})}const ve=A.length/3;W.push({base:ve,width:ee+1,rows:Y+1,wrap:N});for(let xe=0;xe<=Y;xe++){const q=xe/Y;for(let ue=0;ue<=ee;ue++){const pe=V+G*ue/ee,U=I(pe),le=(o.folds??0)*Math.sin(pe*(p?14:22))*q,ce=T(pe),Le=p?0:Math.min(1,o.length*q/k),je=U+(ce-U)*Math.sin(Math.min(1,Le)*Math.PI/2);let ie=(p?U+(U*o.flare+.03-U)*q:q*o.length<=k?je:ce+(w(pe)-ce)*((o.length*q-k)/Math.max(1e-6,o.length-k)))+le,Me=Math.cos(pe)*ie;p&&(Me=Math.min(Me,Math.cos(pe)*U+(-.12-Math.cos(pe)*U)*q,Math.cos(pe)*j(g-o.length*q))),A.push(Math.sin(pe)*ie,g-M(pe)*(1-q)-o.length*q,Me);const Ee=N?(pe-V)/G*_:(pe-V)/G*(_-1);let Se=Math.floor(Ee),he=Ee-Se;N?Se%=_:Se>=_-1&&(Se=_-2,he=1);const be=N?(Se+1)%_:Se+1,Fe=q*z,Te=Math.min(z-1,Math.floor(Fe)),_e=Math.min(1,Fe-Te),ze=Math.min(z-1,Te+1),Be=[[(Q+Se)*z+Te,(1-he)*(ze===Te?1:1-_e)],[(Q+be)*z+Te,he*(ze===Te?1:1-_e)]];for(ze!==Te&&Be.push([(Q+Se)*z+ze,(1-he)*_e],[(Q+be)*z+ze,he*_e]);Be.length<4;)Be.push([0,0]);for(const[Ze,F]of Be)H.push(Ze),D.push(F)}}for(let xe=0;xe<Y;xe++)for(let q=0;q<ee;q++){const ue=ve+xe*(ee+1)+q,pe=ue+ee+1;O.push(ue,pe,ue+1,ue+1,pe,pe+1)}}const J=new Tt;return J.setAttribute("position",new Bt(A,3)),J.setAttribute("skinIndex",new vd(H,4)),J.setAttribute("skinWeight",new Bt(D,4)),J.setIndex(O),J.computeVertexNormals(),J.userData.shared=!0,J.userData.rings=W,J.dispose=()=>{},h={geometry:J,roots:$,anchor:b},lh.set(l,h),h}function Gy(e,n,s){const o=e.bones.get(n.anchor),i=[],r=new Map,l=[],h=n.anchor==="torso"?new oe(0,1,0):new oe(0,.93,0);return n.roots.forEach((u,m)=>{let d=o,f=new oe(...u.at);const p=[],b=[];u.dirs.forEach((g,v)=>{const y=new $a;y.name=`${s}${m}_${v}`;const k=v===0?f.clone().sub(h):new oe(...u.dirs[v-1]);y.position.copy(k),d.add(y),e.bones.set(y.name,y),r.set(y.name,new At().makeTranslation(-f.x,-f.y,-f.z)),i.push(y.name),p.push(y),b.push(new oe(...g)),d=y,f=f.clone().add(new oe(...g))}),l.push({bones:p,rest:b,kind:"cloth",stiffness:.5,collide:!0,side:m})}),{bones:i,inverses:r,set:{kind:"cloth",anchor:n.anchor,chains:l}}}const po=new Map;function fo(e,n,s,o,i,r,l){const h=e.pos.length/3,u=o?n:n+1;for(const f of[0,1])for(let p=0;p<=s;p++)for(let b=0;b<u;b++){const g=i(b/n,p/s,f),[v,y]=l(b/n,p/s);e.pos.push(...g),e.col.push(...r(b/n,p/s,f,g[1]));for(let k=0;k<4;k++)e.si.push(v[k]??0),e.sw.push(y[k]??0)}const m=(f,p,b)=>h+f*u*(s+1)+b*u+(o?p%n:p);for(let f=0;f<s;f++)for(let p=0;p<n;p++){const b=M=>[m(M,p,f),m(M,p+1,f),m(M,p+1,f+1),m(M,p,f+1)],[g,v,y,k]=b(0),[C,S,I,j]=b(1);e.idx.push(g,v,y,g,y,k,C,I,S,C,j,I)}const d=(f,p)=>{const b=m(0,...f),g=m(0,...p),v=m(1,...f),y=m(1,...p);e.idx.push(b,v,y,b,y,g)};for(let f=0;f<n;f++)d([f,0],[f+1,0]),d([f+1,s],[f,s]);if(!o)for(let f=0;f<s;f++)d([n,f],[n,f+1]),d([0,f+1],[0,f])}function qy(e,n,s,o,i,r,l,h,u=0){const m=`${s}|${Wn(n)}|${i}|${l}|${h}|${u}`;let d=po.get(m);if(d)return d;const f=js(e,n,s),p=f.getAttribute("position").array,b=o.cat.length,g=new Uint8Array(b),v={pos:[],idx:[],si:[],sw:[],col:[]},y=new Ue(l),k=H=>{const D=new Ue(H);return[D.r/Math.max(.02,y.r),D.g/Math.max(.02,y.g),D.b/Math.max(.02,y.b)]},C=y.r*.3+y.g*.59+y.b*.11,S=k(h),I=k(C>.55?"#8d8f94":"#d9d9d4"),j=k(C>.45?"#2b2c30":"#efefea"),M=k(y.clone().multiplyScalar(.45)),T=i==="boots"?.036:i==="heels"?.022:i==="sandals"?0:i==="sneakers"?.032:.026,w=40,E=12,N=i==="sneakers"?.0045:.003,A=i==="sneakers"?.12:.45;for(const H of["L","R"]){const D=e.bind[`foot${H}`],$=e.bones.indexOf(`foot${H}`),W=e.bones.indexOf(`shin${H}`),z=[],Y=[];for(let he=0;he<b;he++)o.cat[he]===st.foot&&Math.sign(p[he*3])===(H==="L"?-1:1)&&(Y.push(he),o.footY[he]<-.012&&z.push(he));if(!z.length)continue;let J=1/0,V=-1/0;for(const he of z)J=Math.min(J,p[he*3+2]),V=Math.max(V,p[he*3+2]);J-=.006,V+=i==="heels"||i==="dress"?.02:i==="sandals"?.008:.014;const K=14,G=new Float64Array(K),_=new Float64Array(K),ee=new Float64Array(K);for(let he=0;he<K;he++){const be=J+(V-J)*(he/K),Fe=J+(V-J)*((he+1)/K);let Te=1/0,_e=-1/0,ze=-1/0;for(const Be of Y){const Ze=p[Be*3+2];Ze<be-.01||Ze>Fe+.01||o.footY[Be]>.035||(Te=Math.min(Te,p[Be*3]),_e=Math.max(_e,p[Be*3]),ze=Math.max(ze,p[Be*3+1]))}Te===1/0?(G[he]=he?G[he-1]:D[0],_[he]=he?_[he-1]:.04,ee[he]=he?ee[he-1]:D[1]-.03):(G[he]=(Te+_e)/2,_[he]=(_e-Te)/2,ee[he]=ze)}const Q=(he,be)=>{const Fe=Math.min(K-1,Math.max(0,be*K-.5)),Te=Math.floor(Fe),_e=Math.min(K-1,Te+1),ze=Fe-Te;return he[Te]*(1-ze)+he[_e]*ze},ve=D[1]-o.sole-r,xe=ve+r,q=H==="L"?1:-1,ue=he=>{const be=Math.sqrt(Math.max(0,1-((.17-Math.min(he,.17))/.17)**2)),Fe=Math.max(0,(he-.62)/.38),Te=Math.max(Q(_,he),.028)+.006;return{w:Te*be*Math.sqrt(Math.max(0,1-Math.pow(Fe,2.4))),x0:Q(G,he)+q*Te*.28*Math.pow(Fe,1.5),spring:.008*Vt(.7,1,he)**2,z:J+(V-J)*he}},pe=D[1]-(i==="sneakers"?.012:i==="boots"?-.04:i==="heels"?.04:.018),U=i==="heels"?.6:i==="boots"?0:i==="sneakers"?.44:.5,le=i==="sneakers"||i==="boots"?.74:.66,ce=he=>{const be=Math.max(Math.min(D[1]+(i==="boots"?.02:i==="sneakers"?.004:-.006),Q(ee,he)+.009),xe+T)-xe;return Math.max(.004,be*Math.sqrt(Math.max(0,1-Math.pow(Math.max(0,(he-le)/(1-le)),2))))},Le=Math.min(pe,Q(ee,U)+(i==="heels"?-.004:.006)),je=he=>he>=U?1/0:he<.28?pe:pe+(Le-pe)*Vt(.28,U,he),ie=he=>Math.max(ce(he),Number.isFinite(je(he))?je(he)-xe+.025*(1-Vt(U-.06,U,he)):0),Me=(he,be,Fe)=>{const Te=ue(he),_e=Math.cos(be),ze=Math.max(0,Math.sin(be)),Be=Math.sign(_e)*Math.pow(Math.abs(_e),.8);return[Te.x0+(Te.w+Fe)*Be*(1-.16*ze),xe+Te.spring-r*A+(ie(he)+r*A+Fe)*Math.pow(ze,.85),Te.z]},Ee=he=>{const be=je(he);if(!Number.isFinite(be))return Math.PI/2;const Fe=(be-xe-ue(he).spring+r*A)/(ie(he)+r*A);return Fe>=1?Math.PI/2:Math.asin(Math.max(.05,Math.pow(Math.max(0,Fe),1/.85)))},Se=()=>[[$],[1]];for(const he of Y){const be=Math.min(1,Math.max(0,(p[he*3+2]-J)/(V-J))),Fe=p[he*3+1];i==="sandals"?Fe<xe+.004&&(g[he]=1):i==="heels"?(be>=U-.03||Fe<je(be)-.005)&&(g[he]=1):g[he]=1}if(fo(v,w,16,!1,(he,be,Fe)=>{const Te=ue(he),_e=i==="heels"?.001:i==="sneakers"?.006:.0035,ze=be*Math.PI*2,Be=Math.cos(ze),Ze=Math.sin(ze),F=Fe?.6:1;return[Te.x0+(Te.w*1.03+_e)*F*Math.sign(Be)*Math.pow(Math.abs(Be),.35),ve+Te.spring+r*.5+r*.5*F*Math.sign(Ze)*Math.pow(Math.abs(Ze),.35),Te.z]},(he,be,Fe,Te)=>i==="sneakers"&&Te>ve+r*.62&&Te<ve+r*.8?I:S,Se),i==="sandals"){for(const[he,be]of[[.6,.66],[.38,.44]])fo(v,6,16,!1,(Fe,Te,_e)=>{const ze=he+(be-he)*Fe,Be=ue(ze),Ze=Math.PI*Te,F=Math.cos(Ze),te=Math.sin(Ze),Z=_e?.002:.0045,re=Math.max(.006,Q(ee,ze)+.004-xe);return[Be.x0+(Be.w+Z-.004)*Math.sign(F)*Math.pow(Math.abs(F),.7),xe+Be.spring-.001+(re+Z)*Math.pow(te,.8),Be.z]},()=>[1,1,1],Se);continue}for(const he of[1,-1])fo(v,w,E,!1,(be,Fe,Te)=>{const _e=Ee(be),ze=he>0?_e*Fe:Math.PI-_e*Fe;return Me(be,ze,Te?0:N)},(be,Fe,Te)=>Te?be<U+.05?M:[1,1,1]:i==="sneakers"&&be>.44&&be<.68&&Fe>.82&&Math.sin(be*Math.PI*42)>.2?j:[1,1,1],Se);if(i==="boots"){const he=_e=>{for(let ze=.015;;ze*=1.5){let Be=1/0,Ze=-1/0,F=1/0,te=-1/0,Z=0;for(let re=0;re<b;re++)o.cat[re]!==st.leg&&o.cat[re]!==st.foot||Math.sign(p[re*3])!==(H==="L"?-1:1)||Math.abs(p[re*3+1]-_e)>ze||(Z++,Be=Math.min(Be,p[re*3]),Ze=Math.max(Ze,p[re*3]),F=Math.min(F,p[re*3+2]),te=Math.max(te,p[re*3+2]));if(Z>=24||ze>.1)return{cx:(Be+Ze)/2,cz:(F+te)/2,rx:(Ze-Be)/2,rz:(te-F)/2}}},be=D[1]+.005,Fe=D[1]+.2,Te=Array.from({length:9},(_e,ze)=>{const Be=be+(Fe-be)*(ze/8);return{y:Be,...he(Be)}});for(let _e=7;_e>=0;_e--)Te[_e].rx=Math.max(Te[_e].rx,Te[_e+1].rx*.9),Te[_e].rz=Math.max(Te[_e].rz,Te[_e+1].rz*.9);fo(v,32,8,!0,(_e,ze,Be)=>{const Ze=Te[Math.round(ze*8)],F=_e*Math.PI*2,te=u+(Be?.004:.0075);return[Ze.cx+(Ze.rx+te)*Math.sin(F),Ze.y,Ze.cz+(Ze.rz+te)*Math.cos(F)]},()=>[1,1,1],(_e,ze)=>{const Be=Vt(D[1]-.01,D[1]+.05,Te[Math.round(ze*8)].y);return[[$,W],[1-Be,Be]]})}}const O=new Tt;return O.setAttribute("position",new Bt(v.pos,3)),O.setAttribute("skinIndex",new bs(v.si,4)),O.setAttribute("skinWeight",new Bt(v.sw,4)),O.setAttribute("color",new Bt(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},po.size>48&&po.clear(),po.set(m,d),d}const Uy=new At().makeTranslation(0,-.008,-.0155).multiply(new At().makeScale(.66,1,.75));function Xy(e,n,s,o,i,r={}){const l=[],h=Vr(e,i,s),u=[],m=[],d=(S,I,j,M,T,w={},E)=>{const N=Ky(e,s,i,S,I,E??(()=>j),w);N.geometry.getIndex()?.count&&(l.push({geometry:N.geometry,material:M,slot:T,skinned:!0}),u.push(N.covered),m.push(S))},f=S=>_s(`fab:${Oy(S)}:${S.color}`),p=(S,I,j,M,T="skirt")=>{if(r.fittedOnly)return;const w=Wy(e,s,i,S,I,T),E=Gy(n,w,`${M}${T}`);l.push({geometry:w.geometry,material:j,slot:M,skinned:!0,bones:E.bones,inverses:E.inverses,chains:E.set,drape:T!=="cape"})},b=o.top?Go[o.top.type]??Go.tshirt:null,g=!!b&&!!o.bottom&&(["shirt","police","polo"].includes(o.top.type)&&["trousers","jeans","shorts","ancient"].includes(o.bottom.type)||!!wn[o.bottom.type]?.loose&&!b.loose),v=b&&g?{...b,hem:(wn[o.bottom.type]?.waist??.05)-.05}:b,y=S=>h.cat[S]===st.torso?.003:0;if(o.bottom){const S=wn[o.bottom.type]??wn.trousers,I=g?v.th+.005:0,j=o.shoes?.type==="boots"&&S.leg>1.6;d(`bottom|${o.bottom.type}|${g}|${j}`,zy(h,j?{...S,leg:1.6}:S),S.th,f(o.bottom),"bottom",{},M=>(o.bottom.type==="ancient"?S.th*(.6+.6*Vt(.6,1.8,h.legT[M])):S.th)+(I?I*Vt(-.2,-.05,h.yt[M]):0)),S.loose&&p(S.loose,0,f(o.bottom),"bottom")}if(o.top){const S=v,I=!S.loose&&S.hem<ja,j=I?{...S,hem:ja}:S,M=o.top.color2,T=o.bottom&&!g?(wn[o.bottom.type]?.th??.007)+.002:0,w=j.stripes?A=>{const O=h.yt[A],D=(Math.abs(O-.12)<.018||Math.abs(O-.26)<.018)&&h.cat[A]===st.torso?new Ue(M??"#e6e6e0"):new Ue(o.top.color),$=new Ue(o.top.color);return[D.r/Math.max(.02,$.r),D.g/Math.max(.02,$.g),D.b/Math.max(.02,$.b)]}:void 0,E=w?hh(f(o.top)):f(o.top),N=Math.max(1+j.hem+.1,T?1+(wn[o.bottom.type]?.waist??.06)+.08:0);d(`top|${o.top.type}|${M??""}|${g}|${T}|${N.toFixed(3)}`,rh(h,j,.67*Ga(s).shoulderX),j.th,E,"top",{colors:w,smooth:6,...j.th>=.01?{smoothBase:6,smoothBaseLift:N}:{},...I&&ja-S.hem>.015?{band:{hem:ja,length:ja-S.hem,flare:.25,tuck:.3,cat:h.cat}}:{}},A=>j.th+y(A)+(T&&h.yt[A]<.12?T*Vt(.12,.04,h.yt[A]):0)+(j.neck==="collar"||j.neck==="high"?.005*Vt(.5,.58,h.yt[A]):0)),j.loose&&p(j.loose,1,f(o.top),"top")}if(o.outer){const S=o.outer.type;if(qo[S]){const I=qo[S],j=Math.max(1+I.hem+.1,o.bottom&&wn[o.bottom.type]?1+wn[o.bottom.type].waist+.08:0);d(`outer|${S}|${j.toFixed(3)}`,rh(h,I,.67*Ga(s).shoulderX),I.th,f(o.outer),"outer",{smooth:6,smoothBase:6,smoothBaseLift:j},M=>I.th+(h.cat[M]===st.torso?.006:0)),I.loose&&p(I.loose,2,f(o.outer),"outer")}else if(S==="cape"){const I=[v?.loose,o.bottom?wn[o.bottom.type]?.loose:void 0].reduce((j,M)=>M?Math.max(j,.025+(M.flare-1)*.16):j,0);p({top:.47,length:1.05,flare:1.15,folds:.012,chains:10,...I?{clear:Math.round(I*1e3)/1e3}:{}},2,f(o.outer),"outer","cape")}else S==="apron"&&p({top:.12,length:.55,flare:1.04,panels:"apron",folds:.002,chains:5},2,f(o.outer),"outer")}if(o.shoes&&o.shoes.type!=="barefoot"){const S=o.shoes.type,I=S==="sneakers"?.027:S==="boots"?.022:S==="sandals"?.014:S==="heels"?.008:.014,j=S==="sneakers"?"#f4f4f0":S==="sandals"?vi(o.shoes.color,-.25):S==="boots"||S==="dress"||S==="heels"?vi(o.shoes.color,-.55):vi(o.shoes.color,-.3),M=o.shoes.fabric??(S==="sneakers"||S==="cloth"?"cotton":"leather"),T=hh(_s(M==="leather"?`sol:${o.shoes.color}:0.36:0`:`fab:${M}:${o.shoes.color}`));S!=="sandals"&&S!=="heels"&&S!=="boots"&&d(`socks|${S}`,N=>h.cat[N]===st.leg?(h.legT[N]-1.8)*.43:h.cat[N]===st.foot?Math.min((h.legT[N]-1.8)*.43,(h.footY[N]+.045)*.6,(e.bind.footL[2]+.02-h.z[N])*.6):-1,.0018,_s(`fab:cotton:${S==="sneakers"?"#e9e9e4":"#2a2a2d"}`),"shoes",{smooth:3});const w=S==="boots"&&o.bottom?wn[o.bottom.type]?.th??.007:0,E=qy(e,s,i,h,S,I,o.shoes.color,j,w);if(l.push({geometry:E.geometry,material:T,slot:"shoes",skinned:!0}),u.push(E.hide),m.push(`last|${S}`),S==="heels"&&!r.fittedOnly)for(const N of["L","R"]){const A=new vs(.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:_s(`sol:${o.shoes.color}:0.4:0`),slot:"shoes",skinned:!1,bone:`foot${N}`})}}if(o.hat&&!r.fittedOnly)for(const S of Ly(e,o.hat,o.hair?.style))l.push({geometry:S.geometry,material:_s(S.mat),slot:S.slot,skinned:!1,bone:"head"});if(o.accessories?.length&&!r.fittedOnly){const S=lp({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 cp(S,{accessories:o.accessories})){const j=I.geo.clone();I.group==="head"&&j.applyMatrix4(oy(e).multiply(Uy)),l.push({geometry:j,material:_s(I.mat),slot:"accessory",skinned:!1,bone:I.group})}}const k=[v?.loose,o.bottom?wn[o.bottom.type]?.loose:void 0].find(S=>S&&S.length>=.45&&!S.panels&&!S.open);if(k&&!r.fittedOnly&&(!o.bottom||wn[o.bottom.type]?.loose)){const S=new Uint8Array(h.cat.length);for(let I=0;I<S.length;I++)(h.cat[I]===st.torso&&h.yt[I]<k.top-.02||h.cat[I]===st.leg&&h.legT[I]<.3)&&(S[I]=1);u.push(S),m.push(`seat|${k.top}`)}let C=null;if(u.length){C=new Uint8Array(h.cat.length);for(const S of u)for(let I=0;I<S.length;I++)S[I]&&(C[I]=1)}return{parts:l,hide:C,hideKey:m.join("§")}}const ch=new Map;function hh(e){let n=ch.get(e);return n||(n=e.clone(),n.vertexColors=!0,n.onBeforeCompile=e.onBeforeCompile,n.customProgramCacheKey=e.customProgramCacheKey,n.userData.shared=!0,n.dispose=()=>{},ch.set(e,n)),n}const za=new Qe,dh=new Qe,uh=new Qe,Vy=new At,du=new At,Rs=new oe,ts=new oe,Jt=new oe,Tn=new oe,Gt=new oe,go=new oe,on=new oe,ea=new oe,pn=Array.from({length:14},()=>({a:new oe,b:new oe,r:0,rb:0,lap:!1})),xo=[0,0,0],bo=[0,0,0],uu=(e,n,s,o,i)=>{const r=e.length/_a,l=Math.min(r-1,Math.max(0,n*r-.5)),h=Math.floor(l),u=l-h,m=Math.min(r-1,h+1);xo[0]=s.b.x-s.a.x,xo[1]=s.b.y-s.a.y,xo[2]=s.b.z-s.a.z,bo[0]=o.x-i.x,bo[1]=o.y-i.y,bo[2]=o.z-i.z;const d=hu(xo,bo);return e[h*_a+d]*(1-u)+e[m*_a+d]*u};function oa(e,n,s,o){const i=e.bones.get(n);return s.set(...o??[0,0,0]).applyMatrix4(i.matrixWorld).applyMatrix4(du),s}const Xt=7;function mu(e){du.copy(e.root.matrixWorld).invert();let n=0;const s=(o,i,r,l,h,u=r)=>{const m=pn[n++];oa(e,o,m.a,l),oa(e,i,m.b,h),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 o of["L","R"])s(`fore${o}`,`hand${o}`,.045),s(`hand${o}`,`hand${o}`,.048,[0,0,.005],[0,-.13,.01]);if(n!==Xt)throw new Error("HQ dynamics: leg capsules must start at LEGS");for(const o of["L","R"])s(`thigh${o}`,`shin${o}`,.088,void 0,void 0,.064),s(`shin${o}`,`foot${o}`,.062,void 0,void 0,.05),s(`foot${o}`,`foot${o}`,.058,[0,-.03,-.02],[0,-.04,.2]);for(const[o,i]of[[3,4],[5,6]]){const r=pn[i];ea.addVectors(r.a,r.b).multiplyScalar(.5);for(const l of[Xt,Xt+3]){Yr(pn[l],ea,on),ts.subVectors(ea,on);const h=ts.length();h<.16&&ts.y>.6*h&&(pn[o].lap=pn[i].lap=!0)}}return n}function Yr(e,n,s){Rs.subVectors(e.b,e.a);const o=Rs.lengthSq(),i=o>1e-10?Math.max(0,Math.min(1,ts.subVectors(n,e.a).dot(Rs)/o)):0;return s.copy(e.a).addScaledVector(Rs,i),i}function mh(e,n,s){const o=Yr(n,e,on),i=e.distanceTo(on),r=(n.prof?uu(n.prof,o,n,e,on):n.r+(n.rb-n.r)*o)+s;i<r&&i>1e-6&&e.sub(on).multiplyScalar(r/i).add(on)}const ph=.68,Yy=(e,n,s)=>{const o=n.x-s.x,i=n.z-s.z,r=Math.hypot(o,i);if(r<1e-6)return e.r;const l=o/r,h=i/r;return e.r/Math.sqrt(l*l+h*h/(ph*ph))};function pr(e,n,s,o=!1){for(let i=0;i<n;i++){const r=pn[i];if(o&&(i<2||r.lap))continue;const l=Yr(r,e,on),h=e.distanceTo(on),u=(r.prof?uu(r.prof,l,r,e,on):i===0?Yy(r,e,on):r.r+(r.rb-r.r)*l)+s;h>=u||(h<1e-6?e.y-=u:e.sub(on).multiplyScalar(u/h).add(on))}}function Qy(e,n,s,o){e.root.updateMatrixWorld(!0);const i=mu(e);pn[Xt].prof=s.L.thigh,pn[Xt+1].prof=s.L.shin,pn[Xt+3].prof=s.R.thigh,pn[Xt+4].prof=s.R.shin;for(let r=0;r<n.length;r+=3){Gt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<5;l++)pr(Gt,i,.007,!0);for(const l of[Xt,Xt+1,Xt+3,Xt+4])mh(Gt,pn[l],.007);n[r]=Gt.x,n[r+1]=Gt.y,n[r+2]=Gt.z}if(o?.some(r=>r.wrap)){for(const r of o)r.wrap&&Zy(n,r);for(let r=0;r<n.length;r+=3){Gt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<2;l++)for(const h of[Xt,Xt+1,Xt+3,Xt+4])mh(Gt,pn[h],.007);n[r]=Gt.x,n[r+1]=Gt.y,n[r+2]=Gt.z}}for(const r of[0,1,3,4])pn[Xt+r].prof=void 0}function Zy(e,n){const s=n.width-1,o=new Float64Array(s),i=new Float64Array(s),r=new Float64Array(s),l=new Float64Array(s),h=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++)o[S]=e[(m+S)*3],i[S]=e[(m+S)*3+2],d+=o[S],f+=i[S];d/=s,f/=s;const p=Array.from({length:s},(S,I)=>I).sort((S,I)=>o[S]-o[I]||i[S]-i[I]),b=(S,I,j)=>(o[I]-o[S])*(i[j]-i[S])-(i[I]-i[S])*(o[j]-o[S]),g=[],v=[];for(const S of p){for(;g.length>=2&&b(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&&b(v[v.length-2],v[v.length-1],I)<=0;)v.pop();v.push(I)}const y=[...g.slice(0,-1),...v.slice(0,-1)];for(let S=0;S<s;S++){const I=o[S]-d,j=i[S]-f,M=Math.hypot(I,j);if(l[S]=Math.atan2(I,j),r[S]=M,M<1e-6)continue;const T=I/M,w=j/M;let E=M;for(let N=0;N<y.length;N++){const A=y[N],O=y[(N+1)%y.length],H=o[O]-o[A],D=i[O]-i[A],$=T*D-w*H;if(Math.abs($)<1e-9)continue;const W=o[A]-d,z=i[A]-f,Y=(W*D-z*H)/$,J=(W*w-z*T)/$;Y>0&&J>=-1e-6&&J<=1+1e-6&&(E=Math.max(E,Y))}r[S]=E}for(let S=0;S<s;S++){let I=0;for(let j=-2;j<=2;j++)I+=r[(S+j+s)%s];h[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])*h[S],e[I+2]=f+Math.cos(l[S])*h[S]}const k=(m+s)*3,C=m*3;e[k]=e[C],e[k+1]=e[C+1],e[k+2]=e[C+2]}}const wa=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},On=new oe,Uo=new oe,fh=new oe,fr={L:new oe,R:new oe},Eo={L:new oe,R:new oe},gr={L:1,R:1},gh=e=>n=>On.subVectors(n,fr[e]).dot(Eo[e])/gr[e],xh={L:new Qe,R:new Qe,alongL:gh("L"),alongR:gh("R")};function Jy(e,n){e.bones.get("torso").getWorldQuaternion(za).premultiply(n),fh.set(0,-1,0).applyQuaternion(za);for(const s of["L","R"])oa(e,`thigh${s}`,fr[s]),oa(e,`shin${s}`,Uo),gr[s]=Math.max(1e-6,Eo[s].subVectors(Uo,fr[s]).length()),Eo[s].divideScalar(gr[s]),xh[s].setFromUnitVectors(fh,Eo[s]);return xh}function ev(e,n,s,o){if(!e.length)return;const i=mu(n),r=o?.vel??[0,0,0],l=o?.acc??[0,0,0],h=o?.time??0,u=o?.air??0,m=Math.hypot(r[0],r[1],r[2]);n.root.updateMatrixWorld(!0);const d=new Qe;n.root.getWorldQuaternion(d);const f=d.clone().invert(),p=Jy(n,f);for(const b of e)b.chains.forEach((g,v)=>{const y=g.kind==="cloth",k=(y?.085:.05)*(1+.8*u),C=y?.012:.008,S=new oe(-r[0]*k-l[0]*C,-r[1]*k*.6-l[1]*C,-r[2]*k-l[2]*C),I=Math.min(1,m/3)*(y?.12:.06);g.bones.forEach((j,M)=>{const T=j.parent;T.updateWorldMatrix(!0,!1),T.getWorldQuaternion(dh).premultiply(f);let w=j;for(let O=0;O<=M;O++)w=w.parent;w.getWorldQuaternion(za).premultiply(f),go.copy(g.rest[M]).normalize();const E=g.rest[M].length()*T.getWorldScale(on).x*j.scale.x/n.root.getWorldScale(ts).x;Jt.copy(go).applyQuaternion(za);const N=g.stiffness*(M===0?1.4:1);if(Jt.multiplyScalar(N).add(Rs.set(0,-(1-Math.min(.95,N)),0)).add(S),I){const O=h*(y?5.3:3.7)+v*1.7+M*.9;Jt.x+=Math.sin(O)*I,Jt.z+=Math.cos(O*.8)*I*.5}if(Jt.normalize(),Vy.copy(j.matrixWorld),oa(n,j.name,Tn),y&&b.anchor==="pelvis"){const O=g.bones[0].position,H=Math.atan2(O.x,O.z),D=wa(.06,-.06,O.x),$=D*p.alongL(Tn)+(1-D)*p.alongR(Tn),W=(.6+.3*(M/g.bones.length))*(.3+.7*wa(-.5,.4,Math.cos(H)))*(1-wa(.82,1.02,$)),z=wa(.85,1.05,$)*wa(.2,.7,Math.cos(H));if(z>0)for(const Y of["L","R"]){const J=Y==="L"?D:1-D;J<=0||(oa(n,`foot${Y}`,Uo,[0,-.02,.24]),On.subVectors(Uo,Tn),On.lengthSq()>1e-8&&On.y<0&&Jt.lerp(On.normalize(),z*J).normalize())}W>0&&(On.copy(go).applyQuaternion(za),Rs.copy(On).applyQuaternion(p.L).multiplyScalar(D),ts.copy(On).applyQuaternion(p.R).multiplyScalar(1-D),On.copy(Rs).add(ts).normalize(),Jt.lerp(On,W).normalize())}Gt.copy(Tn).addScaledVector(Jt,E);const A=y&&b.anchor==="pelvis";if(g.collide)for(let O=0;O<6;O++)ea.copy(Tn).addScaledVector(Jt,E*.5),pr(ea,i,y?.014:.008,A),Jt.subVectors(ea,Tn).normalize(),Gt.copy(Tn).addScaledVector(Jt,E),pr(Gt,i,y?.014:.008,A),Jt.subVectors(Gt,Tn).normalize(),Gt.copy(Tn).addScaledVector(Jt,E);Jt.subVectors(Gt,Tn).normalize(),ts.copy(Jt).applyQuaternion(dh.clone().invert()),uh.setFromUnitVectors(go,ts),j.quaternion.copy(uh),j.updateMatrixWorld(!0)})})}const tv=6.5,Ma=new Map;function nv(e){const n=Wn(e);let s=Ma.get(n);if(!s){const i=Xr({...e,head:1,posture:0},Ir,{bind:!0});i.root.updateMatrixWorld(!0),s=[...i.bones.values()].map(l=>l.matrixWorld.clone().invert());const r=[...i.bones.keys()];s.names=r,Ma.set(n,s),Ma.size>64&&Ma.delete(Ma.keys().next().value)}const o=s.names;return new Map(o.map((i,r)=>[i,s[r]]))}function pu(e){const n=new Ue(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 sv(e,n,s){const o=dp(e),i=!e||!Object.keys(o).length,r=pu(n)?"#6d7a86":n;if(i){const l="#"+new Ue(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 $y(o)||(o.top={type:"tank",color:"#e8e4dc"}),Dy(o)||(o.bottom={type:"shorts",color:"#3a3f47"}),o}function av(e,n){return e?.skin??(pu(n)?n:Lr[2])}const yo=(e,n)=>(e.name=n,e.castShadow=!0,e.receiveShadow=!0,e);function ov(e,n,s,o,i={}){const r=Ur();if(!r)throw new Error("HQ character asset not loaded");const l=av(s,n),h=Po({...s??{},skin:l},l),u=i.bare?{}:sv(o,n,h),m=u.shoes?.type==="heels",d=Xr(h,e,{heels:m}),f=nv(h),p=(E,N)=>new Fi(E.map(A=>d.bones.get(A)),E.map(A=>f.get(A).clone())),b=[],g=[],v=i.lod===void 0?[0,1]:[i.lod],y=new tg,k=v.map(()=>new rn);k.forEach((E,N)=>{E.name=`lod${v[N]}`,y.addLevel(E,N===0?0:tv),N&&(E.visible=!1)}),y.name="hqLod",d.root.add(y);const C=(E,N,A,O,H=d.root,D=!0)=>{const $=new Or(E,N);return $.bind(O,new At),yo($,A),yy($),$.userData.grounds=D,b.push($),H.add($),$},S=p(cd),I=u.hat?null:u.hair?.style,j={skin:l,buzz:I==="buzz"?u.hair.color:null,stubble:u.beard?.type==="beard"?u.beard.color:null},M=lv(l);for(const E of["L","R"])d.bones.get(`eye${E}`).add(yo(new ut(dy(M),xy()),"eyes"));const T=[];for(const E of Fy(r,d,u,h)){const N=new Fi(E.bones.map(O=>d.bones.get(O)),E.bones.map(O=>(E.inverses.get(O)??f.get(O)).clone())),A=E.near&&v[0]===0&&v.length>1?k[0]:d.root;C(E.geometry,E.material,E.slot,N,A,!1),E.chains&&T.push(E.chains)}v.forEach((E,N)=>{const A=Xy(r,d,h,u,E,{fittedOnly:N>0}),O=C(ly(r,h,E,j),py(l),"skin",S,k[N],N===0);A.hide&&(O.geometry=rv(O.geometry,A.hide,A.hideKey));for(const H of A.parts){if(H.skinned){const D=H.bones?new Fi(H.bones.map(W=>d.bones.get(W)),H.bones.map(W=>(H.inverses?.get(W)??f.get(W)).clone())):S,$=C(H.geometry,H.material,H.slot,D,H.bones?d.root:k[N],N===0);if(H.drape){const W=new Tt,z=H.geometry.getAttribute("position").count;W.setAttribute("position",new Pt(new Float32Array(z*3),3)),W.setIndex(H.geometry.getIndex());const Y=yo(new ut(W,H.material),H.slot);Y.userData.drape=!0,$.visible=!1,$.userData.grounds=!1,d.root.add(Y),g.push({src:$,mesh:Y})}}else{const D=yo(new ut(H.geometry,H.material),H.slot);(d.bones.get(H.bone)??d.root).add(D)}H.chains&&T.push(H.chains)}});const w={rig:d,b:h,look:u,meshes:b,chains:T,heels:m,drapes:g,legs:Hy(r,h)};return d.root.userData.hq={repose:(E,N)=>bh(w,E,N??null),built:w,torso:iv(r,h,u)},d.root.userData.hqLook=u,bh(w,e,i.motion??null,!0),d.root}function bh(e,n,s,o=!1){const{rig:i,b:r}=e;o||Ho(i,r,n,{heels:e.heels});const l=ld(n);for(const u of e.meshes)u.morphTargetInfluences&&Er.forEach((m,d)=>{u.morphTargetInfluences[d]=l[m]});i.body.position.y=1,i.root.updateMatrixWorld(!0),ev(e.chains,i,n,s);let h=1/0;for(const u of e.meshes)u.userData.grounds!==!1&&aa(u,(m,d)=>{d<h&&(h=d)},i.root);i.body.position.y=1-(Number.isFinite(h)?h: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;aa(u.src,(f,p,b,g)=>{d[g*3]=f,d[g*3+1]=p,d[g*3+2]=b},i.root,!0),Qy(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 vo=new Map;function iv(e,n,s){const o=(s.top?.012:0)+(s.outer?.016:0),i=`${Wn(n)}|${o}`;let r=vo.get(i);if(r)return r;const l=e.lods.length-1,h=e.lods[l],u=js(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 b=.02,g=.3;for(let v=0;v<h.vertices;v++){if(!m.has(h.skinIndex[v*4]))continue;const y=u.getY(v)-1;y<b||y>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+o,rz:(p-f)/2+o,cz:(f+p)/2,y0:b,y1:g}:{rx:.16,rz:.12,cz:0,y0:b,y1:g},vo.size>64&&vo.clear(),vo.set(i,r),r}const jo=new Map;function rv(e,n,s){const o=`${e.uuid}|${s}`;let i=jo.get(o);if(i)return i;jo.size>64&&jo.clear();const r=e.getIndex(),l=[];for(let h=0;h<r.count;h+=3){const u=r.getX(h),m=r.getX(h+1),d=r.getX(h+2);n[u]&&n[m]&&n[d]||l.push(u,m,d)}i=new Tt;for(const h of Object.keys(e.attributes))i.setAttribute(h,e.getAttribute(h));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=()=>{},jo.set(o,i),i}function lv(e){const n=new Ue(e).getHSL({h:0,s:0,l:0}).l;return n>.78?"#4a6a8a":n>.62?"#5a3f2a":"#3a2618"}const xr="shot-hq-characters";function Qr(){try{return globalThis.localStorage?.getItem(xr)!=="off"}catch{return!0}}function cv(e){try{e?globalThis.localStorage?.removeItem(xr):globalThis.localStorage?.setItem(xr,"off")}catch{}for(const n of[...br])n()}const br=new Set;function fu(e){return br.add(e),()=>{br.delete(e)}}const hv=()=>Qr()&&!!Ur();Rr.active=hv;Rr.build=ov;Rr.samples=aa;ss.hq={enabled:Qr,ready:()=>!!Ur(),load:()=>ty(),onSetting:fu,onAsset:au};au(_d);fu(_d);const gu=["Thumb","Index","Middle","Ring","Pinky"],xu={l:"Left",r:"Right",left:"Left",right:"Right"};function dv(e){const n=String(e||"");let s=/^mixamorig\d*[_:]?([A-Za-z]+\d?)$/.exec(n);return s?yr.has(s[1])?s[1]:null:(s=/^Bip\d+[ _](.+)$/i.exec(n),s?uv(s[1].split(/[ _]+/)):(s=/^J_Bip_([CLR])_(\w+)$/i.exec(n),s?mv(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?pv(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?fv(s):yr.has(n)?n:null))))}function uv(e){const[n,s]=e,o={Pelvis:"Hips",Spine:"Spine",Spine1:"Spine1",Spine2:"Spine2",Neck:"Neck",Head:"Head"};if(e.length===1)return o[n]??null;const i=xu[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${gu[+l[1]]}${l[2]?+l[2]+1:1}`:null}function mv(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",o={Shoulder:"Shoulder",UpperArm:"Arm",LowerArm:"ForeArm",Hand:"Hand",UpperLeg:"UpLeg",LowerLeg:"Leg",Foot:"Foot",ToeBase:"ToeBase"}[n];if(o)return s+o;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 pv(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 o=n?xu[n]:null;if(!o)return null;const i={clavicle:"Shoulder",upperarm:"Arm",lowerarm:"ForeArm",hand:"Hand",thigh:"UpLeg",calf:"Leg",foot:"Foot",ball:"ToeBase"}[e];if(i)return o+i;const r=/^(thumb|index|middle|ring|pinky)_0([1-3])$/.exec(e);return r?`${o}Hand${r[1][0].toUpperCase()}${r[1].slice(1)}${r[2]}`:null}function fv(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 gv(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()),o=[[n.get(0),"Hips"]];for(const[i,r]of[[1,"Spine"],[2,"Spine1"],[3,"Spine2"]])n.has(i)&&i<s&&o.push([n.get(i),r]);return s>=5&&n.has(4)&&o.push([n.get(4),"Neck"]),s>=4&&o.push([n.get(s),"Head"]),o}const Zr=["Hips","Spine","Spine2","Neck","Head"];for(const e of["Left","Right"])Zr.push(...["Shoulder","Arm","ForeArm","Hand","UpLeg","Leg","Foot"].map(n=>e+n));const xv=Object.freeze(Zr.slice()),yr=new Set([...Zr,"Spine1","LeftToeBase","RightToeBase",...["Left","Right"].flatMap(e=>gu.flatMap(n=>[1,2,3].map(s=>`${e}Hand${n}${s}`)))]);function bv(e){const n=new Map,s=new Set;let o=0;for(const[r,l]of gv(e||[]))n.set(r,l),s.add(l);for(const r of e||[]){if(n.has(r))continue;const l=dv(r);!l||s.has(l)||(n.set(r,l),s.add(l),(/^mixamorig/.test(r)||yr.has(r))&&o++)}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=xv.filter(r=>!s.has(r));return{ok:i.length===0,exact:i.length===0&&o===n.size,rename:n,missing:i,bones:n.size}}const yv={fingers:.85,palm:.2,across:.07},yh={x:"shot/bot/xbot.glb",y:"shot/bot/ybot.glb"},ia={};let Sa=null;const vr=new Set,vv=()=>!!ia.x&&!!ia.y;function jv(e){return vr.add(e),()=>{vr.delete(e)}}function kv(e){if(Sa)return Sa;const n="/";return Sa=(async()=>{const{createGltfLoader:s}=await fn(async()=>{const{createGltfLoader:l}=await import("./gltfLoader-U0Eebg7v.js").then(h=>h.g);return{createGltfLoader:l}},__vite__mapDeps([7,6])),o=s(),[i,r]=await Promise.all([o.loadAsync(`${n}${yh.x}`),o.loadAsync(`${n}${yh.y}`)]);ia.x=vh(r.scene),ia.y=vh(i.scene);for(const l of[...vr])l()})().catch(s=>{throw Sa=null,s}),Sa}function vh(e){e.updateMatrixWorld(!0);const n=new zt().setFromObject(e),s=e.getObjectByName("mixamorigHips"),o=new oe;return s?.getWorldPosition(o),{scene:e,height:n.max.y-n.min.y,hipsY:o.y-n.min.y}}const wv=[["head","Head"],["arm","Arm"],["fore","ForeArm"],["wrist","Hand"],["thigh","UpLeg"],["shin","Leg"],["foot","Foot"]],Mv={thumb:"HandThumb",index:"HandIndex",middle:"HandMiddle",ring:"HandRing",pinky:"HandPinky"},Sv=[["Hips",1-rd,.3],["Spine",.73,.55],["Spine1",.87,.8],["Spine2",1,1]],Cv=.45,Nv=24,ko=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Av=/hair|bang|fringe|pony|braid|plait|ahoge|tress|bun|tail|ribbon|tassel|earring|hat|ear_?ring/i,Tv=/skirt|hem|coat|cape|cloak|robe|ribbon|tassel|sash|apron|scarf|cloth|flap|necktie|belt|frill|veil|mantle/i,Lv=/twist|eye|tooth|teeth|tongue|jaw|mouth|lip|brow|lid|cheek|nose|mask|weapon|sword|gun|ik|pole|target|end$|_end|helper/i,Ev=e=>new Ue(e).lerp(new Ue("#d8dbe0"),.55),Iv=e=>new Ue(e).offsetHSL(0,.05,-.12);function Rv(e,n,s,o="x"){const i=ia[o]??ia.x;if(!i)throw new Error("bot asset not loaded");return yu(Ed(i.scene),i.height,e,n,s,!1)}function bu(e){const n=[],s=new Set;let o=!1;e.traverse(r=>{r.isSkinnedMesh&&(o=!0),r.isBone&&!s.has(r.name)&&(s.add(r.name),n.push(r.name))});const i=bv(n);return{...i,ok:i.ok&&o,skinned:o,total:n.length}}function Fv(e,n,s,o){const i=bu(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 y of v.skeleton.bones)if(y&&!r.has(y)){let k=y;for(;k.parent;)k=k.parent;r.has(k)||(e.add(k),k.traverse(C=>r.add(C)))}}});const l=new rn,h=Ed(e);l.add(h);const u=new Set;h.traverse(v=>{const y=v.isBone?i.rename.get(v.name):void 0;y&&!u.has(v)&&(v.name=`mixamorig${y}`,u.add(v))}),h.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 oe);let d=0;for(const v of["Left","Right"]){const y=m(`${v}Foot`),k=m(`${v}ToeBase`);y&&k&&(d+=k.z-y.z)}d<0&&(h.rotation.y=Math.PI),l.updateMatrixWorld(!0);const f=l.getObjectByName("mixamorigHips");if(f){const v=new Set;for(let k=f.parent;k;k=k.parent)v.add(k);const y=[];l.traverse(k=>{if(!k.isBone||k===f||v.has(k))return;let C=k.parent;for(;C&&C!==f&&!v.has(C);)C=C.parent;C!==f&&k.parent&&v.has(k.parent)&&y.push(k)});for(const k of y)f.attach(k);l.updateMatrixWorld(!0)}const p=new zt().setFromObject(l),b=Math.max(.001,p.max.y-p.min.y);h.position.y-=p.min.y;const g=yu(l,b,n,s,{height:o},!0);return g.userData.botExact=i.exact,g.userData.nativeBones=i.bones,g}function yu(e,n,s,o,i,r){const l=Wt(i),h=Po({...i??{}},o),u=new rn;u.name="bot";const m=Xr(h,{},{bind:!0});m.root.name="driver",m.root.traverse(ae=>{ae.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(ae=>{if(!(ae instanceof ut)||(ae.castShadow=!0,ae.receiveShadow=!0,ae.frustumCulled=!1,r))return;const ke=/joint/i.test(ae.name);ae.material=new ns({color:ke?Iv(o):Ev(o),roughness:ke?.5:.42,metalness:ke?.15:.08})});const f=new Map;e.traverse(ae=>{ae.isBone&&!f.has(ae.name)&&f.set(ae.name,ae)});const p=f.get("mixamorigHips"),b={};for(const[ae,ke]of f)ae.startsWith("mixamorig")&&(b[ae.slice(9)]={q:ke.getWorldQuaternion(new Qe).toArray(),p:ke.getWorldPosition(new oe).toArray()});u.userData.botRest=b;const g=[],v=[],y=new oe,k=new oe,C=new Qe,S=ae=>ae.getWorldQuaternion(new Qe),I=(ae,ke)=>{ae.getWorldPosition(y);let Oe=null,Re=1e-6;for(const He of ae.children){He.getWorldPosition(k);const Ve=k.clone().sub(y);Ve.lengthSq()>Re&&(Re=Ve.lengthSq(),Oe=Ve)}return Oe?Oe.normalize():ke.clone()},j=ae=>Math.sign(ae.getWorldPosition(new oe).x||0),M=(ae,ke,Oe,Re=!1)=>{const He=m.bones.get(ae);if(!He){v.push(`driver ${ae}`);return}const Ve=j(He),Je=[...f.values()].filter(it=>it.name===`mixamorig${ke}`||it.name===`mixamorigLeft${ke}`||it.name===`mixamorigRight${ke}`),Ye=Je.length===1?Je[0]:Je.find(it=>Math.sign(it.getWorldPosition(new oe).x||0)===Ve);if(!Ye){v.push(`bone ${ke} for ${ae} (${Je.length} cands, want ${Ve})`);return}const We=Re?Oe:I(Ye,Oe),et=Re?Oe:I(He,Oe),ht=new Qe().setFromUnitVectors(We,et);g.push({bone:Ye,driver:He,cal:ht,restInv:S(He).invert(),mRest:S(Ye)})},T=new oe(0,1,0),w=new oe(0,-1,0),E=new oe(0,0,1);M("torso","Spine2",T,!0);for(const[ae,ke]of wv){if(ae==="head"){M("head",ke,T,!0);continue}const Oe=ae==="thigh"||ae==="shin"||ae==="foot";for(const Re of["L","R"])M(`${ae}${Re}`,ke,ae==="foot"?E:w,Oe)}for(const ae of["L","R"])for(const[ke,Oe]of Object.entries(Mv))for(let Re=1;Re<=3;Re++)M(`${ke}${Re}${ae}`,`${Oe}${Re}`,w);const N=ae=>f.get(`mixamorig${ae}`),A=m.bones.get("torso"),O=m.bones.get("head"),H=S(A),D=H.clone().invert(),$=S(O).invert(),W=N("Spine2"),z=W.getWorldPosition(new oe).applyMatrix4(A.matrixWorld.clone().invert()),Y=Sv.filter(([ae])=>N(ae)).map(([ae,ke,Oe])=>({bone:N(ae),lean:ke,twist:Oe,mRest:S(N(ae)),pos:N(ae).position.clone()})),J=N("Neck"),V=S(J),K=["Left","Right"].map(ae=>{const ke=f.get(`mixamorig${ae}Shoulder`),Oe=f.get(`mixamorig${ae}Arm`),Re=Math.sign(ke.getWorldPosition(new oe).x||0),He=["L","R"].map(Ve=>({S:Ve,a:m.bones.get(`arm${Ve}`),f:m.bones.get(`fore${Ve}`)})).find(Ve=>Math.sign(Ve.a.getWorldPosition(new oe).x||0)===Re);return{bone:ke,arm:Oe,sx:Re,drv:He,mRest:S(ke),armPos:Oe.position.clone(),follow:new Qe}}).filter(ae=>ae.bone&&ae.arm&&ae.drv),G=jh(m),_=p.getWorldPosition(new oe),ee=p.position.clone(),Q=new Map;for(const ae of f.values())Q.set(ae,ae.parent);const ve=new Map;for(const ae of g)ve.set(ae.bone,ae);const xe=[];p.traverse(ae=>{ae.isBone&&xe.push(ae)});const q=[];if(r){const ae=new Set([...f.values()].filter(He=>/^mixamorig/.test(He.name))),ke=f.get("mixamorigHead"),Oe=f.get("mixamorigNeck"),Re=new Map;for(const He of xe){if(ae.has(He)||Lv.test(He.name))continue;const Ve=He.children.find(it=>it.isBone);if(!Ve||Ve.position.lengthSq()<1e-10)continue;let Je=He.parent,Ye=!1;for(;Je&&!ae.has(Je);)Je=Je.parent;(Je===ke||Je===Oe)&&(Ye=!0);const We=Re.get(He.parent);if(!(Ye?Av.test(He.name)||We!==void 0:Tv.test(He.name)||We!==void 0))continue;const ht=We===void 0?0:We+1;Re.set(He,ht),q.push({bone:He,rest:He.quaternion.clone(),tip:Ve.position.clone(),hair:Ye,depth:ht})}}const ue={pos:new oe,time:-1},pe=new oe,U=new oe,le=new Qe,ce=new Qe,Le=new Qe,je=new Qe,ie=new oe,Me=new oe,Ee=new oe,Se=new oe;function he(ae){if(!q.length)return;for(const Ye of q)Ye.bone.quaternion.copy(Ye.rest);e.updateMatrixWorld(!0);const ke=f.get("mixamorigHead"),Oe=ae?.time??-1;ke?.getWorldPosition(Ee),U.set(0,0,0),ke&&Oe>=0&&ue.time>=0&&Oe>ue.time&&Oe-ue.time<.2&&U.subVectors(Ee,ue.pos).divideScalar(Oe-ue.time),ue.pos.copy(Ee),ue.time=Oe,u.getWorldQuaternion(le);const Re=ae?.vel??[0,0,0],He=ae?.acc??[0,0,0],Ve=ae?.air??0,Je=Math.hypot(Re[0],Re[1],Re[2]);for(const Ye of q){const We=(Ye.hair?.07:.1)*(1+.6*Ve),et=Ye.hair?.012:.016,ht=Ye.hair?.09:.05;pe.set(-Re[0]*We-He[0]*et,-Re[1]*We*.6-He[1]*et,-Re[2]*We-He[2]*et).applyQuaternion(le).addScaledVector(U,-ht),pe.length()>1.6&&pe.setLength(1.6);const it=Ye.bone,Ke=it.parent;Ke.updateWorldMatrix(!0,!1),it.updateWorldMatrix(!1,!1),it.getWorldPosition(Ee),Se.copy(Ye.tip).applyMatrix4(it.matrixWorld),ie.subVectors(Se,Ee);const wt=ie.length();if(wt<1e-6)continue;ie.divideScalar(wt);const $t=.55+.25*Math.min(3,Ye.depth),Lt=Math.min(1,Je/3)*(Ye.hair?.07:.12),hn=Math.max(0,Oe)*(Ye.hair?3.7:5.3)+Ye.depth*.9+it.id*.37;Me.copy(ie).add(Se.set(0,Ye.hair?-.22:-.3,0)).addScaledVector(pe,$t),Lt&&(Me.x+=Math.sin(hn)*Lt,Me.z+=Math.cos(hn*.8)*Lt*.5),Me.normalize();const qn=u.getWorldPosition(Se).y+.02;if(Ee.y+Me.y*wt<qn){Me.y=Math.min(1,(qn-Ee.y)/wt);const bt=Math.hypot(Me.x,Me.z),$e=Math.sqrt(Math.max(0,1-Me.y*Me.y));bt>1e-6?(Me.x*=$e/bt,Me.z*=$e/bt):Me.x=$e,Me.normalize()}const Un=Ye.depth===0?.96:.35,Cn=ie.angleTo(Me);Cn>Un&&Me.lerp(ie,1-Un/Cn).normalize(),ce.setFromUnitVectors(ie,Me),Ke.getWorldQuaternion(Le),it.getWorldQuaternion(je),it.quaternion.copy(Le.invert().multiply(ce).multiply(je)),it.updateMatrixWorld(!0)}}const be=new Map,Fe=new Qe,Te=new Qe,_e=new Qe,ze=[];e.traverse(ae=>{ae.isSkinnedMesh&&ze.push(ae)});let Be=0;const Ze=()=>{e.updateMatrixWorld(!0);let ae=1/0;for(const ke of ze)aa(ke,(Oe,Re)=>{Re<ae&&(ae=Re)},u);Number.isFinite(ae)&&(Be-=ae,m.body.position.y=1+Be)};let F=s;const te=[];function Z(ae,ke,Oe){F=ae;for(const Re of q)Re.bone.quaternion.copy(Re.rest);Ho(m,h,ae),m.body.position.y=1+Be,m.root.updateMatrixWorld(!0),lt(),Ze(),lt();for(const Re of te)Re.userData.active=!!(ke&&ke.w>0);ke&&ke.w>0&&Xe(ke),he(Oe)}const re=new Qe,me=new Qe,Pe=new Qe,ye=new Qe,rt=new oe,It=new Qe;function qt(ae,ke,Oe,Re,He){const Ve=Math.max(0,Math.min(ae.n-1,Oe*ae.rate)),Je=Math.floor(Ve),Ye=Math.min(ae.n-1,Je+1),We=Ve-Je,et=ae.bones.length,ht=(Je*et+ke)*4,it=(Ye*et+ke)*4;return re.set(ae.q[ht],ae.q[ht+1],ae.q[ht+2],ae.q[ht+3]),me.set(ae.q[it],ae.q[it+1],ae.q[it+2],ae.q[it+3]),He.copy(re).slerp(me,We).normalize(),Re&&(rt.set(0,0,1).applyQuaternion(He),ye.setFromAxisAngle(T,-Math.atan2(rt.x,rt.z)),He.premultiply(ye)),He}function Xe(ae){const ke=Vl(ae.id);if(!ke)return;const Oe=ke.bones.length,Re=Math.min(1,ae.w),He=ae.from?Vl(ae.from.id):void 0,Ve=He?new Map(He.bones.map((We,et)=>[We,et])):null;for(let We=0;We<Oe;We++){const et=f.get(ke.bones[We]);if(!et)continue;qt(ke,We,ae.t,et===p,Pe);const ht=Ve?.get(ke.bones[We]);He&&ht!==void 0&&ae.from.k>0&&Pe.slerp(qt(He,ht,ae.from.t,et===p,It),Math.min(1,ae.from.k)).normalize(),Re>=1?et.quaternion.copy(Pe):et.quaternion.slerp(Pe,Re)}e.updateMatrixWorld(!0);let Je=1/0;for(const We of ze)aa(We,(et,ht)=>{ht<Je&&(Je=ht)},u);const Ye=ae.po;if(Number.isFinite(Je)&&Math.abs(Je)>1e-4||Ye){const We=p.getWorldPosition(new oe);Number.isFinite(Je)&&(We.y-=Je*u.getWorldScale(new oe).y),Ye&&(We.x-=Ye[0]*Re,We.z-=Ye[1]*Re),p.position.copy(p.parent.worldToLocal(We)),e.updateMatrixWorld(!0)}}function lt(){m.root.updateMatrixWorld(!0);const ae=jh(m),ke=_.clone().add(ae.sub(G));p.parent.updateWorldMatrix(!0,!1),p.position.copy(p.parent.worldToLocal(ke)),ee.y=ee.y,be.clear();const Oe=Yt(F);for(const Re of Y.slice(1))Re.bone.position.copy(Re.pos);for(const Re of xe){const He=Q.get(Re);be.has(He)?Fe.copy(be.get(He)):He.getWorldQuaternion(Fe);const Ve=ve.get(Re),Je=Oe.get(Re);Je?(_e.copy(Fe).invert(),Re.quaternion.copy(_e).multiply(Je)):Ve&&(Ve.driver.getWorldQuaternion(C),Te.copy(C).multiply(Ve.restInv).multiply(Ve.cal).multiply(Ve.mRest),_e.copy(Fe).invert(),Re.quaternion.copy(_e).multiply(Te)),be.set(Re,Fe.clone().multiply(Re.quaternion))}e.updateMatrixWorld(!0),bn()}const jt=new Qe,St=new Qe,gt=new Qe,at=new Qe,tn=new Qe,Ie=new oe(1,0,0),ot=new oe(0,1,0),nn=new oe(0,0,1),mt=new Qe,Rt=Ga(h);function Yt(ae){const ke=new Map,Oe=zn.degToRad,Re=ko(ae.lean),He=ko(ae.spineTwist),Ve=ko(ae.sideBend),Je=ko(ae.tumble)+Rt.torsoLean;A.parent.getWorldQuaternion(mt);const Ye=(Ke,wt)=>mt.clone().multiply(jt.setFromAxisAngle(Ie,Oe(Je+Ke*Re))).multiply(St.setFromAxisAngle(ot,Oe(wt*He))).multiply(gt.setFromAxisAngle(nn,Oe(Ke*Ve))).multiply(D);for(const Ke of Y)(Ke.lean<1||Ke.twist<1)&&ke.set(Ke.bone,Ye(Ke.lean,Ke.twist).multiply(Ke.mRest));const We=A.getWorldQuaternion(at).multiply(D).clone(),et=O.getWorldQuaternion(tn).multiply($).clone();ke.set(J,We.clone().slerp(et,Cv).multiply(V));const ht=new oe(0,-1,0).applyQuaternion(We),it=new oe(0,0,1).applyQuaternion(We);for(const Ke of K){const wt=Ke.drv.f.getWorldPosition(new oe).sub(Ke.drv.a.getWorldPosition(new oe)).normalize(),$t=zn.radToDeg(wt.angleTo(ht)),Lt=zn.clamp(($t-80)/90,0,1);Ke.follow.copy(We).multiply(Ke.mRest);const hn=new Qe().setFromAxisAngle(it,Oe(Ke.sx*Nv*Lt*Lt*(3-2*Lt)));ke.set(Ke.bone,hn.multiply(Ke.follow))}return ke}const ln=new oe,Qt=new oe,xt=new At,cn=new oe,Ft=new oe,Zt=new Qe;function bn(){Qt.copy(z).applyMatrix4(A.matrixWorld);const ae=Qt.sub(W.getWorldPosition(ln)).multiplyScalar(1/3);for(const ke of Y.slice(1)){ke.bone.parent.updateWorldMatrix(!0,!1);const Oe=ke.bone.getWorldPosition(new oe).add(ae);ke.bone.position.copy(ke.bone.parent.worldToLocal(Oe)),ke.bone.updateMatrixWorld(!0)}for(const ke of K){ke.bone.matrixWorld.decompose(cn,Zt,Ft);const Oe=ke.armPos.clone().applyMatrix4(xt.compose(cn,ke.follow,Ft));ke.arm.position.copy(ke.bone.worldToLocal(Oe)),ke.arm.updateMatrixWorld(!0)}}Z(s),u.updateMatrixWorld(!0);for(const ae of["L","R"]){const ke=g.find($e=>$e.driver.name===`wrist${ae}`);if(!ke)continue;const Oe=$e=>f.get(`${ke.bone.name}${$e}`)?.getWorldPosition(new oe),Re=ke.bone.getWorldPosition(new oe),He=Oe("Index1"),Ve=Oe("Middle1"),Je=Oe("Pinky1"),Ye=Oe("Thumb1");if(!He||!Ve||!Je||!Ye)continue;const We=He.clone().sub(Je).normalize(),et=Ve.clone().sub(Re);et.addScaledVector(We,-et.dot(We)).normalize();let ht=new oe().crossVectors(et,We);ht.dot(Ye.clone().sub(Re))<0&&ht.negate();const it=new oe().setFromMatrixScale(ke.driver.matrixWorld),Ke=Ve.distanceTo(Re),wt=yv,$t=Re.clone().addScaledVector(et,wt.fingers*Ke).addScaledVector(ht,wt.palm*Ke).addScaledVector(We,wt.across*Ke),Lt=We,hn=et,qn=new oe().crossVectors(hn,Lt).normalize(),Un=new At().makeBasis(qn,hn,Lt).setPosition($t).scale(it),Cn=ke.bone.matrixWorld.clone().invert().multiply(Un),bt=new ng;bt.name=`rigHold${ae}`,bt.userData.rigHold=ae,bt.userData.active=!1,te.push(bt),Cn.decompose(bt.position,bt.quaternion,bt.scale),ke.bone.add(bt)}const Gn=(ae,ke,Oe,Re)=>{for(const $e of xe){const yt=ae.get($e.name);yt&&$e.quaternion.copy(yt)}ke&&p.position.copy(ke),e.rotation.y=0,e.updateMatrixWorld(!0);const He=p.getWorldPosition(new oe),Ve=(()=>{const $e=p.getWorldQuaternion(new Qe),yt=new oe(0,0,1).applyQuaternion($e);if(!Re?.steadyYaw)return Math.atan2(yt.x,yt.z);const yn=new oe(1,0,0).applyQuaternion($e);return Math.atan2(yt.x-yn.z,yt.z+yn.x)})();e.rotation.y=-Ve,e.updateMatrixWorld(!0),Ho(m,h,{},{bind:!0}),m.root.updateMatrixWorld(!0);const Je=new Qe,Ye=new Qe,We=new Qe;for(const $e of g)$e.bone.getWorldQuaternion(Je),Ye.copy(Je).multiply($e.mRest.clone().invert()).multiply($e.cal.clone().invert()).multiply($e.restInv.clone().invert()),$e.driver.parent.getWorldQuaternion(We),$e.driver.quaternion.copy(We.invert()).multiply(Ye),$e.driver.updateMatrixWorld(!0);const et=Ga(h),ht=zn.radToDeg,it=new rr,Ke={},wt=$e=>(($e+180)%360+360)%360-180,$t=($e,yt,yn=[])=>{const ks=m.bones.get($e);it.setFromQuaternion(ks.quaternion,yt);const Ce=[ht(it.x),ht(it.y),ht(it.z)],dn=Kt=>{const Et=yn[Kt];if(!(!Oe||!Et||Oe[Et[0]]===void 0))return Oe[Et[0]]*Et[1]},un=yt[1]==="X"?0:yt[1]==="Y"?1:2,Fn=Ce.map((Kt,Et)=>wt(Et===un?180-Kt:Kt+180)),Ae=Kt=>Kt.reduce((Et,Ht,mn)=>{const Nn=dn(mn);return Et+(Nn===void 0?0:Math.abs(wt(Ht-Nn)))+.05*Math.abs(Ht)},0);let Dt=Ae(Fn)<Ae(Ce)?Fn:Ce;if(Oe&&Math.abs(Dt[un])>70){const Kt=[0,1,2].filter(ws=>ws!==un),[Et,Ht]=Kt,mn=(yt==="XYZ"?-1:1)*Math.sign(Dt[un]),Nn=dn(Et),Xn=dn(Ht);if(Nn!==void 0&&Xn!==void 0){const ws=(wt(Nn-Dt[Et])*mn+wt(Xn-Dt[Ht]))/2,we=[...Dt];we[Et]=wt(Dt[Et]+mn*ws),we[Ht]=wt(Dt[Ht]+ws);const Qa=new rr(zn.degToRad(we[0]),zn.degToRad(we[1]),zn.degToRad(we[2]),yt),si=new Qe().setFromEuler(Qa);2*Math.acos(Math.min(1,Math.abs(si.dot(ks.quaternion))))*57.3<4&&(Dt=we)}}return Dt},[Lt,hn,qn]=$t("torso","XYZ",[["lean",1],["spineTwist",1],["sideBend",1]]);Ke.lean=Lt-et.torsoLean,Ke.spineTwist=hn,Ke.sideBend=qn;const[Un,Cn,bt]=$t("head","YXZ",[["headPitch",1],["head",1],["headRoll",1]]);Ke.headPitch=Un-et.headPitch,Ke.head=Cn,Ke.headRoll=bt;for(const $e of["L","R"]){const yt=$e==="L",yn=yt?1:-1,[ks,Ce,dn]=$t(`arm${$e}`,"XZY",[[`shoulder${$e}`,1],[`armTwist${$e}`,yt?1:-1],[`shoulderOut${$e}`,yt?-1:1]]);Ke[`shoulder${$e}`]=ks,Ke[`armTwist${$e}`]=yt?Ce:-Ce,Ke[`shoulderOut${$e}`]=yt?-dn:dn,Ke[`elbow${$e}`]=-$t(`fore${$e}`,"XYZ")[0];const[un,Fn,Ae]=$t(`wrist${$e}`,"YXZ",[[`wrist${$e}`,1],[`wristTwist${$e}`,-yn],[`wristSide${$e}`,-yn]]);Ke[`wrist${$e}`]=un,Ke[`wristTwist${$e}`]=-Fn*yn,Ke[`wristSide${$e}`]=-Ae*yn;const[Dt,Kt,Et]=$t(`thigh${$e}`,"XZY",[[`hip${$e}`,1],[`hipTwist${$e}`,yt?1:-1],[`hipOut${$e}`,yt?-1:1]]);Ke[`hip${$e}`]=Dt,Ke[`hipTwist${$e}`]=yt?Kt:-Kt,Ke[`hipOut${$e}`]=yt?-Et:Et,Ke[`knee${$e}`]=$t(`shin${$e}`,"XYZ")[0],Ke[`ankle${$e}`]=$t(`foot${$e}`,"XYZ")[0];const Ht=mn=>Math.abs($t(`${mn}2${$e}`,"XYZ")[2]);Ke[`grip${$e}`]=Math.max(0,Math.min(100,(Ht("index")+Ht("middle")+Ht("ring"))/3/100*100)),Ke[`thumb${$e}`]=Math.max(0,Math.min(100,Ht("thumb")/60*100))}return e.rotation.y=0,{pose:Ke,hips:He,yaw:ht(Ve)}};return u.userData.bot={repose:Z,poseFrom:Gn},u.userData.dynamicBones=q.length,u.userData.botMisses=v,u.userData.botLinks=g.map(ae=>`${ae.driver.name}→${ae.bone.name.replace("mixamorig","")} cal ${Math.round(2*Math.acos(Math.min(1,Math.abs(ae.cal.w)))*57.3)}°`),u}function jh(e){const n=e.bones.get("thighL").getWorldPosition(new oe),s=e.bones.get("thighR").getWorldPosition(new oe);return n.add(s).multiplyScalar(.5)}ss.bot={ready:vv,load:()=>kv(),onAsset:jv,build:Rv,native:Fv,nativeOf:bu};function Pv(e,n,s={}){const o=n.items.find(h=>h.id===s.selected&&h.kind!=="fx"&&!h.hidden)??null,i=Math.max(0,+(s.start??0).toFixed(2)),r=Dg(e,{items:n.items,selected:o,ground:s.ground??[0,0,0],reach:s.reach,anchor:s.anchor?(h,u)=>s.anchor(h.id,u,i):null}),l={...mp(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{...Mn("fx",n.items.length),name:e.name,color:e.color,position:r.position,rotation:r.rotation,fx:l}}function $v(e,n,s){const o=n.fx,i=e.shots.find(u=>u.id===e.activeShot)??e.shots[0],r=Math.min(o.start,Math.max(0,i.duration-.2)),l=s?.fill?Math.max(Math.min(s.duration,3),i.duration-r):o.duration,h={start:+r.toFixed(2),duration:+Math.min(60,l).toFixed(2),...o.loop?{loop:!0}:{}};return{...e,items:[...e.items,{...n,fx:{...o,start:h.start,duration:h.duration}}],shots:e.shots.map(u=>u.id===i.id?{...u,fxTiming:{...u.fxTiming,[n.id]:h}}:u)}}function vu(e,n,s={}){const o=Pv(n,e,s),i=e.items.filter(u=>u.kind==="fx"&&u.fx?.preset===n.preset).length,r={...o,name:`${s.label??n.name} ${i+1}`},l=up(e.items,r.fx);if(!l.ok)return{error:"limit",detail:l.errors.join("; ")};const h=$v(e,r,n);return{stage:h,item:h.items[h.items.length-1]}}let jr=0;const kr=new Set;function ju(e=!1){return pp("fx",e).then(n=>{fp(n.filter(s=>s.kind==="fx"&&s.preset).map(s=>gp(s))),jr++,kr.forEach(s=>s())},()=>{})}function Dv(){const[e,n]=R.useState(jr);return R.useEffect(()=>{const s=()=>n(jr);return kr.add(s),ju(),()=>{kr.delete(s)}},[]),{entries:xp(),version:e}}const kh=new Map;function ku(e){let n=kh.get(e.id);return n||(n=yp(e,24),kh.set(e.id,n)),n}const wu=(e,n)=>e[Math.max(0,Math.min(e.length-1,Math.round(n*24)))];function Ov(e){const n=e.keys.find(s=>s.strike);return n?n.t:e.duration/2}const wh=(e,n)=>[e[0]-n[0],e[1]-n[1],e[2]-n[2]],Wi=(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]],Gi=(e,n)=>e[0]*n[0]+e[1]*n[1]+e[2]*n[2],Mh=e=>{const n=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/n,e[1]/n,e[2]/n]};function _v(e,n,s){const o=Mh(wh(e.target,e.position)),i=Mh(Wi(o,[0,1,0])),r=Wi(i,o),l=Math.cos(e.roll*Math.PI/180),h=Math.sin(e.roll*Math.PI/180),u=[i[0]*l+r[0]*h,i[1]*l+r[1]*h,i[2]*l+r[2]*h],m=Wi(u,o),d=e.lens/36*n;return f=>{const p=wh(f,e.position),b=Gi(p,o);return b<.05?null:[n/2+Gi(p,u)/b*d,s/2-Gi(p,m)/b*d]}}const zv=[["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"]],Sh={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 Mu(e,n,s,o="spear"){const i=Kg(e.pose),r=Math.cos(s*Math.PI/180),l=Math.sin(s*Math.PI/180),h=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]=h(i[g]));const m=vp(e.pose),d=[0,1-i.lift,0],f=g=>h([d[0]+g[0],d[1]+g[1],d[2]+g[2]]),p=Sh[o]??Sh.spear,b=g=>f(m.front.map((v,y)=>v+m.dir[y]*g));return{pts:u,tip:b(p.tip),butt:b(-p.butt),blade:b(p.blade)}}function Su(e,n,s,o,i,r=0){const l=_v(o,n,s),h=e.createLinearGradient(0,0,0,s);h.addColorStop(0,"#1a2532"),h.addColorStop(1,"#0b1018"),e.fillStyle=h,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 b=l(f),g=l(p);!b||!g||(e.beginPath(),e.moveTo(b[0],b[1]),e.lineTo(g[0],g[1]),e.stroke())}for(const d of i){const f=(g,v,y,k)=>{const C=l(g),S=l(v);!C||!S||(e.strokeStyle=y,e.lineWidth=k,e.beginPath(),e.moveTo(C[0],C[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 zv)f(d.pts[g],d.pts[v],"#dfe6ee",2.2*p);const b=l(d.pts.head);b&&(e.fillStyle="#dfe6ee",e.beginPath(),e.arc(b[0],b[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 Bv(e,n,s,o,i,r="spear"){const l=ku(n),h=wu(l,s),u=[h.dx??0,h.dy??0,h.dz??0],m=h.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};Su(e,o,i,p,[Mu(h,u,m,r)])}const Kv=["spear-thrust","spear-double-thrust","spear-spin"].map(e=>bp.find(n=>n.id===e)).filter(Boolean),ta=(()=>{let e=0,n=0;const s=Kv.map(i=>{const r=ku(i),l={clip:i,s:r,at:e,z:n};return e+=i.duration,n+=r[r.length-1].dz??0,l}),o=s.flatMap(i=>i.clip.keys.filter(r=>r.strike).map(r=>i.at+r.t));return{parts:s,duration:e,beats:o}})(),Hv=ta.duration;function Ch(e){const n=[...ta.parts].reverse().find(o=>e>=o.at)??ta.parts[0],s=wu(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 Wv(e,n,s,o,i){const r={start:0,end:ta.duration,yaw:0,height:1.8,beats:ta.beats,centre:m=>{const d=Ch(m);return[d.root[0],0,d.root[2]]}},l=Og(n,s,r),h=Ch(s),u=ta.beats.reduce((m,d)=>Math.max(m,s>=d&&s-d<.12?1-(s-d)/.12:0),0);Su(e,o,i,l,[Mu(h.k,h.root,h.yaw)],n.beats?u:0)}const Xo=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/đ/g,"d").toLowerCase();function Cu({draw:e,rest:n,loop:s,hot:o}){const i=R.useRef(null);return R.useEffect(()=>{const r=i.current,l=r?.getContext("2d");if(!r||!l)return;if(!o){e(l,n,r.width,r.height);return}let h=0;const u=performance.now(),m=()=>{e(l,(performance.now()-u)/1e3%s,r.width,r.height),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>cancelAnimationFrame(h)},[e,n,s,o]),t.jsx("canvas",{ref:i,width:192,height:108,"aria-hidden":"true"})}function Gv({stage:e,selected:n,playhead:s,change:o,setError:i,query:r}){const l=ct(),h=l==="en",[u,m]=R.useState(null),[d,f]=R.useState("all"),p=Xo(r.trim()),b=_g.filter(y=>p?Xo(`${y.name} ${y.nameEn} ${y.desc??""} ${y.id}`).includes(p):d==="all"||y.cat===d),g=zg(e,n),v=y=>{if(!g){i(a("Thêm một nhân vật hoặc vật thể vào cảnh để camera bám theo."));return}const k=Sc(e,{preset:y,subject:g.id,start:s});if(!k.ok){i(k.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead cho chuyển động camera."):k.error);return}i(""),o(C=>{const S=Sc(C,{preset:y,subject:g.id,start:s});return S.ok?S.stage:C})};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Nhóm camera"),children:[{id:"all",name:"Tất cả",nameEn:"All"},...Bg].map(y=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===y.id,className:d===y.id&&!p?"active":"",onClick:()=>f(y.id),children:h?y.nameEn:a(y.name)},y.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("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]):a("Thêm một nhân vật vào cảnh để camera bám theo.")}),t.jsxs("div",{className:"shot-fx-grid",children:[b.map(y=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-camera":y.id,title:h?y.descEn:y.desc,onMouseEnter:()=>m(y.id),onMouseLeave:()=>m(null),onFocus:()=>m(y.id),onBlur:()=>m(null),onClick:()=>v(y),children:[t.jsx(Cu,{draw:(k,C,S,I)=>Wv(k,y,C,S,I),rest:1.2,loop:Hv,hot:u===y.id}),t.jsx("span",{children:h?y.nameEn:y.name})]},y.id)),!b.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có camera nào khớp.")})]})]})}function qv({stage:e,selected:n,onPlay:s,setError:o,query:i}){const r=ct(),l=r==="en",[h,u]=R.useState(null),[m,d]=R.useState("all"),f=Xo(i.trim()),p=jp.filter(({clip:y,pack:k})=>f?Xo(`${y.label} ${y.labelEn} ${y.id} ${k.label} ${k.labelEn} ${k.id==="spear"?"thuong giao":k.id==="katana"?"kiem guom":"con gay truong"}`).includes(f):m==="all"||k.id===m),b=n?e.items.find(y=>y.id===n):null,g=b&&Fr(b)?b:e.items.find(y=>y.kind==="person"&&!y.hidden)??null,v=y=>{const k=kp(y.id);if(!g||!k){o(a("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}o(""),s(g.id,k)};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Loại vũ khí"),children:[{id:"all",label:"Tất cả",labelEn:"All"},...dd].map(y=>t.jsx("button",{type:"button",role:"tab","data-weapon-pack":y.id,"aria-selected":m===y.id,className:m===y.id&&!f?"active":"",onClick:()=>d(y.id),children:l?y.labelEn:a(y.label)},y.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("Áp lên “{0}” từ playhead — tự đặt vũ khí vào tay, hai tay bám cán.",[g.name]):a("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:y,pack:k})=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-combo":y.id,title:`${l?y.labelEn:y.label} · ${y.duration}s`,onMouseEnter:()=>u(y.id),onMouseLeave:()=>u(null),onFocus:()=>u(y.id),onBlur:()=>u(null),onClick:()=>v(y),children:[t.jsx(Cu,{draw:(C,S,I,j)=>Bv(C,y,S,I,j,k.prop.prop),rest:Ov(y),loop:y.duration+.4,hot:h===y.id}),t.jsx("span",{children:l?y.labelEn:y.label})]},y.id)),!p.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có combo nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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 Uv=[.5,.3,.15],Xv=[["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"]],Vv=e=>{const{trail:n,...s}=e;return s};function Yv({stage:e,playhead:n,change:s,setError:o}){ct();const[i,r]=R.useState("medium"),[l,h]=R.useState(.3),u=e.shots.find(j=>j.id===e.activeShot)??e.shots[0],m=u.duration,d=so(u.timing,m),f=wp(e).map(j=>j.time),p=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const w=j(so(T.timing,T.duration)),{timing:E,...N}=T;return w?{...N,timing:w}:N})})),b=()=>e.items.filter(j=>Fr(j)).flatMap(j=>Ep([...u.objectKeys?.[j.id]||[]].sort((M,T)=>M.time-T.time).map(M=>({t:M.time*m,y:M.position[1],air:!!M.air})))),g=e.items.filter(j=>j.kind==="prop"&&j.hold&&j.prop&&Mp[j.prop.kind]),v=g.length>0&&g.every(j=>j.trail),y=(j,M={})=>s(T=>({...T,items:T.items.map(w=>g.some(E=>E.id===w.id)?j?{...w,trail:{...w.trail||{},...M}}:Vv(w):w)})),k=g[0]?.trail?.style??"ribbon",C=Sp({duration:m,timing:d??void 0}),S=Cp(u.impactFrame),I=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const{impactFrame:w,...E}=T;return j?{...E,impactFrame:j}:E})}));return t.jsxs("div",{className:"shot-timing",children:[t.jsx("p",{className:"shot-fx-hint",children:a("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:a("Nhịp anime (sakuga)")}),t.jsx("p",{className:"shot-fx-hint",children:a("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 j=Np(u,Ap(e),{keepLook:!1});if(!j){o(a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."));return}o(""),s(M=>({...M,shots:M.shots.map(T=>T.id===M.activeShot?{...T,timing:j.shot.timing,impacts:j.shot.impacts,impactFrame:j.shot.impactFrame}:T)}))},children:a("Áp nhịp anime ({0} đòn)",[u.impacts?.length||f.length])})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Hit-stop")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ khựng")}),t.jsxs("select",{"aria-label":a("Độ khựng"),value:i,onChange:j=>r(j.target.value),children:[t.jsx("option",{value:"light",children:a("Nhẹ")}),t.jsx("option",{value:"medium",children:a("Vừa")}),t.jsx("option",{value:"heavy",children:a("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:a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."),onClick:()=>{o(""),p(j=>Yl(j,f,Ql[i],m))},children:a("Khựng mọi đòn ({0})",[f.length])}),t.jsx("button",{type:"button",onClick:()=>p(j=>Yl(j,[n],Ql[i],m)),children:a("Khựng tại playhead")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Slow-mo")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tốc độ")}),t.jsx("select",{"aria-label":a("Tốc độ slow-mo"),value:l,onChange:j=>h(+j.target.value),children:Uv.map(j=>t.jsxs("option",{value:j,children:[Math.round(j*100),"%"]},j))})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"apex",onClick:()=>{const j=b();if(!j.length){o(a("Không thấy cú nhảy nào trong shot."));return}o(""),p(M=>j.reduce((T,w)=>ji(T,w,.3,l,m),M))},children:a("Chậm ở đỉnh cú nhảy")}),t.jsx("button",{type:"button","data-timing":"slow-playhead",onClick:()=>p(j=>ji(j,n,.35,l,m)),children:a("Chậm quanh playhead")}),f.length>0&&t.jsx("button",{type:"button",onClick:()=>p(j=>ji(j,f[f.length-1],.3,l,m)),children:a("Chậm đòn kết")})]})]}),d&&t.jsxs("div",{className:"shot-list shot-timing-list",children:[d.holds.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["⏸ ",a("Khựng {0}s · {1}s",[j.at.toFixed(2),j.hold.toFixed(2)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ khựng {0}s",[j.at.toFixed(2)]),onClick:()=>p(M=>so({holds:(M?.holds||[]).filter(T=>T.at!==j.at),slows:M?.slows||[]},m)),children:t.jsx(Ne.trash,{})})]},`h${j.at}`)),d.slows.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["🐢 ",a("Chậm {0}–{1}s · {2}%",[j.start.toFixed(2),j.end.toFixed(2),Math.round(j.speed*100)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ slow-mo {0}s",[j.start.toFixed(2)]),onClick:()=>p(M=>so({holds:M?.holds||[],slows:(M?.slows||[]).filter(T=>T.start!==j.start)},m)),children:t.jsx(Ne.trash,{})})]},`s${j.start}`))]}),t.jsx("p",{className:"shot-fx-hint","data-testid":"timing-length",children:d?a("Video dài {0}s (shot {1}s).",[C.toFixed(2),m.toFixed(2)]):a("Chưa có hit-stop hay slow-mo.")}),d&&t.jsx("button",{type:"button",onClick:()=>p(()=>null),children:a("Xoá nhịp đòn")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khung va chạm")}),t.jsx("p",{className:"shot-fx-hint",children:a("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:a("Kiểu")}),t.jsxs("select",{"aria-label":a("Kiểu khung va chạm"),"data-timing":"impact-style",value:S?.style??"",onChange:j=>I(j.target.value?{style:j.target.value,strength:S?.strength??1}:null),children:[t.jsx("option",{value:"",children:a("Không")}),Xv.map(([j,M])=>t.jsx("option",{value:j,children:a(M)},j))]})]}),S&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ mạnh")}),t.jsx("input",{type:"range","aria-label":a("Độ mạnh khung va chạm"),min:.1,max:1,step:.05,value:S.strength,onChange:j=>I({...S,strength:+j.target.value})})]}),S&&!d?.holds.length&&t.jsx("p",{className:"shot-fx-hint",children:a("Thêm hit-stop để khung va chạm hiện ra.")})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Vệt chém")}),g.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Vệt chém trên vũ khí đang cầm ({0})",[g.length])}),t.jsx("input",{type:"checkbox","aria-label":a("Vệt chém"),checked:v,onChange:j=>y(j.target.checked)})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu vệt")}),t.jsxs("select",{"aria-label":a("Kiểu vệt chém"),"data-timing":"trail-style",value:k,onChange:j=>y(!0,{style:j.target.value}),children:[t.jsx("option",{value:"ribbon",children:a("Dải sáng")}),t.jsx("option",{value:"smear",children:a("Smear trắng (anime)")})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu vệt")}),t.jsx("input",{type:"color","aria-label":a("Màu vệt chém"),value:g[0].trail?.color||(k==="smear"?Tp.color:Lp.color),onChange:j=>y(!0,{color:j.target.value})})]})]}):t.jsx("p",{className:"shot-fx-hint",children:a("Chưa có vũ khí nào đang cầm (thương, kiếm, côn, gậy, dao).")})]})]})}const Qv={blocked:"đỡ",miss:"né",body:"trúng"};function Zv({stage:e,playhead:n,change:s,setError:o}){const i=ct(),r=i==="en",l=e.items.filter(N=>Fr(N)&&!N.hidden),[h,u]=R.useState(""),[m,d]=R.useState(""),[f,p]=R.useState(["katana","katana"]),[b,g]=R.useState(4),[v,y]=R.useState(1),[k,C]=R.useState(!0),[S,I]=R.useState(""),j=l.find(N=>N.id===h)??l[0],M=l.find(N=>N.id===m&&N.id!==j?.id)??l.find(N=>N.id!==j?.id),T=()=>s(N=>{const A=N.items.find(H=>H.id===j?.id),O=A?[A.position[0],0,A.position[2]+2]:[0,0,2];return{...N,items:[...N.items,{...Mn("person",N.items.length),name:a("Đối thủ"),position:O,rotation:[0,180,0]}]}}),w=N=>{if(!j||!M){o(a("Cần hai nhân vật trong cảnh để dàn cảnh đấu."));return}const A=Wg(e,{a:j.id,b:M.id,packs:f,exchanges:b,seed:N,start:n},()=>crypto.randomUUID());if(!A.ok){o(A.error);return}let O=A.stage;if(k)try{O=Ip(O,{fighters:[j.name,M.name],start:n,end:A.end+.4}).stage}catch{}o(""),y(N),I(A.plan.map(H=>`${H.time.toFixed(1)}s ${H.attackerName} → ${r?H.result:a(Qv[H.result])}`).join(" · ")),s(()=>O)},E=(N,A)=>p(O=>N===0?[A,O[1]]:[O[0],A]);return t.jsxs("fieldset",{className:"shot-duel",children:[t.jsx("legend",{children:a("Đấu 2 người")}),l.length<2?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:a("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:a("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?a("Người tấn công trước"):a("Đối thủ"),value:(N===0?j:M)?.id??"",onChange:A=>(N===0?u:d)(A.target.value),children:l.filter(A=>N===0||A.id!==j?.id).map(A=>t.jsx("option",{value:A.id,children:A.name},A.id))}),t.jsx("select",{"aria-label":a("Vũ khí"),"data-duel-weapon":N,value:f[N],onChange:A=>E(N,A.target.value),children:[...dd.filter(A=>A.id in Hg),{id:"fist",label:"Tay không",labelEn:"Unarmed"}].map(A=>t.jsx("option",{value:A.id,children:r?A.labelEn:a(A.label)},A.id))})]},N)),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Số pha đấu")}),t.jsx("input",{type:"number","aria-label":a("Số pha đấu"),min:1,max:10,value:b,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:a("Camera đấu (giữ cả hai trong khung)")}),t.jsx("input",{type:"checkbox","aria-label":a("Camera đấu"),checked:k,onChange:N=>C(N.target.checked)})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-duel":"stage",onClick:()=>w(v),children:a("Dàn cảnh đấu từ playhead")}),t.jsx("button",{type:"button","data-duel":"reroll",onClick:()=>w(v+1),children:a("Phương án khác")})]}),t.jsx("p",{className:"shot-fx-hint",children:S||a("Đò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 wr="application/x-clipoox-fx",Mr=(e,n)=>e.lib?n==="en"&&e.nameEn?e.nameEn:e.name:a(e.name),Jv=(e,n)=>e.lib?n==="en"&&e.descEn?e.descEn:e.desc:a(e.desc);function e1({entry:e,hot:n}){const s=R.useRef(null);return R.useEffect(()=>{const o=s.current;if(!o)return;const i=o.getContext("2d");if(!i)return;const r=o.width,l=o.height;if(!n){Mc(i,e,Fg(e),r,l);return}let h=0;const u=performance.now(),m=Pg(e),d=()=>{Mc(i,e,(performance.now()-u)/1e3%m,r,l),h=requestAnimationFrame(d)};return h=requestAnimationFrame(d),()=>cancelAnimationFrame(h)},[e,n]),t.jsx("canvas",{ref:s,width:192,height:108,"aria-hidden":"true"})}function Ks({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}const Nh=[["chest","ngực"],["head","đầu"],["feet","chân"],["hand_right","tay phải"],["hand_left","tay trái"]];function t1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,anchor:l,setError:h,onEdit:u,onPlayClip:m}){const d=ct(),f=Dv(),[p,b]=R.useState(""),[g,v]=R.useState("tu-tien"),[y,k]=R.useState(null),C=e.shots.find(T=>T.id===e.activeShot)??e.shots[0],S=R.useMemo(()=>g==="camera"||g==="weapon"||g==="timing"?[]:Rp(p,p.trim()?void 0:g),[p,g,f.version]),I=e.items.filter(T=>T.kind==="fx"&&T.fx),j=I.find(T=>T.id===n)??null,M=T=>{const w=vu(e,T,{selected:n,ground:r(),start:s,label:Mr(T,d),anchor:l});if("error"in w){h(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[xn.maxItems]));return}h(""),o(()=>w.stage),i(w.item.id)};return t.jsxs("div",{className:"shot-fx",children:[j&&u&&t.jsxs("button",{type:"button",className:"shot-fx-edit-jump",onClick:u,children:["✎ ",a("Sửa {0}",[j.name])]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm hiệu ứng"),placeholder:a("Tìm hiệu ứng… (vd: kiem, set, aura)"),value:p,onChange:T=>b(T.target.value)})}),t.jsxs("div",{className:"shot-fx-cats",role:"tablist","aria-label":a("Nhóm hiệu ứng"),children:[Fp.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?a(T.name):a("Sắp có"),onClick:()=>{v(T.id),b("")},children:[a(T.name),!T.ready&&t.jsx("small",{children:a("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:["🎥 ",a("Camera")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="weapon",className:`shot-lib-tab${g==="weapon"?" active":""}`,onClick:()=>v("weapon"),children:["⚔ ",a("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:["⏱ ",a("Nhịp đòn")]})]}),g==="camera"&&t.jsx(Gv,{stage:e,selected:n,playhead:s,change:o,setError:h,query:p}),g==="weapon"&&!p&&t.jsx(Zv,{stage:e,playhead:s,change:o,setError:h}),g==="weapon"&&(m?t.jsx(qv,{stage:e,selected:n,onPlay:m,setError:h,query:p}):null),g==="timing"&&t.jsx(Yv,{stage:e,playhead:s,change:o,setError:h}),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:Jv(T,d),onMouseEnter:()=>k(T.id),onMouseLeave:()=>k(null),onFocus:()=>k(T.id),onBlur:()=>k(null),onDragStart:w=>{w.dataTransfer.setData(wr,T.id),w.dataTransfer.effectAllowed="copy"},onClick:()=>M(T),children:[t.jsx(e1,{entry:T,hot:y===T.id}),t.jsx("span",{children:Mr(T,d)}),T.lib&&t.jsx("small",{className:"shot-fx-lib",children:a("Thư viện Clipoox")})]},T.id)),!S.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có hiệu ứng nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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:[a("Hiệu ứng trong cảnh")," ",t.jsxs("small",{className:"shot-total",children:["· ",I.length,"/",xn.maxItems]})]}),t.jsxs("div",{className:"shot-list shot-fx-list",children:[I.map(T=>{const w=Rn(T,C);return t.jsxs("div",{className:n===T.id?"active":"",children:[t.jsxs("button",{title:a("Sửa {0}",[T.name]),onClick:()=>{i(T.id),u?.()},children:["✦ ",T.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",w.off?a("không phát trong shot này"):`${w.start.toFixed(1)}s → ${(w.start+w.duration).toFixed(1)}s`]})]}),t.jsx("button",{title:T.hidden?a("Hiện"):a("Ẩn"),onClick:()=>o(E=>({...E,items:E.items.map(N=>N.id===T.id?{...N,hidden:!N.hidden}:N)})),children:T.hidden?"○":"●"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[T.name]),title:a("Xóa {0}",[T.name]),onClick:()=>{o(E=>({...E,items:E.items.filter(N=>N.id!==T.id),shots:E.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(Ne.trash,{})})]},T.id)}),!I.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Chưa có hiệu ứng. Chọn một thẻ ở trên.")})]})]})}function n1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,engine:l}){ct();const h=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":a("Hiệu ứng đang sửa"),value:m?.id??"",onChange:d=>i(d.target.value||null),children:[!m&&t.jsx("option",{value:"",children:a("Chọn hiệu ứng…")}),u.map(d=>t.jsxs("option",{value:d.id,children:["✦ ",d.name]},d.id))]}),m?t.jsx(s1,{item:m,stage:e,shot:h,playhead:s,change:o,ground:r,engine:l??null}):t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:u.length?a("Bấm vào một hiệu ứng trên timeline (hàng ✦) hoặc chọn ở trên để sửa."):a("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:["✎ ",a("Sửa {0}",[u[0].name])]})]})]})}function s1({item:e,stage:n,shot:s,playhead:o,change:i,ground:r,engine:l}){const h=ct(),[u,m]=R.useState(null),d=e.fx,f=$o[d.preset],p=ud(d.cat??""),b=Rn(e,s),g=!!s.fxTiming?.[e.id],v=n.items.filter($=>$.id!==e.id&&$.kind!=="fx"&&!$.hidden),y=($,W={})=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id?{...Y,...W,fx:{...Y.fx,...$}}:Y)})),k=$=>i(W=>({...W,items:W.items.map(z=>z.id===e.id?{...z,...$}:z)})),C=$=>i(W=>({...W,shots:W.shots.map(z=>z.id===W.activeShot?{...z,fxTiming:{...z.fxTiming,[e.id]:Pr({...Rn(e,z),...$,off:!1},z.duration)}}:z)})),S=($,W)=>y({params:{...d.params,[$]:W}}),I=tr(er(d).fx??d),j=d.path??[],M=$=>y({path:$.length>=2?$:void 0}),T=j.length;R.useEffect(()=>{if(!(!l||T<2))return l.setFxPathEditor({itemId:e.id,selected:u,select:m,move:($,W)=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id&&Y.fx?.path?{...Y,fx:{...Y.fx,path:Y.fx.path.map((J,V)=>V===$?W.map(K=>+K.toFixed(2)):J)}}:Y)}))}),()=>l.setFxPathEditor(null)},[l,e.id,T,u]);const w=d.attach?v.find($=>$.id===d.attach.to):void 0,E=s.duration>0?Math.min(1,Math.max(0,o/s.duration)):0,N=md(e,s),A=Do(e,s,E),O=$=>{N?i(W=>Oo(W,e.id,E,$)):$.position?y({attach:{...d.attach,offset:$.position}}):$.yaw!==void 0&&k({rotation:[e.rotation[0],$.yaw,e.rotation[2]]})},H=$=>{const[W,z]=$.split("|"),Y=v.find(J=>J.id===W);return Y?Zl(Y,z).map(J=>+J.toFixed(2)):null},D=v.flatMap($=>Nh.filter(([W])=>$.kind==="person"||W==="chest"||W==="feet").map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)));return t.jsxs("div",{className:"shot-fx-inspector","aria-label":a("Chỉnh hiệu ứng"),children:[t.jsxs("h3",{children:[a("CHỈNH HIỆU ỨNG")," ",t.jsxs("small",{className:"shot-total",children:["· ",p?Mr(p,h):e.name]})]}),t.jsx("input",{"aria-label":a("Tên hiệu ứng"),value:e.name,onChange:$=>k({name:$.target.value})}),n.plate&&t.jsxs("label",{className:"shot-field",title:a("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:a("Lớp VFX")}),t.jsxs("select",{"aria-label":a("Lớp VFX"),value:pd(e),onChange:$=>k({vfxLayer:$.target.value}),children:[t.jsx("option",{value:"behind",children:a("Sau người")}),t.jsx("option",{value:"front",children:a("Trước người")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian trong shot")}),g?t.jsxs(t.Fragment,{children:[t.jsx(Ks,{label:"Bắt đầu (s)",value:b.start,min:0,max:Math.max(.1,s.duration),step:.1,onChange:$=>C({start:$})}),t.jsx(Ks,{label:"Kéo dài (s)",value:b.duration,min:.2,max:xn.maxDuration,step:.1,onChange:$=>C({duration:$})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lặp lại")}),t.jsx("input",{type:"checkbox","aria-label":a("Lặp lại"),checked:b.loop,onChange:$=>C({loop:$.target.checked})})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",onClick:()=>C({start:+(o*s.duration).toFixed(2)}),children:a("Bắt đầu tại playhead")}),t.jsx("button",{type:"button",onClick:()=>i($=>({...$,shots:$.shots.map(W=>W.id===$.activeShot?{...W,fxTiming:Object.fromEntries(Object.entries(W.fxTiming??{}).filter(([z])=>z!==e.id))}:W)})),children:a("Bỏ khỏi shot này")})]})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>C({start:+(o*s.duration).toFixed(2),duration:d.duration}),children:a("Phát trong shot này")})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu hiệu ứng"),value:e.color,onChange:$=>k({color:$.target.value})})]}),t.jsx(Ks,{label:"Cường độ",value:d.intensity,min:.1,max:3,step:.1,onChange:$=>y({intensity:$})}),t.jsx(Ks,{label:"Kích thước",value:e.scale[0],min:.1,max:6,step:.1,onChange:$=>k({scale:[$,$,$]})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Sn,{"aria-label":a("Seed"),value:d.seed,min:0,max:2147483647,step:1,onCommit:$=>y({seed:Math.round($)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>y({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ne.reset,{}),a("Xáo trộn")]})]})]}),f.params.length>0&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thông số")}),f.params.map($=>$.type==="number"?t.jsx(Ks,{label:$.label??$.key,value:Number(d.params[$.key]??$.def),min:$.min,max:$.max,step:$.max-$.min>20?1:.05,onChange:W=>S($.key,W)},$.key):t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a($.label??$.key)}),t.jsx("select",{"aria-label":a($.label??$.key),value:String(d.params[$.key]??$.def),onChange:W=>S($.key,W.target.value),children:$.options.map(W=>t.jsx("option",{value:W,children:W},W))})]},$.key))]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Gắn vào")}),t.jsxs("select",{"aria-label":a("Đối tượng gắn hiệu ứng"),value:d.attach?.to??"",onChange:$=>{const W=$.target.value;y({attach:W?{to:W,...d.attach?.hand?{hand:d.attach.hand}:{},offset:d.attach?.offset}:void 0})},children:[t.jsx("option",{value:"",children:a("Tự do (theo vị trí của hiệu ứng)")}),v.map($=>t.jsx("option",{value:$.id,children:$.name},$.id))]}),d.attach&&t.jsxs(t.Fragment,{children:[w?.kind==="person"&&t.jsxs("select",{"aria-label":a("Bộ phận gắn"),value:d.attach.hand??d.attach.part??"",onChange:$=>{const W=$.target.value,{hand:z,part:Y,...J}=d.attach;y({attach:{...J,...W==="L"||W==="R"?{hand:W}:W==="chest"||W==="head"?{part:W}:{}}})},children:[t.jsx("option",{value:"",children:a("Cơ thể (chân)")}),t.jsx("option",{value:"chest",children:a("Ngực")}),t.jsx("option",{value:"head",children:a("Đầu")}),t.jsx("option",{value:"R",children:a("Tay phải")}),t.jsx("option",{value:"L",children:a("Tay trái")})]}),d.attach.hand&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Ở đầu vật đang cầm (nòng súng)")}),t.jsx("input",{type:"checkbox","aria-label":a("Ở đầu vật đang cầm (nòng súng)"),checked:d.attach.tip===!0,onChange:$=>y({attach:{...d.attach,tip:$.target.checked?!0:void 0}})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xoay theo đối tượng")}),t.jsx("input",{type:"checkbox","aria-label":a("Xoay theo đối tượng"),checked:d.attach.follow!=="position",onChange:$=>{const{follow:W,...z}=d.attach;y({attach:{...z,...$.target.checked?{}:{follow:"position"}}})}})]}),t.jsx("p",{className:"shot-fx-hint",children:N?a("Độ 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]):a("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(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Sn,{"aria-label":a("Lệch {0}",[$]),precision:2,step:.1,min:-100,max:100,value:+A.position[W].toFixed(3),onCommit:z=>{const Y=[...A.position];Y[W]=z,O({position:Y})}})]},$))}),t.jsx("button",{type:"button",onClick:()=>i($=>Oo($,e.id,E)),children:a("+◆ Key độ lệch tại playhead")})]}),!d.attach&&t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Sn,{"aria-label":a("Vị trí {0}",[$]),precision:2,step:.1,min:-1e3,max:1e3,value:e.position[W],onCommit:z=>{const Y=[...e.position];Y[W]=z,k({position:Y})}})]},$))}),t.jsx(Ks,{label:"Hướng (độ)",value:d.attach?+A.yaw.toFixed(1):e.rotation[1],min:-360,max:360,step:5,onChange:$=>d.attach?O({yaw:$}):k({rotation:[e.rotation[0],$,e.rotation[2]]})})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Nhắm vào")}),t.jsxs("select",{"aria-label":a("Mục tiêu bám theo"),value:d.target?`${d.target.to}|${d.target.part}`:"",onChange:$=>{const[W,z]=$.target.value.split("|");y({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:a("Không (theo đường bay / hướng)")}),v.flatMap($=>[...Nh.filter(([W])=>["chest","head","feet"].includes(W)).map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)),t.jsxs("option",{value:`${$.id}|center`,children:[$.name," · ",a("Cả khối (nhà, tường, cửa kính)")]},`${$.id}|center`)])]}),d.target&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Chỉ một phần (tên, vd: window)")}),t.jsx("input",{"aria-label":a("Tên phần của mục tiêu"),value:d.target.name??"",onChange:$=>y({target:{...d.target,name:$.target.value.trim()?$.target.value.slice(0,60):void 0}})})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đường bay")}),j.length<2&&t.jsx("button",{type:"button",onClick:()=>{const $=Zl(w??{kind:"box",position:e.position,scale:[1,1,1]},"chest"),W=r();M([$.map(z=>+z.toFixed(2)),[+($[0]+6).toFixed(2),$[1],+(W[2]||$[2]).toFixed(2)]])},children:a("Tạo đường bay")}),j.length>=2&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Từ")}),t.jsxs("select",{"aria-label":a("Điểm xuất phát"),value:"",onChange:$=>{const W=H($.target.value);W&&M([W,...j.slice(1)])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tới")}),t.jsxs("select",{"aria-label":a("Điểm đến"),value:"",onChange:$=>{const W=H($.target.value);W&&M([...j.slice(0,-1),W])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),j.map(($,W)=>t.jsxs("div",{className:`shot-fx-point ${u===W?"active":""}`,children:[t.jsx("b",{role:"button",tabIndex:0,title:a("Chọn điểm để kéo trong khung 3D"),onClick:()=>m(W),onKeyDown:z=>{z.key==="Enter"&&m(W)},children:W===0?a("Đầu"):W===j.length-1?a("Cuối"):`${W+1}`}),[0,1,2].map(z=>t.jsx(Sn,{"aria-label":a("Điểm {0} {1}",[W+1,"XYZ"[z]]),precision:2,step:.1,min:-1e3,max:1e3,value:$[z],onCommit:Y=>{const J=j.map(V=>[...V]);J[W][z]=Y,M(J)}},z)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[W+1]),disabled:j.length<=2,onClick:()=>M(j.filter((z,Y)=>Y!==W)),children:t.jsx(Ne.close,{})})]},W)),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",disabled:j.length>=xn.maxPathPoints,onClick:()=>{const $=j.at(-2),W=j.at(-1);M([...j.slice(0,-1),[+(($[0]+W[0])/2).toFixed(2),+(($[1]+W[1])/2+.8).toFixed(2),+(($[2]+W[2])/2).toFixed(2)],W])},children:a("Thêm điểm giữa")}),t.jsx("button",{type:"button",onClick:()=>y({path:void 0}),children:a("Xóa đường bay")})]})]})]}),t.jsx("small",{className:"shot-fx-budget",children:a("{0} hạt · giới hạn {1}/hiệu ứng",[I,xn.maxParticlesPerItem])})]})}const en=e=>+e.toFixed(2),a1=[{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}],o1=[{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}],i1={collapse:"🏚",explosion:"💥",shatter:"🪟",burning:"🔥",collapse_building:"🏢"},r1={pancake:"Sập tại chỗ (từng tầng)",topple:"Đổ nghiêng",base:"Sập từ chân"},Nu=e=>od.has(String(e)),Ba=e=>!!e&&e.kind==="fx"&&e.fx?.preset===Ji,Au=e=>e.items.filter(n=>Zd.has(n.kind)&&!n.hidden&&!n.hold);function Tu(e,n){const s=e.shots.find(b=>b.id===e.activeShot)??e.shots[0],o=e.items.find(b=>b.id===n.target),i=n.bounds??{min:[o.position[0]-.5,0,o.position[2]-.5],max:[o.position[0]+.5,1,o.position[2]+.5]},r=[0,1,2].map(b=>i.max[b]-i.min[b]),l=en(Math.min(6,Math.max(.6,Math.max(...r)/5))),h=Nu(n.recipe),u=en(Math.min(Math.max(0,n.playhead),Math.max(0,s.duration-.2))),m=en(Math.max(.3,h?Math.min(4,s.duration-u):s.duration-u)),d=Op({target:o.id,recipe:n.recipe,seed:n.seed??Math.floor(Math.random()*1e9)+1,start:u,duration:m,params:{radius:l,...n.params}}),f=h?[en((i.min[0]+i.max[0])/2),en(i.max[1]+.6),en((i.min[2]+i.max[2])/2)]:[en(i.min[0]-l-Number(d.params.falloff)-.3),en((i.min[1]+i.max[1])/2),en((i.min[2]+i.max[2])/2)],p={...Mn("fx",e.items.length),name:n.name,color:Wa[n.recipe].color,position:f,fx:d};return{item:p,stage:{...e,items:[...e.items,p],shots:e.shots.map(b=>b.id===s.id?{...b,fxTiming:{...b.fxTiming,[p.id]:{start:u,duration:m}}}:b)}}}function wo(e,n,s,o,i=vt()){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 h=r.objectKeys?.[n]??[],u=_n(l,r,s),m=h.find(f=>Math.abs(f.time-s)<1e-6),d={...m,id:m?.id??i,time:s,position:o??[...u.position],rotation:[...u.rotation],scale:[...u.scale]};return{...e,shots:e.shots.map(f=>f.id===r.id?{...f,objectKeys:{...f.objectKeys,[n]:[...h.filter(p=>p.id!==d.id),d].sort((p,b)=>p.time-b.time)}}:f)}}function Mo({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function l1({stage:e,selected:n,progress:s,change:o,onSelect:i,engine:r,setError:l}){ct();const h=e.shots.find(k=>k.id===e.activeShot)??e.shots[0],u=s*h.duration,m=e.items.filter(Ba),d=Au(e),f=m.find(k=>k.id===n)??null,[p,b]=R.useState(()=>({target:"",recipe:"collapse"})),g=d.find(k=>k.id===n)??null,v=d.some(k=>k.id===p.target)?p.target:g?.id??d[0]?.id??"",y=()=>{if(!v)return;if(e.items.filter(S=>S.kind==="fx").length>=xn.maxItems){l?.(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[xn.maxItems]));return}const k=r?.objectBounds()[v]??null,C=Tu(e,{target:v,recipe:p.recipe,playhead:u,bounds:k,name:`${a("Mix FX")} ${m.length+1}`});o(()=>C.stage),i(C.item.id)};return t.jsxs("div",{className:"shot-fx shot-mixfx",children:[t.jsx("p",{className:"shot-fx-hint",children:a("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(k=>t.jsx("div",{className:k.id===f?.id?"active":"",children:t.jsxs("button",{type:"button",onClick:()=>i(k.id),children:["💥 ",k.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",e.items.find(C=>C.id===k.fx?.target?.to)?.name??a("chưa có mục tiêu")]})]})},k.id))}),!f&&t.jsxs("fieldset",{className:"shot-mixfx-new",children:[t.jsx("legend",{children:a("Tạo Mix FX")}),d.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsx("select",{"aria-label":a("Mục tiêu bị phá"),value:v,onChange:k=>b(C=>({...C,target:k.target.value})),children:d.map(k=>t.jsx("option",{value:k.id,children:k.name},k.id))})]}),t.jsx(Lu,{value:p.recipe,onPick:k=>b(C=>({...C,recipe:k}))}),t.jsx("button",{type:"button",className:"shot-primary",onClick:y,children:a("Tạo khối cầu phá huỷ")})]}):t.jsx("p",{className:"shot-fx-empty",children:a("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(c1,{item:f,stage:e,progress:s,change:o,onSelect:i,engine:r??null},f.id)]})}function Lu({value:e,onPick:n}){return t.jsx("div",{className:"shot-mixfx-recipes",role:"group","aria-label":a("Công thức hiệu ứng"),children:Pp.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:i1[s]}),a(Wa[s].name)]},s))})}function c1({item:e,stage:n,progress:s,change:o,onSelect:i,engine:r}){const l=n.shots.find(M=>M.id===n.activeShot)??n.shots[0],h=e.fx,u=h.params,m=Rn(e,l),d=!!l.fxTiming?.[e.id],f=l.objectKeys?.[e.id]??[],p=Au(n),b=n.items.find(M=>M.id===h.target?.to)??null,g=(M,T={})=>o(w=>({...w,items:w.items.map(E=>E.id===e.id?{...E,...T,fx:{...E.fx,...M}}:E)})),v=(M,T)=>g({params:{...u,[M]:T}}),y=M=>o(T=>({...T,shots:T.shots.map(w=>w.id===T.activeShot?{...w,fxTiming:{...w.fxTiming,[e.id]:Pr({...Rn(e,w),...M,off:!1},w.duration)}}:w)})),[k,C]=R.useState(null),S=Nu(u.recipe),I=()=>{if(!b||n.items.filter(A=>A.kind==="fx").length>=xn.maxItems)return;const M=(k?.first??m.start)+.6,T=r?.objectBounds()[b.id]??null,w=n.items.filter(Ba).length,E=Tu(n,{target:b.id,recipe:"collapse_building",playhead:Math.min(M,Math.max(0,l.duration-.3)),bounds:T,name:`${a("Sập toà nhà")} ${w+1}`,params:{chunks:Number(u.chunks)}}),N={...E.item,fx:{...E.item.fx,seed:h.seed}};o(()=>({...E.stage,items:E.stage.items.map(A=>A.id===N.id?N:A)})),i(N.id)};R.useEffect(()=>{const M=()=>C(r?.fx?.mixStats?.(s*l.duration).find(w=>w.id===e.id)??null);M();const T=window.setInterval(M,500);return()=>window.clearInterval(T)},[r,e.id,s,l.duration,n.revision]);const j=()=>{const M=b&&r?.objectBounds()[b.id];if(!M||l.duration<=0)return;const T=Number(u.radius)*e.scale[0]+Number(u.falloff)+.3,w=en((M.min[1]+M.max[1])/2),E=en((M.min[2]+M.max[2])/2),N=Math.min(1,m.start/l.duration),A=Math.min(1,(m.start+m.duration)/l.duration);o(O=>{const H={...O,shots:O.shots.map(D=>D.id===O.activeShot?{...D,objectKeys:{...D.objectKeys,[e.id]:[]}}:D)};return wo(wo(H,e.id,N,[en(M.min[0]-T),w,E]),e.id,A,[en(M.max[0]+T),w,E])})};return t.jsxs("div",{className:"shot-fx-inspector shot-mixfx-inspector","aria-label":a("Chỉnh Mix FX"),children:[t.jsxs("h3",{children:[a("MIX FX")," ",t.jsxs("small",{className:"shot-total",children:["· ",e.name]})]}),t.jsx("input",{"aria-label":a("Tên Mix FX"),value:e.name,onChange:M=>o(T=>({...T,items:T.items.map(w=>w.id===e.id?{...w,name:M.target.value}:w)}))}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsxs("select",{"aria-label":a("Mục tiêu bị phá"),value:b?.id??"",onChange:M=>g({target:M.target.value?{to:M.target.value,part:"center"}:void 0}),children:[!b&&t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),p.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id))]})]}),t.jsx(Lu,{value:String(u.recipe),onPick:M=>g({params:$p(M,u)},{color:Wa[M].color})}),k?.overridden&&t.jsx("p",{className:"shot-fx-hint shot-mixfx-note","data-mix":"note",children:a("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(M=>M.id===k.lead)?.name??""])}),S?t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Sập toà nhà")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu sập")}),t.jsx("select",{"aria-label":a("Kiểu sập"),"data-mix":"mode",value:String(u.mode??"pancake"),onChange:M=>v("mode",M.target.value),children:Dp.map(M=>t.jsx("option",{value:M,children:a(r1[M])},M))})]}),o1.filter(({key:M})=>M!=="yaw"||u.mode==="topple").map(({key:M,step:T})=>{const w=Jl.find(E=>E.key===M);return t.jsx(Mo,{label:w.label??M,value:Number(u[M]??w.def),min:w.min,max:w.max,step:T,onChange:E=>v(M,M==="chunks"?Math.round(E):E)},M)})]}):t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khối cầu & độ ảnh hưởng")}),a1.map(({key:M,step:T})=>{const w=Jl.find(E=>E.key===M);return t.jsx(Mo,{label:w.label??M,value:Number(u[M]??w.def),min:w.min,max:w.max,step:T,onChange:E=>v(M,M==="chunks"?Math.round(E):E)},M)}),t.jsxs("label",{className:"shot-field shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Mất đỡ thì rơi"),"data-mix":"support",checked:u.support!=="off",onChange:M=>v("support",M.target.checked?"on":"off")}),t.jsx("span",{children:a("Mất đỡ thì rơi")})]}),t.jsxs("button",{type:"button","data-mix":"collapse-after",disabled:!b,onClick:I,children:["🏢 ",a("Thêm sập sau nổ")]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Seed & màu")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Sn,{"aria-label":a("Seed"),value:h.seed,min:0,max:2147483647,step:1,onCommit:M=>g({seed:Math.round(M)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>g({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ne.reset,{}),a("Xáo trộn")]})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu bụi / lửa")}),t.jsx("input",{type:"color","aria-label":a("Màu bụi / lửa"),value:e.color,onChange:M=>o(T=>({...T,items:T.items.map(w=>w.id===e.id?{...w,color:M.target.value}:w)}))})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian phá trong shot")}),d?t.jsxs(t.Fragment,{children:[t.jsx(Mo,{label:"Bắt đầu (s)",value:m.start,min:0,max:Math.max(.1,l.duration),step:.1,onChange:M=>y({start:M})}),t.jsx(Mo,{label:"Kéo dài (s)",value:m.duration,min:.2,max:xn.maxDuration,step:.1,onChange:M=>y({duration:M})})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>y({start:en(s*l.duration),duration:en(Math.max(.2,l.duration*(1-s)))}),children:a("Phát trong shot này")})]}),!S&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đườ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:()=>o(M=>wo(M,e.id,s)),children:["+◆ ",a("Thêm điểm tại playhead")]}),t.jsx("button",{type:"button","data-mix":"sweep",disabled:!b,onClick:j,children:a("Quét ngang qua mục tiêu")})]}),f.map((M,T)=>t.jsxs("div",{className:"shot-fx-point shot-mixfx-key","data-key":M.id,children:[t.jsxs("b",{children:[(M.time*l.duration).toFixed(1),"s"]}),[0,1,2].map(w=>t.jsx(Sn,{"aria-label":a("Điểm {0} {1}",[T+1,"XYZ"[w]]),precision:2,step:.1,min:-1e3,max:1e3,value:M.position[w],onCommit:E=>{const N=[...M.position];N[w]=E,o(A=>wo(A,e.id,M.time,N,M.id))}},w)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[T+1]),onClick:()=>o(w=>({...w,shots:w.shots.map(E=>E.id===w.activeShot?{...E,objectKeys:{...E.objectKeys,[e.id]:(E.objectKeys?.[e.id]??[]).filter(N=>N.id!==M.id)}}:E)})),children:t.jsx(Ne.close,{})})]},M.id)),!f.length&&t.jsx("p",{className:"shot-fx-hint",children:a("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”.")})]}),k&&t.jsxs("small",{className:"shot-fx-budget","data-mix-stats":`${k.broken}/${k.chunks}`,children:[a("{0} mảnh · {1} mảnh đã vỡ tại playhead · {2} sẽ vỡ",[k.chunks,k.broken,k.hit]),k.falling?a(" · {0} mảnh mất đỡ rơi xuống",[k.falling]):""]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",className:"shot-delete-item",onClick:()=>{o(M=>({...M,items:M.items.filter(T=>T.id!==e.id),shots:M.shots.map(T=>({...T,...T.objectKeys?.[e.id]?{objectKeys:Object.fromEntries(Object.entries(T.objectKeys).filter(([w])=>w!==e.id))}:{},...T.fxTiming?.[e.id]?{fxTiming:Object.fromEntries(Object.entries(T.fxTiming).filter(([w])=>w!==e.id))}:{}}))})),i(null)},children:a("Xóa {0}",[e.name])}),t.jsx("button",{type:"button",onClick:()=>i(null),children:a("+ Mix FX khác")})]})]})}let Dn=null,Ws,Io,Sr,Ah=null;const Th=new Map,qi=new Map;let Lh=Promise.resolve(),Eh=0;const Ih=112;function h1(){const e=document.createElement("canvas");e.width=e.height=64;const n=e.getContext("2d");for(let o=0;o<8;o++)for(let i=0;i<8;i++)n.fillStyle=(i+o)%2?"#3a4148":"#262b30",n.fillRect(i*8,o*8,8,8);const s=new Kr(e);return s.colorSpace=Jo,s.wrapS=s.wrapT=Md,s.repeat.set(3,3),s.magFilter=sg,s}function d1(){if(Dn)return Dn;Dn=new _r({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),Dn.outputColorSpace=Jo,Dn.toneMapping=jd,Dn.toneMappingExposure=1.1,Dn.setClearColor(0,0),Dn.setSize(Ih,Ih,!1),Ws=new zr;const e=new kd(Dn);Ah=e.fromScene(new Ld,.04).texture,e.dispose(),Ws.environment=Ah;const n=new Zo("#fff4e4",2.2);n.position.set(-2,3,3),Ws.add(n);const s=new ut(new ei(4,4),new fs({map:h1()}));return s.position.set(0,0,-1.4),Ws.add(s),Sr=new ut(new Hn(.5,48,32)),Ws.add(Sr),Io=new Br(30,1,.1,20),Io.position.set(0,.18,2.15),Io.lookAt(0,0,0),Dn}function u1(e){const n=d1(),s=_p({preset:e},Va,{studio:!0});if(!s)throw new Error(`unknown material ${e}`);Sr.material=s,n.render(Ws,Io);const o=n.domElement.toDataURL("image/png");return s.dispose(),o}function m1(e){const n=Th.get(e);if(n)return Promise.resolve(n);const s=qi.get(e);if(s)return s;if(!Ha(e))return Promise.reject(new Error(`unknown material ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&Eh>=o)return Promise.reject(new Error("thumbnail limit"));Eh++;const i=Lh.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=u1(e);Th.set(e,h),r(h)}catch(h){l(h)}},20))).finally(()=>qi.delete(e));return Lh=i.catch(()=>{}),qi.set(e,i),i}const Ro="application/x-clipoox-material",Ia=e=>!!e&&e.kind!=="fx"&&e.kind!=="splat",Ca=e=>e===Qs?a("Cả đối tượng"):/^part-\d+/.test(e)?a("Phần {0}",[e.slice(5)]):e;function p1({preset:e,alt:n}){const[s,o]=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 h=new IntersectionObserver(u=>{u.some(m=>m.isIntersecting)&&(r(!0),h.disconnect())},{rootMargin:"120px"});return h.observe(l.current),()=>h.disconnect()},[i]),R.useEffect(()=>{if(!i)return;let h=!0;return m1(e.id).then(u=>{h&&o(u)}).catch(()=>{}),()=>{h=!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 cs({label:e,value:n,range:s,step:o,onInput:i,format:r}){return t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a(e)}),t.jsx("input",{type:"range","aria-label":a(e),min:s[0],max:s[1],step:o,value:n,onChange:l=>i(Number(l.target.value))}),t.jsx("output",{children:r?r(n):n.toFixed(2)})]})}function f1({stage:e,selected:n,change:s,engine:o,setError:i,scope:r,setScope:l}){const h=ct(),[u,m]=R.useState(""),[d,f]=R.useState(""),[p,b]=R.useState(!1),[g,v]=R.useState([]),y=e.items.find(q=>q.id===n)??null,k=Ia(y),C=R.useMemo(()=>zp(u,u.trim()?"":d),[u,d]);R.useEffect(()=>{if(!y||!k){v([]);return}const q=()=>v(o?.materialSlots(y.id)??[]);q();const ue=setTimeout(q,400),pe=setTimeout(q,1600);return()=>{clearTimeout(ue),clearTimeout(pe)}},[o,y?.id,y?.model?.gcsUri,y?.look,y?.figure,e.revision,k]),R.useEffect(()=>()=>o?.setPartPicker(null),[o]),R.useEffect(()=>{b(!1),o?.setPartPicker(null)},[n,o]);const S=g.length>1,I=r.mode==="part"&&S&&r.slot&&g.some(q=>q.slot===r.slot)?r.slot:Qs,j=y?.materials?.[I]??null,M=ec(j),[T,w]=R.useState([]),E=e.items.filter(q=>q.id!==y?.id&&Ia(q)&&!q.hidden),N=T.filter(q=>E.some(ue=>ue.id===q&&!ue.locked)),A=(q,ue=y?.id,pe=I,U=!0)=>{const le=e.items.find(Le=>Le.id===ue);if(!le||!Ia(le)){i(a("Chọn một đối tượng (hộp, model, nhân vật…) để áp vật liệu."));return}if(le.locked){i(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[le.name]));return}i("");const ce=U?N.filter(Le=>Le!==le.id):[];s(Le=>ce.reduce((je,ie)=>Gs(je,ie,Qs,q),Gs(Le,le.id,pe,q)))},O=(q,ue=y?.id,pe=I)=>A({preset:q.id},ue,pe),H=()=>A({mode:"tint",params:{color:"#ffffff"}}),[D,$]=R.useState(null),W=R.useRef(null),z=R.useRef(void 0),Y=()=>{clearTimeout(z.current);const q=W.current;W.current=null,q&&($(null),s(ue=>Gs(ue,q.itemId,q.slot,q.override)))};R.useEffect(()=>()=>Y(),[]);const J=`${y?.id}|${I}|${JSON.stringify(j)}`,V=D?.key===J?D.params:null,K=q=>{if(!y||!j)return;const ue={...j.params||{},...V||{},...q},pe=da(j)?{mode:"tint",params:{color:ue.color??"#ffffff",...ue.roughness!==void 0?{roughness:ue.roughness}:{},...ue.metalness!==void 0?{metalness:ue.metalness}:{}}}:{preset:j.preset,params:ue};$({key:J,params:ue}),o?.previewMaterials(y.id,Bp(y.materials,I,pe)),W.current={itemId:y.id,slot:I,override:pe},clearTimeout(z.current),z.current=setTimeout(Y,450)},G=j&&!da(j)?V?ec({preset:j.preset,params:V}):M:null,_=j&&da(j)?{...j.params,...V||{}}:null,ee=q=>{y&&(W.current=null,clearTimeout(z.current),s(ue=>Gs(ue,y.id,q,null)))},Q=()=>{y&&(W.current=null,clearTimeout(z.current),s(q=>({...q,items:q.items.map(ue=>{if(ue.id!==y.id)return ue;const{materials:pe,...U}=ue;return U})})))},ve=()=>{if(!(!o||!y)){if(p){o.setPartPicker(null),b(!1);return}b(!0),o.setPartPicker((q,ue)=>{b(!1);const pe=e.items.find(U=>U.id===q);if(q!==y.id){pe&&Ia(pe)&&!pe.locked&&i(a("Phần đó thuộc {0} — chọn đối tượng ấy trước.",[pe.name]));return}i(""),l({mode:"part",slot:ue})})}},xe=Object.entries(y?.materials||{});return t.jsxs("div",{className:"shot-mat",children:[t.jsx("div",{className:"shot-mat-target",children:y?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:y.name}),!k&&t.jsx("small",{children:a("Đối tượng này không đổi được vật liệu.")}),y.locked&&t.jsx("small",{children:a("Đang khoá")})]}):t.jsx("small",{children:a("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.")})}),y&&k&&S&&t.jsxs("div",{className:"shot-mat-scope",children:[t.jsxs("div",{className:"shot-seg",role:"radiogroup","aria-label":a("Á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:a("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(q=>q.slot===r.slot)?r.slot:g[0].slot}),children:a("Từng phần")})]}),r.mode==="part"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-mat-parts",role:"listbox","aria-label":a("Các phần của model"),children:g.map(({slot:q})=>{const ue=y.materials?.[q],pe=ue?Ha(ue.preset):null;return t.jsxs("button",{type:"button",role:"option","data-slot":q,"aria-selected":I===q,className:I===q?"active":"",onClick:()=>l({mode:"part",slot:q}),children:[Ca(q),pe?t.jsxs("small",{children:[" · ",Ta(pe,h)]}):da(ue)?t.jsxs("small",{children:[" · ",a("Giữ texture")]}):null]},q)})}),t.jsxs("button",{type:"button",className:`shot-mat-pick${p?" active":""}`,"aria-pressed":p,onClick:ve,children:[t.jsx(Ne.focus,{})," ",p?a("Bấm vào một phần của model… (bấm lại để huỷ)"):a("Chọn phần trên khung 3D")]})]})]}),y&&k&&!y.locked&&t.jsx("div",{className:"shot-mat-tintbar",children:t.jsxs("button",{type:"button","data-mat":"tint",className:_?"active":"","aria-pressed":!!_,onClick:()=>_?ee(I):H(),title:a("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:["🎨 ",a("Giữ texture gốc, chỉ đổi màu")]})}),y&&k&&_&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),"data-mat":"tint-panel",children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:a("Giữ texture gốc, chỉ đổi màu")}),t.jsxs("small",{children:[" · ",Ca(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ne.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu nhân")}),t.jsx("input",{type:"color","aria-label":a("Màu nhân"),value:_.color,onChange:q=>K({color:q.target.value})}),t.jsx("output",{children:_.color})]}),t.jsx(cs,{label:"Độ nhám",value:_.roughness??.5,range:Ns.roughness,step:.01,onInput:q=>K({roughness:q}),format:q=>_.roughness===void 0?a("gốc"):q.toFixed(2)}),t.jsx(cs,{label:"Độ kim loại",value:_.metalness??0,range:Ns.metalness,step:.01,onInput:q=>K({metalness:q}),format:q=>_.metalness===void 0?a("gốc"):q.toFixed(2)})]}),y&&k&&E.length>0&&t.jsxs("details",{className:"shot-mat-also",open:N.length>0,children:[t.jsx("summary",{children:a("Áp cho cả: {0} đối tượng khác",[N.length])}),t.jsx("div",{className:"shot-mat-also-list",role:"group","aria-label":a("Áp cho nhiều đối tượng"),children:E.map(q=>t.jsxs("label",{className:q.locked?"is-locked":"",children:[t.jsx("input",{type:"checkbox","data-also":q.id,disabled:q.locked,checked:N.includes(q.id),onChange:ue=>w(pe=>ue.target.checked?[...pe.filter(U=>U!==q.id),q.id]:pe.filter(U=>U!==q.id))}),q.name]},q.id))}),t.jsx("small",{className:"shot-fx-hint",children:a("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).",[y.name])})]}),y&&k&&j&&G&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:Ta(G.preset,h)}),t.jsxs("small",{children:[" · ",Ca(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ne.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu vật liệu"),value:G.color,onChange:q=>K({color:q.target.value})}),t.jsx("output",{children:G.color})]}),t.jsx(cs,{label:"Độ nhám",value:G.roughness,range:Ns.roughness,step:.01,onInput:q=>K({roughness:q})}),t.jsx(cs,{label:"Độ kim loại",value:G.metalness,range:Ns.metalness,step:.01,onInput:q=>K({metalness:q})}),!G.preset.mapless&&t.jsxs(t.Fragment,{children:[t.jsx(cs,{label:"Cỡ vân",value:G.scale,range:[.1,5],step:.05,onInput:q=>K({scale:q}),format:q=>`×${q.toFixed(2)}`}),t.jsx(cs,{label:"Xoay vân",value:G.rotation,range:Ns.rotation,step:1,onInput:q=>K({rotation:q}),format:q=>`${Math.round(q)}°`})]}),t.jsx(cs,{label:"Phát sáng",value:G.emissive,range:Ns.emissive,step:.1,onInput:q=>K({emissive:q}),format:q=>q.toFixed(1)}),t.jsx(cs,{label:G.preset.transmission?"Độ đục (kính)":"Độ đặc",value:G.opacity,range:Ns.opacity,step:.01,onInput:q=>K({opacity:q})})]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm vật liệu"),placeholder:a("Tìm vật liệu… (vd: go, kinh, thep)"),value:u,onChange:q=>m(q.target.value)})}),t.jsxs("div",{className:"shot-fx-cats shot-mat-cats",role:"tablist","aria-label":a("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:a("Tất cả")}),sd.map(q=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===q.id&&!u.trim(),className:d===q.id&&!u.trim()?"active":"",onClick:()=>{f(q.id),m("")},children:h==="en"?q.en:q.vi},q.id))]}),t.jsxs("div",{className:"shot-mat-grid",children:[C.map(q=>{const ue=Ta(q,h),pe=j?.preset===q.id;return t.jsxs("button",{type:"button",className:`shot-mat-card${pe?" active":""}`,"data-material":q.id,draggable:!0,"aria-pressed":pe,title:y&&k?a("Áp {0} cho {1}",[ue,y.name]):ue,onDragStart:U=>{U.dataTransfer.setData(Ro,q.id),U.dataTransfer.effectAllowed="copy"},onClick:()=>O(q),children:[t.jsx(p1,{preset:q,alt:ue}),t.jsx("span",{children:ue})]},q.id)}),!C.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có vật liệu nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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 đó.")}),y&&xe.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("h3",{children:[a("Vật liệu đang dùng")," ",t.jsxs("small",{className:"shot-total",children:["· ",xe.length]})]}),t.jsx("div",{className:"shot-list shot-mat-list",children:xe.map(([q,ue])=>{const pe=Ha(ue.preset);return t.jsxs("div",{className:q===I?"active":"",children:[t.jsxs("button",{type:"button",onClick:()=>l(q===Qs?{mode:"all",slot:r.slot}:{mode:"part",slot:q}),children:[Ca(q),t.jsxs("small",{className:"shot-list-meta",children:[" · ",pe?Ta(pe,h):da(ue)?a("Giữ texture · {0}",[ue.params.color]):ue.preset]})]}),t.jsx("button",{type:"button",className:"shot-delete-item","aria-label":a("Đặt lại {0}",[Ca(q)]),title:a("Đặt lại vật liệu gốc"),onClick:()=>ee(q),children:t.jsx(Ne.reset,{})})]},q)})}),t.jsxs("button",{type:"button",className:"shot-mat-reset-all",onClick:Q,children:[t.jsx(Ne.reset,{})," ",a("Đặt lại tất cả vật liệu gốc")]})]})]})}function Jr({pose:e}){ct();const n=(h,u,m,d,f,p,b,g=0)=>{const v=(m+b*g*.34)*Math.PI/180,y=(m-d+b*g*.22)*Math.PI/180,k=[h+Math.sin(v)*f,u+Math.cos(v)*f];return{joint:k,end:[k[0]+Math.sin(y)*p,k[1]+Math.cos(y)*p]}},s=n(35,38,e.shoulderL,e.elbowL,21,19,-1,e.shoulderOutL),o=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=(h,u,m,d)=>t.jsxs("g",{children:[t.jsx("path",{d:`M${h} 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],o.joint,o.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 g1=["person","prop","box","sphere","cylinder","model"],x1=[["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 b1({item:e,shot:n,playhead:s,patchItem:o,change:i}){ct();const r=Kp(e.toon),l=!!r?.on,h=r??{...Hp,on:!1},u=p=>o(e.id,{toon:{...h,...p}}),m=e.kind==="prop"&&e.prop?.kind==="ball",d=e.ball?.restitution??Wp.restitution,f=()=>i(p=>({...p,shots:p.shots.map(b=>b.id===n.id?{...b,ball:{...b.ball,[e.id]:[...(b.ball?.[e.id]||[]).filter(g=>g.t<s*b.duration-1e-6),{t:Math.round(s*b.duration*1e3)/1e3,kind:"launch",from:[...e.position],vel:[0,0,0]}]}}:b)}));return t.jsxs("div",{className:"shot-toon","data-testid":"shot-toon",children:[t.jsx("h3",{children:a("HOẠT HÌNH / CARTOON")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Phong cách hoạt hình"),checked:l,onChange:p=>u({on:p.target.checked})}),t.jsx("span",{children:a("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:a("Mức cường điệu")}),t.jsxs("span",{children:[Math.round(h.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Mức cường điệu"),type:"range",min:0,max:1,step:.05,value:h.amount,disabled:!l,onChange:p=>u({amount:+p.target.value})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Hình nhảy cách (on twos)"),checked:h.twos,disabled:!l,onChange:p=>u({twos:p.target.checked})}),t.jsx("span",{children:a("Hình nhảy cách (on twos)")})]}),t.jsxs("details",{className:"shot-toon-more",children:[t.jsx("summary",{children:a("Chi tiết nguyên lý")}),t.jsx("div",{className:"shot-toon-flags",children:x1.map(([p,b])=>t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a(b),checked:h[p],disabled:!l,onChange:g=>u({[p]:g.target.checked})}),t.jsx("span",{children:a(b)})]},p))})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[t.jsx("span",{className:"shot-toon-name",children:a("Độ nảy")}),t.jsxs("span",{children:[Math.round(d*100),"%"]}),t.jsx("input",{"aria-label":a("Độ nảy"),type:"range",min:.3,max:.95,step:.01,value:d,onChange:p=>o(e.id,{ball:{...e.ball,restitution:+p.target.value}})})]}),t.jsx("button",{type:"button",onClick:f,children:a("Thả bóng nảy từ đây")})]}),t.jsx("small",{className:"shot-hint",children:a("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 y1=[{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"}],hs=e=>(Number(e)||0).toFixed(1),Rh=()=>crypto.randomUUID(),v1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null;function j1({shot:e,item:n,playhead:s,change:o,engine:i,seek:r}){const l=ct(),h=l==="en",u=e.motionEdits?.[n.id]||[],m=v1(e.clipSpans?.[n.id],s),[d,f]=R.useState("moment"),[p,b]=R.useState(Es.default),[g,v]=R.useState(!1),[y,k]=R.useState("handR"),[C,S]=R.useState(null),I=u.find(A=>A.id===C)??null,j=(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},M=A=>o(O=>({...O,shots:O.shots.map(H=>H.id===e.id?{...H,motionEdits:{...H.motionEdits,[n.id]:fd(H.motionEdits?.[n.id],A,H.duration)}}:H)})),T=A=>{o(O=>({...O,shots:O.shots.map(H=>H.id===e.id?{...H,motionEdits:{...H.motionEdits,[n.id]:(H.motionEdits?.[n.id]||[]).filter(D=>D.id!==A)}}:H)})),C===A&&S(null)},w=(A,O)=>{if(I){M({...I,...A});return}const H=Rh();S(H),M({id:H,...j(),label:O,...A})},E=R.useRef({reach:j,write:M,setSelId:S,setPart:k});E.current={reach:j,write:M,setSelId:S,setPart:k},R.useEffect(()=>{if(i){if(!g){i.editTool&&!i.editTool.direct&&i.setEditTool(null);return}i.setEditTool({personId:n.id,part:y,draft:(A,O)=>({id:"__drag",...E.current.reach(O==="hips"&&d==="moment"?"after":d),...A}),commit:(A,O)=>{const H=Rh(),D=E.current;D.setSelId(H),D.write({id:H,...D.reach(O==="hips"&&d==="moment"?"after":d),label:a(_o[O]),...A})},select:A=>E.current.setPart(A)})}},[i,g,n.id,y,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:[a("SỬA CHUYỂN ĐỘNG"),t.jsx("small",{children:a("{0} chỉnh",[u.length])})]}),t.jsxs("p",{className:"shot-hint",children:[m?a("Đang ở khối “{0}” {1}–{2}s",[m.label,hs(m.start),hs(m.end)]):a("Playhead {0}s",[hs(s)])," · ",a("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":a("Phạm vi chỉnh"),children:y1.map(A=>t.jsx("button",{role:"radio","aria-checked":d===A.id,className:d===A.id?"active":"",disabled:A.id==="span"&&!m,title:a(A.hint),onClick:()=>f(A.id),children:a(A.label)},A.id))}),t.jsxs("label",{className:"shot-joint",children:[a("Độ mềm (hoà vào/ra)")," ",t.jsxs("span",{children:[p.toFixed(2),"s"]}),t.jsx("input",{"aria-label":a("Độ mềm (hoà vào/ra)"),type:"range",min:Es.min,max:1.2,step:.05,value:p,onChange:A=>b(+A.target.value)})]}),t.jsx("h4",{children:a("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)}),a("Hiện tay cầm để kéo tay, chân, hông")]}),g&&t.jsx("div",{className:"shot-edit-parts",children:Gp.map(A=>t.jsx("button",{"data-edit-part":A,className:y===A?"active":"",onClick:()=>k(A),children:a(_o[A])},A))}),g&&t.jsx("small",{className:"shot-hint",children:y==="hips"?a("Kéo ngang để dời vị trí, kéo xuống để hạ trọng tâm (chân vẫn bám đất)."):a("Kéo chấm sáng: khớp vai, khuỷu, hông, gối tự xoay theo (IK).")}),t.jsx("h4",{children:a("Dáng đứng mẫu")}),t.jsx("div",{className:"shot-stance-grid",children:qp.map(A=>t.jsx("button",{"data-stance":A.id,className:I?.preset?.id===A.id?"active":"",onClick:()=>w({preset:{id:A.id,amount:I?.preset?.amount??.7}},h?A.nameEn:A.name),children:h?A.nameEn:a(A.name)},A.id))}),I?.preset&&t.jsxs("label",{className:"shot-joint",children:[a("Độ mạnh dáng mẫu")," ",t.jsxs("span",{children:[Math.round(I.preset.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Độ mạnh dáng mẫu"),type:"range",min:0,max:1,step:.05,value:I.preset.amount,onChange:A=>w({preset:{...I.preset,amount:+A.target.value}},"")})]}),t.jsx("h4",{children:a("Chỉnh nhanh")}),Up.map(A=>t.jsxs("label",{className:"shot-joint",children:[h?A.nameEn:a(A.name)," ",t.jsx("span",{children:A.max===1?`${Math.round(N(A.id)*100)}%`:`${N(A.id)}°`}),t.jsx("input",{"aria-label":h?A.nameEn:a(A.name),"data-stance-slider":A.id,type:"range",min:A.min,max:A.max,step:A.step,value:N(A.id),onChange:O=>w({stance:{...I?.stance||{},[A.id]:+O.target.value}},h?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:[a(A)," ",t.jsx("span",{children:(I?.move?.[O]??0).toFixed(2)}),t.jsx("input",{"aria-label":a(A),type:"range",min:-2,max:2,step:.02,value:I?.move?.[O]??0,onChange:H=>{const D=[...I?.move??[0,0,0]];D[O]=+H.target.value,w({move:D},a("Vị trí"))}})]},A)),t.jsxs("label",{className:"shot-joint",children:[a("Xoay hướng")," ",t.jsxs("span",{children:[I?.turn??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay hướng"),type:"range",min:-180,max:180,step:1,value:I?.turn??0,onChange:A=>w({turn:+A.target.value},a("Hướng"))})]})]}),t.jsx("h4",{children:a("Các chỉnh đã có")}),!u.length&&t.jsx("small",{className:"shot-hint",children:a("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=Xp(A),H=O?0:Vp(A,s);return t.jsxs("li",{className:`${A.id===C?"active":""} ${A.off?"off":""} ${O?"broken":""}`,children:[t.jsxs("button",{className:"shot-edit-pick",onClick:()=>{S(A.id===C?null:A.id),r(Number(A.start)||0)},title:O?a("Chỉnh này bị lỗi dữ liệu nên đã được bỏ qua — xoá nó và chỉnh lại"):a("Chọn chỉnh này và tua tới"),children:[t.jsxs("b",{children:[O?"⚠ ":"",A.label||a("Chỉnh")]}),t.jsx("small",{children:A.scope==="span"?`${hs(A.start)}–${hs(A.end)}s`:A.scope==="after"?a("từ {0}s",[hs(A.start)]):`${hs(A.start)}s ±${(Number(A.fade)||0).toFixed(1)}`}),t.jsx("i",{className:"shot-edit-weight",style:{width:`${Math.round(H*100)}%`},"aria-hidden":!0})]}),t.jsx("button",{title:A.off?a("Bật"):a("Tắt (xem bản gốc)"),"aria-pressed":!A.off,onClick:()=>M({...A,off:!A.off}),children:A.off?"○":"●"}),t.jsx("button",{title:a("Xoá chỉnh"),onClick:()=>T(A.id),children:"✕"})]},A.id)})}),I&&t.jsx("button",{className:"shot-edit-new",onClick:()=>S(null),children:a("+ Chỉnh mới tại {0}s",[hs(s)])})]})}const Fh=[{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)"}],k1=[{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)"}],w1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null,M1=(e,n)=>!!(e.objectKeys?.[n]?.length||e.clipSpans?.[n]?.length);function S1({engine:e,stage:n,shot:s,item:o,playhead:i,change:r,onDone:l}){ct();const h=w1(s.clipSpans?.[o.id],i),[u,m]=R.useState(()=>M1(s,o.id)?"moment":"after"),[d,f]=R.useState("free"),[p,b]=R.useState(()=>Math.max(0,+(i-1).toFixed(2))),[g,v]=R.useState(()=>Math.min(s.duration,+(i+1).toFixed(2))),y={start:Math.max(0,Math.min(p,g)),end:Math.min(s.duration,Math.max(p,g))},[k,C]=R.useState(!1),[S,I]=R.useState(0),[j,M]=R.useState([]),[T,w]=R.useState(null),[E,N]=R.useState(null),[A,O]=R.useState(!0),[H,D]=R.useState(!0),$=F=>F==="key"?{scope:"moment",start:i,end:i,fade:Es.default}:F==="range"&&y.end-y.start>.05?{scope:"span",start:y.start,end:y.end,fade:Es.default}:F==="range"?{scope:"moment",start:i,end:i,fade:Es.default}:F==="span"&&h?{scope:"span",start:h.start,end:h.end,fade:Es.default}:{scope:F==="span"?"moment":F,start:i,end:i,fade:Es.default},W=F=>r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:fd(Z.motionEdits?.[o.id],F,Z.duration)}}:Z)})),z=i/Math.max(1e-6,s.duration),Y=(F,te)=>{const Z=s.objectKeys?.[o.id];r(re=>({...re,shots:re.shots.map(me=>me.id===s.id?Jp(me,re.items.find(Pe=>Pe.id===o.id)??o,z,F??{},te):me)})),M(re=>[...re,{kind:"key",prev:Z}])},J=(F,te,Z=u)=>{if(Z==="key"&&!F.stance&&!F.track&&!F.turn&&!F.preset){Y(F.pose,F.move);return}const re=crypto.randomUUID();W({id:re,...$(Z),label:te,...F}),M(me=>[...me,{kind:"edit",id:re}])},V=()=>{const F=j.at(-1);F&&(F.kind==="key"?r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,objectKeys:{...Z.objectKeys,[o.id]:F.prev??[]}}:Z)})):r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:(Z.motionEdits?.[o.id]||[]).filter(re=>re.id!==F.id)}}:Z)})),M(te=>te.slice(0,-1)))},K=Yp(s,o.id,z),[G,_]=R.useState(.5),ee=()=>{const F=s.objectKeys?.[o.id],te=tc(s,n.items.find(Z=>Z.id===o.id)??o,z,G);te&&(r(Z=>({...Z,shots:Z.shots.map(re=>re.id===s.id?te:re)})),M(Z=>[...Z,{kind:"key",prev:F}]))},Q=!!tc(s,o,z,.5),[ve,xe]=R.useState(!1),[q,ue]=R.useState(!1),[pe,U]=R.useState("");R.useEffect(()=>{let F=!0;return fn(()=>import("./api-BFN7blbw.js").then(te=>te.bV),__vite__mapDeps([5,1,4,3])).then(te=>te.shotInbetweenInfo()).then(te=>{F&&xe(te.available)}),()=>{F=!1}},[]);const le=async()=>{if(!q){ue(!0),U("");try{const F=await fn(()=>import("./aiInbetween-AOOM1e6p.js"),__vite__mapDeps([18,1,6,2,3,4,5,7,8,9,10,11,12,13,14,15,16])),te=s.objectKeys?.[o.id],Z=await F.aiInbetween(n,o.id,{at:z},await F.editorInbetweenDeps());r(()=>Z.stage),M(re=>[...re,{kind:"key",prev:te}])}catch(F){U(F.message||a("Không tạo được chuyển động nối"))}finally{ue(!1)}}},[ce,Le]=R.useState(0),je=F=>{if(!e||!T||!T.startsWith("foot")||!F)return;const te=e.rollFootAt(i,o.id,T,F,Z=>({id:"__drag",...$(u),...Z}));te&&J(te.fields,`${a("Cuộn bàn chân")} ${F>0?"+":""}${F}°`),Le(0)},ie=F=>F==="hips"&&u==="moment"?"after":u,Me=R.useRef({reach:$,add:J,scopeOf:ie,setSel:w,writeKey:Y});Me.current={reach:$,add:J,scopeOf:ie,setSel:w,writeKey:Y},R.useEffect(()=>{if(e)return e.setEditTool({personId:o.id,part:null,parts:Qp,direct:!0,mode:d,lockFeet:H,draft:(F,te)=>({id:"__drag",...Me.current.reach(Me.current.scopeOf(te)),...F}),commit:(F,te)=>{const Z=ki(te);Me.current.add(F,Z?na()!=="en"?Z.vi:Z.en:a(_o[te]),Me.current.scopeOf(te))},select:F=>Me.current.setSel(F),hover:F=>N(F)}),()=>{e.editTool?.direct&&e.setEditTool(null)}},[e,o.id,d,H]);const Ee=R.useRef(T);Ee.current=T,R.useEffect(()=>{Ee.current&&e?.selectPosePart(Ee.current)},[e,d]);const Se=F=>{w(F),e?.selectPosePart(F)},he=()=>Me.current.writeKey(),be=R.useRef({pick:Se,sel:T,insertKey:he,breakdown:ee});be.current={pick:Se,sel:T,insertKey:he,breakdown:ee},R.useEffect(()=>{const F=te=>{const Z=te.target;if(te.metaKey||te.ctrlKey||te.altKey||Z&&(Z.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Z.tagName)))return;const re=te.key.toLowerCase(),me=re==="g"?"move":re==="r"?"rotate":re==="f"?"free":null;if(me){te.preventDefault(),te.stopImmediatePropagation(),f(me);return}if((re==="i"||re==="k")&&!te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),be.current.insertKey();return}if(re==="e"&&te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),be.current.breakdown();return}te.key==="Tab"&&(te.preventDefault(),te.stopImmediatePropagation(),be.current.pick(ef(ki(be.current.sel??"")?.id??null,te.shiftKey?-1:1).part))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[]);const Fe=na()!=="en",Te=ki(E??T??"");R.useEffect(()=>{if(e)return e.setFocusLock(o.id),()=>e.setFocusLock(null)},[e,o.id]);const _e=()=>gs(n.items.find(F=>F.id===o.id)??o,s,i/Math.max(1e-6,s.duration),n.items).pose,ze=(F,te)=>{const Z=tf(_e(),F,te);Z&&Object.keys(Z).length&&J({pose:Z},`${a(_o[`hand${F}`])}: ${a(wi[te].name)}`)},Be=T==="handL"||T==="handR"?T.slice(-1):null,Ze=F=>{const te=_e(),Z=Kn[F],re={};for(const[me,Pe]of Object.entries(Z))if(typeof Pe=="number"&&Number.isFinite(Pe)){const ye=Pe-(typeof te[me]=="number"?te[me]:0);Math.abs(ye)>.01&&(re[me]=Math.round(ye*100)/100)}Object.keys(re).length&&J({pose:re},a(F))};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-pose-banner shot-pose-bar",role:"toolbar","aria-label":a("Chỉnh dáng"),children:[t.jsx("span",{className:"shot-pose-who",title:a("Kéo các tay cầm để chỉnh dáng {0}",[o.name]),children:o.name}),t.jsx("span",{className:"shot-pose-control","aria-live":"polite",style:Te?{color:`#${nc[Te.side].toString(16).padStart(6,"0")}`}:void 0,children:Te?`${Fe?Te.vi:Te.en} · ${Te.id}`:a("Chọn một tay cầm")}),t.jsx("button",{className:A?"active":"","aria-expanded":A,"aria-label":a("Bảng điều khiển"),title:a("Bảng điều khiển: bấm tên để chọn tay cầm (Tab: tay cầm kế tiếp)"),onClick:()=>O(F=>!F),children:"🧍"}),t.jsx("select",{"aria-label":a("Phạm vi chỉnh"),title:a(Fh.find(F=>F.id===u)?.hint??""),value:u,onChange:F=>m(F.target.value),children:Fh.map(F=>t.jsx("option",{value:F.id,disabled:F.id==="span"&&!h,children:a(F.label)},F.id))}),u==="range"&&t.jsxs("span",{className:"shot-pose-range",role:"group","aria-label":a("Vùng key"),children:[t.jsx("input",{type:"number","aria-label":a("Vùng key từ (giây)"),title:a("Đặt đầu vùng ở playhead"),min:0,max:s.duration,step:.1,value:p,onChange:F=>b(+F.target.value),onDoubleClick:()=>b(+i.toFixed(2))}),t.jsx("span",{"aria-hidden":!0,children:"–"}),t.jsx("input",{type:"number","aria-label":a("Vùng key đến (giây)"),title:a("Đặt cuối vùng ở playhead"),min:0,max:s.duration,step:.1,value:g,onChange:F=>v(+F.target.value),onDoubleClick:()=>v(+i.toFixed(2))}),"s"]}),t.jsx("div",{className:"shot-seg shot-pose-modes",role:"radiogroup","aria-label":a("Cách chỉnh"),children:k1.map(F=>t.jsx("button",{role:"radio","aria-checked":d===F.id,"aria-label":a(F.label),className:d===F.id?"active":"",title:`${a(F.label)} · ${a(F.hint)}`,onClick:()=>f(F.id),children:F.icon},F.id))}),Be&&t.jsxs("select",{"aria-label":a("Kiểu bàn tay"),value:"",onChange:F=>{F.target.value&&ze(Be,F.target.value)},children:[t.jsx("option",{value:"",children:a("Bàn tay…")}),Object.keys(wi).map(F=>t.jsx("option",{value:F,children:a(wi[F].name)},F))]}),t.jsx("button",{className:H?"active":"","aria-pressed":H,"aria-label":a("Khoá chân"),title:a("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:()=>D(F=>!F),children:"🔒"}),t.jsx("button",{className:K?"active shot-pose-key":"shot-pose-key","aria-label":a("Đặt key"),title:a("Đặt key tư thế tại playhead (I)"),onClick:()=>Y(),children:"◆"}),t.jsx("button",{disabled:!Q,className:"shot-pose-breakdown","aria-label":a("Breakdown"),title:a("Breakdown: key chuyển tiếp giữa key trước và sau ({0}% về key sau) — Shift+E",[Math.round(G*100)]),onClick:ee,onWheel:F=>_(te=>Math.max(0,Math.min(1,+(te+(F.deltaY<0?.1:-.1)).toFixed(1)))),children:"◇"}),ve&&t.jsx("button",{disabled:!Q||q,className:q?"shot-pose-ai busy":"shot-pose-ai","aria-busy":q,"aria-label":a("AI nối tư thế"),title:pe?`${a("Không tạo được chuyển động nối")}: ${pe}`:a("AI nối tư thế: tạo chuyển động tự nhiên (bước chân, dồn trọng tâm, vung tay) giữa key trước và key sau playhead"),onClick:()=>void le(),children:q?"…":"AI ◆→◆"}),T?.startsWith("foot")&&t.jsxs("label",{className:"shot-pose-roll",title:a("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:a("Cuộn")}),t.jsx("input",{type:"range","aria-label":a("Cuộn bàn chân"),min:-40,max:60,step:5,value:ce,onChange:F=>Le(+F.target.value),onPointerUp:()=>je(ce),onKeyUp:F=>{F.key==="Enter"&&je(ce)}}),t.jsxs("b",{children:[ce>0?"+":"",ce,"°"]})]}),t.jsx("button",{className:k?"active":"","aria-expanded":k,"aria-label":a("Thư viện dáng"),title:a("Thư viện dáng"),onClick:()=>C(F=>!F),children:a("Dáng")}),t.jsx("button",{disabled:!j.length,"aria-label":a("Hoàn tác"),title:a("Bỏ lần chỉnh vừa rồi"),onClick:V,children:"↶"}),t.jsx("button",{className:"shot-primary",title:a("Xong (Esc)"),onClick:l,children:a("Xong")})]}),A&&t.jsx("div",{className:"shot-pose-picker",role:"group","aria-label":a("Bảng điều khiển"),children:Zp.map(F=>{const te=`#${nc[F.side].toString(16).padStart(6,"0")}`,Z=T===F.part;return t.jsx("button",{"data-control":F.id,"aria-pressed":Z,className:`shot-pose-pick ${F.shape}${Z?" active":""}`,style:{gridColumn:F.picker[0]+1,gridRow:F.picker[1]+1,borderColor:te,...Z?{background:te}:{}},title:`${Fe?F.vi:F.en} (${F.id})`,onMouseEnter:()=>N(F.part),onMouseLeave:()=>N(null),onClick:()=>Se(F.part),children:Fe?F.vi:F.en},F.id)})}),k&&t.jsxs("div",{className:"shot-pose-library",children:[t.jsx("div",{className:"shot-pose-tabs",role:"tablist",children:zo.map((F,te)=>t.jsx("button",{role:"tab","aria-selected":S===te,className:S===te?"active":"",onClick:()=>I(te),children:a(F.name)},F.name))}),t.jsx("div",{className:"shot-rig-grid",children:zo[S]?.presets.map(F=>t.jsxs("button",{title:a("Áp dáng {0} tại {1}s",[a(F),i.toFixed(1)]),onClick:()=>Ze(F),children:[t.jsx(Jr,{pose:Kn[F]}),t.jsx("span",{children:a(F)})]},F))})]})]})}const Ra=e=>na()==="en"?e.labelEn:e.label,Ph=e=>na()==="en"?of(e):rf(e),$h={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"},Dh=["Di chuyển","Giao tiếp","Tư thế","Võ","Phản ứng trúng đòn","Thể thao","Nhảy múa","Đời thường"],Ui=[...Dh.filter(e=>sc.includes(e)),...sc.filter(e=>!Dh.includes(e))];function Eu(e,n){if(!$r(e))return Cr(e);const s=e.keys(0),o=e.duration?n%e.duration:0;if(o<=s[0].t)return s[0].pose;for(let i=0;i<s.length-1;i++)if(o<=s[i+1].t)return cf(s[i].pose,s[i+1].pose,(o-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 Cr=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},C1=()=>typeof window<"u"&&Number.isFinite(window.__CLIPOOX_THUMB_LIMIT)?Math.max(0,window.__CLIPOOX_THUMB_LIMIT):48,Vo=new Set;let Nr=0;const N1=performance.now();function Iu(e){if(e-Oh>=80){Oh=e;for(const n of Vo)n((e-N1)/1e3)}Nr=Vo.size?requestAnimationFrame(Iu):0}let Oh=0;function Ru(e){return Vo.add(e),Nr||(Nr=requestAnimationFrame(Iu)),()=>{Vo.delete(e)}}function A1({clip:e,animate:n}){const[s,o]=R.useState(()=>Cr(e));return R.useEffect(()=>{if(!n){o(Cr(e));return}let i=!0;e.mocap&&!$r(e)&&Dr(e.id).catch(()=>{});const r=Ru(l=>{i&&o(Eu(e,l))});return()=>{i=!1,r()}},[n,e]),t.jsx(Jr,{pose:s})}function T1({person:e,clip:n}){const s=R.useRef(null),[o,i]=R.useState(!1);return R.useEffect(()=>{const r=s.current;if(!r||!n)return;let l;try{l=new _r({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=Jo,l.toneMapping=ag;const h=new zr,u=new Br(28,(r.clientWidth||220)/(r.clientHeight||280),.1,50);h.add(new wd("#e8eeff","#5e5a52",1.4));const m=new Zo("#fff4e4",2.4);m.position.set(-2.5,3.5,3.5),h.add(m);const d=new ut(new og(.9,40),new fs({color:"#1d242b"}));d.rotation.x=-Math.PI/2,h.add(d),u.position.set(1.9,1.35,4.6),u.lookAt(0,.9,0);let f=null,p=!0,b=null;const g=e?.color??"#8f9aa3",v=e?.kind==="person"?e.figure:void 0,y=e?.kind==="person"?e.look:void 0,k=S=>{if(!p)return;const I=Eu(n,S);if(I!==b){b=I,f&&(h.remove(f),f.traverse(M=>{M instanceof ut&&(M.geometry.dispose(),(Array.isArray(M.material)?M.material:[M.material]).forEach(T=>T.dispose()))})),f=lf(I,g,v,y);const j=new zt().setFromObject(f).getSize(new oe).y||1.8;f.scale.multiplyScalar(1.8/Math.max(1.2,j>2.4?j:1.8)),h.add(f)}l.render(h,u)};n.mocap&&!$r(n)&&(i(!0),Dr(n.id).then(()=>{p&&i(!1)}).catch(()=>p&&i(!1))),k(0);const C=Ru(k);return()=>{p=!1,C(),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":a("Xem trước chuyển động trên nhân vật")}):t.jsx("div",{className:"mocap-preview-empty",children:a("Chọn một chuyển động để xem trước trên nhân vật")}),o&&t.jsx("small",{className:"shot-hint",children:a("Đang tải dữ liệu mocap…")})]})}const Xi=e=>e.meta?.pair;function L1({person:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,onClose:l,playhead:h}){ct();const[u,m]=R.useState(""),[d,f]=R.useState(null),[p,b]=R.useState(null),[g,v]=R.useState(null),[y,k]=R.useState(()=>new Set),C=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=nf(u),A=H=>(!d||H.group===d)&&Bo(H.meta);if(!N)return us.filter(A).sort((H,D)=>Ui.indexOf(H.group)-Ui.indexOf(D.group));const O=new Map(sf(u,{limit:120}).map(H=>[H.id,H.score]));return us.filter(H=>O.has(H.id)&&A(H)).sort((H,D)=>(O.get(D.id)??0)-(O.get(H.id)??0))},[u,d]);R.useEffect(()=>{const N=C.current;if(!N||typeof IntersectionObserver>"u")return;const A=new IntersectionObserver(O=>k(H=>{const D=new Set(H);for(const $ of O){const W=$.target.dataset.clip;$.isIntersecting?D.add(W):D.delete(W)}return D}),{root:N,rootMargin:"80px"});return N.querySelectorAll("[data-clip]").forEach(O=>A.observe(O)),()=>A.disconnect()},[I]);const j=R.useMemo(()=>{const N=C1();return new Set(I.filter(A=>y.has(A.id)).slice(0,N).map(A=>A.id))},[I,y]),M=us.find(N=>N.id===p)??null,T=us.find(N=>N.id===(g??p))??null,w=N=>[N.anchor&&N.anchor.kind!=="floor"?a($h[N.anchor.kind]):"",...N.props.length?[a("Đạo cụ: {0}",[N.props.map(A=>a(La[A.prop].label)).join(", ")])]:[]].filter(Boolean).join(" · "),E=M?.meta?.src?af[M.meta.src.license]:null;return t.jsx("div",{className:"shot-char-overlay mocap-overlay",role:"dialog","aria-modal":"true","aria-label":a("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:[a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:us.filter(N=>Bo(N.meta)).length})]}),t.jsx("span",{className:"shot-char-for",children:e?a("Áp dụng cho: {0}",[e.name]):""}),t.jsx("button",{className:"shot-char-close","aria-label":a("Đó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:a("Tìm chuyển động (đấm móc, ngã, nhảy salsa, cat hanh…)"),"aria-label":a("Tìm chuyển động"),onChange:N=>m(N.target.value)}),t.jsxs("div",{className:"shot-motion-chips mocap-chips",role:"group","aria-label":a("Nhóm chuyển động"),children:[t.jsx("button",{type:"button",className:d?"":"active","aria-pressed":!d,onClick:()=>f(null),children:a("Tất cả")}),Ui.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:Ph(N)},N))]})]}),I.length===0&&t.jsx("small",{className:"shot-hint mocap-empty",children:a('Không có chuyển động khớp "{0}"',[u])}),t.jsx("div",{className:"shot-motion-grid mocap-grid",ref:C,role:"listbox","aria-label":a("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:`${Ra(N)} · ${N.duration.toFixed(1)}s${w(N)?` · ${w(N)}`:""}`,onClick:()=>b(N.id),onDoubleClick:()=>r(N),onPointerEnter:()=>v(N.id),onPointerLeave:()=>v(A=>A===N.id?null:A),children:[t.jsx(A1,{clip:N,animate:j.has(N.id)||g===N.id}),t.jsx("span",{className:"mocap-card-name",children:Ra(N)}),t.jsxs("span",{className:"mocap-card-meta",children:[N.duration.toFixed(1),"s",N.loop?` · ${a("↻ lặp")}`:"",N.mocap?" · mocap":"",Xi(N)?` · ${a("cặp đôi")}`:""]}),N.anchor&&N.anchor.kind!=="floor"||N.props.length?t.jsx("em",{children:[N.anchor&&N.anchor.kind!=="floor"?a($h[N.anchor.kind]):"",N.props.length?"+"+N.props.length:""].filter(Boolean).join(" ")}):null]},N.id))})]}),t.jsxs("aside",{className:"mocap-side",children:[t.jsx(T1,{person:e,clip:T}),M?t.jsxs("div",{className:"mocap-detail",children:[t.jsx("b",{children:Ra(M)}),t.jsxs("small",{children:[Ph(M.group)," · ",M.duration.toFixed(1),"s",M.loop?` · ${a("↻ lặp")}`:""]}),w(M)&&t.jsx("small",{children:w(M)}),Xi(M)&&t.jsx("small",{className:"mocap-pair",children:a("Clip cặp đôi với “{0}”. Áp ở đây chỉ chạy một người; nhờ Agent để đặt cả hai (play_motion partner).",[Ra(us.find(N=>N.id===Xi(M).with)??M)])}),E&&M.meta?.src&&M.meta.src.db!=="Clipoox"&&t.jsx("small",{className:"mocap-source",children:a("Nguồn: {0} (cảnh {1}) · {2}",[E.name,M.meta.src.trial,a("miễn phí, được dùng thương mại")])})]}):t.jsx("small",{className:"shot-hint",children:a("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=>o(N.target.checked)}),a("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)}),a("Đổi tay / chân")]}),t.jsx("button",{type:"button",className:"shot-primary mocap-apply",disabled:!M,onClick:()=>M&&r(M),children:h!=null?a("Áp từ playhead ({0}s)",[h.toFixed(1)]):a("Áp từ playhead")}),t.jsx("small",{className:"shot-hint",children:a("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 E1(e){ct();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:a("Mở thư viện chuyển động: {0} chuyển động, có mocap thật",[us.filter(o=>Bo(o.meta)).length]),children:[t.jsx(Ne.person,{})," ",a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:us.filter(o=>Bo(o.meta)).length})]}),n&&gd.createPortal(t.jsx(L1,{...e,onClose:()=>s(!1),onApply:o=>{s(!1),e.onApply(o)}}),document.querySelector(".shot-workspace")||document.body)]})}function Fu({disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onPlay:r,person:l,playhead:h}){return ct(),t.jsx("div",{className:"shot-motion-lib",children:t.jsx(E1,{disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,person:l,playhead:h})})}const I1=24;function Ar(e,n="joint"){const s=new Set((e?.joints||[]).map(o=>o.name));for(let o=1;;o++){const i=`${n}${o}`.slice(0,I1);if(!s.has(i))return i}}function _h(e,n,s,o){const i=o||Ar(e);if(!e)return Yo({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 Pu(e,r)}function R1(e,n){const s=e.joints.find(r=>r.name===n);if(!s)return e;const o=e.joints.filter(r=>r.name!==n).map(r=>r.parent===n?{...r,parent:s.parent}:r);if(!o.length)return null;const i=e.bones?Object.fromEntries(Object.entries(e.bones).filter(([r])=>r!==n)):void 0;return Pu({...e,...i?{bones:i}:{}},o)}function F1(e,n,s){return Yo({...e,joints:e.joints.map(o=>o.name===n?{...o,pos:s}:o)})}function Pu(e,n){const s=Yo({...e,joints:n});return s.kind!==e.kind?{...s,source:"manual"}:s}class P1{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&&Cc(n),this.engine.orbit.enabled=!0}set(n,s,o){this.itemId=n,this.mode=n?s:"off",this.picked=o}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||(Cc(n),this.mode==="off"))return;const o=this.engine.transform;if(this.mode==="place"&&o.detach(),!s)return;Gg(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"&&o.detach();return}if(this.mode==="edit"){const r=s.bones[i].children.find(l=>l.userData.rigJoint===this.picked);r&&(o.attach(r),o.setMode("translate"),o.setSpace("world"))}else this.mode==="pose"&&(o.attach(s.bones[i]),o.setMode("rotate"),o.setSpace("local"))}commit(n){const s=this.state(),o=this.root(),i=this.itemId;if(!s||!o||!i)return!1;if(n.userData.rigJoint&&this.mode==="edit"){const r=o.worldToLocal(n.getWorldPosition(new oe)).toArray().map(l=>Math.round(l*1e4)/1e4);return this.ev.setRig(i,F1(s.rig,n.userData.rigJoint,r)),!0}return n.userData.rigBone&&this.mode==="pose"&&this.ev.boneKey(i,n.userData.rigBone,qg(s,n.userData.rigBone,this.ev.pose(i))),!0}ray(n){const s=this.engine.renderer.domElement.getBoundingClientRect(),o=new bc;return o.layers.enable(1),o.setFromCamera(new ra((n.clientX-s.left)/s.width*2-1,-(n.clientY-s.top)/s.height*2+1),this.engine.camera),o}jointHit(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];return s.traverse(i=>{i.userData.rigJoint&&o.push(i)}),n.intersectObjects(o,!1)[0]?.object.userData.rigJoint??null}interiorPoint(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];s.traverse(f=>{f instanceof ut&&!f.userData.rigOverlay&&o.push(f)});const i=n.intersectObjects(o,!1);if(!i.length)return null;const r=i[0],l=n.ray.direction.clone(),h=new zt().setFromObject(r.object).getSize(new oe).length()+.1,u=new bc(r.point.clone().addScaledVector(l,h),l.clone().negate(),0,h-1e-4);u.layers.mask=n.layers.mask;const m=u.intersectObjects(o,!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 o=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&&o&&i){const d=this.interiorPoint(this.ray(n));if(d){const f=Ar(i.rig);this.picked=f,this.ev.setRig(o,_h(i.rig,d,s.link,f))}}else r||(this.picked=s.link,this.ev.changed());return}if(r||this.engine.transform.axis||!o)return;const l=this.ray(n),h=this.jointHit(l);if(h){this.picked=h,this.ev.changed();return}if(this.mode!=="place")return;const u=this.interiorPoint(l);if(!u)return;const m=Ar(i?.rig);this.ev.setRig(o,_h(i?.rig,u,this.picked,m)),this.picked=m}}const zh=[["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"]],Bh=[["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 $1(e){ct();const{stage:n,shot:s,selected:o,engine:i,playhead:r}=e,l=n.items.find(_=>_.id===o&&_.kind==="model"&&_.model),h=l?.rig,[u,m]=R.useState("edit"),[d,f]=R.useState(4),[p,b]=R.useState(null),[g,v]=R.useState(!1),[y,k]=R.useState(""),[C,S]=R.useState(()=>{try{return localStorage.getItem("clipoox.rig.fingers")==="1"}catch{return!1}}),I=_=>{S(_);try{localStorage.setItem("clipoox.rig.fingers",_?"1":"0")}catch{}},[,j]=R.useReducer(_=>_+1,0),M=R.useRef(null),T=R.useRef(e);T.current=e;const w=(_,ee)=>T.current.change(Q=>({...Q,items:Q.items.map(ve=>ve.id!==_?ve:ee?{...ve,rig:ee,skeleton:void 0}:(({rig:xe,...q})=>q)(ve)),...ee?{}:{shots:Q.shots.map(ve=>({...ve,objectKeys:Object.fromEntries(Object.entries(ve.objectKeys||{}).map(([xe,q])=>[xe,xe===_?q.map(ue=>(({bones:pe,...U})=>U)(ue)):q]))}))}})),E=(_,ee,Q)=>T.current.change(ve=>{const xe=ve.shots.find(je=>je.id===ve.activeShot),q=ve.items.find(je=>je.id===_),ue=xe.objectKeys?.[_]||[],pe=T.current.playhead,U=xd(ue,pe,q.rig?.bones),le=(je,ie)=>{const Me=ue.find(Se=>Math.abs(Se.time-je)<1e-6),Ee=_n(q,xe,je);return{...Me,id:Me?.id||vt(),time:je,position:Ee.position,rotation:Ee.rotation,scale:Ee.scale,bones:ie}};let ce=[...ue];if(!ue.some(je=>je.bones)&&pe>1e-6){const je=le(0,{...q.rig?.bones||{}});ce=[...ce.filter(ie=>ie.id!==je.id),je]}const Le=le(pe,{...U,[ee]:Q});return ce=[...ce.filter(je=>je.id!==Le.id),Le].sort((je,ie)=>je.time-ie.time),{...ve,shots:ve.shots.map(je=>je.id===ve.activeShot?{...je,objectKeys:{...je.objectKeys,[_]:ce}}:je)}}),N=_=>T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===_&&Q.rig?{...Q,rig:(({bones:ve,...xe})=>xe)(Q.rig)}:Q),shots:ee.shots.map(Q=>Q.id!==ee.activeShot?Q:{...Q,objectKeys:{...Q.objectKeys,[_]:(Q.objectKeys?.[_]||[]).map(ve=>(({bones:xe,...q})=>q)(ve))}})}));R.useEffect(()=>{if(!i)return;const _=new P1(i,{setRig:(ee,Q)=>{w(ee,Q),j()},boneKey:(ee,Q,ve)=>{E(ee,Q,ve),j()},pose:ee=>{const Q=T.current.stage,ve=Q.shots.find(q=>q.id===Q.activeShot),xe=Q.items.find(q=>q.id===ee);return xe?gs(xe,ve,T.current.playhead).pose:null},changed:()=>{j(),T.current.resync()}});return M.current=_,()=>{_.dispose(),M.current=null,T.current.resync()}},[i]),R.useEffect(()=>{const _=M.current;if(!_)return;const ee=_.itemId===l?.id&&_.mode===u&&h?.joints.some(Q=>Q.name===_.picked)?_.picked:null;_.set(l?.id??null,l?u:"off",ee),e.resync()},[i,l?.id,u,!!h]),R.useEffect(()=>Ug(()=>j()),[]),R.useEffect(()=>{let _=!0;return rg().then(ee=>{_&&b(ee)}).catch(()=>{}),()=>{_=!1}},[]),e.keys.current={del:()=>{const _=M.current;if(!_||!l?.rig||!_.picked||u!=="edit"&&u!=="place")return!1;const ee=_.picked;return _.picked=null,w(l.id,R1(l.rig,ee)),j(),!0},esc:()=>{const _=M.current;return _?.picked?(_.picked=null,j(),e.resync(),!0):!1}};const A=()=>{const _=M.current?.root();return _?Qg(_):null},O=_=>{const ee=A();if(!l||!ee||ee.isEmpty()){e.setError(a("Model chưa tải xong."));return}k(""),M.current&&(M.current.picked=null);const Q=M.current?.root(),ve=_==="humanoid"&&Q?Yg(Q):null;let xe=df(_,{min:ee.min.toArray(),max:ee.max.toArray()},{segments:d,...ve?{tips:ve}:{}});_==="humanoid"&&C&&Q&&(xe=Si(xe,{positions:Pi(Q).positions})),w(l.id,xe),m("edit"),j()},H=()=>{const _=A();!l?.rig||!_||(w(l.id,uf(l.rig,(_.min.x+_.max.x)/2)),j())},D=async()=>{const _=M.current?.root();if(!l||!_){e.setError(a("Model chưa tải xong."));return}v(!0),k("");try{const ee=tx(_),Q=await lg({requestId:vt(),front:ee.front,side:ee.side,name:l.name});if(!Q.humanoid||!Q.landmarks||!Q.landmarks.humanoid){k(a("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 ve=mf(Q.landmarks,ee.frame);C&&(ve=Si(ve,{positions:Pi(_).positions,tips:pf(Q.landmarks,ee.frame)})),M.current&&(M.current.picked=null),w(l.id,ve),m("edit"),j(),dt.getState().toast(a("Đã gắn xương tự động · {0} credits",[Q.credits]),"ok"),Q.landmarks.facing==="away"&&k(a("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){k(ee.message||a("Gắn xương AI gặp lỗi."))}finally{v(!1)}},$=()=>{const _=M.current?.root();!l?.rig||!_||(M.current&&(M.current.picked=null),w(l.id,Mi(l.rig)?ff(l.rig):Si(l.rig,{positions:Pi(_).positions})),j())},W=_=>{const ee=nr.find(ve=>ve.id===_);if(!l||!ee)return;let Q=l.pose||{};for(const ve of["L","R"])Q=bd(Q,ve,ee);e.patchItem(l.id,{pose:Q})},z=M.current?.state(),Y=M.current?.picked??null,J=hf(h),V=n.items.filter(_=>_.kind==="model"&&_.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:a("Chọn một model GLB để gắn xương.")}),V.length?t.jsx("div",{className:"shot-rig-models",children:V.map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}):t.jsx("small",{className:"shot-hint",children:a("Thêm model ở tab Dựng cảnh (Nhập GLB / Thư viện 3D), rồi quay lại đây.")})]})});const K=(s.objectKeys?.[l.id]||[]).filter(_=>_.bones),G=l.model?Xg(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":a("Model khác"),children:V.filter(_=>_.id!==l.id).map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}),t.jsxs("div",{className:"shot-rig-target",children:[t.jsx("b",{children:l.name}),t.jsx("small",{children:h?a("{0} khớp · {1}",[h.joints.length,J?a("xương người"):a(zh.find(_=>_[0]===h.kind)?.[1]??"Gắn tay")]):a("Chưa có xương")})]}),(()=>{const _=i?.nativeSkeleton(l.id);return!_?.ok&&l.skeleton!=="native"?null:t.jsxs("div",{className:"shot-rig-native",children:[t.jsx("h3",{children:a("XƯƠNG TRONG FILE")}),l.skeleton==="native"?t.jsxs(t.Fragment,{children:[t.jsx("small",{className:"shot-hint",children:a("Đang dùng xương gốc của file ({0} xương) — chuyển động như trong Blender.",[_?.bones??"…"])}),t.jsx("button",{type:"button",onClick:()=>{T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,skeleton:void 0}:Q)})),j()},children:a("Bỏ xương gốc")})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>{M.current&&(M.current.picked=null),T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,rig:void 0,skeleton:"native"}:Q)})),j()},children:a("Dùng xương có sẵn trong file")}),t.jsx("small",{className:"shot-hint",children:a("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í.",[_?.bones??0])})]})]})})(),t.jsx("h3",{children:a("TỰ ĐỘNG")}),t.jsx("button",{type:"button",className:"shot-primary shot-rig-auto",disabled:g||e.busy||p?.configured===!1,onClick:()=>void D(),title:a("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?a("Đang gắn xương…"):a("✦ Tự gắn xương · ≈{0} credits",[p?p.estimate.toFixed(2):"…"])}),t.jsx("small",{className:"shot-hint shot-rig-price",children:p?a("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)]):a("Cho nhân vật hình người (2 tay, 2 chân).")}),y&&t.jsx("div",{className:"shot-rig-note",role:"status",children:y}),t.jsx("h3",{children:a("MẪU CÓ SẴN · MIỄN PHÍ")}),t.jsx("div",{className:"shot-rig-templates",children:zh.map(([_,ee,Q])=>t.jsx("button",{type:"button","data-template":_,title:a(Q),onClick:()=>O(_),children:a(ee)},_))}),t.jsxs("label",{className:"shot-rig-check",children:[t.jsx("input",{type:"checkbox",checked:C,onChange:_=>I(_.target.checked)})," ",a("Thêm xương ngón tay (mẫu Người / AI)")]}),t.jsxs("label",{className:"shot-field shot-rig-segments",children:[a("Số đốt (đuôi / chuỗi)"),t.jsx("input",{"aria-label":a("Số đốt (đuôi / chuỗi)"),type:"number",min:ao.chainMin,max:ao.chainMax,value:d,onChange:_=>f(Math.max(ao.chainMin,Math.min(ao.chainMax,Math.round(+_.target.value)||4)))})]}),t.jsx("h3",{children:a("GẮN TAY")}),t.jsx("div",{className:"shot-rig-modes",role:"group","aria-label":a("Công cụ xương"),children:Bh.map(([_,ee,Q])=>t.jsx("button",{type:"button",className:u===_?"active":"","aria-pressed":u===_,title:a(Q),onClick:()=>m(_),children:a(ee)},_))}),t.jsx("small",{className:"shot-hint",children:a(Bh.find(_=>_[0]===u)[2])}),Y&&t.jsx("div",{className:"shot-rig-picked",children:a("Khớp: {0}",[Y])}),t.jsxs("div",{className:"shot-rig-actions",children:[t.jsx("button",{type:"button",disabled:!h,onClick:H,title:a("Chép nửa trái (−X) sang phải qua tâm model, tự đặt tên .L / .R"),children:a("⇆ Đối xứng L/R")}),t.jsx("button",{type:"button",disabled:!h||!Y||u==="pose",onClick:()=>e.keys.current?.del(),children:a("Xoá khớp")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{l.model&&Vg(l.model.gcsUri),e.resync(),j()},children:a("Tính lại trọng số")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{M.current&&(M.current.picked=null),w(l.id,null),j()},children:a("Bỏ xương")})]}),G?t.jsxs("div",{className:"shot-rig-progress",role:"status",children:[t.jsx("span",{children:G.done?a("Đã tính xong trọng số chạy nền · {0} đỉnh",[G.vertices.toLocaleString()]):a("Đang tính trọng số chạy nền… {0}% · {1} đỉnh",[Math.round(G.progress*100),G.vertices.toLocaleString()])}),t.jsx("progress",{max:100,value:Math.round(G.progress*100),"aria-label":a("Tiến độ tính trọng số")}),!G.done&&t.jsx("small",{className:"shot-hint",children:a("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:a("{0} đỉnh · trọng số {1} ms{2}",[z.info.vertices.toLocaleString(),z.info.ms,(z.info.via==="worker"?a(" · chạy nền"):"")+(z.info.source==="disk"?a(" (đã lưu trên máy)"):z.info.cached?a(" (bộ nhớ đệm)"):"")])}),J&&h&&t.jsxs("div",{className:"shot-rig-fingers",children:[t.jsx("span",{children:Mi(h)?a("Ngón tay: 5 ngón × 3 đốt mỗi tay"):a("Chưa có xương ngón tay")}),t.jsx("button",{type:"button",onClick:$,children:Mi(h)?a("Bỏ ngón tay"):a("Thêm ngón tay")})]}),h&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("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:a("Xoay xương tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsx("button",{type:"button",disabled:!K.length&&!h.bones,onClick:()=>N(l.id),children:a("Đặt lại dáng xương")})]}),t.jsx("small",{className:"shot-hint",children:K.length?a("{0} key xương trên timeline.",[K.length]):a("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:a("◇ Key tư thế tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsxs("div",{className:"shot-rig-hands",role:"group","aria-label":a("Dáng tay"),children:[t.jsx("span",{children:a("Dáng tay")}),nr.map(_=>t.jsx("button",{type:"button","data-hand":_.id,onClick:()=>W(_.id),children:a(_.label)},_.id))]}),t.jsx("div",{className:"shot-rig-presets",children:zo[0].presets.map(_=>t.jsx("button",{type:"button",onClick:()=>e.patchItem(l.id,{pose:{...Kn[_]}}),children:a(_)},_))}),t.jsx(Fu,{disabled:e.busy,loop:e.motionLoop,mirror:e.motionMirror,onLoop:e.onMotionLoop,onMirror:e.onMotionMirror,onPlay:_=>e.onPlayClip(l.id,_),person:l,playhead:r*s.duration})]}):t.jsx("small",{className:"shot-hint",children:a("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},O1=()=>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"})]});ss.rig={apply(e,n,s){n.rig&&n.model&&ex(e,n.rig,n.model.gcsUri,s?(o,i)=>s.trackRigJob(o,i):void 0)},pose(e,n,s,o,i,r){const l=e.userData.rig;l&&n.rig&&Jg(l,i,xd(s.objectKeys?.[n.id],o,n.rig.bones),r)},gaze(e,n,s){const o=e.userData.rig;o&&o.rig.kind==="humanoid"&&Zg(o,s)}};ss.generate=e=>e.gen?.kind==="character"?Od(e.gen.spec).root:null;function _1({shot:e,engine:n,onClose:s,onBusy:o,onReady:i,timelineTarget:r,vfx:l}){ct();const[h,u]=R.useState(0),[m,d]=R.useState(e.duration),[f,p]=R.useState(720),[b,g]=R.useState(gn(e)),[v,y]=R.useState(!1),[k,C]=R.useState(0),[S,I]=R.useState(""),[j,M]=R.useState("film"),T=R.useRef(null);R.useEffect(()=>()=>T.current?.abort(),[]);const w=Number.isFinite(h)&&Number.isFinite(m)&&h>=0&&m>h&&m<=e.duration,E=async()=>{if(!n||!l)return;const A=new AbortController;T.current=A,y(!0),o(!0),C(0),I("");try{await l.run({height:f,fps:b,motionBlur:ua[j].samples,shutter:ua[j].shutter},C,A.signal),s()}catch(O){I(A.signal.aborted?"Đã huỷ xuất video.":O.message)}finally{T.current=null,y(!1),o(!1)}},N=async A=>{if(!n||!w)return;const O=new AbortController;T.current=O,y(!0),o(!0),C(0),I("");let H;try{const D={motionBlur:ua[j].samples,shutter:ua[j].shutter};if(H=await n.exportVideo({start:h,end:m,height:f,fps:b,...D,signal:O.signal,progress:C}),A==="download"){const $=URL.createObjectURL(H.blob),W=document.createElement("a");W.href=$,W.download=`${e.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-${h}-${m}.mp4`,W.click();const z=H.cleanup;setTimeout(()=>{URL.revokeObjectURL($),z()},6e4),H=void 0}else await i(H.blob,{start:h,end:m,height:f,fps:b,...D},A);s()}catch(D){I(O.signal.aborted?"Đã huỷ xuất video.":D.message)}finally{await H?.cleanup(),T.current=null,y(!1),o(!1)}};return t.jsx("div",{className:"shot-video-overlay",children:t.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":a("Xuất video camera"),className:"shot-video-dialog",children:[t.jsx("h2",{children:a("Xuất video camera · MP4")}),t.jsx("p",{children:a("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:[a("Từ giây"),t.jsx("input",{"aria-label":a("Video từ giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(h)?h:"",onChange:A=>u(A.target.valueAsNumber)})]}),t.jsxs("label",{children:[a("Đến giây"),t.jsx("input",{"aria-label":a("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:[a("Chất lượng"),t.jsxs("select",{"aria-label":a("Độ phân giải video"),value:f,onChange:A=>p(+A.target.value),children:[t.jsx("option",{value:720,children:a("720p · Nhẹ")}),t.jsx("option",{value:1080,children:a("1080p · Chi tiết")})]})]}),t.jsxs("label",{children:[a("Khung hình/giây"),t.jsx("select",{"aria-label":a("FPS video"),value:b,onChange:A=>g(+A.target.value),children:yd.map(A=>t.jsx("option",{value:A,children:a("{0} fps",[A])},A))})]}),t.jsxs("label",{title:a("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:[a("Nhoè chuyển động"),t.jsxs("select",{"aria-label":a("Nhoè chuyển động"),value:j,onChange:A=>M(A.target.value),children:[t.jsx("option",{value:"off",children:a("Tắt · xuất nhanh")}),t.jsx("option",{value:"film",children:a("Điện ảnh · màn trập 180°")}),t.jsx("option",{value:"strong",children:a("Mạnh · hành động nhanh")})]})]})]}),t.jsxs("p",{children:[w?a("{0} giây · {1} · khoảng {2} MB",[(m-h).toFixed(1),e.aspect,Math.ceil((m-h)*(f===1080?6:3)/8)]):a("Chọn khoảng thời gian hợp lệ trong shot."),w&&j!=="off"?" · "+a("xuất lâu hơn khoảng {0} lần",[ua[j].samples]):""]}),v&&t.jsxs(t.Fragment,{children:[t.jsx("progress",{max:100,value:k}),t.jsx("p",{children:k<100?a("Đang xuất từng frame… {0}%",[k]):a("Đang hoàn tất / lưu video…")}),t.jsx("button",{disabled:k===100,onClick:()=>T.current?.abort(),children:a("Huỷ xuất")})]}),S&&t.jsx("p",{role:"alert",children:a(S)}),!v&&l&&t.jsxs("div",{className:"shot-video-vfx",children:[t.jsx("p",{children:l.layers?a("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}”`:a("gốc")]):a("Cảnh chưa có hiệu ứng nào để xuất.")}),t.jsx("button",{className:"shot-primary",disabled:!l.layers,onClick:()=>void E(),children:a("✦ Xuất lớp hiệu ứng về Timeline")})]}),!v&&t.jsxs("div",{className:"shot-video-actions",children:[t.jsx("button",{onClick:s,children:a("Đóng")}),t.jsx("button",{disabled:!w,onClick:()=>void N("download"),children:a("Tải MP4")}),t.jsx("button",{disabled:!w,className:r||l?void 0:"shot-primary",onClick:()=>void N("canvas"),children:a("Đưa video vào Canvas")}),r&&t.jsx("button",{disabled:!w,className:"shot-primary",title:r,onClick:()=>void N("timeline"),children:a("Đưa về Timeline")})]}),t.jsx("small",{children:a("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 z1=(e,n)=>`${e} · VFX ${n==="behind"?a("sau người"):a("trước người")}`;async function B1(e,n,s,o,i={}){const r=n.shots.find(p=>p.id===n.activeShot),l=e.vfxLayers();if(!n.plate)throw new Error(a("Cảnh này không có video nền (mở từ một clip trên Timeline)."));if(!l.length)throw new Error(a("Cảnh chưa có hiệu ứng nào để xuất."));const h=dt.getState().canvasId,u=[],m=o.vfxAlpha??"auto",{vfxAlpha:d,...f}=o;for(const[p,b]of l.entries()){const g=m==="on"||m==="auto"&&await e.vfxOccludes(b),{blob:v,cleanup:y}=await e.exportVideo({...f,start:0,end:r.duration,vfx:b,alpha:g,signal:i.signal??new AbortController().signal,progress:k=>i.progress?.(Math.round((p*100+k)/l.length))});try{const k=z1(r.name,b),C=g?"webm":"mp4",{url:S,gcsUri:I}=await Us(new File([v],`${r.name}-vfx-${b}.${C}`,{type:`video/${C}`}),void 0,"video"),j=_t()?.getNode(s);if(!j||dt.getState().canvasId!==h)throw new Error(a("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi."));const M=_t()?.addNode("video",{url:S,gcsUri:I,label:k,duration:r.duration,ratio:r.aspect,status:"succeeded",shotSourceId:s,shotId:r.id,vfxLayer:b},{x:j.position.x+380,y:j.position.y+p*260},{sourceIds:[s]});if(!M)throw new Error(a("Không tạo được video trên Canvas"));const{width:T,height:w}=gf(r.aspect,{short:o.height});u.push({layer:b,nodeId:M,url:S,gcsUri:I,duration:r.duration,label:k,...g?{alpha:!0,fps:o.fps,width:T,height:w}:{}})}finally{await y()}}return u}const K1=(e,n)=>[...e].sort((s,o)=>(s.layer==="behind"?0:1)-(o.layer==="behind"?0:1)).map(s=>({op:"addVfxLayer",materialId:s.nodeId,clipId:n,layer:s.layer}));function H1(e,n){const s=dt.getState(),o=n?s.clips.find(l=>l.id===n):void 0;if(!o||o.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=nx(s.clips,K1(e,o.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(h=>!l.some(u=>u.source==="canvas"&&u.id===h.nodeId)).map(h=>({id:h.nodeId,source:"canvas",kind:"video",url:h.url,gcsUri:h.gcsUri,label:h.label,duration:h.duration}))]),{passes:e,placed:!0,clipId:o.id,pendingMatte:!!r.mattes?.length}}function W1({stage:e,selected:n,time:s,disabled:o,onApply:i,getBounds:r,getColliders:l,onPreview:h,embedded:u=!1}){ct();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([]),[b,g]=R.useState(""),[v,y]=R.useState(!1),[k,C]=R.useState(""),[S,I]=R.useState(null),[j,M]=R.useState(null),[T,w]=R.useState(null),[E,N]=R.useState(!1),[A,O]=R.useState(null),H=R.useRef(null),D=[...f,{role:"user",content:b.trim()}].slice(-12),$=JSON.stringify({scene:Lc(e,n,s,r(),l?.()),messages:D,model:m});R.useEffect(()=>{if(w(null),!b.trim()||v)return;let G=!1;N(!0);const _=setTimeout(()=>{const ee=JSON.parse($);cg(ee.scene,ee.messages,ee.model).then(Q=>{G||w({signature:$,credits:Q.reservedCredits})}).catch(Q=>{G||C(Q.message)}).finally(()=>{G||N(!1)})},400);return()=>{G=!0,clearTimeout(_)}},[$,b,v]);const W=R.useRef(null),z=R.useRef(!0),Y=R.useRef(!1);R.useEffect(()=>(z.current=!0,hg().then(G=>{z.current&&I(G)}).catch(()=>{}),()=>{z.current=!1}),[]),R.useEffect(()=>{W.current&&(W.current.scrollTop=W.current.scrollHeight)},[f,v,j]);const J=j&&(j.revision!==e.revision||j.shotId!==e.activeShot),V=async(G=!1)=>{if(Y.current||o||!G&&(!b.trim()||T?.signature!==$))return;const _=G?H.current:{scene:Lc(e,n,s,r(),l?.()),messages:D,id:crypto.randomUUID(),revision:e.revision,shotId:e.activeShot,model:m};if(_){H.current=_,Y.current=!0,y(!0),C(""),M(null),p(_.messages),g("");try{const{plan:ee,model:Q,billing:ve}=await dg(_.scene,_.messages,_.id,_.model);if(!z.current)return;H.current=null,O(ve.credits),I({available:!0,model:Q}),p([..._.messages,{role:"assistant",content:ee.message}]),ee.tracks.length&&M({plan:ee,revision:_.revision,shotId:_.shotId})}catch(ee){z.current&&C(ee.message)}finally{Y.current=!1,z.current&&y(!1)}}},K=u?"div":"section";return t.jsxs(K,{className:u?"shot-agent-embedded":"shot-agent","aria-label":a("AI Agent 3D"),children:[t.jsxs("select",{"aria-label":a("Model AI"),value:m,disabled:v,onChange:G=>{d(G.target.value),H.current=null,C("");try{localStorage.setItem("clipoox.shot.keyModel",G.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:a("Đề xuất key cho đối tượng đang chọn hoặc camera")}):t.jsxs(t.Fragment,{children:[t.jsx("b",{children:a("✦ AI Agent")}),t.jsx("small",{children:S?.model||"GPT 5.6 sol"})]}),t.jsx("button",{title:a("Xóa hội thoại"),disabled:v,onClick:()=>{p([]),M(null),C(""),H.current=null},children:"↺"})]}),t.jsxs("div",{className:"shot-agent-chat",ref:W,role:"log","aria-label":a("Hội thoại AI"),children:[!f.length&&t.jsx("p",{className:"shot-agent-intro",children:a("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((G,_)=>t.jsx("div",{className:`shot-agent-message ${G.role}`,children:G.content},_)),v&&t.jsx("p",{role:"status",children:a("Đang tạo đề xuất key…")}),k&&t.jsxs("p",{role:"alert",children:[k,H.current&&t.jsx("button",{disabled:v,onClick:()=>void V(!0),children:a("Thử lại")})]}),j&&t.jsxs("div",{className:"shot-agent-proposal",children:[t.jsxs("small",{children:[j.plan.tracks.length," ",a("track ·")," ",j.plan.tracks.reduce((G,_)=>G+_.keys.length,0)," ",a("key ·")," ",j.plan.duration,a("s")]}),J?t.jsx("p",{children:a("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:j.plan.tracks.map(G=>t.jsxs("li",{children:[G.subjectId==="camera"?"Camera":e.items.find(_=>_.id===G.subjectId)?.name,": ",G.replaceRange?a("Sửa đoạn {0}–{1}s",[G.replaceRange.start.toFixed(2),G.replaceRange.end.toFixed(2)]):a("Thêm/cập nhật {0}–{1}s",[G.keys[0].seconds.toFixed(2),G.keys.at(-1).seconds.toFixed(2)])]},G.subjectId))}),t.jsx("button",{disabled:o,onClick:()=>h(j.plan,G=>{G&&(M(null),p(_=>[..._,{role:"assistant",content:a("Đã giữ thay đổi sau khi xem thử. Có thể hoàn tác bằng Ctrl/Cmd + Z.")}]))}),children:a("Xem thử chuyển động")}),t.jsx("button",{className:"shot-primary",disabled:o,onClick:()=>{try{i(j.plan),M(null),p(G=>[...G,{role:"assistant",content:a("Đã áp dụng key. Bấm Play để xem; Ctrl/Cmd + Z để hoàn tác.")}])}catch(G){C(G.message)}},children:a("Áp dụng key")})]})]})]}),t.jsxs("form",{onSubmit:G=>{G.preventDefault(),V()},children:[t.jsx("textarea",{"aria-label":a("Mô tả key cho AI"),maxLength:4e3,rows:3,value:b,placeholder:a("Ví dụ: xe đi tới 3 mét trong 5 giây…"),onChange:G=>g(G.target.value)}),t.jsx("small",{children:T?.signature===$?a("Tạm giữ tối đa {0} credit; hoàn phần dư theo token thực tế.",[T.credits.toFixed(2)]):E&&b.trim()?a("Đang tính phí…"):a("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||o||!b.trim()||T?.signature!==$||S?.available===!1,children:a("Tạo key")})]}),A!==null&&t.jsx("small",{children:a("Phí: {0} credit.",[A.toFixed(2)])}),S?.available===!1&&t.jsx("small",{children:a("Admin cần cấu hình API key để bật Agent.")})]})}const Kh=[["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)"]],G1={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"]},Hh=(e,n)=>{try{return localStorage.getItem(e)||n}catch{return n}},Vi=(e,n)=>{try{localStorage.setItem(e,n)}catch{}},Ln=e=>String(Math.round(e*100)/100);function q1({stage:e,disabled:n,agent:s,lock:o}){ct();const i=td(),[r,l]=R.useState(()=>{const ie=Hh("clipoox.shot.missionMode","mission");return ie==="keys"||ie==="set"?ie:"mission"}),h=ie=>[ie==="set"?"clipoox.shot.setModel2":"clipoox.shot.missionModel2","gpt-6.1-sol"],u=ie=>{const[Me,Ee]=h(ie),Se=Hh(Me,Ee);return Kh.some(([he])=>he===Se)?Se:Ee},[m,d]=R.useState(()=>u(r)),[f,p]=R.useState(!1),b=ie=>{p(ie),Vi("clipoox.shot.hq","")},g=f?Ea:m,[v,y]=R.useState(""),[k,C]=R.useState(null),[S,I]=R.useState(""),j=R.useRef(null),M=R.useRef(null),T=xf(e),w=bf(T),[E,N]=R.useState(null),[A,O]=R.useState(!1),[H,D]=R.useState(null),$=R.useRef(null);R.useEffect(()=>{if(!H)return;const ie=Ee=>{$.current?.contains(Ee.target)||D(null)},Me=Ee=>{Ee.key==="Escape"&&(Ee.stopPropagation(),D(null))};return window.addEventListener("pointerdown",ie),window.addEventListener("keydown",Me,!0),()=>{window.removeEventListener("pointerdown",ie),window.removeEventListener("keydown",Me,!0)}},[H]);const[W,z]=R.useState(""),[Y,J]=R.useState(""),[V,K]=R.useState(null),G=["thinking","acting","rendering"].includes(i.phase);R.useEffect(()=>{j.current&&(j.current.scrollTop=j.current.scrollHeight)},[i.log.length]);const _=ie=>{l(ie),Vi("clipoox.shot.missionMode",ie),d(u(ie))},ee=ie=>{d(ie),Vi(h(r)[0],ie)},Q=async ie=>{if(I(""),!ie){C(null);return}if(ie.size>28e4||!["image/jpeg","image/png"].includes(ie.type)){I(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const Me=await new Promise((Ee,Se)=>{const he=new FileReader;he.onload=()=>Ee(String(he.result)),he.onerror=()=>Se(he.error),he.readAsDataURL(ie)});C({name:ie.name,data:Me})},ve=(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===g&&i.quality==="high"===f,xe=A?yf({from:Number(W),to:Number(Y)},T.duration):null,q=(ie=!1)=>{const Me=v.trim();if(!Me||G||n)return;y("");const Ee={window:xe,continueFrom:V,quality:f?"high":null};K(null),ie&&ve?i.followUp(Me,Ee):i.start(Me,k?.data||null,g,r==="set"?"set":"shot",Ee)},ue=ie=>{N(null),o&&Math.abs(ie-w)>1e-6&&o.onChange(Math.max(0,Math.min(T.duration,ie)))},pe=(ie,Me=null)=>{y(ie),K(Me),requestAnimationFrame(()=>{const Ee=M.current;Ee&&(Ee.focus(),Ee.setSelectionRange(ie.length,ie.length))})},U=ie=>a("Giữ nguyên 0–{0}s, kéo dài shot thêm 5s, từ {0}s đến {1}s: ",[Ln(ie),Ln(ie+5)]),le=()=>{A||(z(Ln(w)),J(Ln(T.duration))),O(!A)},ce=(navigator.language||"").startsWith("vi"),Le={thinking:a("Đang nghĩ…"),acting:a("Đang dựng trong composer…"),rendering:a("Đang render & đưa vào canvas…"),done:a("Xong"),error:a("Lỗi"),cancelled:a("Đã dừng"),capped:a("Đã dùng hết {0} credit của lượt này",[Ka]),idle:""}[i.phase],je=t.jsxs("label",{className:`shot-lock-chip shot-hq-chip${f?" on":""}`,children:[t.jsx("input",{type:"checkbox","aria-label":a("Model chất lượng cao · Opus"),checked:f,disabled:G,onChange:ie=>b(ie.target.checked)}),t.jsxs("span",{"aria-hidden":"true",children:["✦ ",a("Chất lượng cao")]})]});return t.jsxs("section",{className:"shot-agent shot-mission","aria-label":a("Mission Agent"),children:[t.jsxs("div",{className:"shot-agent-heading",children:[t.jsx("b",{children:a("✦ Mission")}),r!=="keys"&&t.jsx("select",{className:"shot-mission-model","aria-label":a("Model AI"),value:g,disabled:G||f,onChange:ie=>ee(ie.target.value),title:a("GPT 6 Astra suy luận tốt hơn, giá token cao hơn (tính theo dùng thật)"),children:Kh.map(([ie,Me])=>t.jsx("option",{value:ie,children:a(Me)},ie))}),r!=="keys"&&i.missionId&&!G&&t.jsx("button",{title:a("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:G,onClick:()=>_("mission"),children:a("Dựng shot")}),t.jsx("button",{role:"tab","aria-selected":r==="set",className:r==="set"?"active":"",disabled:G,onClick:()=>_("set"),children:a("Dựng bối cảnh")}),t.jsx("button",{role:"tab","aria-selected":r==="keys",className:r==="keys"?"active":"",disabled:G,onClick:()=>_("keys"),children:a("Key đối tượng")})]}),r==="keys"?t.jsx(W1,{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"?a("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."):a("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":a("Gợi ý"),children:G1[r==="set"?"set":"mission"].map(ie=>t.jsx("button",{type:"button",disabled:G||n,onClick:()=>y(a(ie)),children:a(ie)},ie))})]}),i.log.length>0&&t.jsxs("div",{className:"shot-agent-chat shot-mission-log",ref:j,role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[i.quality==="high"&&t.jsx("b",{className:"shot-hq-badge",children:a("Chất lượng cao · Opus")}),Le," · ",a("bước")," ",i.step,"/",i.maxSteps," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-12).map((ie,Me)=>t.jsx("div",{className:"shot-mission-line",children:ie},Me)),i.sheet&&t.jsx("img",{className:"shot-mission-sheet",src:i.sheet,alt:a("Contact sheet 6 khung hình")}),i.phase==="done"&&t.jsx("div",{className:"shot-mission-facts",children:vf(e,i.facts,ce)}),i.phase==="done"&&i.purpose==="set"&&i.ready&&t.jsx("div",{className:"shot-mission-done",children:a('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:a('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:a('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).',[Ka])}),i.error&&t.jsx("p",{role:"alert",children:i.error})]})]}),r==="set"&&t.jsx("div",{className:"shot-mission-lock",children:je}),r==="mission"&&t.jsxs("div",{ref:$,className:`shot-mission-lock${w>0?" on":""}`,role:"group","aria-label":a("Khoá đoạn đã ưng"),children:[o&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:`shot-lock-chip${w>0?" on":""}`,"aria-expanded":H==="lock",title:w>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[Ln(w)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên."),onClick:()=>D(H==="lock"?null:"lock"),children:["🔒 ",w>0?`0–${Ln(w)}s`:a("Khoá")]}),t.jsxs("button",{type:"button",className:`shot-lock-chip${A?xe?" on":" bad":""}`,"aria-expanded":H==="window",onClick:()=>D(H==="window"?null:"window"),children:["✂ ",A&&xe?`${Ln(xe.from)}–${Ln(xe.to)}s`:a("Chỉ sửa đoạn")]})]}),je,H==="lock"&&o&&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:[a("Khoá")," 0–"]}),t.jsx("input",{"aria-label":a("Khoá đến (giây)"),inputMode:"decimal",value:E??Ln(w),disabled:G,onFocus:ie=>ie.target.select(),onChange:ie=>N(ie.target.value),onBlur:()=>{if(E!=null){const ie=Number(E.replace(",","."));Number.isFinite(ie)?ue(ie):N(null)}},onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),ie.target.blur()),ie.key==="Escape"&&(N(null),ie.target.blur())}}),t.jsx("span",{children:"s"}),t.jsx("button",{type:"button",disabled:G||o.playhead<=0,title:a("Agent sẽ không sửa gì trước vị trí playhead; bạn vẫn sửa tay được."),onClick:()=>ue(o.playhead),children:a("Khoá tới playhead")}),w>0&&t.jsx("button",{type:"button",disabled:G,onClick:()=>ue(0),children:a("Mở khoá")})]}),t.jsx("small",{children:w>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[Ln(w)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên.")})]}),H==="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:G,onChange:le}),t.jsx("span",{children:a("Chỉ sửa đoạn")}),A&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Sửa từ (giây)"),inputMode:"decimal",value:W,disabled:G,onChange:ie=>z(ie.target.value.replace(",","."))}),t.jsx("span",{children:"–"}),t.jsx("input",{"aria-label":a("Sửa đến (giây)"),inputMode:"decimal",value:Y,disabled:G,onChange:ie=>J(ie.target.value.replace(",","."))}),t.jsx("span",{children:"s"})]})]}),A&&!xe&&t.jsx("small",{role:"alert",children:a("Đ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:a("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:ie=>{ie.preventDefault(),q(!1)},children:[t.jsx("textarea",{ref:M,"aria-label":a("Mô tả shot cho Agent"),maxLength:4e3,rows:3,value:v,disabled:G||n,placeholder:ve?a("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"?a("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"):a("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:ie=>{y(ie.target.value),ie.target.value.trim()||K(null)}}),ve&&r==="mission"&&t.jsxs("div",{className:"shot-mission-chips","aria-label":a("Làm tiếp"),children:[t.jsx("button",{type:"button",disabled:n,onClick:()=>pe(a("Sửa đoạn đã làm: ")),children:a("Sửa đoạn đã làm")}),t.jsx("button",{type:"button",disabled:n,onClick:()=>pe(U(T.duration),T.duration),children:a("Làm tiếp thêm 5s")}),o&&t.jsx("button",{type:"button",disabled:n,title:a("Khoá 0–{0}s rồi viết phần tiếp theo",[Ln(T.duration)]),onClick:()=>{ue(T.duration),pe(U(T.duration),T.duration)},children:a("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:G,onChange:ie=>{Q(ie.target.files?.[0]),ie.target.value=""}}),t.jsx("span",{children:k?`🖼 ${k.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),k&&!G&&t.jsx("button",{type:"button",onClick:()=>C(null),children:"×"}),G?t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>i.stop(),children:a("Dừng")}):t.jsxs(t.Fragment,{children:[ve&&t.jsx("button",{type:"button",className:"shot-continue",disabled:n||!v.trim(),title:a("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:()=>q(!0),children:a("↪ Sửa / làm tiếp phiên này")}),t.jsx("button",{className:"shot-primary",disabled:n||!v.trim(),title:a("Yêu cầu mới: Agent không dùng lịch sử phiên trước"),children:a("Chạy Agent (mới)")})]})]}),S&&t.jsx("small",{role:"alert",children:S})]})]})]})}const U1=1200,X1=4e3,V1=8e3,Y1=12e4;function Q1(e,n,s,o){let i=!1,r=null,l=0,h=!1;const u=jf(),m=()=>typeof document<"u"&&document.hidden?V1:Date.now()-l<Y1?U1:X1,d=async p=>{l=Date.now();let b;try{b=await kf(p.tool,p.args||{},e)}catch(y){b={ok:!1,error:String(y?.message||y).slice(0,500)}}const{_image:g,...v}=b;try{await mg(p.id,{tabId:u,ok:b.ok!==!1,result:wf(v),...typeof g=="string"?{image:g}:{}})}catch{}p.tool==="drive_character"&&b.ok!==!1&&typeof b.start=="number"&&s?.(b.start)},f=async()=>{if(!i){if(!h){h=!0;try{const p=o?.()||void 0,{commands:b}=await ug({tabId:u,scene:n().slice(0,120),...p?{sceneId:p}:{}});for(const g of b||[]){if(i)break;await d(g)}}catch{}finally{h=!1}}i||(r=setTimeout(()=>{f()},m()))}};return f(),()=>{i=!0,r&&clearTimeout(r)}}function Z1({shot:e,patch:n,progress:s,seek:o,engine:i,selected:r,select:l}){ct();const[h,u]=R.useState(!1),m=e.cameraKeys||[],d=m.find(j=>j.id===r),f=e.cameraMode==="free",p=[...m].sort((j,M)=>j.time-M.time),b=d?Mf(p,p.indexOf(d)):null,g=j=>n(sr(j)),v=(j,M)=>g(m.map(T=>T.id===j?{...T,...M}:T)),y=j=>Cf(e,j),k=()=>{const j=m.find(T=>Math.abs(T.time-s)<1e-6);if(j){l(j.id);return}const M=y(s);g([...m,M]),l(M.id)};R.useEffect(()=>{if(i){if(e.motion!=="path"&&!h){i.setPathEditor(void 0);return}return i.setPathEditor({selected:r,drawing:h,select:j=>{l(j);const M=m.find(T=>T.id===j);M&&o(M.time)},move:(j,M)=>v(j,{position:M}),add:j=>{const M={...y(1),position:j},T=[...m,M].map((w,E,N)=>({...w,time:N.length>1?E/(N.length-1):0}));g(T),l(M.id),o(T.at(-1)?.time||0)}}),()=>i.setPathEditor(void 0)}},[i,e.id,e.cameraKeys,e.motion,r,h]),R.useEffect(()=>{u(!1),l(null)},[e.id]);const C=j=>{const M=Nf(e,j);g(M),l(M[0].id),o(0),u(!1)},S=(j,M,T,w,E)=>t.jsxs("label",{className:"shot-path-number",children:[a(j),t.jsx(Sn,{"aria-label":a(j),step:"0.1",min:w,max:E,precision:3,value:M,onCommit:T})]}),I=(j,M,T)=>t.jsx("div",{className:"shot-path-vector",children:M.map((w,E)=>t.jsx("div",{children:S(`${a(j)} ${"XYZ"[E]}`,w,N=>T(M.map((A,O)=>E===O?N:A)))},E))});return t.jsxs("section",{className:"shot-path-editor",children:[t.jsx("h3",{children:a("ĐƯỜNG CHẠY CAMERA")}),t.jsx("p",{children:a("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":a("Hướng camera"),children:[t.jsx("button",{role:"radio","aria-checked":!f,className:f?"":"shot-primary",onClick:()=>n({cameraMode:void 0}),children:a("Bám theo (Track)")}),t.jsx("button",{role:"radio","aria-checked":f,className:f?"shot-primary":"",onClick:()=>n({cameraMode:"free"}),children:a("Tự do (Free style)")})]}),t.jsx("p",{className:"shot-camera-mode-hint",children:f?a("Camera nhìn theo hướng đi của đường; chọn từng điểm để xoay hướng nhìn tuỳ ý."):a('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(([j,M])=>t.jsxs("button",{onClick:()=>C(j),children:[{circle:t.jsx(Ne.circle,{}),spiral:t.jsx(Ne.spiral,{}),line:t.jsx(Ne.line,{}),curve:t.jsx(Ne.curve,{})}[j],a(M)]},j))}),t.jsxs("button",{className:h?"shot-primary":"",onClick:()=>{u(!h),h||(g([]),l(null),o(0),i?.view(!0))},children:[t.jsx(Ne.pen,{}),h?a("✓ Xong vẽ đường").replace("✓ ",""):a("✎ Vẽ đường mới bằng điểm").replace("✎ ","")]}),h&&t.jsx("p",{children:a("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:k,children:[t.jsx(Ne.key,{}),a("+ Key tại thời điểm này").replace("+ ","")]}),t.jsx("button",{disabled:!m.length,onClick:()=>g(m.map((j,M)=>({...j,time:m.length>1?M/(m.length-1):0}))),children:a("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:j=>n({pathSmooth:j.target.checked})})," ",a("Đường cong mượt")]}),t.jsx("div",{className:"shot-path-keys",children:m.map((j,M)=>t.jsxs("button",{className:j.id===r?"shot-primary":"",onClick:()=>{l(j.id),o(j.time)},children:["◆ ",M+1," · ",(j.time*e.duration).toFixed(1),a("s")]},j.id))})]}),d&&t.jsxs("div",{className:"shot-path-key",children:[t.jsxs("b",{children:[a("Điểm")," ",m.indexOf(d)+1]}),t.jsx("button",{onClick:()=>l(null),children:a("Bỏ chọn điểm")}),S(a("Thời điểm key (giây)"),d.time*e.duration,j=>{const M=j/e.duration;m.some(T=>T.id!==d.id&&Math.abs(T.time-M)<1e-6)||(v(d.id,{time:M}),o(M))},0,e.duration),I("Camera",d.position,j=>v(d.id,{position:j})),!f&&I(a("Nhìn tới"),d.target,j=>v(d.id,{target:j})),f&&b&&t.jsxs("div",{className:"shot-path-aim",children:[S(a("Xoay ngang (°)"),b[0],j=>v(d.id,{aim:[j,b[1]]}),-360,360),S(a("Ngẩng / cúi (°)"),b[1],j=>v(d.id,{aim:[b[0],j]}),-85,85),t.jsx("button",{disabled:!d.aim,onClick:()=>v(d.id,{aim:void 0}),children:a("Nhìn theo hướng đi")})]}),S(a("Tiêu cự key (mm)"),d.lens,j=>v(d.id,{lens:j}),14,200),S(a("Nghiêng key (°)"),d.roll,j=>v(d.id,{roll:j})),t.jsx("button",{onClick:()=>{const j=i?.captureCamera();j&&v(d.id,{position:j.position,target:j.target,lens:j.lens,roll:j.roll,...f&&j.target&&j.position?{aim:Sf(new oe(j.target[0]-j.position[0],j.target[1]-j.position[1],j.target[2]-j.position[2]))}:{}})},children:a("Lấy góc đang quan sát cho key")}),t.jsx("button",{onClick:()=>{g(m.filter(j=>j.id!==d.id)),l(null)},children:a("Xoá key này")})]})]})}const $u=.5,Du=60,J1=e=>Math.min(Du,Math.max($u,Math.round(e*100)/100));function Ou(e){const n=gn(e);return{aspect:[...ac.includes(e.aspect)?[]:[a("Seedance không nhận tỷ lệ {0}; khi gửi sẽ dùng {1}.",[e.aspect,ar(e.aspect,ac)])],...Fa.includes(e.aspect)?[]:[a("Ảnh thật (GPT Image) không nhận tỷ lệ {0}; sẽ dùng {1}.",[e.aspect,ar(e.aspect,Fa)])]],duration:e.duration<4?[a("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?[]:[a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[n])]}}const Wh=e=>{const n=Ef(e),s=n>=1?14:14*n,o=n>=1?14/n:14;return t.jsx("span",{className:"shot-fmt-glyph","aria-hidden":"true",style:{width:s,height:o}})};function ej({shot:e,patch:n,disabled:s}){ct();const[o,i]=R.useState(null),[r,l]=R.useState(null),h=R.useRef(null),u=gn(e),m=Ou(e);R.useEffect(()=>{if(!o)return;const C=S=>{h.current?.contains(S.target)||i(null)};return document.addEventListener("pointerdown",C,!0),()=>document.removeEventListener("pointerdown",C,!0)},[o]),R.useEffect(()=>{o&&h.current?.querySelector('.shot-fmt-pop [aria-checked="true"], .shot-fmt-pop button')?.focus()},[o]);const d=C=>h.current?.querySelector(`[data-fmt="${C}"]`),f=C=>{const S=o;i(null),S&&requestAnimationFrame(()=>d(S)?.focus())},p=C=>{n(C),f()},b=C=>{if(Number.isFinite(C)){const S=J1(C);S!==e.duration&&n({duration:S})}},g=()=>{if(r!==null){const C=Number(r.replace(",","."));r.trim()!==""&&b(C),l(null)}},v=C=>{if(C.key==="Escape"&&o){C.preventDefault(),C.stopPropagation(),f();return}const S=C.target.closest(".shot-fmt-pop");if(S&&["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(C.key)){C.preventDefault();const I=[...S.querySelectorAll("button")],j=I.indexOf(C.target),M=C.key==="Home"?0:C.key==="End"?I.length-1:(j+(C.key==="ArrowDown"||C.key==="ArrowRight"?1:-1)+I.length)%I.length;I[M]?.focus()}},y=[...Af,...Tf.includes(e.aspect)?[e.aspect]:[]],k=a("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:h,onKeyDown:v,children:[t.jsxs("small",{children:[Number(e.lens.toFixed(1)),a("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":o==="aspect","aria-label":a("Tỷ lệ khung hình: {0}",[e.aspect]),title:[a("Tỷ lệ khung hình của shot"),...m.aspect].join(`
283
+ }`;function Qd(e,n){const s=[];e.traverse(i=>{i.isMesh&&i.visible&&!i.userData.fxMarker&&s.push(i)});const o=s.filter(i=>i.isSkinnedMesh);n.makeEmpty();for(const i of o.length?o:s)n.expandByObject(i,!0);return n}let Tb=null;const Lb=()=>Tb??=Object.assign(Zh(Kn["Thiền định"],"#d8dde6",void 0),{name:"fx-ghost-stand-in"}),Eb=e=>{e.isLine=!0};function Ib(e,n,s){const o=new rn;o.name="fx-ghost";const i=new Ua({vertexShader:Nb,fragmentShader:Ab,transparent:!0,depthWrite:!1,blending:Hr,side:Va,uniforms:{uColor:{value:new Ue},uCore:{value:new Ue},uAlpha:{value:0},uTime:{value:0},uBase:{value:0},uHeight:{value:1},uReveal:{value:1},uCut:{value:0},uStars:{value:1},uScale:{value:1},uFlow:{value:1}}});let r=[],l=null,h=-1,u=null,m=0,d=!1;const f=new At,p=new At,b=new oe,g=new oe,v=new zt,y=()=>{for(const S of r)o.remove(S.copy);r=[],l=null,h=-1},k=S=>{const I=[];return S.traverse(j=>{j.isMesh&&j.visible&&!j.userData.fxMarker&&!j.isLine&&j.layers.isEnabled(0)&&I.push(j)}),I},C=(S,I)=>{y();for(const j of I){let M;if(j.isSkinnedMesh){const T=j,w=new Or(T.geometry,i);w.bindMode=Q0,w.bind(T.skeleton,T.bindMatrix),w.updateMatrixWorld=()=>{},w.updateWorldMatrix=()=>{},M=w}else M=new ut(j.geometry,i);M.matrixAutoUpdate=!1,M.matrixWorldAutoUpdate=!1,M.frustumCulled=!1,M.castShadow=!1,M.receiveShadow=!1,M.renderOrder=ni(n,!0),Eb(M),o.add(M),r.push({src:j,copy:M})}l=S,h=I.length};return{object:o,update(S,I){const j=e.eval(S,I);let M=s();if(!j||j.alpha<=.002)return o.visible=!1,0;M||(M=Lb(),M.position.set(I.origin[0],I.origin[1],I.origin[2]),M.rotation.set(0,I.yaw,0),M.scale.setScalar(I.size)),M.updateWorldMatrix(!0,!0);const T=k(M);if((l!==M||T.length!==h)&&C(M,T),!r.length||((l!==u||Math.abs(S-m)>.25||!d)&&(Qd(M,v),u=l,m=S,d=!v.isEmpty()),!d))return o.visible=!1,0;b.set((v.min.x+v.max.x)/2,v.min.y,(v.min.z+v.max.z)/2),g.set(j.offset[0],j.offset[1],j.offset[2]),f.makeTranslation(b.x+g.x,b.y+g.y,b.z+g.z).multiply(p.makeRotationY(j.turn??0)).multiply(p.makeScale(j.scale,j.scale,j.scale)).multiply(p.makeTranslation(-b.x,-b.y,-b.z));for(const{src:A,copy:O}of r)O.matrixWorld.multiplyMatrices(f,A.matrixWorld),O.isSkinnedMesh&&O.bindMatrixInverse.copy(A.matrixWorld).invert(),O.visible=A.visible;const w=b.y+g.y,E=Math.max(.2,(v.max.y-v.min.y)*j.scale),N=i.uniforms;return N.uColor.value.setRGB(j.color[0]*j.color[3],j.color[1]*j.color[3],j.color[2]*j.color[3],xs),N.uCore.value.setRGB(j.core[0],j.core[1],j.core[2],xs),N.uAlpha.value=j.alpha,N.uTime.value=S,N.uBase.value=w,N.uHeight.value=E,N.uReveal.value=j.reveal,N.uCut.value=j.cut,N.uStars.value=j.stars,N.uScale.value=j.scale,N.uFlow.value=j.flow,o.visible=!0,r.length},setShare(){},hide(){o.visible=!1},dispose(){y(),i.dispose()}}}const Rb=new Set(["box","wall","platform","floor"]),Zd=new Set(["model","proxy","box","wall","platform","floor","sphere","cylinder","set","prop"]),Fb=1500,zi=8,ma=new Map,Xc=()=>{},Pb=new ns({color:"#7d766b",roughness:1,metalness:0,name:"mix-rubble"});function $b(e,n,s){const o=e.kind==="model"?`${e.model?.gcsUri}|${e.model?.height??""}`:e.kind==="proxy"?JSON.stringify(e.proxy):e.kind==="set"?e.set?.id:e.kind==="prop"?e.prop?.kind:"";return`${e.id}|${e.kind}|${o}|${e.scale.map(i=>i.toFixed(3)).join(",")}|${Math.round(n)}|${s}`}function Jd(e){const n=[];return e.traverse(s=>{s instanceof ut&&!s.userData.fxMarker&&n.push(s)}),n}function Db(e,n){const s=n.clone().multiply(e.matrixWorld),o=e;if(!o.isInstancedMesh)return[s];const i=[],r=new At;for(let l=0;l<o.count;l++)o.getMatrixAt(l,r),i.push(s.clone().multiply(r));return i}const dr=e=>Array.isArray(e.material)?e.material:[e.material];function Ob(e,n,s,o){const i=yx(e,s,o),r=bx(i);if(!r)return null;const l=i.length/3,h=i.reduce((p,b,g)=>g%3===0?p+i[g]:p,0)/l,u=i.reduce((p,b,g)=>g%3===1?p+i[g]:p,0)/l,m=i.reduce((p,b,g)=>g%3===2?p+i[g]:p,0)/l,d=new Float32Array(r.length*3);r.forEach((p,b)=>{d[b*3]=h+(i[p*3]-h)*.97,d[b*3+1]=u+(i[p*3+1]-u)*.97,d[b*3+2]=m+(i[p*3+2]-m)*.97});const f=new Tt;return f.setAttribute("position",new Pt(d,3)),f.computeVertexNormals(),f.computeBoundingSphere(),f}function _b(e,n,s,o){const i=$b(n,s,o),r=ma.get(i);if(r)return r;const l=performance.now(),h=n.scale.map(g=>Math.max(.001,Math.abs(g))),u=[];let m=1,d=0,f=0;const p=Rb.has(n.kind);if(p){const g=qm(h,s,o);m=Math.cbrt(h[0]*h[1]*h[2]/Math.max(1,g.length));for(const v of g){const y=v.s.map((S,I)=>S/h[I]),k=v.c.map((S,I)=>S/h[I]),C=new Xa(y[0],y[1],y[2]).translate(k[0],k[1],k[2]);C.clearGroups(),C.addGroup(0,C.index.count,0),u.push({geo:C,core:null,c:k,h:y.map(S=>S/2)})}d=1,f=g.length*12}else{e.updateMatrixWorld(!0);const g=e.matrixWorld.clone().invert(),v=[],y=[];for(const D of Jd(e)){let $=D.geometry;$.getAttribute("position")&&!$.getAttribute("normal")&&($=$.clone(),$.computeVertexNormals());const W=$.getAttribute("position"),z=$.getAttribute("normal"),Y=$.getAttribute("uv"),J=$.index;if(!W){d+=dr(D).length;continue}const V=(G,_)=>{const ee=new Float32Array(G.count*_);for(let Q=0;Q<G.count;Q++)ee[Q*_]=G.getX(Q),ee[Q*_+1]=G.getY(Q),_>2&&(ee[Q*_+2]=G.getZ(Q));return ee},K=Um({pos:V(W,3),nor:z?V(z,3):null,uv:Y?V(Y,2):null,index:J?J.array:null,groups:Array.isArray(D.material)&&$.groups.length?$.groups:null},Db(D,g).map(G=>G.elements),d);v.push(K.verts),y.push(K.slots),d+=dr(D).length}let k=new Float32Array(v.reduce((D,$)=>D+$.length,0)),C=0;for(const D of v)k.set(D,C),C+=D.length;let S=new Int32Array(y.reduce((D,$)=>D+$.length,0));C=0;for(const D of y)S.set(D,C),C+=D.length;if(f=S.length,!f)return{key:i,cells:[],cell:1,slots:d,ms:0,tris:0,solid:p};const I=[1/0,1/0,1/0],j=[-1/0,-1/0,-1/0];for(let D=0;D<k.length;D+=zi)for(let $=0;$<3;$++){const W=k[D+$]*h[$];W<I[$]&&(I[$]=W),W>j[$]&&(j[$]=W)}const M=[0,1,2].map(D=>Math.max(.05,j[D]-I[D]));m=Math.cbrt(M[0]*M[1]*M[2]/Math.max(1,s));const T=Xm(k,zi,S,m*.7,Zm,h);k=T.verts,S=T.slots,f=T.tris;const w=new Float32Array(f*3);for(let D=0;D<f;D++)for(let $=0;$<3;$++)w[D*3+$]=(k[D*24+$]+k[D*24+8+$]+k[D*24+16+$])/3*h[$];const E=Vm(I,j.map((D,$)=>Math.max(D,I[$]+.05)),s,o),N=Ym(w,E),A=[0,1,2].map(D=>(I[D]+j[D])/2/h[D]),O=(h[0]+h[1]+h[2])/3,H=Array.from({length:E.count},()=>[]);for(let D=0;D<f;D++)H[N[D]].push(D);for(const D of H){if(!D.length)continue;D.sort((Q,ve)=>S[Q]-S[ve]||Q-ve);const $=new Float32Array(D.length*9),W=new Float32Array(D.length*9),z=new Float32Array(D.length*6),Y=[1/0,1/0,1/0],J=[-1/0,-1/0,-1/0],V=new Tt;let K=0,G=S[D[0]];D.forEach((Q,ve)=>{S[Q]!==G&&(V.addGroup(K*3,(ve-K)*3,G),K=ve,G=S[Q]);for(let xe=0;xe<3;xe++){const q=(Q*3+xe)*zi,ue=(ve*3+xe)*3;for(let pe=0;pe<3;pe++){const U=k[q+pe];$[ue+pe]=U,W[ue+pe]=k[q+3+pe],U<Y[pe]&&(Y[pe]=U),U>J[pe]&&(J[pe]=U)}z[(ve*3+xe)*2]=k[q+6],z[(ve*3+xe)*2+1]=k[q+7]}}),V.addGroup(K*3,(D.length-K)*3,G),V.setAttribute("position",new Pt($,3)),V.setAttribute("normal",new Pt(W,3)),V.setAttribute("uv",new Pt(z,2)),V.computeBoundingSphere();const _=[0,1,2].map(Q=>(Y[Q]+J[Q])/2),ee=Ob($,_,[A[0]-_[0],A[1]-_[1],A[2]-_[2]],m*.22/O);u.push({geo:V,core:ee,c:_,h:[0,1,2].map(Q=>Math.max(.01,(J[Q]-Y[Q])/2))})}}const b={key:i,cells:u,cell:Math.max(.05,m),slots:d,ms:performance.now()-l,tris:f,solid:p};for(ma.set(i,b);ma.size>6;){const[g,v]=ma.entries().next().value;ma.delete(g),v.cells.forEach(y=>{y.geo.dispose(),y.core?.dispose()})}return b}function zb(e,n){return e.k==="particles"?Ud(e,10+n):e.k==="segments"?Xd(e,10+n):e.k==="props"?Vd(e):e.k==="shell"?Yd(e,10+n):null}const Qn=(e,n)=>typeof e=="number"&&Number.isFinite(e)?e:n,pa=e=>od.has(String(e.fx?.params?.recipe));function Bb(e,n,s,o){const i=e.fx?.attach,r=i&&n?.items.find(l=>l.id===i.to);return i&&r?Qm(gs(r,s,o),Do(e,s,o).position,i):[...gs(e,s,o).position]}class Kb{constructor(n){this.host=n,this.group.name="mix-fx"}group=new rn;effs=new Map;groups=new Map;stage=null;share=1;m=new At;r=new At;v=new oe;rev=0;marker(n){const s=n.fx?.params??{},o=Number(s.radius??1.5),i=Number(s.falloff??0),r=new rn,l=new ut(new ir(pa(n)?.3:.18),new fs({color:n.color,depthTest:!1,transparent:!0,opacity:.9}));if(l.renderOrder=999,!pa(n)){const h=new ut(new Hn(o,28,18),new fs({color:n.color,wireframe:!0,transparent:!0,opacity:.5,depthTest:!1})),u=new ut(new Hn(o+i,24,14),new fs({color:n.color,transparent:!0,opacity:.07,depthWrite:!1,depthTest:!1,side:ys}));h.raycast=Xc,u.raycast=Xc,h.renderOrder=u.renderOrder=999,h.userData.mixSphere=!0,r.add(u,h)}return r.add(l),r.traverse(h=>h.layers.set(1)),r.userData.fxMarker=!0,r}sync(n,s){this.stage=n;const o=new Set(s.map(r=>r.id));for(const[r,l]of this.effs)o.has(r)||(this.dropBursts(l.bursts),this.effs.delete(r));for(const r of this.groups.values())this.unbind(r),this.dropBursts(r.bursts);this.groups.clear();const i=new Map;for(const r of s){const h=this.effs.get(r.id)??{item:r,hits:[],samples:[],plan:null,burstKey:"",bursts:[]};h.item=r,this.effs.set(r.id,h);const u=n.items.find(d=>d.id===r.fx?.target?.to&&d.id!==r.id&&Zd.has(d.kind)&&!d.hidden);if(!u){this.dropBursts(h.bursts),h.burstKey="";continue}const m=i.get(u.id)??{target:u,effs:[]};m.effs.push(h),i.set(u.id,m)}for(const[r,{target:l,effs:h}]of i){const u=this.host.object(r);if(!u)continue;const m=h[0].item.fx,d=Number(m.params.chunks),f=m.seed,p=_b(u,l,d,f),b=h.slice(1).some(k=>Math.round(Number(k.item.fx.params.chunks))!==Math.round(d)||k.item.fx.seed!==f),g=Jd(u),v=g.flatMap(dr),y={id:r,target:l,root:u,frac:p,effs:h,note:b?h[0].item.id:null,meshes:[],cores:[],originals:g,planFor:null,planKey:"",matrices:[],rest:0,boxes:[],graph:null,graphKey:"",entries:[],falls:[],burstKey:"",bursts:[]};y.meshes=p.cells.map((k,C)=>{const S=new ut(k.geo,v.length?v:[new ns({color:l.color})]);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk ${C}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),y.cores=p.cells.map((k,C)=>{if(!k.core)return null;const S=new ut(k.core,Pb);return S.matrixAutoUpdate=!1,S.castShadow=!0,S.receiveShadow=!0,S.name=`chunk core ${C}`,S.visible=!1,S.userData.mixTarget=r,this.group.add(S),S}),this.groups.set(r,y)}for(const r of this.effs.values())[...this.groups.values()].some(l=>l.effs.includes(r))||(this.dropBursts(r.bursts),r.burstKey="")}unbind(n){for(const s of n.meshes)this.group.remove(s);for(const s of n.cores)s&&this.group.remove(s);for(const s of n.originals)s.visible=!0;n.meshes=[],n.cores=[],n.originals=[]}dropBursts(n){for(const s of n)for(const o of s.layers)o.dispose(),this.group.remove(o.object);n.length=0}ensure(n,s){if(n.planFor===s)return;n.planFor=s;const o=n.target,i=gn(s),r=Math.max(.1,s.duration),l=Math.max(1/i,r/Fb),h=n.effs.map(w=>Fn(w.item,s)),u=n.effs.map(w=>{const E=w.item.fx?.attach,N=E&&this.stage?.items.find(A=>A.id===E.to);return N?[N.position,N.rotation,N.scale,s.objectKeys?.[N.id]]:null}),m=JSON.stringify([n.effs.map(w=>[w.item.fx,w.item.position,w.item.scale,s.objectKeys?.[w.item.id]]),u,h,o.position,o.rotation,o.scale,s.objectKeys?.[o.id],r,l,n.frac.key]);if(m===n.planKey)return;n.planKey=m,this.rev++;const d=n.frac.cells,f=d.length,p=n.effs[0].item.fx,b=p.params,g=[];for(let w=0;;w++){const E=Math.min(r,w*l);if(g.push(E),E>=r)break}const v=g.map(w=>{const E=gs(o,s,w/r);return Bm(E.position,E.rotation,E.scale)});n.matrices=v.map(w=>new At().fromArray(w));const y=b.support!=="off",k=[];n.effs.forEach((w,E)=>{const N=w.item.fx.params,A=h[E];w.plan=null,w.hits=[],w.samples=[],!(A.off||pa(w.item))&&(w.samples=g.map((O,H)=>({t:O,c:Bb(w.item,this.stage,s,O/r),r:Number(N.radius)*Math.max(.05,Math.abs(w.item.fx?.attach?w.item.scale[0]:gs(w.item,s,O/r).scale[0])),m:v[H]})),w.hits=Km(d,w.samples,{falloff:Number(N.falloff),start:A.start,end:A.start+A.duration,collapse:y?0:Number(N.collapse),cell:n.frac.cell,seed:w.item.fx.seed}),k.push({e:E,hits:w.hits}))});const C=Math.min(...h.filter(w=>!w.off).map(w=>w.start),r);n.rest=Hm(g.map(w=>({t:w})),C),n.boxes=d.map(w=>sx(v[n.rest],w.c,w.h));const S=(()=>{const w=[0,2].map(N=>Math.min(...n.boxes.map(A=>A.min[N]))),E=[0,2].map(N=>Math.max(...n.boxes.map(A=>A.max[N])));return[(w[0]+E[0])/2,0,(w[1]+E[1])/2]})(),I=n.effs.some((w,E)=>!h[E].off&&pa(w.item));n.falls=new Array(f).fill(null);const j=xx(f,k);if(y&&k.length){const w=`${n.frac.key}|${n.rest}|${v[n.rest].map(A=>A.toFixed(4)).join(",")}`;(n.graphKey!==w||!n.graph)&&(n.graph=ax(n.boxes,{cell:n.frac.cell}),n.graphKey=w);const E=lx(n.graph,j,{slack:rx(Qn(b.collapse,.85)),seed:p.seed,centres:n.boxes.map(A=>A.c)}),N=I?[]:[...Array(f).keys()].filter(A=>!Number.isFinite(j[A])&&!E[A]);n.falls=dx(n.boxes,E,N,{base:n.graph.base,cell:n.frac.cell,seed:p.seed,centre:S})}const M=Float64Array.from(j,(w,E)=>Math.min(w,n.falls[E]?.t??1/0)),T=[];n.effs.forEach((w,E)=>{const N=w.item.fx.params,A=h[E];A.off||!pa(w.item)||(w.plan=ux(n.boxes,{mode:String(N.mode),start:A.start,duration:A.duration,yaw:Qn(N.yaw,0),crumble:Qn(N.crumble,.6),seed:w.item.fx.seed,cell:n.frac.cell,gone:M,gravity:Qn(N.gravity,9.8)}),T.push({e:E,plan:w.plan}))}),n.entries=gx(f,{blasts:k,collapses:T,falls:n.falls}),this.ensureBursts(n,s)}makeBurst(n,s,o,i,r,l,h,u,m,d,f={}){if(!$o[n.preset])return null;const p=n.fill?Math.max(n.duration,d.duration-o):n.duration,b={preset:n.preset,intensity:Math.min(3,u),seed:qa(i|0,l,r+7)%1e9,duration:p,loop:!1,params:{...Wm(n.preset),...n.params,...f}},g=[],v=[];for(const[y,k]of ad(b,{color:h,size:m}).entries()){if(k.k==="light"){v.push(k);continue}const C=zb(k,y);C&&(C.hide(),C.setShare(this.share),g.push(C),this.group.add(C.object))}return{t:o,at:s,dur:p,tail:$o[n.preset].tail??0,layers:g,lights:v,size:m}}ensureBursts(n,s){const o=Math.min(4,Math.max(.6,n.frac.cell*1.3));for(const d of n.effs){const f=d.item.fx,p=f.params,b=Wa[p.recipe]??Wa.collapse,g=Number(p.debris);Fn(d.item,s);let v=[];if(d.plan){const k=d.plan,C=[Math.max(...n.boxes.map(I=>I.max[0]))-Math.min(...n.boxes.map(I=>I.min[0])),Math.max(...n.boxes.map(I=>I.max[2]))-Math.min(...n.boxes.map(I=>I.min[2]))];v=[{t:k.t0,at:[k.centre[0],k.base,k.centre[2]],base:!0}];const S=g<=.01?0:Math.max(1,Math.round(b.maxBursts*Math.min(1,.35+g*.55)));for(let I=0;I<S;I++){const j=I/Math.max(1,S)*Math.PI*2+.6;v.push({t:k.t0+k.D*(.3+.6*(I/Math.max(1,S))),at:[k.centre[0]+Math.cos(j)*C[0]*.45,k.base,k.centre[2]+Math.sin(j)*C[1]*.45]})}}else{const k=g<=.01?0:Math.max(1,Math.round(b.maxBursts*Math.min(1,.35+g*.55)));v=ql(d.hits,k)}const y=JSON.stringify([v.map(k=>[+k.t.toFixed(3),...k.at.map(C=>+C.toFixed(2))]),p.recipe,p.dust,g,d.item.color,f.seed,s.duration,o,f.intensity,n.boxes.length]);y!==d.burstKey&&(this.dropBursts(d.bursts),d.burstKey=y,v.forEach((k,C)=>b.bursts.forEach((S,I)=>{const j=S.at==="base";if(j!==!!k.base)return;const M=j?[0,1,2].map(E=>Math.max(...n.boxes.map(N=>N.max[E]))-Math.min(...n.boxes.map(N=>N.min[E]))):null,T=M?{width:Math.max(2,M[0]*1.6),height:Math.max(2,M[1]),depth:Math.max(2,M[2]*1.6),dust:Qn(p.dust,1),spread:d.plan?.D??3}:{},w=this.makeBurst(S,k.at,k.t,f.seed,I,C,d.item.color,(.55+.6*g)*f.intensity,j?1:o,s,T);w&&d.bursts.push(w)})))}const i=n.effs[0].item,l=n.falls.map((d,f)=>d?{f:d,i:f}:null).filter(Boolean).map(({f:d,i:f})=>({t:d.t+Math.sqrt(2*Math.max(0,d.p0[1]-d.land)/Math.max(.5,Number(i.fx.params.gravity))),at:[d.to[0],d.land,d.to[1]],i:f})).sort((d,f)=>d.t-f.t||d.i-f.i),h=Math.min(3,l.length),u=[];for(let d=0;d<h;d++){const f=l.slice(Math.floor(d*l.length/h),Math.floor((d+1)*l.length/h));f.length&&u.push({t:f[0].t,at:Hb(f.map(p=>p.at))})}const m=JSON.stringify([u.map(d=>[+d.t.toFixed(3),...d.at.map(f=>+f.toFixed(2))]),i.color,i.fx.seed,s.duration,o]);m!==n.burstKey&&(this.dropBursts(n.bursts),n.burstKey=m,u.forEach((d,f)=>{const p=this.makeBurst({preset:"va_cham",params:{kind:"dust"},duration:1.4},[d.at[0],Math.max(0,d.at[1]),d.at[2]],d.t,i.fx.seed,3,f+50,"#b59a7a",1,o*1.4,s);p&&n.bursts.push(p)}))}impacts(n){const s=[],o=Math.max(.1,n.duration),i=(r,l)=>{const h=r/o;l>.01&&h>=0&&h<=1&&s.push({time:+h.toFixed(4),strength:Math.min(1,l)})};for(const r of this.groups.values()){this.ensure(r,n);for(const u of r.effs){const m=Qn(u.item.fx.params.shake,.5);if(!(m<=.01))if(u.plan){const d=u.plan;i(d.t0+.05,m*.45),i(d.t0+d.D*.4,m),i(d.t0+d.D*.75,m*.85),i(d.t0+d.D,m*(d.mode==="topple"?1:.6))}else ql(u.hits,3).forEach((d,f)=>i(d.t,m*(f===0?1:.6)))}const l=Qn(r.effs[0].item.fx.params.shake,.5),h=r.falls.reduce((u,m)=>m&&m.t<u?m.t:u,1/0);Number.isFinite(h)&&l>.01&&i(h+.35,l*.45)}return s.sort((r,l)=>r.time-l.time||l.strength-r.strength)}update(n,s){const o=[],i=r=>{for(const l of r){const h=s-l.t;if(h<0||h>l.dur+l.tail){l.layers.forEach(m=>m.hide());continue}const u=No(l.at,0,l.size);u.target=l.at,u.light=1,u.volume=null;for(const m of l.layers)m.update(h,u);for(const m of l.lights){const d=m.eval(h,u);d&&d.intensity>.01&&o.push({pos:d.pos,color:d.color,intensity:d.intensity})}}};for(const r of this.groups.values()){if(!r.effs.some(d=>!Fn(d.item,n).off)||!r.frac.cells.length){for(const d of r.originals)d.visible=!0;for(const d of r.meshes)d.visible=!1;for(const d of r.cores)d&&(d.visible=!1);for(const d of r.effs)d.bursts.forEach(f=>f.layers.forEach(p=>p.hide()));r.bursts.forEach(d=>d.layers.forEach(f=>f.hide()));continue}this.ensure(r,n);for(const d of r.originals)d.visible=!1;r.root.updateWorldMatrix(!0,!1);const h=r.root.matrixWorld,u=r.effs[0].item.fx.params,m={gravity:Qn(u.gravity,9.8),seed:r.effs[0].item.fx.seed,crumble:Qn(u.crumble,.6)};r.meshes.forEach((d,f)=>{const p=r.entries[f],b=r.cores[f];let g=null,v=null,y=r.rest;if(p?.kind==="hit"){const k=r.effs[p.e],C=k.hits[f],S=k.item.fx.params;g=Gm(C,f,s,{strength:Number(S.strength),lift:Number(S.lift),gravity:Number(S.gravity),spin:Number(S.spin),seed:k.item.fx.seed}),v=C.p0,y=C.s}else if(p?.kind==="fall"){const k=r.falls[f];g=hx(k,f,s,m),v=k.p0}else p?.kind==="collapse"&&(g=Ac(r.effs[p.e].plan,r.boxes[f],f,s),v=r.boxes[f].c);d.visible=!0,!g||!v?(d.matrix.copy(h),b&&(b.visible=!1)):(this.m.copy(r.matrices[y]),this.m.premultiply(this.r.makeTranslation(-v[0],-v[1],-v[2])),this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.axis[0],g.axis[1],g.axis[2]),g.angle)),g.extra&&this.m.premultiply(this.r.makeRotationAxis(this.v.set(g.extra.axis[0],g.extra.axis[1],g.extra.axis[2]).normalize(),g.extra.angle)),this.m.premultiply(this.r.makeTranslation(g.pos[0],g.pos[1],g.pos[2])),d.matrix.copy(this.m),b&&(b.visible=!0,b.matrix.copy(this.m),b.matrixWorldNeedsUpdate=!0)),d.matrixWorldNeedsUpdate=!0});for(const d of r.effs)i(d.bursts);i(r.bursts)}return o}setShare(n){this.share=n;for(const s of this.effs.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n));for(const s of this.groups.values())for(const o of s.bursts)o.layers.forEach(i=>i.setShare(n))}pick(n){const s=this.group.children.filter(i=>i.visible&&i.userData.mixTarget);if(!s.length)return null;this.group.updateMatrixWorld(!0);const o=n.intersectObjects(s,!1)[0];return o?{id:String(o.object.userData.mixTarget),distance:o.distance}:null}groupOf(n){for(const s of this.groups.values())if(s.effs.some(o=>o.item.id===n))return s;return null}stats(n){return[...this.effs.values()].map(s=>{const o=this.groupOf(s.item.id),i=o?o.effs.indexOf(s):-1,r=o?o.entries.filter((l,h)=>l&&n>=l.t&&(l.kind!=="collapse"||Ac(o.effs[l.e].plan,o.boxes[h],h,n))).length:0;return{id:s.item.id,target:o?.id??null,chunks:o?.frac.cells.length??0,tris:o?.frac.tris??0,ms:Math.round(o?.frac.ms??0),broken:r,hit:s.hits.filter(Boolean).length,bursts:s.bursts.length,falling:o?o.entries.filter(l=>l?.kind==="fall").length:0,own:o?o.entries.filter(l=>l&&l.e===i).length:0,cores:o?o.cores.filter(Boolean).length:0,first:s.hits.reduce((l,h)=>h&&(l===null||h.t<l)?h.t:l,null),lead:o?.effs[0].item.id??null,overridden:!!o&&i>0&&o.note!==null}})}chunkCentres(n){const s=this.groupOf(n);return s?s.meshes.map((o,i)=>{const r=s.frac.cells[i].c,l=new oe(r[0],r[1],r[2]).applyMatrix4(o.matrix);return[l.x,l.y,l.z]}):[]}visibleCounts(n){const s=this.groupOf(n);return s?{chunks:s.meshes.filter(o=>o.visible).length,cells:s.frac.cells.length,originals:s.originals.filter(o=>o.visible).length,meshes:this.group.children.filter(o=>o.userData.mixTarget===s.id&&o.isMesh&&!o.name.includes("core")&&o.visible).length}:null}dispose(){for(const n of this.groups.values())this.unbind(n),this.dropBursts(n.bursts);for(const n of this.effs.values())this.dropBursts(n.bursts);this.groups.clear(),this.effs.clear(),this.group.parent?.remove(this.group)}}function Hb(e){const n=e.reduce((s,o)=>[s[0]+o[0],s[1]+o[1],s[2]+o[2]],[0,0,0]);return[n[0]/e.length,n[1]/e.length,n[2]/e.length]}const Wb=Math.PI/180,Gb=xn.maxLights,qb={day:1,golden:.8,overcast:.85,night:.22};class Ub{constructor(n,s){this.host=s,this.group.name="fx",this.mix=new Kb(s),n.add(this.group,this.pathGroup,this.mix.group)}group=new rn;insts=new Map;lights=[];share=1;heat=[];light={fill:0,color:[1,1,1],pos:null,sources:[]};stage;only=null;pathGroup=new rn;mix;syncPath(n,s){this.pathGroup.traverse(h=>{(h instanceof ut||h instanceof Ri)&&(h.geometry.dispose(),h.material.dispose())}),this.pathGroup.clear();const o=s&&n.items.find(h=>h.id===s.itemId),i=o?.fx?.path;if(!s||!i||i.length<2)return;const r=Jm(i),l=new Ri(new Tt().setFromPoints(Array.from({length:48},(h,u)=>new oe(...r.at(u/47)))),new xc({color:"#b8df78",depthTest:!1,transparent:!0,opacity:.9}));l.renderOrder=998,l.layers.set(1),this.pathGroup.add(l),i.forEach((h,u)=>{const m=new ut(new Hn(.1,14,10),new fs({color:u===s.selected?"#ffad52":u===0?"#7fe9ff":"#b8df78",depthTest:!1}));m.position.set(...h),m.userData.fxPoint=u,m.renderOrder=999,m.layers.set(1),this.pathGroup.add(m)})}pathHandles(){return this.pathGroup.children.filter(n=>n.userData.fxPoint!==void 0)}setFilter(n){this.only=n}get active(){return this.insts.size>0}marker(n){if(n.fx?.preset===Ji)return this.mix.marker(n);const s=new rn,o=new ut(new ir(.13),new fs({color:n.color,wireframe:!0,depthTest:!1,transparent:!0,opacity:.9})),i=new ut(new ir(.06),new fs({color:n.color,depthTest:!1,transparent:!0,opacity:.85})),r=new Ri(new Tt().setFromPoints([new oe(0,0,0),new oe(0,-.4,0)]),new xc({color:n.color,depthTest:!1,transparent:!0,opacity:.45}));return o.renderOrder=i.renderOrder=r.renderOrder=999,s.add(o,i,r),s.traverse(l=>l.layers.set(1)),s.userData.fxMarker=!0,s.position.y=0,s}sync(n){this.stage=n;const s=new Map;let o=0,i=0;for(const r of n.items){if(r.kind!=="fx"||!r.fx||r.hidden)continue;if(++i>xn.maxItems)break;const l=er(r.fx);if(!l.fx)continue;const h=tr(l.fx);h>xn.maxParticlesPerItem||o+h>xn.maxTotalParticles||(o+=h,s.set(r.id,r))}for(const[r,l]of this.insts)s.has(r)||this.drop(r,l);for(const[r,l]of s){const h=this.sizeOf(l,n),u=JSON.stringify([l.fx,l.color,h]),m=this.insts.get(r);if(m?.key===u){m.item=l;continue}m&&this.drop(r,m),this.insts.set(r,this.build(l,h,u))}this.mix.sync(n,[...s.values()].filter(r=>r.fx?.preset===Ji)),this.ensureLights()}sizeOf(n,s){const o=Math.max(.1,n.scale[0]),i=n.fx?.attach&&s.items.find(r=>r.id===n.fx.attach.to);return o*(i?this.host.figureScale(i)*Math.max(.1,i.scale[1]):1)}build(n,s,o){const i=er(n.fx).fx,r=ad(i,{color:n.color,size:s}),l=new rn;l.name=`fx:${n.name}`;const h=[],u=[],m=[],d=r.length?Vb(n.color):[.3,.8,1];return r.forEach((f,p)=>{if(f.k==="light"){u.push(f);return}if(f.k==="heat"){m.push(f);return}const b=f.k==="particles"?Ud(f,10+p):f.k==="segments"?Xd(f,10+p):f.k==="swords"?wb(f,d):f.k==="props"?Vd(f):f.k==="water"?gb(f,5+p):f.k==="ghost"?Ib(f,10+p,()=>n.fx?.attach?this.host.object(n.fx.attach.to):void 0):Yd(f,10+p);b.hide(),b.setShare(this.share),h.push(b),l.add(b.object)}),l.visible=!1,this.group.add(l),{item:n,key:o,layers:h,defs:r,tail:ep(i.preset),group:l,lights:u,heats:m,budget:tr(i),share:this.share}}drop(n,s){s.layers.forEach(o=>o.dispose()),this.group.remove(s.group),this.insts.delete(n)}ensureLights(){if(this.insts.size&&!this.lights.length)for(let n=0;n<Gb;n++){const s=new Z0(16777215,0,0,2);s.visible=!0,this.lights.push(s),this.group.add(s)}if(!this.insts.size&&this.lights.length){for(const n of this.lights)this.group.remove(n),n.dispose();this.lights=[]}}frameOf(n,s,o,i,r=0){const l=n.fx?.attach,h=l&&this.host.object(l.to);if(!l||!h)return No([o.position.x,o.position.y,o.position.z],o.rotation.y,s);h.updateWorldMatrix(!0,!1);const u=Do(n,i??{},r),m=u.yaw*Wb,d=(l.follow==="position"?0:h.rotation.y)+m,f=new oe(...u.position);let p;if(l.hand&&l.tip){const b=this.stage?.items.find(v=>v.hold?.by===l.to&&v.hold.hand===l.hand&&v.prop&&!v.hidden),g=Ul(h,l.hand);if(b?.prop&&b.hold&&g.frame){const v=tp(g.frame,b.prop.kind,b.hold.angle??0,b.hold.tilt,g.fist),y=v.tip.clone().sub(v.grip);return No([v.tip.x,v.tip.y,v.tip.z],Math.atan2(y.x,y.z),s)}}if(l.hand){o.userData.fxOffsetYaw=d,o.userData.fxOffsetScale=1;const b=Ul(h,l.hand);p=b.frame?b.frame.localToWorld(b.fist.clone()):h.getWorldPosition(new oe).add(new oe(l.hand==="R"?-.3:.3,1,.3)),p.add(f.applyAxisAngle(new oe(0,1,0),d))}else{const b=h.getWorldPosition(new oe),g=l.part?h.getObjectByName("head")?.getWorldPosition(new oe):void 0,v=g&&l.part==="head"?g:g?b.clone().lerp(g,.74):b;o.userData.fxOffsetYaw=l.follow==="position"?0:h.rotation.y,o.userData.fxOffsetScale=h.scale.x||1,p=v.add(f.multiply(h.scale).applyAxisAngle(new oe(0,1,0),l.follow==="position"?0:h.rotation.y))}return No([p.x,p.y,p.z],d,s)}hidden=new Set;hideTargets(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return[];if(!s.name)return[o];const i=s.name.toLowerCase(),r=[];return o.traverse(l=>{l instanceof ut&&l.name.toLowerCase().includes(i)&&r.push(l)}),r}volumeOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to),i=s&&this.stage?.items.find(m=>m.id===s.to);if(!s||!o||!i)return null;o.updateWorldMatrix(!0,!0);const r=m=>[m.r,m.g,m.b];if(s.name){const m=s.name.toLowerCase(),d=new zt;let f=null;if(o.traverse(g=>{if(g instanceof ut&&g.name.toLowerCase().includes(m)){d.expandByObject(g);const v=Array.isArray(g.material)?g.material[0]:g.material;!f&&v.color&&(f=r(v.color))}}),d.isEmpty())return null;const p=d.getSize(new oe),b=d.getCenter(new oe);return p.x>=p.z?{size:[p.x,p.y,p.z],base:[b.x,d.min.y,b.z],yaw:0,color:f??r(new Ue(i.color))}:{size:[p.z,p.y,p.x],base:[b.x,d.min.y,b.z],yaw:Math.PI/2,color:f??r(new Ue(i.color))}}if(i.kind==="proxy"&&i.proxy){const m=i.proxy.dims,d=o.scale,f=o.getWorldPosition(new oe);return{size:[m[0]*d.x,m[1]*d.y,m[2]*d.z],base:[f.x,f.y,f.z],yaw:o.rotation.y,color:r(new Ue(i.color))}}const l=new zt().setFromObject(o);if(l.isEmpty())return null;const h=l.getSize(new oe),u=l.getCenter(new oe);return{size:[h.x,h.y,h.z],base:[u.x,l.min.y,u.z],yaw:0,color:r(new Ue(i.color))}}targetOf(n){const s=n.fx?.target,o=s&&this.host.object(s.to);if(!s||!o)return null;o.updateWorldMatrix(!0,!0);const i=o.getWorldPosition(new oe),r=this.stage?.items.find(m=>m.id===s.to)?.kind==="person";if(s.part==="feet")return[i.x,i.y,i.z];const l=r?o.getObjectByName("head")?.getWorldPosition(new oe):null;if(s.part==="head"&&l)return[l.x,l.y+.1,l.z];if(r&&l){const m=i.clone().lerp(l,.74);return[m.x,m.y,m.z]}const h=new zt().setFromObject(o);if(h.isEmpty())return[i.x,i.y+1,i.z];const u=h.getCenter(new oe);return[u.x,u.y,u.z]}headOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;let i=o.getObjectByName("head");if(i||o.traverse(l=>{!i&&/head/i.test(l.name)&&!/top|end|scale|ref|_end|nub/i.test(l.name)&&(i=l)}),i){const l=i.getWorldPosition(new oe);return[l.x,l.y,l.z]}const r=new zt().setFromObject(o);return r.isEmpty()?null:[(r.min.x+r.max.x)/2,r.max.y-(r.max.y-r.min.y)*.08,(r.min.z+r.max.z)/2]}feetBox=new zt;feetOf(n){const s=n.fx?.attach,o=s&&this.host.object(s.to);if(!o)return null;const i=Qd(o,this.feetBox);return i.isEmpty()?null:[(i.min.x+i.max.x)/2,i.min.y,(i.min.z+i.max.z)/2]}offsetAfterDrag(n,s,o,i){const r=this.stage?.items.find(p=>p.id===n),l=this.host.object(n);if(!r?.fx?.attach||!l?.userData.fxAttached)return null;const h=Do(r,s,o),u=l.userData.fxOffsetYaw??0,m=l.userData.fxOffsetScale??1,d=new oe(l.position.x-i.position[0],l.position.y-i.position[1],l.position.z-i.position[2]).applyAxisAngle(new oe(0,1,0),-u).divideScalar(m),f=p=>+p.toFixed(3);return{position:[f(h.position[0]+d.x),f(h.position[1]+d.y),f(h.position[2]+d.z)],rotation:[0,f(h.yaw+zn.radToDeg(l.rotation.y-i.yaw)),0]}}impacts(n,s){const o=np(n.items,s),i=this.mix.impacts(s);return i.length?[...o,...i]:o}get impactsRev(){return this.mix.rev}pickChunk(n){return this.mix.pick(n)}mixStats(n){return this.mix.stats(n)}update(n,s,o){if(!this.stage)return;const i=[],r=new Set;this.heat=[],Gr.uOcclude.value=Gc[this.stage.lighting?.time??"day"]??Gc.day;for(const l of this.insts.values()){const h=this.host.object(l.item.id);h&&h.traverse(k=>{k.userData.fxMarker&&(k.visible=o)});const u=Fn(l.item,n),m=h?sp(u,s,l.tail):null,d=$o[l.item.fx.preset]?.hides===!0;if(d&&!u.off&&s>=u.start)for(const k of this.hideTargets(l.item))r.add(k);if(m===null||!h||this.only&&!this.only(l.item)){l.group.visible=!1,l.layers.forEach(k=>k.hide());continue}l.group.visible=!0;const f=this.sizeOf(l.item,this.stage),p=this.frameOf(l.item,f,h,n,n.duration>0?s/n.duration:0);p.target=this.targetOf(l.item),p.head=this.headOf(l.item);const b=l.defs.some(k=>k.k==="ghost");p.feet=b?this.feetOf(l.item):null;const g=b&&l.item.fx?.attach&&!l.item.fx.attach.hand&&!l.item.fx.attach.part?this.host.object(l.item.fx.attach.to):void 0;p.shift=g?(()=>{const k=g.getWorldPosition(new oe);return[p.origin[0]-k.x,p.origin[1]-k.y,p.origin[2]-k.z]})():null,p.volume=d?this.volumeOf(l.item):null,p.light=qb[this.stage.lighting?.time??"day"]??1,o&&h.children[0]?.userData.fxMarker;for(const k of l.layers)k.update(m,p);for(const k of l.lights){const C=k.eval(m,p);C&&(C.intensity>.01||(C.fill??0)>.01)&&i.push({pos:C.pos,color:C.color,intensity:C.intensity,fill:C.fill??Vc(C.intensity)})}for(const k of l.heats){const C=k.eval(m,p);C&&C.amount>.01&&this.heat.push(C)}const v=h.children.find(k=>k.userData.fxMarker),y=l.item.fx?.attach;h.userData.fxAttached=!!y&&!(y.hand&&y.tip),y&&!h.userData.fxDragging&&(h.position.set(...p.origin),h.rotation.set(0,p.yaw,0),h.updateMatrixWorld(!0)),v&&v.position.set(0,0,0)}for(const l of this.hidden)r.has(l)||(l.visible=!0);for(const l of r)l.visible=!1;this.hidden=r,i.push(...this.mix.update(n,s).map(l=>({...l,fill:Vc(l.intensity)}))),i.sort((l,h)=>h.intensity-l.intensity),this.light=Xb(i),this.lights.forEach((l,h)=>{const u=i[h];u?(l.position.set(...u.pos),l.color.setRGB(u.color[0],u.color[1],u.color[2],xs),l.intensity=u.intensity):l.intensity=0})}setQuality(n){const s=n==="draft"?ap:1;if(s!==this.share){this.share=s;for(const o of this.insts.values())o.layers.forEach(i=>i.setShare(s));this.mix.setShare(s)}}dispose(){for(const[n,s]of[...this.insts])this.drop(n,s);this.mix.dispose();for(const n of this.lights)n.dispose();this.lights=[],this.pathGroup.clear(),this.group.parent?.remove(this.group,this.pathGroup)}stats(){return[...this.insts.values()].map(n=>({id:n.item.id,name:n.item.name,visible:n.group.visible,budget:n.budget}))}}const Vc=e=>Math.max(0,e-24)/220;function Xb(e){let n=0,s=0,o=[1,1,1],i=null;for(const l of e)n+=l.fill,l.fill>s&&(s=l.fill,o=l.color,i=l.pos);const r=e.filter(l=>l.intensity>.5).slice(0,4).map(l=>({pos:l.pos,color:l.color,intensity:l.intensity}));return{fill:Math.min(2,n),color:o,pos:i,sources:r}}function Vb(e){const n=new Ue(e);return[n.r,n.g,n.b]}ss.fxFactory=(e,n)=>new Ub(e,n);ss.fxPrompt=e=>$g(e.items,e.shots.find(n=>n.id===e.activeShot)??e.shots[0]);ss.codeModel=e=>e.gen?.kind!=="code"?Promise.reject(new Error("not a code model")):kg(e.gen.code);const eu={corner:[.01836,-.09969,.15467],upper:[0,-.09717,.1634],lower:[0,-.11192,.15558],cheek:[.03455,-.07455,.11851],browIn:[.01285,-.00904,.14251],browMid:[.02998,-.00104,.13851],browOut:[.04568,-.00704,.12451],nostril:[.011,-.07855,.1674],lidLow:[.02855,-.04704,.13651],chin:[0,-.14492,.14958]},Nt=!0,ft=(e,n=e,s=e)=>[e,n,s];function tu(e){const n=g=>[Math.abs(g[0]),g[1],g[2]],s=n(e.corner),o=n(e.cheek),i=n(e.browIn),r=n(e.browMid),l=n(e.browOut),h=n(e.nostril),u=n(e.lidLow),m=e.upper,d=e.lower,f=e.chin,p=[(h[0]+s[0])/2+.008,(h[1]+s[1])/2,(h[2]+s[2])/2-.006],b=[r[0],r[1]+.022,r[2]-.006];return{smile:[[s,ft(.024,.022,.018),[.0042,.005,-.0028],Nt],[p,ft(.014,.016,.014),[.0014,.0026,.0014],Nt],[o,ft(.022,.018,.02),[.001,.0034,.002],Nt],[u,ft(.012,.008,.01),[0,.0012,4e-4],Nt],[m,ft(.014,.006,.01),[0,.0011,-4e-4]],[d,ft(.014,.006,.01),[0,-5e-4,-6e-4]]],angry:[[i,ft(.014,.011,.012),[-.0024,-.0032,.0012],Nt],[r,ft(.014,.011,.012),[-8e-4,-.0018,6e-4],Nt],[h,ft(.008),[.0011,7e-4,0],Nt],[s,ft(.013,.011,.012),[-8e-4,-.0014,0],Nt],[m,ft(.011,.006,.009),[0,-5e-4,3e-4]],[d,ft(.011,.006,.009),[0,7e-4,4e-4]],[f,ft(.016,.012,.012),[0,.001,6e-4]]],surprise:[[i,ft(.016,.013,.014),[0,.0042,4e-4],Nt],[r,ft(.017,.014,.014),[0,.005,3e-4],Nt],[l,ft(.015,.013,.013),[0,.0036,0],Nt],[b,ft(.03,.016,.02),[0,.0014,0],Nt],[s,ft(.012,.01,.011),[-.0013,-5e-4,2e-4],Nt]],sad:[[i,ft(.013,.011,.012),[5e-4,.0036,5e-4],Nt],[l,ft(.013,.011,.012),[0,-.0018,0],Nt],[s,ft(.016,.016,.014),[-6e-4,-.0046,-6e-4],Nt],[d,ft(.011,.006,.009),[0,.0011,9e-4]],[f,ft(.016,.012,.012),[0,.0014,8e-4]]],pain:[[i,ft(.013,.011,.012),[-.002,-9e-4,9e-4],Nt],[r,ft(.014,.011,.012),[0,-.0022,5e-4],Nt],[o,ft(.02,.016,.018),[7e-4,.0032,.0014],Nt],[s,ft(.018,.016,.014),[.0044,-.0012,-.0024],Nt],[m,ft(.012,.006,.009),[0,.0019,3e-4]],[h,ft(.009),[9e-4,.0013,0],Nt],[u,ft(.011,.008,.01),[0,.0014,5e-4],Nt]]}}let nu=tu(eu);function Yb(e){nu=tu(e??eu)}const Qb=e=>e>=1?0:(1-e)**4*(1+4*e);function Zb(e,n,s,o,i,r=1){for(const[l,h,u,m]of nu[e])for(const d of m?[1,-1]:[1]){const f=Math.hypot((n-l[0]*d)/h[0],(s-l[1])/h[1],(o-l[2])/h[2]);if(f>=1)continue;const p=Qb(f)*r;i[0]+=u[0]*d*p,i[1]+=u[1]*p,i[2]+=u[2]*p}}function su(e,n,s){const o=e.length/3,i=[];for(const r of Er){const l=new Float32Array(o*3),h=[0,0,0];for(let u=0;u<o;u++){const m=s?s(u):1;m<=0||(h[0]=h[1]=h[2]=0,Zb(r,e[u*3]-n[0],e[u*3+1]-n[1],e[u*3+2]-n[2],h,m),l[u*3]=h[0],l[u*3+1]=h[1],l[u*3+2]=h[2])}i.push(l)}return i}let Js=null,fa=null;const ur=new Set;function Jb(e){const n=new Uint8Array(e,0,8);if(String.fromCharCode(...n.slice(0,4))!=="HQB1")throw new Error("HQ character asset: bad magic");const s=new DataView(e).getUint32(4,!0),o=JSON.parse(new TextDecoder().decode(new Uint8Array(e,8,s)));if(o.version!==Xl)throw new Error(`HQ character asset: version ${o.version}, expected ${Xl}`);const i=8+s+((8+s)%4?4-(8+s)%4:0),r=p=>new Float32Array(e,i+p.at,p.n),l=p=>new Uint8Array(e,i+p.at,p.n),h=p=>new Uint16Array(e,i+p.at,p.n),u=p=>new Uint32Array(e,i+p.at,p.n),m=p=>new Int16Array(e,i+p.at,p.n),d=o.lods.map(p=>({vertices:p.vertices,triangles:p.triangles,position:r(p.position),index:p.index32?u(p.index):h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),region:l(p.region),morphs:p.morphs.map(b=>({data:m(b),scale:b.scale}))})),f=new Map;for(const p of o.hair)f.set(p.id,{id:p.id,kind:p.kind,position:r(p.position),index:h(p.index),skinIndex:l(p.skinIndex),skinWeight:l(p.skinWeight),flow:r(p.flow),bones:p.chains.bones,chains:p.chains.chains});return{version:o.version,license:o.license,bones:o.bones,regions:o.regions,morphs:o.morphs,lods:d,hair:f,bind:o.bind,face:o.face,sources:o.sources??[],bytes:e.byteLength}}function ey(e){Js=Jb(e),Yb(Js.face.landmarks);for(const n of[...ur])n();return Js}const Ur=()=>Js;function ty(e){return Js?Promise.resolve(Js):fa||(fa=fetch(`/${op}`).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.arrayBuffer()}).then(ey).catch(s=>{throw fa=null,s}),fa)}function au(e){return ur.add(e),()=>{ur.delete(e)}}const As=zn.degToRad,Yc=new Qe,ny=new Qe;new rr;function sy(e){const n=ld(e),s=Math.min(1,Math.max(0,(e.blink||0)/100));let o=0,i=0,r=0;for(const l of Er)o+=yi[l].lidU*n[l],i+=yi[l].lidD*n[l],r+=yi[l].jaw*n[l];return o=o-(e.eyePitch||0)*.45,o=o+(46-o)*s,i=i+(4-i)*s,{lidU:Math.max(-14,Math.min(46,o)),lidD:Math.max(-6,Math.min(14,i)),jaw:Math.max(0,Math.min(22,r))}}function Xr(e,n,s={}){const o=new rn,i=new Map;for(const h of Qo(e,n,s)){const u=new $a;u.name=h.name,(h.parent?i.get(h.parent):o).add(u),i.set(h.name,u)}const r=new $a;r.name="pelvis",i.get("torso").add(r),i.set("pelvis",r);for(const[h,,u]of id){const m=new $a;m.name=h,i.get(u).parent.add(m),i.set(h,m)}const l={root:o,body:i.get("torso"),bones:i};return Ho(l,e,n,s),l}function Ho(e,n,s,o={}){const{bones:i}=e;for(const u of Qo(n,s,o)){const m=i.get(u.name);m.position.set(u.p[0],u.p[1],u.p[2]),m.rotation.set(As(u.r[0]),As(u.r[1]),As(u.r[2]),u.order),m.scale.setScalar(u.s)}const r=o.bind?{lidU:0,lidD:0,jaw:0}:sy(s);for(const u of["L","R"])i.get(`lidU${u}`).rotation.set(As(r.lidU),0,0),i.get(`lidD${u}`).rotation.set(As(-r.lidD),0,0);i.get("jaw").rotation.set(As(r.jaw),0,0);const l=o.bind?0:(s.lean||0)+Ga(n).torsoLean,h=i.get("pelvis");h.position.set(0,ip,0),h.rotation.set(As(-rd*l),0,0),h.scale.setScalar(1);for(const[u,m,d]of id){const f=i.get(d),p=i.get(u);p.position.copy(f.position),Yc.copy(m==="pelvis"?h.quaternion:ny.identity()),p.quaternion.copy(Yc).slerp(f.quaternion,.5),p.scale.setScalar(1+(f.scale.x-1)*.5)}}const ga=new Map,ou=e=>(e.userData.shared=!0,e.userData.realDispose=e.dispose.bind(e),e.dispose=()=>{},e);function ay(e,n){return e.morphs.map(s=>{const o=n[s.param]??s.from,i=(o-s.from)/(s.to-s.from);return i>0?Math.min(i,1.6):0})}function as(e){const n=e.bind.head;return[n[0]+Zs[0],n[1]+Zs[1],n[2]+Zs[2]]}function oy(e){const n=e.face.stats,s=.079/n.half,o=.13/(n.crown-n.eye),i=.202/(n.front-n.back);return new At().makeTranslation(0,n.eye-.026/o,n.back+.117/i).multiply(new At().makeScale(1/s,1/o,1/i))}function iy(e,n,s=0){const o=e.lods[s],i=Float32Array.from(o.position);ay(e,n).forEach((h,u)=>{if(!h)return;const m=o.morphs[u],d=h*m.scale;for(let f=0;f<i.length;f++)i[f]+=m.data[f]*d}),n.fem>.3&&ry(e,o,i,Math.min(1,(n.fem-.3)/.4),s);const l=iu(n.fem);if(l>0){const h=lu(e,o),u=[0,0,0];for(let m=0;m<o.vertices;m++){const d=h(m);d&&(ru(e,i[m*3],i[m*3+1],i[m*3+2],l*d,u),i[m*3]+=u[0],i[m*3+1]+=u[1],i[m*3+2]+=u[2])}}return i}const iu=e=>Math.min(1,Math.max(0,(e-.3)/.4));function ru(e,n,s,o,i,r){if(r[0]=r[1]=r[2]=0,!i)return r;const l=as(e),h=e.face.landmarks,u=n-l[0],m=s-l[1],d=o-l[2],f=(C,S,I)=>{const j=Math.min(1,Math.max(0,(I-C)/(S-C)));return j*j*(3-2*j)},p=h.mouthY,b=(h.upper[2]+h.lower[2])/2,g=Math.exp(-((u/.03)**2+((m-p)/.02)**2))*f(b-.035,b-.012,d);r[0]-=u*.1*g,r[1]-=(m-p)*.55*g,r[2]-=.009*g;const v=h.nostril[1]+.004,y=Math.exp(-((u/.024)**2+((m-v)/.022)**2))*f(h.cheek[2]-.005,h.nostril[2]-.02,d);r[0]-=u*.22*y,r[2]-=.003*y;const k=f(h.cheek[1]+.025,h.chin[1],m)*(1-f(h.chin[1]-.01,h.chin[1]-.045,m))*f(-.05,.05,d);return r[0]-=u*.16*k,r[0]*=i,r[1]*=i,r[2]*=i,r}function ry(e,n,s,o,i){const r=s.length/3,l=e.bind.torso,h=e.bones.indexOf("torso"),u=(K,G,_)=>{const ee=Math.min(1,Math.max(0,(_-K)/(G-K)));return ee*ee*(3-2*ee)},m=new Float32Array(r);for(let K=0;K<r;K++){let G=0;for(let ve=0;ve<4;ve++)n.skinIndex[K*4+ve]===h&&(G+=n.skinWeight[K*4+ve]/255);if(G<=0)continue;const _=s[K*3],ee=s[K*3+1]-l[1],Q=s[K*3+2]-l[2];m[K]=o*Math.min(1,G*1.5)*u(.1,.18,ee)*(1-u(.4,.48,ee))*u(0,.05,Q)*(1-u(.15,.21,Math.abs(_)))}const d=new Int32Array(r),f=new Map;for(let K=0;K<r;K++){const G=`${Math.round(s[K*3]*1e4)}|${Math.round(s[K*3+1]*1e4)}|${Math.round(s[K*3+2]*1e4)}`,_=f.get(G);_===void 0?(f.set(G,K),d[K]=K):(d[K]=_,m[_]=Math.max(m[_],m[K]))}for(let K=0;K<r;K++)m[K]=m[d[K]];const p=Array.from({length:r},()=>[]);for(let K=0;K<n.index.length;K+=3)for(let G=0;G<3;G++){const _=d[n.index[K+G]],ee=d[n.index[K+(G+1)%3]];_!==ee&&(m[_]||m[ee])&&(p[_].push(ee),p[ee].push(_))}let b=0,g=0,v=-1;for(let K=0;K<r;K++)m[K]>.5&&Math.abs(s[K*3])>.03&&s[K*3+2]>v&&(v=s[K*3+2],b=Math.abs(s[K*3]),g=s[K*3+1]);const y=K=>m[K]>0&&((Math.abs(s[K*3])-b)/.1)**2+((s[K*3+1]-g)/.11)**2<1,k=[],C=new Uint8Array(r),S=new Set;for(let K=0;K<r;K++)d[K]===K&&p[K].length&&y(K)&&(k.push(K),C[K]=1);for(const K of k)for(const G of p[K])C[G]||S.add(G);const I=[...S],j=Array.from({length:4},()=>[0,0,0,0,0]);for(const K of I){const G=s[K*3+1]-l[1],_=[1,G,G*G,-(s[K*3]**2)],ee=s[K*3+2];for(let Q=0;Q<4;Q++){for(let ve=0;ve<4;ve++)j[Q][ve]+=_[Q]*_[ve];j[Q][4]+=_[Q]*ee}}for(let K=0;K<4;K++)j[K][K]+=1e-6;for(let K=0;K<4;K++)for(let G=K+1;G<4;G++){const _=j[G][K]/j[K][K];for(let ee=K;ee<5;ee++)j[G][ee]-=_*j[K][ee]}const M=[0,0,0,0];for(let K=3;K>=0;K--){let G=j[K][4];for(let _=K+1;_<4;_++)G-=j[K][_]*M[_];M[K]=G/j[K][K]}const T=Math.max(0,M[3]),w=new Float32Array(r);for(let K=0;K<r;K++)w[K]=s[K*3+2]+T*s[K*3]**2;for(let K=0;K<(i===0?1500:400);K++)for(const G of k){let _=0;for(const ee of p[G])_+=w[ee];w[G]=_/p[G].length}for(let K=0;K<r;K++)w[K]=w[d[K]]-T*s[K*3]**2;let E=0,N=0,A=0,O=0;for(const K of k){const G=s[K*3+2]-w[K];if(G<=0||m[K]<.6)continue;O=Math.max(O,G);const _=G*G*G;E+=Math.abs(s[K*3])*_,N+=s[K*3+1]*_,A+=_}if(!A||O<.004)return;const H=.5*(E/A),D=N/A+.012,$=O*.6,W=.07+.3*O,z=W*.9,Y=W*1.2,J=(K,G)=>{const _=G-D,ee=K-H,Q=_/(_<0?z:Y),ve=(ee/W)**2+Q**2;if(ve>=1)return 0;const xe=Q>0?Q/Math.sqrt(ve+1e-9):0;return $*(1-ve)**(.7+1.5*xe*xe)},V=(K,G,_)=>{const ee=Math.max(0,_-Math.abs(K-G))/_;return Math.max(K,G)+ee*ee*_*.25*Math.min(1,Math.min(K,G)/(.3*$))};for(let K=0;K<r;K++){const G=m[K];if(!G)continue;const _=s[K*3],ee=s[K*3+1],Q=V(J(_,ee),J(-_,ee),.03);s[K*3+2]+=(w[K]+Q-s[K*3+2])*G}}function lu(e,n){const s=["head","jaw","headHalf"].map(o=>e.bones.indexOf(o));return o=>{let i=0;for(let r=0;r<4;r++)s.includes(n.skinIndex[o*4+r])&&(i+=n.skinWeight[o*4+r]/255);return Math.min(1,i*1.15)}}function js(e,n,s=0){const o=`${s}|${Wn(n)}`;let i=ga.get(o);if(i)return i;ga.size>48&&(ga.forEach(u=>u.userData.realDispose()),ga.clear());const r=e.lods[s];i=new Tt;const l=iy(e,n,s);i.setAttribute("position",new Pt(l,3)),i.setIndex(new Pt(r.index,1)),i.setAttribute("skinIndex",new bs(r.skinIndex,4)),i.setAttribute("skinWeight",new bs(r.skinWeight,4,!0)),i.computeVertexNormals();const h=lu(e,r);return i.morphAttributes.position=su(l,as(e),h).map(u=>new Pt(u,3)),i.morphTargetsRelative=!0,i.userData.region=r.region,i.userData.lod=s,i.computeBoundingBox(),i.computeBoundingSphere(),ou(i),ga.set(o,i),i}const xa=new Map;function ly(e,n,s,o){const i=js(e,n,s),r=`${s}|${Wn(n)}|${o.skin}|${o.buzz??""}|${o.stubble??""}`;let l=xa.get(r);if(l)return l;xa.size>64&&(xa.forEach(T=>T.userData.realDispose()),xa.clear()),l=new Tt;for(const T of Object.keys(i.attributes))l.setAttribute(T,i.getAttribute(T));l.setIndex(i.getIndex()),l.morphAttributes=i.morphAttributes,l.morphTargetsRelative=!0,l.boundingBox=i.boundingBox,l.boundingSphere=i.boundingSphere,l.userData={...i.userData};const h=i.userData.region,u=i.getAttribute("position"),m=u.count,d=new Float32Array(m*3),f=new Ue(o.skin),p=as(e),b=o.buzz?new Ue(o.buzz):null,g=o.stubble?new Ue(o.stubble):null,v=e.regions,y=e.face.landmarks,k=v.indexOf("lips"),C=v.indexOf("tip"),S=v.indexOf("ear"),I=v.indexOf("nose"),j=v.indexOf("scalp"),M=v.indexOf("stubble");for(let T=0;T<m;T++){let w=1,E=1,N=1;const A=h[T],O=u.getX(T)-p[0],H=u.getY(T)-p[1],D=u.getZ(T)-p[2];if(A===k){const W=Math.max(0,1-Math.abs(H-y.mouthY)/.0022)*Math.max(0,1-Math.abs(O)/(Math.abs(y.corner[0])+.004));w=.9-.4*W,E=.62-.3*W,N=.62-.3*W}(A===S||A===I)&&(w=1,E=.94,N=.92);const $=Math.max(0,1-((Math.abs(O)-Math.abs(y.cheek[0]))**2+(H-y.cheek[1])**2+(D-y.cheek[2])**2)/6e-4);$>0&&(E*=1-.05*$,N*=1-.05*$),A===C&&(w*=1.06),b&&A===j&&(w=w*(1-.85)+b.r/Math.max(.02,f.r)*.85,E=E*(1-.85)+b.g/Math.max(.02,f.g)*.85,N=N*(1-.85)+b.b/Math.max(.02,f.b)*.85),g&&A===M&&(w=w*(1-.4)+g.r/Math.max(.02,f.r)*.4,E=E*(1-.4)+g.g/Math.max(.02,f.g)*.4,N=N*(1-.4)+g.b/Math.max(.02,f.b)*.4),d[T*3]=w,d[T*3+1]=E,d[T*3+2]=N}return l.setAttribute("color",new Pt(d,3)),ou(l),xa.set(r,l),l}const Qc=new Map,cy=(e,n)=>{let s=Qc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Qc.set(e,s)),s},hy=rp.eyeR;function dy(e){return cy(`eye|${e}`,()=>{const n=[0,.09,.16,.2,.27,.36,.44,.5,.53,.58,.75,1,1.35,1.75,2.2,2.7,Math.PI],s=28,o=[],i=[],r=[],l=new Ue(e),h=l.clone().multiplyScalar(.45),u=new Ue("#e9e4dc"),m=new Ue("#0c0a09"),d=l.clone().multiplyScalar(.25);n.forEach((p,b)=>{const g=p<.5?.0011*Math.cos(p/.5*Math.PI/2):0,v=hy+g,y=p<.17?m:p<.42?l.clone().lerp(h,Math.max(0,(.42-p)/.25)*.6):p<.5?d:p<.55?d.clone().lerp(u,.6):u.clone().lerp(new Ue("#e8cfc6"),Math.max(0,p-1.2)/2);for(let k=0;k<=s;k++){const C=k/s*Math.PI*2;o.push(v*Math.sin(p)*Math.cos(C),v*Math.sin(p)*Math.sin(C),v*Math.cos(p)),i.push(y.r,y.g,y.b)}if(b)for(let k=0;k<s;k++){const C=(b-1)*(s+1)+k,S=C+s+1;r.push(C,S,C+1,C+1,S,S+1)}});const f=new Tt;return f.setAttribute("position",new Bt(o,3)),f.setAttribute("color",new Bt(i,3)),f.setIndex(r),f.computeVertexNormals(),f})}const Zc=new Map,Ya=(e,n)=>{let s=Zc.get(e);return s||(s=n(),s.userData.shared=!0,s.dispose=()=>{},Zc.set(e,s)),s},Jc="reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );",uy=`float hqWrap = saturate( ( dot( geometryNormal, directLight.direction ) + 0.5 ) / 1.5 );
284
+ reflectedLight.directDiffuse += ( irradiance + directLight.color * max( 0.0, hqWrap - dotNL ) * vec3( 0.9, 0.36, 0.24 ) ) * BRDF_Lambert( material.diffuseContribution );`;function my(e){return e.onBeforeCompile=n=>{const s=J0.lights_physical_pars_fragment;s.includes(Jc)&&(n.fragmentShader=n.fragmentShader.replace("#include <lights_physical_pars_fragment>",s.replace(Jc,uy)))},e.customProgramCacheKey=()=>"hq-skin-sss-v1",e}function py(e,n=!0){return Ya(`skin|${e}|${n}`,()=>{const s=new Ue(e),o=my(new Ps({color:s,roughness:.52,metalness:0,sheen:.35,sheenRoughness:.45,sheenColor:s.clone().lerp(new Ue("#ffd9c8"),.5),specularIntensity:.55,vertexColors:n}));return o.name="skin",o})}function fy(e){return Ya(`hair|${e}`,()=>{const n=new Ue(e),s=new Ps({color:n,roughness:.42,metalness:0,sheen:.55,sheenRoughness:.35,sheenColor:n.clone().lerp(new Ue("#ffffff"),.35),anisotropy:.75,specularIntensity:.7,side:ys});return s.name="hair",s})}function gy(e){return Ya(`facial|${e}`,()=>{const n=new Ue(e),s=new Ps({color:"#ffffff",vertexColors:!0,alphaHash:!0,roughness:.7,metalness:0,sheen:.25,sheenRoughness:.6,sheenColor:n.clone().lerp(new Ue("#ffffff"),.2),anisotropy:.5,specularIntensity:.3});return s.name="beard",s})}function xy(){return Ya("eye",()=>{const e=new Ps({vertexColors:!0,roughness:.18,clearcoat:1,clearcoatRoughness:.04});return e.name="eyes",e})}function Bi(e,n,s=.6,o=Va){return Ya(`plain|${e}|${n}|${s}|${o}`,()=>{const i=new ns({color:n,roughness:s,side:o});return i.name=e,i})}const eh=[],th=new At,mr=new oe,ba=new oe,nh=new oe;function by(e,n=5,s=.16){let o=e.userData.samples;if(o)return o;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 o=Uint32Array.from(r),e.userData.samples=o,o}function aa(e,n,s,o=!1){const i=e.geometry,r=e.skeleton,l=o?Array.from({length:i.getAttribute("position").count},(d,f)=>f):by(i),h=i.getAttribute("position"),u=i.getAttribute("skinIndex"),m=i.getAttribute("skinWeight");th.copy((s??e).matrixWorld).invert();for(let d=0;d<r.bones.length;d++)(eh[d]??=new At).multiplyMatrices(r.bones[d].matrixWorld,r.boneInverses[d]).premultiply(th);for(const d of l){mr.fromBufferAttribute(h,d),ba.set(0,0,0);for(let f=0;f<4;f++){const p=m.getComponent(d,f);p&&(nh.copy(mr).applyMatrix4(eh[u.getComponent(d,f)]),ba.addScaledVector(nh,p))}n(ba.x,ba.y,ba.z,d)}}function yy(e){return e.computeBoundingBox=function(){const n=(this.boundingBox??=new zt).makeEmpty();aa(this,(s,o,i)=>{n.expandByPoint(mr.set(s,o,i))}),n.expandByScalar(.004)},e.computeBoundingSphere=function(){this.boundingBox||this.computeBoundingBox(),this.boundingBox.getBoundingSphere(this.boundingSphere??=new eg)},e}const an=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)};function vy(e,n){const s=e.face.landmarks,o=e.regions,i=o.indexOf("lips"),r=o.indexOf("stubble"),l=Math.abs(s.corner[0])+.007,h=s.upper[1]+.0025,u=s.nostril[1]-.004,m=(p,b,g,v)=>{const y=Math.abs(p),k=an(.35,1,y/l),C=u-.009*k,S=h-.0045*k-.004*k*k,I=an(0,.0022,b-S)*an(0,.0028,C-b)*an(0,.004,l-y)*an(.11,.13,g);return v===i?I*an(.8,1,y/l):I},d=(p,b,g,v)=>{const y=Math.abs(p),k=.019-.006*an(s.lower[1]-.01,s.lower[1]-.003,b),C=an(0,.003,s.lower[1]-.0045-b)*an(0,.006,b-(s.chin[1]-.016))*an(0,.004,k-y)*an(.1,.125,g);return v===i?0:C},f=(p,b,g,v)=>(v===i?0:v===r?1:0)||m(p,b,g,v);return n==="goatee"?{zone:d,th:p=>.0042*Math.pow(p,.6)}:n==="beard"?{zone:f,th:(p,b,g)=>(.0032+.002*an(s.mouthY,s.chin[1],g))*Math.pow(p,.7)}:{zone:m,th:(p,b)=>(.0032+.001*(1-an(0,.02,Math.abs(b))))*Math.pow(p,.55)}}const ro=new Map;function jy(e,n,s,o){const i=`${Wn(n)}|${s}|${o}`;let r=ro.get(i);if(r)return r;const l=js(e,n,0),h=l.getAttribute("position"),u=l.getAttribute("normal"),m=l.getIndex(),d=as(e),f=l.userData.region,p=h.count,{zone:b,th:g}=vy(e,s),v=new Float32Array(p);for(let Y=0;Y<p;Y++){const J=h.getX(Y)-d[0],V=h.getY(Y)-d[1],K=h.getZ(Y)-d[2];V>.02||V<-.2||K<0||(v[Y]=b(J,V,K,f[Y]))}const y=Array.from({length:p},()=>[]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),K=m.getX(Y+2);(v[J]||v[V]||v[K])&&(y[J].push(V,K),y[V].push(J,K),y[K].push(J,V))}for(let Y=0;Y<2;Y++){const J=Float32Array.from(v);for(let V=0;V<p;V++){if(!y[V].length)continue;let K=0;for(const G of y[V])K+=J[G];J[V]>0&&(v[V]=Math.min(J[V],.5*J[V]+.5*(K/y[V].length)))}}const k=new Int32Array(p).fill(-1),C=[],S=[],I=Y=>(k[Y]<0&&(k[Y]=S.length,S.push(Y)),k[Y]);for(let Y=0;Y<m.count;Y+=3){const J=m.getX(Y),V=m.getX(Y+1),K=m.getX(Y+2);Math.max(v[J],v[V],v[K])<.04||C.push(I(J),I(V),I(K))}if(!C.length)return null;const j=S.length,M=new Float32Array(j*3),T=new Float32Array(j*4),w=new Float32Array(j*4),E=new Uint8Array(j*4),N=new Uint8Array(j*4),A=l.getAttribute("skinIndex"),O=l.getAttribute("skinWeight"),H=new Ue(o),D=H.clone().lerp(new Ue("#8a6a4e"),.22),$=H.clone().multiplyScalar(.7),W=l.morphAttributes.position||[],z=W.map(()=>new Float32Array(j*3));return S.forEach((Y,J)=>{const V=h.getX(Y)-d[0],K=h.getY(Y)-d[1],G=v[Y],_=g(G,V,K)+3e-4;M[J*3]=h.getX(Y)+u.getX(Y)*_,M[J*3+1]=h.getY(Y)+u.getY(Y)*_,M[J*3+2]=h.getZ(Y)+u.getZ(Y)*_;const ee=.5+.5*Math.sin(V*2300+Math.sin(K*900)*2.2)*Math.sin(V*870-K*610),Q=$.clone().lerp(D,Math.pow(ee,2.5)*.85);T[J*4]=Q.r,T[J*4+1]=Q.g,T[J*4+2]=Q.b,T[J*4+3]=an(.04,.55,G);const ve=Math.sign(V)*.55,xe=Math.hypot(ve,1,.25);w[J*4]=ve/xe,w[J*4+1]=-1/xe,w[J*4+2]=.25/xe,w[J*4+3]=1;for(let q=0;q<4;q++)E[J*4+q]=A.getComponent(Y,q),N[J*4+q]=Math.round(O.getComponent(Y,q)*(O.normalized?255:1));z.forEach((q,ue)=>{const pe=W[ue];q[J*3]=pe.getX(Y),q[J*3+1]=pe.getY(Y),q[J*3+2]=pe.getZ(Y)})}),r=new Tt,r.setAttribute("position",new Pt(M,3)),r.setAttribute("color",new Pt(T,4)),r.setAttribute("tangent",new Pt(w,4)),r.setAttribute("skinIndex",new bs(E,4)),r.setAttribute("skinWeight",new bs(N,4,!0)),r.setIndex(C),r.computeVertexNormals(),r.morphAttributes.position=z.map(Y=>new Pt(Y,3)),r.morphTargetsRelative=!0,r.userData.shared=!0,r.userData.facialHair={type:s,triangles:C.length/3,maxLift:Math.max(...S.map((Y,J)=>Math.hypot(M[J*3]-h.getX(Y),M[J*3+1]-h.getY(Y),M[J*3+2]-h.getZ(Y))))},r.dispose=()=>{},ro.size>32&&ro.clear(),ro.set(i,r),r}const ky=cd,$n=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},Rn=Math.PI*2;function wy(e){const n=e.face.stats,s=e.face.landmarks,o=n.eye+.02;return{cy:o,cz:(n.front+n.back)/2,ax:n.half*1.04,ay:n.crown-o,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 Vs=(e,n,s)=>Math.atan2(n,s-e.cz),Wo=(e,n,s,o)=>Math.hypot(n/e.ax,(s-e.cy)/e.ay,(o-e.cz)/e.az);function Fs(e,n,s,o){const i=(o-e.cy)/(n*e.ay),r=n*Math.sqrt(Math.max(0,1-i*i));return[e.ax*r*Math.sin(s),o,e.cz+e.az*r*Math.cos(s)]}const Bs=(e,n)=>s=>n+(e-n)*(.5+.5*Math.cos(s)),sh=new WeakMap;function Lo(e){let n=sh.get(e);if(n)return n;const s=e.lods[0],o=as(e),i=["head","jaw","lidUL","lidUR","lidDL","lidDR"].map(h=>e.bones.indexOf(h)),r=[];for(let h=0;h<s.vertices;h++){let u=0;for(let m=0;m<4;m++)i.includes(s.skinIndex[h*4+m])&&(u+=s.skinWeight[h*4+m]/255);u>=.5&&r.push(s.position[h*3]-o[0],s.position[h*3+1]-o[1],s.position[h*3+2]-o[2])}const l=new Map;for(const[h,u]of e.hair)u.kind==="hair"&&l.set(h,u.position.map((m,d)=>m-o[d%3]));return n={skin:Float32Array.from(r),hair:l},sh.set(e,n),n}const ah=new WeakMap;function My(e,n){let s=ah.get(e);if(s)return s;const o=e.lods[0],i=as(e),r=["torso","pelvis","headHalf"].map(f=>e.bones.indexOf(f)),l=48,h=-.36,u=.01,m=30,d=new Float32Array(l*m);for(let f=0;f<o.vertices;f++){if(!r.includes(o.skinIndex[f*4]))continue;const p=o.position[f*3]-i[0],b=o.position[f*3+1]-i[1],g=o.position[f*3+2]-i[2],v=Math.round((b-h)/u);if(v<0||v>=m)continue;const y=(Math.round(Math.atan2(p,g-n)/Rn*l)%l+l)%l;d[v*l+y]=Math.max(d[v*l+y],Math.hypot(p,g-n))}for(let f=0;f<3;f++){const p=d.slice();for(let b=0;b<m;b++)for(let g=0;g<l;g++)d[b*l+g]=Math.max(p[b*l+g],p[b*l+(g+1)%l],p[b*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 b=0;b<m;b++)for(let g=0;g<l;g++)d[b*l+g]=.5*p[b*l+g]+.25*(p[b*l+(g+1)%l]+p[b*l+(g+l-1)%l])}return s=(f,p)=>{const b=(f/Rn*l+l*4)%l,g=Math.floor(b),v=b-g,y=Math.min(m-1,Math.max(0,Math.round((p-h)/u)));return d[y*l+g]*(1-v)+d[y*l+(g+1)%l]*v},ah.set(e,s),s}function Ts(e,n,s,o,i=.004,r=.0025){const l=Lo(e),h=(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],b=l.skin[d+2];p>s(Vs(n,f,b))-.004&&(u=Math.max(u,Wo(n,f,p,b)+i/h))}const m=o?l.hair.get(o):void 0;if(m)for(let d=0;d<m.length;d+=3){const f=m[d],p=m[d+1],b=m[d+2],g=s(Vs(n,f,b));p>g-.006&&p<g+.012&&(u=Math.max(u,Wo(n,f,p,b)+r/h))}return u}function ms(e,n,s,o,i=!1){const r=[],l=[],h=s?e:e+1;for(const p of[0,1])for(let b=0;b<=n;b++)for(let g=0;g<h;g++)r.push(...o(g/e,b/n,p));const u=(p,b,g)=>p*h*(n+1)+g*h+(s?b%e:b),m=(p,b,g)=>i?l.push(p,g,b):l.push(p,b,g);for(let p=0;p<n;p++)for(let b=0;b<e;b++){const g=T=>[u(T,b,p),u(T,b+1,p),u(T,b+1,p+1),u(T,b,p+1)],[v,y,k,C]=g(0),[S,I,j,M]=g(1);m(v,y,k),m(v,k,C),m(S,j,I),m(S,M,j)}const d=(p,b)=>{const g=u(0,...p),v=u(0,...b),y=u(1,...p),k=u(1,...b);m(g,y,k),m(g,k,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 Tt;return f.setAttribute("position",new Bt(r,3)),f.setIndex(l),f}function Zn(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 h=i.getIndex();for(let u=0;u<h.count;u++)s.push(h.getX(u)+r);i.dispose()}const o=new Tt;return o.setAttribute("position",new Bt(n,3)),o.setIndex(s),o.computeVertexNormals(),o}function oh(e,n,s,o,i,r){const l=(e.ax+e.az)/2;return ms(96,20,!0,(h,u,m)=>{const d=h*Rn,f=m?n:n+s/l,p=o(d),b=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,y=Fs(e,f,d,Math.min(b,e.cy+f*e.ay*Math.sin(v)));if(r){const k=r(d,u);y[0]*=k,y[2]=e.cz+(y[2]-e.cz)*k}return!m&&i&&(y[1]+=i(y)),y})}function ya(e,n,s,o,i,r,l,h,u=!1){const m=(e.ax+e.az)/2,d=n+.6*h/m;return ms(u?72:40,8,u,(f,p,b)=>{const g=o+(i-o)*f,v=s(g),y=Fs(e,d,g,v),k=Math.sin(g)/e.ax,C=Math.cos(g)/e.az,S=Math.hypot(k,C),I=-.003+(r(g)+.003)*p;return[y[0]+k/S*I,v-l(g,Math.max(0,I))-(b?h:0),y[2]+C/S*I]},!0)}function lo(e,n,s,o,i,r,l={}){const h=(e.ax+e.az)/2,u=22,m=14;return ms(64,u,!0,(d,f,p)=>{const b=d*Rn,g=s(b),v=Fs(e,n+(p?0:r/h),b,g),y=v[0],k=v[2]-e.cz;if(f*u<=m){const M=f*u/m,T=i(M)*(l.pleats?.(b,M)??1);return[y*T,g+(o-(p?r:0)-g)*M,e.cz+k*T]}const C=1-(f*u-m)/(u-m),S=i(1)*C*(l.pleats?.(b,1)??1),I=y*S,j=k*S;return[I,o-(p?r:0)-(l.dent?.(I,j)??0)*(1-C*C),e.cz+j]})}function Ki(e,n,s,o,i,r,l=.0015){const h=(e.ax+e.az)/2;return ms(64,2,!0,(u,m,d)=>{const f=u*Rn,p=s(f),b=Fs(e,n+(d?0:l/h),f,p),g=o+(i-o)*m,v=r(g);return[b[0]*v,p+g,e.cz+(b[2]-e.cz)*v]})}function Sy(e,n,s=[14,10]){const o=new Hn(1,s[0],s[1]);return o.scale(...e),o.translate(...n),o.deleteAttribute("uv"),o.deleteAttribute("normal"),o}function Cy(e){const n=e.brow;return{cap:Bs(n+.02,e.eye+.008),helmet:Bs(n+.024,e.eye+.016),police:Bs(n+.022,e.eye+.012),fedora:Bs(n+.026,e.eye+.02),chef:Bs(n+.024,e.eye+.018),ancient:Bs(n+.028,e.eye+.022)}}function Ny(e,n,s){const o=wy(e),i=Cy(o),r=(o.ax+o.az)/2,l=h=>(u,m,d)=>m>h(Vs(o,u,d))-.003;switch(n){case"cap":{const h=i.cap,u=Ts(e,o,h,void 0),m=Math.min(Ts(e,o,h,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=ya(o,m+.02,h,-.8,.8,g=>.075*Math.pow(Math.max(0,1-(g/.8)**2),.4),(g,v)=>.12*v*v+.05*(g/.8)**2*$n(0,.05,v),.004),b=o.cy+(m+d/r)*o.ay;return{main:Zn([oh(o,m,d,h,void 0,f),p]),trim:Sy([.008,.004,.008],[0,b+.0015,o.cz]),cut:(g,v,y)=>{const k=Vs(o,g,y);return v>h(k)-.003-.035*Math.max(0,Math.cos(k))}}}case"helmet":{const h=i.helmet,u=Ts(e,o,h,s,.02,.012),m=.005,d=p=>.007*Math.exp(-((p[0]/.014)**2))*$n(o.cy,o.cy+o.ay*.6,p[1]),f=ya(o,u+m/r,h,0,Rn,p=>.018+.028*Math.max(0,Math.cos(p))**2,(p,b)=>.25*b*b,.004,!0);return{main:Zn([oh(o,u,m,h,d),f]),cut:l(h)}}case"police":{const h=i.police,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.068,d=lo(o,u,h,m,p=>1+.17*$n(.4,1,p),.003),f=ya(o,u+.004/r,h,-1.05,1.05,p=>.05*Math.pow(Math.max(0,1-(p/1.05)**2),.6),(p,b)=>.3*b,.003);return{main:Zn([d,f]),trim:Ki(o,u+.002/r,h,.004,.02,()=>1),cut:l(h)}}case"fedora":{const h=i.fedora,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.09,d=lo(o,u,h,m,p=>1-.07*p,.003,{dent:p=>.016*Math.exp(-((p/.022)**2)),pleats:(p,b)=>1-.05*$n(.6,1,b)*Math.max(0,Math.cos(p))**4}),f=ya(o,u+.003/r,h,0,Rn,p=>.055+.008*Math.cos(p)**2,(p,b)=>.18*b*b*Math.cos(p)**2-.3*b*b*Math.sin(p)**2,.003,!0);return{main:Zn([d,f]),trim:Ki(o,u+.0035/r,h,.002,.022,p=>1-.07*(p/.09)),cut:l(h)}}case"chef":{const h=i.chef,u=Ts(e,o,h,s,.005),m=Math.max(h(0),h(Math.PI))+.17;return{main:lo(o,u,h,m,f=>f<.42?1.01:1.01+.3*Math.sin(Math.min(1,(f-.42)/.4)*Math.PI/2)-.12*$n(.85,1,f),.003,{pleats:(f,p)=>1+.03*$n(.42,.6,p)*Math.sin(f*16)}),cut:l(h)}}case"ancient":{const h=i.ancient,u=Ts(e,o,h,s,.006),m=Math.max(h(0),h(Math.PI))+.085,d=lo(o,u,h,m,g=>1+.04*g,.003,{dent:(g,v)=>-.012*Math.exp(-((g/.05)**2+((v-o.cz)/.06)**2))}),f=h(Math.PI)+.055,p=o.cz-o.az*u*.7,b=[-1,1].map(g=>{const v=new vs(1,1,1,20);return v.rotateX(Math.PI/2),v.scale(.055,.017,.003),v.rotateZ(g*.22),v.translate(g*(o.ax*u+.045),f,p),v.deleteAttribute("uv"),v.deleteAttribute("normal"),v});return{main:Zn([d,...b]),trim:Ki(o,u+.0035/r,h,.002,.018,()=>1),cut:l(h)}}case"nonla":{const m=Lo(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]-o.cz)*.15/.235+.008);const p=ms(56,10,!0,(g,v,y)=>{const k=g*Rn,C=.235*v,S=f-.15*v-(y?.003:0);return[C*Math.sin(k),S,o.cz+C*Math.cos(k)]},!0),b=new Wr(.235,.0035,6,56);return b.rotateX(Math.PI/2),b.translate(0,f-.15-.0015,o.cz),b.deleteAttribute("uv"),b.deleteAttribute("normal"),{main:Zn([p]),trim:Zn([b]),cut:null}}case"moto":{const h={...o,cy:o.eye-.004,ay:o.crown-o.eye+.004,ax:o.ax*1.1},u=g=>$n(1.25,1.05,Math.abs(g)),m=g=>-.118+.012*Math.cos(g)**2+(o.brow+.016+.118)*u(g),d=Lo(e);let f=1;for(let g=0;g<d.skin.length;g+=3){const v=d.skin[g],y=d.skin[g+1],k=d.skin[g+2];y>m(Vs(h,v,k))-.01&&(f=Math.max(f,Wo(h,v,y,k)+.025/r))}const p=ms(96,18,!0,(g,v,y)=>{const k=g*Rn-Math.PI,C=y?f:f+.006/r,S=m(k),I=Math.asin(Math.max(-1,Math.min(1,(S-h.cy)/(C*h.ay)))),j=I+(Math.PI/2-I)*v;return Fs(h,C,k,h.cy+C*h.ay*Math.sin(j))}),b=ya(h,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:Zn([p,b]),cut:"hide"}}case"hijab":{const h={...o,cy:o.eye-.035,ay:o.crown-o.eye+.035,ax:o.ax*1.12,az:o.az*1.04},u=e.face.landmarks,m=u.chin[1],d=S=>$n(1,.82,Math.abs(S)),f=S=>m-.012+(o.brow+.03-m+.012)*d(S)-.05*$n(1.4,2.6,Math.abs(S)),p=Lo(e);let b=1;for(let S=0;S<p.skin.length;S+=3){const I=p.skin[S],j=p.skin[S+1],M=p.skin[S+2],T=Vs(h,I,M);j>f(T)-.004&&d(T)<.98&&(b=Math.max(b,Wo(h,I,j,M)+.008/r))}const g=ms(96,18,!0,(S,I,j)=>{const M=S*Rn-Math.PI,T=j?b:b+.003/r,w=f(M),E=Math.asin(Math.max(-1,Math.min(1,(w-h.cy)/(T*h.ay)))),N=E+(Math.PI/2-E)*I;return Fs(h,T,M,h.cy+T*h.ay*Math.sin(N))}),v=S=>Math.min(m+.004,f(S)+.02),y=-.27,k=My(e,o.cz),C=ms(72,12,!0,(S,I,j)=>{const M=S*Rn-Math.PI,T=v(M),w=Fs(h,b+.004/r,M,T),E=T+(y-T)*I,N=Math.hypot(w[0],w[2]-o.cz),A=Math.max(N*(1+.5*I*I),(k(M,E)+.012)*$n(0,.4,I))-(j?.003:0);return[Math.sin(M)*A,E,o.cz+Math.cos(M)*A]});return{main:Zn([g,C]),cut:"hide"}}}return null}const va=new Map;function cu(e,n,s){const o=`${e.bytes}|${n}|${s??""}`;if(!va.has(o)){va.size>48&&va.clear();const i=Ny(e,n,s);for(const r of[i?.main,i?.trim])r&&(r.computeVertexNormals(),r.userData.shared=!0,r.dispose=()=>{});va.set(o,i)}return va.get(o)}function Ay(e,n,s){return cu(e,n,s)?.cut??null}const ih=(e,n)=>"#"+new Ue(e).lerp(new Ue(n>0?"#ffffff":"#000000"),Math.abs(n)).getHexString(),Ty=e=>{const n=new Ue(e);return n.r*.3+n.g*.59+n.b*.11>.5?ih(e,-.55):ih(e,.65)},co={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 Ly(e,n,s){const o=cu(e,n.type,s);if(!o)return[];const i=[{geometry:o.main,mat:(co[n.type]??co.cap)(n.color),slot:"hat"}],r=n.type==="cap"?n.color:n.color2??(n.type==="police"?"#d8b64a":Ty(n.color));return o.trim&&i.push({geometry:o.trim,mat:n.type==="police"||n.type==="ancient"?`sol:${r}:0.35:0.6`:(co[n.type]??co.cap)(r),slot:"hat"}),i}const ho=new Map,Hi=new Map;function Ey(e,n){let s=Hi.get(n.id);if(s!==void 0)return s;const o=e.morphs.findIndex(p=>p.name==="femFace"),i=e.lods[0];if(o<0)return Hi.set(n.id,null),null;const r=i.morphs[o],l=i.position,h=n.position,u=h.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 b=0;b<3;b++)m[b]=Math.min(m[b],h[p*3+b]),d[b]=Math.max(d[b],h[p*3+b]);const f=[];for(let p=0;p<i.vertices;p++)[0,1,2].every(b=>l[p*3+b]>m[b]-.015&&l[p*3+b]<d[b]+.015)&&f.push(p);s=new Float32Array(u*3);for(let p=0;p<u;p++){let b=-1,g=1/0;for(const v of f){const y=(l[v*3]-h[p*3])**2+(l[v*3+1]-h[p*3+1])**2+(l[v*3+2]-h[p*3+2])**2;y<g&&(g=y,b=v)}if(b>=0)for(let v=0;v<3;v++)s[p*3+v]=r.data[b*3+v]*r.scale}return Hi.set(n.id,s),s}function Iy(e,n){const s=as(e),o=Float32Array.from(n),i=(l,h,u,m)=>{const d=l<h?(l-h+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<o.length;l+=3){const h=o[l]-s[0],u=Math.abs(h);if(u<.05)continue;const m=i(o[l+1]-s[1],-.072,-.016,.015)*i(o[l+2]-s[2],.025,.075,.02),d=.091+(u-.072)*.3;m>0&&u<d&&(o[l]=s[0]+Math.sign(h)*(u+(d-u)*m),r=!0)}return r?o:null}function Ry(e,n,s,o,i=0){const r=i>0&&(n.kind==="brows"||n.kind==="teeth"||n.kind==="lashes")?Ey(e,n):null,l=r?Math.round(i*100)/100:0,h=`${n.id}|${o}|${l}`;let u=ho.get(h);if(u)return u;ho.size>96&&ho.clear();const m=r?n.position.map((y,k)=>y+r[k]*l):n.position,d=r?iu(l):0;if(d>0){const y=[0,0,0];for(let k=0;k<m.length;k+=3)ru(e,m[k],m[k+1],m[k+2],d,y),m[k]+=y[0],m[k+1]+=y[1],m[k+2]+=y[2]}const f=n.kind==="hair"?Iy(e,n.position):null;u=new Tt,u.setAttribute("position",new Pt(f??m,3)),u.setAttribute("skinIndex",new bs(n.skinIndex,4)),u.setAttribute("skinWeight",new bs(n.skinWeight,4,!0));const p=n.position.length/3,b=new Float32Array(p*4);for(let y=0;y<p;y++)b[y*4]=n.flow[y*3],b[y*4+1]=n.flow[y*3+1],b[y*4+2]=n.flow[y*3+2],b[y*4+3]=1;u.setAttribute("tangent",new Pt(b,4));const g=as(e);let v=n.index;if(typeof s=="function"){const y=[],k=C=>s(m[C*3]-g[0],m[C*3+1]-g[1],m[C*3+2]-g[2]);for(let C=0;C<n.index.length;C+=3)k(n.index[C])&&k(n.index[C+1])&&k(n.index[C+2])||y.push(n.index[C],n.index[C+1],n.index[C+2]);v=y}return u.setIndex(Array.from(v)),u.computeVertexNormals(),(n.kind==="beard"||n.kind==="brows")&&(u.morphAttributes.position=su(m,g).map(y=>new Pt(y,3)),u.morphTargetsRelative=!0),u.userData.shared=!0,u.dispose=()=>{},ho.set(h,u),u}function Fy(e,n,s,o){const i=[],r=s.hat?Ay(e,s.hat.type,s.hair?.style):null,l=s.hat?`hat:${s.hat.type}`:"",h=s.hair?.color??"#2a211b",u=(f,p,b,g)=>{const v=e.hair.get(f);if(!v||g==="hide")return;const y=n.bones.get("head"),k=new Map,C=v.chains.length?{kind:"hair",anchor:"head",chains:[]}:null;for(const[S,I]of v.chains.entries()){let j=y,M=[-Zs[0],-Zs[1],-Zs[2]];const T=[],w=[];I.forEach((E,N)=>{const A=new $a;A.name=E.name,A.position.set(E.at[0]-M[0],E.at[1]-M[1],E.at[2]-M[2]),j.add(A),n.bones.set(E.name,A),T.push(A);const O=as(e);k.set(E.name,new At().makeTranslation(-(O[0]+E.at[0]),-(O[1]+E.at[1]),-(O[2]+E.at[2])));const H=I[N+1];w.push(H?new oe(H.at[0]-E.at[0],H.at[1]-E.at[1],H.at[2]-E.at[2]):w[N-1]?.clone()??new oe(0,-.08,0)),j=A,M=E.at}),C.chains.push({bones:T,rest:w,kind:"hair",stiffness:f==="long"?.55:.4,collide:!0,side:S})}i.push({geometry:Ry(e,v,g,g?l:"",o.fem),material:typeof p=="string"?fy(p):p,slot:b,bones:v.bones,inverses:k,chains:C,near:v.kind==="lashes"||v.kind==="teeth"||v.kind==="brows"})},m=s.hair?.style;if(m&&m!=="none"&&m!=="buzz"&&u(m,h,"hair",r),u("brows",Py(s.hair&&s.hair.style!=="none"?h:s.beard?.color??"#2a211b",o.skin),"hair",null),s.beard&&s.beard.type!=="none"){const f=jy(e,o,s.beard.type,s.beard.color);f&&i.push({geometry:f,material:gy(s.beard.color),slot:"beard",bones:[...ky],inverses:new Map,chains:null,near:!1})}u("lashes",Bi("lashes","#17110d",.75,ys),"lashes",null);const d=Bi("teeth","#e6dfd2",.3);return u("teeth-upper",d,"teeth",null),u("teeth-lower",d,"teeth",null),u("tongue",Bi("tongue","#a5525a",.45),"mouth",null),i}function Py(e,n="#c9956f"){const s=new Ue(e);return"#"+(s.getHSL({h:0,s:0,l:0}).l>.7?s.multiplyScalar(.75):s.lerp(new Ue(n),.1)).getHexString()}const Vt=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},ja=-.1,Go={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}}},wn={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}}},qo={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}}},$y=e=>!!e.top||!!(e.outer&&qo[e.outer.type]),Dy=e=>!!e.bottom||!!(e.top&&Go[e.top.type]?.loose&&Go[e.top.type].loose.length>.4)||!!(e.outer&&qo[e.outer.type]?.loose),Oy=e=>e.fabric??hp[e.type]??"cotton",st={torso:0,arm:1,hand:2,leg:3,foot:4,head:5},uo=new Map;function Vr(e,n,s){const o=e.lods[n],i=`${n}|${Wn(s)}`;let r=uo.get(i);if(r)return r;uo.size>48&&uo.clear();const l=hd(Qo({...s,head:1,posture:0},Ir,{bind:!0})),h=new Proxy(e.bind,{get:(f,p)=>l.get(p)?.t??f[p]}),u=o.vertices,m=js(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,b)=>{const g=[b[0]-p[0],b[1]-p[1],b[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]],b=p[0]<0?"L":"R",g=e.bones[o.skinIndex[f*4]];r.cat[f]=/^(arm|fore)/.test(g)?st.arm:/^(wrist|thumb|index|middle|ring|pinky)/.test(g)?st.hand:/^(thigh|shin)/.test(g)?st.leg:/^foot/.test(g)?st.foot:/^(head|jaw|lid)/.test(g)?st.head:st.torso,r.yt[f]=p[1]-h.torso[1],r.x[f]=p[0],r.z[f]=p[2];const v=h[`arm${b}`],y=h[`fore${b}`],k=h[`wrist${b}`];let C=d(p,v,y);C>1&&(C=1+d(p,y,k),C>2&&(C=2+Math.hypot(p[0]-k[0],p[1]-k[1],p[2]-k[2])/.19)),r.armT[f]=C;const S=h[`thigh${b}`],I=h[`shin${b}`],j=h[`foot${b}`];let M=d(p,S,I);M>1&&(M=1+d(p,I,j)),r.legT[f]=M,r.footY[f]=p[1]-j[1],r.cat[f]===st.foot&&(r.sole=Math.max(r.sole,-r.footY[f]))}return uo.set(i,r),r}function _y(e,n,s){const o=Vt(-.015,.05,s),i=Math.abs(n);switch(e){case"crew":return .565-.045*o*Math.max(0,1-(i/.07)**2);case"collar":return .6-.065*o*Math.max(0,1-i/.035);case"v":return .565-.13*o*Math.max(0,1-i/.08);case"deepv":return .57-.24*o*Math.max(0,1-i/.1);case"scoop":return .53-.1*o*Math.max(0,1-(i/.11)**2);case"high":return .62-.02*o}}function rh(e,n,s=.134){return o=>{const i=e.cat[o];if(i===st.head||i===st.foot)return-1;if(i===st.arm||i===st.hand)return n.sleeve<0?Math.min(-.01,s-Math.abs(e.x[o])):(n.sleeve-e.armT[o])*.29;let r=Math.min(e.yt[o]-n.hem,_y(n.neck,e.x[o],e.z[o])-e.yt[o]);return n.sleeve<0&&(r=Math.min(r,s-Math.abs(e.x[o])+2.5*Math.max(0,.3-e.yt[o]))),r}}function zy(e,n){return s=>{const o=e.cat[s];if(o===st.head||o===st.arm||o===st.hand)return-1;const i=n.waist-e.yt[s];return o===st.torso?i:Math.min(i,(n.leg-e.legT[s])*.43)}}const ka=new Map;function By(e,n,s,o){const{out:i,nv:r,idx:l}=o,h=new Map,u=new Map;for(let O=0;O<l.length;O+=3)for(let H=0;H<3;H++){const D=l[O+H],$=l[O+(H+1)%3],W=Math.min(D,$)*r+Math.max(D,$);h.set(W,(h.get(W)??0)+1),u.set(W,[D,$])}const m=new Map;for(const[O,H]of h)if(H===1){const[D,$]=u.get(O);m.set($,D)}let d=1+s.hem,f=null;const p=new Set;for(const O of m.keys()){if(p.has(O))continue;const H=[];let D=O;for(;!p.has(D)&&m.has(D);)p.add(D),H.push(D),D=m.get(D);if(H.length<12)continue;const $=H.map(z=>i[z*3+1]),W=H.map(z=>i[z*3]);if(Math.max(...$.map(z=>Math.abs(z-d)))<.05&&Math.min(...W)<-.05&&Math.max(...W)>.05){f=H;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 b=120,g=.01,v=Math.ceil(s.length/g)+2,y=new Float32Array(b*v);for(let O=0;O<s.cat.length;O++){const H=s.cat[O];if(H===st.arm||H===st.hand||H===st.head)continue;const D=n[O*3+1],$=Math.round((d-D)/g);if($<0||$>=v)continue;const W=n[O*3],z=n[O*3+2],Y=(Math.round(Math.atan2(W,z)/(Math.PI*2)*b)%b+b)%b;y[$*b+Y]=Math.max(y[$*b+Y],Math.hypot(W,z))}for(let O=0;O<v;O++)for(let H=0;H<4;H++){const D=y.slice(O*b,(O+1)*b);for(let $=0;$<b;$++)y[O*b+$]=Math.max(D[$],(D[($+1)%b]+D[($+b-1)%b])/2*.998)}{const O=y.slice(),H=(D,$)=>D<0||D>=v?0:O[D*b+($+b)%b];for(let D=0;D<v;D++)for(let $=0;$<b;$++){let W=0;for(let z=-1;z<=1;z++)for(let Y=-1;Y<=1;Y++)W=Math.max(W,H(D+z,$+Y));y[D*b+$]=W}}const k=(O,H)=>{const D=(O/(Math.PI*2)*b+b*4)%b,$=Math.floor(D),W=D-$,z=Math.min(v-1,Math.max(0,Math.round(H/g)));return y[z*b+$]*(1-W)+y[z*b+($+1)%b]*W},C=e.bones.indexOf("pelvis"),S=e.bones.indexOf("thighHalfL"),I=e.bones.indexOf("thighHalfR"),j=e.bones.indexOf("thighL"),M=e.bones.indexOf("thighR"),T=f.length,w=Math.max(3,Math.round(s.length/.012)),E=[...i],N=f.map(O=>Math.hypot(i[O*3],i[O*3+2]));let A=f.slice();for(let O=1;O<=w;O++){const H=s.length*O/w,D=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]);D.push(Math.max(N[W]-s.tuck*(s.length/w),k(Y,H)+o.th[z]+.004+.01*Math.min(1,H/.012)))}for(let W=0;W<3;W++){const z=D.slice();for(let Y=0;Y<T;Y++)D[Y]=Math.max(z[Y],(z[(Y+1)%T]+z[(Y+T-1)%T])/2)}const $=[];for(let W=0;W<T;W++){const z=f[W],Y=Math.atan2(i[z*3],i[z*3+2]),J=D[W]*(1+s.flare*H),V=E.length/3;E.push(Math.sin(Y)*J,d-H,Math.cos(Y)*J),o.base.push(Math.sin(Y)*(J-o.th[z]),d-H,Math.cos(Y)*(J-o.th[z])),o.nrm.push(Math.sin(Y),0,Math.cos(Y)),o.th.push(o.th[z]);const K=Math.min(1,H/.03),G=i[z*3],_=Vt(.015,.07,Math.abs(G)),ee=.45*_,Q=(Math.cos(Y)>0?.55:.3)*Vt(.1,.7,Math.abs(Math.cos(Y))),ve=Vt(-.04,.04,G),xe=new Map;for(let U=0;U<4;U++){const le=o.sw[z*4+U];le&&xe.set(o.si[z*4+U],(xe.get(o.si[z*4+U])??0)+le*(1-K))}xe.set(C,(xe.get(C)??0)+K*(1-ee-Q));const q=G<0?S:I;if(xe.set(q,(xe.get(q)??0)+K*ee),Q>0)for(const[U,le]of[[j,1-ve],[M,ve]])le>0&&xe.set(U,(xe.get(U)??0)+K*Q*le);const ue=[...xe].sort((U,le)=>le[1]-U[1]).slice(0,4);let pe=0;for(const[,U]of ue)pe+=U;for(let U=0;U<4;U++)o.si.push(ue[U]?.[0]??0),o.sw.push(ue[U]?ue[U][1]/pe:0);o.col.length&&o.col.push(o.col[z*3],o.col[z*3+1],o.col[z*3+2]),$.push(V),N[W]=D[W]}for(let W=0;W<T;W++){const z=A[W],Y=A[(W+1)%T],J=$[W],V=$[(W+1)%T];l.push(z,Y,V,z,V,J)}A=$}return{out:Float32Array.from(E),nv:E.length/3}}function Ky(e,n,s,o,i,r,l={}){const h=`${s}|${Wn(n)}|${o}`;let u=ka.get(h);if(u)return u;ka.size>96&&(ka.forEach(U=>U.geometry.userData.realDispose?.()),ka.clear());const m=e.lods[s],d=js(e,n,s),f=d.getAttribute("position").array,p=d.getAttribute("normal").array,b=m.vertices,g=new Float32Array(b),v=new Uint8Array(b);for(let U=0;U<b;U++){let le=i(U);Math.abs(le)<.0012&&(le=le>=0?.0012:-.0012),g[U]=le,le>.028&&(v[U]=1)}const y=[],k=[],C=[],S=[],I=[],j=[],M=[],T=new Int32Array(b).fill(-1),w=new Map,E=U=>{const le=new Map;for(let ce=0;ce<4;ce++){const Le=m.skinWeight[U*4+ce];Le&&le.set(m.skinIndex[U*4+ce],Le/255)}return le},N=(U,le,ce,Le,je)=>{const ie=k.length/3;k.push(U[0],U[1],U[2]),y.push(le[0],le[1],le[2]),C.push(Le);const Me=[...ce].sort((Se,he)=>he[1]-Se[1]).slice(0,4);let Ee=0;for(const[,Se]of Me)Ee+=Se;for(let Se=0;Se<4;Se++)S.push(Me[Se]?.[0]??0),I.push(Me[Se]?Me[Se][1]/Ee:0);return je&&j.push(...je),ie},A=U=>(T[U]<0&&(T[U]=N([f[U*3],f[U*3+1],f[U*3+2]],[p[U*3],p[U*3+1],p[U*3+2]],E(U),r(U),l.colors?.(U))),T[U]),O=(U,le)=>{const ce=U<le?U*b+le:le*b+U;let Le=w.get(ce);if(Le!==void 0)return Le;const je=g[U]/(g[U]-g[le]),ie=(Fe,Te)=>Fe[U*3+Te]+(Fe[le*3+Te]-Fe[U*3+Te])*je,Me=E(U),Ee=E(le),Se=new Map;for(const[Fe,Te]of Me)Se.set(Fe,Te*(1-je));for(const[Fe,Te]of Ee)Se.set(Fe,(Se.get(Fe)??0)+Te*je);const he=l.colors?.(U),be=l.colors?.(le);return Le=N([ie(f,0),ie(f,1),ie(f,2)],[ie(p,0),ie(p,1),ie(p,2)],Se,r(U)*(1-je)+r(le)*je,he&&be?[he[0]*(1-je)+be[0]*je,he[1]*(1-je)+be[1]*je,he[2]*(1-je)+be[2]*je]:void 0),w.set(ce,Le),Le},H=m.index;for(let U=0;U<H.length;U+=3){const le=[H[U],H[U+1],H[U+2]],ce=le.map(Se=>g[Se]>0),Le=ce.filter(Boolean).length;if(!Le)continue;if(Le===3){M.push(A(le[0]),A(le[1]),A(le[2]));continue}let je=0;Le===1?je=ce.indexOf(!0):je=ce.indexOf(!1);const ie=le[je],Me=le[(je+1)%3],Ee=le[(je+2)%3];if(Le===1)M.push(A(ie),O(ie,Me),O(ie,Ee));else{const Se=O(ie,Me),he=O(ie,Ee);M.push(Se,A(Me),A(Ee),Se,A(Ee),he)}}let D=k.length/3;const $=Array.from({length:D},()=>[]);for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3];$[ce].push(Le),$[Le].push(ce)}if(l.smoothBase){const U=l.smoothBaseAbove,le=l.smoothBaseLift,ce=Se=>U==null?1:Vt(U,U+.1,k[Se*3+1])*Vt(.15,.45,y[Se*3+2]),Le=Float64Array.from({length:D},(Se,he)=>ce(he)),je=Float64Array.from({length:D},(Se,he)=>le==null?0:1-Vt(le,le+.1,k[he*3+1])),ie=Se=>{const he=Float64Array.from(k);for(let be=0;be<D;be++){if(!$[be].length||!Le[be])continue;let Fe=0,Te=0,_e=0;for(const re of $[be])Fe+=k[re*3],Te+=k[re*3+1],_e+=k[re*3+2];const ze=1/$[be].length,Be=Se*Le[be];let Ze=(Fe*ze-k[be*3])*Be,F=(Te*ze-k[be*3+1])*Be,te=(_e*ze-k[be*3+2])*Be;const Z=Ze*y[be*3]+F*y[be*3+1]+te*y[be*3+2];Z<0&&je[be]&&(Ze-=y[be*3]*Z*je[be],F-=y[be*3+1]*Z*je[be],te-=y[be*3+2]*Z*je[be]),he[be*3]=k[be*3]+Ze,he[be*3+1]=k[be*3+1]+F,he[be*3+2]=k[be*3+2]+te}for(let be=0;be<he.length;be++)k[be]=he[be]};for(let Se=0;Se<l.smoothBase;Se++)ie(.5);const Me=new Tt;Me.setAttribute("position",new Bt(k,3)),Me.setIndex(M),Me.computeVertexNormals();const Ee=Me.getAttribute("normal");for(let Se=0;Se<D;Se++)y[Se*3]=Ee.getX(Se),y[Se*3+1]=Ee.getY(Se),y[Se*3+2]=Ee.getZ(Se);Me.dispose()}let W=new Float32Array(D*3);for(let U=0;U<D;U++)for(let le=0;le<3;le++)W[U*3+le]=k[U*3+le]+y[U*3+le]*C[U];const z=l.smooth??4,Y=new Map;for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3],je=Math.min(ce,Le)*D+Math.max(ce,Le);Y.set(je,(Y.get(je)??0)+1)}const J=Array.from({length:D},()=>[]);for(const[U,le]of Y)if(le===1){const ce=Math.floor(U/D),Le=U%D;J[ce].push(Le),J[Le].push(ce)}for(let U=0;U<z+8;U++){const le=Float32Array.from(W);for(let ce=0;ce<D;ce++){const Le=J[ce].length?J[ce]:$[ce];if(!Le.length||U>=z&&!J[ce].length)continue;let je=0,ie=0,Me=0;for(const Se of Le)je+=W[Se*3],ie+=W[Se*3+1],Me+=W[Se*3+2];const Ee=1/Le.length;le[ce*3]=W[ce*3]*.5+je*Ee*.5,le[ce*3+1]=W[ce*3+1]*.5+ie*Ee*.5,le[ce*3+2]=W[ce*3+2]*.5+Me*Ee*.5}for(let ce=0;ce<D;ce++){const Le=le[ce*3]-k[ce*3],je=le[ce*3+1]-k[ce*3+1],ie=le[ce*3+2]-k[ce*3+2],Me=Le*y[ce*3]+je*y[ce*3+1]+ie*y[ce*3+2],Ee=C[ce]*.85;if(Me<Ee)for(let Se=0;Se<3;Se++)le[ce*3+Se]+=y[ce*3+Se]*(Ee-Me)}W.set(le)}if(l.band){const U=By(e,f,l.band,{out:W,base:k,nrm:y,th:C,si:S,sw:I,col:j,idx:M,nv:D});U&&(W=U.out,D=U.nv)}if(l.sole)for(let U=0;U<D;U++){const le=W[U*3+1];if(le<l.sole.y+.02){const ce=Vt(l.sole.y+.02,l.sole.y-.005,le);W[U*3+1]=le-l.sole.th*ce,W[U*3+1]<l.sole.y-l.sole.th&&(W[U*3+1]=l.sole.y-l.sole.th)}}const V=new Map;for(let U=0;U<M.length;U+=3)for(let le=0;le<3;le++){const ce=M[U+le],Le=M[U+(le+1)%3],je=Math.min(ce,Le)*D+Math.max(ce,Le);V.has(je)?V.delete(je):V.set(je,[ce,Le])}const K=[],G=new Map,_=U=>{let le=G.get(U);return le===void 0&&(le=D+K.length/3,K.push(k[U*3]+y[U*3]*C[U]*.12,k[U*3+1]+y[U*3+1]*C[U]*.12,k[U*3+2]+y[U*3+2]*C[U]*.12),G.set(U,le)),le};for(const[U,le]of V.values()){const ce=_(U),Le=_(le);M.push(le,U,ce,le,ce,Le)}const ee=D+K.length/3,Q=[...G.keys()],ve=new Float32Array(ee*3);ve.set(W),ve.set(K,D*3);const xe=new Uint8Array(ee*4),q=new Float32Array(ee*4),ue=j.length?new Float32Array(ee*3):null;xe.set(S),q.set(I),ue?.set(j),Q.forEach((U,le)=>{for(let ce=0;ce<4;ce++)xe[(D+le)*4+ce]=S[U*4+ce],q[(D+le)*4+ce]=I[U*4+ce];if(ue)for(let ce=0;ce<3;ce++)ue[(D+le)*3+ce]=j[U*3+ce]});const pe=new Tt;return pe.setAttribute("position",new Pt(ve,3)),pe.setAttribute("skinIndex",new bs(xe,4)),pe.setAttribute("skinWeight",new Pt(q,4)),ue&&pe.setAttribute("color",new Pt(ue,3)),pe.setIndex(M),pe.computeVertexNormals(),pe.userData.shared=!0,pe.userData.realDispose=pe.dispose.bind(pe),pe.dispose=()=>{},u={geometry:pe,covered:v},ka.set(h,u),u}const _a=8;function hu(e,n,s=_a){const o=Math.hypot(e[0],e[1],e[2])||1,i=e[0]/o,r=e[1]/o,l=e[2]/o;let h=1-i*i,u=-i*r,m=-i*l;const d=Math.hypot(h,u,m);d<1e-4?(h=-l*i,u=-l*r,m=1-l*l):(h/=d,u/=d,m/=d);const f=r*m-l*u,p=l*h-i*m,b=i*u-r*h,g=Math.atan2(n[0]*f+n[1]*p+n[2]*b,n[0]*h+n[1]*u+n[2]*m);return(Math.round(g/(Math.PI*2)*s)%s+s)%s}const mo=new Map;function Hy(e,n){const s=Wn(n);let o=mo.get(s);if(o)return o;const i=Vr(e,0,n),r=js(e,n,0).getAttribute("position").array,l=hd(Qo({...n,head:1,posture:0},Ir,{bind:!0})),h=12,u=_a;o={L:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)},R:{thigh:new Float32Array(h*u),shin:new Float32Array(h*u)}};for(const m of["L","R"])for(const[d,f,p]of[["thigh",`thigh${m}`,`shin${m}`],["shin",`shin${m}`,`foot${m}`]]){const b=l.get(f).t,g=l.get(p).t,v=[g[0]-b[0],g[1]-b[1],g[2]-b[2]],y=v[0]**2+v[1]**2+v[2]**2,k=o[m][d];for(let S=0;S<i.cat.length;S++){const I=d==="thigh"&&i.cat[S]===st.torso&&r[S*3+1]<b[1]+.02&&r[S*3+2]<b[2]+.02;if(i.cat[S]!==st.leg&&!I||Math.sign(r[S*3])!==(m==="L"?-1:1))continue;const j=[r[S*3]-b[0],r[S*3+1]-b[1],r[S*3+2]-b[2]],M=(j[0]*v[0]+j[1]*v[1]+j[2]*v[2])/y,T=I?Math.max(0,M):M;if(T<0||T>(I?.35:1)||I&&M<-.12)continue;const w=[j[0]-v[0]*T,j[1]-v[1]*T,j[2]-v[2]*T],E=Math.hypot(w[0],w[1],w[2]);if(E>(d==="thigh"&&T<.4&&w[2]<0?.18:.12))continue;const N=Math.min(h-1,Math.floor(T*h)),A=hu(v,w,u);k[N*u+A]=Math.max(k[N*u+A],E)}const C=k.slice();for(let S=0;S<h;S++)for(let I=0;I<u;I++){let j=0;for(const M of[S-1,S,S+1])for(const T of[I-1,I,I+1])M<0||M>=h||(j=Math.max(j,C[M*u+(T+u)%u]));k[S*u+I]=j}for(let S=0;S<h;S++)for(let I=0;I<u;I++)k[S*u+I]||(k[S*u+I]=S?k[(S-1)*u+I]:.06)}return mo.size>48&&mo.clear(),mo.set(s,o),o}const lh=new Map;function Wy(e,n,s,o,i,r){const l=`${s}|${Wn(n)}|${JSON.stringify(o)}|${i}|${r}`;let h=lh.get(l);if(h)return h;const u=js(e,n,s),m=u.getAttribute("position"),d=Vr(e,s,n),f=e.bind,p=r==="cape",b=p?"torso":"pelvis",g=f.torso[1]+o.top,v=72,y=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==st.torso&&d.cat[V]!==st.leg&&!(p&&d.cat[V]===st.arm&&d.armT[V]<.15)||Math.abs(m.getY(V)-g)>.025)continue;const K=m.getX(V),G=m.getZ(V),_=Math.atan2(K,G),ee=(Math.round(_/(Math.PI*2)*v)%v+v)%v;y[ee]=Math.max(y[ee],Math.hypot(K,G))}const k=o.panels==="apron"?.34:.2,C=new Float32Array(v);for(let V=0;V<m.count;V++){if(d.cat[V]!==st.torso&&!(k>.2&&d.cat[V]===st.leg))continue;const K=g-m.getY(V);if(K<0||K>k)continue;const G=m.getX(V),_=m.getZ(V),ee=Math.atan2(G,_),Q=(Math.round(ee/(Math.PI*2)*v)%v+v)%v;C[Q]=Math.max(C[Q],Math.hypot(G,_))}for(let V=0;V<3;V++){const K=Float32Array.from(y),G=Float32Array.from(C);for(let _=0;_<v;_++)y[_]=Math.max(K[_],(K[(_+v-1)%v]+K[(_+1)%v])/2),C[_]=Math.max(G[_],(G[(_+v-1)%v]+G[(_+1)%v])/2)}const S=V=>{const K=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(K),_=K-G;return C[G%v]*(1-_)+C[(G+1)%v]*_+.014+i*.006},I=V=>{const K=(V/(Math.PI*2)*v+v*4)%v,G=Math.floor(K),_=K-G;return y[G%v]*(1-_)+y[(G+1)%v]*_+.008+i*.006},j=(()=>{if(!p)return()=>0;const V=Math.ceil((o.length+.1)/.02),K=new Float32Array(V);for(let G=0;G<m.count;G++){if(d.cat[G]!==st.torso&&d.cat[G]!==st.leg)continue;const _=Math.floor((g-m.getY(G))/.02),ee=m.getZ(G);_<0||_>=V||ee>=0||Math.abs(m.getX(G))>.16||(K[_]=Math.max(K[_],-ee))}for(let G=1;G<V;G++)K[G]=Math.max(K[G],K[G-1]);return G=>{const _=g-G,ee=Math.max(0,Math.min(V-1,Math.floor(_/.02)));return K[ee]+.012+(o.clear??0)*Math.min(1,Math.max(0,(_-.35)/Math.max(.1,o.length-.35)))}})(),M=V=>p?.07*Math.sin(V)**2:0,T=V=>r==="cape"?I(V):Math.max(I(V),S(V)),w=V=>Math.max(T(V)*1.04,I(V)*o.flare),E=p?[[Math.PI*.55,Math.PI*1.45]]:o.panels==="aodai"?[[-.95,.95],[Math.PI-1.3,Math.PI+1.3]]:o.panels==="apron"?[[-1.1,1.1]]:o.open?[[o.open*Math.PI/180,Math.PI*2-o.open*Math.PI/180]]:[[0,Math.PI*2]],N=!p&&!o.panels&&!o.open,A=[],O=[],H=[],D=[],$=[],W=[],z=4,Y=Math.max(16,Math.round(o.length/.022));p?f.torso[1]:f.torso[1]-.07;for(const[V,K]of E){const G=K-V,_=Math.max(2,Math.round((o.chains??12)*G/(Math.PI*2))+(N?0:1)),ee=Math.max(8,Math.round(56*G/(Math.PI*2))),Q=$.length;for(let xe=0;xe<_;xe++){const q=N?V+G*xe/_:V+G*xe/(_-1),ue=I(q),pe=[Math.sin(q)*ue,g-M(q),Math.cos(q)*ue],U=(p?ue*o.flare:w(q))+(p?.03:0),le=[Math.sin(q)*U,g-o.length,Math.cos(q)*U];p&&(le[2]=Math.min(le[2],-.12-.02*Math.abs(Math.sin(q)),Math.cos(q)*j(le[1])));const ce=[(le[0]-pe[0])/z,(le[1]-pe[1])/z,(le[2]-pe[2])/z];$.push({at:pe,dirs:Array.from({length:z},()=>ce),seg:xe})}const ve=A.length/3;W.push({base:ve,width:ee+1,rows:Y+1,wrap:N});for(let xe=0;xe<=Y;xe++){const q=xe/Y;for(let ue=0;ue<=ee;ue++){const pe=V+G*ue/ee,U=I(pe),le=(o.folds??0)*Math.sin(pe*(p?14:22))*q,ce=T(pe),Le=p?0:Math.min(1,o.length*q/k),je=U+(ce-U)*Math.sin(Math.min(1,Le)*Math.PI/2);let ie=(p?U+(U*o.flare+.03-U)*q:q*o.length<=k?je:ce+(w(pe)-ce)*((o.length*q-k)/Math.max(1e-6,o.length-k)))+le,Me=Math.cos(pe)*ie;p&&(Me=Math.min(Me,Math.cos(pe)*U+(-.12-Math.cos(pe)*U)*q,Math.cos(pe)*j(g-o.length*q))),A.push(Math.sin(pe)*ie,g-M(pe)*(1-q)-o.length*q,Me);const Ee=N?(pe-V)/G*_:(pe-V)/G*(_-1);let Se=Math.floor(Ee),he=Ee-Se;N?Se%=_:Se>=_-1&&(Se=_-2,he=1);const be=N?(Se+1)%_:Se+1,Fe=q*z,Te=Math.min(z-1,Math.floor(Fe)),_e=Math.min(1,Fe-Te),ze=Math.min(z-1,Te+1),Be=[[(Q+Se)*z+Te,(1-he)*(ze===Te?1:1-_e)],[(Q+be)*z+Te,he*(ze===Te?1:1-_e)]];for(ze!==Te&&Be.push([(Q+Se)*z+ze,(1-he)*_e],[(Q+be)*z+ze,he*_e]);Be.length<4;)Be.push([0,0]);for(const[Ze,F]of Be)H.push(Ze),D.push(F)}}for(let xe=0;xe<Y;xe++)for(let q=0;q<ee;q++){const ue=ve+xe*(ee+1)+q,pe=ue+ee+1;O.push(ue,pe,ue+1,ue+1,pe,pe+1)}}const J=new Tt;return J.setAttribute("position",new Bt(A,3)),J.setAttribute("skinIndex",new vd(H,4)),J.setAttribute("skinWeight",new Bt(D,4)),J.setIndex(O),J.computeVertexNormals(),J.userData.shared=!0,J.userData.rings=W,J.dispose=()=>{},h={geometry:J,roots:$,anchor:b},lh.set(l,h),h}function Gy(e,n,s){const o=e.bones.get(n.anchor),i=[],r=new Map,l=[],h=n.anchor==="torso"?new oe(0,1,0):new oe(0,.93,0);return n.roots.forEach((u,m)=>{let d=o,f=new oe(...u.at);const p=[],b=[];u.dirs.forEach((g,v)=>{const y=new $a;y.name=`${s}${m}_${v}`;const k=v===0?f.clone().sub(h):new oe(...u.dirs[v-1]);y.position.copy(k),d.add(y),e.bones.set(y.name,y),r.set(y.name,new At().makeTranslation(-f.x,-f.y,-f.z)),i.push(y.name),p.push(y),b.push(new oe(...g)),d=y,f=f.clone().add(new oe(...g))}),l.push({bones:p,rest:b,kind:"cloth",stiffness:.5,collide:!0,side:m})}),{bones:i,inverses:r,set:{kind:"cloth",anchor:n.anchor,chains:l}}}const po=new Map;function fo(e,n,s,o,i,r,l){const h=e.pos.length/3,u=o?n:n+1;for(const f of[0,1])for(let p=0;p<=s;p++)for(let b=0;b<u;b++){const g=i(b/n,p/s,f),[v,y]=l(b/n,p/s);e.pos.push(...g),e.col.push(...r(b/n,p/s,f,g[1]));for(let k=0;k<4;k++)e.si.push(v[k]??0),e.sw.push(y[k]??0)}const m=(f,p,b)=>h+f*u*(s+1)+b*u+(o?p%n:p);for(let f=0;f<s;f++)for(let p=0;p<n;p++){const b=M=>[m(M,p,f),m(M,p+1,f),m(M,p+1,f+1),m(M,p,f+1)],[g,v,y,k]=b(0),[C,S,I,j]=b(1);e.idx.push(g,v,y,g,y,k,C,I,S,C,j,I)}const d=(f,p)=>{const b=m(0,...f),g=m(0,...p),v=m(1,...f),y=m(1,...p);e.idx.push(b,v,y,b,y,g)};for(let f=0;f<n;f++)d([f,0],[f+1,0]),d([f+1,s],[f,s]);if(!o)for(let f=0;f<s;f++)d([n,f],[n,f+1]),d([0,f+1],[0,f])}function qy(e,n,s,o,i,r,l,h,u=0){const m=`${s}|${Wn(n)}|${i}|${l}|${h}|${u}`;let d=po.get(m);if(d)return d;const f=js(e,n,s),p=f.getAttribute("position").array,b=o.cat.length,g=new Uint8Array(b),v={pos:[],idx:[],si:[],sw:[],col:[]},y=new Ue(l),k=H=>{const D=new Ue(H);return[D.r/Math.max(.02,y.r),D.g/Math.max(.02,y.g),D.b/Math.max(.02,y.b)]},C=y.r*.3+y.g*.59+y.b*.11,S=k(h),I=k(C>.55?"#8d8f94":"#d9d9d4"),j=k(C>.45?"#2b2c30":"#efefea"),M=k(y.clone().multiplyScalar(.45)),T=i==="boots"?.036:i==="heels"?.022:i==="sandals"?0:i==="sneakers"?.032:.026,w=40,E=12,N=i==="sneakers"?.0045:.003,A=i==="sneakers"?.12:.45;for(const H of["L","R"]){const D=e.bind[`foot${H}`],$=e.bones.indexOf(`foot${H}`),W=e.bones.indexOf(`shin${H}`),z=[],Y=[];for(let he=0;he<b;he++)o.cat[he]===st.foot&&Math.sign(p[he*3])===(H==="L"?-1:1)&&(Y.push(he),o.footY[he]<-.012&&z.push(he));if(!z.length)continue;let J=1/0,V=-1/0;for(const he of z)J=Math.min(J,p[he*3+2]),V=Math.max(V,p[he*3+2]);J-=.006,V+=i==="heels"||i==="dress"?.02:i==="sandals"?.008:.014;const K=14,G=new Float64Array(K),_=new Float64Array(K),ee=new Float64Array(K);for(let he=0;he<K;he++){const be=J+(V-J)*(he/K),Fe=J+(V-J)*((he+1)/K);let Te=1/0,_e=-1/0,ze=-1/0;for(const Be of Y){const Ze=p[Be*3+2];Ze<be-.01||Ze>Fe+.01||o.footY[Be]>.035||(Te=Math.min(Te,p[Be*3]),_e=Math.max(_e,p[Be*3]),ze=Math.max(ze,p[Be*3+1]))}Te===1/0?(G[he]=he?G[he-1]:D[0],_[he]=he?_[he-1]:.04,ee[he]=he?ee[he-1]:D[1]-.03):(G[he]=(Te+_e)/2,_[he]=(_e-Te)/2,ee[he]=ze)}const Q=(he,be)=>{const Fe=Math.min(K-1,Math.max(0,be*K-.5)),Te=Math.floor(Fe),_e=Math.min(K-1,Te+1),ze=Fe-Te;return he[Te]*(1-ze)+he[_e]*ze},ve=D[1]-o.sole-r,xe=ve+r,q=H==="L"?1:-1,ue=he=>{const be=Math.sqrt(Math.max(0,1-((.17-Math.min(he,.17))/.17)**2)),Fe=Math.max(0,(he-.62)/.38),Te=Math.max(Q(_,he),.028)+.006;return{w:Te*be*Math.sqrt(Math.max(0,1-Math.pow(Fe,2.4))),x0:Q(G,he)+q*Te*.28*Math.pow(Fe,1.5),spring:.008*Vt(.7,1,he)**2,z:J+(V-J)*he}},pe=D[1]-(i==="sneakers"?.012:i==="boots"?-.04:i==="heels"?.04:.018),U=i==="heels"?.6:i==="boots"?0:i==="sneakers"?.44:.5,le=i==="sneakers"||i==="boots"?.74:.66,ce=he=>{const be=Math.max(Math.min(D[1]+(i==="boots"?.02:i==="sneakers"?.004:-.006),Q(ee,he)+.009),xe+T)-xe;return Math.max(.004,be*Math.sqrt(Math.max(0,1-Math.pow(Math.max(0,(he-le)/(1-le)),2))))},Le=Math.min(pe,Q(ee,U)+(i==="heels"?-.004:.006)),je=he=>he>=U?1/0:he<.28?pe:pe+(Le-pe)*Vt(.28,U,he),ie=he=>Math.max(ce(he),Number.isFinite(je(he))?je(he)-xe+.025*(1-Vt(U-.06,U,he)):0),Me=(he,be,Fe)=>{const Te=ue(he),_e=Math.cos(be),ze=Math.max(0,Math.sin(be)),Be=Math.sign(_e)*Math.pow(Math.abs(_e),.8);return[Te.x0+(Te.w+Fe)*Be*(1-.16*ze),xe+Te.spring-r*A+(ie(he)+r*A+Fe)*Math.pow(ze,.85),Te.z]},Ee=he=>{const be=je(he);if(!Number.isFinite(be))return Math.PI/2;const Fe=(be-xe-ue(he).spring+r*A)/(ie(he)+r*A);return Fe>=1?Math.PI/2:Math.asin(Math.max(.05,Math.pow(Math.max(0,Fe),1/.85)))},Se=()=>[[$],[1]];for(const he of Y){const be=Math.min(1,Math.max(0,(p[he*3+2]-J)/(V-J))),Fe=p[he*3+1];i==="sandals"?Fe<xe+.004&&(g[he]=1):i==="heels"?(be>=U-.03||Fe<je(be)-.005)&&(g[he]=1):g[he]=1}if(fo(v,w,16,!1,(he,be,Fe)=>{const Te=ue(he),_e=i==="heels"?.001:i==="sneakers"?.006:.0035,ze=be*Math.PI*2,Be=Math.cos(ze),Ze=Math.sin(ze),F=Fe?.6:1;return[Te.x0+(Te.w*1.03+_e)*F*Math.sign(Be)*Math.pow(Math.abs(Be),.35),ve+Te.spring+r*.5+r*.5*F*Math.sign(Ze)*Math.pow(Math.abs(Ze),.35),Te.z]},(he,be,Fe,Te)=>i==="sneakers"&&Te>ve+r*.62&&Te<ve+r*.8?I:S,Se),i==="sandals"){for(const[he,be]of[[.6,.66],[.38,.44]])fo(v,6,16,!1,(Fe,Te,_e)=>{const ze=he+(be-he)*Fe,Be=ue(ze),Ze=Math.PI*Te,F=Math.cos(Ze),te=Math.sin(Ze),Z=_e?.002:.0045,re=Math.max(.006,Q(ee,ze)+.004-xe);return[Be.x0+(Be.w+Z-.004)*Math.sign(F)*Math.pow(Math.abs(F),.7),xe+Be.spring-.001+(re+Z)*Math.pow(te,.8),Be.z]},()=>[1,1,1],Se);continue}for(const he of[1,-1])fo(v,w,E,!1,(be,Fe,Te)=>{const _e=Ee(be),ze=he>0?_e*Fe:Math.PI-_e*Fe;return Me(be,ze,Te?0:N)},(be,Fe,Te)=>Te?be<U+.05?M:[1,1,1]:i==="sneakers"&&be>.44&&be<.68&&Fe>.82&&Math.sin(be*Math.PI*42)>.2?j:[1,1,1],Se);if(i==="boots"){const he=_e=>{for(let ze=.015;;ze*=1.5){let Be=1/0,Ze=-1/0,F=1/0,te=-1/0,Z=0;for(let re=0;re<b;re++)o.cat[re]!==st.leg&&o.cat[re]!==st.foot||Math.sign(p[re*3])!==(H==="L"?-1:1)||Math.abs(p[re*3+1]-_e)>ze||(Z++,Be=Math.min(Be,p[re*3]),Ze=Math.max(Ze,p[re*3]),F=Math.min(F,p[re*3+2]),te=Math.max(te,p[re*3+2]));if(Z>=24||ze>.1)return{cx:(Be+Ze)/2,cz:(F+te)/2,rx:(Ze-Be)/2,rz:(te-F)/2}}},be=D[1]+.005,Fe=D[1]+.2,Te=Array.from({length:9},(_e,ze)=>{const Be=be+(Fe-be)*(ze/8);return{y:Be,...he(Be)}});for(let _e=7;_e>=0;_e--)Te[_e].rx=Math.max(Te[_e].rx,Te[_e+1].rx*.9),Te[_e].rz=Math.max(Te[_e].rz,Te[_e+1].rz*.9);fo(v,32,8,!0,(_e,ze,Be)=>{const Ze=Te[Math.round(ze*8)],F=_e*Math.PI*2,te=u+(Be?.004:.0075);return[Ze.cx+(Ze.rx+te)*Math.sin(F),Ze.y,Ze.cz+(Ze.rz+te)*Math.cos(F)]},()=>[1,1,1],(_e,ze)=>{const Be=Vt(D[1]-.01,D[1]+.05,Te[Math.round(ze*8)].y);return[[$,W],[1-Be,Be]]})}}const O=new Tt;return O.setAttribute("position",new Bt(v.pos,3)),O.setAttribute("skinIndex",new bs(v.si,4)),O.setAttribute("skinWeight",new Bt(v.sw,4)),O.setAttribute("color",new Bt(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},po.size>48&&po.clear(),po.set(m,d),d}const Uy=new At().makeTranslation(0,-.008,-.0155).multiply(new At().makeScale(.66,1,.75));function Xy(e,n,s,o,i,r={}){const l=[],h=Vr(e,i,s),u=[],m=[],d=(S,I,j,M,T,w={},E)=>{const N=Ky(e,s,i,S,I,E??(()=>j),w);N.geometry.getIndex()?.count&&(l.push({geometry:N.geometry,material:M,slot:T,skinned:!0}),u.push(N.covered),m.push(S))},f=S=>_s(`fab:${Oy(S)}:${S.color}`),p=(S,I,j,M,T="skirt")=>{if(r.fittedOnly)return;const w=Wy(e,s,i,S,I,T),E=Gy(n,w,`${M}${T}`);l.push({geometry:w.geometry,material:j,slot:M,skinned:!0,bones:E.bones,inverses:E.inverses,chains:E.set,drape:T!=="cape"})},b=o.top?Go[o.top.type]??Go.tshirt:null,g=!!b&&!!o.bottom&&(["shirt","police","polo"].includes(o.top.type)&&["trousers","jeans","shorts","ancient"].includes(o.bottom.type)||!!wn[o.bottom.type]?.loose&&!b.loose),v=b&&g?{...b,hem:(wn[o.bottom.type]?.waist??.05)-.05}:b,y=S=>h.cat[S]===st.torso?.003:0;if(o.bottom){const S=wn[o.bottom.type]??wn.trousers,I=g?v.th+.005:0,j=o.shoes?.type==="boots"&&S.leg>1.6;d(`bottom|${o.bottom.type}|${g}|${j}`,zy(h,j?{...S,leg:1.6}:S),S.th,f(o.bottom),"bottom",{},M=>(o.bottom.type==="ancient"?S.th*(.6+.6*Vt(.6,1.8,h.legT[M])):S.th)+(I?I*Vt(-.2,-.05,h.yt[M]):0)),S.loose&&p(S.loose,0,f(o.bottom),"bottom")}if(o.top){const S=v,I=!S.loose&&S.hem<ja,j=I?{...S,hem:ja}:S,M=o.top.color2,T=o.bottom&&!g?(wn[o.bottom.type]?.th??.007)+.002:0,w=j.stripes?A=>{const O=h.yt[A],D=(Math.abs(O-.12)<.018||Math.abs(O-.26)<.018)&&h.cat[A]===st.torso?new Ue(M??"#e6e6e0"):new Ue(o.top.color),$=new Ue(o.top.color);return[D.r/Math.max(.02,$.r),D.g/Math.max(.02,$.g),D.b/Math.max(.02,$.b)]}:void 0,E=w?hh(f(o.top)):f(o.top),N=Math.max(1+j.hem+.1,T?1+(wn[o.bottom.type]?.waist??.06)+.08:0);d(`top|${o.top.type}|${M??""}|${g}|${T}|${N.toFixed(3)}`,rh(h,j,.67*Ga(s).shoulderX),j.th,E,"top",{colors:w,smooth:6,...j.th>=.01?{smoothBase:6,smoothBaseLift:N}:{},...I&&ja-S.hem>.015?{band:{hem:ja,length:ja-S.hem,flare:.25,tuck:.3,cat:h.cat}}:{}},A=>j.th+y(A)+(T&&h.yt[A]<.12?T*Vt(.12,.04,h.yt[A]):0)+(j.neck==="collar"||j.neck==="high"?.005*Vt(.5,.58,h.yt[A]):0)),j.loose&&p(j.loose,1,f(o.top),"top")}if(o.outer){const S=o.outer.type;if(qo[S]){const I=qo[S],j=Math.max(1+I.hem+.1,o.bottom&&wn[o.bottom.type]?1+wn[o.bottom.type].waist+.08:0);d(`outer|${S}|${j.toFixed(3)}`,rh(h,I,.67*Ga(s).shoulderX),I.th,f(o.outer),"outer",{smooth:6,smoothBase:6,smoothBaseLift:j},M=>I.th+(h.cat[M]===st.torso?.006:0)),I.loose&&p(I.loose,2,f(o.outer),"outer")}else if(S==="cape"){const I=[v?.loose,o.bottom?wn[o.bottom.type]?.loose:void 0].reduce((j,M)=>M?Math.max(j,.025+(M.flare-1)*.16):j,0);p({top:.47,length:1.05,flare:1.15,folds:.012,chains:10,...I?{clear:Math.round(I*1e3)/1e3}:{}},2,f(o.outer),"outer","cape")}else S==="apron"&&p({top:.12,length:.55,flare:1.04,panels:"apron",folds:.002,chains:5},2,f(o.outer),"outer")}if(o.shoes&&o.shoes.type!=="barefoot"){const S=o.shoes.type,I=S==="sneakers"?.027:S==="boots"?.022:S==="sandals"?.014:S==="heels"?.008:.014,j=S==="sneakers"?"#f4f4f0":S==="sandals"?vi(o.shoes.color,-.25):S==="boots"||S==="dress"||S==="heels"?vi(o.shoes.color,-.55):vi(o.shoes.color,-.3),M=o.shoes.fabric??(S==="sneakers"||S==="cloth"?"cotton":"leather"),T=hh(_s(M==="leather"?`sol:${o.shoes.color}:0.36:0`:`fab:${M}:${o.shoes.color}`));S!=="sandals"&&S!=="heels"&&S!=="boots"&&d(`socks|${S}`,N=>h.cat[N]===st.leg?(h.legT[N]-1.8)*.43:h.cat[N]===st.foot?Math.min((h.legT[N]-1.8)*.43,(h.footY[N]+.045)*.6,(e.bind.footL[2]+.02-h.z[N])*.6):-1,.0018,_s(`fab:cotton:${S==="sneakers"?"#e9e9e4":"#2a2a2d"}`),"shoes",{smooth:3});const w=S==="boots"&&o.bottom?wn[o.bottom.type]?.th??.007:0,E=qy(e,s,i,h,S,I,o.shoes.color,j,w);if(l.push({geometry:E.geometry,material:T,slot:"shoes",skinned:!0}),u.push(E.hide),m.push(`last|${S}`),S==="heels"&&!r.fittedOnly)for(const N of["L","R"]){const A=new vs(.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:_s(`sol:${o.shoes.color}:0.4:0`),slot:"shoes",skinned:!1,bone:`foot${N}`})}}if(o.hat&&!r.fittedOnly)for(const S of Ly(e,o.hat,o.hair?.style))l.push({geometry:S.geometry,material:_s(S.mat),slot:S.slot,skinned:!1,bone:"head"});if(o.accessories?.length&&!r.fittedOnly){const S=lp({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 cp(S,{accessories:o.accessories})){const j=I.geo.clone();I.group==="head"&&j.applyMatrix4(oy(e).multiply(Uy)),l.push({geometry:j,material:_s(I.mat),slot:"accessory",skinned:!1,bone:I.group})}}const k=[v?.loose,o.bottom?wn[o.bottom.type]?.loose:void 0].find(S=>S&&S.length>=.45&&!S.panels&&!S.open);if(k&&!r.fittedOnly&&(!o.bottom||wn[o.bottom.type]?.loose)){const S=new Uint8Array(h.cat.length);for(let I=0;I<S.length;I++)(h.cat[I]===st.torso&&h.yt[I]<k.top-.02||h.cat[I]===st.leg&&h.legT[I]<.3)&&(S[I]=1);u.push(S),m.push(`seat|${k.top}`)}let C=null;if(u.length){C=new Uint8Array(h.cat.length);for(const S of u)for(let I=0;I<S.length;I++)S[I]&&(C[I]=1)}return{parts:l,hide:C,hideKey:m.join("§")}}const ch=new Map;function hh(e){let n=ch.get(e);return n||(n=e.clone(),n.vertexColors=!0,n.onBeforeCompile=e.onBeforeCompile,n.customProgramCacheKey=e.customProgramCacheKey,n.userData.shared=!0,n.dispose=()=>{},ch.set(e,n)),n}const za=new Qe,dh=new Qe,uh=new Qe,Vy=new At,du=new At,Rs=new oe,ts=new oe,Jt=new oe,Ln=new oe,Gt=new oe,go=new oe,on=new oe,ea=new oe,pn=Array.from({length:14},()=>({a:new oe,b:new oe,r:0,rb:0,lap:!1})),xo=[0,0,0],bo=[0,0,0],uu=(e,n,s,o,i)=>{const r=e.length/_a,l=Math.min(r-1,Math.max(0,n*r-.5)),h=Math.floor(l),u=l-h,m=Math.min(r-1,h+1);xo[0]=s.b.x-s.a.x,xo[1]=s.b.y-s.a.y,xo[2]=s.b.z-s.a.z,bo[0]=o.x-i.x,bo[1]=o.y-i.y,bo[2]=o.z-i.z;const d=hu(xo,bo);return e[h*_a+d]*(1-u)+e[m*_a+d]*u};function oa(e,n,s,o){const i=e.bones.get(n);return s.set(...o??[0,0,0]).applyMatrix4(i.matrixWorld).applyMatrix4(du),s}const Xt=7;function mu(e){du.copy(e.root.matrixWorld).invert();let n=0;const s=(o,i,r,l,h,u=r)=>{const m=pn[n++];oa(e,o,m.a,l),oa(e,i,m.b,h),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 o of["L","R"])s(`fore${o}`,`hand${o}`,.045),s(`hand${o}`,`hand${o}`,.048,[0,0,.005],[0,-.13,.01]);if(n!==Xt)throw new Error("HQ dynamics: leg capsules must start at LEGS");for(const o of["L","R"])s(`thigh${o}`,`shin${o}`,.088,void 0,void 0,.064),s(`shin${o}`,`foot${o}`,.062,void 0,void 0,.05),s(`foot${o}`,`foot${o}`,.058,[0,-.03,-.02],[0,-.04,.2]);for(const[o,i]of[[3,4],[5,6]]){const r=pn[i];ea.addVectors(r.a,r.b).multiplyScalar(.5);for(const l of[Xt,Xt+3]){Yr(pn[l],ea,on),ts.subVectors(ea,on);const h=ts.length();h<.16&&ts.y>.6*h&&(pn[o].lap=pn[i].lap=!0)}}return n}function Yr(e,n,s){Rs.subVectors(e.b,e.a);const o=Rs.lengthSq(),i=o>1e-10?Math.max(0,Math.min(1,ts.subVectors(n,e.a).dot(Rs)/o)):0;return s.copy(e.a).addScaledVector(Rs,i),i}function mh(e,n,s){const o=Yr(n,e,on),i=e.distanceTo(on),r=(n.prof?uu(n.prof,o,n,e,on):n.r+(n.rb-n.r)*o)+s;i<r&&i>1e-6&&e.sub(on).multiplyScalar(r/i).add(on)}const ph=.68,Yy=(e,n,s)=>{const o=n.x-s.x,i=n.z-s.z,r=Math.hypot(o,i);if(r<1e-6)return e.r;const l=o/r,h=i/r;return e.r/Math.sqrt(l*l+h*h/(ph*ph))};function pr(e,n,s,o=!1){for(let i=0;i<n;i++){const r=pn[i];if(o&&(i<2||r.lap))continue;const l=Yr(r,e,on),h=e.distanceTo(on),u=(r.prof?uu(r.prof,l,r,e,on):i===0?Yy(r,e,on):r.r+(r.rb-r.r)*l)+s;h>=u||(h<1e-6?e.y-=u:e.sub(on).multiplyScalar(u/h).add(on))}}function Qy(e,n,s,o){e.root.updateMatrixWorld(!0);const i=mu(e);pn[Xt].prof=s.L.thigh,pn[Xt+1].prof=s.L.shin,pn[Xt+3].prof=s.R.thigh,pn[Xt+4].prof=s.R.shin;for(let r=0;r<n.length;r+=3){Gt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<5;l++)pr(Gt,i,.007,!0);for(const l of[Xt,Xt+1,Xt+3,Xt+4])mh(Gt,pn[l],.007);n[r]=Gt.x,n[r+1]=Gt.y,n[r+2]=Gt.z}if(o?.some(r=>r.wrap)){for(const r of o)r.wrap&&Zy(n,r);for(let r=0;r<n.length;r+=3){Gt.set(n[r],n[r+1],n[r+2]);for(let l=0;l<2;l++)for(const h of[Xt,Xt+1,Xt+3,Xt+4])mh(Gt,pn[h],.007);n[r]=Gt.x,n[r+1]=Gt.y,n[r+2]=Gt.z}}for(const r of[0,1,3,4])pn[Xt+r].prof=void 0}function Zy(e,n){const s=n.width-1,o=new Float64Array(s),i=new Float64Array(s),r=new Float64Array(s),l=new Float64Array(s),h=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++)o[S]=e[(m+S)*3],i[S]=e[(m+S)*3+2],d+=o[S],f+=i[S];d/=s,f/=s;const p=Array.from({length:s},(S,I)=>I).sort((S,I)=>o[S]-o[I]||i[S]-i[I]),b=(S,I,j)=>(o[I]-o[S])*(i[j]-i[S])-(i[I]-i[S])*(o[j]-o[S]),g=[],v=[];for(const S of p){for(;g.length>=2&&b(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&&b(v[v.length-2],v[v.length-1],I)<=0;)v.pop();v.push(I)}const y=[...g.slice(0,-1),...v.slice(0,-1)];for(let S=0;S<s;S++){const I=o[S]-d,j=i[S]-f,M=Math.hypot(I,j);if(l[S]=Math.atan2(I,j),r[S]=M,M<1e-6)continue;const T=I/M,w=j/M;let E=M;for(let N=0;N<y.length;N++){const A=y[N],O=y[(N+1)%y.length],H=o[O]-o[A],D=i[O]-i[A],$=T*D-w*H;if(Math.abs($)<1e-9)continue;const W=o[A]-d,z=i[A]-f,Y=(W*D-z*H)/$,J=(W*w-z*T)/$;Y>0&&J>=-1e-6&&J<=1+1e-6&&(E=Math.max(E,Y))}r[S]=E}for(let S=0;S<s;S++){let I=0;for(let j=-2;j<=2;j++)I+=r[(S+j+s)%s];h[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])*h[S],e[I+2]=f+Math.cos(l[S])*h[S]}const k=(m+s)*3,C=m*3;e[k]=e[C],e[k+1]=e[C+1],e[k+2]=e[C+2]}}const wa=(e,n,s)=>{const o=Math.min(1,Math.max(0,(s-e)/(n-e)));return o*o*(3-2*o)},On=new oe,Uo=new oe,fh=new oe,fr={L:new oe,R:new oe},Eo={L:new oe,R:new oe},gr={L:1,R:1},gh=e=>n=>On.subVectors(n,fr[e]).dot(Eo[e])/gr[e],xh={L:new Qe,R:new Qe,alongL:gh("L"),alongR:gh("R")};function Jy(e,n){e.bones.get("torso").getWorldQuaternion(za).premultiply(n),fh.set(0,-1,0).applyQuaternion(za);for(const s of["L","R"])oa(e,`thigh${s}`,fr[s]),oa(e,`shin${s}`,Uo),gr[s]=Math.max(1e-6,Eo[s].subVectors(Uo,fr[s]).length()),Eo[s].divideScalar(gr[s]),xh[s].setFromUnitVectors(fh,Eo[s]);return xh}function ev(e,n,s,o){if(!e.length)return;const i=mu(n),r=o?.vel??[0,0,0],l=o?.acc??[0,0,0],h=o?.time??0,u=o?.air??0,m=Math.hypot(r[0],r[1],r[2]);n.root.updateMatrixWorld(!0);const d=new Qe;n.root.getWorldQuaternion(d);const f=d.clone().invert(),p=Jy(n,f);for(const b of e)b.chains.forEach((g,v)=>{const y=g.kind==="cloth",k=(y?.085:.05)*(1+.8*u),C=y?.012:.008,S=new oe(-r[0]*k-l[0]*C,-r[1]*k*.6-l[1]*C,-r[2]*k-l[2]*C),I=Math.min(1,m/3)*(y?.12:.06);g.bones.forEach((j,M)=>{const T=j.parent;T.updateWorldMatrix(!0,!1),T.getWorldQuaternion(dh).premultiply(f);let w=j;for(let O=0;O<=M;O++)w=w.parent;w.getWorldQuaternion(za).premultiply(f),go.copy(g.rest[M]).normalize();const E=g.rest[M].length()*T.getWorldScale(on).x*j.scale.x/n.root.getWorldScale(ts).x;Jt.copy(go).applyQuaternion(za);const N=g.stiffness*(M===0?1.4:1);if(Jt.multiplyScalar(N).add(Rs.set(0,-(1-Math.min(.95,N)),0)).add(S),I){const O=h*(y?5.3:3.7)+v*1.7+M*.9;Jt.x+=Math.sin(O)*I,Jt.z+=Math.cos(O*.8)*I*.5}if(Jt.normalize(),Vy.copy(j.matrixWorld),oa(n,j.name,Ln),y&&b.anchor==="pelvis"){const O=g.bones[0].position,H=Math.atan2(O.x,O.z),D=wa(.06,-.06,O.x),$=D*p.alongL(Ln)+(1-D)*p.alongR(Ln),W=(.6+.3*(M/g.bones.length))*(.3+.7*wa(-.5,.4,Math.cos(H)))*(1-wa(.82,1.02,$)),z=wa(.85,1.05,$)*wa(.2,.7,Math.cos(H));if(z>0)for(const Y of["L","R"]){const J=Y==="L"?D:1-D;J<=0||(oa(n,`foot${Y}`,Uo,[0,-.02,.24]),On.subVectors(Uo,Ln),On.lengthSq()>1e-8&&On.y<0&&Jt.lerp(On.normalize(),z*J).normalize())}W>0&&(On.copy(go).applyQuaternion(za),Rs.copy(On).applyQuaternion(p.L).multiplyScalar(D),ts.copy(On).applyQuaternion(p.R).multiplyScalar(1-D),On.copy(Rs).add(ts).normalize(),Jt.lerp(On,W).normalize())}Gt.copy(Ln).addScaledVector(Jt,E);const A=y&&b.anchor==="pelvis";if(g.collide)for(let O=0;O<6;O++)ea.copy(Ln).addScaledVector(Jt,E*.5),pr(ea,i,y?.014:.008,A),Jt.subVectors(ea,Ln).normalize(),Gt.copy(Ln).addScaledVector(Jt,E),pr(Gt,i,y?.014:.008,A),Jt.subVectors(Gt,Ln).normalize(),Gt.copy(Ln).addScaledVector(Jt,E);Jt.subVectors(Gt,Ln).normalize(),ts.copy(Jt).applyQuaternion(dh.clone().invert()),uh.setFromUnitVectors(go,ts),j.quaternion.copy(uh),j.updateMatrixWorld(!0)})})}const tv=6.5,Ma=new Map;function nv(e){const n=Wn(e);let s=Ma.get(n);if(!s){const i=Xr({...e,head:1,posture:0},Ir,{bind:!0});i.root.updateMatrixWorld(!0),s=[...i.bones.values()].map(l=>l.matrixWorld.clone().invert());const r=[...i.bones.keys()];s.names=r,Ma.set(n,s),Ma.size>64&&Ma.delete(Ma.keys().next().value)}const o=s.names;return new Map(o.map((i,r)=>[i,s[r]]))}function pu(e){const n=new Ue(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 sv(e,n,s){const o=dp(e),i=!e||!Object.keys(o).length,r=pu(n)?"#6d7a86":n;if(i){const l="#"+new Ue(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 $y(o)||(o.top={type:"tank",color:"#e8e4dc"}),Dy(o)||(o.bottom={type:"shorts",color:"#3a3f47"}),o}function av(e,n){return e?.skin??(pu(n)?n:Lr[2])}const yo=(e,n)=>(e.name=n,e.castShadow=!0,e.receiveShadow=!0,e);function ov(e,n,s,o,i={}){const r=Ur();if(!r)throw new Error("HQ character asset not loaded");const l=av(s,n),h=Po({...s??{},skin:l},l),u=i.bare?{}:sv(o,n,h),m=u.shoes?.type==="heels",d=Xr(h,e,{heels:m}),f=nv(h),p=(E,N)=>new Fi(E.map(A=>d.bones.get(A)),E.map(A=>f.get(A).clone())),b=[],g=[],v=i.lod===void 0?[0,1]:[i.lod],y=new tg,k=v.map(()=>new rn);k.forEach((E,N)=>{E.name=`lod${v[N]}`,y.addLevel(E,N===0?0:tv),N&&(E.visible=!1)}),y.name="hqLod",d.root.add(y);const C=(E,N,A,O,H=d.root,D=!0)=>{const $=new Or(E,N);return $.bind(O,new At),yo($,A),yy($),$.userData.grounds=D,b.push($),H.add($),$},S=p(cd),I=u.hat?null:u.hair?.style,j={skin:l,buzz:I==="buzz"?u.hair.color:null,stubble:u.beard?.type==="beard"?u.beard.color:null},M=lv(l);for(const E of["L","R"])d.bones.get(`eye${E}`).add(yo(new ut(dy(M),xy()),"eyes"));const T=[];for(const E of Fy(r,d,u,h)){const N=new Fi(E.bones.map(O=>d.bones.get(O)),E.bones.map(O=>(E.inverses.get(O)??f.get(O)).clone())),A=E.near&&v[0]===0&&v.length>1?k[0]:d.root;C(E.geometry,E.material,E.slot,N,A,!1),E.chains&&T.push(E.chains)}v.forEach((E,N)=>{const A=Xy(r,d,h,u,E,{fittedOnly:N>0}),O=C(ly(r,h,E,j),py(l),"skin",S,k[N],N===0);A.hide&&(O.geometry=rv(O.geometry,A.hide,A.hideKey));for(const H of A.parts){if(H.skinned){const D=H.bones?new Fi(H.bones.map(W=>d.bones.get(W)),H.bones.map(W=>(H.inverses?.get(W)??f.get(W)).clone())):S,$=C(H.geometry,H.material,H.slot,D,H.bones?d.root:k[N],N===0);if(H.drape){const W=new Tt,z=H.geometry.getAttribute("position").count;W.setAttribute("position",new Pt(new Float32Array(z*3),3)),W.setIndex(H.geometry.getIndex());const Y=yo(new ut(W,H.material),H.slot);Y.userData.drape=!0,$.visible=!1,$.userData.grounds=!1,d.root.add(Y),g.push({src:$,mesh:Y})}}else{const D=yo(new ut(H.geometry,H.material),H.slot);(d.bones.get(H.bone)??d.root).add(D)}H.chains&&T.push(H.chains)}});const w={rig:d,b:h,look:u,meshes:b,chains:T,heels:m,drapes:g,legs:Hy(r,h)};return d.root.userData.hq={repose:(E,N)=>bh(w,E,N??null),built:w,torso:iv(r,h,u)},d.root.userData.hqLook=u,bh(w,e,i.motion??null,!0),d.root}function bh(e,n,s,o=!1){const{rig:i,b:r}=e;o||Ho(i,r,n,{heels:e.heels});const l=ld(n);for(const u of e.meshes)u.morphTargetInfluences&&Er.forEach((m,d)=>{u.morphTargetInfluences[d]=l[m]});i.body.position.y=1,i.root.updateMatrixWorld(!0),ev(e.chains,i,n,s);let h=1/0;for(const u of e.meshes)u.userData.grounds!==!1&&aa(u,(m,d)=>{d<h&&(h=d)},i.root);i.body.position.y=1-(Number.isFinite(h)?h: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;aa(u.src,(f,p,b,g)=>{d[g*3]=f,d[g*3+1]=p,d[g*3+2]=b},i.root,!0),Qy(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 vo=new Map;function iv(e,n,s){const o=(s.top?.012:0)+(s.outer?.016:0),i=`${Wn(n)}|${o}`;let r=vo.get(i);if(r)return r;const l=e.lods.length-1,h=e.lods[l],u=js(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 b=.02,g=.3;for(let v=0;v<h.vertices;v++){if(!m.has(h.skinIndex[v*4]))continue;const y=u.getY(v)-1;y<b||y>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+o,rz:(p-f)/2+o,cz:(f+p)/2,y0:b,y1:g}:{rx:.16,rz:.12,cz:0,y0:b,y1:g},vo.size>64&&vo.clear(),vo.set(i,r),r}const jo=new Map;function rv(e,n,s){const o=`${e.uuid}|${s}`;let i=jo.get(o);if(i)return i;jo.size>64&&jo.clear();const r=e.getIndex(),l=[];for(let h=0;h<r.count;h+=3){const u=r.getX(h),m=r.getX(h+1),d=r.getX(h+2);n[u]&&n[m]&&n[d]||l.push(u,m,d)}i=new Tt;for(const h of Object.keys(e.attributes))i.setAttribute(h,e.getAttribute(h));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=()=>{},jo.set(o,i),i}function lv(e){const n=new Ue(e).getHSL({h:0,s:0,l:0}).l;return n>.78?"#4a6a8a":n>.62?"#5a3f2a":"#3a2618"}const xr="shot-hq-characters";function Qr(){try{return globalThis.localStorage?.getItem(xr)!=="off"}catch{return!0}}function cv(e){try{e?globalThis.localStorage?.removeItem(xr):globalThis.localStorage?.setItem(xr,"off")}catch{}for(const n of[...br])n()}const br=new Set;function fu(e){return br.add(e),()=>{br.delete(e)}}const hv=()=>Qr()&&!!Ur();Rr.active=hv;Rr.build=ov;Rr.samples=aa;ss.hq={enabled:Qr,ready:()=>!!Ur(),load:()=>ty(),onSetting:fu,onAsset:au};au(_d);fu(_d);const gu=["Thumb","Index","Middle","Ring","Pinky"],xu={l:"Left",r:"Right",left:"Left",right:"Right"};function dv(e){const n=String(e||"");let s=/^mixamorig\d*[_:]?([A-Za-z]+\d?)$/.exec(n);return s?yr.has(s[1])?s[1]:null:(s=/^Bip\d+[ _](.+)$/i.exec(n),s?uv(s[1].split(/[ _]+/)):(s=/^J_Bip_([CLR])_(\w+)$/i.exec(n),s?mv(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?pv(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?fv(s):yr.has(n)?n:null))))}function uv(e){const[n,s]=e,o={Pelvis:"Hips",Spine:"Spine",Spine1:"Spine1",Spine2:"Spine2",Neck:"Neck",Head:"Head"};if(e.length===1)return o[n]??null;const i=xu[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${gu[+l[1]]}${l[2]?+l[2]+1:1}`:null}function mv(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",o={Shoulder:"Shoulder",UpperArm:"Arm",LowerArm:"ForeArm",Hand:"Hand",UpperLeg:"UpLeg",LowerLeg:"Leg",Foot:"Foot",ToeBase:"ToeBase"}[n];if(o)return s+o;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 pv(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 o=n?xu[n]:null;if(!o)return null;const i={clavicle:"Shoulder",upperarm:"Arm",lowerarm:"ForeArm",hand:"Hand",thigh:"UpLeg",calf:"Leg",foot:"Foot",ball:"ToeBase"}[e];if(i)return o+i;const r=/^(thumb|index|middle|ring|pinky)_0([1-3])$/.exec(e);return r?`${o}Hand${r[1][0].toUpperCase()}${r[1].slice(1)}${r[2]}`:null}function fv(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 gv(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()),o=[[n.get(0),"Hips"]];for(const[i,r]of[[1,"Spine"],[2,"Spine1"],[3,"Spine2"]])n.has(i)&&i<s&&o.push([n.get(i),r]);return s>=5&&n.has(4)&&o.push([n.get(4),"Neck"]),s>=4&&o.push([n.get(s),"Head"]),o}const Zr=["Hips","Spine","Spine2","Neck","Head"];for(const e of["Left","Right"])Zr.push(...["Shoulder","Arm","ForeArm","Hand","UpLeg","Leg","Foot"].map(n=>e+n));const xv=Object.freeze(Zr.slice()),yr=new Set([...Zr,"Spine1","LeftToeBase","RightToeBase",...["Left","Right"].flatMap(e=>gu.flatMap(n=>[1,2,3].map(s=>`${e}Hand${n}${s}`)))]);function bv(e){const n=new Map,s=new Set;let o=0;for(const[r,l]of gv(e||[]))n.set(r,l),s.add(l);for(const r of e||[]){if(n.has(r))continue;const l=dv(r);!l||s.has(l)||(n.set(r,l),s.add(l),(/^mixamorig/.test(r)||yr.has(r))&&o++)}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=xv.filter(r=>!s.has(r));return{ok:i.length===0,exact:i.length===0&&o===n.size,rename:n,missing:i,bones:n.size}}const yv={fingers:.85,palm:.2,across:.07},yh={x:"shot/bot/xbot.glb",y:"shot/bot/ybot.glb"},ia={};let Sa=null;const vr=new Set,vv=()=>!!ia.x&&!!ia.y;function jv(e){return vr.add(e),()=>{vr.delete(e)}}function kv(e){if(Sa)return Sa;const n="/";return Sa=(async()=>{const{createGltfLoader:s}=await fn(async()=>{const{createGltfLoader:l}=await import("./gltfLoader-U0Eebg7v.js").then(h=>h.g);return{createGltfLoader:l}},__vite__mapDeps([7,6])),o=s(),[i,r]=await Promise.all([o.loadAsync(`${n}${yh.x}`),o.loadAsync(`${n}${yh.y}`)]);ia.x=vh(r.scene),ia.y=vh(i.scene);for(const l of[...vr])l()})().catch(s=>{throw Sa=null,s}),Sa}function vh(e){e.updateMatrixWorld(!0);const n=new zt().setFromObject(e),s=e.getObjectByName("mixamorigHips"),o=new oe;return s?.getWorldPosition(o),{scene:e,height:n.max.y-n.min.y,hipsY:o.y-n.min.y}}const wv=[["head","Head"],["arm","Arm"],["fore","ForeArm"],["wrist","Hand"],["thigh","UpLeg"],["shin","Leg"],["foot","Foot"]],Mv={thumb:"HandThumb",index:"HandIndex",middle:"HandMiddle",ring:"HandRing",pinky:"HandPinky"},Sv=[["Hips",1-rd,.3],["Spine",.73,.55],["Spine1",.87,.8],["Spine2",1,1]],Cv=.45,Nv=24,ko=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Av=/hair|bang|fringe|pony|braid|plait|ahoge|tress|bun|tail|ribbon|tassel|earring|hat|ear_?ring/i,Tv=/skirt|hem|coat|cape|cloak|robe|ribbon|tassel|sash|apron|scarf|cloth|flap|necktie|belt|frill|veil|mantle/i,Lv=/twist|eye|tooth|teeth|tongue|jaw|mouth|lip|brow|lid|cheek|nose|mask|weapon|sword|gun|ik|pole|target|end$|_end|helper/i,Ev=e=>new Ue(e).lerp(new Ue("#d8dbe0"),.55),Iv=e=>new Ue(e).offsetHSL(0,.05,-.12);function Rv(e,n,s,o="x"){const i=ia[o]??ia.x;if(!i)throw new Error("bot asset not loaded");return yu(Ed(i.scene),i.height,e,n,s,!1)}function bu(e){const n=[],s=new Set;let o=!1;e.traverse(r=>{r.isSkinnedMesh&&(o=!0),r.isBone&&!s.has(r.name)&&(s.add(r.name),n.push(r.name))});const i=bv(n);return{...i,ok:i.ok&&o,skinned:o,total:n.length}}function Fv(e,n,s,o){const i=bu(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 y of v.skeleton.bones)if(y&&!r.has(y)){let k=y;for(;k.parent;)k=k.parent;r.has(k)||(e.add(k),k.traverse(C=>r.add(C)))}}});const l=new rn,h=Ed(e);l.add(h);const u=new Set;h.traverse(v=>{const y=v.isBone?i.rename.get(v.name):void 0;y&&!u.has(v)&&(v.name=`mixamorig${y}`,u.add(v))}),h.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 oe);let d=0;for(const v of["Left","Right"]){const y=m(`${v}Foot`),k=m(`${v}ToeBase`);y&&k&&(d+=k.z-y.z)}d<0&&(h.rotation.y=Math.PI),l.updateMatrixWorld(!0);const f=l.getObjectByName("mixamorigHips");if(f){const v=new Set;for(let k=f.parent;k;k=k.parent)v.add(k);const y=[];l.traverse(k=>{if(!k.isBone||k===f||v.has(k))return;let C=k.parent;for(;C&&C!==f&&!v.has(C);)C=C.parent;C!==f&&k.parent&&v.has(k.parent)&&y.push(k)});for(const k of y)f.attach(k);l.updateMatrixWorld(!0)}const p=new zt().setFromObject(l),b=Math.max(.001,p.max.y-p.min.y);h.position.y-=p.min.y;const g=yu(l,b,n,s,{height:o},!0);return g.userData.botExact=i.exact,g.userData.nativeBones=i.bones,g}function yu(e,n,s,o,i,r){const l=Wt(i),h=Po({...i??{}},o),u=new rn;u.name="bot";const m=Xr(h,{},{bind:!0});m.root.name="driver",m.root.traverse(ae=>{ae.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(ae=>{if(!(ae instanceof ut)||(ae.castShadow=!0,ae.receiveShadow=!0,ae.frustumCulled=!1,r))return;const ke=/joint/i.test(ae.name);ae.material=new ns({color:ke?Iv(o):Ev(o),roughness:ke?.5:.42,metalness:ke?.15:.08})});const f=new Map;e.traverse(ae=>{ae.isBone&&!f.has(ae.name)&&f.set(ae.name,ae)});const p=f.get("mixamorigHips"),b={};for(const[ae,ke]of f)ae.startsWith("mixamorig")&&(b[ae.slice(9)]={q:ke.getWorldQuaternion(new Qe).toArray(),p:ke.getWorldPosition(new oe).toArray()});u.userData.botRest=b;const g=[],v=[],y=new oe,k=new oe,C=new Qe,S=ae=>ae.getWorldQuaternion(new Qe),I=(ae,ke)=>{ae.getWorldPosition(y);let Oe=null,Re=1e-6;for(const He of ae.children){He.getWorldPosition(k);const Ve=k.clone().sub(y);Ve.lengthSq()>Re&&(Re=Ve.lengthSq(),Oe=Ve)}return Oe?Oe.normalize():ke.clone()},j=ae=>Math.sign(ae.getWorldPosition(new oe).x||0),M=(ae,ke,Oe,Re=!1)=>{const He=m.bones.get(ae);if(!He){v.push(`driver ${ae}`);return}const Ve=j(He),Je=[...f.values()].filter(it=>it.name===`mixamorig${ke}`||it.name===`mixamorigLeft${ke}`||it.name===`mixamorigRight${ke}`),Ye=Je.length===1?Je[0]:Je.find(it=>Math.sign(it.getWorldPosition(new oe).x||0)===Ve);if(!Ye){v.push(`bone ${ke} for ${ae} (${Je.length} cands, want ${Ve})`);return}const We=Re?Oe:I(Ye,Oe),et=Re?Oe:I(He,Oe),ht=new Qe().setFromUnitVectors(We,et);g.push({bone:Ye,driver:He,cal:ht,restInv:S(He).invert(),mRest:S(Ye)})},T=new oe(0,1,0),w=new oe(0,-1,0),E=new oe(0,0,1);M("torso","Spine2",T,!0);for(const[ae,ke]of wv){if(ae==="head"){M("head",ke,T,!0);continue}const Oe=ae==="thigh"||ae==="shin"||ae==="foot";for(const Re of["L","R"])M(`${ae}${Re}`,ke,ae==="foot"?E:w,Oe)}for(const ae of["L","R"])for(const[ke,Oe]of Object.entries(Mv))for(let Re=1;Re<=3;Re++)M(`${ke}${Re}${ae}`,`${Oe}${Re}`,w);const N=ae=>f.get(`mixamorig${ae}`),A=m.bones.get("torso"),O=m.bones.get("head"),H=S(A),D=H.clone().invert(),$=S(O).invert(),W=N("Spine2"),z=W.getWorldPosition(new oe).applyMatrix4(A.matrixWorld.clone().invert()),Y=Sv.filter(([ae])=>N(ae)).map(([ae,ke,Oe])=>({bone:N(ae),lean:ke,twist:Oe,mRest:S(N(ae)),pos:N(ae).position.clone()})),J=N("Neck"),V=S(J),K=["Left","Right"].map(ae=>{const ke=f.get(`mixamorig${ae}Shoulder`),Oe=f.get(`mixamorig${ae}Arm`),Re=Math.sign(ke.getWorldPosition(new oe).x||0),He=["L","R"].map(Ve=>({S:Ve,a:m.bones.get(`arm${Ve}`),f:m.bones.get(`fore${Ve}`)})).find(Ve=>Math.sign(Ve.a.getWorldPosition(new oe).x||0)===Re);return{bone:ke,arm:Oe,sx:Re,drv:He,mRest:S(ke),armPos:Oe.position.clone(),follow:new Qe}}).filter(ae=>ae.bone&&ae.arm&&ae.drv),G=jh(m),_=p.getWorldPosition(new oe),ee=p.position.clone(),Q=new Map;for(const ae of f.values())Q.set(ae,ae.parent);const ve=new Map;for(const ae of g)ve.set(ae.bone,ae);const xe=[];p.traverse(ae=>{ae.isBone&&xe.push(ae)});const q=[];if(r){const ae=new Set([...f.values()].filter(He=>/^mixamorig/.test(He.name))),ke=f.get("mixamorigHead"),Oe=f.get("mixamorigNeck"),Re=new Map;for(const He of xe){if(ae.has(He)||Lv.test(He.name))continue;const Ve=He.children.find(it=>it.isBone);if(!Ve||Ve.position.lengthSq()<1e-10)continue;let Je=He.parent,Ye=!1;for(;Je&&!ae.has(Je);)Je=Je.parent;(Je===ke||Je===Oe)&&(Ye=!0);const We=Re.get(He.parent);if(!(Ye?Av.test(He.name)||We!==void 0:Tv.test(He.name)||We!==void 0))continue;const ht=We===void 0?0:We+1;Re.set(He,ht),q.push({bone:He,rest:He.quaternion.clone(),tip:Ve.position.clone(),hair:Ye,depth:ht})}}const ue={pos:new oe,time:-1},pe=new oe,U=new oe,le=new Qe,ce=new Qe,Le=new Qe,je=new Qe,ie=new oe,Me=new oe,Ee=new oe,Se=new oe;function he(ae){if(!q.length)return;for(const Ye of q)Ye.bone.quaternion.copy(Ye.rest);e.updateMatrixWorld(!0);const ke=f.get("mixamorigHead"),Oe=ae?.time??-1;ke?.getWorldPosition(Ee),U.set(0,0,0),ke&&Oe>=0&&ue.time>=0&&Oe>ue.time&&Oe-ue.time<.2&&U.subVectors(Ee,ue.pos).divideScalar(Oe-ue.time),ue.pos.copy(Ee),ue.time=Oe,u.getWorldQuaternion(le);const Re=ae?.vel??[0,0,0],He=ae?.acc??[0,0,0],Ve=ae?.air??0,Je=Math.hypot(Re[0],Re[1],Re[2]);for(const Ye of q){const We=(Ye.hair?.07:.1)*(1+.6*Ve),et=Ye.hair?.012:.016,ht=Ye.hair?.09:.05;pe.set(-Re[0]*We-He[0]*et,-Re[1]*We*.6-He[1]*et,-Re[2]*We-He[2]*et).applyQuaternion(le).addScaledVector(U,-ht),pe.length()>1.6&&pe.setLength(1.6);const it=Ye.bone,Ke=it.parent;Ke.updateWorldMatrix(!0,!1),it.updateWorldMatrix(!1,!1),it.getWorldPosition(Ee),Se.copy(Ye.tip).applyMatrix4(it.matrixWorld),ie.subVectors(Se,Ee);const Mt=ie.length();if(Mt<1e-6)continue;ie.divideScalar(Mt);const $t=.55+.25*Math.min(3,Ye.depth),Lt=Math.min(1,Je/3)*(Ye.hair?.07:.12),hn=Math.max(0,Oe)*(Ye.hair?3.7:5.3)+Ye.depth*.9+it.id*.37;Me.copy(ie).add(Se.set(0,Ye.hair?-.22:-.3,0)).addScaledVector(pe,$t),Lt&&(Me.x+=Math.sin(hn)*Lt,Me.z+=Math.cos(hn*.8)*Lt*.5),Me.normalize();const qn=u.getWorldPosition(Se).y+.02;if(Ee.y+Me.y*Mt<qn){Me.y=Math.min(1,(qn-Ee.y)/Mt);const bt=Math.hypot(Me.x,Me.z),$e=Math.sqrt(Math.max(0,1-Me.y*Me.y));bt>1e-6?(Me.x*=$e/bt,Me.z*=$e/bt):Me.x=$e,Me.normalize()}const Un=Ye.depth===0?.96:.35,Cn=ie.angleTo(Me);Cn>Un&&Me.lerp(ie,1-Un/Cn).normalize(),ce.setFromUnitVectors(ie,Me),Ke.getWorldQuaternion(Le),it.getWorldQuaternion(je),it.quaternion.copy(Le.invert().multiply(ce).multiply(je)),it.updateMatrixWorld(!0)}}const be=new Map,Fe=new Qe,Te=new Qe,_e=new Qe,ze=[];e.traverse(ae=>{ae.isSkinnedMesh&&ze.push(ae)});let Be=0;const Ze=()=>{e.updateMatrixWorld(!0);let ae=1/0;for(const ke of ze)aa(ke,(Oe,Re)=>{Re<ae&&(ae=Re)},u);Number.isFinite(ae)&&(Be-=ae,m.body.position.y=1+Be)};let F=s;const te=[];function Z(ae,ke,Oe){F=ae;for(const Re of q)Re.bone.quaternion.copy(Re.rest);Ho(m,h,ae),m.body.position.y=1+Be,m.root.updateMatrixWorld(!0),lt(),Ze(),lt();for(const Re of te)Re.userData.active=!!(ke&&ke.w>0);ke&&ke.w>0&&Xe(ke),he(Oe)}const re=new Qe,me=new Qe,Pe=new Qe,ye=new Qe,rt=new oe,It=new Qe;function qt(ae,ke,Oe,Re,He){const Ve=Math.max(0,Math.min(ae.n-1,Oe*ae.rate)),Je=Math.floor(Ve),Ye=Math.min(ae.n-1,Je+1),We=Ve-Je,et=ae.bones.length,ht=(Je*et+ke)*4,it=(Ye*et+ke)*4;return re.set(ae.q[ht],ae.q[ht+1],ae.q[ht+2],ae.q[ht+3]),me.set(ae.q[it],ae.q[it+1],ae.q[it+2],ae.q[it+3]),He.copy(re).slerp(me,We).normalize(),Re&&(rt.set(0,0,1).applyQuaternion(He),ye.setFromAxisAngle(T,-Math.atan2(rt.x,rt.z)),He.premultiply(ye)),He}function Xe(ae){const ke=Vl(ae.id);if(!ke)return;const Oe=ke.bones.length,Re=Math.min(1,ae.w),He=ae.from?Vl(ae.from.id):void 0,Ve=He?new Map(He.bones.map((We,et)=>[We,et])):null;for(let We=0;We<Oe;We++){const et=f.get(ke.bones[We]);if(!et)continue;qt(ke,We,ae.t,et===p,Pe);const ht=Ve?.get(ke.bones[We]);He&&ht!==void 0&&ae.from.k>0&&Pe.slerp(qt(He,ht,ae.from.t,et===p,It),Math.min(1,ae.from.k)).normalize(),Re>=1?et.quaternion.copy(Pe):et.quaternion.slerp(Pe,Re)}e.updateMatrixWorld(!0);let Je=1/0;for(const We of ze)aa(We,(et,ht)=>{ht<Je&&(Je=ht)},u);const Ye=ae.po;if(Number.isFinite(Je)&&Math.abs(Je)>1e-4||Ye){const We=p.getWorldPosition(new oe);Number.isFinite(Je)&&(We.y-=Je*u.getWorldScale(new oe).y),Ye&&(We.x-=Ye[0]*Re,We.z-=Ye[1]*Re),p.position.copy(p.parent.worldToLocal(We)),e.updateMatrixWorld(!0)}}function lt(){m.root.updateMatrixWorld(!0);const ae=jh(m),ke=_.clone().add(ae.sub(G));p.parent.updateWorldMatrix(!0,!1),p.position.copy(p.parent.worldToLocal(ke)),ee.y=ee.y,be.clear();const Oe=Yt(F);for(const Re of Y.slice(1))Re.bone.position.copy(Re.pos);for(const Re of xe){const He=Q.get(Re);be.has(He)?Fe.copy(be.get(He)):He.getWorldQuaternion(Fe);const Ve=ve.get(Re),Je=Oe.get(Re);Je?(_e.copy(Fe).invert(),Re.quaternion.copy(_e).multiply(Je)):Ve&&(Ve.driver.getWorldQuaternion(C),Te.copy(C).multiply(Ve.restInv).multiply(Ve.cal).multiply(Ve.mRest),_e.copy(Fe).invert(),Re.quaternion.copy(_e).multiply(Te)),be.set(Re,Fe.clone().multiply(Re.quaternion))}e.updateMatrixWorld(!0),bn()}const jt=new Qe,Ct=new Qe,gt=new Qe,at=new Qe,tn=new Qe,Ie=new oe(1,0,0),ot=new oe(0,1,0),nn=new oe(0,0,1),mt=new Qe,Rt=Ga(h);function Yt(ae){const ke=new Map,Oe=zn.degToRad,Re=ko(ae.lean),He=ko(ae.spineTwist),Ve=ko(ae.sideBend),Je=ko(ae.tumble)+Rt.torsoLean;A.parent.getWorldQuaternion(mt);const Ye=(Ke,Mt)=>mt.clone().multiply(jt.setFromAxisAngle(Ie,Oe(Je+Ke*Re))).multiply(Ct.setFromAxisAngle(ot,Oe(Mt*He))).multiply(gt.setFromAxisAngle(nn,Oe(Ke*Ve))).multiply(D);for(const Ke of Y)(Ke.lean<1||Ke.twist<1)&&ke.set(Ke.bone,Ye(Ke.lean,Ke.twist).multiply(Ke.mRest));const We=A.getWorldQuaternion(at).multiply(D).clone(),et=O.getWorldQuaternion(tn).multiply($).clone();ke.set(J,We.clone().slerp(et,Cv).multiply(V));const ht=new oe(0,-1,0).applyQuaternion(We),it=new oe(0,0,1).applyQuaternion(We);for(const Ke of K){const Mt=Ke.drv.f.getWorldPosition(new oe).sub(Ke.drv.a.getWorldPosition(new oe)).normalize(),$t=zn.radToDeg(Mt.angleTo(ht)),Lt=zn.clamp(($t-80)/90,0,1);Ke.follow.copy(We).multiply(Ke.mRest);const hn=new Qe().setFromAxisAngle(it,Oe(Ke.sx*Nv*Lt*Lt*(3-2*Lt)));ke.set(Ke.bone,hn.multiply(Ke.follow))}return ke}const ln=new oe,Qt=new oe,xt=new At,cn=new oe,Ft=new oe,Zt=new Qe;function bn(){Qt.copy(z).applyMatrix4(A.matrixWorld);const ae=Qt.sub(W.getWorldPosition(ln)).multiplyScalar(1/3);for(const ke of Y.slice(1)){ke.bone.parent.updateWorldMatrix(!0,!1);const Oe=ke.bone.getWorldPosition(new oe).add(ae);ke.bone.position.copy(ke.bone.parent.worldToLocal(Oe)),ke.bone.updateMatrixWorld(!0)}for(const ke of K){ke.bone.matrixWorld.decompose(cn,Zt,Ft);const Oe=ke.armPos.clone().applyMatrix4(xt.compose(cn,ke.follow,Ft));ke.arm.position.copy(ke.bone.worldToLocal(Oe)),ke.arm.updateMatrixWorld(!0)}}Z(s),u.updateMatrixWorld(!0);for(const ae of["L","R"]){const ke=g.find($e=>$e.driver.name===`wrist${ae}`);if(!ke)continue;const Oe=$e=>f.get(`${ke.bone.name}${$e}`)?.getWorldPosition(new oe),Re=ke.bone.getWorldPosition(new oe),He=Oe("Index1"),Ve=Oe("Middle1"),Je=Oe("Pinky1"),Ye=Oe("Thumb1");if(!He||!Ve||!Je||!Ye)continue;const We=He.clone().sub(Je).normalize(),et=Ve.clone().sub(Re);et.addScaledVector(We,-et.dot(We)).normalize();let ht=new oe().crossVectors(et,We);ht.dot(Ye.clone().sub(Re))<0&&ht.negate();const it=new oe().setFromMatrixScale(ke.driver.matrixWorld),Ke=Ve.distanceTo(Re),Mt=yv,$t=Re.clone().addScaledVector(et,Mt.fingers*Ke).addScaledVector(ht,Mt.palm*Ke).addScaledVector(We,Mt.across*Ke),Lt=We,hn=et,qn=new oe().crossVectors(hn,Lt).normalize(),Un=new At().makeBasis(qn,hn,Lt).setPosition($t).scale(it),Cn=ke.bone.matrixWorld.clone().invert().multiply(Un),bt=new ng;bt.name=`rigHold${ae}`,bt.userData.rigHold=ae,bt.userData.active=!1,te.push(bt),Cn.decompose(bt.position,bt.quaternion,bt.scale),ke.bone.add(bt)}const Gn=(ae,ke,Oe,Re)=>{for(const $e of xe){const yt=ae.get($e.name);yt&&$e.quaternion.copy(yt)}ke&&p.position.copy(ke),e.rotation.y=0,e.updateMatrixWorld(!0);const He=p.getWorldPosition(new oe),Ve=(()=>{const $e=p.getWorldQuaternion(new Qe),yt=new oe(0,0,1).applyQuaternion($e);if(!Re?.steadyYaw)return Math.atan2(yt.x,yt.z);const yn=new oe(1,0,0).applyQuaternion($e);return Math.atan2(yt.x-yn.z,yt.z+yn.x)})();e.rotation.y=-Ve,e.updateMatrixWorld(!0),Ho(m,h,{},{bind:!0}),m.root.updateMatrixWorld(!0);const Je=new Qe,Ye=new Qe,We=new Qe;for(const $e of g)$e.bone.getWorldQuaternion(Je),Ye.copy(Je).multiply($e.mRest.clone().invert()).multiply($e.cal.clone().invert()).multiply($e.restInv.clone().invert()),$e.driver.parent.getWorldQuaternion(We),$e.driver.quaternion.copy(We.invert()).multiply(Ye),$e.driver.updateMatrixWorld(!0);const et=Ga(h),ht=zn.radToDeg,it=new rr,Ke={},Mt=$e=>(($e+180)%360+360)%360-180,$t=($e,yt,yn=[])=>{const ks=m.bones.get($e);it.setFromQuaternion(ks.quaternion,yt);const Ce=[ht(it.x),ht(it.y),ht(it.z)],dn=Kt=>{const Et=yn[Kt];if(!(!Oe||!Et||Oe[Et[0]]===void 0))return Oe[Et[0]]*Et[1]},un=yt[1]==="X"?0:yt[1]==="Y"?1:2,Pn=Ce.map((Kt,Et)=>Mt(Et===un?180-Kt:Kt+180)),Ae=Kt=>Kt.reduce((Et,Ht,mn)=>{const Nn=dn(mn);return Et+(Nn===void 0?0:Math.abs(Mt(Ht-Nn)))+.05*Math.abs(Ht)},0);let Dt=Ae(Pn)<Ae(Ce)?Pn:Ce;if(Oe&&Math.abs(Dt[un])>70){const Kt=[0,1,2].filter(ws=>ws!==un),[Et,Ht]=Kt,mn=(yt==="XYZ"?-1:1)*Math.sign(Dt[un]),Nn=dn(Et),Xn=dn(Ht);if(Nn!==void 0&&Xn!==void 0){const ws=(Mt(Nn-Dt[Et])*mn+Mt(Xn-Dt[Ht]))/2,we=[...Dt];we[Et]=Mt(Dt[Et]+mn*ws),we[Ht]=Mt(Dt[Ht]+ws);const Qa=new rr(zn.degToRad(we[0]),zn.degToRad(we[1]),zn.degToRad(we[2]),yt),si=new Qe().setFromEuler(Qa);2*Math.acos(Math.min(1,Math.abs(si.dot(ks.quaternion))))*57.3<4&&(Dt=we)}}return Dt},[Lt,hn,qn]=$t("torso","XYZ",[["lean",1],["spineTwist",1],["sideBend",1]]);Ke.lean=Lt-et.torsoLean,Ke.spineTwist=hn,Ke.sideBend=qn;const[Un,Cn,bt]=$t("head","YXZ",[["headPitch",1],["head",1],["headRoll",1]]);Ke.headPitch=Un-et.headPitch,Ke.head=Cn,Ke.headRoll=bt;for(const $e of["L","R"]){const yt=$e==="L",yn=yt?1:-1,[ks,Ce,dn]=$t(`arm${$e}`,"XZY",[[`shoulder${$e}`,1],[`armTwist${$e}`,yt?1:-1],[`shoulderOut${$e}`,yt?-1:1]]);Ke[`shoulder${$e}`]=ks,Ke[`armTwist${$e}`]=yt?Ce:-Ce,Ke[`shoulderOut${$e}`]=yt?-dn:dn,Ke[`elbow${$e}`]=-$t(`fore${$e}`,"XYZ")[0];const[un,Pn,Ae]=$t(`wrist${$e}`,"YXZ",[[`wrist${$e}`,1],[`wristTwist${$e}`,-yn],[`wristSide${$e}`,-yn]]);Ke[`wrist${$e}`]=un,Ke[`wristTwist${$e}`]=-Pn*yn,Ke[`wristSide${$e}`]=-Ae*yn;const[Dt,Kt,Et]=$t(`thigh${$e}`,"XZY",[[`hip${$e}`,1],[`hipTwist${$e}`,yt?1:-1],[`hipOut${$e}`,yt?-1:1]]);Ke[`hip${$e}`]=Dt,Ke[`hipTwist${$e}`]=yt?Kt:-Kt,Ke[`hipOut${$e}`]=yt?-Et:Et,Ke[`knee${$e}`]=$t(`shin${$e}`,"XYZ")[0],Ke[`ankle${$e}`]=$t(`foot${$e}`,"XYZ")[0];const Ht=mn=>Math.abs($t(`${mn}2${$e}`,"XYZ")[2]);Ke[`grip${$e}`]=Math.max(0,Math.min(100,(Ht("index")+Ht("middle")+Ht("ring"))/3/100*100)),Ke[`thumb${$e}`]=Math.max(0,Math.min(100,Ht("thumb")/60*100))}return e.rotation.y=0,{pose:Ke,hips:He,yaw:ht(Ve)}};return u.userData.bot={repose:Z,poseFrom:Gn},u.userData.dynamicBones=q.length,u.userData.botMisses=v,u.userData.botLinks=g.map(ae=>`${ae.driver.name}→${ae.bone.name.replace("mixamorig","")} cal ${Math.round(2*Math.acos(Math.min(1,Math.abs(ae.cal.w)))*57.3)}°`),u}function jh(e){const n=e.bones.get("thighL").getWorldPosition(new oe),s=e.bones.get("thighR").getWorldPosition(new oe);return n.add(s).multiplyScalar(.5)}ss.bot={ready:vv,load:()=>kv(),onAsset:jv,build:Rv,native:Fv,nativeOf:bu};function Pv(e,n,s={}){const o=n.items.find(h=>h.id===s.selected&&h.kind!=="fx"&&!h.hidden)??null,i=Math.max(0,+(s.start??0).toFixed(2)),r=Dg(e,{items:n.items,selected:o,ground:s.ground??[0,0,0],reach:s.reach,anchor:s.anchor?(h,u)=>s.anchor(h.id,u,i):null}),l={...mp(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{...Mn("fx",n.items.length),name:e.name,color:e.color,position:r.position,rotation:r.rotation,fx:l}}function $v(e,n,s){const o=n.fx,i=e.shots.find(u=>u.id===e.activeShot)??e.shots[0],r=Math.min(o.start,Math.max(0,i.duration-.2)),l=s?.fill?Math.max(Math.min(s.duration,3),i.duration-r):o.duration,h={start:+r.toFixed(2),duration:+Math.min(60,l).toFixed(2),...o.loop?{loop:!0}:{}};return{...e,items:[...e.items,{...n,fx:{...o,start:h.start,duration:h.duration}}],shots:e.shots.map(u=>u.id===i.id?{...u,fxTiming:{...u.fxTiming,[n.id]:h}}:u)}}function vu(e,n,s={}){const o=Pv(n,e,s),i=e.items.filter(u=>u.kind==="fx"&&u.fx?.preset===n.preset).length,r={...o,name:`${s.label??n.name} ${i+1}`},l=up(e.items,r.fx);if(!l.ok)return{error:"limit",detail:l.errors.join("; ")};const h=$v(e,r,n);return{stage:h,item:h.items[h.items.length-1]}}let jr=0;const kr=new Set;function ju(e=!1){return pp("fx",e).then(n=>{fp(n.filter(s=>s.kind==="fx"&&s.preset).map(s=>gp(s))),jr++,kr.forEach(s=>s())},()=>{})}function Dv(){const[e,n]=R.useState(jr);return R.useEffect(()=>{const s=()=>n(jr);return kr.add(s),ju(),()=>{kr.delete(s)}},[]),{entries:xp(),version:e}}const kh=new Map;function ku(e){let n=kh.get(e.id);return n||(n=yp(e,24),kh.set(e.id,n)),n}const wu=(e,n)=>e[Math.max(0,Math.min(e.length-1,Math.round(n*24)))];function Ov(e){const n=e.keys.find(s=>s.strike);return n?n.t:e.duration/2}const wh=(e,n)=>[e[0]-n[0],e[1]-n[1],e[2]-n[2]],Wi=(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]],Gi=(e,n)=>e[0]*n[0]+e[1]*n[1]+e[2]*n[2],Mh=e=>{const n=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/n,e[1]/n,e[2]/n]};function _v(e,n,s){const o=Mh(wh(e.target,e.position)),i=Mh(Wi(o,[0,1,0])),r=Wi(i,o),l=Math.cos(e.roll*Math.PI/180),h=Math.sin(e.roll*Math.PI/180),u=[i[0]*l+r[0]*h,i[1]*l+r[1]*h,i[2]*l+r[2]*h],m=Wi(u,o),d=e.lens/36*n;return f=>{const p=wh(f,e.position),b=Gi(p,o);return b<.05?null:[n/2+Gi(p,u)/b*d,s/2-Gi(p,m)/b*d]}}const zv=[["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"]],Sh={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 Mu(e,n,s,o="spear"){const i=Kg(e.pose),r=Math.cos(s*Math.PI/180),l=Math.sin(s*Math.PI/180),h=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]=h(i[g]));const m=vp(e.pose),d=[0,1-i.lift,0],f=g=>h([d[0]+g[0],d[1]+g[1],d[2]+g[2]]),p=Sh[o]??Sh.spear,b=g=>f(m.front.map((v,y)=>v+m.dir[y]*g));return{pts:u,tip:b(p.tip),butt:b(-p.butt),blade:b(p.blade)}}function Su(e,n,s,o,i,r=0){const l=_v(o,n,s),h=e.createLinearGradient(0,0,0,s);h.addColorStop(0,"#1a2532"),h.addColorStop(1,"#0b1018"),e.fillStyle=h,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 b=l(f),g=l(p);!b||!g||(e.beginPath(),e.moveTo(b[0],b[1]),e.lineTo(g[0],g[1]),e.stroke())}for(const d of i){const f=(g,v,y,k)=>{const C=l(g),S=l(v);!C||!S||(e.strokeStyle=y,e.lineWidth=k,e.beginPath(),e.moveTo(C[0],C[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 zv)f(d.pts[g],d.pts[v],"#dfe6ee",2.2*p);const b=l(d.pts.head);b&&(e.fillStyle="#dfe6ee",e.beginPath(),e.arc(b[0],b[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 Bv(e,n,s,o,i,r="spear"){const l=ku(n),h=wu(l,s),u=[h.dx??0,h.dy??0,h.dz??0],m=h.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};Su(e,o,i,p,[Mu(h,u,m,r)])}const Kv=["spear-thrust","spear-double-thrust","spear-spin"].map(e=>bp.find(n=>n.id===e)).filter(Boolean),ta=(()=>{let e=0,n=0;const s=Kv.map(i=>{const r=ku(i),l={clip:i,s:r,at:e,z:n};return e+=i.duration,n+=r[r.length-1].dz??0,l}),o=s.flatMap(i=>i.clip.keys.filter(r=>r.strike).map(r=>i.at+r.t));return{parts:s,duration:e,beats:o}})(),Hv=ta.duration;function Ch(e){const n=[...ta.parts].reverse().find(o=>e>=o.at)??ta.parts[0],s=wu(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 Wv(e,n,s,o,i){const r={start:0,end:ta.duration,yaw:0,height:1.8,beats:ta.beats,centre:m=>{const d=Ch(m);return[d.root[0],0,d.root[2]]}},l=Og(n,s,r),h=Ch(s),u=ta.beats.reduce((m,d)=>Math.max(m,s>=d&&s-d<.12?1-(s-d)/.12:0),0);Su(e,o,i,l,[Mu(h.k,h.root,h.yaw)],n.beats?u:0)}const Xo=e=>e.normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/đ/g,"d").toLowerCase();function Cu({draw:e,rest:n,loop:s,hot:o}){const i=R.useRef(null);return R.useEffect(()=>{const r=i.current,l=r?.getContext("2d");if(!r||!l)return;if(!o){e(l,n,r.width,r.height);return}let h=0;const u=performance.now(),m=()=>{e(l,(performance.now()-u)/1e3%s,r.width,r.height),h=requestAnimationFrame(m)};return h=requestAnimationFrame(m),()=>cancelAnimationFrame(h)},[e,n,s,o]),t.jsx("canvas",{ref:i,width:192,height:108,"aria-hidden":"true"})}function Gv({stage:e,selected:n,playhead:s,change:o,setError:i,query:r}){const l=ct(),h=l==="en",[u,m]=R.useState(null),[d,f]=R.useState("all"),p=Xo(r.trim()),b=_g.filter(y=>p?Xo(`${y.name} ${y.nameEn} ${y.desc??""} ${y.id}`).includes(p):d==="all"||y.cat===d),g=zg(e,n),v=y=>{if(!g){i(a("Thêm một nhân vật hoặc vật thể vào cảnh để camera bám theo."));return}const k=Sc(e,{preset:y,subject:g.id,start:s});if(!k.ok){i(k.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead cho chuyển động camera."):k.error);return}i(""),o(C=>{const S=Sc(C,{preset:y,subject:g.id,start:s});return S.ok?S.stage:C})};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Nhóm camera"),children:[{id:"all",name:"Tất cả",nameEn:"All"},...Bg].map(y=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===y.id,className:d===y.id&&!p?"active":"",onClick:()=>f(y.id),children:h?y.nameEn:a(y.name)},y.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("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]):a("Thêm một nhân vật vào cảnh để camera bám theo.")}),t.jsxs("div",{className:"shot-fx-grid",children:[b.map(y=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-camera":y.id,title:h?y.descEn:y.desc,onMouseEnter:()=>m(y.id),onMouseLeave:()=>m(null),onFocus:()=>m(y.id),onBlur:()=>m(null),onClick:()=>v(y),children:[t.jsx(Cu,{draw:(k,C,S,I)=>Wv(k,y,C,S,I),rest:1.2,loop:Hv,hot:u===y.id}),t.jsx("span",{children:h?y.nameEn:y.name})]},y.id)),!b.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có camera nào khớp.")})]})]})}function qv({stage:e,selected:n,onPlay:s,setError:o,query:i}){const r=ct(),l=r==="en",[h,u]=R.useState(null),[m,d]=R.useState("all"),f=Xo(i.trim()),p=jp.filter(({clip:y,pack:k})=>f?Xo(`${y.label} ${y.labelEn} ${y.id} ${k.label} ${k.labelEn} ${k.id==="spear"?"thuong giao":k.id==="katana"?"kiem guom":"con gay truong"}`).includes(f):m==="all"||k.id===m),b=n?e.items.find(y=>y.id===n):null,g=b&&Fr(b)?b:e.items.find(y=>y.kind==="person"&&!y.hidden)??null,v=y=>{const k=kp(y.id);if(!g||!k){o(a("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}o(""),s(g.id,k)};return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-fx-cats shot-lib-subcats",role:"tablist","aria-label":a("Loại vũ khí"),children:[{id:"all",label:"Tất cả",labelEn:"All"},...dd].map(y=>t.jsx("button",{type:"button",role:"tab","data-weapon-pack":y.id,"aria-selected":m===y.id,className:m===y.id&&!f?"active":"",onClick:()=>d(y.id),children:l?y.labelEn:a(y.label)},y.id))}),t.jsx("p",{className:"shot-fx-hint",children:g?a("Áp lên “{0}” từ playhead — tự đặt vũ khí vào tay, hai tay bám cán.",[g.name]):a("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:y,pack:k})=>t.jsxs("button",{type:"button",className:"shot-fx-card shot-lib-card","data-combo":y.id,title:`${l?y.labelEn:y.label} · ${y.duration}s`,onMouseEnter:()=>u(y.id),onMouseLeave:()=>u(null),onFocus:()=>u(y.id),onBlur:()=>u(null),onClick:()=>v(y),children:[t.jsx(Cu,{draw:(C,S,I,j)=>Bv(C,y,S,I,j,k.prop.prop),rest:Ov(y),loop:y.duration+.4,hot:h===y.id}),t.jsx("span",{children:l?y.labelEn:y.label})]},y.id)),!p.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có combo nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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 Uv=[.5,.3,.15],Xv=[["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"]],Vv=e=>{const{trail:n,...s}=e;return s};function Yv({stage:e,playhead:n,change:s,setError:o}){ct();const[i,r]=R.useState("medium"),[l,h]=R.useState(.3),u=e.shots.find(j=>j.id===e.activeShot)??e.shots[0],m=u.duration,d=so(u.timing,m),f=wp(e).map(j=>j.time),p=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const w=j(so(T.timing,T.duration)),{timing:E,...N}=T;return w?{...N,timing:w}:N})})),b=()=>e.items.filter(j=>Fr(j)).flatMap(j=>Ep([...u.objectKeys?.[j.id]||[]].sort((M,T)=>M.time-T.time).map(M=>({t:M.time*m,y:M.position[1],air:!!M.air})))),g=e.items.filter(j=>j.kind==="prop"&&j.hold&&j.prop&&Mp[j.prop.kind]),v=g.length>0&&g.every(j=>j.trail),y=(j,M={})=>s(T=>({...T,items:T.items.map(w=>g.some(E=>E.id===w.id)?j?{...w,trail:{...w.trail||{},...M}}:Vv(w):w)})),k=g[0]?.trail?.style??"ribbon",C=Sp({duration:m,timing:d??void 0}),S=Cp(u.impactFrame),I=j=>s(M=>({...M,shots:M.shots.map(T=>{if(T.id!==M.activeShot)return T;const{impactFrame:w,...E}=T;return j?{...E,impactFrame:j}:E})}));return t.jsxs("div",{className:"shot-timing",children:[t.jsx("p",{className:"shot-fx-hint",children:a("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:a("Nhịp anime (sakuga)")}),t.jsx("p",{className:"shot-fx-hint",children:a("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 j=Np(u,Ap(e),{keepLook:!1});if(!j){o(a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."));return}o(""),s(M=>({...M,shots:M.shots.map(T=>T.id===M.activeShot?{...T,timing:j.shot.timing,impacts:j.shot.impacts,impactFrame:j.shot.impactFrame}:T)}))},children:a("Áp nhịp anime ({0} đòn)",[u.impacts?.length||f.length])})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Hit-stop")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ khựng")}),t.jsxs("select",{"aria-label":a("Độ khựng"),value:i,onChange:j=>r(j.target.value),children:[t.jsx("option",{value:"light",children:a("Nhẹ")}),t.jsx("option",{value:"medium",children:a("Vừa")}),t.jsx("option",{value:"heavy",children:a("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:a("Chưa có đòn đánh nào trong shot (áp một combo vũ khí hoặc động tác võ trước)."),onClick:()=>{o(""),p(j=>Yl(j,f,Ql[i],m))},children:a("Khựng mọi đòn ({0})",[f.length])}),t.jsx("button",{type:"button",onClick:()=>p(j=>Yl(j,[n],Ql[i],m)),children:a("Khựng tại playhead")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Slow-mo")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tốc độ")}),t.jsx("select",{"aria-label":a("Tốc độ slow-mo"),value:l,onChange:j=>h(+j.target.value),children:Uv.map(j=>t.jsxs("option",{value:j,children:[Math.round(j*100),"%"]},j))})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-timing":"apex",onClick:()=>{const j=b();if(!j.length){o(a("Không thấy cú nhảy nào trong shot."));return}o(""),p(M=>j.reduce((T,w)=>ji(T,w,.3,l,m),M))},children:a("Chậm ở đỉnh cú nhảy")}),t.jsx("button",{type:"button","data-timing":"slow-playhead",onClick:()=>p(j=>ji(j,n,.35,l,m)),children:a("Chậm quanh playhead")}),f.length>0&&t.jsx("button",{type:"button",onClick:()=>p(j=>ji(j,f[f.length-1],.3,l,m)),children:a("Chậm đòn kết")})]})]}),d&&t.jsxs("div",{className:"shot-list shot-timing-list",children:[d.holds.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["⏸ ",a("Khựng {0}s · {1}s",[j.at.toFixed(2),j.hold.toFixed(2)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ khựng {0}s",[j.at.toFixed(2)]),onClick:()=>p(M=>so({holds:(M?.holds||[]).filter(T=>T.at!==j.at),slows:M?.slows||[]},m)),children:t.jsx(Ne.trash,{})})]},`h${j.at}`)),d.slows.map(j=>t.jsxs("div",{children:[t.jsxs("span",{children:["🐢 ",a("Chậm {0}–{1}s · {2}%",[j.start.toFixed(2),j.end.toFixed(2),Math.round(j.speed*100)])]}),t.jsx("button",{type:"button","aria-label":a("Bỏ slow-mo {0}s",[j.start.toFixed(2)]),onClick:()=>p(M=>so({holds:M?.holds||[],slows:(M?.slows||[]).filter(T=>T.start!==j.start)},m)),children:t.jsx(Ne.trash,{})})]},`s${j.start}`))]}),t.jsx("p",{className:"shot-fx-hint","data-testid":"timing-length",children:d?a("Video dài {0}s (shot {1}s).",[C.toFixed(2),m.toFixed(2)]):a("Chưa có hit-stop hay slow-mo.")}),d&&t.jsx("button",{type:"button",onClick:()=>p(()=>null),children:a("Xoá nhịp đòn")}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khung va chạm")}),t.jsx("p",{className:"shot-fx-hint",children:a("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:a("Kiểu")}),t.jsxs("select",{"aria-label":a("Kiểu khung va chạm"),"data-timing":"impact-style",value:S?.style??"",onChange:j=>I(j.target.value?{style:j.target.value,strength:S?.strength??1}:null),children:[t.jsx("option",{value:"",children:a("Không")}),Xv.map(([j,M])=>t.jsx("option",{value:j,children:a(M)},j))]})]}),S&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Độ mạnh")}),t.jsx("input",{type:"range","aria-label":a("Độ mạnh khung va chạm"),min:.1,max:1,step:.05,value:S.strength,onChange:j=>I({...S,strength:+j.target.value})})]}),S&&!d?.holds.length&&t.jsx("p",{className:"shot-fx-hint",children:a("Thêm hit-stop để khung va chạm hiện ra.")})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Vệt chém")}),g.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Vệt chém trên vũ khí đang cầm ({0})",[g.length])}),t.jsx("input",{type:"checkbox","aria-label":a("Vệt chém"),checked:v,onChange:j=>y(j.target.checked)})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu vệt")}),t.jsxs("select",{"aria-label":a("Kiểu vệt chém"),"data-timing":"trail-style",value:k,onChange:j=>y(!0,{style:j.target.value}),children:[t.jsx("option",{value:"ribbon",children:a("Dải sáng")}),t.jsx("option",{value:"smear",children:a("Smear trắng (anime)")})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu vệt")}),t.jsx("input",{type:"color","aria-label":a("Màu vệt chém"),value:g[0].trail?.color||(k==="smear"?Tp.color:Lp.color),onChange:j=>y(!0,{color:j.target.value})})]})]}):t.jsx("p",{className:"shot-fx-hint",children:a("Chưa có vũ khí nào đang cầm (thương, kiếm, côn, gậy, dao).")})]})]})}const Qv={blocked:"đỡ",miss:"né",body:"trúng"};function Zv({stage:e,playhead:n,change:s,setError:o}){const i=ct(),r=i==="en",l=e.items.filter(N=>Fr(N)&&!N.hidden),[h,u]=R.useState(""),[m,d]=R.useState(""),[f,p]=R.useState(["katana","katana"]),[b,g]=R.useState(4),[v,y]=R.useState(1),[k,C]=R.useState(!0),[S,I]=R.useState(""),j=l.find(N=>N.id===h)??l[0],M=l.find(N=>N.id===m&&N.id!==j?.id)??l.find(N=>N.id!==j?.id),T=()=>s(N=>{const A=N.items.find(H=>H.id===j?.id),O=A?[A.position[0],0,A.position[2]+2]:[0,0,2];return{...N,items:[...N.items,{...Mn("person",N.items.length),name:a("Đối thủ"),position:O,rotation:[0,180,0]}]}}),w=N=>{if(!j||!M){o(a("Cần hai nhân vật trong cảnh để dàn cảnh đấu."));return}const A=Wg(e,{a:j.id,b:M.id,packs:f,exchanges:b,seed:N,start:n},()=>crypto.randomUUID());if(!A.ok){o(A.error);return}let O=A.stage;if(k)try{O=Ip(O,{fighters:[j.name,M.name],start:n,end:A.end+.4}).stage}catch{}o(""),y(N),I(A.plan.map(H=>`${H.time.toFixed(1)}s ${H.attackerName} → ${r?H.result:a(Qv[H.result])}`).join(" · ")),s(()=>O)},E=(N,A)=>p(O=>N===0?[A,O[1]]:[O[0],A]);return t.jsxs("fieldset",{className:"shot-duel",children:[t.jsx("legend",{children:a("Đấu 2 người")}),l.length<2?t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:a("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:a("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?a("Người tấn công trước"):a("Đối thủ"),value:(N===0?j:M)?.id??"",onChange:A=>(N===0?u:d)(A.target.value),children:l.filter(A=>N===0||A.id!==j?.id).map(A=>t.jsx("option",{value:A.id,children:A.name},A.id))}),t.jsx("select",{"aria-label":a("Vũ khí"),"data-duel-weapon":N,value:f[N],onChange:A=>E(N,A.target.value),children:[...dd.filter(A=>A.id in Hg),{id:"fist",label:"Tay không",labelEn:"Unarmed"}].map(A=>t.jsx("option",{value:A.id,children:r?A.labelEn:a(A.label)},A.id))})]},N)),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Số pha đấu")}),t.jsx("input",{type:"number","aria-label":a("Số pha đấu"),min:1,max:10,value:b,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:a("Camera đấu (giữ cả hai trong khung)")}),t.jsx("input",{type:"checkbox","aria-label":a("Camera đấu"),checked:k,onChange:N=>C(N.target.checked)})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button","data-duel":"stage",onClick:()=>w(v),children:a("Dàn cảnh đấu từ playhead")}),t.jsx("button",{type:"button","data-duel":"reroll",onClick:()=>w(v+1),children:a("Phương án khác")})]}),t.jsx("p",{className:"shot-fx-hint",children:S||a("Đò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 wr="application/x-clipoox-fx",Mr=(e,n)=>e.lib?n==="en"&&e.nameEn?e.nameEn:e.name:a(e.name),Jv=(e,n)=>e.lib?n==="en"&&e.descEn?e.descEn:e.desc:a(e.desc);function e1({entry:e,hot:n}){const s=R.useRef(null);return R.useEffect(()=>{const o=s.current;if(!o)return;const i=o.getContext("2d");if(!i)return;const r=o.width,l=o.height;if(!n){Mc(i,e,Fg(e),r,l);return}let h=0;const u=performance.now(),m=Pg(e),d=()=>{Mc(i,e,(performance.now()-u)/1e3%m,r,l),h=requestAnimationFrame(d)};return h=requestAnimationFrame(d),()=>cancelAnimationFrame(h)},[e,n]),t.jsx("canvas",{ref:s,width:192,height:108,"aria-hidden":"true"})}function Ks({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}const Nh=[["chest","ngực"],["head","đầu"],["feet","chân"],["hand_right","tay phải"],["hand_left","tay trái"]];function t1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,anchor:l,setError:h,onEdit:u,onPlayClip:m}){const d=ct(),f=Dv(),[p,b]=R.useState(""),[g,v]=R.useState("tu-tien"),[y,k]=R.useState(null),C=e.shots.find(T=>T.id===e.activeShot)??e.shots[0],S=R.useMemo(()=>g==="camera"||g==="weapon"||g==="timing"?[]:Rp(p,p.trim()?void 0:g),[p,g,f.version]),I=e.items.filter(T=>T.kind==="fx"&&T.fx),j=I.find(T=>T.id===n)??null,M=T=>{const w=vu(e,T,{selected:n,ground:r(),start:s,label:Mr(T,d),anchor:l});if("error"in w){h(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[xn.maxItems]));return}h(""),o(()=>w.stage),i(w.item.id)};return t.jsxs("div",{className:"shot-fx",children:[j&&u&&t.jsxs("button",{type:"button",className:"shot-fx-edit-jump",onClick:u,children:["✎ ",a("Sửa {0}",[j.name])]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm hiệu ứng"),placeholder:a("Tìm hiệu ứng… (vd: kiem, set, aura)"),value:p,onChange:T=>b(T.target.value)})}),t.jsxs("div",{className:"shot-fx-cats",role:"tablist","aria-label":a("Nhóm hiệu ứng"),children:[Fp.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?a(T.name):a("Sắp có"),onClick:()=>{v(T.id),b("")},children:[a(T.name),!T.ready&&t.jsx("small",{children:a("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:["🎥 ",a("Camera")]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":g==="weapon",className:`shot-lib-tab${g==="weapon"?" active":""}`,onClick:()=>v("weapon"),children:["⚔ ",a("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:["⏱ ",a("Nhịp đòn")]})]}),g==="camera"&&t.jsx(Gv,{stage:e,selected:n,playhead:s,change:o,setError:h,query:p}),g==="weapon"&&!p&&t.jsx(Zv,{stage:e,playhead:s,change:o,setError:h}),g==="weapon"&&(m?t.jsx(qv,{stage:e,selected:n,onPlay:m,setError:h,query:p}):null),g==="timing"&&t.jsx(Yv,{stage:e,playhead:s,change:o,setError:h}),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:Jv(T,d),onMouseEnter:()=>k(T.id),onMouseLeave:()=>k(null),onFocus:()=>k(T.id),onBlur:()=>k(null),onDragStart:w=>{w.dataTransfer.setData(wr,T.id),w.dataTransfer.effectAllowed="copy"},onClick:()=>M(T),children:[t.jsx(e1,{entry:T,hot:y===T.id}),t.jsx("span",{children:Mr(T,d)}),T.lib&&t.jsx("small",{className:"shot-fx-lib",children:a("Thư viện Clipoox")})]},T.id)),!S.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có hiệu ứng nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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:[a("Hiệu ứng trong cảnh")," ",t.jsxs("small",{className:"shot-total",children:["· ",I.length,"/",xn.maxItems]})]}),t.jsxs("div",{className:"shot-list shot-fx-list",children:[I.map(T=>{const w=Fn(T,C);return t.jsxs("div",{className:n===T.id?"active":"",children:[t.jsxs("button",{title:a("Sửa {0}",[T.name]),onClick:()=>{i(T.id),u?.()},children:["✦ ",T.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",w.off?a("không phát trong shot này"):`${w.start.toFixed(1)}s → ${(w.start+w.duration).toFixed(1)}s`]})]}),t.jsx("button",{title:T.hidden?a("Hiện"):a("Ẩn"),onClick:()=>o(E=>({...E,items:E.items.map(N=>N.id===T.id?{...N,hidden:!N.hidden}:N)})),children:T.hidden?"○":"●"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[T.name]),title:a("Xóa {0}",[T.name]),onClick:()=>{o(E=>({...E,items:E.items.filter(N=>N.id!==T.id),shots:E.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(Ne.trash,{})})]},T.id)}),!I.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Chưa có hiệu ứng. Chọn một thẻ ở trên.")})]})]})}function n1({stage:e,selected:n,playhead:s,change:o,onSelect:i,ground:r,engine:l}){ct();const h=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":a("Hiệu ứng đang sửa"),value:m?.id??"",onChange:d=>i(d.target.value||null),children:[!m&&t.jsx("option",{value:"",children:a("Chọn hiệu ứng…")}),u.map(d=>t.jsxs("option",{value:d.id,children:["✦ ",d.name]},d.id))]}),m?t.jsx(s1,{item:m,stage:e,shot:h,playhead:s,change:o,ground:r,engine:l??null}):t.jsxs(t.Fragment,{children:[t.jsx("p",{className:"shot-fx-hint",children:u.length?a("Bấm vào một hiệu ứng trên timeline (hàng ✦) hoặc chọn ở trên để sửa."):a("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:["✎ ",a("Sửa {0}",[u[0].name])]})]})]})}function s1({item:e,stage:n,shot:s,playhead:o,change:i,ground:r,engine:l}){const h=ct(),[u,m]=R.useState(null),d=e.fx,f=$o[d.preset],p=ud(d.cat??""),b=Fn(e,s),g=!!s.fxTiming?.[e.id],v=n.items.filter($=>$.id!==e.id&&$.kind!=="fx"&&!$.hidden),y=($,W={})=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id?{...Y,...W,fx:{...Y.fx,...$}}:Y)})),k=$=>i(W=>({...W,items:W.items.map(z=>z.id===e.id?{...z,...$}:z)})),C=$=>i(W=>({...W,shots:W.shots.map(z=>z.id===W.activeShot?{...z,fxTiming:{...z.fxTiming,[e.id]:Pr({...Fn(e,z),...$,off:!1},z.duration)}}:z)})),S=($,W)=>y({params:{...d.params,[$]:W}}),I=tr(er(d).fx??d),j=d.path??[],M=$=>y({path:$.length>=2?$:void 0}),T=j.length;R.useEffect(()=>{if(!(!l||T<2))return l.setFxPathEditor({itemId:e.id,selected:u,select:m,move:($,W)=>i(z=>({...z,items:z.items.map(Y=>Y.id===e.id&&Y.fx?.path?{...Y,fx:{...Y.fx,path:Y.fx.path.map((J,V)=>V===$?W.map(K=>+K.toFixed(2)):J)}}:Y)}))}),()=>l.setFxPathEditor(null)},[l,e.id,T,u]);const w=d.attach?v.find($=>$.id===d.attach.to):void 0,E=s.duration>0?Math.min(1,Math.max(0,o/s.duration)):0,N=md(e,s),A=Do(e,s,E),O=$=>{N?i(W=>Oo(W,e.id,E,$)):$.position?y({attach:{...d.attach,offset:$.position}}):$.yaw!==void 0&&k({rotation:[e.rotation[0],$.yaw,e.rotation[2]]})},H=$=>{const[W,z]=$.split("|"),Y=v.find(J=>J.id===W);return Y?Zl(Y,z).map(J=>+J.toFixed(2)):null},D=v.flatMap($=>Nh.filter(([W])=>$.kind==="person"||W==="chest"||W==="feet").map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)));return t.jsxs("div",{className:"shot-fx-inspector","aria-label":a("Chỉnh hiệu ứng"),children:[t.jsxs("h3",{children:[a("CHỈNH HIỆU ỨNG")," ",t.jsxs("small",{className:"shot-total",children:["· ",p?Mr(p,h):e.name]})]}),t.jsx("input",{"aria-label":a("Tên hiệu ứng"),value:e.name,onChange:$=>k({name:$.target.value})}),n.plate&&t.jsxs("label",{className:"shot-field",title:a("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:a("Lớp VFX")}),t.jsxs("select",{"aria-label":a("Lớp VFX"),value:pd(e),onChange:$=>k({vfxLayer:$.target.value}),children:[t.jsx("option",{value:"behind",children:a("Sau người")}),t.jsx("option",{value:"front",children:a("Trước người")})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian trong shot")}),g?t.jsxs(t.Fragment,{children:[t.jsx(Ks,{label:"Bắt đầu (s)",value:b.start,min:0,max:Math.max(.1,s.duration),step:.1,onChange:$=>C({start:$})}),t.jsx(Ks,{label:"Kéo dài (s)",value:b.duration,min:.2,max:xn.maxDuration,step:.1,onChange:$=>C({duration:$})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lặp lại")}),t.jsx("input",{type:"checkbox","aria-label":a("Lặp lại"),checked:b.loop,onChange:$=>C({loop:$.target.checked})})]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",onClick:()=>C({start:+(o*s.duration).toFixed(2)}),children:a("Bắt đầu tại playhead")}),t.jsx("button",{type:"button",onClick:()=>i($=>({...$,shots:$.shots.map(W=>W.id===$.activeShot?{...W,fxTiming:Object.fromEntries(Object.entries(W.fxTiming??{}).filter(([z])=>z!==e.id))}:W)})),children:a("Bỏ khỏi shot này")})]})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>C({start:+(o*s.duration).toFixed(2),duration:d.duration}),children:a("Phát trong shot này")})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu hiệu ứng"),value:e.color,onChange:$=>k({color:$.target.value})})]}),t.jsx(Ks,{label:"Cường độ",value:d.intensity,min:.1,max:3,step:.1,onChange:$=>y({intensity:$})}),t.jsx(Ks,{label:"Kích thước",value:e.scale[0],min:.1,max:6,step:.1,onChange:$=>k({scale:[$,$,$]})}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Sn,{"aria-label":a("Seed"),value:d.seed,min:0,max:2147483647,step:1,onCommit:$=>y({seed:Math.round($)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>y({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ne.reset,{}),a("Xáo trộn")]})]})]}),f.params.length>0&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thông số")}),f.params.map($=>$.type==="number"?t.jsx(Ks,{label:$.label??$.key,value:Number(d.params[$.key]??$.def),min:$.min,max:$.max,step:$.max-$.min>20?1:.05,onChange:W=>S($.key,W)},$.key):t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a($.label??$.key)}),t.jsx("select",{"aria-label":a($.label??$.key),value:String(d.params[$.key]??$.def),onChange:W=>S($.key,W.target.value),children:$.options.map(W=>t.jsx("option",{value:W,children:W},W))})]},$.key))]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Gắn vào")}),t.jsxs("select",{"aria-label":a("Đối tượng gắn hiệu ứng"),value:d.attach?.to??"",onChange:$=>{const W=$.target.value;y({attach:W?{to:W,...d.attach?.hand?{hand:d.attach.hand}:{},offset:d.attach?.offset}:void 0})},children:[t.jsx("option",{value:"",children:a("Tự do (theo vị trí của hiệu ứng)")}),v.map($=>t.jsx("option",{value:$.id,children:$.name},$.id))]}),d.attach&&t.jsxs(t.Fragment,{children:[w?.kind==="person"&&t.jsxs("select",{"aria-label":a("Bộ phận gắn"),value:d.attach.hand??d.attach.part??"",onChange:$=>{const W=$.target.value,{hand:z,part:Y,...J}=d.attach;y({attach:{...J,...W==="L"||W==="R"?{hand:W}:W==="chest"||W==="head"?{part:W}:{}}})},children:[t.jsx("option",{value:"",children:a("Cơ thể (chân)")}),t.jsx("option",{value:"chest",children:a("Ngực")}),t.jsx("option",{value:"head",children:a("Đầu")}),t.jsx("option",{value:"R",children:a("Tay phải")}),t.jsx("option",{value:"L",children:a("Tay trái")})]}),d.attach.hand&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Ở đầu vật đang cầm (nòng súng)")}),t.jsx("input",{type:"checkbox","aria-label":a("Ở đầu vật đang cầm (nòng súng)"),checked:d.attach.tip===!0,onChange:$=>y({attach:{...d.attach,tip:$.target.checked?!0:void 0}})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xoay theo đối tượng")}),t.jsx("input",{type:"checkbox","aria-label":a("Xoay theo đối tượng"),checked:d.attach.follow!=="position",onChange:$=>{const{follow:W,...z}=d.attach;y({attach:{...z,...$.target.checked?{}:{follow:"position"}}})}})]}),t.jsx("p",{className:"shot-fx-hint",children:N?a("Độ 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]):a("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(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Sn,{"aria-label":a("Lệch {0}",[$]),precision:2,step:.1,min:-100,max:100,value:+A.position[W].toFixed(3),onCommit:z=>{const Y=[...A.position];Y[W]=z,O({position:Y})}})]},$))}),t.jsx("button",{type:"button",onClick:()=>i($=>Oo($,e.id,E)),children:a("+◆ Key độ lệch tại playhead")})]}),!d.attach&&t.jsx("div",{className:"shot-fx-vec",children:["X","Y","Z"].map(($,W)=>t.jsxs("label",{children:[t.jsx("span",{children:$}),t.jsx(Sn,{"aria-label":a("Vị trí {0}",[$]),precision:2,step:.1,min:-1e3,max:1e3,value:e.position[W],onCommit:z=>{const Y=[...e.position];Y[W]=z,k({position:Y})}})]},$))}),t.jsx(Ks,{label:"Hướng (độ)",value:d.attach?+A.yaw.toFixed(1):e.rotation[1],min:-360,max:360,step:5,onChange:$=>d.attach?O({yaw:$}):k({rotation:[e.rotation[0],$,e.rotation[2]]})})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Nhắm vào")}),t.jsxs("select",{"aria-label":a("Mục tiêu bám theo"),value:d.target?`${d.target.to}|${d.target.part}`:"",onChange:$=>{const[W,z]=$.target.value.split("|");y({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:a("Không (theo đường bay / hướng)")}),v.flatMap($=>[...Nh.filter(([W])=>["chest","head","feet"].includes(W)).map(([W,z])=>t.jsxs("option",{value:`${$.id}|${W}`,children:[$.name," · ",a(z)]},`${$.id}|${W}`)),t.jsxs("option",{value:`${$.id}|center`,children:[$.name," · ",a("Cả khối (nhà, tường, cửa kính)")]},`${$.id}|center`)])]}),d.target&&t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Chỉ một phần (tên, vd: window)")}),t.jsx("input",{"aria-label":a("Tên phần của mục tiêu"),value:d.target.name??"",onChange:$=>y({target:{...d.target,name:$.target.value.trim()?$.target.value.slice(0,60):void 0}})})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đường bay")}),j.length<2&&t.jsx("button",{type:"button",onClick:()=>{const $=Zl(w??{kind:"box",position:e.position,scale:[1,1,1]},"chest"),W=r();M([$.map(z=>+z.toFixed(2)),[+($[0]+6).toFixed(2),$[1],+(W[2]||$[2]).toFixed(2)]])},children:a("Tạo đường bay")}),j.length>=2&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Từ")}),t.jsxs("select",{"aria-label":a("Điểm xuất phát"),value:"",onChange:$=>{const W=H($.target.value);W&&M([W,...j.slice(1)])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tới")}),t.jsxs("select",{"aria-label":a("Điểm đến"),value:"",onChange:$=>{const W=H($.target.value);W&&M([...j.slice(0,-1),W])},children:[t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),D]})]}),j.map(($,W)=>t.jsxs("div",{className:`shot-fx-point ${u===W?"active":""}`,children:[t.jsx("b",{role:"button",tabIndex:0,title:a("Chọn điểm để kéo trong khung 3D"),onClick:()=>m(W),onKeyDown:z=>{z.key==="Enter"&&m(W)},children:W===0?a("Đầu"):W===j.length-1?a("Cuối"):`${W+1}`}),[0,1,2].map(z=>t.jsx(Sn,{"aria-label":a("Điểm {0} {1}",[W+1,"XYZ"[z]]),precision:2,step:.1,min:-1e3,max:1e3,value:$[z],onCommit:Y=>{const J=j.map(V=>[...V]);J[W][z]=Y,M(J)}},z)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[W+1]),disabled:j.length<=2,onClick:()=>M(j.filter((z,Y)=>Y!==W)),children:t.jsx(Ne.close,{})})]},W)),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",disabled:j.length>=xn.maxPathPoints,onClick:()=>{const $=j.at(-2),W=j.at(-1);M([...j.slice(0,-1),[+(($[0]+W[0])/2).toFixed(2),+(($[1]+W[1])/2+.8).toFixed(2),+(($[2]+W[2])/2).toFixed(2)],W])},children:a("Thêm điểm giữa")}),t.jsx("button",{type:"button",onClick:()=>y({path:void 0}),children:a("Xóa đường bay")})]})]})]}),t.jsx("small",{className:"shot-fx-budget",children:a("{0} hạt · giới hạn {1}/hiệu ứng",[I,xn.maxParticlesPerItem])})]})}const en=e=>+e.toFixed(2),a1=[{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}],o1=[{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}],i1={collapse:"🏚",explosion:"💥",shatter:"🪟",burning:"🔥",collapse_building:"🏢"},r1={pancake:"Sập tại chỗ (từng tầng)",topple:"Đổ nghiêng",base:"Sập từ chân"},Nu=e=>od.has(String(e)),Ba=e=>!!e&&e.kind==="fx"&&e.fx?.preset===Ji,Au=e=>e.items.filter(n=>Zd.has(n.kind)&&!n.hidden&&!n.hold);function Tu(e,n){const s=e.shots.find(b=>b.id===e.activeShot)??e.shots[0],o=e.items.find(b=>b.id===n.target),i=n.bounds??{min:[o.position[0]-.5,0,o.position[2]-.5],max:[o.position[0]+.5,1,o.position[2]+.5]},r=[0,1,2].map(b=>i.max[b]-i.min[b]),l=en(Math.min(6,Math.max(.6,Math.max(...r)/5))),h=Nu(n.recipe),u=en(Math.min(Math.max(0,n.playhead),Math.max(0,s.duration-.2))),m=en(Math.max(.3,h?Math.min(4,s.duration-u):s.duration-u)),d=Op({target:o.id,recipe:n.recipe,seed:n.seed??Math.floor(Math.random()*1e9)+1,start:u,duration:m,params:{radius:l,...n.params}}),f=h?[en((i.min[0]+i.max[0])/2),en(i.max[1]+.6),en((i.min[2]+i.max[2])/2)]:[en(i.min[0]-l-Number(d.params.falloff)-.3),en((i.min[1]+i.max[1])/2),en((i.min[2]+i.max[2])/2)],p={...Mn("fx",e.items.length),name:n.name,color:Wa[n.recipe].color,position:f,fx:d};return{item:p,stage:{...e,items:[...e.items,p],shots:e.shots.map(b=>b.id===s.id?{...b,fxTiming:{...b.fxTiming,[p.id]:{start:u,duration:m}}}:b)}}}function wo(e,n,s,o,i=vt()){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 h=r.objectKeys?.[n]??[],u=_n(l,r,s),m=h.find(f=>Math.abs(f.time-s)<1e-6),d={...m,id:m?.id??i,time:s,position:o??[...u.position],rotation:[...u.rotation],scale:[...u.scale]};return{...e,shots:e.shots.map(f=>f.id===r.id?{...f,objectKeys:{...f.objectKeys,[n]:[...h.filter(p=>p.id!==d.id),d].sort((p,b)=>p.time-b.time)}}:f)}}function Mo({label:e,value:n,onChange:s,min:o,max:i,step:r=.1}){return t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function l1({stage:e,selected:n,progress:s,change:o,onSelect:i,engine:r,setError:l}){ct();const h=e.shots.find(k=>k.id===e.activeShot)??e.shots[0],u=s*h.duration,m=e.items.filter(Ba),d=Au(e),f=m.find(k=>k.id===n)??null,[p,b]=R.useState(()=>({target:"",recipe:"collapse"})),g=d.find(k=>k.id===n)??null,v=d.some(k=>k.id===p.target)?p.target:g?.id??d[0]?.id??"",y=()=>{if(!v)return;if(e.items.filter(S=>S.kind==="fx").length>=xn.maxItems){l?.(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[xn.maxItems]));return}const k=r?.objectBounds()[v]??null,C=Tu(e,{target:v,recipe:p.recipe,playhead:u,bounds:k,name:`${a("Mix FX")} ${m.length+1}`});o(()=>C.stage),i(C.item.id)};return t.jsxs("div",{className:"shot-fx shot-mixfx",children:[t.jsx("p",{className:"shot-fx-hint",children:a("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(k=>t.jsx("div",{className:k.id===f?.id?"active":"",children:t.jsxs("button",{type:"button",onClick:()=>i(k.id),children:["💥 ",k.name,t.jsxs("small",{className:"shot-list-meta",children:[" · ",e.items.find(C=>C.id===k.fx?.target?.to)?.name??a("chưa có mục tiêu")]})]})},k.id))}),!f&&t.jsxs("fieldset",{className:"shot-mixfx-new",children:[t.jsx("legend",{children:a("Tạo Mix FX")}),d.length?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsx("select",{"aria-label":a("Mục tiêu bị phá"),value:v,onChange:k=>b(C=>({...C,target:k.target.value})),children:d.map(k=>t.jsx("option",{value:k.id,children:k.name},k.id))})]}),t.jsx(Lu,{value:p.recipe,onPick:k=>b(C=>({...C,recipe:k}))}),t.jsx("button",{type:"button",className:"shot-primary",onClick:y,children:a("Tạo khối cầu phá huỷ")})]}):t.jsx("p",{className:"shot-fx-empty",children:a("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(c1,{item:f,stage:e,progress:s,change:o,onSelect:i,engine:r??null},f.id)]})}function Lu({value:e,onPick:n}){return t.jsx("div",{className:"shot-mixfx-recipes",role:"group","aria-label":a("Công thức hiệu ứng"),children:Pp.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:i1[s]}),a(Wa[s].name)]},s))})}function c1({item:e,stage:n,progress:s,change:o,onSelect:i,engine:r}){const l=n.shots.find(M=>M.id===n.activeShot)??n.shots[0],h=e.fx,u=h.params,m=Fn(e,l),d=!!l.fxTiming?.[e.id],f=l.objectKeys?.[e.id]??[],p=Au(n),b=n.items.find(M=>M.id===h.target?.to)??null,g=(M,T={})=>o(w=>({...w,items:w.items.map(E=>E.id===e.id?{...E,...T,fx:{...E.fx,...M}}:E)})),v=(M,T)=>g({params:{...u,[M]:T}}),y=M=>o(T=>({...T,shots:T.shots.map(w=>w.id===T.activeShot?{...w,fxTiming:{...w.fxTiming,[e.id]:Pr({...Fn(e,w),...M,off:!1},w.duration)}}:w)})),[k,C]=R.useState(null),S=Nu(u.recipe),I=()=>{if(!b||n.items.filter(A=>A.kind==="fx").length>=xn.maxItems)return;const M=(k?.first??m.start)+.6,T=r?.objectBounds()[b.id]??null,w=n.items.filter(Ba).length,E=Tu(n,{target:b.id,recipe:"collapse_building",playhead:Math.min(M,Math.max(0,l.duration-.3)),bounds:T,name:`${a("Sập toà nhà")} ${w+1}`,params:{chunks:Number(u.chunks)}}),N={...E.item,fx:{...E.item.fx,seed:h.seed}};o(()=>({...E.stage,items:E.stage.items.map(A=>A.id===N.id?N:A)})),i(N.id)};R.useEffect(()=>{const M=()=>C(r?.fx?.mixStats?.(s*l.duration).find(w=>w.id===e.id)??null);M();const T=window.setInterval(M,500);return()=>window.clearInterval(T)},[r,e.id,s,l.duration,n.revision]);const j=()=>{const M=b&&r?.objectBounds()[b.id];if(!M||l.duration<=0)return;const T=Number(u.radius)*e.scale[0]+Number(u.falloff)+.3,w=en((M.min[1]+M.max[1])/2),E=en((M.min[2]+M.max[2])/2),N=Math.min(1,m.start/l.duration),A=Math.min(1,(m.start+m.duration)/l.duration);o(O=>{const H={...O,shots:O.shots.map(D=>D.id===O.activeShot?{...D,objectKeys:{...D.objectKeys,[e.id]:[]}}:D)};return wo(wo(H,e.id,N,[en(M.min[0]-T),w,E]),e.id,A,[en(M.max[0]+T),w,E])})};return t.jsxs("div",{className:"shot-fx-inspector shot-mixfx-inspector","aria-label":a("Chỉnh Mix FX"),children:[t.jsxs("h3",{children:[a("MIX FX")," ",t.jsxs("small",{className:"shot-total",children:["· ",e.name]})]}),t.jsx("input",{"aria-label":a("Tên Mix FX"),value:e.name,onChange:M=>o(T=>({...T,items:T.items.map(w=>w.id===e.id?{...w,name:M.target.value}:w)}))}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Mục tiêu")}),t.jsxs("select",{"aria-label":a("Mục tiêu bị phá"),value:b?.id??"",onChange:M=>g({target:M.target.value?{to:M.target.value,part:"center"}:void 0}),children:[!b&&t.jsx("option",{value:"",children:a("Chọn đối tượng…")}),p.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id))]})]}),t.jsx(Lu,{value:String(u.recipe),onPick:M=>g({params:$p(M,u)},{color:Wa[M].color})}),k?.overridden&&t.jsx("p",{className:"shot-fx-hint shot-mixfx-note","data-mix":"note",children:a("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(M=>M.id===k.lead)?.name??""])}),S?t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Sập toà nhà")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Kiểu sập")}),t.jsx("select",{"aria-label":a("Kiểu sập"),"data-mix":"mode",value:String(u.mode??"pancake"),onChange:M=>v("mode",M.target.value),children:Dp.map(M=>t.jsx("option",{value:M,children:a(r1[M])},M))})]}),o1.filter(({key:M})=>M!=="yaw"||u.mode==="topple").map(({key:M,step:T})=>{const w=Jl.find(E=>E.key===M);return t.jsx(Mo,{label:w.label??M,value:Number(u[M]??w.def),min:w.min,max:w.max,step:T,onChange:E=>v(M,M==="chunks"?Math.round(E):E)},M)})]}):t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Khối cầu & độ ảnh hưởng")}),a1.map(({key:M,step:T})=>{const w=Jl.find(E=>E.key===M);return t.jsx(Mo,{label:w.label??M,value:Number(u[M]??w.def),min:w.min,max:w.max,step:T,onChange:E=>v(M,M==="chunks"?Math.round(E):E)},M)}),t.jsxs("label",{className:"shot-field shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Mất đỡ thì rơi"),"data-mix":"support",checked:u.support!=="off",onChange:M=>v("support",M.target.checked?"on":"off")}),t.jsx("span",{children:a("Mất đỡ thì rơi")})]}),t.jsxs("button",{type:"button","data-mix":"collapse-after",disabled:!b,onClick:I,children:["🏢 ",a("Thêm sập sau nổ")]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Seed & màu")}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Seed")}),t.jsxs("span",{className:"shot-fx-seed",children:[t.jsx(Sn,{"aria-label":a("Seed"),value:h.seed,min:0,max:2147483647,step:1,onCommit:M=>g({seed:Math.round(M)})}),t.jsxs("button",{type:"button","aria-label":a("Đổi seed ngẫu nhiên"),title:a("Đổi seed ngẫu nhiên"),onClick:()=>g({seed:Math.floor(Math.random()*1e9)+1}),children:[t.jsx(Ne.reset,{}),a("Xáo trộn")]})]})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Màu bụi / lửa")}),t.jsx("input",{type:"color","aria-label":a("Màu bụi / lửa"),value:e.color,onChange:M=>o(T=>({...T,items:T.items.map(w=>w.id===e.id?{...w,color:M.target.value}:w)}))})]})]}),t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Thời gian phá trong shot")}),d?t.jsxs(t.Fragment,{children:[t.jsx(Mo,{label:"Bắt đầu (s)",value:m.start,min:0,max:Math.max(.1,l.duration),step:.1,onChange:M=>y({start:M})}),t.jsx(Mo,{label:"Kéo dài (s)",value:m.duration,min:.2,max:xn.maxDuration,step:.1,onChange:M=>y({duration:M})})]}):t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>y({start:en(s*l.duration),duration:en(Math.max(.2,l.duration*(1-s)))}),children:a("Phát trong shot này")})]}),!S&&t.jsxs("fieldset",{children:[t.jsx("legend",{children:a("Đườ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:()=>o(M=>wo(M,e.id,s)),children:["+◆ ",a("Thêm điểm tại playhead")]}),t.jsx("button",{type:"button","data-mix":"sweep",disabled:!b,onClick:j,children:a("Quét ngang qua mục tiêu")})]}),f.map((M,T)=>t.jsxs("div",{className:"shot-fx-point shot-mixfx-key","data-key":M.id,children:[t.jsxs("b",{children:[(M.time*l.duration).toFixed(1),"s"]}),[0,1,2].map(w=>t.jsx(Sn,{"aria-label":a("Điểm {0} {1}",[T+1,"XYZ"[w]]),precision:2,step:.1,min:-1e3,max:1e3,value:M.position[w],onCommit:E=>{const N=[...M.position];N[w]=E,o(A=>wo(A,e.id,M.time,N,M.id))}},w)),t.jsx("button",{type:"button","aria-label":a("Xóa điểm {0}",[T+1]),onClick:()=>o(w=>({...w,shots:w.shots.map(E=>E.id===w.activeShot?{...E,objectKeys:{...E.objectKeys,[e.id]:(E.objectKeys?.[e.id]??[]).filter(N=>N.id!==M.id)}}:E)})),children:t.jsx(Ne.close,{})})]},M.id)),!f.length&&t.jsx("p",{className:"shot-fx-hint",children:a("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”.")})]}),k&&t.jsxs("small",{className:"shot-fx-budget","data-mix-stats":`${k.broken}/${k.chunks}`,children:[a("{0} mảnh · {1} mảnh đã vỡ tại playhead · {2} sẽ vỡ",[k.chunks,k.broken,k.hit]),k.falling?a(" · {0} mảnh mất đỡ rơi xuống",[k.falling]):""]}),t.jsxs("div",{className:"shot-fx-row",children:[t.jsx("button",{type:"button",className:"shot-delete-item",onClick:()=>{o(M=>({...M,items:M.items.filter(T=>T.id!==e.id),shots:M.shots.map(T=>({...T,...T.objectKeys?.[e.id]?{objectKeys:Object.fromEntries(Object.entries(T.objectKeys).filter(([w])=>w!==e.id))}:{},...T.fxTiming?.[e.id]?{fxTiming:Object.fromEntries(Object.entries(T.fxTiming).filter(([w])=>w!==e.id))}:{}}))})),i(null)},children:a("Xóa {0}",[e.name])}),t.jsx("button",{type:"button",onClick:()=>i(null),children:a("+ Mix FX khác")})]})]})}let Dn=null,Ws,Io,Sr,Ah=null;const Th=new Map,qi=new Map;let Lh=Promise.resolve(),Eh=0;const Ih=112;function h1(){const e=document.createElement("canvas");e.width=e.height=64;const n=e.getContext("2d");for(let o=0;o<8;o++)for(let i=0;i<8;i++)n.fillStyle=(i+o)%2?"#3a4148":"#262b30",n.fillRect(i*8,o*8,8,8);const s=new Kr(e);return s.colorSpace=Jo,s.wrapS=s.wrapT=Md,s.repeat.set(3,3),s.magFilter=sg,s}function d1(){if(Dn)return Dn;Dn=new _r({antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),Dn.outputColorSpace=Jo,Dn.toneMapping=jd,Dn.toneMappingExposure=1.1,Dn.setClearColor(0,0),Dn.setSize(Ih,Ih,!1),Ws=new zr;const e=new kd(Dn);Ah=e.fromScene(new Ld,.04).texture,e.dispose(),Ws.environment=Ah;const n=new Zo("#fff4e4",2.2);n.position.set(-2,3,3),Ws.add(n);const s=new ut(new ei(4,4),new fs({map:h1()}));return s.position.set(0,0,-1.4),Ws.add(s),Sr=new ut(new Hn(.5,48,32)),Ws.add(Sr),Io=new Br(30,1,.1,20),Io.position.set(0,.18,2.15),Io.lookAt(0,0,0),Dn}function u1(e){const n=d1(),s=_p({preset:e},Va,{studio:!0});if(!s)throw new Error(`unknown material ${e}`);Sr.material=s,n.render(Ws,Io);const o=n.domElement.toDataURL("image/png");return s.dispose(),o}function m1(e){const n=Th.get(e);if(n)return Promise.resolve(n);const s=qi.get(e);if(s)return s;if(!Ha(e))return Promise.reject(new Error(`unknown material ${e}`));const o=globalThis.__CLIPOOX_THUMB_LIMIT;if(typeof o=="number"&&Eh>=o)return Promise.reject(new Error("thumbnail limit"));Eh++;const i=Lh.then(()=>new Promise((r,l)=>setTimeout(()=>{try{const h=u1(e);Th.set(e,h),r(h)}catch(h){l(h)}},20))).finally(()=>qi.delete(e));return Lh=i.catch(()=>{}),qi.set(e,i),i}const Ro="application/x-clipoox-material",Ia=e=>!!e&&e.kind!=="fx"&&e.kind!=="splat",Ca=e=>e===Qs?a("Cả đối tượng"):/^part-\d+/.test(e)?a("Phần {0}",[e.slice(5)]):e;function p1({preset:e,alt:n}){const[s,o]=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 h=new IntersectionObserver(u=>{u.some(m=>m.isIntersecting)&&(r(!0),h.disconnect())},{rootMargin:"120px"});return h.observe(l.current),()=>h.disconnect()},[i]),R.useEffect(()=>{if(!i)return;let h=!0;return m1(e.id).then(u=>{h&&o(u)}).catch(()=>{}),()=>{h=!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 cs({label:e,value:n,range:s,step:o,onInput:i,format:r}){return t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a(e)}),t.jsx("input",{type:"range","aria-label":a(e),min:s[0],max:s[1],step:o,value:n,onChange:l=>i(Number(l.target.value))}),t.jsx("output",{children:r?r(n):n.toFixed(2)})]})}function f1({stage:e,selected:n,change:s,engine:o,setError:i,scope:r,setScope:l}){const h=ct(),[u,m]=R.useState(""),[d,f]=R.useState(""),[p,b]=R.useState(!1),[g,v]=R.useState([]),y=e.items.find(q=>q.id===n)??null,k=Ia(y),C=R.useMemo(()=>zp(u,u.trim()?"":d),[u,d]);R.useEffect(()=>{if(!y||!k){v([]);return}const q=()=>v(o?.materialSlots(y.id)??[]);q();const ue=setTimeout(q,400),pe=setTimeout(q,1600);return()=>{clearTimeout(ue),clearTimeout(pe)}},[o,y?.id,y?.model?.gcsUri,y?.look,y?.figure,e.revision,k]),R.useEffect(()=>()=>o?.setPartPicker(null),[o]),R.useEffect(()=>{b(!1),o?.setPartPicker(null)},[n,o]);const S=g.length>1,I=r.mode==="part"&&S&&r.slot&&g.some(q=>q.slot===r.slot)?r.slot:Qs,j=y?.materials?.[I]??null,M=ec(j),[T,w]=R.useState([]),E=e.items.filter(q=>q.id!==y?.id&&Ia(q)&&!q.hidden),N=T.filter(q=>E.some(ue=>ue.id===q&&!ue.locked)),A=(q,ue=y?.id,pe=I,U=!0)=>{const le=e.items.find(Le=>Le.id===ue);if(!le||!Ia(le)){i(a("Chọn một đối tượng (hộp, model, nhân vật…) để áp vật liệu."));return}if(le.locked){i(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[le.name]));return}i("");const ce=U?N.filter(Le=>Le!==le.id):[];s(Le=>ce.reduce((je,ie)=>Gs(je,ie,Qs,q),Gs(Le,le.id,pe,q)))},O=(q,ue=y?.id,pe=I)=>A({preset:q.id},ue,pe),H=()=>A({mode:"tint",params:{color:"#ffffff"}}),[D,$]=R.useState(null),W=R.useRef(null),z=R.useRef(void 0),Y=()=>{clearTimeout(z.current);const q=W.current;W.current=null,q&&($(null),s(ue=>Gs(ue,q.itemId,q.slot,q.override)))};R.useEffect(()=>()=>Y(),[]);const J=`${y?.id}|${I}|${JSON.stringify(j)}`,V=D?.key===J?D.params:null,K=q=>{if(!y||!j)return;const ue={...j.params||{},...V||{},...q},pe=da(j)?{mode:"tint",params:{color:ue.color??"#ffffff",...ue.roughness!==void 0?{roughness:ue.roughness}:{},...ue.metalness!==void 0?{metalness:ue.metalness}:{}}}:{preset:j.preset,params:ue};$({key:J,params:ue}),o?.previewMaterials(y.id,Bp(y.materials,I,pe)),W.current={itemId:y.id,slot:I,override:pe},clearTimeout(z.current),z.current=setTimeout(Y,450)},G=j&&!da(j)?V?ec({preset:j.preset,params:V}):M:null,_=j&&da(j)?{...j.params,...V||{}}:null,ee=q=>{y&&(W.current=null,clearTimeout(z.current),s(ue=>Gs(ue,y.id,q,null)))},Q=()=>{y&&(W.current=null,clearTimeout(z.current),s(q=>({...q,items:q.items.map(ue=>{if(ue.id!==y.id)return ue;const{materials:pe,...U}=ue;return U})})))},ve=()=>{if(!(!o||!y)){if(p){o.setPartPicker(null),b(!1);return}b(!0),o.setPartPicker((q,ue)=>{b(!1);const pe=e.items.find(U=>U.id===q);if(q!==y.id){pe&&Ia(pe)&&!pe.locked&&i(a("Phần đó thuộc {0} — chọn đối tượng ấy trước.",[pe.name]));return}i(""),l({mode:"part",slot:ue})})}},xe=Object.entries(y?.materials||{});return t.jsxs("div",{className:"shot-mat",children:[t.jsx("div",{className:"shot-mat-target",children:y?t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:y.name}),!k&&t.jsx("small",{children:a("Đối tượng này không đổi được vật liệu.")}),y.locked&&t.jsx("small",{children:a("Đang khoá")})]}):t.jsx("small",{children:a("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.")})}),y&&k&&S&&t.jsxs("div",{className:"shot-mat-scope",children:[t.jsxs("div",{className:"shot-seg",role:"radiogroup","aria-label":a("Á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:a("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(q=>q.slot===r.slot)?r.slot:g[0].slot}),children:a("Từng phần")})]}),r.mode==="part"&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"shot-mat-parts",role:"listbox","aria-label":a("Các phần của model"),children:g.map(({slot:q})=>{const ue=y.materials?.[q],pe=ue?Ha(ue.preset):null;return t.jsxs("button",{type:"button",role:"option","data-slot":q,"aria-selected":I===q,className:I===q?"active":"",onClick:()=>l({mode:"part",slot:q}),children:[Ca(q),pe?t.jsxs("small",{children:[" · ",Ta(pe,h)]}):da(ue)?t.jsxs("small",{children:[" · ",a("Giữ texture")]}):null]},q)})}),t.jsxs("button",{type:"button",className:`shot-mat-pick${p?" active":""}`,"aria-pressed":p,onClick:ve,children:[t.jsx(Ne.focus,{})," ",p?a("Bấm vào một phần của model… (bấm lại để huỷ)"):a("Chọn phần trên khung 3D")]})]})]}),y&&k&&!y.locked&&t.jsx("div",{className:"shot-mat-tintbar",children:t.jsxs("button",{type:"button","data-mat":"tint",className:_?"active":"","aria-pressed":!!_,onClick:()=>_?ee(I):H(),title:a("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:["🎨 ",a("Giữ texture gốc, chỉ đổi màu")]})}),y&&k&&_&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),"data-mat":"tint-panel",children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:a("Giữ texture gốc, chỉ đổi màu")}),t.jsxs("small",{children:[" · ",Ca(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ne.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu nhân")}),t.jsx("input",{type:"color","aria-label":a("Màu nhân"),value:_.color,onChange:q=>K({color:q.target.value})}),t.jsx("output",{children:_.color})]}),t.jsx(cs,{label:"Độ nhám",value:_.roughness??.5,range:Ns.roughness,step:.01,onInput:q=>K({roughness:q}),format:q=>_.roughness===void 0?a("gốc"):q.toFixed(2)}),t.jsx(cs,{label:"Độ kim loại",value:_.metalness??0,range:Ns.metalness,step:.01,onInput:q=>K({metalness:q}),format:q=>_.metalness===void 0?a("gốc"):q.toFixed(2)})]}),y&&k&&E.length>0&&t.jsxs("details",{className:"shot-mat-also",open:N.length>0,children:[t.jsx("summary",{children:a("Áp cho cả: {0} đối tượng khác",[N.length])}),t.jsx("div",{className:"shot-mat-also-list",role:"group","aria-label":a("Áp cho nhiều đối tượng"),children:E.map(q=>t.jsxs("label",{className:q.locked?"is-locked":"",children:[t.jsx("input",{type:"checkbox","data-also":q.id,disabled:q.locked,checked:N.includes(q.id),onChange:ue=>w(pe=>ue.target.checked?[...pe.filter(U=>U!==q.id),q.id]:pe.filter(U=>U!==q.id))}),q.name]},q.id))}),t.jsx("small",{className:"shot-fx-hint",children:a("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).",[y.name])})]}),y&&k&&j&&G&&t.jsxs("section",{className:"shot-mat-tweak","aria-label":a("Chỉnh vật liệu"),children:[t.jsxs("div",{className:"shot-mat-tweak-head",children:[t.jsx("strong",{children:Ta(G.preset,h)}),t.jsxs("small",{children:[" · ",Ca(I)]}),t.jsxs("button",{type:"button",className:"shot-mat-reset",onClick:()=>ee(I),title:a("Đặt lại vật liệu gốc"),children:[t.jsx(Ne.reset,{})," ",a("Đặt lại vật liệu gốc")]})]}),t.jsxs("label",{className:"shot-mat-slider",children:[t.jsx("span",{children:a("Màu")}),t.jsx("input",{type:"color","aria-label":a("Màu vật liệu"),value:G.color,onChange:q=>K({color:q.target.value})}),t.jsx("output",{children:G.color})]}),t.jsx(cs,{label:"Độ nhám",value:G.roughness,range:Ns.roughness,step:.01,onInput:q=>K({roughness:q})}),t.jsx(cs,{label:"Độ kim loại",value:G.metalness,range:Ns.metalness,step:.01,onInput:q=>K({metalness:q})}),!G.preset.mapless&&t.jsxs(t.Fragment,{children:[t.jsx(cs,{label:"Cỡ vân",value:G.scale,range:[.1,5],step:.05,onInput:q=>K({scale:q}),format:q=>`×${q.toFixed(2)}`}),t.jsx(cs,{label:"Xoay vân",value:G.rotation,range:Ns.rotation,step:1,onInput:q=>K({rotation:q}),format:q=>`${Math.round(q)}°`})]}),t.jsx(cs,{label:"Phát sáng",value:G.emissive,range:Ns.emissive,step:.1,onInput:q=>K({emissive:q}),format:q=>q.toFixed(1)}),t.jsx(cs,{label:G.preset.transmission?"Độ đục (kính)":"Độ đặc",value:G.opacity,range:Ns.opacity,step:.01,onInput:q=>K({opacity:q})})]}),t.jsx("div",{className:"shot-fx-search",children:t.jsx("input",{type:"search","aria-label":a("Tìm vật liệu"),placeholder:a("Tìm vật liệu… (vd: go, kinh, thep)"),value:u,onChange:q=>m(q.target.value)})}),t.jsxs("div",{className:"shot-fx-cats shot-mat-cats",role:"tablist","aria-label":a("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:a("Tất cả")}),sd.map(q=>t.jsx("button",{type:"button",role:"tab","aria-selected":d===q.id&&!u.trim(),className:d===q.id&&!u.trim()?"active":"",onClick:()=>{f(q.id),m("")},children:h==="en"?q.en:q.vi},q.id))]}),t.jsxs("div",{className:"shot-mat-grid",children:[C.map(q=>{const ue=Ta(q,h),pe=j?.preset===q.id;return t.jsxs("button",{type:"button",className:`shot-mat-card${pe?" active":""}`,"data-material":q.id,draggable:!0,"aria-pressed":pe,title:y&&k?a("Áp {0} cho {1}",[ue,y.name]):ue,onDragStart:U=>{U.dataTransfer.setData(Ro,q.id),U.dataTransfer.effectAllowed="copy"},onClick:()=>O(q),children:[t.jsx(p1,{preset:q,alt:ue}),t.jsx("span",{children:ue})]},q.id)}),!C.length&&t.jsx("p",{className:"shot-fx-empty",children:a("Không có vật liệu nào khớp.")})]}),t.jsx("p",{className:"shot-fx-hint",children:a("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 đó.")}),y&&xe.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("h3",{children:[a("Vật liệu đang dùng")," ",t.jsxs("small",{className:"shot-total",children:["· ",xe.length]})]}),t.jsx("div",{className:"shot-list shot-mat-list",children:xe.map(([q,ue])=>{const pe=Ha(ue.preset);return t.jsxs("div",{className:q===I?"active":"",children:[t.jsxs("button",{type:"button",onClick:()=>l(q===Qs?{mode:"all",slot:r.slot}:{mode:"part",slot:q}),children:[Ca(q),t.jsxs("small",{className:"shot-list-meta",children:[" · ",pe?Ta(pe,h):da(ue)?a("Giữ texture · {0}",[ue.params.color]):ue.preset]})]}),t.jsx("button",{type:"button",className:"shot-delete-item","aria-label":a("Đặt lại {0}",[Ca(q)]),title:a("Đặt lại vật liệu gốc"),onClick:()=>ee(q),children:t.jsx(Ne.reset,{})})]},q)})}),t.jsxs("button",{type:"button",className:"shot-mat-reset-all",onClick:Q,children:[t.jsx(Ne.reset,{})," ",a("Đặt lại tất cả vật liệu gốc")]})]})]})}function Jr({pose:e}){ct();const n=(h,u,m,d,f,p,b,g=0)=>{const v=(m+b*g*.34)*Math.PI/180,y=(m-d+b*g*.22)*Math.PI/180,k=[h+Math.sin(v)*f,u+Math.cos(v)*f];return{joint:k,end:[k[0]+Math.sin(y)*p,k[1]+Math.cos(y)*p]}},s=n(35,38,e.shoulderL,e.elbowL,21,19,-1,e.shoulderOutL),o=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=(h,u,m,d)=>t.jsxs("g",{children:[t.jsx("path",{d:`M${h} 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],o.joint,o.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 g1=["person","prop","box","sphere","cylinder","model"],x1=[["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 b1({item:e,shot:n,playhead:s,patchItem:o,change:i}){ct();const r=Kp(e.toon),l=!!r?.on,h=r??{...Hp,on:!1},u=p=>o(e.id,{toon:{...h,...p}}),m=e.kind==="prop"&&e.prop?.kind==="ball",d=e.ball?.restitution??Wp.restitution,f=()=>i(p=>({...p,shots:p.shots.map(b=>b.id===n.id?{...b,ball:{...b.ball,[e.id]:[...(b.ball?.[e.id]||[]).filter(g=>g.t<s*b.duration-1e-6),{t:Math.round(s*b.duration*1e3)/1e3,kind:"launch",from:[...e.position],vel:[0,0,0]}]}}:b)}));return t.jsxs("div",{className:"shot-toon","data-testid":"shot-toon",children:[t.jsx("h3",{children:a("HOẠT HÌNH / CARTOON")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Phong cách hoạt hình"),checked:l,onChange:p=>u({on:p.target.checked})}),t.jsx("span",{children:a("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:a("Mức cường điệu")}),t.jsxs("span",{children:[Math.round(h.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Mức cường điệu"),type:"range",min:0,max:1,step:.05,value:h.amount,disabled:!l,onChange:p=>u({amount:+p.target.value})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a("Hình nhảy cách (on twos)"),checked:h.twos,disabled:!l,onChange:p=>u({twos:p.target.checked})}),t.jsx("span",{children:a("Hình nhảy cách (on twos)")})]}),t.jsxs("details",{className:"shot-toon-more",children:[t.jsx("summary",{children:a("Chi tiết nguyên lý")}),t.jsx("div",{className:"shot-toon-flags",children:x1.map(([p,b])=>t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox","aria-label":a(b),checked:h[p],disabled:!l,onChange:g=>u({[p]:g.target.checked})}),t.jsx("span",{children:a(b)})]},p))})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[t.jsx("span",{className:"shot-toon-name",children:a("Độ nảy")}),t.jsxs("span",{children:[Math.round(d*100),"%"]}),t.jsx("input",{"aria-label":a("Độ nảy"),type:"range",min:.3,max:.95,step:.01,value:d,onChange:p=>o(e.id,{ball:{...e.ball,restitution:+p.target.value}})})]}),t.jsx("button",{type:"button",onClick:f,children:a("Thả bóng nảy từ đây")})]}),t.jsx("small",{className:"shot-hint",children:a("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 y1=[{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"}],hs=e=>(Number(e)||0).toFixed(1),Rh=()=>crypto.randomUUID(),v1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null;function j1({shot:e,item:n,playhead:s,change:o,engine:i,seek:r}){const l=ct(),h=l==="en",u=e.motionEdits?.[n.id]||[],m=v1(e.clipSpans?.[n.id],s),[d,f]=R.useState("moment"),[p,b]=R.useState(Es.default),[g,v]=R.useState(!1),[y,k]=R.useState("handR"),[C,S]=R.useState(null),I=u.find(A=>A.id===C)??null,j=(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},M=A=>o(O=>({...O,shots:O.shots.map(H=>H.id===e.id?{...H,motionEdits:{...H.motionEdits,[n.id]:fd(H.motionEdits?.[n.id],A,H.duration)}}:H)})),T=A=>{o(O=>({...O,shots:O.shots.map(H=>H.id===e.id?{...H,motionEdits:{...H.motionEdits,[n.id]:(H.motionEdits?.[n.id]||[]).filter(D=>D.id!==A)}}:H)})),C===A&&S(null)},w=(A,O)=>{if(I){M({...I,...A});return}const H=Rh();S(H),M({id:H,...j(),label:O,...A})},E=R.useRef({reach:j,write:M,setSelId:S,setPart:k});E.current={reach:j,write:M,setSelId:S,setPart:k},R.useEffect(()=>{if(i){if(!g){i.editTool&&!i.editTool.direct&&i.setEditTool(null);return}i.setEditTool({personId:n.id,part:y,draft:(A,O)=>({id:"__drag",...E.current.reach(O==="hips"&&d==="moment"?"after":d),...A}),commit:(A,O)=>{const H=Rh(),D=E.current;D.setSelId(H),D.write({id:H,...D.reach(O==="hips"&&d==="moment"?"after":d),label:a(_o[O]),...A})},select:A=>E.current.setPart(A)})}},[i,g,n.id,y,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:[a("SỬA CHUYỂN ĐỘNG"),t.jsx("small",{children:a("{0} chỉnh",[u.length])})]}),t.jsxs("p",{className:"shot-hint",children:[m?a("Đang ở khối “{0}” {1}–{2}s",[m.label,hs(m.start),hs(m.end)]):a("Playhead {0}s",[hs(s)])," · ",a("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":a("Phạm vi chỉnh"),children:y1.map(A=>t.jsx("button",{role:"radio","aria-checked":d===A.id,className:d===A.id?"active":"",disabled:A.id==="span"&&!m,title:a(A.hint),onClick:()=>f(A.id),children:a(A.label)},A.id))}),t.jsxs("label",{className:"shot-joint",children:[a("Độ mềm (hoà vào/ra)")," ",t.jsxs("span",{children:[p.toFixed(2),"s"]}),t.jsx("input",{"aria-label":a("Độ mềm (hoà vào/ra)"),type:"range",min:Es.min,max:1.2,step:.05,value:p,onChange:A=>b(+A.target.value)})]}),t.jsx("h4",{children:a("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)}),a("Hiện tay cầm để kéo tay, chân, hông")]}),g&&t.jsx("div",{className:"shot-edit-parts",children:Gp.map(A=>t.jsx("button",{"data-edit-part":A,className:y===A?"active":"",onClick:()=>k(A),children:a(_o[A])},A))}),g&&t.jsx("small",{className:"shot-hint",children:y==="hips"?a("Kéo ngang để dời vị trí, kéo xuống để hạ trọng tâm (chân vẫn bám đất)."):a("Kéo chấm sáng: khớp vai, khuỷu, hông, gối tự xoay theo (IK).")}),t.jsx("h4",{children:a("Dáng đứng mẫu")}),t.jsx("div",{className:"shot-stance-grid",children:qp.map(A=>t.jsx("button",{"data-stance":A.id,className:I?.preset?.id===A.id?"active":"",onClick:()=>w({preset:{id:A.id,amount:I?.preset?.amount??.7}},h?A.nameEn:A.name),children:h?A.nameEn:a(A.name)},A.id))}),I?.preset&&t.jsxs("label",{className:"shot-joint",children:[a("Độ mạnh dáng mẫu")," ",t.jsxs("span",{children:[Math.round(I.preset.amount*100),"%"]}),t.jsx("input",{"aria-label":a("Độ mạnh dáng mẫu"),type:"range",min:0,max:1,step:.05,value:I.preset.amount,onChange:A=>w({preset:{...I.preset,amount:+A.target.value}},"")})]}),t.jsx("h4",{children:a("Chỉnh nhanh")}),Up.map(A=>t.jsxs("label",{className:"shot-joint",children:[h?A.nameEn:a(A.name)," ",t.jsx("span",{children:A.max===1?`${Math.round(N(A.id)*100)}%`:`${N(A.id)}°`}),t.jsx("input",{"aria-label":h?A.nameEn:a(A.name),"data-stance-slider":A.id,type:"range",min:A.min,max:A.max,step:A.step,value:N(A.id),onChange:O=>w({stance:{...I?.stance||{},[A.id]:+O.target.value}},h?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:[a(A)," ",t.jsx("span",{children:(I?.move?.[O]??0).toFixed(2)}),t.jsx("input",{"aria-label":a(A),type:"range",min:-2,max:2,step:.02,value:I?.move?.[O]??0,onChange:H=>{const D=[...I?.move??[0,0,0]];D[O]=+H.target.value,w({move:D},a("Vị trí"))}})]},A)),t.jsxs("label",{className:"shot-joint",children:[a("Xoay hướng")," ",t.jsxs("span",{children:[I?.turn??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay hướng"),type:"range",min:-180,max:180,step:1,value:I?.turn??0,onChange:A=>w({turn:+A.target.value},a("Hướng"))})]})]}),t.jsx("h4",{children:a("Các chỉnh đã có")}),!u.length&&t.jsx("small",{className:"shot-hint",children:a("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=Xp(A),H=O?0:Vp(A,s);return t.jsxs("li",{className:`${A.id===C?"active":""} ${A.off?"off":""} ${O?"broken":""}`,children:[t.jsxs("button",{className:"shot-edit-pick",onClick:()=>{S(A.id===C?null:A.id),r(Number(A.start)||0)},title:O?a("Chỉnh này bị lỗi dữ liệu nên đã được bỏ qua — xoá nó và chỉnh lại"):a("Chọn chỉnh này và tua tới"),children:[t.jsxs("b",{children:[O?"⚠ ":"",A.label||a("Chỉnh")]}),t.jsx("small",{children:A.scope==="span"?`${hs(A.start)}–${hs(A.end)}s`:A.scope==="after"?a("từ {0}s",[hs(A.start)]):`${hs(A.start)}s ±${(Number(A.fade)||0).toFixed(1)}`}),t.jsx("i",{className:"shot-edit-weight",style:{width:`${Math.round(H*100)}%`},"aria-hidden":!0})]}),t.jsx("button",{title:A.off?a("Bật"):a("Tắt (xem bản gốc)"),"aria-pressed":!A.off,onClick:()=>M({...A,off:!A.off}),children:A.off?"○":"●"}),t.jsx("button",{title:a("Xoá chỉnh"),onClick:()=>T(A.id),children:"✕"})]},A.id)})}),I&&t.jsx("button",{className:"shot-edit-new",onClick:()=>S(null),children:a("+ Chỉnh mới tại {0}s",[hs(s)])})]})}const Fh=[{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)"}],k1=[{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)"}],w1=(e,n)=>(e||[]).find(s=>n>=s.start-.001&&n<=s.end+.001)??null,M1=(e,n)=>!!(e.objectKeys?.[n]?.length||e.clipSpans?.[n]?.length);function S1({engine:e,stage:n,shot:s,item:o,playhead:i,change:r,onDone:l}){ct();const h=w1(s.clipSpans?.[o.id],i),[u,m]=R.useState(()=>M1(s,o.id)?"moment":"after"),[d,f]=R.useState("free"),[p,b]=R.useState(()=>Math.max(0,+(i-1).toFixed(2))),[g,v]=R.useState(()=>Math.min(s.duration,+(i+1).toFixed(2))),y={start:Math.max(0,Math.min(p,g)),end:Math.min(s.duration,Math.max(p,g))},[k,C]=R.useState(!1),[S,I]=R.useState(0),[j,M]=R.useState([]),[T,w]=R.useState(null),[E,N]=R.useState(null),[A,O]=R.useState(!0),[H,D]=R.useState(!0),$=F=>F==="key"?{scope:"moment",start:i,end:i,fade:Es.default}:F==="range"&&y.end-y.start>.05?{scope:"span",start:y.start,end:y.end,fade:Es.default}:F==="range"?{scope:"moment",start:i,end:i,fade:Es.default}:F==="span"&&h?{scope:"span",start:h.start,end:h.end,fade:Es.default}:{scope:F==="span"?"moment":F,start:i,end:i,fade:Es.default},W=F=>r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:fd(Z.motionEdits?.[o.id],F,Z.duration)}}:Z)})),z=i/Math.max(1e-6,s.duration),Y=(F,te)=>{const Z=s.objectKeys?.[o.id];r(re=>({...re,shots:re.shots.map(me=>me.id===s.id?Jp(me,re.items.find(Pe=>Pe.id===o.id)??o,z,F??{},te):me)})),M(re=>[...re,{kind:"key",prev:Z}])},J=(F,te,Z=u)=>{if(Z==="key"&&!F.stance&&!F.track&&!F.turn&&!F.preset){Y(F.pose,F.move);return}const re=crypto.randomUUID();W({id:re,...$(Z),label:te,...F}),M(me=>[...me,{kind:"edit",id:re}])},V=()=>{const F=j.at(-1);F&&(F.kind==="key"?r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,objectKeys:{...Z.objectKeys,[o.id]:F.prev??[]}}:Z)})):r(te=>({...te,shots:te.shots.map(Z=>Z.id===s.id?{...Z,motionEdits:{...Z.motionEdits,[o.id]:(Z.motionEdits?.[o.id]||[]).filter(re=>re.id!==F.id)}}:Z)})),M(te=>te.slice(0,-1)))},K=Yp(s,o.id,z),[G,_]=R.useState(.5),ee=()=>{const F=s.objectKeys?.[o.id],te=tc(s,n.items.find(Z=>Z.id===o.id)??o,z,G);te&&(r(Z=>({...Z,shots:Z.shots.map(re=>re.id===s.id?te:re)})),M(Z=>[...Z,{kind:"key",prev:F}]))},Q=!!tc(s,o,z,.5),[ve,xe]=R.useState(!1),[q,ue]=R.useState(!1),[pe,U]=R.useState("");R.useEffect(()=>{let F=!0;return fn(()=>import("./api-Dnl2uaKO.js").then(te=>te.bV),__vite__mapDeps([5,1,4,3])).then(te=>te.shotInbetweenInfo()).then(te=>{F&&xe(te.available)}),()=>{F=!1}},[]);const le=async()=>{if(!q){ue(!0),U("");try{const F=await fn(()=>import("./aiInbetween-6eKDYbYS.js"),__vite__mapDeps([18,1,6,2,3,4,5,7,8,9,10,11,12,13,14,15,16])),te=s.objectKeys?.[o.id],Z=await F.aiInbetween(n,o.id,{at:z},await F.editorInbetweenDeps());r(()=>Z.stage),M(re=>[...re,{kind:"key",prev:te}])}catch(F){U(F.message||a("Không tạo được chuyển động nối"))}finally{ue(!1)}}},[ce,Le]=R.useState(0),je=F=>{if(!e||!T||!T.startsWith("foot")||!F)return;const te=e.rollFootAt(i,o.id,T,F,Z=>({id:"__drag",...$(u),...Z}));te&&J(te.fields,`${a("Cuộn bàn chân")} ${F>0?"+":""}${F}°`),Le(0)},ie=F=>F==="hips"&&u==="moment"?"after":u,Me=R.useRef({reach:$,add:J,scopeOf:ie,setSel:w,writeKey:Y});Me.current={reach:$,add:J,scopeOf:ie,setSel:w,writeKey:Y},R.useEffect(()=>{if(e)return e.setEditTool({personId:o.id,part:null,parts:Qp,direct:!0,mode:d,lockFeet:H,draft:(F,te)=>({id:"__drag",...Me.current.reach(Me.current.scopeOf(te)),...F}),commit:(F,te)=>{const Z=ki(te);Me.current.add(F,Z?na()!=="en"?Z.vi:Z.en:a(_o[te]),Me.current.scopeOf(te))},select:F=>Me.current.setSel(F),hover:F=>N(F)}),()=>{e.editTool?.direct&&e.setEditTool(null)}},[e,o.id,d,H]);const Ee=R.useRef(T);Ee.current=T,R.useEffect(()=>{Ee.current&&e?.selectPosePart(Ee.current)},[e,d]);const Se=F=>{w(F),e?.selectPosePart(F)},he=()=>Me.current.writeKey(),be=R.useRef({pick:Se,sel:T,insertKey:he,breakdown:ee});be.current={pick:Se,sel:T,insertKey:he,breakdown:ee},R.useEffect(()=>{const F=te=>{const Z=te.target;if(te.metaKey||te.ctrlKey||te.altKey||Z&&(Z.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(Z.tagName)))return;const re=te.key.toLowerCase(),me=re==="g"?"move":re==="r"?"rotate":re==="f"?"free":null;if(me){te.preventDefault(),te.stopImmediatePropagation(),f(me);return}if((re==="i"||re==="k")&&!te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),be.current.insertKey();return}if(re==="e"&&te.shiftKey){te.preventDefault(),te.stopImmediatePropagation(),be.current.breakdown();return}te.key==="Tab"&&(te.preventDefault(),te.stopImmediatePropagation(),be.current.pick(ef(ki(be.current.sel??"")?.id??null,te.shiftKey?-1:1).part))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[]);const Fe=na()!=="en",Te=ki(E??T??"");R.useEffect(()=>{if(e)return e.setFocusLock(o.id),()=>e.setFocusLock(null)},[e,o.id]);const _e=()=>gs(n.items.find(F=>F.id===o.id)??o,s,i/Math.max(1e-6,s.duration),n.items).pose,ze=(F,te)=>{const Z=tf(_e(),F,te);Z&&Object.keys(Z).length&&J({pose:Z},`${a(_o[`hand${F}`])}: ${a(wi[te].name)}`)},Be=T==="handL"||T==="handR"?T.slice(-1):null,Ze=F=>{const te=_e(),Z=Kn[F],re={};for(const[me,Pe]of Object.entries(Z))if(typeof Pe=="number"&&Number.isFinite(Pe)){const ye=Pe-(typeof te[me]=="number"?te[me]:0);Math.abs(ye)>.01&&(re[me]=Math.round(ye*100)/100)}Object.keys(re).length&&J({pose:re},a(F))};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"shot-pose-banner shot-pose-bar",role:"toolbar","aria-label":a("Chỉnh dáng"),children:[t.jsx("span",{className:"shot-pose-who",title:a("Kéo các tay cầm để chỉnh dáng {0}",[o.name]),children:o.name}),t.jsx("span",{className:"shot-pose-control","aria-live":"polite",style:Te?{color:`#${nc[Te.side].toString(16).padStart(6,"0")}`}:void 0,children:Te?`${Fe?Te.vi:Te.en} · ${Te.id}`:a("Chọn một tay cầm")}),t.jsx("button",{className:A?"active":"","aria-expanded":A,"aria-label":a("Bảng điều khiển"),title:a("Bảng điều khiển: bấm tên để chọn tay cầm (Tab: tay cầm kế tiếp)"),onClick:()=>O(F=>!F),children:"🧍"}),t.jsx("select",{"aria-label":a("Phạm vi chỉnh"),title:a(Fh.find(F=>F.id===u)?.hint??""),value:u,onChange:F=>m(F.target.value),children:Fh.map(F=>t.jsx("option",{value:F.id,disabled:F.id==="span"&&!h,children:a(F.label)},F.id))}),u==="range"&&t.jsxs("span",{className:"shot-pose-range",role:"group","aria-label":a("Vùng key"),children:[t.jsx("input",{type:"number","aria-label":a("Vùng key từ (giây)"),title:a("Đặt đầu vùng ở playhead"),min:0,max:s.duration,step:.1,value:p,onChange:F=>b(+F.target.value),onDoubleClick:()=>b(+i.toFixed(2))}),t.jsx("span",{"aria-hidden":!0,children:"–"}),t.jsx("input",{type:"number","aria-label":a("Vùng key đến (giây)"),title:a("Đặt cuối vùng ở playhead"),min:0,max:s.duration,step:.1,value:g,onChange:F=>v(+F.target.value),onDoubleClick:()=>v(+i.toFixed(2))}),"s"]}),t.jsx("div",{className:"shot-seg shot-pose-modes",role:"radiogroup","aria-label":a("Cách chỉnh"),children:k1.map(F=>t.jsx("button",{role:"radio","aria-checked":d===F.id,"aria-label":a(F.label),className:d===F.id?"active":"",title:`${a(F.label)} · ${a(F.hint)}`,onClick:()=>f(F.id),children:F.icon},F.id))}),Be&&t.jsxs("select",{"aria-label":a("Kiểu bàn tay"),value:"",onChange:F=>{F.target.value&&ze(Be,F.target.value)},children:[t.jsx("option",{value:"",children:a("Bàn tay…")}),Object.keys(wi).map(F=>t.jsx("option",{value:F,children:a(wi[F].name)},F))]}),t.jsx("button",{className:H?"active":"","aria-pressed":H,"aria-label":a("Khoá chân"),title:a("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:()=>D(F=>!F),children:"🔒"}),t.jsx("button",{className:K?"active shot-pose-key":"shot-pose-key","aria-label":a("Đặt key"),title:a("Đặt key tư thế tại playhead (I)"),onClick:()=>Y(),children:"◆"}),t.jsx("button",{disabled:!Q,className:"shot-pose-breakdown","aria-label":a("Breakdown"),title:a("Breakdown: key chuyển tiếp giữa key trước và sau ({0}% về key sau) — Shift+E",[Math.round(G*100)]),onClick:ee,onWheel:F=>_(te=>Math.max(0,Math.min(1,+(te+(F.deltaY<0?.1:-.1)).toFixed(1)))),children:"◇"}),ve&&t.jsx("button",{disabled:!Q||q,className:q?"shot-pose-ai busy":"shot-pose-ai","aria-busy":q,"aria-label":a("AI nối tư thế"),title:pe?`${a("Không tạo được chuyển động nối")}: ${pe}`:a("AI nối tư thế: tạo chuyển động tự nhiên (bước chân, dồn trọng tâm, vung tay) giữa key trước và key sau playhead"),onClick:()=>void le(),children:q?"…":"AI ◆→◆"}),T?.startsWith("foot")&&t.jsxs("label",{className:"shot-pose-roll",title:a("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:a("Cuộn")}),t.jsx("input",{type:"range","aria-label":a("Cuộn bàn chân"),min:-40,max:60,step:5,value:ce,onChange:F=>Le(+F.target.value),onPointerUp:()=>je(ce),onKeyUp:F=>{F.key==="Enter"&&je(ce)}}),t.jsxs("b",{children:[ce>0?"+":"",ce,"°"]})]}),t.jsx("button",{className:k?"active":"","aria-expanded":k,"aria-label":a("Thư viện dáng"),title:a("Thư viện dáng"),onClick:()=>C(F=>!F),children:a("Dáng")}),t.jsx("button",{disabled:!j.length,"aria-label":a("Hoàn tác"),title:a("Bỏ lần chỉnh vừa rồi"),onClick:V,children:"↶"}),t.jsx("button",{className:"shot-primary",title:a("Xong (Esc)"),onClick:l,children:a("Xong")})]}),A&&t.jsx("div",{className:"shot-pose-picker",role:"group","aria-label":a("Bảng điều khiển"),children:Zp.map(F=>{const te=`#${nc[F.side].toString(16).padStart(6,"0")}`,Z=T===F.part;return t.jsx("button",{"data-control":F.id,"aria-pressed":Z,className:`shot-pose-pick ${F.shape}${Z?" active":""}`,style:{gridColumn:F.picker[0]+1,gridRow:F.picker[1]+1,borderColor:te,...Z?{background:te}:{}},title:`${Fe?F.vi:F.en} (${F.id})`,onMouseEnter:()=>N(F.part),onMouseLeave:()=>N(null),onClick:()=>Se(F.part),children:Fe?F.vi:F.en},F.id)})}),k&&t.jsxs("div",{className:"shot-pose-library",children:[t.jsx("div",{className:"shot-pose-tabs",role:"tablist",children:zo.map((F,te)=>t.jsx("button",{role:"tab","aria-selected":S===te,className:S===te?"active":"",onClick:()=>I(te),children:a(F.name)},F.name))}),t.jsx("div",{className:"shot-rig-grid",children:zo[S]?.presets.map(F=>t.jsxs("button",{title:a("Áp dáng {0} tại {1}s",[a(F),i.toFixed(1)]),onClick:()=>Ze(F),children:[t.jsx(Jr,{pose:Kn[F]}),t.jsx("span",{children:a(F)})]},F))})]})]})}const Ra=e=>na()==="en"?e.labelEn:e.label,Ph=e=>na()==="en"?of(e):rf(e),$h={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"},Dh=["Di chuyển","Giao tiếp","Tư thế","Võ","Phản ứng trúng đòn","Thể thao","Nhảy múa","Đời thường"],Ui=[...Dh.filter(e=>sc.includes(e)),...sc.filter(e=>!Dh.includes(e))];function Eu(e,n){if(!$r(e))return Cr(e);const s=e.keys(0),o=e.duration?n%e.duration:0;if(o<=s[0].t)return s[0].pose;for(let i=0;i<s.length-1;i++)if(o<=s[i+1].t)return cf(s[i].pose,s[i+1].pose,(o-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 Cr=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},C1=()=>typeof window<"u"&&Number.isFinite(window.__CLIPOOX_THUMB_LIMIT)?Math.max(0,window.__CLIPOOX_THUMB_LIMIT):48,Vo=new Set;let Nr=0;const N1=performance.now();function Iu(e){if(e-Oh>=80){Oh=e;for(const n of Vo)n((e-N1)/1e3)}Nr=Vo.size?requestAnimationFrame(Iu):0}let Oh=0;function Ru(e){return Vo.add(e),Nr||(Nr=requestAnimationFrame(Iu)),()=>{Vo.delete(e)}}function A1({clip:e,animate:n}){const[s,o]=R.useState(()=>Cr(e));return R.useEffect(()=>{if(!n){o(Cr(e));return}let i=!0;e.mocap&&!$r(e)&&Dr(e.id).catch(()=>{});const r=Ru(l=>{i&&o(Eu(e,l))});return()=>{i=!1,r()}},[n,e]),t.jsx(Jr,{pose:s})}function T1({person:e,clip:n}){const s=R.useRef(null),[o,i]=R.useState(!1);return R.useEffect(()=>{const r=s.current;if(!r||!n)return;let l;try{l=new _r({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=Jo,l.toneMapping=ag;const h=new zr,u=new Br(28,(r.clientWidth||220)/(r.clientHeight||280),.1,50);h.add(new wd("#e8eeff","#5e5a52",1.4));const m=new Zo("#fff4e4",2.4);m.position.set(-2.5,3.5,3.5),h.add(m);const d=new ut(new og(.9,40),new fs({color:"#1d242b"}));d.rotation.x=-Math.PI/2,h.add(d),u.position.set(1.9,1.35,4.6),u.lookAt(0,.9,0);let f=null,p=!0,b=null;const g=e?.color??"#8f9aa3",v=e?.kind==="person"?e.figure:void 0,y=e?.kind==="person"?e.look:void 0,k=S=>{if(!p)return;const I=Eu(n,S);if(I!==b){b=I,f&&(h.remove(f),f.traverse(M=>{M instanceof ut&&(M.geometry.dispose(),(Array.isArray(M.material)?M.material:[M.material]).forEach(T=>T.dispose()))})),f=lf(I,g,v,y);const j=new zt().setFromObject(f).getSize(new oe).y||1.8;f.scale.multiplyScalar(1.8/Math.max(1.2,j>2.4?j:1.8)),h.add(f)}l.render(h,u)};n.mocap&&!$r(n)&&(i(!0),Dr(n.id).then(()=>{p&&i(!1)}).catch(()=>p&&i(!1))),k(0);const C=Ru(k);return()=>{p=!1,C(),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":a("Xem trước chuyển động trên nhân vật")}):t.jsx("div",{className:"mocap-preview-empty",children:a("Chọn một chuyển động để xem trước trên nhân vật")}),o&&t.jsx("small",{className:"shot-hint",children:a("Đang tải dữ liệu mocap…")})]})}const Xi=e=>e.meta?.pair;function L1({person:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,onClose:l,playhead:h}){ct();const[u,m]=R.useState(""),[d,f]=R.useState(null),[p,b]=R.useState(null),[g,v]=R.useState(null),[y,k]=R.useState(()=>new Set),C=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=nf(u),A=H=>(!d||H.group===d)&&Bo(H.meta);if(!N)return us.filter(A).sort((H,D)=>Ui.indexOf(H.group)-Ui.indexOf(D.group));const O=new Map(sf(u,{limit:120}).map(H=>[H.id,H.score]));return us.filter(H=>O.has(H.id)&&A(H)).sort((H,D)=>(O.get(D.id)??0)-(O.get(H.id)??0))},[u,d]);R.useEffect(()=>{const N=C.current;if(!N||typeof IntersectionObserver>"u")return;const A=new IntersectionObserver(O=>k(H=>{const D=new Set(H);for(const $ of O){const W=$.target.dataset.clip;$.isIntersecting?D.add(W):D.delete(W)}return D}),{root:N,rootMargin:"80px"});return N.querySelectorAll("[data-clip]").forEach(O=>A.observe(O)),()=>A.disconnect()},[I]);const j=R.useMemo(()=>{const N=C1();return new Set(I.filter(A=>y.has(A.id)).slice(0,N).map(A=>A.id))},[I,y]),M=us.find(N=>N.id===p)??null,T=us.find(N=>N.id===(g??p))??null,w=N=>[N.anchor&&N.anchor.kind!=="floor"?a($h[N.anchor.kind]):"",...N.props.length?[a("Đạo cụ: {0}",[N.props.map(A=>a(La[A.prop].label)).join(", ")])]:[]].filter(Boolean).join(" · "),E=M?.meta?.src?af[M.meta.src.license]:null;return t.jsx("div",{className:"shot-char-overlay mocap-overlay",role:"dialog","aria-modal":"true","aria-label":a("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:[a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:us.filter(N=>Bo(N.meta)).length})]}),t.jsx("span",{className:"shot-char-for",children:e?a("Áp dụng cho: {0}",[e.name]):""}),t.jsx("button",{className:"shot-char-close","aria-label":a("Đó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:a("Tìm chuyển động (đấm móc, ngã, nhảy salsa, cat hanh…)"),"aria-label":a("Tìm chuyển động"),onChange:N=>m(N.target.value)}),t.jsxs("div",{className:"shot-motion-chips mocap-chips",role:"group","aria-label":a("Nhóm chuyển động"),children:[t.jsx("button",{type:"button",className:d?"":"active","aria-pressed":!d,onClick:()=>f(null),children:a("Tất cả")}),Ui.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:Ph(N)},N))]})]}),I.length===0&&t.jsx("small",{className:"shot-hint mocap-empty",children:a('Không có chuyển động khớp "{0}"',[u])}),t.jsx("div",{className:"shot-motion-grid mocap-grid",ref:C,role:"listbox","aria-label":a("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:`${Ra(N)} · ${N.duration.toFixed(1)}s${w(N)?` · ${w(N)}`:""}`,onClick:()=>b(N.id),onDoubleClick:()=>r(N),onPointerEnter:()=>v(N.id),onPointerLeave:()=>v(A=>A===N.id?null:A),children:[t.jsx(A1,{clip:N,animate:j.has(N.id)||g===N.id}),t.jsx("span",{className:"mocap-card-name",children:Ra(N)}),t.jsxs("span",{className:"mocap-card-meta",children:[N.duration.toFixed(1),"s",N.loop?` · ${a("↻ lặp")}`:"",N.mocap?" · mocap":"",Xi(N)?` · ${a("cặp đôi")}`:""]}),N.anchor&&N.anchor.kind!=="floor"||N.props.length?t.jsx("em",{children:[N.anchor&&N.anchor.kind!=="floor"?a($h[N.anchor.kind]):"",N.props.length?"+"+N.props.length:""].filter(Boolean).join(" ")}):null]},N.id))})]}),t.jsxs("aside",{className:"mocap-side",children:[t.jsx(T1,{person:e,clip:T}),M?t.jsxs("div",{className:"mocap-detail",children:[t.jsx("b",{children:Ra(M)}),t.jsxs("small",{children:[Ph(M.group)," · ",M.duration.toFixed(1),"s",M.loop?` · ${a("↻ lặp")}`:""]}),w(M)&&t.jsx("small",{children:w(M)}),Xi(M)&&t.jsx("small",{className:"mocap-pair",children:a("Clip cặp đôi với “{0}”. Áp ở đây chỉ chạy một người; nhờ Agent để đặt cả hai (play_motion partner).",[Ra(us.find(N=>N.id===Xi(M).with)??M)])}),E&&M.meta?.src&&M.meta.src.db!=="Clipoox"&&t.jsx("small",{className:"mocap-source",children:a("Nguồn: {0} (cảnh {1}) · {2}",[E.name,M.meta.src.trial,a("miễn phí, được dùng thương mại")])})]}):t.jsx("small",{className:"shot-hint",children:a("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=>o(N.target.checked)}),a("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)}),a("Đổi tay / chân")]}),t.jsx("button",{type:"button",className:"shot-primary mocap-apply",disabled:!M,onClick:()=>M&&r(M),children:h!=null?a("Áp từ playhead ({0}s)",[h.toFixed(1)]):a("Áp từ playhead")}),t.jsx("small",{className:"shot-hint",children:a("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 E1(e){ct();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:a("Mở thư viện chuyển động: {0} chuyển động, có mocap thật",[us.filter(o=>Bo(o.meta)).length]),children:[t.jsx(Ne.person,{})," ",a("Thư viện Mocap")," ",t.jsx("span",{className:"shot-motion-count",children:us.filter(o=>Bo(o.meta)).length})]}),n&&gd.createPortal(t.jsx(L1,{...e,onClose:()=>s(!1),onApply:o=>{s(!1),e.onApply(o)}}),document.querySelector(".shot-workspace")||document.body)]})}function Fu({disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onPlay:r,person:l,playhead:h}){return ct(),t.jsx("div",{className:"shot-motion-lib",children:t.jsx(E1,{disabled:e,loop:n,mirror:s,onLoop:o,onMirror:i,onApply:r,person:l,playhead:h})})}const I1=24;function Ar(e,n="joint"){const s=new Set((e?.joints||[]).map(o=>o.name));for(let o=1;;o++){const i=`${n}${o}`.slice(0,I1);if(!s.has(i))return i}}function _h(e,n,s,o){const i=o||Ar(e);if(!e)return Yo({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 Pu(e,r)}function R1(e,n){const s=e.joints.find(r=>r.name===n);if(!s)return e;const o=e.joints.filter(r=>r.name!==n).map(r=>r.parent===n?{...r,parent:s.parent}:r);if(!o.length)return null;const i=e.bones?Object.fromEntries(Object.entries(e.bones).filter(([r])=>r!==n)):void 0;return Pu({...e,...i?{bones:i}:{}},o)}function F1(e,n,s){return Yo({...e,joints:e.joints.map(o=>o.name===n?{...o,pos:s}:o)})}function Pu(e,n){const s=Yo({...e,joints:n});return s.kind!==e.kind?{...s,source:"manual"}:s}class P1{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&&Cc(n),this.engine.orbit.enabled=!0}set(n,s,o){this.itemId=n,this.mode=n?s:"off",this.picked=o}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||(Cc(n),this.mode==="off"))return;const o=this.engine.transform;if(this.mode==="place"&&o.detach(),!s)return;Gg(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"&&o.detach();return}if(this.mode==="edit"){const r=s.bones[i].children.find(l=>l.userData.rigJoint===this.picked);r&&(o.attach(r),o.setMode("translate"),o.setSpace("world"))}else this.mode==="pose"&&(o.attach(s.bones[i]),o.setMode("rotate"),o.setSpace("local"))}commit(n){const s=this.state(),o=this.root(),i=this.itemId;if(!s||!o||!i)return!1;if(n.userData.rigJoint&&this.mode==="edit"){const r=o.worldToLocal(n.getWorldPosition(new oe)).toArray().map(l=>Math.round(l*1e4)/1e4);return this.ev.setRig(i,F1(s.rig,n.userData.rigJoint,r)),!0}return n.userData.rigBone&&this.mode==="pose"&&this.ev.boneKey(i,n.userData.rigBone,qg(s,n.userData.rigBone,this.ev.pose(i))),!0}ray(n){const s=this.engine.renderer.domElement.getBoundingClientRect(),o=new bc;return o.layers.enable(1),o.setFromCamera(new ra((n.clientX-s.left)/s.width*2-1,-(n.clientY-s.top)/s.height*2+1),this.engine.camera),o}jointHit(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];return s.traverse(i=>{i.userData.rigJoint&&o.push(i)}),n.intersectObjects(o,!1)[0]?.object.userData.rigJoint??null}interiorPoint(n){const s=this.root();if(!s)return null;s.updateMatrixWorld(!0);const o=[];s.traverse(f=>{f instanceof ut&&!f.userData.rigOverlay&&o.push(f)});const i=n.intersectObjects(o,!1);if(!i.length)return null;const r=i[0],l=n.ray.direction.clone(),h=new zt().setFromObject(r.object).getSize(new oe).length()+.1,u=new bc(r.point.clone().addScaledVector(l,h),l.clone().negate(),0,h-1e-4);u.layers.mask=n.layers.mask;const m=u.intersectObjects(o,!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 o=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&&o&&i){const d=this.interiorPoint(this.ray(n));if(d){const f=Ar(i.rig);this.picked=f,this.ev.setRig(o,_h(i.rig,d,s.link,f))}}else r||(this.picked=s.link,this.ev.changed());return}if(r||this.engine.transform.axis||!o)return;const l=this.ray(n),h=this.jointHit(l);if(h){this.picked=h,this.ev.changed();return}if(this.mode!=="place")return;const u=this.interiorPoint(l);if(!u)return;const m=Ar(i?.rig);this.ev.setRig(o,_h(i?.rig,u,this.picked,m)),this.picked=m}}const zh=[["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"]],Bh=[["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 $1(e){ct();const{stage:n,shot:s,selected:o,engine:i,playhead:r}=e,l=n.items.find(_=>_.id===o&&_.kind==="model"&&_.model),h=l?.rig,[u,m]=R.useState("edit"),[d,f]=R.useState(4),[p,b]=R.useState(null),[g,v]=R.useState(!1),[y,k]=R.useState(""),[C,S]=R.useState(()=>{try{return localStorage.getItem("clipoox.rig.fingers")==="1"}catch{return!1}}),I=_=>{S(_);try{localStorage.setItem("clipoox.rig.fingers",_?"1":"0")}catch{}},[,j]=R.useReducer(_=>_+1,0),M=R.useRef(null),T=R.useRef(e);T.current=e;const w=(_,ee)=>T.current.change(Q=>({...Q,items:Q.items.map(ve=>ve.id!==_?ve:ee?{...ve,rig:ee,skeleton:void 0}:(({rig:xe,...q})=>q)(ve)),...ee?{}:{shots:Q.shots.map(ve=>({...ve,objectKeys:Object.fromEntries(Object.entries(ve.objectKeys||{}).map(([xe,q])=>[xe,xe===_?q.map(ue=>(({bones:pe,...U})=>U)(ue)):q]))}))}})),E=(_,ee,Q)=>T.current.change(ve=>{const xe=ve.shots.find(je=>je.id===ve.activeShot),q=ve.items.find(je=>je.id===_),ue=xe.objectKeys?.[_]||[],pe=T.current.playhead,U=xd(ue,pe,q.rig?.bones),le=(je,ie)=>{const Me=ue.find(Se=>Math.abs(Se.time-je)<1e-6),Ee=_n(q,xe,je);return{...Me,id:Me?.id||vt(),time:je,position:Ee.position,rotation:Ee.rotation,scale:Ee.scale,bones:ie}};let ce=[...ue];if(!ue.some(je=>je.bones)&&pe>1e-6){const je=le(0,{...q.rig?.bones||{}});ce=[...ce.filter(ie=>ie.id!==je.id),je]}const Le=le(pe,{...U,[ee]:Q});return ce=[...ce.filter(je=>je.id!==Le.id),Le].sort((je,ie)=>je.time-ie.time),{...ve,shots:ve.shots.map(je=>je.id===ve.activeShot?{...je,objectKeys:{...je.objectKeys,[_]:ce}}:je)}}),N=_=>T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===_&&Q.rig?{...Q,rig:(({bones:ve,...xe})=>xe)(Q.rig)}:Q),shots:ee.shots.map(Q=>Q.id!==ee.activeShot?Q:{...Q,objectKeys:{...Q.objectKeys,[_]:(Q.objectKeys?.[_]||[]).map(ve=>(({bones:xe,...q})=>q)(ve))}})}));R.useEffect(()=>{if(!i)return;const _=new P1(i,{setRig:(ee,Q)=>{w(ee,Q),j()},boneKey:(ee,Q,ve)=>{E(ee,Q,ve),j()},pose:ee=>{const Q=T.current.stage,ve=Q.shots.find(q=>q.id===Q.activeShot),xe=Q.items.find(q=>q.id===ee);return xe?gs(xe,ve,T.current.playhead).pose:null},changed:()=>{j(),T.current.resync()}});return M.current=_,()=>{_.dispose(),M.current=null,T.current.resync()}},[i]),R.useEffect(()=>{const _=M.current;if(!_)return;const ee=_.itemId===l?.id&&_.mode===u&&h?.joints.some(Q=>Q.name===_.picked)?_.picked:null;_.set(l?.id??null,l?u:"off",ee),e.resync()},[i,l?.id,u,!!h]),R.useEffect(()=>Ug(()=>j()),[]),R.useEffect(()=>{let _=!0;return rg().then(ee=>{_&&b(ee)}).catch(()=>{}),()=>{_=!1}},[]),e.keys.current={del:()=>{const _=M.current;if(!_||!l?.rig||!_.picked||u!=="edit"&&u!=="place")return!1;const ee=_.picked;return _.picked=null,w(l.id,R1(l.rig,ee)),j(),!0},esc:()=>{const _=M.current;return _?.picked?(_.picked=null,j(),e.resync(),!0):!1}};const A=()=>{const _=M.current?.root();return _?Qg(_):null},O=_=>{const ee=A();if(!l||!ee||ee.isEmpty()){e.setError(a("Model chưa tải xong."));return}k(""),M.current&&(M.current.picked=null);const Q=M.current?.root(),ve=_==="humanoid"&&Q?Yg(Q):null;let xe=df(_,{min:ee.min.toArray(),max:ee.max.toArray()},{segments:d,...ve?{tips:ve}:{}});_==="humanoid"&&C&&Q&&(xe=Si(xe,{positions:Pi(Q).positions})),w(l.id,xe),m("edit"),j()},H=()=>{const _=A();!l?.rig||!_||(w(l.id,uf(l.rig,(_.min.x+_.max.x)/2)),j())},D=async()=>{const _=M.current?.root();if(!l||!_){e.setError(a("Model chưa tải xong."));return}v(!0),k("");try{const ee=tx(_),Q=await lg({requestId:vt(),front:ee.front,side:ee.side,name:l.name});if(!Q.humanoid||!Q.landmarks||!Q.landmarks.humanoid){k(a("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 ve=mf(Q.landmarks,ee.frame);C&&(ve=Si(ve,{positions:Pi(_).positions,tips:pf(Q.landmarks,ee.frame)})),M.current&&(M.current.picked=null),w(l.id,ve),m("edit"),j(),dt.getState().toast(a("Đã gắn xương tự động · {0} credits",[Q.credits]),"ok"),Q.landmarks.facing==="away"&&k(a("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){k(ee.message||a("Gắn xương AI gặp lỗi."))}finally{v(!1)}},$=()=>{const _=M.current?.root();!l?.rig||!_||(M.current&&(M.current.picked=null),w(l.id,Mi(l.rig)?ff(l.rig):Si(l.rig,{positions:Pi(_).positions})),j())},W=_=>{const ee=nr.find(ve=>ve.id===_);if(!l||!ee)return;let Q=l.pose||{};for(const ve of["L","R"])Q=bd(Q,ve,ee);e.patchItem(l.id,{pose:Q})},z=M.current?.state(),Y=M.current?.picked??null,J=hf(h),V=n.items.filter(_=>_.kind==="model"&&_.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:a("Chọn một model GLB để gắn xương.")}),V.length?t.jsx("div",{className:"shot-rig-models",children:V.map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}):t.jsx("small",{className:"shot-hint",children:a("Thêm model ở tab Dựng cảnh (Nhập GLB / Thư viện 3D), rồi quay lại đây.")})]})});const K=(s.objectKeys?.[l.id]||[]).filter(_=>_.bones),G=l.model?Xg(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":a("Model khác"),children:V.filter(_=>_.id!==l.id).map(_=>t.jsxs("button",{type:"button",onClick:()=>e.onSelect(_.id),children:[_.name,_.rig||_.skeleton==="native"?` · ${a("đã có xương")}`:""]},_.id))}),t.jsxs("div",{className:"shot-rig-target",children:[t.jsx("b",{children:l.name}),t.jsx("small",{children:h?a("{0} khớp · {1}",[h.joints.length,J?a("xương người"):a(zh.find(_=>_[0]===h.kind)?.[1]??"Gắn tay")]):a("Chưa có xương")})]}),(()=>{const _=i?.nativeSkeleton(l.id);return!_?.ok&&l.skeleton!=="native"?null:t.jsxs("div",{className:"shot-rig-native",children:[t.jsx("h3",{children:a("XƯƠNG TRONG FILE")}),l.skeleton==="native"?t.jsxs(t.Fragment,{children:[t.jsx("small",{className:"shot-hint",children:a("Đang dùng xương gốc của file ({0} xương) — chuyển động như trong Blender.",[_?.bones??"…"])}),t.jsx("button",{type:"button",onClick:()=>{T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,skeleton:void 0}:Q)})),j()},children:a("Bỏ xương gốc")})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>{M.current&&(M.current.picked=null),T.current.change(ee=>({...ee,items:ee.items.map(Q=>Q.id===l.id?{...Q,rig:void 0,skeleton:"native"}:Q)})),j()},children:a("Dùng xương có sẵn trong file")}),t.jsx("small",{className:"shot-hint",children:a("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í.",[_?.bones??0])})]})]})})(),t.jsx("h3",{children:a("TỰ ĐỘNG")}),t.jsx("button",{type:"button",className:"shot-primary shot-rig-auto",disabled:g||e.busy||p?.configured===!1,onClick:()=>void D(),title:a("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?a("Đang gắn xương…"):a("✦ Tự gắn xương · ≈{0} credits",[p?p.estimate.toFixed(2):"…"])}),t.jsx("small",{className:"shot-hint shot-rig-price",children:p?a("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)]):a("Cho nhân vật hình người (2 tay, 2 chân).")}),y&&t.jsx("div",{className:"shot-rig-note",role:"status",children:y}),t.jsx("h3",{children:a("MẪU CÓ SẴN · MIỄN PHÍ")}),t.jsx("div",{className:"shot-rig-templates",children:zh.map(([_,ee,Q])=>t.jsx("button",{type:"button","data-template":_,title:a(Q),onClick:()=>O(_),children:a(ee)},_))}),t.jsxs("label",{className:"shot-rig-check",children:[t.jsx("input",{type:"checkbox",checked:C,onChange:_=>I(_.target.checked)})," ",a("Thêm xương ngón tay (mẫu Người / AI)")]}),t.jsxs("label",{className:"shot-field shot-rig-segments",children:[a("Số đốt (đuôi / chuỗi)"),t.jsx("input",{"aria-label":a("Số đốt (đuôi / chuỗi)"),type:"number",min:ao.chainMin,max:ao.chainMax,value:d,onChange:_=>f(Math.max(ao.chainMin,Math.min(ao.chainMax,Math.round(+_.target.value)||4)))})]}),t.jsx("h3",{children:a("GẮN TAY")}),t.jsx("div",{className:"shot-rig-modes",role:"group","aria-label":a("Công cụ xương"),children:Bh.map(([_,ee,Q])=>t.jsx("button",{type:"button",className:u===_?"active":"","aria-pressed":u===_,title:a(Q),onClick:()=>m(_),children:a(ee)},_))}),t.jsx("small",{className:"shot-hint",children:a(Bh.find(_=>_[0]===u)[2])}),Y&&t.jsx("div",{className:"shot-rig-picked",children:a("Khớp: {0}",[Y])}),t.jsxs("div",{className:"shot-rig-actions",children:[t.jsx("button",{type:"button",disabled:!h,onClick:H,title:a("Chép nửa trái (−X) sang phải qua tâm model, tự đặt tên .L / .R"),children:a("⇆ Đối xứng L/R")}),t.jsx("button",{type:"button",disabled:!h||!Y||u==="pose",onClick:()=>e.keys.current?.del(),children:a("Xoá khớp")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{l.model&&Vg(l.model.gcsUri),e.resync(),j()},children:a("Tính lại trọng số")}),t.jsx("button",{type:"button",disabled:!h,onClick:()=>{M.current&&(M.current.picked=null),w(l.id,null),j()},children:a("Bỏ xương")})]}),G?t.jsxs("div",{className:"shot-rig-progress",role:"status",children:[t.jsx("span",{children:G.done?a("Đã tính xong trọng số chạy nền · {0} đỉnh",[G.vertices.toLocaleString()]):a("Đang tính trọng số chạy nền… {0}% · {1} đỉnh",[Math.round(G.progress*100),G.vertices.toLocaleString()])}),t.jsx("progress",{max:100,value:Math.round(G.progress*100),"aria-label":a("Tiến độ tính trọng số")}),!G.done&&t.jsx("small",{className:"shot-hint",children:a("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:a("{0} đỉnh · trọng số {1} ms{2}",[z.info.vertices.toLocaleString(),z.info.ms,(z.info.via==="worker"?a(" · chạy nền"):"")+(z.info.source==="disk"?a(" (đã lưu trên máy)"):z.info.cached?a(" (bộ nhớ đệm)"):"")])}),J&&h&&t.jsxs("div",{className:"shot-rig-fingers",children:[t.jsx("span",{children:Mi(h)?a("Ngón tay: 5 ngón × 3 đốt mỗi tay"):a("Chưa có xương ngón tay")}),t.jsx("button",{type:"button",onClick:$,children:Mi(h)?a("Bỏ ngón tay"):a("Thêm ngón tay")})]}),h&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("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:a("Xoay xương tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsx("button",{type:"button",disabled:!K.length&&!h.bones,onClick:()=>N(l.id),children:a("Đặt lại dáng xương")})]}),t.jsx("small",{className:"shot-hint",children:K.length?a("{0} key xương trên timeline.",[K.length]):a("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:a("◇ Key tư thế tại {0}s",[(r*s.duration).toFixed(1)])}),t.jsxs("div",{className:"shot-rig-hands",role:"group","aria-label":a("Dáng tay"),children:[t.jsx("span",{children:a("Dáng tay")}),nr.map(_=>t.jsx("button",{type:"button","data-hand":_.id,onClick:()=>W(_.id),children:a(_.label)},_.id))]}),t.jsx("div",{className:"shot-rig-presets",children:zo[0].presets.map(_=>t.jsx("button",{type:"button",onClick:()=>e.patchItem(l.id,{pose:{...Kn[_]}}),children:a(_)},_))}),t.jsx(Fu,{disabled:e.busy,loop:e.motionLoop,mirror:e.motionMirror,onLoop:e.onMotionLoop,onMirror:e.onMotionMirror,onPlay:_=>e.onPlayClip(l.id,_),person:l,playhead:r*s.duration})]}):t.jsx("small",{className:"shot-hint",children:a("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},O1=()=>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"})]});ss.rig={apply(e,n,s){n.rig&&n.model&&ex(e,n.rig,n.model.gcsUri,s?(o,i)=>s.trackRigJob(o,i):void 0)},pose(e,n,s,o,i,r){const l=e.userData.rig;l&&n.rig&&Jg(l,i,xd(s.objectKeys?.[n.id],o,n.rig.bones),r)},gaze(e,n,s){const o=e.userData.rig;o&&o.rig.kind==="humanoid"&&Zg(o,s)}};ss.generate=e=>e.gen?.kind==="character"?Od(e.gen.spec).root:null;function _1({shot:e,engine:n,onClose:s,onBusy:o,onReady:i,timelineTarget:r,vfx:l}){ct();const[h,u]=R.useState(0),[m,d]=R.useState(e.duration),[f,p]=R.useState(720),[b,g]=R.useState(gn(e)),[v,y]=R.useState(!1),[k,C]=R.useState(0),[S,I]=R.useState(""),[j,M]=R.useState("film"),T=R.useRef(null);R.useEffect(()=>()=>T.current?.abort(),[]);const w=Number.isFinite(h)&&Number.isFinite(m)&&h>=0&&m>h&&m<=e.duration,E=async()=>{if(!n||!l)return;const A=new AbortController;T.current=A,y(!0),o(!0),C(0),I("");try{await l.run({height:f,fps:b,motionBlur:ua[j].samples,shutter:ua[j].shutter},C,A.signal),s()}catch(O){I(A.signal.aborted?"Đã huỷ xuất video.":O.message)}finally{T.current=null,y(!1),o(!1)}},N=async A=>{if(!n||!w)return;const O=new AbortController;T.current=O,y(!0),o(!0),C(0),I("");let H;try{const D={motionBlur:ua[j].samples,shutter:ua[j].shutter};if(H=await n.exportVideo({start:h,end:m,height:f,fps:b,...D,signal:O.signal,progress:C}),A==="download"){const $=URL.createObjectURL(H.blob),W=document.createElement("a");W.href=$,W.download=`${e.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-${h}-${m}.mp4`,W.click();const z=H.cleanup;setTimeout(()=>{URL.revokeObjectURL($),z()},6e4),H=void 0}else await i(H.blob,{start:h,end:m,height:f,fps:b,...D},A);s()}catch(D){I(O.signal.aborted?"Đã huỷ xuất video.":D.message)}finally{await H?.cleanup(),T.current=null,y(!1),o(!1)}};return t.jsx("div",{className:"shot-video-overlay",children:t.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":a("Xuất video camera"),className:"shot-video-dialog",children:[t.jsx("h2",{children:a("Xuất video camera · MP4")}),t.jsx("p",{children:a("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:[a("Từ giây"),t.jsx("input",{"aria-label":a("Video từ giây"),type:"number",min:0,max:e.duration,step:"0.1",value:Number.isFinite(h)?h:"",onChange:A=>u(A.target.valueAsNumber)})]}),t.jsxs("label",{children:[a("Đến giây"),t.jsx("input",{"aria-label":a("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:[a("Chất lượng"),t.jsxs("select",{"aria-label":a("Độ phân giải video"),value:f,onChange:A=>p(+A.target.value),children:[t.jsx("option",{value:720,children:a("720p · Nhẹ")}),t.jsx("option",{value:1080,children:a("1080p · Chi tiết")})]})]}),t.jsxs("label",{children:[a("Khung hình/giây"),t.jsx("select",{"aria-label":a("FPS video"),value:b,onChange:A=>g(+A.target.value),children:yd.map(A=>t.jsx("option",{value:A,children:a("{0} fps",[A])},A))})]}),t.jsxs("label",{title:a("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:[a("Nhoè chuyển động"),t.jsxs("select",{"aria-label":a("Nhoè chuyển động"),value:j,onChange:A=>M(A.target.value),children:[t.jsx("option",{value:"off",children:a("Tắt · xuất nhanh")}),t.jsx("option",{value:"film",children:a("Điện ảnh · màn trập 180°")}),t.jsx("option",{value:"strong",children:a("Mạnh · hành động nhanh")})]})]})]}),t.jsxs("p",{children:[w?a("{0} giây · {1} · khoảng {2} MB",[(m-h).toFixed(1),e.aspect,Math.ceil((m-h)*(f===1080?6:3)/8)]):a("Chọn khoảng thời gian hợp lệ trong shot."),w&&j!=="off"?" · "+a("xuất lâu hơn khoảng {0} lần",[ua[j].samples]):""]}),v&&t.jsxs(t.Fragment,{children:[t.jsx("progress",{max:100,value:k}),t.jsx("p",{children:k<100?a("Đang xuất từng frame… {0}%",[k]):a("Đang hoàn tất / lưu video…")}),t.jsx("button",{disabled:k===100,onClick:()=>T.current?.abort(),children:a("Huỷ xuất")})]}),S&&t.jsx("p",{role:"alert",children:a(S)}),!v&&l&&t.jsxs("div",{className:"shot-video-vfx",children:[t.jsx("p",{children:l.layers?a("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}”`:a("gốc")]):a("Cảnh chưa có hiệu ứng nào để xuất.")}),t.jsx("button",{className:"shot-primary",disabled:!l.layers,onClick:()=>void E(),children:a("✦ Xuất lớp hiệu ứng về Timeline")})]}),!v&&t.jsxs("div",{className:"shot-video-actions",children:[t.jsx("button",{onClick:s,children:a("Đóng")}),t.jsx("button",{disabled:!w,onClick:()=>void N("download"),children:a("Tải MP4")}),t.jsx("button",{disabled:!w,className:r||l?void 0:"shot-primary",onClick:()=>void N("canvas"),children:a("Đưa video vào Canvas")}),r&&t.jsx("button",{disabled:!w,className:"shot-primary",title:r,onClick:()=>void N("timeline"),children:a("Đưa về Timeline")})]}),t.jsx("small",{children:a("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 z1=(e,n)=>`${e} · VFX ${n==="behind"?a("sau người"):a("trước người")}`;async function B1(e,n,s,o,i={}){const r=n.shots.find(p=>p.id===n.activeShot),l=e.vfxLayers();if(!n.plate)throw new Error(a("Cảnh này không có video nền (mở từ một clip trên Timeline)."));if(!l.length)throw new Error(a("Cảnh chưa có hiệu ứng nào để xuất."));const h=dt.getState().canvasId,u=[],m=o.vfxAlpha??"auto",{vfxAlpha:d,...f}=o;for(const[p,b]of l.entries()){const g=m==="on"||m==="auto"&&await e.vfxOccludes(b),{blob:v,cleanup:y}=await e.exportVideo({...f,start:0,end:r.duration,vfx:b,alpha:g,signal:i.signal??new AbortController().signal,progress:k=>i.progress?.(Math.round((p*100+k)/l.length))});try{const k=z1(r.name,b),C=g?"webm":"mp4",{url:S,gcsUri:I}=await Us(new File([v],`${r.name}-vfx-${b}.${C}`,{type:`video/${C}`}),void 0,"video"),j=_t()?.getNode(s);if(!j||dt.getState().canvasId!==h)throw new Error(a("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi."));const M=_t()?.addNode("video",{url:S,gcsUri:I,label:k,duration:r.duration,ratio:r.aspect,status:"succeeded",shotSourceId:s,shotId:r.id,vfxLayer:b},{x:j.position.x+380,y:j.position.y+p*260},{sourceIds:[s]});if(!M)throw new Error(a("Không tạo được video trên Canvas"));const{width:T,height:w}=gf(r.aspect,{short:o.height});u.push({layer:b,nodeId:M,url:S,gcsUri:I,duration:r.duration,label:k,...g?{alpha:!0,fps:o.fps,width:T,height:w}:{}})}finally{await y()}}return u}const K1=(e,n)=>[...e].sort((s,o)=>(s.layer==="behind"?0:1)-(o.layer==="behind"?0:1)).map(s=>({op:"addVfxLayer",materialId:s.nodeId,clipId:n,layer:s.layer}));function H1(e,n){const s=dt.getState(),o=n?s.clips.find(l=>l.id===n):void 0;if(!o||o.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=nx(s.clips,K1(e,o.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(h=>!l.some(u=>u.source==="canvas"&&u.id===h.nodeId)).map(h=>({id:h.nodeId,source:"canvas",kind:"video",url:h.url,gcsUri:h.gcsUri,label:h.label,duration:h.duration}))]),{passes:e,placed:!0,clipId:o.id,pendingMatte:!!r.mattes?.length}}function W1({stage:e,selected:n,time:s,disabled:o,onApply:i,getBounds:r,getColliders:l,onPreview:h,embedded:u=!1}){ct();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([]),[b,g]=R.useState(""),[v,y]=R.useState(!1),[k,C]=R.useState(""),[S,I]=R.useState(null),[j,M]=R.useState(null),[T,w]=R.useState(null),[E,N]=R.useState(!1),[A,O]=R.useState(null),H=R.useRef(null),D=[...f,{role:"user",content:b.trim()}].slice(-12),$=JSON.stringify({scene:Lc(e,n,s,r(),l?.()),messages:D,model:m});R.useEffect(()=>{if(w(null),!b.trim()||v)return;let G=!1;N(!0);const _=setTimeout(()=>{const ee=JSON.parse($);cg(ee.scene,ee.messages,ee.model).then(Q=>{G||w({signature:$,credits:Q.reservedCredits})}).catch(Q=>{G||C(Q.message)}).finally(()=>{G||N(!1)})},400);return()=>{G=!0,clearTimeout(_)}},[$,b,v]);const W=R.useRef(null),z=R.useRef(!0),Y=R.useRef(!1);R.useEffect(()=>(z.current=!0,hg().then(G=>{z.current&&I(G)}).catch(()=>{}),()=>{z.current=!1}),[]),R.useEffect(()=>{W.current&&(W.current.scrollTop=W.current.scrollHeight)},[f,v,j]);const J=j&&(j.revision!==e.revision||j.shotId!==e.activeShot),V=async(G=!1)=>{if(Y.current||o||!G&&(!b.trim()||T?.signature!==$))return;const _=G?H.current:{scene:Lc(e,n,s,r(),l?.()),messages:D,id:crypto.randomUUID(),revision:e.revision,shotId:e.activeShot,model:m};if(_){H.current=_,Y.current=!0,y(!0),C(""),M(null),p(_.messages),g("");try{const{plan:ee,model:Q,billing:ve}=await dg(_.scene,_.messages,_.id,_.model);if(!z.current)return;H.current=null,O(ve.credits),I({available:!0,model:Q}),p([..._.messages,{role:"assistant",content:ee.message}]),ee.tracks.length&&M({plan:ee,revision:_.revision,shotId:_.shotId})}catch(ee){z.current&&C(ee.message)}finally{Y.current=!1,z.current&&y(!1)}}},K=u?"div":"section";return t.jsxs(K,{className:u?"shot-agent-embedded":"shot-agent","aria-label":a("AI Agent 3D"),children:[t.jsxs("select",{"aria-label":a("Model AI"),value:m,disabled:v,onChange:G=>{d(G.target.value),H.current=null,C("");try{localStorage.setItem("clipoox.shot.keyModel",G.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:a("Đề xuất key cho đối tượng đang chọn hoặc camera")}):t.jsxs(t.Fragment,{children:[t.jsx("b",{children:a("✦ AI Agent")}),t.jsx("small",{children:S?.model||"GPT 5.6 sol"})]}),t.jsx("button",{title:a("Xóa hội thoại"),disabled:v,onClick:()=>{p([]),M(null),C(""),H.current=null},children:"↺"})]}),t.jsxs("div",{className:"shot-agent-chat",ref:W,role:"log","aria-label":a("Hội thoại AI"),children:[!f.length&&t.jsx("p",{className:"shot-agent-intro",children:a("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((G,_)=>t.jsx("div",{className:`shot-agent-message ${G.role}`,children:G.content},_)),v&&t.jsx("p",{role:"status",children:a("Đang tạo đề xuất key…")}),k&&t.jsxs("p",{role:"alert",children:[k,H.current&&t.jsx("button",{disabled:v,onClick:()=>void V(!0),children:a("Thử lại")})]}),j&&t.jsxs("div",{className:"shot-agent-proposal",children:[t.jsxs("small",{children:[j.plan.tracks.length," ",a("track ·")," ",j.plan.tracks.reduce((G,_)=>G+_.keys.length,0)," ",a("key ·")," ",j.plan.duration,a("s")]}),J?t.jsx("p",{children:a("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:j.plan.tracks.map(G=>t.jsxs("li",{children:[G.subjectId==="camera"?"Camera":e.items.find(_=>_.id===G.subjectId)?.name,": ",G.replaceRange?a("Sửa đoạn {0}–{1}s",[G.replaceRange.start.toFixed(2),G.replaceRange.end.toFixed(2)]):a("Thêm/cập nhật {0}–{1}s",[G.keys[0].seconds.toFixed(2),G.keys.at(-1).seconds.toFixed(2)])]},G.subjectId))}),t.jsx("button",{disabled:o,onClick:()=>h(j.plan,G=>{G&&(M(null),p(_=>[..._,{role:"assistant",content:a("Đã giữ thay đổi sau khi xem thử. Có thể hoàn tác bằng Ctrl/Cmd + Z.")}]))}),children:a("Xem thử chuyển động")}),t.jsx("button",{className:"shot-primary",disabled:o,onClick:()=>{try{i(j.plan),M(null),p(G=>[...G,{role:"assistant",content:a("Đã áp dụng key. Bấm Play để xem; Ctrl/Cmd + Z để hoàn tác.")}])}catch(G){C(G.message)}},children:a("Áp dụng key")})]})]})]}),t.jsxs("form",{onSubmit:G=>{G.preventDefault(),V()},children:[t.jsx("textarea",{"aria-label":a("Mô tả key cho AI"),maxLength:4e3,rows:3,value:b,placeholder:a("Ví dụ: xe đi tới 3 mét trong 5 giây…"),onChange:G=>g(G.target.value)}),t.jsx("small",{children:T?.signature===$?a("Tạm giữ tối đa {0} credit; hoàn phần dư theo token thực tế.",[T.credits.toFixed(2)]):E&&b.trim()?a("Đang tính phí…"):a("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||o||!b.trim()||T?.signature!==$||S?.available===!1,children:a("Tạo key")})]}),A!==null&&t.jsx("small",{children:a("Phí: {0} credit.",[A.toFixed(2)])}),S?.available===!1&&t.jsx("small",{children:a("Admin cần cấu hình API key để bật Agent.")})]})}const Kh=[["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)"]],G1={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"]},Hh=(e,n)=>{try{return localStorage.getItem(e)||n}catch{return n}},Vi=(e,n)=>{try{localStorage.setItem(e,n)}catch{}},En=e=>String(Math.round(e*100)/100);function q1({stage:e,disabled:n,agent:s,lock:o}){ct();const i=td(),[r,l]=R.useState(()=>{const ie=Hh("clipoox.shot.missionMode","mission");return ie==="keys"||ie==="set"?ie:"mission"}),h=ie=>[ie==="set"?"clipoox.shot.setModel2":"clipoox.shot.missionModel2","gpt-6.1-sol"],u=ie=>{const[Me,Ee]=h(ie),Se=Hh(Me,Ee);return Kh.some(([he])=>he===Se)?Se:Ee},[m,d]=R.useState(()=>u(r)),[f,p]=R.useState(!1),b=ie=>{p(ie),Vi("clipoox.shot.hq","")},g=f?Ea:m,[v,y]=R.useState(""),[k,C]=R.useState(null),[S,I]=R.useState(""),j=R.useRef(null),M=R.useRef(null),T=xf(e),w=bf(T),[E,N]=R.useState(null),[A,O]=R.useState(!1),[H,D]=R.useState(null),$=R.useRef(null);R.useEffect(()=>{if(!H)return;const ie=Ee=>{$.current?.contains(Ee.target)||D(null)},Me=Ee=>{Ee.key==="Escape"&&(Ee.stopPropagation(),D(null))};return window.addEventListener("pointerdown",ie),window.addEventListener("keydown",Me,!0),()=>{window.removeEventListener("pointerdown",ie),window.removeEventListener("keydown",Me,!0)}},[H]);const[W,z]=R.useState(""),[Y,J]=R.useState(""),[V,K]=R.useState(null),G=["thinking","acting","rendering"].includes(i.phase);R.useEffect(()=>{j.current&&(j.current.scrollTop=j.current.scrollHeight)},[i.log.length]);const _=ie=>{l(ie),Vi("clipoox.shot.missionMode",ie),d(u(ie))},ee=ie=>{d(ie),Vi(h(r)[0],ie)},Q=async ie=>{if(I(""),!ie){C(null);return}if(ie.size>28e4||!["image/jpeg","image/png"].includes(ie.type)){I(a("Ảnh tham chiếu phải là JPG/PNG ≤ 280 KB."));return}const Me=await new Promise((Ee,Se)=>{const he=new FileReader;he.onload=()=>Ee(String(he.result)),he.onerror=()=>Se(he.error),he.readAsDataURL(ie)});C({name:ie.name,data:Me})},ve=(i.phase==="done"||i.phase==="capped")&&!!i.missionId&&i.model===g&&i.quality==="high"===f,xe=A?yf({from:Number(W),to:Number(Y)},T.duration):null,q=(ie=!1)=>{const Me=v.trim();if(!Me||G||n)return;y("");const Ee={window:xe,continueFrom:V,quality:f?"high":null};K(null),ie&&ve?i.followUp(Me,Ee):i.start(Me,k?.data||null,g,r==="set"?"set":"shot",Ee)},ue=ie=>{N(null),o&&Math.abs(ie-w)>1e-6&&o.onChange(Math.max(0,Math.min(T.duration,ie)))},pe=(ie,Me=null)=>{y(ie),K(Me),requestAnimationFrame(()=>{const Ee=M.current;Ee&&(Ee.focus(),Ee.setSelectionRange(ie.length,ie.length))})},U=ie=>a("Giữ nguyên 0–{0}s, kéo dài shot thêm 5s, từ {0}s đến {1}s: ",[En(ie),En(ie+5)]),le=()=>{A||(z(En(w)),J(En(T.duration))),O(!A)},ce=(navigator.language||"").startsWith("vi"),Le={thinking:a("Đang nghĩ…"),acting:a("Đang dựng trong composer…"),rendering:a("Đang render & đưa vào canvas…"),done:a("Xong"),error:a("Lỗi"),cancelled:a("Đã dừng"),capped:a("Đã dùng hết {0} credit của lượt này",[Ka]),idle:""}[i.phase],je=t.jsxs("label",{className:`shot-lock-chip shot-hq-chip${f?" on":""}`,children:[t.jsx("input",{type:"checkbox","aria-label":a("Model chất lượng cao · Opus"),checked:f,disabled:G,onChange:ie=>b(ie.target.checked)}),t.jsxs("span",{"aria-hidden":"true",children:["✦ ",a("Chất lượng cao")]})]});return t.jsxs("section",{className:"shot-agent shot-mission","aria-label":a("Mission Agent"),children:[t.jsxs("div",{className:"shot-agent-heading",children:[t.jsx("b",{children:a("✦ Mission")}),r!=="keys"&&t.jsx("select",{className:"shot-mission-model","aria-label":a("Model AI"),value:g,disabled:G||f,onChange:ie=>ee(ie.target.value),title:a("GPT 6 Astra suy luận tốt hơn, giá token cao hơn (tính theo dùng thật)"),children:Kh.map(([ie,Me])=>t.jsx("option",{value:ie,children:a(Me)},ie))}),r!=="keys"&&i.missionId&&!G&&t.jsx("button",{title:a("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:G,onClick:()=>_("mission"),children:a("Dựng shot")}),t.jsx("button",{role:"tab","aria-selected":r==="set",className:r==="set"?"active":"",disabled:G,onClick:()=>_("set"),children:a("Dựng bối cảnh")}),t.jsx("button",{role:"tab","aria-selected":r==="keys",className:r==="keys"?"active":"",disabled:G,onClick:()=>_("keys"),children:a("Key đối tượng")})]}),r==="keys"?t.jsx(W1,{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"?a("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."):a("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":a("Gợi ý"),children:G1[r==="set"?"set":"mission"].map(ie=>t.jsx("button",{type:"button",disabled:G||n,onClick:()=>y(a(ie)),children:a(ie)},ie))})]}),i.log.length>0&&t.jsxs("div",{className:"shot-agent-chat shot-mission-log",ref:j,role:"log",children:[t.jsxs("div",{className:"shot-mission-status",children:[i.quality==="high"&&t.jsx("b",{className:"shot-hq-badge",children:a("Chất lượng cao · Opus")}),Le," · ",a("bước")," ",i.step,"/",i.maxSteps," · ",i.spent.toFixed(2),i.budget!=null?` / ${i.budget}`:""," cr"]}),i.log.slice(-12).map((ie,Me)=>t.jsx("div",{className:"shot-mission-line",children:ie},Me)),i.sheet&&t.jsx("img",{className:"shot-mission-sheet",src:i.sheet,alt:a("Contact sheet 6 khung hình")}),i.phase==="done"&&t.jsx("div",{className:"shot-mission-facts",children:vf(e,i.facts,ce)}),i.phase==="done"&&i.purpose==="set"&&i.ready&&t.jsx("div",{className:"shot-mission-done",children:a('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:a('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:a('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).',[Ka])}),i.error&&t.jsx("p",{role:"alert",children:i.error})]})]}),r==="set"&&t.jsx("div",{className:"shot-mission-lock",children:je}),r==="mission"&&t.jsxs("div",{ref:$,className:`shot-mission-lock${w>0?" on":""}`,role:"group","aria-label":a("Khoá đoạn đã ưng"),children:[o&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:`shot-lock-chip${w>0?" on":""}`,"aria-expanded":H==="lock",title:w>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[En(w)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên."),onClick:()=>D(H==="lock"?null:"lock"),children:["🔒 ",w>0?`0–${En(w)}s`:a("Khoá")]}),t.jsxs("button",{type:"button",className:`shot-lock-chip${A?xe?" on":" bad":""}`,"aria-expanded":H==="window",onClick:()=>D(H==="window"?null:"window"),children:["✂ ",A&&xe?`${En(xe.from)}–${En(xe.to)}s`:a("Chỉ sửa đoạn")]})]}),je,H==="lock"&&o&&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:[a("Khoá")," 0–"]}),t.jsx("input",{"aria-label":a("Khoá đến (giây)"),inputMode:"decimal",value:E??En(w),disabled:G,onFocus:ie=>ie.target.select(),onChange:ie=>N(ie.target.value),onBlur:()=>{if(E!=null){const ie=Number(E.replace(",","."));Number.isFinite(ie)?ue(ie):N(null)}},onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),ie.target.blur()),ie.key==="Escape"&&(N(null),ie.target.blur())}}),t.jsx("span",{children:"s"}),t.jsx("button",{type:"button",disabled:G||o.playhead<=0,title:a("Agent sẽ không sửa gì trước vị trí playhead; bạn vẫn sửa tay được."),onClick:()=>ue(o.playhead),children:a("Khoá tới playhead")}),w>0&&t.jsx("button",{type:"button",disabled:G,onClick:()=>ue(0),children:a("Mở khoá")})]}),t.jsx("small",{children:w>0?a("Agent giữ nguyên 0–{0}s, chỉ làm tiếp từ {0}s (bạn vẫn sửa tay được).",[En(w)]):a("Ưng phần đầu rồi thì khoá lại: Agent làm tiếp mà không đè lên.")})]}),H==="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:G,onChange:le}),t.jsx("span",{children:a("Chỉ sửa đoạn")}),A&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Sửa từ (giây)"),inputMode:"decimal",value:W,disabled:G,onChange:ie=>z(ie.target.value.replace(",","."))}),t.jsx("span",{children:"–"}),t.jsx("input",{"aria-label":a("Sửa đến (giây)"),inputMode:"decimal",value:Y,disabled:G,onChange:ie=>J(ie.target.value.replace(",","."))}),t.jsx("span",{children:"s"})]})]}),A&&!xe&&t.jsx("small",{role:"alert",children:a("Đ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:a("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:ie=>{ie.preventDefault(),q(!1)},children:[t.jsx("textarea",{ref:M,"aria-label":a("Mô tả shot cho Agent"),maxLength:4e3,rows:3,value:v,disabled:G||n,placeholder:ve?a("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"?a("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"):a("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:ie=>{y(ie.target.value),ie.target.value.trim()||K(null)}}),ve&&r==="mission"&&t.jsxs("div",{className:"shot-mission-chips","aria-label":a("Làm tiếp"),children:[t.jsx("button",{type:"button",disabled:n,onClick:()=>pe(a("Sửa đoạn đã làm: ")),children:a("Sửa đoạn đã làm")}),t.jsx("button",{type:"button",disabled:n,onClick:()=>pe(U(T.duration),T.duration),children:a("Làm tiếp thêm 5s")}),o&&t.jsx("button",{type:"button",disabled:n,title:a("Khoá 0–{0}s rồi viết phần tiếp theo",[En(T.duration)]),onClick:()=>{ue(T.duration),pe(U(T.duration),T.duration)},children:a("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:G,onChange:ie=>{Q(ie.target.files?.[0]),ie.target.value=""}}),t.jsx("span",{children:k?`🖼 ${k.name}`:a("+ Ảnh tham chiếu (tuỳ chọn)")})]}),k&&!G&&t.jsx("button",{type:"button",onClick:()=>C(null),children:"×"}),G?t.jsx("button",{type:"button",className:"shot-primary",onClick:()=>i.stop(),children:a("Dừng")}):t.jsxs(t.Fragment,{children:[ve&&t.jsx("button",{type:"button",className:"shot-continue",disabled:n||!v.trim(),title:a("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:()=>q(!0),children:a("↪ Sửa / làm tiếp phiên này")}),t.jsx("button",{className:"shot-primary",disabled:n||!v.trim(),title:a("Yêu cầu mới: Agent không dùng lịch sử phiên trước"),children:a("Chạy Agent (mới)")})]})]}),S&&t.jsx("small",{role:"alert",children:S})]})]})]})}const U1=1200,X1=4e3,V1=8e3,Y1=12e4;function Q1(e,n,s,o){let i=!1,r=null,l=0,h=!1;const u=jf(),m=()=>typeof document<"u"&&document.hidden?V1:Date.now()-l<Y1?U1:X1,d=async p=>{l=Date.now();let b;try{b=await kf(p.tool,p.args||{},e)}catch(y){b={ok:!1,error:String(y?.message||y).slice(0,500)}}const{_image:g,...v}=b;try{await mg(p.id,{tabId:u,ok:b.ok!==!1,result:wf(v),...typeof g=="string"?{image:g}:{}})}catch{}p.tool==="drive_character"&&b.ok!==!1&&typeof b.start=="number"&&s?.(b.start)},f=async()=>{if(!i){if(!h){h=!0;try{const p=o?.()||void 0,{commands:b}=await ug({tabId:u,scene:n().slice(0,120),...p?{sceneId:p}:{}});for(const g of b||[]){if(i)break;await d(g)}}catch{}finally{h=!1}}i||(r=setTimeout(()=>{f()},m()))}};return f(),()=>{i=!0,r&&clearTimeout(r)}}function Z1({shot:e,patch:n,progress:s,seek:o,engine:i,selected:r,select:l}){ct();const[h,u]=R.useState(!1),m=e.cameraKeys||[],d=m.find(j=>j.id===r),f=e.cameraMode==="free",p=[...m].sort((j,M)=>j.time-M.time),b=d?Mf(p,p.indexOf(d)):null,g=j=>n(sr(j)),v=(j,M)=>g(m.map(T=>T.id===j?{...T,...M}:T)),y=j=>Cf(e,j),k=()=>{const j=m.find(T=>Math.abs(T.time-s)<1e-6);if(j){l(j.id);return}const M=y(s);g([...m,M]),l(M.id)};R.useEffect(()=>{if(i){if(e.motion!=="path"&&!h){i.setPathEditor(void 0);return}return i.setPathEditor({selected:r,drawing:h,select:j=>{l(j);const M=m.find(T=>T.id===j);M&&o(M.time)},move:(j,M)=>v(j,{position:M}),add:j=>{const M={...y(1),position:j},T=[...m,M].map((w,E,N)=>({...w,time:N.length>1?E/(N.length-1):0}));g(T),l(M.id),o(T.at(-1)?.time||0)}}),()=>i.setPathEditor(void 0)}},[i,e.id,e.cameraKeys,e.motion,r,h]),R.useEffect(()=>{u(!1),l(null)},[e.id]);const C=j=>{const M=Nf(e,j);g(M),l(M[0].id),o(0),u(!1)},S=(j,M,T,w,E)=>t.jsxs("label",{className:"shot-path-number",children:[a(j),t.jsx(Sn,{"aria-label":a(j),step:"0.1",min:w,max:E,precision:3,value:M,onCommit:T})]}),I=(j,M,T)=>t.jsx("div",{className:"shot-path-vector",children:M.map((w,E)=>t.jsx("div",{children:S(`${a(j)} ${"XYZ"[E]}`,w,N=>T(M.map((A,O)=>E===O?N:A)))},E))});return t.jsxs("section",{className:"shot-path-editor",children:[t.jsx("h3",{children:a("ĐƯỜNG CHẠY CAMERA")}),t.jsx("p",{children:a("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":a("Hướng camera"),children:[t.jsx("button",{role:"radio","aria-checked":!f,className:f?"":"shot-primary",onClick:()=>n({cameraMode:void 0}),children:a("Bám theo (Track)")}),t.jsx("button",{role:"radio","aria-checked":f,className:f?"shot-primary":"",onClick:()=>n({cameraMode:"free"}),children:a("Tự do (Free style)")})]}),t.jsx("p",{className:"shot-camera-mode-hint",children:f?a("Camera nhìn theo hướng đi của đường; chọn từng điểm để xoay hướng nhìn tuỳ ý."):a('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(([j,M])=>t.jsxs("button",{onClick:()=>C(j),children:[{circle:t.jsx(Ne.circle,{}),spiral:t.jsx(Ne.spiral,{}),line:t.jsx(Ne.line,{}),curve:t.jsx(Ne.curve,{})}[j],a(M)]},j))}),t.jsxs("button",{className:h?"shot-primary":"",onClick:()=>{u(!h),h||(g([]),l(null),o(0),i?.view(!0))},children:[t.jsx(Ne.pen,{}),h?a("✓ Xong vẽ đường").replace("✓ ",""):a("✎ Vẽ đường mới bằng điểm").replace("✎ ","")]}),h&&t.jsx("p",{children:a("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:k,children:[t.jsx(Ne.key,{}),a("+ Key tại thời điểm này").replace("+ ","")]}),t.jsx("button",{disabled:!m.length,onClick:()=>g(m.map((j,M)=>({...j,time:m.length>1?M/(m.length-1):0}))),children:a("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:j=>n({pathSmooth:j.target.checked})})," ",a("Đường cong mượt")]}),t.jsx("div",{className:"shot-path-keys",children:m.map((j,M)=>t.jsxs("button",{className:j.id===r?"shot-primary":"",onClick:()=>{l(j.id),o(j.time)},children:["◆ ",M+1," · ",(j.time*e.duration).toFixed(1),a("s")]},j.id))})]}),d&&t.jsxs("div",{className:"shot-path-key",children:[t.jsxs("b",{children:[a("Điểm")," ",m.indexOf(d)+1]}),t.jsx("button",{onClick:()=>l(null),children:a("Bỏ chọn điểm")}),S(a("Thời điểm key (giây)"),d.time*e.duration,j=>{const M=j/e.duration;m.some(T=>T.id!==d.id&&Math.abs(T.time-M)<1e-6)||(v(d.id,{time:M}),o(M))},0,e.duration),I("Camera",d.position,j=>v(d.id,{position:j})),!f&&I(a("Nhìn tới"),d.target,j=>v(d.id,{target:j})),f&&b&&t.jsxs("div",{className:"shot-path-aim",children:[S(a("Xoay ngang (°)"),b[0],j=>v(d.id,{aim:[j,b[1]]}),-360,360),S(a("Ngẩng / cúi (°)"),b[1],j=>v(d.id,{aim:[b[0],j]}),-85,85),t.jsx("button",{disabled:!d.aim,onClick:()=>v(d.id,{aim:void 0}),children:a("Nhìn theo hướng đi")})]}),S(a("Tiêu cự key (mm)"),d.lens,j=>v(d.id,{lens:j}),14,200),S(a("Nghiêng key (°)"),d.roll,j=>v(d.id,{roll:j})),t.jsx("button",{onClick:()=>{const j=i?.captureCamera();j&&v(d.id,{position:j.position,target:j.target,lens:j.lens,roll:j.roll,...f&&j.target&&j.position?{aim:Sf(new oe(j.target[0]-j.position[0],j.target[1]-j.position[1],j.target[2]-j.position[2]))}:{}})},children:a("Lấy góc đang quan sát cho key")}),t.jsx("button",{onClick:()=>{g(m.filter(j=>j.id!==d.id)),l(null)},children:a("Xoá key này")})]})]})}const $u=.5,Du=60,J1=e=>Math.min(Du,Math.max($u,Math.round(e*100)/100));function Ou(e){const n=gn(e);return{aspect:[...ac.includes(e.aspect)?[]:[a("Seedance không nhận tỷ lệ {0}; khi gửi sẽ dùng {1}.",[e.aspect,ar(e.aspect,ac)])],...Fa.includes(e.aspect)?[]:[a("Ảnh thật (GPT Image) không nhận tỷ lệ {0}; sẽ dùng {1}.",[e.aspect,ar(e.aspect,Fa)])]],duration:e.duration<4?[a("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?[]:[a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[n])]}}const Wh=e=>{const n=Ef(e),s=n>=1?14:14*n,o=n>=1?14/n:14;return t.jsx("span",{className:"shot-fmt-glyph","aria-hidden":"true",style:{width:s,height:o}})};function ej({shot:e,patch:n,disabled:s}){ct();const[o,i]=R.useState(null),[r,l]=R.useState(null),h=R.useRef(null),u=gn(e),m=Ou(e);R.useEffect(()=>{if(!o)return;const C=S=>{h.current?.contains(S.target)||i(null)};return document.addEventListener("pointerdown",C,!0),()=>document.removeEventListener("pointerdown",C,!0)},[o]),R.useEffect(()=>{o&&h.current?.querySelector('.shot-fmt-pop [aria-checked="true"], .shot-fmt-pop button')?.focus()},[o]);const d=C=>h.current?.querySelector(`[data-fmt="${C}"]`),f=C=>{const S=o;i(null),S&&requestAnimationFrame(()=>d(S)?.focus())},p=C=>{n(C),f()},b=C=>{if(Number.isFinite(C)){const S=J1(C);S!==e.duration&&n({duration:S})}},g=()=>{if(r!==null){const C=Number(r.replace(",","."));r.trim()!==""&&b(C),l(null)}},v=C=>{if(C.key==="Escape"&&o){C.preventDefault(),C.stopPropagation(),f();return}const S=C.target.closest(".shot-fmt-pop");if(S&&["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(C.key)){C.preventDefault();const I=[...S.querySelectorAll("button")],j=I.indexOf(C.target),M=C.key==="Home"?0:C.key==="End"?I.length-1:(j+(C.key==="ArrowDown"||C.key==="ArrowRight"?1:-1)+I.length)%I.length;I[M]?.focus()}},y=[...Af,...Tf.includes(e.aspect)?[e.aspect]:[]],k=a("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:h,onKeyDown:v,children:[t.jsxs("small",{children:[Number(e.lens.toFixed(1)),a("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":o==="aspect","aria-label":a("Tỷ lệ khung hình: {0}",[e.aspect]),title:[a("Tỷ lệ khung hình của shot"),...m.aspect].join(`
285
285
  `),onClick:()=>i(o==="aspect"?null:"aspect"),children:[Wh(e.aspect),e.aspect]}),o==="aspect"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Tỷ lệ khung hình"),children:[y.map(C=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.aspect===C,className:e.aspect===C?"active":"",onClick:()=>p({aspect:C}),children:[Wh(C),C]},C)),m.aspect.map(C=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",C]},C))]})]}),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":a("Thời lượng shot (giây)"),title:k,children:[t.jsx("button",{type:"button",disabled:s||e.duration<=$u,"aria-label":a("Giảm 0,5 giây"),title:a("Giảm 0,5 giây"),onClick:()=>b(e.duration-.5),children:"−"}),t.jsx("input",{"aria-label":a("Thời lượng shot (giây)"),title:k,inputMode:"decimal",disabled:s,className:m.duration.length?"warn":"",value:r??String(Number(e.duration.toFixed(2))),onFocus:C=>C.currentTarget.select(),onChange:C=>l(C.target.value),onBlur:g,onKeyDown:C=>{if(C.key==="Enter")C.preventDefault(),g(),C.currentTarget.blur();else if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),l(null),C.currentTarget.blur();else if(C.key==="ArrowUp"||C.key==="ArrowDown"){C.preventDefault();const S=r!==null&&Number.isFinite(Number(r.replace(",",".")))?Number(r.replace(",",".")):e.duration;l(null),b(S+(C.key==="ArrowUp"?.5:-.5))}}}),t.jsx("span",{className:"shot-fmt-unit","aria-hidden":"true",children:a("s")}),t.jsx("button",{type:"button",disabled:s||e.duration>=Du,"aria-label":a("Tăng 0,5 giây"),title:a("Tăng 0,5 giây"),onClick:()=>b(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":o==="dur","aria-label":a("Chọn nhanh thời lượng"),title:[a("Chọn nhanh thời lượng"),...m.duration].join(`
286
286
  `),onClick:()=>i(o==="dur"?null:"dur"),children:"▾"}),o==="dur"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Chọn nhanh thời lượng"),children:[Lf.map(C=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e.duration===C,className:e.duration===C?"active":"",onClick:()=>p({duration:C}),children:[C," ",a("giây")]},C)),m.duration.map(C=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",C]},C))]})]}),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":o==="fps","aria-label":a("Tốc độ khung hình: {0} fps",[u]),title:[a("Tốc độ khung hình (fps) khi xuất video camera"),...m.fps].join(`
287
- `),onClick:()=>i(o==="fps"?null:"fps"),children:[u,a("fps")]}),o==="fps"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Tốc độ khung hình (fps)"),children:[yd.map(C=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u===C,className:u===C?"active":"",title:C===40?a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[C]):void 0,onClick:()=>p({fps:C}),children:[C," ",a("fps")]},C)),m.fps.map(C=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",C]},C))]})]})]})}function Tr(e,n,s){const o=_t();if(!o||!e.url)return null;const i=o.nodes().find(l=>l.type==="image"&&l.data.gcsUri===e.gcsUri);if(i)return i.id;const r=o.getNode(n);return o.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 Gh(e,n){const s=e?_t()?.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 tj(e,n,s){let o=!1;const i=e.items.map((r,l)=>{const h=r.castId?n.cast.find(m=>m.id===r.castId):void 0;if(!h)return r;const u={...r,name:h.name,color:h.color};if(r.kind==="person"&&(u.figure=h.figure?Wt(h.figure):void 0,u.look=h.look),h.reference&&(r.reference?.nodeId?_t()?.getNode(r.reference.nodeId)?.data?.gcsUri:void 0)!==h.reference.gcsUri){const d=Tr(h.reference,s,l);d&&(u.reference={nodeId:d,url:h.reference.url||"",name:h.reference.name})}return JSON.stringify(u)!==JSON.stringify(r)&&(o=!0),u});return o?{...e,items:i}:null}function nj({stage:e,nodeId:n,selected:s,disabled:o,change:i,onError:r,onSelect:l}){ct();const[h,u]=R.useState(null),[m,d]=R.useState(null),[f,p]=R.useState(""),[b,g]=R.useState(!1),v=R.useRef(null),y=e.series;R.useEffect(()=>{if(!y?.id){d(null);return}let w=!0;return pg(y.id).then(E=>{if(w&&(d(E),v.current!==E.id)){v.current=E.id;const N=tj(e,E,n);N&&i(()=>N)}}).catch(E=>r(E.message)),()=>{w=!1}},[y?.id]),R.useEffect(()=>{!y?.id&&h===null&&fg().then(w=>u(w.series)).catch(()=>u([]))},[y?.id,h]);const k=async w=>{g(!0);try{const{id:E,updatedAt:N,...A}=w;await gg(E,A),d(w)}catch(E){r(E.message)}finally{g(!1)}},C=async()=>{const w=f.trim();if(!w)return;const E={id:vt(),name:w,cast:[],locations:[],episodes:[]};await k(E),i(N=>({...N,series:{id:E.id,name:w}})),p("")},S=async()=>{if(!m||!s||!["person","model"].includes(s.kind))return;const w=s.castId&&m.cast.some(A=>A.id===s.castId)?s.castId:vt(),E=Gh(s.reference?.nodeId,s.reference?.name||s.name),N={id:w,name:s.name.slice(0,60),color:/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#baca9e",...s.kind==="person"&&s.figure?{figure:Wt(s.figure)}:{},...s.kind==="person"&&s.look?{look:s.look}:{},...E?{reference:E}:{},...s.kind==="model"&&s.model?{model:{gcsUri:s.model.gcsUri,name:s.model.name,...s.model.height?{height:s.model.height}:{}}}:{}};await k({...m,cast:[...m.cast.filter(A=>A.id!==w),N]}),i(A=>({...A,items:A.items.map(O=>O.id===s.id?{...O,castId:w}:O)})),s.reference&&!E&&r(a("Ả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=w=>{const E=e.items.length,N=w.model?{...Mn("model",E),model:w.model}:{...Mn("person",E),...w.figure?{figure:Wt(w.figure)}:{},...w.look?{look:w.look}:{}},A=w.reference?Tr(w.reference,n,E):null,O={...N,name:w.name,color:w.color,castId:w.id,...A&&w.reference?{reference:{nodeId:A,url:w.reference.url||"",name:w.reference.name}}:{}};i(H=>({...H,items:[...H.items,O]})),l(O.id)},j=async w=>{if(!m)return;const E=e.items.find(H=>H.kind==="set"&&H.set),N=(e.styleRefs||[]).flatMap(H=>{const D=Gh(H.nodeId,H.name);return D?[D]:[]}),O={id:m.locations.find(H=>H.name===w)?.id||vt(),name:w,...E?.set?{setId:E.set.id}:{},lighting:Pa(e.lighting),...N.length?{styleRefs:N}:{}};await k({...m,locations:[...m.locations.filter(H=>H.id!==O.id),O]}),i(H=>({...H,series:{...H.series,location:O.id}}))},M=w=>{const E=(w.styleRefs||[]).flatMap((N,A)=>{const O=Tr(N,n,10+A);return O?[{nodeId:O,url:N.url||"",name:N.name}]:[]});i(N=>{const A=w.setId&&N.items.some(H=>H.kind==="set"&&H.set?.id===w.setId),O=w.setId&&!A?[{...Mn("set",N.items.length),name:w.name,set:{id:w.setId,name:w.name}},...N.items]:N.items;return{...N,items:O,...w.lighting?{lighting:Pa(w.lighting)}:{},...E.length?{styleRefs:E}:{},series:{...N.series,location:w.id}}})},T=async w=>{if(!m||!w.trim())return;const E={id:vt(),name:w.trim().slice(0,80)};await k({...m,episodes:[...m.episodes,E]}),i(N=>({...N,series:{...N.series,episode:E.id}}))};return y?t.jsxs("div",{className:"shot-series",children:[t.jsxs("div",{className:"shot-series-row",children:[t.jsx("b",{children:y.name}),t.jsx("button",{disabled:o,onClick:()=>i(w=>({...w,series:void 0})),children:a("Bỏ gắn")})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tập")}),t.jsxs("select",{"aria-label":a("Tập"),value:y.episode||"",disabled:o,onChange:w=>{if(w.target.value==="+"){const E=window.prompt(a("Tên tập"),`Tập ${m.episodes.length+1}`);E&&T(E);return}i(E=>({...E,series:{...E.series,episode:w.target.value||void 0}}))},children:[t.jsx("option",{value:"",children:"—"}),m.episodes.map(w=>t.jsx("option",{value:w.id,children:w.name},w.id)),t.jsx("option",{value:"+",children:a("+ Tập mới…")})]})]}),t.jsxs("h4",{children:[a("Dàn nhân vật")," · ",m.cast.length]}),t.jsx("ul",{className:"shot-series-list",children:m.cast.map(w=>t.jsxs("li",{children:[w.reference?.url?t.jsx("img",{src:w.reference.url,alt:""}):t.jsx("span",{className:"shot-series-dot",style:{background:w.color}}),t.jsxs("span",{children:[w.name,w.figure?t.jsxs("small",{children:[" · ",w.figure.height.toFixed(2)," m"]}):null]}),t.jsx("button",{"aria-label":a("Đưa {0} vào cảnh",[w.name]),disabled:o,onClick:()=>I(w),children:"+"})]},w.id))}),t.jsx("button",{disabled:o||b||!s||!["person","model"].includes(s.kind),onClick:()=>void S(),children:s?.castId?a("Cập nhật nhân vật vào series"):a("Lưu nhân vật đang chọn vào series")}),t.jsxs("h4",{children:[a("Bối cảnh")," · ",m.locations.length]}),t.jsx("ul",{className:"shot-series-list",children:m.locations.map(w=>t.jsxs("li",{className:y.location===w.id?"active":"",children:[t.jsx("span",{className:"shot-series-dot","aria-hidden":"true",children:"⌂"}),t.jsxs("span",{children:[w.name,w.setId?t.jsxs("small",{children:[" · ",a("có set")]}):null]}),t.jsx("button",{"aria-label":a("Áp dụng bối cảnh {0}",[w.name]),disabled:o,onClick:()=>M(w),children:a("Dùng")})]},w.id))}),t.jsx("button",{disabled:o||b,onClick:()=>{const w=window.prompt(a("Tên bối cảnh"),e.items.find(E=>E.kind==="set")?.name||`Bối cảnh ${m.locations.length+1}`);w?.trim()&&j(w.trim().slice(0,60))},children:a("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":a("Chọn series"),value:"",disabled:o||!h?.length,onChange:w=>{const E=h?.find(N=>N.id===w.target.value);E&&i(N=>({...N,series:{id:E.id,name:E.name}}))},children:[t.jsx("option",{value:"",children:h===null?a("Đang tải…"):h.length?a("Gắn shot vào series…"):a("Chưa có series")}),h?.map(w=>t.jsx("option",{value:w.id,children:w.name},w.id))]}),t.jsxs("form",{className:"shot-series-row",onSubmit:w=>{w.preventDefault(),C()},children:[t.jsx("input",{"aria-label":a("Tên series mới"),placeholder:a('Tên series mới, ví dụ "Chuyện quán cà phê"'),maxLength:80,value:f,onChange:w=>p(w.target.value),disabled:o||b}),t.jsx("button",{disabled:o||b||!f.trim(),children:a("Tạo")})]}),t.jsx("small",{className:"shot-hint",children:a("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.")})]})}const qh=e=>`f/${Number(e.toFixed(1))}`,sj=e=>Ko.reduce((n,s,o)=>Math.abs(Math.log(s/e))<Math.abs(Math.log(Ko[n]/e))?o:n,0),aj=()=>globalThis.crypto?.randomUUID?.()??`fk-${Math.random().toString(36).slice(2)}`;function oj({shot:e,items:n,progress:s,presetFstop:o,onChange:i}){const r=e.focus,l=r?.keys||[],h=oc(r?.fstop??o),u=n.filter(y=>y.kind!=="fx"&&y.kind!=="set"),m=y=>y?n.find(k=>k.id===y)?.name??"?":"",d=y=>i(Object.keys(y).length?y:void 0),f=y=>{const k={...r||{},...y};for(const C of Object.keys(k))k[C]===void 0&&delete k[C];d(k)},p=r?.subject?n.find(y=>y.id===r.subject):void 0,b=(()=>{if(!p)return"";const y=[p.position[0],p.position[1]+(p.kind==="person"?1.6*(p.scale?.[1]||1):.4),p.position[2]],k=Math.hypot(y[0]-e.position[0],y[1]-e.position[1],y[2]-e.position[2]),C=If(k,e.lens,h);return`${C.near.toFixed(1)}–${Number.isFinite(C.far)?`${C.far.toFixed(1)} m`:"∞"}`})(),g=()=>{const y=Math.min(1,Math.max(0,s)),k=l.find(S=>Math.abs(S.time-y)<1e-4),C={id:k?.id??aj(),time:k?.time??y,...r?.subject?{subject:r.subject}:r?.distance!==void 0?{distance:r.distance}:{},fstop:h};d({...r||{},keys:[...l.filter(S=>S!==k),C].sort((S,I)=>S.time-I.time)})},v=y=>{const k=l.filter(I=>I.id!==y),{keys:C,...S}=r||{};d(k.length?{...S,keys:k}:S)};return t.jsxs("div",{className:"shot-focus","data-testid":"shot-focus",children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lấy nét vào (shot này)")}),t.jsxs("select",{"aria-label":a("Lấy nét vào (shot này)"),value:r?.subject??"",onChange:y=>f({subject:y.target.value||void 0,distance:void 0}),children:[t.jsx("option",{value:"",children:a("Tự động (mục tiêu camera)")}),u.map(y=>t.jsx("option",{value:y.id,children:y.name},y.id))]})]}),t.jsxs("label",{className:"shot-joint",children:[a("Khẩu độ")," ",t.jsx("span",{children:qh(h)}),t.jsx("input",{"aria-label":a("Khẩu độ"),type:"range",min:0,max:Ko.length-1,step:1,value:sj(h),onChange:y=>f({fstop:Ko[+y.target.value]})})]}),t.jsx("small",{className:"shot-hint",children:b?a("Ống kính {0} mm · vùng nét {1}",[Math.round(e.lens),b]):a("Ống kính {0} mm",[Math.round(e.lens)])}),r?.fstop!==void 0&&t.jsx("button",{type:"button",onClick:()=>f({fstop:void 0}),children:a("Theo mức xoá phông")}),t.jsx("button",{type:"button",onClick:g,children:a("Thêm điểm lấy nét tại playhead")}),l.length>0&&t.jsxs("div",{className:"shot-focus-keys",role:"list","aria-label":a("Điểm lấy nét"),children:[t.jsx("small",{className:"shot-hint",children:a("Điểm lấy nét quyết định chỗ nét theo thời gian; nét được kéo mượt giữa các điểm.")}),l.map(y=>{const k=`${(y.time*e.duration).toFixed(2)}s`;return t.jsxs("div",{role:"listitem",className:"shot-focus-key",children:[t.jsxs("span",{children:[k," · ",y.subject?m(y.subject):y.distance!==void 0?`${y.distance.toFixed(1)} m`:a("Tự động")," · ",qh(oc(y.fstop??r?.fstop??o))]}),t.jsx("button",{type:"button","aria-label":a("Xoá điểm lấy nét {0}",[k]),title:a("Xoá điểm lấy nét {0}",[k]),onClick:()=>v(y.id),children:"×"})]},y.id)}),t.jsx("button",{type:"button",onClick:()=>{const{keys:y,...k}=r||{};d(k)},children:a("Xoá hết điểm lấy nét")})]})]})}const Uh=(e,n,s)=>Math.max(n,Math.min(s,e)),Jn=e=>Math.round(e*100)/100;function ij(e,n,s=45){const o=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2],l=Math.hypot(o,r),h=Uh(Math.hypot(o,i,r),1.6,60),u=l>.05?Math.atan2(o,r):.35,m=(d,f,p,b=.25)=>{const g=u+d*Math.PI/180,v=p*Math.PI/180,y=h*f,k=Math.cos(v)*y;return[Jn(e[0]+Math.sin(g)*k),Jn(Math.max(b,e[1]+Math.sin(v)*y)),Jn(e[2]+Math.cos(g)*k)]};return[{id:"wide",label:"Toàn cảnh",subtitle:"28mm · Thiết lập không gian",camera:m(-18,1.45,22),target:[...e],lens:28},{id:"hero_34",label:"Trung cảnh 3/4",subtitle:"45mm · Góc kể chuyện chuẩn",camera:m(36,1,14),target:[...e],lens:Uh(Math.round(s),35,55)},{id:"low_hero",label:"Góc thấp anh hùng",subtitle:"35mm · Tạo cảm giác uy lực",camera:m(-28,.82,-6,.3),target:[Jn(e[0]),Jn(e[1]+.15),Jn(e[2])],lens:35},{id:"closeup",label:"Cận cảnh",subtitle:"70mm · Nhấn biểu cảm & chi tiết",camera:m(12,.56,8),target:[Jn(e[0]),Jn(e[1]+.12),Jn(e[2])],lens:70},{id:"top_down",label:"Từ trên xuống",subtitle:"35mm · Toàn cục & địa hình",camera:m(0,1.38,68),target:[...e],lens:35},{id:"reverse",label:"Góc ngược vai",subtitle:"50mm · Đối thoại / kịch tính",camera:m(152,.92,12),target:[...e],lens:50}]}function rj({x:e,y:n,items:s,canPaste:o,hiddenCount:i,blenderKeys:r,renaming:l,onBlenderKeys:h,onAction:u,onRename:m,onClose:d}){const f=R.useRef(null),[p,b]=R.useState({left:e,top:n}),[g,v]=R.useState(s[0]?.name??""),y=w=>s.length>0&&s.every(w),k=s[0]?.shading,C=w=>r?w:void 0,S=s.length?[[{action:"shade-smooth",label:"Bề mặt mượt",check:"shading",checked:y(w=>w.shading==="smooth")},{action:"shade-auto",label:"Mượt tự động (30°)",check:"shading",checked:y(w=>w.shading==="auto")},{action:"shade-flat",label:"Bề mặt phẳng",check:"shading",checked:y(w=>w.shading==="flat")},...k||s.some(w=>w.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(w=>w.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:C("Shift+D"),check:"duplicate"},{action:"duplicate-linked",label:"Nhân bản liên kết",keys:C("Alt+D"),check:"duplicate"},...s.some(w=>w.link)?[{action:"unlink",label:"Bỏ liên kết",check:"unlink"}]:[]],[{action:"mirror-x",label:"Lật theo X",check:"mirror",checked:y(w=>(w.mirror?.[0]??1)<0)},{action:"mirror-y",label:"Lật theo Y",check:"mirror",checked:y(w=>(w.mirror?.[1]??1)<0)},{action:"mirror-z",label:"Lật theo Z",check:"mirror",checked:y(w=>(w.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:C("H"),check:"hide"},{action:"lock",label:y(w=>w.locked)?"Mở khoá":"Khoá",check:"lock"},{action:"delete",label:"Xoá",keys:C("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:C("A")},{action:"box-select",label:"Chọn theo vùng",keys:C("B")},{action:"unhide-all",label:"Hiện tất cả",keys:C("Alt+H")}]],I=w=>w.soon?"Sắp có":w.action==="paste"?o?null:"Chưa sao chép đối tượng nào":w.action==="unhide-all"?i?null:"Không có đối tượng nào đang ẩn":w.check?s.some(E=>!Ao(E,w.check))?null:Ao(s[0],w.check):null,j=s.length!==1?"Chọn một đối tượng để đổi tên":Ao(s[0],"rename");R.useLayoutEffect(()=>{const w=f.current;if(!w)return;const E=w.getBoundingClientRect();b({left:Math.max(4,Math.min(e,innerWidth-E.width-4)),top:Math.max(4,Math.min(n,innerHeight-E.height-4))})},[e,n,l]),R.useEffect(()=>{const w=f.current;if(!w)return;l?w.querySelector("input[type=text]")?.select():w.querySelector("[role=menuitem]:not([disabled])")?.focus();const E=N=>{w.contains(N.target)||d()};return document.addEventListener("mousedown",E,!0),()=>document.removeEventListener("mousedown",E,!0)},[l,d]);const M=w=>{if(w.key==="Escape"){w.preventDefault(),d();return}if(w.key!=="ArrowDown"&&w.key!=="ArrowUp")return;w.preventDefault();const E=[...f.current.querySelectorAll("[role=menuitem]:not([disabled]),[role=menuitemcheckbox]")],N=E.indexOf(document.activeElement);E[(N+(w.key==="ArrowDown"?1:-1)+E.length)%E.length]?.focus()},T=s.length>1?a("{0} đối tượng",[s.length]):s[0]?.name;return t.jsxs("div",{className:"shot-ctxmenu",role:"menu","aria-label":a("Menu đối tượng"),ref:f,style:p,onKeyDown:M,onContextMenu:w=>w.preventDefault(),children:[T&&t.jsx("div",{className:"shot-ctxmenu-title",children:T}),l?t.jsxs("form",{className:"shot-ctxmenu-rename",onSubmit:w=>{w.preventDefault(),g.trim()&&m(g.trim().slice(0,80))},children:[t.jsx("input",{type:"text","aria-label":a("Tên mới"),value:g,maxLength:80,onChange:w=>v(w.target.value)}),t.jsx("button",{type:"submit",children:a("Đổi tên")})]}):t.jsxs(t.Fragment,{children:[s.length>0&&t.jsxs("button",{type:"button",role:"menuitem",disabled:!!j,title:j?a(j):void 0,onClick:()=>u("rename"),children:[t.jsx("span",{children:a("Đổi tên…")}),r&&t.jsx("kbd",{children:"F2"})]}),S.map((w,E)=>t.jsx("div",{className:"shot-ctxmenu-group",role:"group",children:w.map((N,A)=>{const O=I(N);return t.jsxs("button",{type:"button",role:"menuitem",disabled:!!O,title:O?a(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?"✓ ":"",a(N.label),N.soon?t.jsxs("small",{children:[" · ",a("Sắp có")]}):null]}),N.keys&&t.jsx("kbd",{children:N.keys})]},N.action+A)})},E)),t.jsxs("button",{type:"button",className:"shot-ctxmenu-keys",role:"menuitemcheckbox","aria-checked":r,onClick:()=>h(!r),children:[t.jsxs("span",{children:[r?"☑":"☐"," ",a("Phím tắt kiểu Blender")]}),t.jsx("small",{children:"G R S · Shift+D · X · H · A · B"})]})]})]})}const lj=[{id:"above",label:"Thả từ trên cao"},{id:"here",label:"Từ vị trí hiện tại"}],cj=[{id:"bouncy",label:"Nảy nhiều"},{id:"normal",label:"Vừa"},{id:"heavy",label:"Nặng"}];function hj({count:e,start:n,left:s,busy:o,onRun:i,onClose:r}){const[l,h]=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":a("Rơi tự nhiên"),onSubmit:d=>{d.preventDefault(),!o&&s>=.25&&i(l)},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),r())},children:[t.jsx("div",{className:"shot-ctxmenu-title",children:a("Rơi tự nhiên · {0} đối tượng",[e])}),t.jsx("div",{className:"shot-seg shot-seg-2",role:"group","aria-label":a("Bắt đầu rơi"),children:lj.map(d=>t.jsx("button",{type:"button",className:l.mode===d.id?"active":"","aria-pressed":l.mode===d.id,onClick:()=>h({...l,mode:d.id}),children:a(d.label)},d.id))}),t.jsx("div",{className:"shot-seg",role:"group","aria-label":a("Độ nảy"),children:cj.map(d=>t.jsx("button",{type:"button",className:l.bounciness===d.id?"active":"","aria-pressed":l.bounciness===d.id,onClick:()=>h({...l,bounciness:d.id}),children:a(d.label)},d.id))}),t.jsxs("label",{className:"shot-drop-row",children:[a("Thời lượng")," ",t.jsxs("b",{children:[l.duration,a("s")]}),t.jsx("input",{type:"range",min:1,max:6,step:.5,value:l.duration,"aria-label":a("Thời lượng rơi"),onChange:d=>h({...l,duration:+d.target.value})})]}),t.jsx("small",{className:"shot-drop-hint",children:s<.25?a("Đầu phát đang ở cuối shot — kéo về trước rồi thử lại."):a("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:a("Huỷ")}),t.jsx("button",{type:"submit",className:"shot-primary",disabled:o||s<.25,children:o?a("Đang mô phỏng…"):a("Mô phỏng")})]})]})}ss.plateUrl=e=>vg({gcsUri:e.gcsUri,url:e.url});const Yi=[["person","Nhân vật"],["box","Hộp"],["sphere","Cầu"],["cylinder","Trụ"],["wall","Tường"],["platform","Bục"],["floor","Sàn"]],So=[["scene","Dựng cảnh",t.jsx(Ne.scene,{},"scene")],["objects","Đối tượng",t.jsx(Ne.objects,{},"objects")],["material","Vật liệu",t.jsx(Ne.material,{},"material")],["rigging","Rigging · gắn xương",t.jsx(O1,{},"rigging")],["modeling","Dựng model",t.jsx(zd,{},"modeling")],["camera","Camera & shot",t.jsx(Ne.camera,{},"camera")],["light","Ánh sáng cảnh",t.jsx(Ne.light,{},"light")],["shots","Danh sách shot",t.jsx(Ne.film,{},"shots")],["notes","Ghi chú 3D",t.jsx(Ne.note,{},"notes")],["series","Series",t.jsx(Ne.series,{},"series")],["fx","Hiệu ứng",t.jsx(Ne.fx,{},"fx")],["fxedit","Sửa hiệu ứng",t.jsx(Ne.pen,{},"fxedit")],["mixfx","Mix FX",t.jsx(Ne.mixfx,{},"mixfx")]],Qi={drawer:300,right:320,timeline:210},dj={person:t.jsx(Ne.person,{}),box:t.jsx(Ne.box,{}),sphere:t.jsx(Ne.sphere,{}),cylinder:t.jsx(Ne.cylinder,{}),wall:t.jsx(Ne.wall,{}),platform:t.jsx(Ne.platform,{}),floor:t.jsx(Ne.floor,{}),model:t.jsx(Ne.cube,{}),proxy:t.jsx(Ne.cube,{}),splat:t.jsx(Ne.image,{}),prop:t.jsx(Ne.key,{}),fx:t.jsx(Ne.fx,{})},Fo={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 es({label:e,value:n,onChange:s,min:o=-100,max:i=100,step:r=.1}){return ct(),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function Co({label:e,root:n,bend:s,upper:o,lower:i,onChange:r}){ct();const l=R.useRef(null),h=D0(n,s,o,i),u=o+i,m=f=>{const p=l.current.getBoundingClientRect(),b=((f.clientX-p.left)/p.width*2-1)*u,g=((f.clientY-p.top)/p.height*2-1)*u,v=O0(b,g,o,i);r(Math.round(v.root),Math.round(v.bend))},d=f=>{f.preventDefault(),m(f);const p=g=>m(g),b=()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)};window.addEventListener("mousemove",p),window.addEventListener("mouseup",b)};return t.jsxs("div",{children:[t.jsx("small",{children:a(e)}),t.jsx("div",{ref:l,className:"shot-ik-pad",onMouseDown:d,children:t.jsx("i",{style:{left:`${50+h.forward/u*50}%`,top:`${50+h.down/u*50}%`}})})]})}const Zi={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"},uj=(e,n)=>{if(e[n]!==void 0)return e[n];const s=n.endsWith("L")?"L":"R",o=n.slice(0,-1);return L0.includes(o)?Math.round(E0(e,s)[o]):0},mj=(e,n,s)=>bd(e,n,s);function pj(e,n){return Object.keys(Fo).every(s=>(e[s]||0)===(n[s]||0))}const Xh="clipoox.shot.objectClipboard",fj=e=>e.kind==="person"||e.kind==="model"&&e.skeleton==="native";function Hj({nodeId:e,headless:n=!1,background:s}){ct();const[o,i]=R.useState(null),[r,l]=R.useState(!1),h=R.useRef(!1),[u,m]=R.useState(!1),[d,f]=R.useState(null),[p,b]=R.useState(!1),g=R.useRef([]),[v,y]=R.useState(!1),[k,C]=R.useState(!1),[S,I]=R.useState(!1),[j,M]=R.useState(null),[T,w]=R.useState([]),[E,N]=R.useState(!1),[A,O]=R.useState(null),[H,D]=R.useState(!1),[$,W]=R.useState(!1),[z,Y]=R.useState(()=>{const c=_t()?.getNode(e)?.data.shotScene;if(c)return pc(fc(c));const x=Rf();return x.items=x.items.map((L,P)=>({...L,name:`${a(Yi.find(([B])=>B===L.kind)?.[1]||"Model")} ${P+1}`})),x}),[J,V]=R.useState(z.items[0]?.id||null),[K,G]=R.useState([]),[_,ee]=R.useState("translate"),[Q,ve]=R.useState(()=>{try{const c=localStorage.getItem("clipoox.shot.panel");return So.some(x=>x[0]===c)?c:null}catch{return null}}),[xe,q]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.railWide")==="1"}catch{return!1}}),[ue,pe]=R.useState(()=>{try{return{...Qi,...JSON.parse(localStorage.getItem("clipoox.shot.layout")||"{}")}}catch{return Qi}}),[U,le]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.tools")!=="0"}catch{return!0}}),[ce,Le]=R.useState(!1),[je,ie]=R.useState(Ff),[Me,Ee]=R.useState(!1),[Se,he]=R.useState("shot"),[be,Fe]=R.useState({done:0,total:64}),[Te,_e]=R.useState(0),[ze,Be]=R.useState(null),[Ze,F]=R.useState(Qr),[te,Z]=R.useState([]),[re,me]=R.useState(!1),[Pe,ye]=R.useState(""),[rt,It]=R.useState([]),[qt,Xe]=R.useState(null),[lt,jt]=R.useState(!1),[St,gt]=R.useState(1),[at,tn]=R.useState(!1),[Ie,ot]=R.useState(0),[nn,mt]=R.useState(null),[Rt,Yt]=R.useState({}),ln=R.useRef(null),Qt=R.useRef(null);R.useEffect(()=>{if(!Me){Qt.current?.dispose(),Qt.current=null;return}const c=Ce.current,x=ln.current;if(!c||!x)return;let L=!1;return Fe({done:0,total:64}),fn(async()=>{const{ShotPathTracer:P}=await import("./pathTracer-bqau16sX.js");return{ShotPathTracer:P}},__vite__mapDeps([19,1,6])).then(({ShotPathTracer:P})=>{if(L)return;Qt.current?.dispose();const B=new P(x);Qt.current=B,B.start(c.getPathTraceSource(),{view:Se,targetSamples:64,bounces:4,onProgress:(X,se)=>{L||Fe({done:X,total:se})},onError:X=>{L||(ye(`Path Trace: ${X}`),Ee(!1))}})}),()=>{L=!0,Qt.current?.dispose(),Qt.current=null}},[Me,Se,Te,at]);const xt=c=>{V(c),G([])},cn=J?[J,...K.filter(c=>c!==J)]:[],Ft=R.useRef(cn);Ft.current=cn;const Zt=c=>{V(c[0]??null),G(c.slice(1))},bn=(c,x=!1)=>{const L=Ft.current;if(!x||!c)return Zt(c?[c]:x?L:[]);Zt(L.includes(c)?L.filter(P=>P!==c):[c,...L])},Gn=R.useRef(bn);Gn.current=bn;const[ae,ke]=R.useState(null),[Oe,Re]=R.useState(!1),He=R.useCallback(()=>ke(null),[]),[Ve,Je]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.blenderKeys")!=="0"}catch{return!0}}),Ye=c=>{Je(c);try{localStorage.setItem("clipoox.shot.blenderKeys",c?"1":"0")}catch{}},[We,et]=R.useState({on:!1}),ht=R.useRef("keys"),[it,Ke]=R.useState(!1),[wt,$t]=R.useState(null),[Lt,hn]=R.useState(null),[qn,Un]=R.useState({mode:"all",slot:null}),Cn=R.useRef(null),bt=R.useRef(Ie);bt.current=Ie,R.useEffect(()=>{nn&&J!==nn&&mt(null)},[J,nn]);const $e=R.useRef(null),yt=R.useRef(null),yn=R.useRef(null),ks=R.useRef(null),Ce=R.useRef(null),dn=R.useRef(null),un=R.useRef(null),Fn=R.useRef(null),Ae=R.useRef(z),Dt=R.useRef([]),Kt=R.useRef([]),Et=dt(c=>c.saveError),Ht=dt(c=>c.saveState),mn=Ci(c=>c.close);Ae.current=z;const Nn=dt(c=>c.canvasId),Xn=ic(c=>c.conflict),ws=ic(c=>c.reloading);R.useEffect(()=>n||!Nn?void 0:Pf(Nn,e,c=>{const x=pc(fc(c));Dt.current=[],Kt.current=[],Ae.current=x,Y(x)}),[Nn,e,n]),$f(n?null:Nn,e,()=>dt.getState().saveState!=="saved");const we=c=>{const x=Ae.current;Dt.current.push(x),Dt.current.length>60&&Dt.current.shift(),Kt.current=[];const L={...i0(x,c(x)),revision:x.revision+1};Ae.current=L,Y(L)},Qa={getStage:()=>Ae.current,setStage:we,engine:()=>Ce.current},si=c=>{const{item:x,fingers:L}=r0(c,Ae.current.items.length),P=wt?Ae.current.items.find(X=>X.id===wt&&X.kind==="person"):void 0,B=P?{...x,id:P.id,name:P.name,position:P.position,rotation:P.rotation,...P.hidden?{hidden:!0}:{}}:x;we(X=>({...X,items:P?X.items.map(se=>se.id===P.id?B:se):[...X.items,B]})),xt(B.id),W(!1),$t(null),L&&B.rig&&Nc(Qa,B.id,B.rig)};R.useEffect(()=>{if(!at)return;const c=Ci.getState().fitFingers;if(!(!c||c.node!==e)){Ci.setState({fitFingers:null});for(const x of c.items){const L=Ae.current.items.find(P=>P.id===x);L?.rig&&Nc(Qa,x,L.rig)}}},[at,e]);const ai=c=>{A&&(D(!1),ot(A.time),c&&we(x=>$i(x,A.plan)),A.done(c),O(null))},tt=(c,x)=>{D(!1),we(L=>el(L,c,x))},el=(c,x,L)=>{{const P=c.shots.find(fe=>fe.id===c.activeShot),B=c.items.find(fe=>fe.id===x),X=B.kind==="fx"?B.fx?.attach:void 0;if(X&&!(X.hand&&X.tip)&&(L.position||L.rotation)){if(md(B,P)){const fe=Oo(c,x,bt.current,{position:L.position,yaw:L.rotation?.[1]});return L.scale?{...fe,items:fe.items.map(Ge=>Ge.id===x?{...Ge,scale:L.scale}:Ge)}:fe}return{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L.scale?{scale:L.scale}:{},...L.rotation?{rotation:[fe.rotation[0],L.rotation[1],fe.rotation[2]]}:{},fx:{...fe.fx,attach:{...X,...L.position?{offset:L.position}:{}}}}:fe)}}const se=P.objectKeys?.[x]||[],ge=!!L.pose&&se.some(fe=>fe.pose);if(se.length&&(L.position||L.rotation||L.scale||ge)){const fe={..._n(B,P,bt.current),...L},Ge=se,De=Ge.find(pt=>Math.abs(pt.time-bt.current)<1e-6),qe={...De,id:De?.id||vt(),time:bt.current,position:fe.position,rotation:fe.rotation,scale:fe.scale,...ge?{pose:L.pose}:{}};return{...c,shots:c.shots.map(pt=>pt.id===c.activeShot?{...pt,objectKeys:{...pt.objectKeys,[x]:[...Ge.filter(Mt=>Mt.id!==qe.id),qe].sort((Mt,An)=>Mt.time-An.time)}}:pt)}}return B.kind==="fx"&&B.fx&&L.position&&!L.fx&&(L={...L,fx:l0(B.fx,B.position,L.position)}),{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L}:fe)}}},_u=(c,x)=>{const L={...Kn[x]};if(!!!Ae.current.shots.find(X=>X.id===Ae.current.activeShot)?.objectKeys?.[c.id]?.length&&!c.hold&&Ce.current){if(Ii(L)==="sit"){const X=Ce.current.sitSnap(c);if(X)return tt(c.id,{pose:L,...X})}else if(Ii(c.pose)==="sit"&&Ii(L)==="stand")return tt(c.id,{pose:L,position:Ce.current.standUp(c).position})}tt(c.id,{pose:L})},tl=c=>{const x=c.filter(L=>L.fix&&!L.locked);x.length&&(D(!1),we(L=>({...L,items:L.items.map(P=>{const B=x.find(X=>X.itemId===P.id)?.fix;return B?{...P,position:B.position,...B.rotation?{rotation:B.rotation}:{}}:P})})))},nl=c=>{D(!1),we(x=>{const L=x.shots.find(De=>De.id===x.activeShot),P=x.items.find(De=>De.id===c),B=L.objectKeys?.[c]||[],X=bt.current,se=_n(P,L,X),ge=(De,qe)=>{const pt=_n(P,L,De),Mt=B.find(An=>Math.abs(An.time-De)<1e-6);return{...Mt,id:Mt?.id||vt(),time:De,position:pt.position,rotation:pt.rotation,scale:pt.scale,pose:structuredClone(qe)}};let fe=[...B];if(!B.some(De=>De.pose)&&X>1e-6){const De=ge(0,P.pose);fe=[...fe.filter(qe=>qe.id!==De.id),De]}const Ge=ge(X,se.pose);return fe=[...fe.filter(De=>De.id!==Ge.id),Ge].sort((De,qe)=>De.time-qe.time),{...x,shots:x.shots.map(De=>De.id===x.activeShot?{...De,objectKeys:{...De.objectKeys,[c]:fe}}:De)}})},zu=c=>{D(!1),we(x=>{const B=(x.shots.find(X=>X.id===x.activeShot).objectKeys?.[c]||[]).map(X=>Math.abs(X.time-bt.current)<1e-6&&X.pose?(({pose:se,poseEase:ge,...fe})=>fe)(X):X);return{...x,shots:x.shots.map(X=>X.id===x.activeShot?{...X,objectKeys:{...X.objectKeys,[c]:B}}:X)}})},Bu=(c,x)=>{D(!1),we(L=>{const X=(L.shots.find(se=>se.id===L.activeShot).objectKeys?.[c]||[]).map(se=>Math.abs(se.time-bt.current)<1e-6&&se.pose?x==="smooth"?(({poseEase:ge,...fe})=>fe)(se):{...se,poseEase:x}:se);return{...L,shots:L.shots.map(se=>se.id===L.activeShot?{...se,objectKeys:{...se.objectKeys,[c]:X}}:se)}})},sl=R.useRef(null),[os,al]=R.useState(null),[la,Ku]=R.useState(1),[ol,Hu]=R.useState(!0),[il,rl]=R.useState(!1),Wu=async c=>{if(c){ye(""),rl(!0);try{if(c.size>60*1024*1024)throw new Error(a("File mocap tối đa 60 MB."));al(await c0(c.name,await c.arrayBuffer()))}catch(x){al(null),ye(x.message)}finally{rl(!1)}}},ll=async c=>{if(Lt)return;D(!1),ye(""),hn({kind:c,pct:0});const x=(L,P)=>hn({kind:c,pct:Math.round(L/P*100)});try{const L=Ae.current;if(c==="follow"){const P=L.items.find(ge=>ge.id===J&&ge.kind==="person"),B=P??L.items.find(ge=>ge.kind==="person");if(!B)throw new Error(a("Cảnh chưa có người đứng thế để bám theo."));const{followPlate:X}=await fn(async()=>{const{followPlate:ge}=await import("./plateFollow-4iGUDTu1.js");return{followPlate:ge}},__vite__mapDeps([20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),se=await X(L,B.id,{newId:vt,progress:x});we(()=>se.stage),dt.getState().toast(a("{0} đã bám theo người trong video: {1}/{2} khung thấy người.",[B.name,se.found,se.frames]),"ok")}else{const{trackPlateCamera:P}=await fn(async()=>{const{trackPlateCamera:X}=await import("./plateCamera-D7iLiNBy.js");return{trackPlateCamera:X}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),B=await P(L,{newId:vt,progress:x});we(()=>B.stage),dt.getState().toast(B.mode==="travel"?a("Đã lấy camera từ video: camera đi {0} m, quay {1}°.",[B.travel,B.pan]):a("Đã lấy camera từ video: {0} key, quay {1}°.",[B.keys,B.pan]),"ok")}}catch(L){const P=L.message;ye(P==="no-person-in-plate"?a("Không thấy người trong video nền."):P==="camera-not-found"?a("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."):P)}finally{hn(null)}},Gu=async()=>{const{shotBlenderScript:c}=await fn(async()=>{const{shotBlenderScript:P}=await import("./plateCamera-D7iLiNBy.js");return{shotBlenderScript:P}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),x=new Blob([c(Ae.current)],{type:"text/x-python"}),L=document.createElement("a");L.href=URL.createObjectURL(x),L.download=`${(de.name||"shot").replace(/[^\w-]+/g,"_")}-camera.py`,L.click(),setTimeout(()=>URL.revokeObjectURL(L.href),4e3)},qu=c=>{if(!os)return;D(!1);const x=Ae.current,L=x.items.find(De=>De.id===c),P=x.shots.find(De=>De.id===x.activeShot),B=bt.current,X=gs(L,P,B),se=(1-B)*P.duration*la,ge=h0(os,15*la,0,Math.min(os.duration,se)).map(De=>({...De,time:De.time/la})),fe=.93*d0(L)*L.scale[1],Ge=u0(x,c,m0(ge,{position:X.position,yaw:X.rotation[1],hipHeight:fe},ol),B,vt);if(!Ge.keys){ye(a("Không còn đủ thời lượng shot sau playhead để đặt mocap."));return}we(()=>Ge.stage),dt.getState().toast(a("Đã áp mocap {0}: {1} key · {2}s",[os.name,Ge.keys,Ge.seconds]),"ok")},[oi,cl]=R.useState(!0),[ii,hl]=R.useState(!1),ri=async(c,x)=>{if(D(!1),x.mocap)try{await Dr(x.id)}catch(se){ye(a("Không tải được dữ liệu mocap: {0}",[se.message]));return}const L=Ae.current,P=L.shots.find(se=>se.id===L.activeShot),B=bt.current,X=p0(L,c,x,{start:B,newId:vt,colliders:Ce.current?.placementColliders(),camera:P.position,loop:oi,mirror:ii});if(!X.ok){ye(X.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."):X.error);return}if(!X.keys){ye(a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."));return}we(()=>X.stage),dt.getState().toast(a('Đã áp "{0}" · {1}s',[Ra(x),X.seconds])+(X.notes.length&&na()==="vi"?` · ${X.notes[0]}`:""),"ok")},dl=(c,x,L)=>{D(!1),we(P=>{const B=ge=>(({hold:fe,...Ge})=>Ge)(ge),X=P.items.find(ge=>ge.id===c);let se=P.items.map(ge=>ge.hold?.by===c&&ge.hold.hand===x?{...B(ge),position:[X.position[0]+(x==="R"?.4:-.4),0,X.position[2]]}:ge);if(L.startsWith("item:"))se=se.map(ge=>ge.id===L.slice(5)?{...ge,hold:{by:c,hand:x}}:ge);else if(L.startsWith("prop:")){const ge=L.slice(5);se=[...se,{...Mn("prop",se.length),name:La[ge].label,prop:{kind:ge},color:"#8a939b",hold:{by:c,hand:x}}]}return{...P,items:se}})},[Uu,ul]=R.useState(""),Xu=()=>{D(!1);let c=[];we(L=>{const P=f0(L);return c=P.outcomes,P.stage});const x=L=>c.filter(P=>P.result===L).length;ul(c.length?a("{0} đòn · {1} trúng · {2} bị đỡ · {3} trượt",[c.length,x("head")+x("body"),x("blocked"),x("miss")])+(x("miss")?" — "+c.filter(L=>L.result==="miss").map(L=>a("{0}s thiếu {1} m",[L.time_s,L.gap_m])).join(", "):""):a('Chưa có đòn nào: đặt key tư thế kiểu "Ra đòn nhanh" giữa hai người.'))},Vu=()=>{D(!1),we(g0),ul("")},ml=c=>{const x=Ae.current.items.find(L=>L.id===c);!x||x.locked||re||(D(!1),we(L=>({...L,items:L.items.filter(P=>P.id!==c),shots:L.shots.map(P=>({...P,objectKeys:Object.fromEntries(Object.entries(P.objectKeys||{}).filter(([B])=>B!==c)),...P.fxTiming?{fxTiming:Object.fromEntries(Object.entries(P.fxTiming).filter(([B])=>B!==c))}:{}}))})),j?.row===c&&M(null),w(L=>L.filter(P=>P.row!==c)),xt(L=>L===c?null:L))},pl=R.useRef(""),Za=()=>{let c=pl.current;try{c=localStorage.getItem(Xh)||c}catch{}return c?x0(c):null},fl=()=>{const c=Ft.current;if(!c.length)return;const x=$0(Ae.current,c);pl.current=x,ht.current="objects";try{localStorage.setItem(Xh,x)}catch{}},gl=()=>{const c=Za();if(!c||re)return;D(!1);let x=[];we(L=>{const P=F0(L,c,vt);return x=P.ids,{...P.stage,items:P.stage.items.map(B=>x.includes(B.id)?P0(B):B)}}),Zt(x)},Ja=c=>{const x=Ft.current;if(!x.length||re)return;D(!1);let L=[];we(P=>{const B=R0(P,x,{linked:c,newId:vt});return L=B.ids,B.stage}),L.length&&Zt(L)},li=()=>{const c=Ft.current.filter(x=>!Ae.current.items.find(L=>L.id===x)?.locked);!c.length||re||(D(!1),we(x=>I0(x,c)),j&&c.includes(j.row)&&M(null),w(x=>x.filter(L=>!c.includes(L.row))),Zt(Ft.current.filter(x=>!c.includes(x))))},ci=(c,x,L)=>{c.length&&(D(!1),we(P=>({...P,items:P.items.map(B=>c.includes(B.id)?{...B,[x]:L}:B)})))},xl=()=>{const c=Ft.current;c.length&&(ci(c,"hidden",!0),Zt([]))},bl=()=>ci(Ae.current.items.filter(c=>c.hidden).map(c=>c.id),"hidden",!1),yl=()=>Zt(Ae.current.items.filter(c=>!c.hidden&&!c.locked).map(c=>c.id)),hi=c=>{const x=Ce.current,L=Ft.current.filter(P=>!Ao(Ae.current.items.find(B=>B.id===P),"origin"));!x||!L.length||(D(!1),we(P=>L.reduce((B,X)=>{if(c==="reset")return mc(B,X,null,!0);const se=x.builtBounds(X),ge=B.items.find(De=>De.id===X);if(!se||!ge)return B;const fe=ge.origin||[0,0,0],Ge=[(se.min[0]+se.max[0])/2,c==="bottom"?se.min[1]:(se.min[1]+se.max[1])/2,(se.min[2]+se.max[2])/2];return mc(B,X,Ge.map((De,qe)=>De-fe[qe]))},P)))},vl=()=>{const c=Ft.current;if(c.length===1)return ui(c[0]);if(!c.length)return;const x=bt.current;D(!1),we(L=>{const P=L.shots.find(X=>X.id===L.activeShot),B={...P.objectKeys};for(const X of c){const se=L.items.find(qe=>qe.id===X);if(!se||se.locked||se.hold||se.kind==="fx"&&se.fx?.attach)continue;const ge=_n(se,P,x),fe=B[X]||[],Ge=fe.find(qe=>Math.abs(qe.time-x)<1e-6),De={...Ge,id:Ge?.id||vt(),time:x,position:ge.position,rotation:ge.rotation,scale:ge.scale};B[X]=[...fe.filter(qe=>qe.id!==De.id),De].sort((qe,pt)=>qe.time-pt.time)}return{...L,shots:L.shots.map(X=>X.id===L.activeShot?{...X,objectKeys:B}:X)}})},di=(c,x,L)=>{re||A||(c&&!Ft.current.includes(c)&&bn(c),ke({x,y:L,scene:!c}))},jl=R.useRef(di);jl.current=di;const Yu=()=>{const c=$e.current?.getBoundingClientRect();ke({x:c?c.left+c.width/2-110:200,y:c?c.top+c.height/3:200,renaming:!0})},Qu=c=>{const x=Ft.current;if(c==="rename"){ke(L=>L&&{...L,renaming:!0});return}switch(ke(null),c){case"shade-smooth":case"shade-auto":case"shade-flat":case"shade-reset":{const L=c==="shade-reset"?null:c.slice(6);D(!1),we(P=>v0(P,x,L));return}case"origin-center":return hi("center");case"origin-bottom":return hi("bottom");case"origin-reset":return hi("reset");case"copy":return fl();case"paste":return gl();case"duplicate":return Ja(!1);case"duplicate-linked":return Ja(!0);case"unlink":D(!1),we(L=>y0(L,x));return;case"mirror-x":case"mirror-y":case"mirror-z":D(!1),we(L=>b0(L,x,c.slice(7)));return;case"key":return vl();case"physics-drop":D(!1),Re(!0);return;case"hide":return xl();case"lock":return ci(x,"locked",!x.every(L=>Ae.current.items.find(P=>P.id===L)?.locked));case"delete":return li();case"rig":{const L=x.find(P=>Ae.current.items.find(B=>B.id===P)?.kind==="model");L&&(xt(L),Vn("rigging"));return}case"select-all":return yl();case"unhide-all":return bl();case"box-select":return et({on:!0})}},Zu=async c=>{const x=Ae.current,L=x.shots.find(qe=>qe.id===x.activeShot),P=bt.current,B=Ft.current,X=await fn(()=>import("./sceneTrack-Bbov7zET.js").then(qe=>qe.X),__vite__mapDeps([10,1])),se=B.map(qe=>x.items.find(pt=>pt.id===qe)).filter(qe=>!!qe&&!X.dropUnavailable(qe)&&!(qe.kind==="prop"&&qe.prop?.kind==="ball"&&L.ball?.[qe.id]?.length)).slice(0,X.MAX_PHYSICS_BODIES);if(!se.length){Re(!1),ye(a("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 ge=P,fe=Math.min(c.duration,(1-ge)*L.duration),Ge=Ce.current,De=se.map(qe=>qe.id);me(!0),ye("");try{const qe=Ge?.physicsShapes(De)??{},pt=(Ge?.placementColliders()??[]).filter(Ot=>!De.includes(Ot.itemId)),Mt=Object.fromEntries(se.map(Ot=>[Ot.id,(L.objectKeys?.[Ot.id]||[]).filter(sn=>sn.time<ge-1e-6).sort((sn,Cs)=>sn.time-Cs.time).pop()])),An=se.map(Ot=>{const sn=_n(Ot,L,ge);return{id:Ot.id,position:sn.position,rotation:sn.rotation,shape:X.shapeKind(Ot),...qe[Ot.id]??X.fallbackShape(Ot)}}),Ut=await X.bakeDrop({bodies:An,statics:pt,mode:c.mode,bounciness:c.bounciness,duration:fe,start:ge*L.duration,shotDuration:L.duration,seed:De.join(","),before:Mt,seam:L.lockUntil?L.lockUntil/L.duration:null}),vn=Object.fromEntries(se.map(Ot=>[Ot.id,_n(Ot,L,ge).scale]));we(Ot=>X.applyDropKeys(Ot,L.id,Ut.tracks,{scale:vn,newId:vt,lifted:c.mode==="above"})),Re(!1)}catch(qe){ye(a("Không mô phỏng được: {0}",[qe.message]))}finally{me(!1)}},Ju=c=>{const x=c.code;return c.shiftKey&&!c.altKey&&x==="KeyD"?(Ja(!1),!0):c.altKey&&!c.shiftKey&&x==="KeyD"?(Ja(!0),!0):c.altKey&&!c.shiftKey&&x==="KeyH"?(bl(),!0):c.altKey&&!c.shiftKey&&x==="KeyA"?(Zt([]),!0):c.altKey||c.shiftKey?!1:x==="KeyG"||x==="KeyR"||x==="KeyS"&&!r?(ee(x==="KeyG"?"translate":x==="KeyR"?"rotate":"scale"),!0):x==="KeyX"?(Q==="rigging"&&Cn.current?.del()||li(),!0):x==="KeyH"?(xl(),!0):x==="KeyA"?(yl(),!0):x==="KeyB"?(et({on:!0}),!0):x==="F2"&&Ft.current.length===1?(Yu(),!0):!1},eo=(c=!1)=>{const x=c?Kt.current:Dt.current,L=c?Dt.current:Kt.current,P=x.pop();P&&(L.push(Ae.current),Ae.current=P,Y(P))};R.useEffect(()=>{ju()},[]),R.useEffect(()=>{Ce.current?.setPlatePlaying(H)},[H]),R.useEffect(()=>{fn(()=>import("./videoExport-Cg4B2Nyh.js"),__vite__mapDeps([24,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,25,26,27])).catch(()=>{})},[]),R.useEffect(()=>{try{Ce.current=new ss($e.current,ks.current,(c,x)=>Gn.current(c,x),(c,x)=>tt(c,x),xg,ye,c=>bg(c).then(x=>x.recipe)),Ce.current.onContext=(c,x,L)=>jl.current(c,x,L),Ce.current.commitMany=c=>{D(!1),we(x=>c.reduce((L,P)=>el(L,P.id,P.patch),x))},Ce.current.setCameraEditor({select:c=>{l(c&&!h.current),c&&(xt(null),i(null),ee(x=>x==="scale"?"translate":x))},commit:c=>kt(c)}),Ce.current.sync(Ae.current,J),tn(!0)}catch(c){ye(`Không khởi tạo được 3D: ${c.message}`)}return()=>Ce.current?.dispose()},[]),R.useEffect(()=>{Ce.current?.sync(A?.stage||z,A?null:J,A?[]:K)},[z,J,K,A]),R.useEffect(()=>{const c={getStage:()=>Ae.current,setStage:P=>{D(!1),we(P)},engine:()=>Ce.current,timelineClip:P=>dt.getState().clips.find(B=>B.id===P),undo:(P,B)=>{let X=0;for(let se=0;se<B;se++){const ge=Ae.current;if(eo(P),Ae.current===ge)break;X++}return X},...n?{}:{exportVideo:async P=>{const B=Ce.current;if(!B)throw new Error("3D chưa sẵn sàng");B.sync(Ae.current,null),me(!0),ye("");try{const{blob:X,cleanup:se}=await B.exportVideo({...P,signal:new AbortController().signal,progress:()=>{}});try{return dn.current=null,un.current=null,Fn.current=null,await fi(X,P,"canvas"),{nodeId:dn.current||void 0,url:un.current||void 0,gcsUri:Fn.current||void 0}}finally{await se()}}finally{me(!1)}},exportVfx:async P=>{me(!0),ye("");try{return await pi(P)}finally{me(!1)}},exportFrame:P=>is(!0,Ae.current.shots.find(B=>B.id===Ae.current.activeShot),0,!0,P)}};if(s){vc().then(P=>rc(!!P?.allowed)).catch(()=>{}),s({ready:()=>!!Ce.current,run:(P,B)=>Df(P,B,c),exportVfx:(P,B,X)=>pi(P,B,X)});return}if(_0(c,async()=>{const P=Ce.current;if(!P)throw new Error("3D chưa sẵn sàng");const B=Ae.current,X=B.shots.find(se=>se.id===B.activeShot);P.sync(B,null),me(!0),ye("");try{const se={start:0,end:X.duration,fps:gn(X),height:720},{blob:ge,cleanup:fe}=await P.exportVideo({...se,signal:new AbortController().signal,progress:()=>{}});try{return dn.current=null,un.current=null,Fn.current=null,await fi(ge,se,"canvas"),{nodeId:dn.current||void 0,url:un.current||void 0,gcsUri:Fn.current||void 0}}finally{await fe()}}finally{me(!1)}}),n)return()=>lc(c);n||vc().then(P=>rc(!!P?.allowed)).catch(()=>{});const x=Of(()=>Ae.current.shots.find(P=>P.id===Ae.current.activeShot)?.name||"3D Shot"),L=Q1(c,()=>Ae.current.shots.find(P=>P.id===Ae.current.activeShot)?.name||"3D Shot",P=>{const B=Ae.current.shots.find(X=>X.id===Ae.current.activeShot)?.duration||1;D(!1),ot(Math.max(0,Math.min(1,P/B))),setTimeout(()=>D(!0),50)},()=>{const P=dt.getState().canvasId;return P?`shot:${P}:${e}`:null});return()=>{x(),L(),lc(c)}},[]),R.useEffect(()=>{_t()?.updateNodeData(e,{shotScene:z})},[z,e]),R.useEffect(()=>{h.current=S,S&&l(!1)},[S]),R.useEffect(()=>Ce.current?.setCameraHidden(k),[k,at]),R.useEffect(()=>Ce.current?.mode(_,ce),[_,ce,r]),R.useEffect(()=>{J&&l(!1)},[J]),R.useEffect(()=>{Ce.current?.setCameraSelected(r&&!J&&!A)},[r,J,A,at]),R.useEffect(()=>{Ce.current&&(Ce.current.cameraTip=a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"))},[at,na()]),R.useEffect(()=>Ce.current?.setQuality(je),[je,at]),R.useEffect(()=>{if(!at||Q!=="shots"||re||A)return;let c=!0,x,L=0;const P=()=>{const B=Ce.current;!B||!c||B.shotThumbnails(Ae.current.shots).then(X=>{c&&Yt(X)}).catch(X=>{c&&++L<8?x=setTimeout(P,1500):console.warn("[shot] thumbnails failed:",X?.message)})};return x=setTimeout(P,900),()=>{c=!1,clearTimeout(x)}},[z.revision,at,Q,re,A]),R.useEffect(()=>Ce.current?.setPreviewProgress(Ie),[Ie]),R.useEffect(()=>{if(!at||A)return;const c=()=>{const P=Ce.current,B=Ae.current;if(!P)return;const X=B.shots.find(ge=>ge.id===B.activeShot),se=new Set(Object.entries(X?.objectKeys||{}).filter(([,ge])=>ge.length).map(([ge])=>ge));try{Z(j0(B,{colliders:P.placementColliders(),keyed:se}))}catch{Z([])}},x=setTimeout(c,350),L=setTimeout(c,2500);return()=>{clearTimeout(x),clearTimeout(L)}},[z.revision,at,A]),R.useEffect(()=>{const c=x=>{if(A){x.key==="Escape"&&(x.preventDefault(),ai(!1)),!x.target.closest(".shot-trial-controls")&&x.key!=="Tab"&&x.stopImmediatePropagation();return}if(x.target.closest(".shot-ctxmenu")||x.target.closest(".shot-playhead-handle")&&["ArrowLeft","ArrowRight","Home","End",",","."].includes(x.key))return;const L=x.target.closest(".shot-fmt");if(!(L&&(["Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(x.key)||x.key==="Escape"&&L.querySelector(".shot-fmt-pop"))||(x.stopImmediatePropagation(),x.target.closest('input,textarea,select,[contenteditable="true"],[role="textbox"]')||re))){if((x.metaKey||x.ctrlKey)&&x.key.toLowerCase()==="z")x.preventDefault(),eo(x.shiftKey);else if((x.key==="Delete"||x.key==="Backspace")&&(j||T.length)&&x.target.closest(".shot-timeline"))x.preventDefault(),Rl();else if((x.key==="Delete"||x.key==="Backspace")&&x.target.closest?.(".shot-shotlist li"))x.preventDefault(),Sl(x.target.closest(".shot-shotlist li").dataset.shot);else if((x.key==="Delete"||x.key==="Backspace")&&Q==="rigging"&&Cn.current?.del())x.preventDefault();else if((x.key==="Delete"||x.key==="Backspace")&&!E&&J&&!Ce.current?.transform.object?.userData.cameraKey)x.preventDefault(),li();else if((x.metaKey||x.ctrlKey)&&!x.altKey&&["c","v"].includes(x.key.toLowerCase())){const B=!!x.target.closest(".shot-timeline");x.key.toLowerCase()==="c"?B||Ms.length?(x.preventDefault(),Ll()):cn.length&&!E&&(x.preventDefault(),fl()):B||g.current.length&&(ht.current==="keys"||!Za())?g.current.length&&(x.preventDefault(),El()):!E&&Za()&&(x.preventDefault(),gl())}else if(!E&&!x.metaKey&&!x.ctrlKey&&!x.altKey&&!x.shiftKey&&x.code==="KeyF")x.preventDefault(),Ce.current?.view();else if(Ve&&!E&&!x.metaKey&&!x.ctrlKey&&Ju(x))x.preventDefault();else if(x.altKey&&(x.code==="Comma"||x.code==="Period"))x.preventDefault(),Il(x.code==="Period"?1:-1);else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&x.key.toLowerCase()==="k"){const B=j?.row??J??(r?"camera":null);x.shiftKey?(x.preventDefault(),Tl()):!j&&cn.length>1?(x.preventDefault(),vl()):B&&(x.preventDefault(),ui(B))}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&["l","i","o"].includes(x.key.toLowerCase())){x.preventDefault();const B=x.key.toLowerCase();B==="l"?m(X=>!X):dm(B==="i"?"in":"out")}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&(x.key===" "||x.key===","||x.key==="."||x.key==="Home"||x.key==="End"))if(x.preventDefault(),x.key===" ")D(B=>(!B&&Ie>=1&&ot(0),!B));else{D(!1);const B=z.shots.find(se=>se.id===z.activeShot),X=gn(B);ot(x.key==="Home"?0:x.key==="End"?1:Math.max(0,Math.min(1,(Math.round(Ie*B.duration*X)+(x.key==="."?1:-1))/X/B.duration)))}else if(r&&!E&&["w","e"].includes(x.key.toLowerCase())&&!x.metaKey&&!x.ctrlKey&&!x.altKey)x.preventDefault(),ee(x.key.toLowerCase()==="w"?"translate":"rotate");else if(x.key==="Escape"){if(nn){mt(null);return}if(We.on){et({on:!1});return}if(ae){ke(null);return}if(Q==="rigging"&&Cn.current?.esc())return;r&&!E?l(!1):E?N(!1):Q?Vn(null):mn()}}};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[mn,re,E,J,K,j,T,z,A,Q,r,Ie,d,Ve,We.on,ae,nn]);const de=(A?.stage||z).shots.find(c=>c.id===z.activeShot),kl=z.items.find(c=>c.id===J),ne=kl?_n(kl,de,Ie):void 0;R.useEffect(()=>{re&&D(!1)},[re]),R.useEffect(()=>{D(!1),ot(0),i(null),M(null),w([])},[z.activeShot]);const em=c=>{const x=ud(c.dataTransfer.getData(wr)),L=Ce.current;if(!x||!L||re)return;c.preventDefault();const P=L.pointerTarget(c.clientX,c.clientY),B=Ae.current,X=B.shots.find(ge=>ge.id===B.activeShot),se=vu(B,x,{selected:P.id??J,ground:P.ground,start:bt.current*X.duration,label:a(x.name),anchor:(ge,fe,Ge)=>L.partPointAt(X,Ge,ge,fe)});if("error"in se){ye(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[24]));return}ye(""),D(!1),we(()=>se.stage),xt(se.item.id),Vn("fx")},tm=c=>{const x=Ha(c.dataTransfer.getData(Ro)),L=Ce.current;if(!x||!L||re)return;c.preventDefault();const P=L.pointerSlot(c.clientX,c.clientY),B=P&&Ae.current.items.find(se=>se.id===P.id);if(!P||!B||!Ia(B)){ye(a("Thả vật liệu lên một đối tượng trong cảnh."));return}if(B.locked){ye(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[B.name]));return}const X=qn.mode==="part"&&L.materialSlots(B.id).length>1;ye(""),D(!1),we(se=>Gs(se,B.id,X?P.slot:"*",{preset:x.id})),xt(B.id),X&&Un({mode:"part",slot:P.slot})},nm=Object.fromEntries(z.items.flatMap(c=>{if(c.kind!=="fx"||!c.fx)return[];const x=Rn(c,de);return x.off?[]:[[c.id,{start:x.start,duration:x.duration}]]})),wl=_f(A?.stage||z),Ct=Pa(z.lighting),Ml=zf(z.shots),Pn=c=>we(x=>({...x,lighting:Pa({...Pa(x.lighting),...c})})),$s=z.notes||[],ca=z.styleRefs||[],sm=()=>{const c=Ce.current;if(c){if(it){c.setNotePlacer(null),Ke(!1);return}Ke(!0),c.setNotePlacer(x=>{Ke(!1),we(L=>({...L,notes:[...L.notes||[],{id:vt(),text:a("Ghi chú"),position:x}].slice(0,dc)}))})}},am=(c,x)=>we(L=>({...L,notes:(L.notes||[]).map(P=>P.id===c?{...P,text:x.slice(0,uc)}:P)})),om=c=>we(x=>({...x,notes:(x.notes||[]).filter(L=>L.id!==c)})),Sl=c=>we(x=>{if(x.shots.length<2)return x;const L=x.shots.findIndex(B=>B.id===c);if(L<0)return x;const P=x.shots.filter(B=>B.id!==c);return{...x,shots:P,activeShot:x.activeShot===c?P[Math.min(L,P.length-1)].id:x.activeShot}}),Cl=(c,x)=>we(L=>{const P=L.shots.findIndex(se=>se.id===c),B=P+x;if(P<0||B<0||B>=L.shots.length)return L;const X=[...L.shots];return[X[P],X[B]]=[X[B],X[P]],{...L,shots:X}});R.useEffect(()=>{if(!H)return;const c=p&&d?d.in:0,x=p&&d?d.out:1;let L=0,P=performance.now(),B=Ie;(B<c||B>=x)&&(B=c);const X=Bf(de),se=Math.max(.1,de.duration),ge=X?Ni(de,c*se):0,fe=X?Ni(de,x*se):0;let Ge=X?Ni(de,B*se):0;const De=qe=>{const pt=(qe-P)/1e3;if(P=qe,X){if(Ge+=pt,Ge>=fe)if(u)Ge=ge+(Ge-fe)%Math.max(1e-6,fe-ge);else{Ce.current?.setOutputClock(null),ot(x),D(!1);return}Ce.current?.setOutputClock(Ge),ot(k0(de,Ge).scene/se),L=requestAnimationFrame(De);return}if(B+=pt/se,B>=x)if(u)B=c+(B-x)%Math.max(1e-6,x-c);else{ot(x),D(!1);return}ot(B),L=requestAnimationFrame(De)};return L=requestAnimationFrame(De),()=>{cancelAnimationFrame(L),Ce.current?.setOutputClock(null)}},[H,de.duration,de.timing,z.activeShot,u,p,d]);const to=(_t()?.nodes()||[]).filter(c=>c.type==="image"&&c.id!==e&&c.data.url),kt=c=>{D(!1),we(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,...c}:L)}))},Nl=c=>kt(sr(c)),im=(c,x)=>{const L=(c==="camera"?de.cameraKeys:de.objectKeys?.[c])?.find(P=>P.id===x);L&&(D(!1),ot(L.time),M({row:c,id:x}),w([]),i(c==="camera"?x:null),xt(c==="camera"?null:c))},Al=c=>{D(!1),w(c),M(c.length===1?c[0]:null),i(c.length===1&&c[0].row==="camera"?c[0].id:null)},ui=c=>{if(c==="camera"){const x=de.motion==="path"?de.cameraKeys||[]:[],L=x.find(X=>Math.abs(X.time-Ie)<1e-6),P=Yh(de,Ie),B={id:L?.id||vt(),time:Ie,position:P.position,target:P.target,lens:P.lens,roll:P.roll};Nl([...x.filter(X=>X.id!==B.id),B]),i(B.id),M({row:c,id:B.id}),xt(null)}else{const x=z.items.find(se=>se.id===c);if(!x||x.locked)return;if(x.kind==="fx"&&x.fx?.attach){const se=x.fx.attach.keyed?(de.objectKeys?.[c]||[]).find(fe=>Math.abs(fe.time-Ie)<1e-6):void 0,ge=se?.id||vt();we(fe=>Oo(fe,c,Ie,{id:ge})),i(null),xt(c),M({row:c,id:ge});return}const L=_n(x,de,Ie),P=de.objectKeys?.[c]||[],X={id:P.find(se=>Math.abs(se.time-Ie)<1e-6)?.id||vt(),time:Ie,position:L.position,rotation:L.rotation,scale:L.scale};kt({objectKeys:{...de.objectKeys,[c]:[...P.filter(se=>se.id!==X.id),X].sort((se,ge)=>se.time-ge.time)}}),i(null),xt(c),M({row:c,id:X.id})}},rm=(c,x)=>we(L=>{const P=L.items.find(fe=>fe.id===c);if(!P?.fx||P.locked||(P.fx.attach?.to??"")===x)return L;const B=P.fx.attach,X=x?{to:x,...B?.part?{part:B.part}:{},...B?.follow?{follow:B.follow}:{}}:void 0,se=B?.keyed?L.shots.map(fe=>fe.objectKeys?.[c]?{...fe,objectKeys:Object.fromEntries(Object.entries(fe.objectKeys).filter(([Ge])=>Ge!==c))}:fe):L.shots,ge=x?L.items.find(fe=>fe.id===x):null;return{...L,shots:se,items:L.items.map(fe=>fe.id===c?{...fe,...!x&&B?{position:[...L.items.find(Ge=>Ge.id===B.to)?.position??fe.position]}:{},...ge?{position:[...ge.position]}:{},fx:{...P.fx,attach:X}}:fe)}}),lm=(c,x)=>{if(c==="camera"){x==="hidden"?C(L=>!L):I(L=>!L);return}D(!1),we(L=>({...L,items:L.items.map(P=>P.id===c?{...P,[x]:!P[x]}:P)})),(x==="hidden"||x==="locked")&&xt(L=>L===c&&!z.items.find(P=>P.id===c)?.[x]?null:L)},cm=(c,x,L)=>{D(!1),we(P=>Cg(P,c,x,Ie,L))},Ms=T.length?T:j?[j]:[],Tl=()=>{D(!1),we(c=>Ng(c,Ie))},Ll=()=>{g.current=Ag(Ae.current,Ms),y(g.current.length>0),ht.current="keys"},El=()=>{if(!g.current.length)return;D(!1);let c=[];we(x=>{const L=Tg(x,g.current,Ie);return c=L.pasted,L.stage}),c.length&&Al(c)},hm=c=>{Ms.length&&we(x=>Lg(x,Ms,c))},Il=c=>{if(!Ms.length)return;const x=c/(gn(de)*de.duration);wc(Ae.current,Ms,x).moved&&(D(!1),we(L=>wc(L,Ms,x).stage))},dm=c=>{const x=Ie;f(L=>c==="in"?{in:x,out:L&&L.out>x?L.out:1}:{in:L&&L.in<x?L.in:0,out:x}),b(!0)},um=(c,x,L)=>{if(!((c==="camera"?de.cameraKeys:de.objectKeys?.[c])||[]).some(B=>B.id!==x&&Math.abs(B.time-L)<1e-6)){if(c==="camera")Nl((de.cameraKeys||[]).map(B=>B.id===x?{...B,time:L}:B));else{if(z.items.find(B=>B.id===c)?.locked)return;kt({objectKeys:{...de.objectKeys,[c]:(de.objectKeys?.[c]||[]).map(B=>B.id===x?{...B,time:L}:B).sort((B,X)=>B.time-X.time)}})}ot(L)}},Rl=()=>{const c=[...T,...j&&!T.some(X=>X.row===j.row&&X.id===j.id)?[j]:[]];if(!c.length)return;const x=X=>new Set(c.filter(se=>se.row===X).map(se=>se.id)),L={...de.objectKeys};let P=!1;for(const X of new Set(c.map(se=>se.row)))if(X!=="camera"&&!z.items.find(se=>se.id===X)?.locked){const se=x(X);L[X]=(L[X]||[]).filter(ge=>!se.has(ge.id)),P=!0}const B=c.some(X=>X.row==="camera")?sr((de.cameraKeys||[]).filter(X=>!x("camera").has(X.id))):{};kt({...B,...P?{objectKeys:L}:{}}),i(null),M(null),w([])},mm=c=>{D(!1),kt(w0(de,c)),c!=="path"&&ot(c==="static"?0:1)},Fl=async c=>{try{const x=await yg("model",c);It(L=>c?[...L,...x.assets]:x.assets),Xe(x.nextCursor)}catch(x){ye(x.message)}},pm=async c=>{if(c){if(ye(""),!c.name.toLowerCase().endsWith(".glb")||c.size>50*1024*1024){ye("Chọn file GLB tối đa 50 MB.");return}jt(!0);try{const x=new DataView(await c.slice(0,12).arrayBuffer());if(x.byteLength<12||x.getUint32(0,!0)!==1179937895||x.getUint32(4,!0)!==2)throw new Error("File không phải GLB 2.0 hợp lệ");const L=await c.arrayBuffer(),P=new DataView(L);if(P.byteLength<20||P.getUint32(8,!0)!==L.byteLength||P.getUint32(16,!0)!==1313821514)throw new Error("Cấu trúc GLB không hợp lệ");const B=P.getUint32(12,!0);if(20+B>L.byteLength)throw new Error("File GLB bị thiếu dữ liệu");const X=JSON.parse(new TextDecoder().decode(new Uint8Array(L,20,B)));if([...X.buffers||[],...X.images||[]].some(fe=>fe.uri&&!fe.uri.startsWith("data:")))throw new Error("Hãy xuất GLB với texture và dữ liệu nhúng trong file.");const{gcsUri:se}=await Us(new File([c],c.name,{type:"model/gltf-binary"})),ge={...Mn("model",Ae.current.items.length),name:c.name,model:{gcsUri:se,name:c.name}};we(fe=>({...fe,items:[...fe.items,ge]})),xt(ge.id)}catch(x){ye(x.message)}finally{jt(!1)}}},Pl=(c,x)=>{const L={...Mn("splat",Ae.current.items.length),name:c,position:[0,0,0],color:"#9aa3a8",splat:x};we(P=>({...P,items:[...P.items,L]})),xt(L.id)},fm=async c=>{if(!c)return;ye("");const x=c.name.split(".").pop()?.toLowerCase()||"";if(!M0.includes(x)||c.size>S0){ye(a("Chọn file bản quét .spz, .ply, .splat, .ksplat hoặc .sog tối đa 300 MB."));return}jt(!0);try{const{gcsUri:L}=await Us(new File([c],c.name,{type:"application/x-gaussian-splat"}));Pl(c.name.replace(/\.[^.]+$/,""),{name:c.name,gcsUri:L,source:"scan",flip:!0})}catch(L){ye(L.message)}finally{jt(!1)}},mi=(_t()?.nodes()||[]).filter(c=>c.type==="world"&&typeof c.data.splatUrl=="string"),gm=c=>{const x=Array.from({length:c==="person"?St:1},(L,P)=>({...Mn(c,z.items.length+P),name:`${a(Yi.find(([B])=>B===c)?.[1]||"Model")} ${z.items.length+P+1}`}));we(L=>({...L,items:[...L.items,...x]})),xt(x[0].id)};async function pi(c,x,L){const P=Ce.current;if(!P)throw new Error("3D chưa sẵn sàng");const B=structuredClone(Ae.current);P.sync(B,null);const X=await B1(P,B,e,c,{signal:L,progress:x}),se=H1(X,B.plate?.timelineClipId);return dn.current=X.at(-1)?.nodeId||null,un.current=X.at(-1)?.url||null,se}async function fi(c,x,L){const P=structuredClone(Ae.current),B=P.shots.find(Mt=>Mt.id===P.activeShot),X=dt.getState().canvasId,se=new File([c],`${B.name}-camera.mp4`,{type:"video/mp4"}),{url:ge,gcsUri:fe}=await Us(se,void 0,"video");un.current=ge,Fn.current=fe||null;const Ge=_t()?.getNode(e);if(!Ge||dt.getState().canvasId!==X)throw new Error("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi.");const De=x.end-x.start,qe=`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.`,pt=_t()?.addNode("video",{url:ge,gcsUri:fe,label:`${B.name} · Camera ref`,duration:De,ratio:B.aspect,status:"succeeded",shotSourceId:e,shotId:B.id,shotRevision:P.revision,cameraVideo:{...x},prompt:qe},{x:Ge.position.x+380,y:Ge.position.y},{sourceIds:[e]});if(dn.current=pt||null,L==="timeline"){if(!pt)throw new Error("Không tạo được video trên Canvas");const Mt=dt.getState(),An=Ge.data?.timelineClipId,Ut=Mt.clips.find(sn=>sn.id===An);if(!Ut)throw new Error("Clip 3D gốc không còn trên Timeline. Video đã lưu vào Canvas.");if(Mt.timelineTracks[Ut.track]?.locked)throw new Error("Track đã khóa. Video đã lưu vào Canvas.");const vn=Ut.kind==="model"?Ut:Ut.from3D?.clip,Ot={id:crypto.randomUUID(),nodeId:pt,track:Ut.track,start:Ut.start,duration:Math.max(1/30,Math.min(Ut.duration,Math.floor(De*30)/30)),sourceDuration:De,inPoint:0,volume:1,url:ge,gcsUri:fe,kind:"video",label:`${Ut.label.replace(/ · 3D$/,"")} · 3D`,...Ut.zIndex!==void 0?{zIndex:Ut.zIndex}:{},...vn?{from3D:{shotNodeId:e,clip:vn}}:{}};Mt.setClips(sn=>sn.map(Cs=>Cs.id===Ut.id?Ot:Cs)),Mt.setTimelineMedia(sn=>sn.some(Cs=>Cs.source==="canvas"&&Cs.id===pt)?sn:[...sn,{id:pt,source:"canvas",kind:"video",url:ge,gcsUri:fe,label:Ot.label,duration:De}]),_t()?.updateNodeData(e,{timelineClipId:Ot.id}),mn(),Mt.setView("timeline"),Mt.toast(a("Đã đưa video 3D về Timeline, thay đúng chỗ clip model"),"ok");return}dt.getState().toast(a("Đã lưu video camera vào Canvas và tài sản của bạn"),"ok")}async function is(c,x=Ae.current.shots.find(se=>se.id===Ae.current.activeShot),L=0,P=!0,B=0,X=""){if(!Ce.current)return;P&&me(!0),ye("");const se=dt.getState().canvasId,ge=structuredClone(Ae.current);ge.activeShot=x.id;const fe=x,Ge=Ae.current.activeShot;try{Ge!==fe.id&&Ce.current.sync(ge,J);const De=await Ce.current.exportPng(B),qe=`${fe.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}${X.replace(/\s+/g,"-")}.png`;if(c){const{url:pt,gcsUri:Mt}=await Us(new File([De],qe,{type:"image/png"})),An=_t()?.getNode(e);if(dt.getState().canvasId!==se)throw new Error("Canvas đã thay đổi; ảnh chưa được chèn");if(!An)throw new Error("Cảnh gốc không còn tồn tại");const Ut=_t()?.addNode("image",{url:pt,gcsUri:Mt,label:`${fe.name}${X}`,ratio:fe.aspect,prompt:Ti(ge),shotSourceId:e,shotId:fe.id,shotRevision:ge.revision,sceneVersion:ge.version,characterReferences:ge.items.filter(vn=>vn.kind==="person"&&vn.reference).map(vn=>vn.reference),cameraMotion:{pathSmooth:fe.pathSmooth,type:fe.motion,duration:fe.duration,endPosition:fe.endPosition,endTarget:fe.endTarget,endLens:fe.endLens},cameraFrame:B},{x:An.position.x+380,y:An.position.y+L*280},{sourceIds:[e,...ge.items.flatMap(vn=>vn.reference?.nodeId?[vn.reference.nodeId]:[])]});return dt.getState().toast(a("Đã đưa ảnh shot vào Canvas"),"ok"),Ut}else{const pt=URL.createObjectURL(De),Mt=document.createElement("a");Mt.href=pt,Mt.download=qe,Mt.click(),setTimeout(()=>URL.revokeObjectURL(pt),1e3)}}catch(De){if(ye(De.message),!P)throw De}finally{Ge!==fe.id&&Ce.current.sync(Ae.current,J),P&&me(!1)}}async function xm(){if(de.motion!=="static"){me(!0),ye("");try{const c=await is(!0,de,0,!1,0," · Start"),x=await is(!0,de,1,!1,1," · End");c&&x&&(_t()?.updateNodeData(c,{pairedShotNodeId:x}),_t()?.updateNodeData(x,{pairedShotNodeId:c})),dt.getState().toast(a("Đã tạo cặp Start/End cho Seedance"),"ok")}catch(c){ye(c.message)}finally{Ce.current?.sync(Ae.current,J),me(!1)}}}async function bm(){let c=!1;me(!0),ye("");try{Fa.includes(de.aspect)||dt.getState().toast(Ou(de).aspect.at(-1)||"","error");const x=await is(!0,de,0,!1,Ie," · Previs");if(!x)return;const L=[x,...Ae.current.items.flatMap(B=>B.reference?.nodeId?[B.reference.nodeId]:[]),...(Ae.current.styleRefs||[]).map(B=>B.nodeId)],P=_t()?.getNode(e);c=!0,mn(),dt.getState().openComposer({mode:"image",generator:"openai:gpt-image",refs:Array.from(new Set(L)),prompt:C0(Ae.current),count:1,aspectRatio:Fa.includes(de.aspect)?de.aspect:ar(de.aspect,Fa),resolution:"2K",quality:"high",anchor:P?{x:P.position.x+760,y:P.position.y}:null}),dt.getState().toast(a("Khung previs đã sẵn sàng để tạo ảnh thật"),"ok")}catch(x){ye(x.message)}finally{c||Ce.current?.sync(Ae.current,J),me(!1)}}async function ym(){if(Ce.current){me(!0),ye("");try{const c=await Ce.current.exportPng(Ie,!0),x=URL.createObjectURL(c),L=document.createElement("a");L.href=x,L.download=`${de.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-ghi-chu.png`,L.click(),setTimeout(()=>URL.revokeObjectURL(x),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}async function vm(){me(!0),ye("");try{for(let c=0;c<Ae.current.shots.length;c++)await is(!0,Ae.current.shots[c],c,!1);dt.getState().toast(a("Đã xuất {0} shot vào Canvas",[Ae.current.shots.length]),"ok")}catch(c){ye(c.message)}finally{me(!1)}}async function jm(){if(Ce.current){me(!0);try{const c=Ae.current.shots.find(B=>B.id===Ae.current.activeShot),x=await Ce.current.exportDepth(Ie),L=URL.createObjectURL(x),P=document.createElement("a");P.href=L,P.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-depth.png`,P.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}async function km(){if(Ce.current){me(!0);try{const c=Ae.current.shots.find(B=>B.id===Ae.current.activeShot),x=await Ce.current.exportPoseMask(Ie),L=URL.createObjectURL(x),P=document.createElement("a");P.href=L,P.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-pose-mask.png`,P.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}const Ss=(c,x,L,P=-100)=>t.jsxs("div",{className:"shot-vector",children:[t.jsx("small",{children:a(c)}),x.map((B,X)=>t.jsx(es,{label:`${a(c)} ${["X","Y","Z"][X]}`,value:B,min:P,onChange:se=>{const ge=[...x];ge[X]=se,L(ge)}},X))]});R.useEffect(()=>{try{localStorage.setItem("clipoox.shot.layout",JSON.stringify(ue))}catch{}},[ue]);const Vn=c=>{ve(c);try{localStorage.setItem("clipoox.shot.panel",c||"")}catch{}},wm=c=>Vn(Q===c?null:c),$l=c=>{q(c);try{localStorage.setItem("clipoox.shot.railWide",c?"1":"0")}catch{}},[no,ha]=R.useState(null),Dl=c=>{const x=c.target.closest("button"),L=x?.querySelector(".lbl");if(!x||!L||getComputedStyle(L).display!=="none"){ha(null);return}const P=x.getBoundingClientRect(),B=c.currentTarget.getBoundingClientRect().right,X=x.getAttribute("aria-label")||"";ha(se=>se&&se.label===X&&se.top===P.top+P.height/2?se:{label:X,left:B+8,top:P.top+P.height/2})},Mm=()=>{pe(Qi),$l(!1);try{localStorage.removeItem("clipoox.shot.layout")}catch{}},gi=(c,x)=>{if(c.button!==0)return;c.preventDefault();const L=c.currentTarget,P={x:c.clientX,y:c.clientY,value:ue[x]},B=c.pointerId;L.setPointerCapture(B),L.classList.add("dragging");const X=fe=>x==="timeline"?Math.max(120,Math.min(window.innerHeight*.55,fe)):x==="drawer"?Math.max(240,Math.min(window.innerWidth*.2,fe)):Math.max(260,Math.min(window.innerWidth*.22,fe)),se=fe=>{const Ge=x==="timeline"?P.y-fe.clientY:x==="drawer"?fe.clientX-P.x:P.x-fe.clientX;pe(De=>({...De,[x]:Math.round(X(P.value+Ge))}))},ge=()=>{L.removeEventListener("pointermove",se),L.removeEventListener("pointerup",ge),L.removeEventListener("pointercancel",ge),L.classList.remove("dragging")};L.addEventListener("pointermove",se),L.addEventListener("pointerup",ge),L.addEventListener("pointercancel",ge)};return t.jsxs("div",{className:"shot-workspace",role:"dialog","aria-modal":"true","aria-label":a("3D Shot Composer"),children:[Oe&&t.jsx(hj,{count:cn.length,start:Ie*de.duration,left:(1-Ie)*de.duration,busy:re,onRun:c=>{Zu(c)},onClose:()=>Re(!1)}),ae&&t.jsx(rj,{x:ae.x,y:ae.y,renaming:!!ae.renaming,items:ae.scene?[]:cn.map(c=>z.items.find(x=>x.id===c)).filter(Boolean),canPaste:!!Za(),hiddenCount:z.items.filter(c=>c.hidden).length,blenderKeys:Ve,onBlenderKeys:Ye,onAction:Qu,onRename:c=>{const x=cn[0];ke(null),x&&tt(x,{name:c})},onClose:He}),We.on&&(()=>{const c=$e.current?.getBoundingClientRect(),x=We.from,L=We.to;if(!c)return null;const P=B=>{if(!x)return;const X=L&&Math.hypot(L[0]-x[0],L[1]-x[1])>3?Ce.current?.objectsInRect(x[0],x[1],B.clientX,B.clientY)??[]:[];Zt(B.shiftKey?[...Ft.current,...X.filter(se=>!Ft.current.includes(se))]:X),et({on:!1})};return t.jsxs("div",{className:"shot-boxsel",role:"presentation","aria-label":a("Kéo để chọn theo vùng"),style:{left:c.left,top:c.top,width:c.width,height:c.height},onMouseDown:B=>{B.button===0&&et({on:!0,from:[B.clientX,B.clientY],to:[B.clientX,B.clientY]})},onMouseMove:B=>{x&&et({on:!0,from:x,to:[B.clientX,B.clientY]})},onMouseUp:P,onContextMenu:B=>{B.preventDefault(),et({on:!1})},children:[t.jsx("span",{className:"shot-boxsel-hint",children:a("Kéo để chọn theo vùng · Shift: chọn thêm · Esc: thôi")}),x&&L&&t.jsx("i",{style:{left:Math.min(x[0],L[0])-c.left,top:Math.min(x[1],L[1])-c.top,width:Math.abs(L[0]-x[0]),height:Math.abs(L[1]-x[1])}})]})})(),E&&t.jsx(_1,{shot:de,engine:Ce.current||null,onClose:()=>N(!1),onBusy:me,onReady:fi,timelineTarget:(()=>{const c=_t()?.getNode(e)?.data?.timelineClipId;return typeof c=="string"?dt.getState().clips.find(x=>x.id===c)?.label:void 0})(),vfx:z.plate?{layers:new Set(z.items.filter(c=>c.kind==="fx"&&!c.hidden).map(pd)).size,target:dt.getState().clips.find(c=>c.id===z.plate?.timelineClipId)?.label,run:async(c,x,L)=>{const P=await pi(c,x,L),B=dt.getState();if(!P.placed){B.toast(a("Đã 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 đó.",[P.passes.length]),"info");return}mn(),B.setView("timeline"),B.toast(P.pendingMatte?a("Đã đặt {0} lớp hiệu ứng lên Timeline. Timeline đang tách người để đặt lớp sau người ra sau.",[P.passes.length]):a("Đã đặt {0} lớp hiệu ứng lên Timeline.",[P.passes.length]),"ok")}}:void 0}),t.jsxs("header",{children:[t.jsxs("button",{disabled:re,onClick:mn,children:[t.jsx(Ne.back,{}),a("← Canvas").replace("← ","")]}),t.jsxs("strong",{children:[a("3D Shot Composer"),t.jsx("em",{children:a("BETA")})]}),t.jsx("span",{className:"shot-save","data-save-state":Ht,title:Ht==="error"&&Et?Et:void 0,children:Ht==="saved"?a("Đã lưu"):Ht==="error"?t.jsxs(t.Fragment,{children:[a("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:a("Thử lại")})]}):a("Đang lưu…")}),t.jsx("button",{"aria-label":a("Hoàn tác"),title:a("Hoàn tác (⌘Z)"),disabled:!Dt.current.length||re,onClick:()=>eo(),children:t.jsx(Ne.undo,{})}),t.jsx("button",{"aria-label":a("Làm lại"),title:a("Làm lại (⇧⌘Z)"),disabled:!Kt.current.length||re,onClick:()=>eo(!0),children:t.jsx(Ne.redo,{})}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),is(!1,de,0,!0,Ie)},title:a("Tải PNG"),children:[t.jsx(Ne.image,{}),t.jsx("span",{className:"lbl",children:a("Tải PNG")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at,onClick:jm,title:a("Depth map"),children:[t.jsx(Ne.depth,{}),t.jsx("span",{className:"lbl",children:a("Depth map")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at,onClick:km,title:a("Pose mask"),children:[t.jsx(Ne.mask,{}),t.jsx("span",{className:"lbl",children:a("Pose mask")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at||z.shots.length<2,onClick:vm,title:a("Xuất tất cả shot"),children:[t.jsx(Ne.layers,{}),t.jsx("span",{className:"lbl",children:a("Xuất tất cả shot")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at||de.motion==="static",onClick:xm,title:a("Start + End"),children:[t.jsx(Ne.frames,{}),t.jsx("span",{className:"lbl",children:a("Start + End")})]}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),bm()},title:a("Biến khung xám thành ảnh thật (giữ nguyên bố cục)"),children:[t.jsx(Ne.image,{}),t.jsx("span",{className:"lbl",children:a("Ảnh thật")})]}),t.jsxs("button",{className:"shot-primary",disabled:re||!at,onClick:()=>{D(!1),N(!0)},title:a("Xuất MP4"),children:[t.jsx(Ne.video,{}),a("Xuất MP4")]}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),is(!0,de,0,!0,Ie)},children:[t.jsx(Ne.plus,{}),re?a("Đang xuất…"):a("Đưa vào Canvas")]})]}),Xn&&Xn.canvasId===Nn&&Xn.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(Xn.by)?a("Cảnh 3D này có phiên bản mới từ trợ lý AI của bạn."):a("Cảnh 3D này có phiên bản mới.")})," ",a("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:ws,onClick:()=>void Hf(Xn.canvasId,Xn.nodeId).then(()=>dt.getState().toast(a("Đã tải phiên bản mới nhất của cảnh 3D."),"ok")),children:a("Tải phiên bản mới")}),t.jsx("button",{disabled:ws,onClick:Wf,children:a("Giữ bản của tôi")})]}),Pe&&t.jsx("div",{className:"shot-error",role:"alert",children:a(Pe)}),$&&t.jsx(Gf,{characters:$==="characters",onClose:()=>{W(!1),$t(null)},onSelect:si}),A&&t.jsx("div",{className:"shot-trial-shield",role:"dialog","aria-label":a("Xem thử đề xuất AI"),children:t.jsxs("div",{className:"shot-trial-controls",children:[t.jsx("b",{children:a("Xem thử · chưa lưu")}),t.jsx("button",{onClick:()=>{Ie>=1&&ot(0),D(!H)},children:H?a("Tạm dừng"):a("Phát lại")}),t.jsx("input",{"aria-label":a("Thời gian xem thử"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(2),a("s")]}),t.jsx("button",{onClick:()=>ai(!1),children:a("Bỏ bản xem thử")}),t.jsx("button",{className:"shot-primary",onClick:()=>ai(!0),children:a("Giữ thay đổi")})]})}),t.jsxs("div",{className:`shot-layout ${Q?"has-drawer":""} ${xe?"rail-wide":""}`,style:{"--drawer-w":`${ue.drawer}px`,"--right-w":`${ue.right}px`},children:[t.jsxs("nav",{className:"shot-rail","aria-label":a("Công cụ dựng cảnh"),onMouseOver:Dl,onFocus:Dl,onMouseLeave:()=>ha(null),onBlur:()=>ha(null),onScroll:()=>ha(null),children:[So.map(([c,x,L])=>t.jsxs("button",{type:"button",className:Q===c?"active":"","aria-pressed":Q===c,"aria-label":a(x),onClick:()=>wm(c),children:[L,t.jsx("span",{className:"lbl",children:a(x)}),c==="objects"&&t.jsx("small",{className:"shot-rail-count",children:z.items.length}),c==="shots"&&z.shots.length>1&&t.jsx("small",{className:"shot-rail-count",children:z.shots.length}),c==="notes"&&$s.length>0&&t.jsx("small",{className:"shot-rail-count",children:$s.length})]},c)),t.jsx("span",{className:"shot-rail-gap"}),t.jsxs("button",{type:"button","aria-label":xe?a("Thu gọn thanh công cụ"):a("Mở rộng thanh công cụ"),onClick:()=>$l(!xe),children:[xe?t.jsx(Ne.collapse,{}):t.jsx(Ne.expand,{}),t.jsx("span",{className:"lbl",children:a("Thu gọn")})]}),t.jsxs("button",{type:"button","aria-label":a("Khôi phục bố cục"),onClick:Mm,children:[t.jsx(Ne.reset,{}),t.jsx("span",{className:"lbl",children:a("Khôi phục bố cục")})]})]}),no&&gd.createPortal(t.jsx("span",{className:"shot-rail-tip",role:"tooltip",style:{left:no.left,top:no.top},children:no.label}),document.querySelector(".shot-workspace")||document.body),Q&&t.jsxs("aside",{className:"shot-drawer shot-inspector","aria-label":a(So.find(c=>c[0]===Q)[1]),children:[t.jsxs("div",{className:"shot-drawer-head",children:[t.jsxs("h3",{children:[a(So.find(c=>c[0]===Q)[1]),Q==="objects"?t.jsxs("small",{className:"shot-total",children:[" · ",z.items.length]}):Q==="shots"?t.jsxs("small",{className:"shot-total",children:[" · ",z.shots.length," · ",Ai(Ml.at(-1)?.end||0)]}):Q==="notes"?t.jsxs("small",{className:"shot-total",children:[" · ",$s.length]}):Q==="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":a("Đóng bảng"),title:a("Đóng bảng (Esc)"),onClick:()=>Vn(null),children:t.jsx(Ne.close,{})})]}),t.jsxs("div",{className:"shot-drawer-body shot-inspector-scroll",tabIndex:0,children:[Q==="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:yt,type:"file",accept:".glb",hidden:!0,onChange:c=>{pm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{onClick:()=>W("all"),children:[t.jsx(Ne.library,{}),a("Kho 3D chung")]}),t.jsxs("button",{onClick:()=>void Fl(),children:[t.jsx(Ne.user,{}),a("Model của tôi")]}),rt.length>0&&t.jsxs("select",{"aria-label":a("Model 3D đã lưu"),value:"",onChange:c=>{const x=rt.find(P=>P.id===c.target.value);if(!x)return;const L={...Mn("model",Ae.current.items.length),name:x.name,model:{gcsUri:x.gcsUri,name:x.name}};we(P=>({...P,items:[...P.items,L]})),xt(L.id)},children:[t.jsx("option",{value:"",children:a("Chọn model đã lưu…")}),rt.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),qt&&t.jsx("button",{onClick:()=>void Fl(qt),children:a("Thêm model đã lưu")}),t.jsxs("button",{disabled:lt,onClick:()=>yt.current?.click(),children:[t.jsx(Ne.cube,{}),lt?a("Đang tải…"):"Model GLB"]}),t.jsx("input",{ref:yn,type:"file",accept:".spz,.ply,.splat,.ksplat,.sog",hidden:!0,onChange:c=>{fm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:lt,title:a("Bản quét 3D địa điểm thật từ app điện thoại (Scaniverse, Polycam, Luma…)"),onClick:()=>yn.current?.click(),children:[t.jsx(Ne.image,{}),a("Bối cảnh thật")]}),mi.length>0&&t.jsxs("select",{"aria-label":a("Dùng 3D World trên Canvas"),value:"",onChange:c=>{const x=mi.find(P=>P.id===c.target.value);if(!x)return;const L=x.data;Pl(L.label||"3D World",{name:L.label||"3D World",url:L.splatUrl,source:"world",flip:!0,...L.worldId?{worldId:L.worldId}:{}})},children:[t.jsx("option",{value:"",children:a("Dùng 3D World trên Canvas…")}),mi.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"3D World")},c.id))]}),Yi.map(([c,x])=>t.jsxs("button",{disabled:re,onClick:()=>gm(c),children:[dj[c],a(x)]},c))]}),t.jsx(es,{label:"Số người mỗi lần thêm",value:St,min:1,max:50,step:1,onChange:c=>gt(Math.floor(c))})]})}),Q==="fx"&&t.jsx(t1,{onEdit:()=>Vn("fxedit"),onPlayClip:(c,x)=>{ri(c,x)},stage:z,selected:J,playhead:Ie*de.duration,change:we,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],anchor:(c,x,L)=>Ce.current?.partPointAt(de,L,c,x)??null,engine:Ce.current,setError:ye}),Q==="material"&&t.jsx(f1,{stage:z,selected:J,change:we,engine:Ce.current,setError:ye,scope:qn,setScope:Un}),Q==="rigging"&&t.jsx($1,{stage:z,shot:de,selected:J,engine:at?Ce.current:null,playhead:Ie,busy:re,change:we,patchItem:tt,onSelect:xt,resync:()=>Ce.current?.sync(Ae.current,J),setError:ye,addPoseKey:nl,onPlayClip:ri,motionLoop:oi,motionMirror:ii,onMotionLoop:cl,onMotionMirror:hl,keys:Cn}),Q==="fxedit"&&t.jsx(n1,{stage:z,selected:J,playhead:Ie*de.duration,change:we,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],engine:Ce.current}),Q==="mixfx"&&t.jsx(l1,{stage:z,selected:J,progress:Ie,change:we,onSelect:xt,engine:Ce.current,setError:ye}),Q==="modeling"&&t.jsx(Bx,{stage:z,selected:J,change:we,getStage:()=>Ae.current,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],engine:Ce.current,setError:ye}),Q==="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:a("Nhân vật có xương: thêm vào cảnh là chạy mocap / chuyển động ngay"),children:[t.jsx(Ne.person,{}),t.jsx("span",{children:a("Thư viện nhân vật")})]})}),t.jsx("div",{className:"shot-list",children:z.items.map(c=>t.jsxs("div",{className:J===c.id?"active":K.includes(c.id)?"picked":"",onContextMenu:x=>{x.preventDefault(),di(c.id,x.clientX,x.clientY)},children:[t.jsxs("button",{"aria-pressed":cn.includes(c.id),title:a("Shift/Ctrl+click: chọn thêm · chuột phải: menu"),onClick:x=>bn(c.id,x.shiftKey||x.ctrlKey||x.metaKey),children:[c.kind==="person"?"♙":c.kind==="set"?"⌂":"◇"," ",c.name,c.kind==="set"&&c.set?.parts?t.jsxs("small",{className:"shot-list-meta",children:[" · ",c.set.parts," ",a("khối")]}):null]}),t.jsx("button",{title:c.hidden?a("Hiện"):a("Ẩn"),onClick:()=>tt(c.id,{hidden:!c.hidden}),children:c.hidden?"○":"●"}),t.jsx("button",{title:c.locked?a("Mở khóa"):a("Khóa"),onClick:()=>tt(c.id,{locked:!c.locked}),children:c.locked?"▣":"□"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[c.name]),title:c.locked?a("Mở khóa đối tượng trước khi xóa"):a("Xóa {0} (Delete)",[c.name]),disabled:re||c.locked,onClick:()=>ml(c.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"})})})]},c.id))})]}),ne&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("CHỈNH ĐỐI TƯỢNG")}),t.jsxs("fieldset",{disabled:ne.locked||re,children:[t.jsx("input",{"aria-label":a("Tên đối tượng"),value:ne.name,onChange:c=>tt(ne.id,{name:c.target.value})}),t.jsxs("label",{className:"shot-field",children:[a("Màu"),t.jsx("input",{"aria-label":a("Màu đối tượng"),type:"color",value:ne.color,onChange:c=>tt(ne.id,{color:c.target.value})})]}),t.jsxs("select",{"aria-label":a("Đặt lên bề mặt"),value:"",onChange:c=>{c.target.value&&Ce.current?.placeOnSurface(c.target.value)},children:[t.jsx("option",{value:"",children:a("Đặt lên bề mặt…")}),t.jsx("option",{value:"ground",children:a("Mặt đất")}),z.items.filter(c=>c.kind!=="person"&&c.id!==ne.id&&!c.hidden).map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),Ss(a("Vị trí"),ne.position,c=>tt(ne.id,{position:c})),Ss("Xoay °",ne.rotation,c=>tt(ne.id,{rotation:c}),-360),Ss(a("Tỷ lệ"),ne.scale,c=>tt(ne.id,{scale:c}),.05),ne.kind==="model"&&ne.model&&t.jsxs("div",{className:"shot-model-size",children:[t.jsx(es,{label:"Chiều cao thật (m)",value:Number((Ce.current?.modelHeight(ne)??2).toFixed(2)),min:.02,max:500,step:.01,onChange:c=>tt(ne.id,{model:{...ne.model,height:c}})}),t.jsx("small",{className:"shot-hint",children:ne.model.height?a("Kích thước thật"):a("Tự động: cạnh dài nhất 2 m")}),ne.model.height&&t.jsx("button",{onClick:()=>{const{height:c,...x}=ne.model;tt(ne.id,{model:x})},children:a("Về tự động")})]}),ne.hold&&(()=>{const c=z.items.find(x=>x.id===ne.hold.by);return t.jsxs("div",{className:"shot-held",children:[t.jsx("small",{className:"shot-hint",children:a("Đang được {0} cầm ở {1}",[c?.name||"?",ne.hold.hand==="R"?a("tay phải"):a("tay trái")])}),t.jsx("button",{onClick:()=>c&&dl(c.id,ne.hold.hand,""),children:a("Thả xuống")})]})})(),ne.kind==="splat"&&ne.splat&&(()=>{const c=Ce.current?.splatExtent(ne.splat);return t.jsxs("div",{className:"shot-splat",children:[t.jsx("h3",{children:a("BỐI CẢNH THẬT")}),t.jsxs("small",{className:"shot-hint",children:[ne.splat.source==="world"?a("3D World do AI tạo"):a("Bản quét địa điểm thật"),c?` · ${(c.max[0]-c.min[0]).toFixed(1)} × ${(c.max[2]-c.min[2]).toFixed(1)} m`:` · ${a("đang tải…")}`]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.splat.flip!==!1,onChange:x=>{const L={...ne.splat,flip:x.target.checked},P=Ce.current?.splatExtent(L);tt(ne.id,P?{splat:{...L,bounds:{min:P.min,max:P.max},floor:P.floor},position:[ne.position[0],-P.floor*ne.scale[1],ne.position[2]]}:{splat:L})}}),a("Lật trục (file quét kiểu OpenCV)")]}),t.jsx(es,{label:"Tỷ lệ bản quét",value:ne.scale[0],min:.05,step:.05,onChange:x=>tt(ne.id,{scale:[x,x,x]})}),t.jsx("button",{disabled:!c,onClick:()=>{c&&tt(ne.id,{position:[ne.position[0],-c.floor*ne.scale[1],ne.position[2]],splat:{...ne.splat,bounds:{min:c.min,max:c.max},floor:c.floor}})},children:a("Căn sàn về mặt đất")}),t.jsx("small",{className:"shot-hint",children:a('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.')})]})})(),g1.includes(ne.kind)&&t.jsx(b1,{item:z.items.find(c=>c.id===ne.id)??ne,shot:de,playhead:Ie,patchItem:tt,change:we}),ne.kind==="person"&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("NHẬN DIỆN NHÂN VẬT")}),t.jsxs("select",{"aria-label":a("Ảnh tham chiếu nhân vật"),value:ne.reference?.nodeId||"",onChange:c=>{const x=to.find(P=>P.id===c.target.value),L=x?.data;tt(ne.id,{reference:x&&L?.url?{nodeId:x.id,url:L.url,name:L.label||"Character reference"}:null})},children:[t.jsx("option",{value:"",children:a("Không dùng ảnh nhận diện")}),to.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]}),ne.reference&&t.jsx("img",{className:"shot-character-ref",src:ne.reference.url,alt:ne.reference.name}),t.jsx("h3",{children:a("NHÂN VẬT")}),t.jsx("button",{type:"button",className:"shot-char-open",title:a("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:()=>{$t(ne.id),W("characters")},children:a("Chọn nhân vật từ thư viện…")}),ne.look||ne.figure&&["legs","shoulders","hips","chest","waist","weight","muscle","posture","skin","face"].some(c=>ne.figure[c]!==void 0)?t.jsx("button",{type:"button",onClick:()=>tt(ne.id,{figure:ne.figure?{height:ne.figure.height,head:ne.figure.head,build:ne.figure.build}:void 0,look:void 0,character:void 0}),children:a("Về mannequin trơn")}):null,t.jsx("h3",{children:a("VÓC DÁNG")}),t.jsx("div",{className:"shot-add shot-figure-presets",children:qf.map(c=>{const x=Wt(ne.figure);return t.jsx("button",{className:x.height===c.figure.height&&x.head===c.figure.head&&x.build===c.figure.build?"active":"",onClick:()=>tt(ne.id,{figure:{...c.figure}}),children:a(c.name)},c.name)})}),t.jsx(es,{label:"Chiều cao (m)",value:Wt(ne.figure).height,min:.3,max:3,step:.01,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),height:c})})}),t.jsxs("label",{className:"shot-joint",children:[a("Cỡ đầu")," ",t.jsxs("span",{children:[Wt(ne.figure).head.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Cỡ đầu"),type:"range",min:.7,max:2,step:.05,value:Wt(ne.figure).head,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),head:+c.target.value})})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Vai / hông")," ",t.jsxs("span",{children:[Wt(ne.figure).build.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Vai / hông"),type:"range",min:.6,max:1.6,step:.05,value:Wt(ne.figure).build,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),build:+c.target.value})})})]}),t.jsx("h3",{children:a("ĐẠO CỤ TRÊN TAY")}),t.jsxs("div",{className:"shot-props",children:[["R","L"].map(c=>{const x=z.items.find(P=>P.hold?.by===ne.id&&P.hold.hand===c),L=z.items.filter(P=>P.id!==ne.id&&!["person","splat","set","floor","wall"].includes(P.kind)&&!(P.hold&&P.hold.by!==ne.id));return t.jsxs("div",{className:"shot-prop-hand",children:[t.jsxs("label",{className:"shot-field",children:[c==="R"?a("Tay phải"):a("Tay trái"),t.jsxs("select",{"aria-label":c==="R"?a("Đạo cụ tay phải"):a("Đạo cụ tay trái"),value:x?`item:${x.id}`:"",onChange:P=>dl(ne.id,c,P.target.value),children:[t.jsx("option",{value:"",children:a("— Tay không —")}),x&&t.jsx("option",{value:`item:${x.id}`,children:x.name}),t.jsx("optgroup",{label:a("Đạo cụ dựng sẵn"),children:Uf.map(P=>t.jsx("option",{value:`prop:${P}`,children:a(La[P].label)},P))}),L.filter(P=>P.id!==x?.id).length>0&&t.jsx("optgroup",{label:a("Vật trong cảnh"),children:L.filter(P=>P.id!==x?.id).map(P=>t.jsx("option",{value:`item:${P.id}`,children:P.name},P.id))})]})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Gập cổ tay")," ",t.jsxs("span",{children:[x.hold.tilt??(x.prop?La[x.prop.kind].tilt??0:0),"°"]}),t.jsx("input",{"aria-label":a("Gập cổ tay"),type:"range",min:-90,max:90,step:5,value:x.hold.tilt??(x.prop?La[x.prop.kind].tilt??0:0),onChange:P=>we(B=>({...B,items:B.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,tilt:+P.target.value}}:X)}))})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Xoay quanh cổ tay")," ",t.jsxs("span",{children:[x.hold.angle??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay đạo cụ quanh cổ tay"),type:"range",min:-180,max:180,step:5,value:x.hold.angle??0,onChange:P=>we(B=>({...B,items:B.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,angle:+P.target.value}}:X)}))})]})]},c)}),t.jsx("small",{className:"shot-hint",children:a("Đạ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:a("CHUYỂN ĐỘNG NGƯỜI")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.gait!=="off",onChange:c=>tt(ne.id,{gait:c.target.checked?"auto":"off"})}),a("Tự bước đi / chạy khi di chuyển")]}),(()=>{const c=de.objectKeys?.[ne.id]||[],x=c.filter(P=>P.pose),L=x.find(P=>Math.abs(P.time-Ie)<1e-6);return t.jsxs("div",{className:"shot-pose-keys",children:[t.jsx("button",{className:L?"active":"",onClick:()=>nl(ne.id),children:L?a("◆ Cập nhật key tư thế · {0}s",[(Ie*de.duration).toFixed(1)]):a("◇ Key tư thế tại {0}s",[(Ie*de.duration).toFixed(1)])}),L&&t.jsx("button",{onClick:()=>zu(ne.id),children:a("Bỏ key tư thế")}),L&&t.jsxs("label",{className:"shot-pose-ease",children:[a("Kiểu chuyển vào key")," ",t.jsx("select",{"aria-label":a("Kiểu chuyển vào key"),value:L.poseEase||"smooth",onChange:P=>Bu(ne.id,P.target.value),children:Xf.map(P=>t.jsx("option",{value:P.id,children:a(P.label)},P.id))})]}),t.jsx("small",{className:"shot-hint",children:x.length?a("{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.",[x.length]):a("Đặt key ở nhiều thời điểm (đứng → ngồi → giơ tay…) để tư thế chuyển động theo thời gian.")})]})})(),t.jsx(j1,{shot:de,item:ne,playhead:Ie*de.duration,change:we,engine:Ce.current,seek:c=>{D(!1),ot(Math.max(0,Math.min(1,c/de.duration)))}}),t.jsx(Fu,{disabled:re,loop:oi,mirror:ii,onLoop:cl,onMirror:hl,onPlay:c=>{ri(ne.id,c)},person:ne,playhead:Ie*de.duration}),t.jsxs("div",{className:"shot-mocap",children:[t.jsx("input",{ref:sl,type:"file",accept:".bvh,.fbx,.glb",hidden:!0,onChange:c=>{Wu(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:il||re,onClick:()=>sl.current?.click(),title:a("Chuyển động người thật: Mixamo (.fbx), CMU (.bvh) hoặc GLB có animation"),children:[t.jsx(Ne.person,{}),il?a("Đang đọc…"):a("Nhập mocap (.bvh · .fbx · .glb)")]}),os&&t.jsxs("div",{className:"shot-mocap-card",children:[t.jsx("b",{children:os.name}),t.jsxs("small",{children:[os.duration.toFixed(1),a("s · khung xương người ✓")]}),t.jsxs("label",{className:"shot-field",children:[a("Tốc độ"),t.jsx("select",{"aria-label":a("Tốc độ mocap"),value:la,onChange:c=>Ku(+c.target.value),children:[.5,.75,1,1.25,1.5,2].map(c=>t.jsxs("option",{value:c,children:[c,"×"]},c))})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ol,onChange:c=>Hu(c.target.checked)}),a("Di chuyển theo mocap (đi, chạy, nhảy)")]}),t.jsx("small",{className:"shot-hint",children:a("Bắt đầu tại {0}s · dùng {1}s (phần dài hơn shot bị cắt)",[(Ie*de.duration).toFixed(1),Math.min(os.duration/la,(1-Ie)*de.duration).toFixed(1)])}),t.jsx("button",{className:"shot-primary",disabled:re,onClick:()=>qu(ne.id),children:a("Áp dụng cho {0}",[ne.name])})]}),Vf(z,ne.id)&&t.jsx("button",{onClick:()=>{D(!1),we(c=>N0(c,ne.id))},children:a("Xoá mocap của {0}",[ne.name])})]}),t.jsxs("div",{className:"shot-hits",children:[t.jsx("button",{onClick:Xu,children:a("⚡ Tự tạo phản ứng trúng đòn")}),Yf(de)&&t.jsx("button",{onClick:Vu,children:a("Xoá phản ứng tự động")}),t.jsx("small",{className:"shot-hint",children:Uu||a('Đò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:[a("RIG PRESETS"),t.jsx("button",{className:"shot-pose-mirror",title:a("Lật tư thế trái ↔ phải"),onClick:()=>tt(ne.id,{pose:Qf(ne.pose)}),children:a("⇆ Lật trái/phải")})]}),t.jsx("div",{className:"shot-rig-library",children:zo.map(c=>t.jsxs("section",{children:[t.jsxs("header",{children:[t.jsx("span",{children:a(c.name)}),t.jsxs("small",{children:[c.presets.length," ",a("rig")]})]}),t.jsx("div",{className:"shot-rig-grid",children:c.presets.map(x=>t.jsxs("button",{className:pj(ne.pose,Kn[x])?"active":"",title:a("Áp dụng rig {0}",[x]),onClick:()=>_u(ne,x),children:[t.jsx(Jr,{pose:Kn[x]}),t.jsx("span",{children:a(x)})]},x))})]},a(c.name)))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thư viện pose cá nhân")}),t.jsxs("div",{className:"shot-pose-library",children:[z.poseLibrary.map(c=>t.jsxs("div",{children:[t.jsx("button",{onClick:()=>tt(ne.id,{pose:{...c.pose}}),children:c.name}),t.jsx("button",{"aria-label":a("Xóa {0}",[c.name]),onClick:()=>we(x=>({...x,poseLibrary:x.poseLibrary.filter(L=>L.id!==c.id)})),children:a("×")})]},c.id)),t.jsx("button",{onClick:()=>{const c=window.prompt(a("Tên pose"),`Pose ${z.poseLibrary.length+1}`)?.trim();c&&we(x=>({...x,poseLibrary:[...x.poseLibrary,{id:vt(),name:c,pose:structuredClone(ne.pose)}]}))},children:a("+ Lưu pose hiện tại")})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Kéo tay/chân IK")}),t.jsxs("div",{className:"shot-ik-grid",children:[t.jsx(Co,{label:"Tay trái",root:ne.pose.shoulderL,bend:ne.pose.elbowL,upper:.29,lower:.27,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,shoulderL:c,elbowL:x}})}),t.jsx(Co,{label:"Tay phải",root:ne.pose.shoulderR,bend:ne.pose.elbowR,upper:.29,lower:.27,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,shoulderR:c,elbowR:x}})}),t.jsx(Co,{label:"Chân trái",root:ne.pose.hipL,bend:ne.pose.kneeL,upper:.43,lower:.4,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,hipL:c,kneeL:x}})}),t.jsx(Co,{label:"Chân phải",root:ne.pose.hipR,bend:ne.pose.kneeR,upper:.43,lower:.4,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,hipR:c,kneeR:x}})})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Chỉnh từng khớp")}),Object.keys(Fo).map(c=>t.jsxs("label",{className:"shot-joint",children:[a(Fo[c])," ",t.jsxs("span",{children:[ne.pose[c]||0,"°"]}),t.jsx("input",{"aria-label":a(Fo[c]),type:"range",min:c.startsWith("knee")||c.startsWith("elbow")?0:-120,max:150,value:ne.pose[c]||0,onChange:x=>tt(ne.id,{pose:{...ne.pose,[c]:+x.target.value}})})]},c))]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Tay · đầu · mắt")}),t.jsx("div",{className:"shot-hand-shapes",children:["R","L"].map(c=>t.jsxs("div",{children:[t.jsx("small",{children:c==="R"?a("Tay phải"):a("Tay trái")}),t.jsx("span",{children:nr.map(x=>t.jsx("button",{type:"button",className:Zf(ne.pose,c,x)?"active":"",onClick:()=>tt(ne.id,{pose:mj(ne.pose,c,x)}),children:a(x.label)},x.id))})]},c))}),t.jsxs("label",{className:"shot-field",children:[a("Mắt nhìn"),t.jsxs("select",{"aria-label":a("Mắt nhìn"),value:ne.gaze||"",onChange:c=>tt(ne.id,{gaze:c.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Theo tư thế")}),t.jsx("option",{value:"camera",children:a("Nhìn vào camera")}),z.items.filter(c=>c.id!==ne.id&&c.kind!=="splat"&&c.kind!=="set").map(c=>t.jsx("option",{value:c.id,children:a("Nhìn {0}",[c.name])},c.id))]})]}),Object.keys(Zi).map(c=>{const[x,L,P]=Jf[c],B=uj(ne.pose,c);return t.jsxs("label",{className:"shot-joint",children:[a(Zi[c])," ",t.jsxs("span",{children:[B,P]}),t.jsx("input",{"aria-label":a(Zi[c]),type:"range",min:x,max:L,value:B,disabled:(c==="eyeYaw"||c==="eyePitch")&&!!ne.gaze,onChange:X=>tt(ne.id,{pose:{...ne.pose,[c]:+X.target.value}})})]},c)})]})]}),t.jsx("button",{onClick:()=>{const c={...structuredClone(ne),id:vt(),name:`${ne.name} copy`,position:[ne.position[0]+1,...ne.position.slice(1)]};we(x=>({...x,items:[...x.items,c]})),xt(c.id)},children:a("Nhân bản")}),t.jsx("button",{onClick:()=>{ml(ne.id)},children:a("Xóa đối tượng")})]})]})]}),Q==="camera"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Tên shot"),value:de.name,onChange:c=>kt({name:c.target.value})}),t.jsxs("div",{className:"shot-camera-gizmo",role:"group","aria-label":a("Chỉnh camera trong cảnh 3D"),children:[t.jsxs("button",{type:"button",className:r?"active":"","aria-pressed":r,disabled:S,title:a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"),onClick:()=>{xt(null),i(null),l(!r),ee(c=>c==="scale"?"translate":c)},children:[t.jsx(Ne.camera,{}),a("Chọn camera")]}),r&&["translate","rotate"].map(c=>t.jsxs("button",{type:"button",className:(_==="rotate"?"rotate":"translate")===c?"active":"","aria-pressed":(_==="rotate"?"rotate":"translate")===c,title:a(c==="translate"?"Di chuyển camera (W)":"Xoay camera (E): vòng xanh dương = nghiêng"),onClick:()=>ee(c),children:[c==="translate"?t.jsx(Ne.move,{}):t.jsx(Ne.rotate,{}),a(c==="translate"?"Di chuyển":"Xoay")]},c))]}),t.jsx("textarea",{className:"shot-note","aria-label":a("Ghi chú đạo diễn cho shot"),placeholder:a("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:de.note||"",onChange:c=>kt({note:c.target.value})}),t.jsxs("div",{className:"shot-row",children:[t.jsx("select",{"aria-label":a("Tỷ lệ ảnh"),value:de.aspect,onChange:c=>kt({aspect:c.target.value}),children:["16:9","9:16","1:1","21:9","4:3","2.39:1"].map(c=>t.jsx("option",{children:c},c))}),de.motion!=="path"&&t.jsx(es,{label:"Lens mm",value:de.lens,min:14,max:200,step:1,onChange:c=>kt({lens:c})})]}),t.jsxs("label",{className:"shot-field",children:[a("Thời lượng camera (giây)"),t.jsx(Sn,{"aria-label":a("Thời lượng camera (giây)"),min:.1,step:"0.1",value:de.duration,onCommit:c=>kt({duration:c})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Rung cầm tay")," ",t.jsxs("span",{children:[Math.round((de.handheld||0)*100),"%"]}),t.jsx("input",{"aria-label":a("Rung cầm tay"),type:"range",min:0,max:1,step:.05,value:de.handheld||0,onChange:c=>kt({handheld:+c.target.value||void 0})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:de.impactShake!==!1,onChange:c=>{const x=c.target.checked;kt(x?{impactShake:void 0}:{impactShake:!1,impacts:void 0})}}),a("Rung camera khi trúng đòn")]}),t.jsx(Z1,{shot:de,patch:kt,progress:Ie,seek:c=>{D(!1),ot(c)},engine:Ce.current||null,selected:o,select:c=>{i(c),M(c?{row:"camera",id:c}:null)}}),de.motion==="path"&&t.jsx("button",{disabled:re||!at||!de.cameraKeys?.length,onClick:async()=>{D(!1),me(!0),ye("");try{for(const[c,x]of(de.cameraKeys||[]).entries())await is(!0,de,c,!1,x.time,` · Key ${c+1} · ${(x.time*de.duration).toFixed(1)}s`)}catch(c){ye(c.message)}finally{me(!1)}},children:a("Xuất các key thành ảnh tham chiếu")}),t.jsx("h3",{children:a("CHUYỂN ĐỘNG NHANH")}),t.jsxs("select",{"aria-label":a("Chuyển động camera"),value:de.motion,onChange:c=>mm(c.target.value),children:[t.jsx("option",{value:"path",disabled:!de.cameraKeys?.length,children:a("Đường chạy keyframe")}),t.jsx("option",{value:"static",children:a("Đứng yên")}),t.jsx("option",{value:"dolly-in",children:a("Dolly in")}),t.jsx("option",{value:"dolly-out",children:a("Dolly out")}),t.jsx("option",{value:"truck-left",children:a("Truck trái")}),t.jsx("option",{value:"truck-right",children:a("Truck phải")}),t.jsx("option",{value:"crane-up",children:a("Crane lên")}),t.jsx("option",{value:"crane-down",children:a("Crane xuống")}),t.jsx("option",{value:"orbit-left",children:a("Orbit trái")}),t.jsx("option",{value:"orbit-right",children:a("Orbit phải")}),t.jsx("option",{value:"custom",children:a("Tùy chỉnh")})]}),de.motion!=="static"&&de.motion!=="path"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[a("Xem chuyển động")," ",t.jsxs("span",{children:[Math.round(Ie*100),"%"]}),t.jsx("input",{"aria-label":a("Tiến trình camera"),type:"range",min:0,max:100,value:Ie*100,onChange:c=>ot(+c.target.value/100)})]}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Camera kết thúc")}),Ss(a("Vị trí cuối"),de.endPosition,c=>kt({endPosition:c,motion:"custom"})),Ss(a("Điểm nhìn cuối"),de.endTarget,c=>kt({endTarget:c,motion:"custom"})),t.jsx(es,{label:"Lens cuối mm",value:de.endLens,min:14,max:200,step:1,onChange:c=>kt({endLens:c,motion:"custom"})})]})]}),t.jsxs("fieldset",{disabled:de.motion==="path",style:{display:de.motion==="path"?"none":void 0},children:[t.jsx("button",{onClick:()=>kt(Ce.current?.captureCamera()||{}),children:a("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((c,x)=>t.jsx("button",{onClick:()=>{const L=ne?.position||[0,0,0];kt({position:[[3,2,6],[0,1.5,3],[0,1.7,1.2],[1,.3,3],[2,5,3],[.5,1.7,-1.5]][x].map((B,X)=>B+L[X]),target:[L[0],L[1]+(x===2?1.65:1.2),L[2]],roll:0})},children:a(c)},c))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thông số camera")}),Ss(a("Vị trí máy"),de.position,c=>kt({position:c})),Ss(a("Điểm nhìn"),de.target,c=>kt({target:c})),t.jsx(es,{label:"Nghiêng máy °",value:de.roll,min:-180,max:180,step:1,onChange:c=>kt({roll:c})}),t.jsx("button",{disabled:z.shots.length<2,onClick:()=>we(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera này")})]})]}),de.motion==="path"&&t.jsx("button",{disabled:z.shots.length<2,onClick:()=>we(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera đường chạy")}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Prompt bố cục")}),t.jsx("textarea",{"aria-label":a("Prompt bố cục"),readOnly:!0,value:Ti(z),rows:8}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(Ti(z)).then(()=>dt.getState().toast(a("Đã copy prompt"),"ok")).catch(()=>ye("Không truy cập được clipboard; hãy chọn và copy nội dung.")),children:a("Copy prompt")})]})]}),Q==="light"&&t.jsx("div",{className:"shot-light-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("select",{"aria-label":a("Thời điểm trong ngày"),value:Ct.time,onChange:c=>{const x=c.target.value;Pn({time:x,elevation:cc[x].elevation})},children:e0.map(c=>t.jsx("option",{value:c,children:a(cc[c].label)},c))}),t.jsxs("label",{className:"shot-joint",children:[a("Hướng mặt trời")," ",t.jsxs("span",{children:[Math.round(Ct.azimuth),"°"]}),t.jsx("input",{"aria-label":a("Hướng mặt trời"),type:"range",min:0,max:359,value:Math.round(Ct.azimuth),onChange:c=>Pn({azimuth:+c.target.value})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Độ cao mặt trời")," ",t.jsxs("span",{children:[Math.round(Ct.elevation),"°"]}),t.jsx("input",{"aria-label":a("Độ cao mặt trời"),type:"range",min:1,max:89,value:Math.round(Ct.elevation),onChange:c=>Pn({elevation:+c.target.value})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Môi trường phản xạ")}),t.jsx("select",{"aria-label":a("Môi trường phản xạ"),value:Ct.env??"auto",onChange:c=>Pn({env:c.target.value}),children:t0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),t.jsxs("label",{className:"shot-joint",children:[a("Xoay môi trường")," ",t.jsxs("span",{children:[Math.round(Ct.envRotation??0),"°"]}),t.jsx("input",{"aria-label":a("Xoay môi trường"),type:"range",min:0,max:359,value:Math.round(Ct.envRotation??0),onChange:c=>Pn({envRotation:+c.target.value})})]}),n0(Ct)==="sky"&&t.jsxs("label",{className:"shot-joint",children:[a("Mây trên trời")," ",t.jsxs("span",{children:[Math.round(hc(Ct)*100),"%"]}),t.jsx("input",{"aria-label":a("Mây trên trời"),type:"range",min:0,max:100,value:Math.round(hc(Ct)*100),onChange:c=>Pn({clouds:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Ánh sáng viền (Rim)")," ",t.jsxs("span",{children:[Math.round((Ct.rim??1)*100),"%"]}),t.jsx("input",{"aria-label":a("Ánh sáng viền (Rim)"),type:"range",min:0,max:200,value:Math.round((Ct.rim??1)*100),onChange:c=>Pn({rim:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xóa phông ống kính (DOF)")}),t.jsx("select",{"aria-label":a("Xóa phông ống kính (DOF)"),value:Ct.dof??"off",onChange:c=>Pn({dof:c.target.value}),children:s0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),Ct.dof&&t.jsxs("label",{className:"shot-joint",children:[a("Khoảng nét")," ",t.jsx("span",{children:Ct.focusDistance?`${Ct.focusDistance.toFixed(1)}m`:a("Tự động")}),t.jsx("input",{"aria-label":a("Khoảng nét"),type:"range",min:.5,max:40,step:.5,value:Ct.focusDistance??Math.max(.5,Math.min(40,Math.hypot(de.position[0]-de.target[0],de.position[1]-de.target[1],de.position[2]-de.target[2]))),onChange:c=>Pn({focusDistance:+c.target.value})})]}),Ct.dof&&Ct.focusDistance!==void 0&&t.jsx("button",{type:"button",onClick:()=>Pn({focusDistance:void 0}),children:a("Lấy nét tự động theo mục tiêu")}),t.jsx("small",{className:"shot-hint",children:a("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.")}),Ct.dof&&t.jsx(oj,{shot:de,items:z.items,progress:Ie,presetFstop:a0(Ct.dof)??2.8,onChange:c=>kt({focus:c})}),t.jsxs("label",{className:"shot-field shot-render-style",children:[t.jsx("span",{children:a("Kiểu hình")}),t.jsxs("select",{"aria-label":a("Kiểu hình"),value:z.style?"clay":"natural",onChange:c=>{const x=c.target.value==="clay";we(L=>{const{style:P,...B}=L;return x?{...B,style:A0({...T0,...P||{},style:"clay"})}:B})},children:[t.jsx("option",{value:"natural",children:a("Tự nhiên")}),t.jsx("option",{value:"clay",children:a("Đất sét · phim tài liệu 3D")})]})]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.accents==="vivid",onChange:c=>{const x=c.target.checked?"vivid":"none";we(L=>L.style?{...L,style:{...L.style,accents:x}}:L)}}),a("Giữ màu nổi bật trên người (đồng phục đỏ, sọc vàng…)")]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.faceted,onChange:c=>{const x=c.target.checked;we(L=>L.style?{...L,style:{...L.style,faceted:x}}:L)}}),a("Mặt góc cạnh (low-poly)")]}),z.style&&t.jsx("small",{className:"shot-hint",children:a("Người và nhân vật thành tượng đất sét xám, bối cảnh và xe cộ giữ màu — kiểu phim tài liệu tội phạm 3D.")}),t.jsxs("label",{className:"shot-field shot-style-refs",children:[t.jsxs("span",{children:[a("Ảnh phong cách bối cảnh")," · ",ca.length,"/",Li]}),t.jsxs("select",{"aria-label":a("Thêm ảnh phong cách bối cảnh"),value:"",disabled:ca.length>=Li,onChange:c=>{const x=to.find(P=>P.id===c.target.value),L=x?.data;x&&L?.url&&we(P=>({...P,styleRefs:[...(P.styleRefs||[]).filter(B=>B.nodeId!==x.id),{nodeId:x.id,url:L.url,name:L.label||"Location look"}].slice(0,Li)}))},children:[t.jsx("option",{value:"",children:a("+ Chọn ảnh trên canvas…")}),to.filter(c=>!ca.some(x=>x.nodeId===c.id)).map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]})]}),ca.length>0&&t.jsx("div",{className:"shot-style-strip",children:ca.map(c=>t.jsxs("span",{children:[t.jsx("img",{src:c.url,alt:c.name}),t.jsx("button",{"aria-label":a("Bỏ {0}",[c.name]),onClick:()=>we(x=>({...x,styleRefs:(x.styleRefs||[]).filter(L=>L.nodeId!==c.nodeId)})),children:"×"})]},c.nodeId))}),t.jsx("small",{className:"shot-hint",children:a("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.")})]})}),Q==="shots"&&t.jsx("div",{className:"shot-shots-section",children:t.jsx("ol",{className:"shot-shotlist",children:z.shots.map((c,x)=>{const L=Ml[x];return t.jsxs("li",{"data-shot":c.id,className:c.id===z.activeShot?"active":"",children:[t.jsxs("button",{className:"shot-shotlist-pick","aria-label":a("Chọn {0}",[c.name]),"aria-current":c.id===z.activeShot,disabled:!!A,onClick:()=>we(P=>({...P,activeShot:c.id})),children:[Rt[c.id]?t.jsx("img",{src:Rt[c.id],alt:""}):t.jsx("span",{className:"shot-thumb-empty","aria-hidden":"true"}),t.jsxs("span",{className:"shot-shotlist-meta",children:[t.jsx("b",{children:c.name}),t.jsxs("small",{children:[Ai(L.start),"–",Ai(L.end)," · ",Number(c.lens.toFixed(1)),"mm"]}),c.note?.trim()&&t.jsx("small",{className:"shot-shotlist-note",children:c.note.trim()})]})]}),t.jsxs("span",{className:"shot-shotlist-order",children:[t.jsx("button",{"aria-label":a("Đưa {0} lên",[c.name]),disabled:x===0||!!A,onClick:()=>Cl(c.id,-1),children:"↑"}),t.jsx("button",{"aria-label":a("Đưa {0} xuống",[c.name]),disabled:x===z.shots.length-1||!!A,onClick:()=>Cl(c.id,1),children:"↓"})]}),t.jsx("button",{className:"shot-shotlist-delete","aria-label":a("Xóa {0}",[c.name]),title:z.shots.length<2?a("Cảnh cần ít nhất một shot"):a("Xóa {0} (hoàn tác bằng ⌘Z)",[c.name]),disabled:z.shots.length<2||!!A,onClick:()=>Sl(c.id),children:t.jsx(Ne.trash,{})})]},c.id)})})}),Q==="notes"&&t.jsx("div",{className:"shot-notes-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("button",{className:it?"active":"","aria-pressed":it,disabled:!at||$s.length>=dc,onClick:sm,children:it?a("Bấm vào cảnh để ghim… (bấm lại để huỷ)"):a("+ Ghim ghi chú vào cảnh")}),t.jsx("ol",{className:"shot-note-list",children:$s.map((c,x)=>t.jsxs("li",{children:[t.jsx("span",{children:x+1}),t.jsx("input",{"aria-label":a("Ghi chú {0}",[x+1]),value:c.text,maxLength:uc,onChange:L=>am(c.id,L.target.value)}),t.jsx("button",{"aria-label":a("Xoá ghi chú {0}",[x+1]),onClick:()=>om(c.id),children:"×"})]},c.id))}),$s.length>0&&t.jsx("button",{disabled:re||!at,onClick:()=>void ym(),children:a("Tải PNG có ghi chú")}),t.jsx("small",{className:"shot-hint",children:a("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ú.")})]})}),Q==="series"&&t.jsx("div",{className:"shot-series-section",children:t.jsx("div",{className:"shot-panel-body",children:t.jsx(nj,{stage:z,nodeId:e,selected:z.items.find(c=>c.id===J)||null,disabled:re||!!A,change:we,onError:ye,onSelect:xt})})})]}),t.jsx("div",{className:"shot-resize shot-resize-x",role:"separator","aria-orientation":"vertical","aria-label":a("Kéo để đổi độ rộng bảng công cụ"),onPointerDown:c=>gi(c,"drawer")})]}),t.jsxs("main",{className:"shot-center",children:[t.jsxs("div",{className:"shot-monitor",children:[t.jsxs("div",{className:`shot-topbar ${U?"":"collapsed"}`,children:[t.jsxs("div",{className:"shot-shot-switcher",children:[t.jsx("select",{"aria-label":a("Chọn shot"),value:de.id,onChange:c=>we(x=>({...x,activeShot:c.target.value})),children:z.shots.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))}),t.jsxs("button",{onClick:()=>{const c={...structuredClone(de),id:vt(),name:`Shot ${z.shots.length+1}`};we(x=>({...x,shots:[...x.shots,c],activeShot:c.id}))},children:[t.jsx(Ne.save,{}),t.jsx("span",{className:"lbl",children:a("+ Lưu góc mới").replace("+ ","")})]}),t.jsx(ej,{shot:de,patch:kt,disabled:re||!!A})]}),t.jsxs("div",{className:"shot-viewtools",hidden:!U,children:[_==="scale"&&ne&&!ne.locked&&t.jsx(es,{label:"Tỷ lệ đồng đều",value:ne.scale[0],min:.05,step:ce?.1:.05,onChange:c=>tt(ne.id,{scale:ne.scale.map(x=>x*c/ne.scale[0])})}),t.jsxs("span",{className:"shot-tools-hint",children:[_==="scale"?a("Kéo ô vuông trên trục để đổi kích thước."):"",ce?a(" Bước: 1 m · 15° · tỷ lệ 0,1"):""]}),["translate","rotate","scale"].map((c,x)=>t.jsxs("button",{className:c===_?"active":"",title:a(["Di chuyển","Xoay","Kích thước"][x]),onClick:()=>ee(c),children:[[t.jsx(Ne.move,{},"m"),t.jsx(Ne.rotate,{},"r"),t.jsx(Ne.scale,{},"s")][x],t.jsx("span",{className:"lbl",children:a(["Di chuyển","Xoay","Kích thước"][x])})]},c)),t.jsxs("button",{className:ce?"active":"",title:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt"),onClick:()=>Le(!ce),children:[t.jsx(Ne.snap,{}),t.jsx("span",{className:"lbl",children:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt")})]}),t.jsxs("button",{className:je==="high"?"active":"","aria-pressed":je==="high",title:je==="high"?a("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."):a("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:()=>ie(je==="high"?"draft":"high"),children:[t.jsx(Ne.cinema,{}),t.jsx("span",{className:"lbl",children:je==="high"?a("Chất lượng cao"):a("Nháp")})]}),t.jsxs("button",{className:Me?"active":"","aria-pressed":Me,title:a("Path Trace (GPU Ray Tracing): ánh sáng nảy GI, bóng mềm & phản chiếu vật lý như Blender Cycles ngay trên trình duyệt"),onClick:()=>{D(!1),Be(null),Ee(c=>!c)},children:[t.jsx(Ne.spark,{}),t.jsx("span",{className:"lbl",children:a("Path Trace")})]}),t.jsxs("button",{className:ze?"active":"","aria-pressed":!!ze,title:a("Chụp nhanh lưới 6 góc máy điện ảnh từ cảnh hiện tại để chọn góc đẹp nhất chỉ bằng 1 bấm"),onClick:()=>{if(ze){Be(null);return}const c=Ce.current;if(!c)return;D(!1),Ee(!1);const x=ij(de.target,de.position,de.lens);Be(c.renderAngleSheet(x,360,202))},children:[t.jsx(Ne.camera,{}),t.jsx("span",{className:"lbl",children:a("6 góc máy")})]}),nd()&&t.jsxs("button",{className:Ze?"active":"","aria-pressed":Ze,title:Ze?a("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."):a("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 c=!Ze;cv(c),F(c)},children:[t.jsx(Ne.person,{}),t.jsx("span",{className:"lbl",children:Ze?a("Người thật"):a("Mannequin")})]}),t.jsxs("button",{title:a("Từ trên xuống"),onClick:()=>Ce.current?.view(!0),children:[t.jsx(Ne.top,{}),t.jsx("span",{className:"lbl",children:a("Từ trên xuống")})]}),t.jsxs("button",{title:a("Tập trung (F)"),"aria-keyshortcuts":"F",onClick:()=>Ce.current?.view(),children:[t.jsx(Ne.focus,{}),t.jsx("span",{className:"lbl",children:a("Tập trung")})]})]}),t.jsx("button",{className:"shot-tools-toggle","aria-expanded":U,title:U?a("Thu gọn công cụ"):a("Mở công cụ"),onClick:()=>{const c=!U;le(c);try{localStorage.setItem("clipoox.shot.tools",c?"1":"0")}catch{}},children:U?t.jsx(Ne.chevUp,{}):t.jsx(Ne.chevDown,{})})]}),t.jsxs("div",{className:"shot-viewport",ref:$e,onDragOver:c=>{(c.dataTransfer.types.includes(wr)||c.dataTransfer.types.includes(Ro))&&(c.preventDefault(),c.dataTransfer.dropEffect="copy")},onDrop:c=>{c.dataTransfer.types.includes(Ro)?tm(c):em(c)},children:[Me&&t.jsxs("div",{className:"shot-pt-overlay",children:[t.jsx("canvas",{ref:ln,className:"shot-pt-canvas"}),t.jsxs("div",{className:"shot-pt-hud",children:[t.jsx("span",{className:"shot-pt-status",children:be.done>=be.total?a("Path Trace · Xong ({0} mẫu)",[be.total]):a("Path Trace · {0}/{1} mẫu",[be.done,be.total])}),t.jsx("button",{type:"button",onClick:()=>he(c=>c==="shot"?"viewport":"shot"),children:Se==="shot"?a("Camera Shot"):a("Góc quan sát")}),t.jsx("button",{type:"button",onClick:()=>_e(c=>c+1),children:a("Vẽ lại")}),t.jsx("button",{type:"button",onClick:()=>{const c=Qt.current?.captureDataUrl();if(!c)return;const x=document.createElement("a");x.href=c,x.download=`clipoox-pathtrace-${Date.now()}.png`,x.click()},children:a("Lưu PNG")}),t.jsx("button",{type:"button",onClick:()=>Ee(!1),children:a("Đóng")})]})]}),ze&&t.jsxs("div",{className:"shot-angles-overlay",onPointerDown:c=>c.stopPropagation(),children:[t.jsxs("div",{className:"shot-angles-head",children:[t.jsx("b",{children:a("Chọn nhanh 6 góc máy điện ảnh")}),t.jsx("button",{type:"button",onClick:()=>Be(null),children:a("Đóng")})]}),t.jsx("div",{className:"shot-angles-grid",children:ze.map(c=>t.jsxs("button",{type:"button",className:"shot-angle-card",onClick:()=>{we(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,position:[...c.camera],target:[...c.target],lens:c.lens}:L)})),Be(null)},children:[t.jsx("img",{src:c.dataUrl,alt:c.label}),t.jsxs("div",{className:"shot-angle-meta",children:[t.jsx("strong",{children:a(c.label)}),t.jsx("span",{children:a(c.subtitle)})]})]},c.id))})]})]}),t.jsx("span",{className:"shot-viewlabel",children:a("GÓC QUAN SÁT · không đổi camera xuất ảnh")}),ne&&fj(ne)&&!A&&(nn===ne.id?t.jsx(S1,{engine:at?Ce.current:null,stage:z,shot:de,item:ne,playhead:Ie*de.duration,change:we,onDone:()=>mt(null)}):t.jsxs("button",{type:"button",className:"shot-pose-chip",title:a("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:()=>{D(!1),mt(ne.id)},children:[t.jsx(Ne.person,{}),a("Chỉnh dáng")]})),ne&&Q!==(Ba(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects")&&t.jsxs("button",{type:"button",className:"shot-edit-chip",onClick:()=>Vn(Ba(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects"),children:[t.jsx(Ne.pen,{}),a("Chỉnh {0}",[ne.name])]})]}),t.jsx("div",{className:"shot-resize shot-resize-y",role:"separator","aria-orientation":"horizontal","aria-label":a("Kéo để đổi chiều cao timeline"),onPointerDown:c=>gi(c,"timeline")}),t.jsx(Yx,{loop:u,onLoop:()=>m(c=>!c),range:d,rangeOn:p,onRangeOn:()=>b(c=>!c),onEnd:()=>{D(!1),ot(1)},onKeyAll:Tl,onCopy:Ll,onPaste:El,canPaste:v,onEase:hm,onNudge:Il,stage:z,cameraActive:r,cameraHidden:k,cameraLocked:S,onToggle:lm,onProp:cm,height:ue.timeline,onHeight:c=>pe(x=>({...x,timeline:c})),shot:de,items:z.items,fxBars:nm,onParent:rm,onFxTiming:(c,x)=>we(L=>({...L,shots:L.shots.map(P=>P.id===L.activeShot?{...P,fxTiming:{...P.fxTiming,[c]:Pr({...Rn(L.items.find(B=>B.id===c),P),...x,off:!1},P.duration)}}:P)})),time:Ie,playing:H,selected:j,picked:T,onPick:Al,onSeek:c=>{D(!1),ot(c)},onPlay:()=>{!H&&Ie>=1&&ot(0),D(!H)},onRow:c=>{i(null),M(null),w([]),xt(c==="camera"?null:c),l(c==="camera"&&!S);{const x=z.items.find(L=>L.id===c);Ba(x)?Vn("mixfx"):x?.kind==="fx"&&Vn("fxedit")}},onSelect:im,onAdd:ui,onMove:um,onDelete:Rl})]}),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":a("Kéo để đổi độ rộng cột xem trước"),onPointerDown:c=>gi(c,"right")}),t.jsxs("section",{className:"shot-preview-pinned",children:[t.jsx("h3",{children:a("KHUNG CAMERA")}),t.jsx("div",{className:"shot-preview",style:{aspectRatio:Ei(de.aspect).join(" / "),width:`min(100%, ${30*Ei(de.aspect)[0]/Ei(de.aspect)[1]}dvh)`},ref:ks}),t.jsxs("div",{className:"shot-camera-player",children:[t.jsx("button",{"aria-label":H?a("Tạm dừng camera"):a("Phát camera"),onClick:()=>{!H&&Ie>=1&&ot(0),D(!H)},children:a(H?"Ⅱ Pause":"▶ Play")}),t.jsx("button",{"aria-label":a("Về đầu"),onClick:()=>{D(!1),ot(0)},children:"↤"}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(1)," / ",de.duration,a("s")]}),t.jsx("input",{"aria-label":a("Thời gian camera"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}})]}),z.plate&&t.jsxs("div",{className:"shot-plate-row",title:a("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":a("Hiện video nền"),checked:!z.plate.hidden,onChange:c=>{const x=c.target.checked;we(L=>L.plate?{...L,plate:{...L.plate,hidden:!x}}:L)}}),a("Hiện video nền")]})]}),z.plate&&t.jsxs("div",{className:"shot-plate-tools",children:[t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt||re,title:a("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 ll("follow"),children:Lt?.kind==="follow"?a("Đang đọc người… {0}%",[Lt.pct]):a("🧍 Bám theo người")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt||re,title:a("Camera của cảnh xoay / lia / zoom giống camera đã quay video."),onClick:()=>void ll("camera"),children:Lt?.kind==="camera"?a("Đang track camera… {0}%",[Lt.pct]):a("🎥 Lấy camera từ video")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt,title:a("Tải camera của shot thành script Python cho Blender, để dựng hiệu ứng khớp với video."),onClick:()=>void Gu(),children:a("⬇ Camera cho Blender")})]}),te.length>0&&t.jsxs("div",{className:"shot-placement",role:"status","aria-label":a("Cảnh báo vị trí nhân vật"),children:[t.jsx("ul",{children:te.map(c=>t.jsxs("li",{children:[t.jsxs("span",{children:["⚠ ",c.type==="floating"?a("{0} lơ lửng {1} m so với mặt đỡ",[c.name,String(c.amount)]):c.type==="sinking"?a("{0} chìm {1} m dưới mặt đỡ",[c.name,String(c.amount)]):c.type==="no_seat"?c.seat?a("{0} ngồi lơ lửng — có thể ngồi lên “{1}”",[c.name,c.seat]):a("{0} ngồi mà không có chỗ ngồi gần",[c.name]):a("{0} đang xuyên vào {1}",[c.name,(c.with||[]).join(", ")])]}),c.fix&&!c.locked&&t.jsx("button",{onClick:()=>tl([c]),children:c.type==="intersect"?a("Đẩy ra chỗ trống"):c.type==="no_seat"?a("Ngồi lên ghế gần nhất"):a("Đặt xuống mặt đỡ")})]},c.itemId+c.type))}),te.filter(c=>c.fix&&!c.locked).length>1&&t.jsx("button",{className:"shot-placement-all",onClick:()=>tl(te),children:a("Sửa tất cả ({0})",[String(te.filter(c=>c.fix&&!c.locked).length)])})]}),wl.length>0&&t.jsx("ul",{className:"shot-warnings",role:"status","aria-label":a("Cảnh báo liền mạch"),children:wl.map(c=>t.jsxs("li",{children:["⚠ ",a(c)]},c))})]}),t.jsx("section",{className:"shot-agent-card",children:t.jsx(q1,{stage:z,disabled:re||E||!!A,lock:{playhead:Math.round(Ie*de.duration*gn(de))/gn(de),onChange:c=>kt({lockUntil:o0(c,de.duration)||void 0})},agent:{selected:J,time:Ie,getBounds:()=>Ce.current?.objectBounds()||{},getColliders:()=>Ce.current?.placementColliders()||[],onPreview:(c,x)=>{D(!1);const L=$i(Ae.current,c);O({stage:L,plan:c,time:Ie,done:x}),ot(Math.min(...c.tracks.map(P=>P.keys[0].seconds))/c.duration),D(!0)},onApply:c=>{D(!1),we(x=>$i(x,c)),ot(0),i(null),M(null)}}})})]})]})]})}export{Hj as default};
287
+ `),onClick:()=>i(o==="fps"?null:"fps"),children:[u,a("fps")]}),o==="fps"&&t.jsxs("div",{className:"shot-fmt-pop",role:"menu","aria-label":a("Tốc độ khung hình (fps)"),children:[yd.map(C=>t.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u===C,className:u===C?"active":"",title:C===40?a("Đa số model video chỉ xuất 24/30 fps; {0} fps chỉ áp dụng cho video camera previs.",[C]):void 0,onClick:()=>p({fps:C}),children:[C," ",a("fps")]},C)),m.fps.map(C=>t.jsxs("p",{className:"shot-fmt-warn",role:"status",children:["⚠ ",C]},C))]})]})]})}function Tr(e,n,s){const o=_t();if(!o||!e.url)return null;const i=o.nodes().find(l=>l.type==="image"&&l.data.gcsUri===e.gcsUri);if(i)return i.id;const r=o.getNode(n);return o.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 Gh(e,n){const s=e?_t()?.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 tj(e,n,s){let o=!1;const i=e.items.map((r,l)=>{const h=r.castId?n.cast.find(m=>m.id===r.castId):void 0;if(!h)return r;const u={...r,name:h.name,color:h.color};if(r.kind==="person"&&(u.figure=h.figure?Wt(h.figure):void 0,u.look=h.look),h.reference&&(r.reference?.nodeId?_t()?.getNode(r.reference.nodeId)?.data?.gcsUri:void 0)!==h.reference.gcsUri){const d=Tr(h.reference,s,l);d&&(u.reference={nodeId:d,url:h.reference.url||"",name:h.reference.name})}return JSON.stringify(u)!==JSON.stringify(r)&&(o=!0),u});return o?{...e,items:i}:null}function nj({stage:e,nodeId:n,selected:s,disabled:o,change:i,onError:r,onSelect:l}){ct();const[h,u]=R.useState(null),[m,d]=R.useState(null),[f,p]=R.useState(""),[b,g]=R.useState(!1),v=R.useRef(null),y=e.series;R.useEffect(()=>{if(!y?.id){d(null);return}let w=!0;return pg(y.id).then(E=>{if(w&&(d(E),v.current!==E.id)){v.current=E.id;const N=tj(e,E,n);N&&i(()=>N)}}).catch(E=>r(E.message)),()=>{w=!1}},[y?.id]),R.useEffect(()=>{!y?.id&&h===null&&fg().then(w=>u(w.series)).catch(()=>u([]))},[y?.id,h]);const k=async w=>{g(!0);try{const{id:E,updatedAt:N,...A}=w;await gg(E,A),d(w)}catch(E){r(E.message)}finally{g(!1)}},C=async()=>{const w=f.trim();if(!w)return;const E={id:vt(),name:w,cast:[],locations:[],episodes:[]};await k(E),i(N=>({...N,series:{id:E.id,name:w}})),p("")},S=async()=>{if(!m||!s||!["person","model"].includes(s.kind))return;const w=s.castId&&m.cast.some(A=>A.id===s.castId)?s.castId:vt(),E=Gh(s.reference?.nodeId,s.reference?.name||s.name),N={id:w,name:s.name.slice(0,60),color:/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#baca9e",...s.kind==="person"&&s.figure?{figure:Wt(s.figure)}:{},...s.kind==="person"&&s.look?{look:s.look}:{},...E?{reference:E}:{},...s.kind==="model"&&s.model?{model:{gcsUri:s.model.gcsUri,name:s.model.name,...s.model.height?{height:s.model.height}:{}}}:{}};await k({...m,cast:[...m.cast.filter(A=>A.id!==w),N]}),i(A=>({...A,items:A.items.map(O=>O.id===s.id?{...O,castId:w}:O)})),s.reference&&!E&&r(a("Ả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=w=>{const E=e.items.length,N=w.model?{...Mn("model",E),model:w.model}:{...Mn("person",E),...w.figure?{figure:Wt(w.figure)}:{},...w.look?{look:w.look}:{}},A=w.reference?Tr(w.reference,n,E):null,O={...N,name:w.name,color:w.color,castId:w.id,...A&&w.reference?{reference:{nodeId:A,url:w.reference.url||"",name:w.reference.name}}:{}};i(H=>({...H,items:[...H.items,O]})),l(O.id)},j=async w=>{if(!m)return;const E=e.items.find(H=>H.kind==="set"&&H.set),N=(e.styleRefs||[]).flatMap(H=>{const D=Gh(H.nodeId,H.name);return D?[D]:[]}),O={id:m.locations.find(H=>H.name===w)?.id||vt(),name:w,...E?.set?{setId:E.set.id}:{},lighting:Pa(e.lighting),...N.length?{styleRefs:N}:{}};await k({...m,locations:[...m.locations.filter(H=>H.id!==O.id),O]}),i(H=>({...H,series:{...H.series,location:O.id}}))},M=w=>{const E=(w.styleRefs||[]).flatMap((N,A)=>{const O=Tr(N,n,10+A);return O?[{nodeId:O,url:N.url||"",name:N.name}]:[]});i(N=>{const A=w.setId&&N.items.some(H=>H.kind==="set"&&H.set?.id===w.setId),O=w.setId&&!A?[{...Mn("set",N.items.length),name:w.name,set:{id:w.setId,name:w.name}},...N.items]:N.items;return{...N,items:O,...w.lighting?{lighting:Pa(w.lighting)}:{},...E.length?{styleRefs:E}:{},series:{...N.series,location:w.id}}})},T=async w=>{if(!m||!w.trim())return;const E={id:vt(),name:w.trim().slice(0,80)};await k({...m,episodes:[...m.episodes,E]}),i(N=>({...N,series:{...N.series,episode:E.id}}))};return y?t.jsxs("div",{className:"shot-series",children:[t.jsxs("div",{className:"shot-series-row",children:[t.jsx("b",{children:y.name}),t.jsx("button",{disabled:o,onClick:()=>i(w=>({...w,series:void 0})),children:a("Bỏ gắn")})]}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Tập")}),t.jsxs("select",{"aria-label":a("Tập"),value:y.episode||"",disabled:o,onChange:w=>{if(w.target.value==="+"){const E=window.prompt(a("Tên tập"),`Tập ${m.episodes.length+1}`);E&&T(E);return}i(E=>({...E,series:{...E.series,episode:w.target.value||void 0}}))},children:[t.jsx("option",{value:"",children:"—"}),m.episodes.map(w=>t.jsx("option",{value:w.id,children:w.name},w.id)),t.jsx("option",{value:"+",children:a("+ Tập mới…")})]})]}),t.jsxs("h4",{children:[a("Dàn nhân vật")," · ",m.cast.length]}),t.jsx("ul",{className:"shot-series-list",children:m.cast.map(w=>t.jsxs("li",{children:[w.reference?.url?t.jsx("img",{src:w.reference.url,alt:""}):t.jsx("span",{className:"shot-series-dot",style:{background:w.color}}),t.jsxs("span",{children:[w.name,w.figure?t.jsxs("small",{children:[" · ",w.figure.height.toFixed(2)," m"]}):null]}),t.jsx("button",{"aria-label":a("Đưa {0} vào cảnh",[w.name]),disabled:o,onClick:()=>I(w),children:"+"})]},w.id))}),t.jsx("button",{disabled:o||b||!s||!["person","model"].includes(s.kind),onClick:()=>void S(),children:s?.castId?a("Cập nhật nhân vật vào series"):a("Lưu nhân vật đang chọn vào series")}),t.jsxs("h4",{children:[a("Bối cảnh")," · ",m.locations.length]}),t.jsx("ul",{className:"shot-series-list",children:m.locations.map(w=>t.jsxs("li",{className:y.location===w.id?"active":"",children:[t.jsx("span",{className:"shot-series-dot","aria-hidden":"true",children:"⌂"}),t.jsxs("span",{children:[w.name,w.setId?t.jsxs("small",{children:[" · ",a("có set")]}):null]}),t.jsx("button",{"aria-label":a("Áp dụng bối cảnh {0}",[w.name]),disabled:o,onClick:()=>M(w),children:a("Dùng")})]},w.id))}),t.jsx("button",{disabled:o||b,onClick:()=>{const w=window.prompt(a("Tên bối cảnh"),e.items.find(E=>E.kind==="set")?.name||`Bối cảnh ${m.locations.length+1}`);w?.trim()&&j(w.trim().slice(0,60))},children:a("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":a("Chọn series"),value:"",disabled:o||!h?.length,onChange:w=>{const E=h?.find(N=>N.id===w.target.value);E&&i(N=>({...N,series:{id:E.id,name:E.name}}))},children:[t.jsx("option",{value:"",children:h===null?a("Đang tải…"):h.length?a("Gắn shot vào series…"):a("Chưa có series")}),h?.map(w=>t.jsx("option",{value:w.id,children:w.name},w.id))]}),t.jsxs("form",{className:"shot-series-row",onSubmit:w=>{w.preventDefault(),C()},children:[t.jsx("input",{"aria-label":a("Tên series mới"),placeholder:a('Tên series mới, ví dụ "Chuyện quán cà phê"'),maxLength:80,value:f,onChange:w=>p(w.target.value),disabled:o||b}),t.jsx("button",{disabled:o||b||!f.trim(),children:a("Tạo")})]}),t.jsx("small",{className:"shot-hint",children:a("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.")})]})}const qh=e=>`f/${Number(e.toFixed(1))}`,sj=e=>Ko.reduce((n,s,o)=>Math.abs(Math.log(s/e))<Math.abs(Math.log(Ko[n]/e))?o:n,0),aj=()=>globalThis.crypto?.randomUUID?.()??`fk-${Math.random().toString(36).slice(2)}`;function oj({shot:e,items:n,progress:s,presetFstop:o,onChange:i}){const r=e.focus,l=r?.keys||[],h=oc(r?.fstop??o),u=n.filter(y=>y.kind!=="fx"&&y.kind!=="set"),m=y=>y?n.find(k=>k.id===y)?.name??"?":"",d=y=>i(Object.keys(y).length?y:void 0),f=y=>{const k={...r||{},...y};for(const C of Object.keys(k))k[C]===void 0&&delete k[C];d(k)},p=r?.subject?n.find(y=>y.id===r.subject):void 0,b=(()=>{if(!p)return"";const y=[p.position[0],p.position[1]+(p.kind==="person"?1.6*(p.scale?.[1]||1):.4),p.position[2]],k=Math.hypot(y[0]-e.position[0],y[1]-e.position[1],y[2]-e.position[2]),C=If(k,e.lens,h);return`${C.near.toFixed(1)}–${Number.isFinite(C.far)?`${C.far.toFixed(1)} m`:"∞"}`})(),g=()=>{const y=Math.min(1,Math.max(0,s)),k=l.find(S=>Math.abs(S.time-y)<1e-4),C={id:k?.id??aj(),time:k?.time??y,...r?.subject?{subject:r.subject}:r?.distance!==void 0?{distance:r.distance}:{},fstop:h};d({...r||{},keys:[...l.filter(S=>S!==k),C].sort((S,I)=>S.time-I.time)})},v=y=>{const k=l.filter(I=>I.id!==y),{keys:C,...S}=r||{};d(k.length?{...S,keys:k}:S)};return t.jsxs("div",{className:"shot-focus","data-testid":"shot-focus",children:[t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Lấy nét vào (shot này)")}),t.jsxs("select",{"aria-label":a("Lấy nét vào (shot này)"),value:r?.subject??"",onChange:y=>f({subject:y.target.value||void 0,distance:void 0}),children:[t.jsx("option",{value:"",children:a("Tự động (mục tiêu camera)")}),u.map(y=>t.jsx("option",{value:y.id,children:y.name},y.id))]})]}),t.jsxs("label",{className:"shot-joint",children:[a("Khẩu độ")," ",t.jsx("span",{children:qh(h)}),t.jsx("input",{"aria-label":a("Khẩu độ"),type:"range",min:0,max:Ko.length-1,step:1,value:sj(h),onChange:y=>f({fstop:Ko[+y.target.value]})})]}),t.jsx("small",{className:"shot-hint",children:b?a("Ống kính {0} mm · vùng nét {1}",[Math.round(e.lens),b]):a("Ống kính {0} mm",[Math.round(e.lens)])}),r?.fstop!==void 0&&t.jsx("button",{type:"button",onClick:()=>f({fstop:void 0}),children:a("Theo mức xoá phông")}),t.jsx("button",{type:"button",onClick:g,children:a("Thêm điểm lấy nét tại playhead")}),l.length>0&&t.jsxs("div",{className:"shot-focus-keys",role:"list","aria-label":a("Điểm lấy nét"),children:[t.jsx("small",{className:"shot-hint",children:a("Điểm lấy nét quyết định chỗ nét theo thời gian; nét được kéo mượt giữa các điểm.")}),l.map(y=>{const k=`${(y.time*e.duration).toFixed(2)}s`;return t.jsxs("div",{role:"listitem",className:"shot-focus-key",children:[t.jsxs("span",{children:[k," · ",y.subject?m(y.subject):y.distance!==void 0?`${y.distance.toFixed(1)} m`:a("Tự động")," · ",qh(oc(y.fstop??r?.fstop??o))]}),t.jsx("button",{type:"button","aria-label":a("Xoá điểm lấy nét {0}",[k]),title:a("Xoá điểm lấy nét {0}",[k]),onClick:()=>v(y.id),children:"×"})]},y.id)}),t.jsx("button",{type:"button",onClick:()=>{const{keys:y,...k}=r||{};d(k)},children:a("Xoá hết điểm lấy nét")})]})]})}const Uh=(e,n,s)=>Math.max(n,Math.min(s,e)),Jn=e=>Math.round(e*100)/100;function ij(e,n,s=45){const o=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2],l=Math.hypot(o,r),h=Uh(Math.hypot(o,i,r),1.6,60),u=l>.05?Math.atan2(o,r):.35,m=(d,f,p,b=.25)=>{const g=u+d*Math.PI/180,v=p*Math.PI/180,y=h*f,k=Math.cos(v)*y;return[Jn(e[0]+Math.sin(g)*k),Jn(Math.max(b,e[1]+Math.sin(v)*y)),Jn(e[2]+Math.cos(g)*k)]};return[{id:"wide",label:"Toàn cảnh",subtitle:"28mm · Thiết lập không gian",camera:m(-18,1.45,22),target:[...e],lens:28},{id:"hero_34",label:"Trung cảnh 3/4",subtitle:"45mm · Góc kể chuyện chuẩn",camera:m(36,1,14),target:[...e],lens:Uh(Math.round(s),35,55)},{id:"low_hero",label:"Góc thấp anh hùng",subtitle:"35mm · Tạo cảm giác uy lực",camera:m(-28,.82,-6,.3),target:[Jn(e[0]),Jn(e[1]+.15),Jn(e[2])],lens:35},{id:"closeup",label:"Cận cảnh",subtitle:"70mm · Nhấn biểu cảm & chi tiết",camera:m(12,.56,8),target:[Jn(e[0]),Jn(e[1]+.12),Jn(e[2])],lens:70},{id:"top_down",label:"Từ trên xuống",subtitle:"35mm · Toàn cục & địa hình",camera:m(0,1.38,68),target:[...e],lens:35},{id:"reverse",label:"Góc ngược vai",subtitle:"50mm · Đối thoại / kịch tính",camera:m(152,.92,12),target:[...e],lens:50}]}function rj({x:e,y:n,items:s,canPaste:o,hiddenCount:i,blenderKeys:r,renaming:l,onBlenderKeys:h,onAction:u,onRename:m,onClose:d}){const f=R.useRef(null),[p,b]=R.useState({left:e,top:n}),[g,v]=R.useState(s[0]?.name??""),y=w=>s.length>0&&s.every(w),k=s[0]?.shading,C=w=>r?w:void 0,S=s.length?[[{action:"shade-smooth",label:"Bề mặt mượt",check:"shading",checked:y(w=>w.shading==="smooth")},{action:"shade-auto",label:"Mượt tự động (30°)",check:"shading",checked:y(w=>w.shading==="auto")},{action:"shade-flat",label:"Bề mặt phẳng",check:"shading",checked:y(w=>w.shading==="flat")},...k||s.some(w=>w.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(w=>w.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:C("Shift+D"),check:"duplicate"},{action:"duplicate-linked",label:"Nhân bản liên kết",keys:C("Alt+D"),check:"duplicate"},...s.some(w=>w.link)?[{action:"unlink",label:"Bỏ liên kết",check:"unlink"}]:[]],[{action:"mirror-x",label:"Lật theo X",check:"mirror",checked:y(w=>(w.mirror?.[0]??1)<0)},{action:"mirror-y",label:"Lật theo Y",check:"mirror",checked:y(w=>(w.mirror?.[1]??1)<0)},{action:"mirror-z",label:"Lật theo Z",check:"mirror",checked:y(w=>(w.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:C("H"),check:"hide"},{action:"lock",label:y(w=>w.locked)?"Mở khoá":"Khoá",check:"lock"},{action:"delete",label:"Xoá",keys:C("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:C("A")},{action:"box-select",label:"Chọn theo vùng",keys:C("B")},{action:"unhide-all",label:"Hiện tất cả",keys:C("Alt+H")}]],I=w=>w.soon?"Sắp có":w.action==="paste"?o?null:"Chưa sao chép đối tượng nào":w.action==="unhide-all"?i?null:"Không có đối tượng nào đang ẩn":w.check?s.some(E=>!Ao(E,w.check))?null:Ao(s[0],w.check):null,j=s.length!==1?"Chọn một đối tượng để đổi tên":Ao(s[0],"rename");R.useLayoutEffect(()=>{const w=f.current;if(!w)return;const E=w.getBoundingClientRect();b({left:Math.max(4,Math.min(e,innerWidth-E.width-4)),top:Math.max(4,Math.min(n,innerHeight-E.height-4))})},[e,n,l]),R.useEffect(()=>{const w=f.current;if(!w)return;l?w.querySelector("input[type=text]")?.select():w.querySelector("[role=menuitem]:not([disabled])")?.focus();const E=N=>{w.contains(N.target)||d()};return document.addEventListener("mousedown",E,!0),()=>document.removeEventListener("mousedown",E,!0)},[l,d]);const M=w=>{if(w.key==="Escape"){w.preventDefault(),d();return}if(w.key!=="ArrowDown"&&w.key!=="ArrowUp")return;w.preventDefault();const E=[...f.current.querySelectorAll("[role=menuitem]:not([disabled]),[role=menuitemcheckbox]")],N=E.indexOf(document.activeElement);E[(N+(w.key==="ArrowDown"?1:-1)+E.length)%E.length]?.focus()},T=s.length>1?a("{0} đối tượng",[s.length]):s[0]?.name;return t.jsxs("div",{className:"shot-ctxmenu",role:"menu","aria-label":a("Menu đối tượng"),ref:f,style:p,onKeyDown:M,onContextMenu:w=>w.preventDefault(),children:[T&&t.jsx("div",{className:"shot-ctxmenu-title",children:T}),l?t.jsxs("form",{className:"shot-ctxmenu-rename",onSubmit:w=>{w.preventDefault(),g.trim()&&m(g.trim().slice(0,80))},children:[t.jsx("input",{type:"text","aria-label":a("Tên mới"),value:g,maxLength:80,onChange:w=>v(w.target.value)}),t.jsx("button",{type:"submit",children:a("Đổi tên")})]}):t.jsxs(t.Fragment,{children:[s.length>0&&t.jsxs("button",{type:"button",role:"menuitem",disabled:!!j,title:j?a(j):void 0,onClick:()=>u("rename"),children:[t.jsx("span",{children:a("Đổi tên…")}),r&&t.jsx("kbd",{children:"F2"})]}),S.map((w,E)=>t.jsx("div",{className:"shot-ctxmenu-group",role:"group",children:w.map((N,A)=>{const O=I(N);return t.jsxs("button",{type:"button",role:"menuitem",disabled:!!O,title:O?a(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?"✓ ":"",a(N.label),N.soon?t.jsxs("small",{children:[" · ",a("Sắp có")]}):null]}),N.keys&&t.jsx("kbd",{children:N.keys})]},N.action+A)})},E)),t.jsxs("button",{type:"button",className:"shot-ctxmenu-keys",role:"menuitemcheckbox","aria-checked":r,onClick:()=>h(!r),children:[t.jsxs("span",{children:[r?"☑":"☐"," ",a("Phím tắt kiểu Blender")]}),t.jsx("small",{children:"G R S · Shift+D · X · H · A · B"})]})]})]})}const lj=[{id:"above",label:"Thả từ trên cao"},{id:"here",label:"Từ vị trí hiện tại"}],cj=[{id:"bouncy",label:"Nảy nhiều"},{id:"normal",label:"Vừa"},{id:"heavy",label:"Nặng"}];function hj({count:e,start:n,left:s,busy:o,onRun:i,onClose:r}){const[l,h]=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":a("Rơi tự nhiên"),onSubmit:d=>{d.preventDefault(),!o&&s>=.25&&i(l)},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),r())},children:[t.jsx("div",{className:"shot-ctxmenu-title",children:a("Rơi tự nhiên · {0} đối tượng",[e])}),t.jsx("div",{className:"shot-seg shot-seg-2",role:"group","aria-label":a("Bắt đầu rơi"),children:lj.map(d=>t.jsx("button",{type:"button",className:l.mode===d.id?"active":"","aria-pressed":l.mode===d.id,onClick:()=>h({...l,mode:d.id}),children:a(d.label)},d.id))}),t.jsx("div",{className:"shot-seg",role:"group","aria-label":a("Độ nảy"),children:cj.map(d=>t.jsx("button",{type:"button",className:l.bounciness===d.id?"active":"","aria-pressed":l.bounciness===d.id,onClick:()=>h({...l,bounciness:d.id}),children:a(d.label)},d.id))}),t.jsxs("label",{className:"shot-drop-row",children:[a("Thời lượng")," ",t.jsxs("b",{children:[l.duration,a("s")]}),t.jsx("input",{type:"range",min:1,max:6,step:.5,value:l.duration,"aria-label":a("Thời lượng rơi"),onChange:d=>h({...l,duration:+d.target.value})})]}),t.jsx("small",{className:"shot-drop-hint",children:s<.25?a("Đầu phát đang ở cuối shot — kéo về trước rồi thử lại."):a("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:a("Huỷ")}),t.jsx("button",{type:"submit",className:"shot-primary",disabled:o||s<.25,children:o?a("Đang mô phỏng…"):a("Mô phỏng")})]})]})}ss.plateUrl=e=>vg({gcsUri:e.gcsUri,url:e.url});const Yi=[["person","Nhân vật"],["box","Hộp"],["sphere","Cầu"],["cylinder","Trụ"],["wall","Tường"],["platform","Bục"],["floor","Sàn"]],So=[["scene","Dựng cảnh",t.jsx(Ne.scene,{},"scene")],["objects","Đối tượng",t.jsx(Ne.objects,{},"objects")],["material","Vật liệu",t.jsx(Ne.material,{},"material")],["rigging","Rigging · gắn xương",t.jsx(O1,{},"rigging")],["modeling","Dựng model",t.jsx(zd,{},"modeling")],["camera","Camera & shot",t.jsx(Ne.camera,{},"camera")],["light","Ánh sáng cảnh",t.jsx(Ne.light,{},"light")],["shots","Danh sách shot",t.jsx(Ne.film,{},"shots")],["notes","Ghi chú 3D",t.jsx(Ne.note,{},"notes")],["series","Series",t.jsx(Ne.series,{},"series")],["fx","Hiệu ứng",t.jsx(Ne.fx,{},"fx")],["fxedit","Sửa hiệu ứng",t.jsx(Ne.pen,{},"fxedit")],["mixfx","Mix FX",t.jsx(Ne.mixfx,{},"mixfx")]],Qi={drawer:300,right:320,timeline:210},dj={person:t.jsx(Ne.person,{}),box:t.jsx(Ne.box,{}),sphere:t.jsx(Ne.sphere,{}),cylinder:t.jsx(Ne.cylinder,{}),wall:t.jsx(Ne.wall,{}),platform:t.jsx(Ne.platform,{}),floor:t.jsx(Ne.floor,{}),model:t.jsx(Ne.cube,{}),proxy:t.jsx(Ne.cube,{}),splat:t.jsx(Ne.image,{}),prop:t.jsx(Ne.key,{}),fx:t.jsx(Ne.fx,{})},Fo={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 es({label:e,value:n,onChange:s,min:o=-100,max:i=100,step:r=.1}){return ct(),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a(e)}),t.jsx(Sn,{"aria-label":a(e),precision:2,value:n,min:o,max:i,step:r,onCommit:s})]})}function Co({label:e,root:n,bend:s,upper:o,lower:i,onChange:r}){ct();const l=R.useRef(null),h=D0(n,s,o,i),u=o+i,m=f=>{const p=l.current.getBoundingClientRect(),b=((f.clientX-p.left)/p.width*2-1)*u,g=((f.clientY-p.top)/p.height*2-1)*u,v=O0(b,g,o,i);r(Math.round(v.root),Math.round(v.bend))},d=f=>{f.preventDefault(),m(f);const p=g=>m(g),b=()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",b)};window.addEventListener("mousemove",p),window.addEventListener("mouseup",b)};return t.jsxs("div",{children:[t.jsx("small",{children:a(e)}),t.jsx("div",{ref:l,className:"shot-ik-pad",onMouseDown:d,children:t.jsx("i",{style:{left:`${50+h.forward/u*50}%`,top:`${50+h.down/u*50}%`}})})]})}const Zi={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"},uj=(e,n)=>{if(e[n]!==void 0)return e[n];const s=n.endsWith("L")?"L":"R",o=n.slice(0,-1);return L0.includes(o)?Math.round(E0(e,s)[o]):0},mj=(e,n,s)=>bd(e,n,s);function pj(e,n){return Object.keys(Fo).every(s=>(e[s]||0)===(n[s]||0))}const Xh="clipoox.shot.objectClipboard",fj=e=>e.kind==="person"||e.kind==="model"&&e.skeleton==="native";function Hj({nodeId:e,headless:n=!1,background:s}){ct();const[o,i]=R.useState(null),[r,l]=R.useState(!1),h=R.useRef(!1),[u,m]=R.useState(!1),[d,f]=R.useState(null),[p,b]=R.useState(!1),g=R.useRef([]),[v,y]=R.useState(!1),[k,C]=R.useState(!1),[S,I]=R.useState(!1),[j,M]=R.useState(null),[T,w]=R.useState([]),[E,N]=R.useState(!1),[A,O]=R.useState(null),[H,D]=R.useState(!1),[$,W]=R.useState(!1),[z,Y]=R.useState(()=>{const c=_t()?.getNode(e)?.data.shotScene;if(c)return pc(fc(c));const x=Rf();return x.items=x.items.map((L,P)=>({...L,name:`${a(Yi.find(([B])=>B===L.kind)?.[1]||"Model")} ${P+1}`})),x}),[J,V]=R.useState(z.items[0]?.id||null),[K,G]=R.useState([]),[_,ee]=R.useState("translate"),[Q,ve]=R.useState(()=>{try{const c=localStorage.getItem("clipoox.shot.panel");return So.some(x=>x[0]===c)?c:null}catch{return null}}),[xe,q]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.railWide")==="1"}catch{return!1}}),[ue,pe]=R.useState(()=>{try{return{...Qi,...JSON.parse(localStorage.getItem("clipoox.shot.layout")||"{}")}}catch{return Qi}}),[U,le]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.tools")!=="0"}catch{return!0}}),[ce,Le]=R.useState(!1),[je,ie]=R.useState(Ff),[Me,Ee]=R.useState(!1),[Se,he]=R.useState("shot"),[be,Fe]=R.useState({done:0,total:64}),[Te,_e]=R.useState(0),[ze,Be]=R.useState(null),[Ze,F]=R.useState(Qr),[te,Z]=R.useState([]),[re,me]=R.useState(!1),[Pe,ye]=R.useState(""),[rt,It]=R.useState([]),[qt,Xe]=R.useState(null),[lt,jt]=R.useState(!1),[Ct,gt]=R.useState(1),[at,tn]=R.useState(!1),[Ie,ot]=R.useState(0),[nn,mt]=R.useState(null),[Rt,Yt]=R.useState({}),ln=R.useRef(null),Qt=R.useRef(null);R.useEffect(()=>{if(!Me){Qt.current?.dispose(),Qt.current=null;return}const c=Ce.current,x=ln.current;if(!c||!x)return;let L=!1;return Fe({done:0,total:64}),fn(async()=>{const{ShotPathTracer:P}=await import("./pathTracer-DykgPkkh.js");return{ShotPathTracer:P}},__vite__mapDeps([19,1,6])).then(({ShotPathTracer:P})=>{if(L)return;Qt.current?.dispose();const B=new P(x);Qt.current=B,B.start(c.getPathTraceSource(),{view:Se,targetSamples:64,bounces:4,onProgress:(X,se)=>{L||Fe({done:X,total:se})},onError:X=>{L||(ye(`Path Trace: ${X}`),Ee(!1))}})}),()=>{L=!0,Qt.current?.dispose(),Qt.current=null}},[Me,Se,Te,at]);const xt=c=>{V(c),G([])},cn=J?[J,...K.filter(c=>c!==J)]:[],Ft=R.useRef(cn);Ft.current=cn;const Zt=c=>{V(c[0]??null),G(c.slice(1))},bn=(c,x=!1)=>{const L=Ft.current;if(!x||!c)return Zt(c?[c]:x?L:[]);Zt(L.includes(c)?L.filter(P=>P!==c):[c,...L])},Gn=R.useRef(bn);Gn.current=bn;const[ae,ke]=R.useState(null),[Oe,Re]=R.useState(!1),He=R.useCallback(()=>ke(null),[]),[Ve,Je]=R.useState(()=>{try{return localStorage.getItem("clipoox.shot.blenderKeys")!=="0"}catch{return!0}}),Ye=c=>{Je(c);try{localStorage.setItem("clipoox.shot.blenderKeys",c?"1":"0")}catch{}},[We,et]=R.useState({on:!1}),ht=R.useRef("keys"),[it,Ke]=R.useState(!1),[Mt,$t]=R.useState(null),[Lt,hn]=R.useState(null),[qn,Un]=R.useState({mode:"all",slot:null}),Cn=R.useRef(null),bt=R.useRef(Ie);bt.current=Ie,R.useEffect(()=>{nn&&J!==nn&&mt(null)},[J,nn]);const $e=R.useRef(null),yt=R.useRef(null),yn=R.useRef(null),ks=R.useRef(null),Ce=R.useRef(null),dn=R.useRef(null),un=R.useRef(null),Pn=R.useRef(null),Ae=R.useRef(z),Dt=R.useRef([]),Kt=R.useRef([]),Et=dt(c=>c.saveError),Ht=dt(c=>c.saveState),mn=Ci(c=>c.close);Ae.current=z;const Nn=dt(c=>c.canvasId),Xn=ic(c=>c.conflict),ws=ic(c=>c.reloading);R.useEffect(()=>n||!Nn?void 0:Pf(Nn,e,c=>{const x=pc(fc(c));Dt.current=[],Kt.current=[],Ae.current=x,Y(x)}),[Nn,e,n]),$f(n?null:Nn,e,()=>dt.getState().saveState!=="saved");const we=c=>{const x=Ae.current;Dt.current.push(x),Dt.current.length>60&&Dt.current.shift(),Kt.current=[];const L={...i0(x,c(x)),revision:x.revision+1};Ae.current=L,Y(L)},Qa={getStage:()=>Ae.current,setStage:we,engine:()=>Ce.current},si=c=>{const{item:x,fingers:L}=r0(c,Ae.current.items.length),P=Mt?Ae.current.items.find(X=>X.id===Mt&&X.kind==="person"):void 0,B=P?{...x,id:P.id,name:P.name,position:P.position,rotation:P.rotation,...P.hidden?{hidden:!0}:{}}:x;we(X=>({...X,items:P?X.items.map(se=>se.id===P.id?B:se):[...X.items,B]})),xt(B.id),W(!1),$t(null),L&&B.rig&&Nc(Qa,B.id,B.rig)};R.useEffect(()=>{if(!at)return;const c=Ci.getState().fitFingers;if(!(!c||c.node!==e)){Ci.setState({fitFingers:null});for(const x of c.items){const L=Ae.current.items.find(P=>P.id===x);L?.rig&&Nc(Qa,x,L.rig)}}},[at,e]);const ai=c=>{A&&(D(!1),ot(A.time),c&&we(x=>$i(x,A.plan)),A.done(c),O(null))},tt=(c,x)=>{D(!1),we(L=>el(L,c,x))},el=(c,x,L)=>{{const P=c.shots.find(fe=>fe.id===c.activeShot),B=c.items.find(fe=>fe.id===x),X=B.kind==="fx"?B.fx?.attach:void 0;if(X&&!(X.hand&&X.tip)&&(L.position||L.rotation)){if(md(B,P)){const fe=Oo(c,x,bt.current,{position:L.position,yaw:L.rotation?.[1]});return L.scale?{...fe,items:fe.items.map(Ge=>Ge.id===x?{...Ge,scale:L.scale}:Ge)}:fe}return{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L.scale?{scale:L.scale}:{},...L.rotation?{rotation:[fe.rotation[0],L.rotation[1],fe.rotation[2]]}:{},fx:{...fe.fx,attach:{...X,...L.position?{offset:L.position}:{}}}}:fe)}}const se=P.objectKeys?.[x]||[],ge=!!L.pose&&se.some(fe=>fe.pose);if(se.length&&(L.position||L.rotation||L.scale||ge)){const fe={..._n(B,P,bt.current),...L},Ge=se,De=Ge.find(pt=>Math.abs(pt.time-bt.current)<1e-6),qe={...De,id:De?.id||vt(),time:bt.current,position:fe.position,rotation:fe.rotation,scale:fe.scale,...ge?{pose:L.pose}:{}};return{...c,shots:c.shots.map(pt=>pt.id===c.activeShot?{...pt,objectKeys:{...pt.objectKeys,[x]:[...Ge.filter(St=>St.id!==qe.id),qe].sort((St,Tn)=>St.time-Tn.time)}}:pt)}}return B.kind==="fx"&&B.fx&&L.position&&!L.fx&&(L={...L,fx:l0(B.fx,B.position,L.position)}),{...c,items:c.items.map(fe=>fe.id===x?{...fe,...L}:fe)}}},_u=(c,x)=>{const L={...Kn[x]};if(!!!Ae.current.shots.find(X=>X.id===Ae.current.activeShot)?.objectKeys?.[c.id]?.length&&!c.hold&&Ce.current){if(Ii(L)==="sit"){const X=Ce.current.sitSnap(c);if(X)return tt(c.id,{pose:L,...X})}else if(Ii(c.pose)==="sit"&&Ii(L)==="stand")return tt(c.id,{pose:L,position:Ce.current.standUp(c).position})}tt(c.id,{pose:L})},tl=c=>{const x=c.filter(L=>L.fix&&!L.locked);x.length&&(D(!1),we(L=>({...L,items:L.items.map(P=>{const B=x.find(X=>X.itemId===P.id)?.fix;return B?{...P,position:B.position,...B.rotation?{rotation:B.rotation}:{}}:P})})))},nl=c=>{D(!1),we(x=>{const L=x.shots.find(De=>De.id===x.activeShot),P=x.items.find(De=>De.id===c),B=L.objectKeys?.[c]||[],X=bt.current,se=_n(P,L,X),ge=(De,qe)=>{const pt=_n(P,L,De),St=B.find(Tn=>Math.abs(Tn.time-De)<1e-6);return{...St,id:St?.id||vt(),time:De,position:pt.position,rotation:pt.rotation,scale:pt.scale,pose:structuredClone(qe)}};let fe=[...B];if(!B.some(De=>De.pose)&&X>1e-6){const De=ge(0,P.pose);fe=[...fe.filter(qe=>qe.id!==De.id),De]}const Ge=ge(X,se.pose);return fe=[...fe.filter(De=>De.id!==Ge.id),Ge].sort((De,qe)=>De.time-qe.time),{...x,shots:x.shots.map(De=>De.id===x.activeShot?{...De,objectKeys:{...De.objectKeys,[c]:fe}}:De)}})},zu=c=>{D(!1),we(x=>{const B=(x.shots.find(X=>X.id===x.activeShot).objectKeys?.[c]||[]).map(X=>Math.abs(X.time-bt.current)<1e-6&&X.pose?(({pose:se,poseEase:ge,...fe})=>fe)(X):X);return{...x,shots:x.shots.map(X=>X.id===x.activeShot?{...X,objectKeys:{...X.objectKeys,[c]:B}}:X)}})},Bu=(c,x)=>{D(!1),we(L=>{const X=(L.shots.find(se=>se.id===L.activeShot).objectKeys?.[c]||[]).map(se=>Math.abs(se.time-bt.current)<1e-6&&se.pose?x==="smooth"?(({poseEase:ge,...fe})=>fe)(se):{...se,poseEase:x}:se);return{...L,shots:L.shots.map(se=>se.id===L.activeShot?{...se,objectKeys:{...se.objectKeys,[c]:X}}:se)}})},sl=R.useRef(null),[os,al]=R.useState(null),[la,Ku]=R.useState(1),[ol,Hu]=R.useState(!0),[il,rl]=R.useState(!1),Wu=async c=>{if(c){ye(""),rl(!0);try{if(c.size>60*1024*1024)throw new Error(a("File mocap tối đa 60 MB."));al(await c0(c.name,await c.arrayBuffer()))}catch(x){al(null),ye(x.message)}finally{rl(!1)}}},ll=async c=>{if(Lt)return;D(!1),ye(""),hn({kind:c,pct:0});const x=(L,P)=>hn({kind:c,pct:Math.round(L/P*100)});try{const L=Ae.current;if(c==="follow"){const P=L.items.find(ge=>ge.id===J&&ge.kind==="person"),B=P??L.items.find(ge=>ge.kind==="person");if(!B)throw new Error(a("Cảnh chưa có người đứng thế để bám theo."));const{followPlate:X}=await fn(async()=>{const{followPlate:ge}=await import("./plateFollow-CJUilsNV.js");return{followPlate:ge}},__vite__mapDeps([20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),se=await X(L,B.id,{newId:vt,progress:x});we(()=>se.stage),dt.getState().toast(a("{0} đã bám theo người trong video: {1}/{2} khung thấy người.",[B.name,se.found,se.frames]),"ok")}else{const{trackPlateCamera:P}=await fn(async()=>{const{trackPlateCamera:X}=await import("./plateCamera-BcdXD1uI.js");return{trackPlateCamera:X}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),B=await P(L,{newId:vt,progress:x});we(()=>B.stage),dt.getState().toast(B.mode==="travel"?a("Đã lấy camera từ video: camera đi {0} m, quay {1}°.",[B.travel,B.pan]):a("Đã lấy camera từ video: {0} key, quay {1}°.",[B.keys,B.pan]),"ok")}}catch(L){const P=L.message;ye(P==="no-person-in-plate"?a("Không thấy người trong video nền."):P==="camera-not-found"?a("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."):P)}finally{hn(null)}},Gu=async()=>{const{shotBlenderScript:c}=await fn(async()=>{const{shotBlenderScript:P}=await import("./plateCamera-BcdXD1uI.js");return{shotBlenderScript:P}},__vite__mapDeps([21,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,22,23])),x=new Blob([c(Ae.current)],{type:"text/x-python"}),L=document.createElement("a");L.href=URL.createObjectURL(x),L.download=`${(de.name||"shot").replace(/[^\w-]+/g,"_")}-camera.py`,L.click(),setTimeout(()=>URL.revokeObjectURL(L.href),4e3)},qu=c=>{if(!os)return;D(!1);const x=Ae.current,L=x.items.find(De=>De.id===c),P=x.shots.find(De=>De.id===x.activeShot),B=bt.current,X=gs(L,P,B),se=(1-B)*P.duration*la,ge=h0(os,15*la,0,Math.min(os.duration,se)).map(De=>({...De,time:De.time/la})),fe=.93*d0(L)*L.scale[1],Ge=u0(x,c,m0(ge,{position:X.position,yaw:X.rotation[1],hipHeight:fe},ol),B,vt);if(!Ge.keys){ye(a("Không còn đủ thời lượng shot sau playhead để đặt mocap."));return}we(()=>Ge.stage),dt.getState().toast(a("Đã áp mocap {0}: {1} key · {2}s",[os.name,Ge.keys,Ge.seconds]),"ok")},[oi,cl]=R.useState(!0),[ii,hl]=R.useState(!1),ri=async(c,x)=>{if(D(!1),x.mocap)try{await Dr(x.id)}catch(se){ye(a("Không tải được dữ liệu mocap: {0}",[se.message]));return}const L=Ae.current,P=L.shots.find(se=>se.id===L.activeShot),B=bt.current,X=p0(L,c,x,{start:B,newId:vt,colliders:Ce.current?.placementColliders(),camera:P.position,loop:oi,mirror:ii});if(!X.ok){ye(X.error.startsWith("not enough")?a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."):X.error);return}if(!X.keys){ye(a("Không còn đủ thời lượng shot sau playhead để đặt chuyển động."));return}we(()=>X.stage),dt.getState().toast(a('Đã áp "{0}" · {1}s',[Ra(x),X.seconds])+(X.notes.length&&na()==="vi"?` · ${X.notes[0]}`:""),"ok")},dl=(c,x,L)=>{D(!1),we(P=>{const B=ge=>(({hold:fe,...Ge})=>Ge)(ge),X=P.items.find(ge=>ge.id===c);let se=P.items.map(ge=>ge.hold?.by===c&&ge.hold.hand===x?{...B(ge),position:[X.position[0]+(x==="R"?.4:-.4),0,X.position[2]]}:ge);if(L.startsWith("item:"))se=se.map(ge=>ge.id===L.slice(5)?{...ge,hold:{by:c,hand:x}}:ge);else if(L.startsWith("prop:")){const ge=L.slice(5);se=[...se,{...Mn("prop",se.length),name:La[ge].label,prop:{kind:ge},color:"#8a939b",hold:{by:c,hand:x}}]}return{...P,items:se}})},[Uu,ul]=R.useState(""),Xu=()=>{D(!1);let c=[];we(L=>{const P=f0(L);return c=P.outcomes,P.stage});const x=L=>c.filter(P=>P.result===L).length;ul(c.length?a("{0} đòn · {1} trúng · {2} bị đỡ · {3} trượt",[c.length,x("head")+x("body"),x("blocked"),x("miss")])+(x("miss")?" — "+c.filter(L=>L.result==="miss").map(L=>a("{0}s thiếu {1} m",[L.time_s,L.gap_m])).join(", "):""):a('Chưa có đòn nào: đặt key tư thế kiểu "Ra đòn nhanh" giữa hai người.'))},Vu=()=>{D(!1),we(g0),ul("")},ml=c=>{const x=Ae.current.items.find(L=>L.id===c);!x||x.locked||re||(D(!1),we(L=>({...L,items:L.items.filter(P=>P.id!==c),shots:L.shots.map(P=>({...P,objectKeys:Object.fromEntries(Object.entries(P.objectKeys||{}).filter(([B])=>B!==c)),...P.fxTiming?{fxTiming:Object.fromEntries(Object.entries(P.fxTiming).filter(([B])=>B!==c))}:{}}))})),j?.row===c&&M(null),w(L=>L.filter(P=>P.row!==c)),xt(L=>L===c?null:L))},pl=R.useRef(""),Za=()=>{let c=pl.current;try{c=localStorage.getItem(Xh)||c}catch{}return c?x0(c):null},fl=()=>{const c=Ft.current;if(!c.length)return;const x=$0(Ae.current,c);pl.current=x,ht.current="objects";try{localStorage.setItem(Xh,x)}catch{}},gl=()=>{const c=Za();if(!c||re)return;D(!1);let x=[];we(L=>{const P=F0(L,c,vt);return x=P.ids,{...P.stage,items:P.stage.items.map(B=>x.includes(B.id)?P0(B):B)}}),Zt(x)},Ja=c=>{const x=Ft.current;if(!x.length||re)return;D(!1);let L=[];we(P=>{const B=R0(P,x,{linked:c,newId:vt});return L=B.ids,B.stage}),L.length&&Zt(L)},li=()=>{const c=Ft.current.filter(x=>!Ae.current.items.find(L=>L.id===x)?.locked);!c.length||re||(D(!1),we(x=>I0(x,c)),j&&c.includes(j.row)&&M(null),w(x=>x.filter(L=>!c.includes(L.row))),Zt(Ft.current.filter(x=>!c.includes(x))))},ci=(c,x,L)=>{c.length&&(D(!1),we(P=>({...P,items:P.items.map(B=>c.includes(B.id)?{...B,[x]:L}:B)})))},xl=()=>{const c=Ft.current;c.length&&(ci(c,"hidden",!0),Zt([]))},bl=()=>ci(Ae.current.items.filter(c=>c.hidden).map(c=>c.id),"hidden",!1),yl=()=>Zt(Ae.current.items.filter(c=>!c.hidden&&!c.locked).map(c=>c.id)),hi=c=>{const x=Ce.current,L=Ft.current.filter(P=>!Ao(Ae.current.items.find(B=>B.id===P),"origin"));!x||!L.length||(D(!1),we(P=>L.reduce((B,X)=>{if(c==="reset")return mc(B,X,null,!0);const se=x.builtBounds(X),ge=B.items.find(De=>De.id===X);if(!se||!ge)return B;const fe=ge.origin||[0,0,0],Ge=[(se.min[0]+se.max[0])/2,c==="bottom"?se.min[1]:(se.min[1]+se.max[1])/2,(se.min[2]+se.max[2])/2];return mc(B,X,Ge.map((De,qe)=>De-fe[qe]))},P)))},vl=()=>{const c=Ft.current;if(c.length===1)return ui(c[0]);if(!c.length)return;const x=bt.current;D(!1),we(L=>{const P=L.shots.find(X=>X.id===L.activeShot),B={...P.objectKeys};for(const X of c){const se=L.items.find(qe=>qe.id===X);if(!se||se.locked||se.hold||se.kind==="fx"&&se.fx?.attach)continue;const ge=_n(se,P,x),fe=B[X]||[],Ge=fe.find(qe=>Math.abs(qe.time-x)<1e-6),De={...Ge,id:Ge?.id||vt(),time:x,position:ge.position,rotation:ge.rotation,scale:ge.scale};B[X]=[...fe.filter(qe=>qe.id!==De.id),De].sort((qe,pt)=>qe.time-pt.time)}return{...L,shots:L.shots.map(X=>X.id===L.activeShot?{...X,objectKeys:B}:X)}})},di=(c,x,L)=>{re||A||(c&&!Ft.current.includes(c)&&bn(c),ke({x,y:L,scene:!c}))},jl=R.useRef(di);jl.current=di;const Yu=()=>{const c=$e.current?.getBoundingClientRect();ke({x:c?c.left+c.width/2-110:200,y:c?c.top+c.height/3:200,renaming:!0})},Qu=c=>{const x=Ft.current;if(c==="rename"){ke(L=>L&&{...L,renaming:!0});return}switch(ke(null),c){case"shade-smooth":case"shade-auto":case"shade-flat":case"shade-reset":{const L=c==="shade-reset"?null:c.slice(6);D(!1),we(P=>v0(P,x,L));return}case"origin-center":return hi("center");case"origin-bottom":return hi("bottom");case"origin-reset":return hi("reset");case"copy":return fl();case"paste":return gl();case"duplicate":return Ja(!1);case"duplicate-linked":return Ja(!0);case"unlink":D(!1),we(L=>y0(L,x));return;case"mirror-x":case"mirror-y":case"mirror-z":D(!1),we(L=>b0(L,x,c.slice(7)));return;case"key":return vl();case"physics-drop":D(!1),Re(!0);return;case"hide":return xl();case"lock":return ci(x,"locked",!x.every(L=>Ae.current.items.find(P=>P.id===L)?.locked));case"delete":return li();case"rig":{const L=x.find(P=>Ae.current.items.find(B=>B.id===P)?.kind==="model");L&&(xt(L),Vn("rigging"));return}case"select-all":return yl();case"unhide-all":return bl();case"box-select":return et({on:!0})}},Zu=async c=>{const x=Ae.current,L=x.shots.find(qe=>qe.id===x.activeShot),P=bt.current,B=Ft.current,X=await fn(()=>import("./sceneTrack-DlAH5s74.js").then(qe=>qe.$),__vite__mapDeps([10,1])),se=B.map(qe=>x.items.find(pt=>pt.id===qe)).filter(qe=>!!qe&&!X.dropUnavailable(qe)&&!(qe.kind==="prop"&&qe.prop?.kind==="ball"&&L.ball?.[qe.id]?.length)).slice(0,X.MAX_PHYSICS_BODIES);if(!se.length){Re(!1),ye(a("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 ge=P,fe=Math.min(c.duration,(1-ge)*L.duration),Ge=Ce.current,De=se.map(qe=>qe.id);me(!0),ye("");try{const qe=Ge?.physicsShapes(De)??{},pt=(Ge?.placementColliders()??[]).filter(Ot=>!De.includes(Ot.itemId)),St=Object.fromEntries(se.map(Ot=>[Ot.id,(L.objectKeys?.[Ot.id]||[]).filter(sn=>sn.time<ge-1e-6).sort((sn,Cs)=>sn.time-Cs.time).pop()])),Tn=se.map(Ot=>{const sn=_n(Ot,L,ge);return{id:Ot.id,position:sn.position,rotation:sn.rotation,shape:X.shapeKind(Ot),...qe[Ot.id]??X.fallbackShape(Ot)}}),Ut=await X.bakeDrop({bodies:Tn,statics:pt,mode:c.mode,bounciness:c.bounciness,duration:fe,start:ge*L.duration,shotDuration:L.duration,seed:De.join(","),before:St,seam:L.lockUntil?L.lockUntil/L.duration:null}),vn=Object.fromEntries(se.map(Ot=>[Ot.id,_n(Ot,L,ge).scale]));we(Ot=>X.applyDropKeys(Ot,L.id,Ut.tracks,{scale:vn,newId:vt,lifted:c.mode==="above"})),Re(!1)}catch(qe){ye(a("Không mô phỏng được: {0}",[qe.message]))}finally{me(!1)}},Ju=c=>{const x=c.code;return c.shiftKey&&!c.altKey&&x==="KeyD"?(Ja(!1),!0):c.altKey&&!c.shiftKey&&x==="KeyD"?(Ja(!0),!0):c.altKey&&!c.shiftKey&&x==="KeyH"?(bl(),!0):c.altKey&&!c.shiftKey&&x==="KeyA"?(Zt([]),!0):c.altKey||c.shiftKey?!1:x==="KeyG"||x==="KeyR"||x==="KeyS"&&!r?(ee(x==="KeyG"?"translate":x==="KeyR"?"rotate":"scale"),!0):x==="KeyX"?(Q==="rigging"&&Cn.current?.del()||li(),!0):x==="KeyH"?(xl(),!0):x==="KeyA"?(yl(),!0):x==="KeyB"?(et({on:!0}),!0):x==="F2"&&Ft.current.length===1?(Yu(),!0):!1},eo=(c=!1)=>{const x=c?Kt.current:Dt.current,L=c?Dt.current:Kt.current,P=x.pop();P&&(L.push(Ae.current),Ae.current=P,Y(P))};R.useEffect(()=>{ju()},[]),R.useEffect(()=>{Ce.current?.setPlatePlaying(H)},[H]),R.useEffect(()=>{fn(()=>import("./videoExport-NN-QijHd.js"),__vite__mapDeps([24,2,3,4,5,1,6,7,8,9,10,11,12,13,14,15,16,25,26,27])).catch(()=>{})},[]),R.useEffect(()=>{try{Ce.current=new ss($e.current,ks.current,(c,x)=>Gn.current(c,x),(c,x)=>tt(c,x),xg,ye,c=>bg(c).then(x=>x.recipe)),Ce.current.onContext=(c,x,L)=>jl.current(c,x,L),Ce.current.commitMany=c=>{D(!1),we(x=>c.reduce((L,P)=>el(L,P.id,P.patch),x))},Ce.current.setCameraEditor({select:c=>{l(c&&!h.current),c&&(xt(null),i(null),ee(x=>x==="scale"?"translate":x))},commit:c=>wt(c)}),Ce.current.sync(Ae.current,J),tn(!0)}catch(c){ye(`Không khởi tạo được 3D: ${c.message}`)}return()=>Ce.current?.dispose()},[]),R.useEffect(()=>{Ce.current?.sync(A?.stage||z,A?null:J,A?[]:K)},[z,J,K,A]),R.useEffect(()=>{const c={getStage:()=>Ae.current,setStage:P=>{D(!1),we(P)},engine:()=>Ce.current,timelineClip:P=>dt.getState().clips.find(B=>B.id===P),undo:(P,B)=>{let X=0;for(let se=0;se<B;se++){const ge=Ae.current;if(eo(P),Ae.current===ge)break;X++}return X},...n?{}:{exportVideo:async P=>{const B=Ce.current;if(!B)throw new Error("3D chưa sẵn sàng");B.sync(Ae.current,null),me(!0),ye("");try{const{blob:X,cleanup:se}=await B.exportVideo({...P,signal:new AbortController().signal,progress:()=>{}});try{return dn.current=null,un.current=null,Pn.current=null,await fi(X,P,"canvas"),{nodeId:dn.current||void 0,url:un.current||void 0,gcsUri:Pn.current||void 0}}finally{await se()}}finally{me(!1)}},exportVfx:async P=>{me(!0),ye("");try{return await pi(P)}finally{me(!1)}},exportFrame:P=>is(!0,Ae.current.shots.find(B=>B.id===Ae.current.activeShot),0,!0,P)}};if(s){vc().then(P=>rc(!!P?.allowed)).catch(()=>{}),s({ready:()=>!!Ce.current,run:(P,B)=>Df(P,B,c),exportVfx:(P,B,X)=>pi(P,B,X)});return}if(_0(c,async()=>{const P=Ce.current;if(!P)throw new Error("3D chưa sẵn sàng");const B=Ae.current,X=B.shots.find(se=>se.id===B.activeShot);P.sync(B,null),me(!0),ye("");try{const se={start:0,end:X.duration,fps:gn(X),height:720},{blob:ge,cleanup:fe}=await P.exportVideo({...se,signal:new AbortController().signal,progress:()=>{}});try{return dn.current=null,un.current=null,Pn.current=null,await fi(ge,se,"canvas"),{nodeId:dn.current||void 0,url:un.current||void 0,gcsUri:Pn.current||void 0}}finally{await fe()}}finally{me(!1)}}),n)return()=>lc(c);n||vc().then(P=>rc(!!P?.allowed)).catch(()=>{});const x=Of(()=>Ae.current.shots.find(P=>P.id===Ae.current.activeShot)?.name||"3D Shot"),L=Q1(c,()=>Ae.current.shots.find(P=>P.id===Ae.current.activeShot)?.name||"3D Shot",P=>{const B=Ae.current.shots.find(X=>X.id===Ae.current.activeShot)?.duration||1;D(!1),ot(Math.max(0,Math.min(1,P/B))),setTimeout(()=>D(!0),50)},()=>{const P=dt.getState().canvasId;return P?`shot:${P}:${e}`:null});return()=>{x(),L(),lc(c)}},[]),R.useEffect(()=>{_t()?.updateNodeData(e,{shotScene:z})},[z,e]),R.useEffect(()=>{h.current=S,S&&l(!1)},[S]),R.useEffect(()=>Ce.current?.setCameraHidden(k),[k,at]),R.useEffect(()=>Ce.current?.mode(_,ce),[_,ce,r]),R.useEffect(()=>{J&&l(!1)},[J]),R.useEffect(()=>{Ce.current?.setCameraSelected(r&&!J&&!A)},[r,J,A,at]),R.useEffect(()=>{Ce.current&&(Ce.current.cameraTip=a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"))},[at,na()]),R.useEffect(()=>Ce.current?.setQuality(je),[je,at]),R.useEffect(()=>{if(!at||Q!=="shots"||re||A)return;let c=!0,x,L=0;const P=()=>{const B=Ce.current;!B||!c||B.shotThumbnails(Ae.current.shots).then(X=>{c&&Yt(X)}).catch(X=>{c&&++L<8?x=setTimeout(P,1500):console.warn("[shot] thumbnails failed:",X?.message)})};return x=setTimeout(P,900),()=>{c=!1,clearTimeout(x)}},[z.revision,at,Q,re,A]),R.useEffect(()=>Ce.current?.setPreviewProgress(Ie),[Ie]),R.useEffect(()=>{if(!at||A)return;const c=()=>{const P=Ce.current,B=Ae.current;if(!P)return;const X=B.shots.find(ge=>ge.id===B.activeShot),se=new Set(Object.entries(X?.objectKeys||{}).filter(([,ge])=>ge.length).map(([ge])=>ge));try{Z(j0(B,{colliders:P.placementColliders(),keyed:se}))}catch{Z([])}},x=setTimeout(c,350),L=setTimeout(c,2500);return()=>{clearTimeout(x),clearTimeout(L)}},[z.revision,at,A]),R.useEffect(()=>{const c=x=>{if(A){x.key==="Escape"&&(x.preventDefault(),ai(!1)),!x.target.closest(".shot-trial-controls")&&x.key!=="Tab"&&x.stopImmediatePropagation();return}if(x.target.closest(".shot-ctxmenu")||x.target.closest(".shot-playhead-handle")&&["ArrowLeft","ArrowRight","Home","End",",","."].includes(x.key))return;const L=x.target.closest(".shot-fmt");if(!(L&&(["Enter","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End"].includes(x.key)||x.key==="Escape"&&L.querySelector(".shot-fmt-pop"))||(x.stopImmediatePropagation(),x.target.closest('input,textarea,select,[contenteditable="true"],[role="textbox"]')||re))){if((x.metaKey||x.ctrlKey)&&x.key.toLowerCase()==="z")x.preventDefault(),eo(x.shiftKey);else if((x.key==="Delete"||x.key==="Backspace")&&(j||T.length)&&x.target.closest(".shot-timeline"))x.preventDefault(),Rl();else if((x.key==="Delete"||x.key==="Backspace")&&x.target.closest?.(".shot-shotlist li"))x.preventDefault(),Sl(x.target.closest(".shot-shotlist li").dataset.shot);else if((x.key==="Delete"||x.key==="Backspace")&&Q==="rigging"&&Cn.current?.del())x.preventDefault();else if((x.key==="Delete"||x.key==="Backspace")&&!E&&J&&!Ce.current?.transform.object?.userData.cameraKey)x.preventDefault(),li();else if((x.metaKey||x.ctrlKey)&&!x.altKey&&["c","v"].includes(x.key.toLowerCase())){const B=!!x.target.closest(".shot-timeline");x.key.toLowerCase()==="c"?B||Ms.length?(x.preventDefault(),Ll()):cn.length&&!E&&(x.preventDefault(),fl()):B||g.current.length&&(ht.current==="keys"||!Za())?g.current.length&&(x.preventDefault(),El()):!E&&Za()&&(x.preventDefault(),gl())}else if(!E&&!x.metaKey&&!x.ctrlKey&&!x.altKey&&!x.shiftKey&&x.code==="KeyF")x.preventDefault(),Ce.current?.view();else if(Ve&&!E&&!x.metaKey&&!x.ctrlKey&&Ju(x))x.preventDefault();else if(x.altKey&&(x.code==="Comma"||x.code==="Period"))x.preventDefault(),Il(x.code==="Period"?1:-1);else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&x.key.toLowerCase()==="k"){const B=j?.row??J??(r?"camera":null);x.shiftKey?(x.preventDefault(),Tl()):!j&&cn.length>1?(x.preventDefault(),vl()):B&&(x.preventDefault(),ui(B))}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&["l","i","o"].includes(x.key.toLowerCase())){x.preventDefault();const B=x.key.toLowerCase();B==="l"?m(X=>!X):dm(B==="i"?"in":"out")}else if(!x.metaKey&&!x.ctrlKey&&!x.altKey&&!E&&(x.key===" "||x.key===","||x.key==="."||x.key==="Home"||x.key==="End"))if(x.preventDefault(),x.key===" ")D(B=>(!B&&Ie>=1&&ot(0),!B));else{D(!1);const B=z.shots.find(se=>se.id===z.activeShot),X=gn(B);ot(x.key==="Home"?0:x.key==="End"?1:Math.max(0,Math.min(1,(Math.round(Ie*B.duration*X)+(x.key==="."?1:-1))/X/B.duration)))}else if(r&&!E&&["w","e"].includes(x.key.toLowerCase())&&!x.metaKey&&!x.ctrlKey&&!x.altKey)x.preventDefault(),ee(x.key.toLowerCase()==="w"?"translate":"rotate");else if(x.key==="Escape"){if(nn){mt(null);return}if(We.on){et({on:!1});return}if(ae){ke(null);return}if(Q==="rigging"&&Cn.current?.esc())return;r&&!E?l(!1):E?N(!1):Q?Vn(null):mn()}}};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)},[mn,re,E,J,K,j,T,z,A,Q,r,Ie,d,Ve,We.on,ae,nn]);const de=(A?.stage||z).shots.find(c=>c.id===z.activeShot),kl=z.items.find(c=>c.id===J),ne=kl?_n(kl,de,Ie):void 0;R.useEffect(()=>{re&&D(!1)},[re]),R.useEffect(()=>{D(!1),ot(0),i(null),M(null),w([])},[z.activeShot]);const em=c=>{const x=ud(c.dataTransfer.getData(wr)),L=Ce.current;if(!x||!L||re)return;c.preventDefault();const P=L.pointerTarget(c.clientX,c.clientY),B=Ae.current,X=B.shots.find(ge=>ge.id===B.activeShot),se=vu(B,x,{selected:P.id??J,ground:P.ground,start:bt.current*X.duration,label:a(x.name),anchor:(ge,fe,Ge)=>L.partPointAt(X,Ge,ge,fe)});if("error"in se){ye(a("Cảnh đã có quá nhiều hiệu ứng hoặc hạt (tối đa {0} hiệu ứng).",[24]));return}ye(""),D(!1),we(()=>se.stage),xt(se.item.id),Vn("fx")},tm=c=>{const x=Ha(c.dataTransfer.getData(Ro)),L=Ce.current;if(!x||!L||re)return;c.preventDefault();const P=L.pointerSlot(c.clientX,c.clientY),B=P&&Ae.current.items.find(se=>se.id===P.id);if(!P||!B||!Ia(B)){ye(a("Thả vật liệu lên một đối tượng trong cảnh."));return}if(B.locked){ye(a("{0} đang khoá — mở khoá ở timeline để đổi vật liệu.",[B.name]));return}const X=qn.mode==="part"&&L.materialSlots(B.id).length>1;ye(""),D(!1),we(se=>Gs(se,B.id,X?P.slot:"*",{preset:x.id})),xt(B.id),X&&Un({mode:"part",slot:P.slot})},nm=Object.fromEntries(z.items.flatMap(c=>{if(c.kind!=="fx"||!c.fx)return[];const x=Fn(c,de);return x.off?[]:[[c.id,{start:x.start,duration:x.duration}]]})),wl=_f(A?.stage||z),kt=Pa(z.lighting),Ml=zf(z.shots),An=c=>we(x=>({...x,lighting:Pa({...Pa(x.lighting),...c})})),$s=z.notes||[],ca=z.styleRefs||[],sm=()=>{const c=Ce.current;if(c){if(it){c.setNotePlacer(null),Ke(!1);return}Ke(!0),c.setNotePlacer(x=>{Ke(!1),we(L=>({...L,notes:[...L.notes||[],{id:vt(),text:a("Ghi chú"),position:x}].slice(0,dc)}))})}},am=(c,x)=>we(L=>({...L,notes:(L.notes||[]).map(P=>P.id===c?{...P,text:x.slice(0,uc)}:P)})),om=c=>we(x=>({...x,notes:(x.notes||[]).filter(L=>L.id!==c)})),Sl=c=>we(x=>{if(x.shots.length<2)return x;const L=x.shots.findIndex(B=>B.id===c);if(L<0)return x;const P=x.shots.filter(B=>B.id!==c);return{...x,shots:P,activeShot:x.activeShot===c?P[Math.min(L,P.length-1)].id:x.activeShot}}),Cl=(c,x)=>we(L=>{const P=L.shots.findIndex(se=>se.id===c),B=P+x;if(P<0||B<0||B>=L.shots.length)return L;const X=[...L.shots];return[X[P],X[B]]=[X[B],X[P]],{...L,shots:X}});R.useEffect(()=>{if(!H)return;const c=p&&d?d.in:0,x=p&&d?d.out:1;let L=0,P=performance.now(),B=Ie;(B<c||B>=x)&&(B=c);const X=Bf(de),se=Math.max(.1,de.duration),ge=X?Ni(de,c*se):0,fe=X?Ni(de,x*se):0;let Ge=X?Ni(de,B*se):0;const De=qe=>{const pt=(qe-P)/1e3;if(P=qe,X){if(Ge+=pt,Ge>=fe)if(u)Ge=ge+(Ge-fe)%Math.max(1e-6,fe-ge);else{Ce.current?.setOutputClock(null),ot(x),D(!1);return}Ce.current?.setOutputClock(Ge),ot(k0(de,Ge).scene/se),L=requestAnimationFrame(De);return}if(B+=pt/se,B>=x)if(u)B=c+(B-x)%Math.max(1e-6,x-c);else{ot(x),D(!1);return}ot(B),L=requestAnimationFrame(De)};return L=requestAnimationFrame(De),()=>{cancelAnimationFrame(L),Ce.current?.setOutputClock(null)}},[H,de.duration,de.timing,z.activeShot,u,p,d]);const to=(_t()?.nodes()||[]).filter(c=>c.type==="image"&&c.id!==e&&c.data.url),wt=c=>{D(!1),we(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,...c}:L)}))},Nl=c=>wt(sr(c)),im=(c,x)=>{const L=(c==="camera"?de.cameraKeys:de.objectKeys?.[c])?.find(P=>P.id===x);L&&(D(!1),ot(L.time),M({row:c,id:x}),w([]),i(c==="camera"?x:null),xt(c==="camera"?null:c))},Al=c=>{D(!1),w(c),M(c.length===1?c[0]:null),i(c.length===1&&c[0].row==="camera"?c[0].id:null)},ui=c=>{if(c==="camera"){const x=de.motion==="path"?de.cameraKeys||[]:[],L=x.find(X=>Math.abs(X.time-Ie)<1e-6),P=Yh(de,Ie),B={id:L?.id||vt(),time:Ie,position:P.position,target:P.target,lens:P.lens,roll:P.roll};Nl([...x.filter(X=>X.id!==B.id),B]),i(B.id),M({row:c,id:B.id}),xt(null)}else{const x=z.items.find(se=>se.id===c);if(!x||x.locked)return;if(x.kind==="fx"&&x.fx?.attach){const se=x.fx.attach.keyed?(de.objectKeys?.[c]||[]).find(fe=>Math.abs(fe.time-Ie)<1e-6):void 0,ge=se?.id||vt();we(fe=>Oo(fe,c,Ie,{id:ge})),i(null),xt(c),M({row:c,id:ge});return}const L=_n(x,de,Ie),P=de.objectKeys?.[c]||[],X={id:P.find(se=>Math.abs(se.time-Ie)<1e-6)?.id||vt(),time:Ie,position:L.position,rotation:L.rotation,scale:L.scale};wt({objectKeys:{...de.objectKeys,[c]:[...P.filter(se=>se.id!==X.id),X].sort((se,ge)=>se.time-ge.time)}}),i(null),xt(c),M({row:c,id:X.id})}},rm=(c,x)=>we(L=>{const P=L.items.find(fe=>fe.id===c);if(!P?.fx||P.locked||(P.fx.attach?.to??"")===x)return L;const B=P.fx.attach,X=x?{to:x,...B?.part?{part:B.part}:{},...B?.follow?{follow:B.follow}:{}}:void 0,se=B?.keyed?L.shots.map(fe=>fe.objectKeys?.[c]?{...fe,objectKeys:Object.fromEntries(Object.entries(fe.objectKeys).filter(([Ge])=>Ge!==c))}:fe):L.shots,ge=x?L.items.find(fe=>fe.id===x):null;return{...L,shots:se,items:L.items.map(fe=>fe.id===c?{...fe,...!x&&B?{position:[...L.items.find(Ge=>Ge.id===B.to)?.position??fe.position]}:{},...ge?{position:[...ge.position]}:{},fx:{...P.fx,attach:X}}:fe)}}),lm=(c,x)=>{if(c==="camera"){x==="hidden"?C(L=>!L):I(L=>!L);return}D(!1),we(L=>({...L,items:L.items.map(P=>P.id===c?{...P,[x]:!P[x]}:P)})),(x==="hidden"||x==="locked")&&xt(L=>L===c&&!z.items.find(P=>P.id===c)?.[x]?null:L)},cm=(c,x,L)=>{D(!1),we(P=>Cg(P,c,x,Ie,L))},Ms=T.length?T:j?[j]:[],Tl=()=>{D(!1),we(c=>Ng(c,Ie))},Ll=()=>{g.current=Ag(Ae.current,Ms),y(g.current.length>0),ht.current="keys"},El=()=>{if(!g.current.length)return;D(!1);let c=[];we(x=>{const L=Tg(x,g.current,Ie);return c=L.pasted,L.stage}),c.length&&Al(c)},hm=c=>{Ms.length&&we(x=>Lg(x,Ms,c))},Il=c=>{if(!Ms.length)return;const x=c/(gn(de)*de.duration);wc(Ae.current,Ms,x).moved&&(D(!1),we(L=>wc(L,Ms,x).stage))},dm=c=>{const x=Ie;f(L=>c==="in"?{in:x,out:L&&L.out>x?L.out:1}:{in:L&&L.in<x?L.in:0,out:x}),b(!0)},um=(c,x,L)=>{if(!((c==="camera"?de.cameraKeys:de.objectKeys?.[c])||[]).some(B=>B.id!==x&&Math.abs(B.time-L)<1e-6)){if(c==="camera")Nl((de.cameraKeys||[]).map(B=>B.id===x?{...B,time:L}:B));else{if(z.items.find(B=>B.id===c)?.locked)return;wt({objectKeys:{...de.objectKeys,[c]:(de.objectKeys?.[c]||[]).map(B=>B.id===x?{...B,time:L}:B).sort((B,X)=>B.time-X.time)}})}ot(L)}},Rl=()=>{const c=[...T,...j&&!T.some(X=>X.row===j.row&&X.id===j.id)?[j]:[]];if(!c.length)return;const x=X=>new Set(c.filter(se=>se.row===X).map(se=>se.id)),L={...de.objectKeys};let P=!1;for(const X of new Set(c.map(se=>se.row)))if(X!=="camera"&&!z.items.find(se=>se.id===X)?.locked){const se=x(X);L[X]=(L[X]||[]).filter(ge=>!se.has(ge.id)),P=!0}const B=c.some(X=>X.row==="camera")?sr((de.cameraKeys||[]).filter(X=>!x("camera").has(X.id))):{};wt({...B,...P?{objectKeys:L}:{}}),i(null),M(null),w([])},mm=c=>{D(!1),wt(w0(de,c)),c!=="path"&&ot(c==="static"?0:1)},Fl=async c=>{try{const x=await yg("model",c);It(L=>c?[...L,...x.assets]:x.assets),Xe(x.nextCursor)}catch(x){ye(x.message)}},pm=async c=>{if(c){if(ye(""),!c.name.toLowerCase().endsWith(".glb")||c.size>50*1024*1024){ye("Chọn file GLB tối đa 50 MB.");return}jt(!0);try{const x=new DataView(await c.slice(0,12).arrayBuffer());if(x.byteLength<12||x.getUint32(0,!0)!==1179937895||x.getUint32(4,!0)!==2)throw new Error("File không phải GLB 2.0 hợp lệ");const L=await c.arrayBuffer(),P=new DataView(L);if(P.byteLength<20||P.getUint32(8,!0)!==L.byteLength||P.getUint32(16,!0)!==1313821514)throw new Error("Cấu trúc GLB không hợp lệ");const B=P.getUint32(12,!0);if(20+B>L.byteLength)throw new Error("File GLB bị thiếu dữ liệu");const X=JSON.parse(new TextDecoder().decode(new Uint8Array(L,20,B)));if([...X.buffers||[],...X.images||[]].some(fe=>fe.uri&&!fe.uri.startsWith("data:")))throw new Error("Hãy xuất GLB với texture và dữ liệu nhúng trong file.");const{gcsUri:se}=await Us(new File([c],c.name,{type:"model/gltf-binary"})),ge={...Mn("model",Ae.current.items.length),name:c.name,model:{gcsUri:se,name:c.name}};we(fe=>({...fe,items:[...fe.items,ge]})),xt(ge.id)}catch(x){ye(x.message)}finally{jt(!1)}}},Pl=(c,x)=>{const L={...Mn("splat",Ae.current.items.length),name:c,position:[0,0,0],color:"#9aa3a8",splat:x};we(P=>({...P,items:[...P.items,L]})),xt(L.id)},fm=async c=>{if(!c)return;ye("");const x=c.name.split(".").pop()?.toLowerCase()||"";if(!M0.includes(x)||c.size>S0){ye(a("Chọn file bản quét .spz, .ply, .splat, .ksplat hoặc .sog tối đa 300 MB."));return}jt(!0);try{const{gcsUri:L}=await Us(new File([c],c.name,{type:"application/x-gaussian-splat"}));Pl(c.name.replace(/\.[^.]+$/,""),{name:c.name,gcsUri:L,source:"scan",flip:!0})}catch(L){ye(L.message)}finally{jt(!1)}},mi=(_t()?.nodes()||[]).filter(c=>c.type==="world"&&typeof c.data.splatUrl=="string"),gm=c=>{const x=Array.from({length:c==="person"?Ct:1},(L,P)=>({...Mn(c,z.items.length+P),name:`${a(Yi.find(([B])=>B===c)?.[1]||"Model")} ${z.items.length+P+1}`}));we(L=>({...L,items:[...L.items,...x]})),xt(x[0].id)};async function pi(c,x,L){const P=Ce.current;if(!P)throw new Error("3D chưa sẵn sàng");const B=structuredClone(Ae.current);P.sync(B,null);const X=await B1(P,B,e,c,{signal:L,progress:x}),se=H1(X,B.plate?.timelineClipId);return dn.current=X.at(-1)?.nodeId||null,un.current=X.at(-1)?.url||null,se}async function fi(c,x,L){const P=structuredClone(Ae.current),B=P.shots.find(St=>St.id===P.activeShot),X=dt.getState().canvasId,se=new File([c],`${B.name}-camera.mp4`,{type:"video/mp4"}),{url:ge,gcsUri:fe}=await Us(se,void 0,"video");un.current=ge,Pn.current=fe||null;const Ge=_t()?.getNode(e);if(!Ge||dt.getState().canvasId!==X)throw new Error("Canvas đã thay đổi. Video đã lưu trong Tài sản của tôi.");const De=x.end-x.start,qe=`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.`,pt=_t()?.addNode("video",{url:ge,gcsUri:fe,label:`${B.name} · Camera ref`,duration:De,ratio:B.aspect,status:"succeeded",shotSourceId:e,shotId:B.id,shotRevision:P.revision,cameraVideo:{...x},prompt:qe},{x:Ge.position.x+380,y:Ge.position.y},{sourceIds:[e]});if(dn.current=pt||null,L==="timeline"){if(!pt)throw new Error("Không tạo được video trên Canvas");const St=dt.getState(),Tn=Ge.data?.timelineClipId,Ut=St.clips.find(sn=>sn.id===Tn);if(!Ut)throw new Error("Clip 3D gốc không còn trên Timeline. Video đã lưu vào Canvas.");if(St.timelineTracks[Ut.track]?.locked)throw new Error("Track đã khóa. Video đã lưu vào Canvas.");const vn=Ut.kind==="model"?Ut:Ut.from3D?.clip,Ot={id:crypto.randomUUID(),nodeId:pt,track:Ut.track,start:Ut.start,duration:Math.max(1/30,Math.min(Ut.duration,Math.floor(De*30)/30)),sourceDuration:De,inPoint:0,volume:1,url:ge,gcsUri:fe,kind:"video",label:`${Ut.label.replace(/ · 3D$/,"")} · 3D`,...Ut.zIndex!==void 0?{zIndex:Ut.zIndex}:{},...vn?{from3D:{shotNodeId:e,clip:vn}}:{}};St.setClips(sn=>sn.map(Cs=>Cs.id===Ut.id?Ot:Cs)),St.setTimelineMedia(sn=>sn.some(Cs=>Cs.source==="canvas"&&Cs.id===pt)?sn:[...sn,{id:pt,source:"canvas",kind:"video",url:ge,gcsUri:fe,label:Ot.label,duration:De}]),_t()?.updateNodeData(e,{timelineClipId:Ot.id}),mn(),St.setView("timeline"),St.toast(a("Đã đưa video 3D về Timeline, thay đúng chỗ clip model"),"ok");return}dt.getState().toast(a("Đã lưu video camera vào Canvas và tài sản của bạn"),"ok")}async function is(c,x=Ae.current.shots.find(se=>se.id===Ae.current.activeShot),L=0,P=!0,B=0,X=""){if(!Ce.current)return;P&&me(!0),ye("");const se=dt.getState().canvasId,ge=structuredClone(Ae.current);ge.activeShot=x.id;const fe=x,Ge=Ae.current.activeShot;try{Ge!==fe.id&&Ce.current.sync(ge,J);const De=await Ce.current.exportPng(B),qe=`${fe.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}${X.replace(/\s+/g,"-")}.png`;if(c){const{url:pt,gcsUri:St}=await Us(new File([De],qe,{type:"image/png"})),Tn=_t()?.getNode(e);if(dt.getState().canvasId!==se)throw new Error("Canvas đã thay đổi; ảnh chưa được chèn");if(!Tn)throw new Error("Cảnh gốc không còn tồn tại");const Ut=_t()?.addNode("image",{url:pt,gcsUri:St,label:`${fe.name}${X}`,ratio:fe.aspect,prompt:Ti(ge),shotSourceId:e,shotId:fe.id,shotRevision:ge.revision,sceneVersion:ge.version,characterReferences:ge.items.filter(vn=>vn.kind==="person"&&vn.reference).map(vn=>vn.reference),cameraMotion:{pathSmooth:fe.pathSmooth,type:fe.motion,duration:fe.duration,endPosition:fe.endPosition,endTarget:fe.endTarget,endLens:fe.endLens},cameraFrame:B},{x:Tn.position.x+380,y:Tn.position.y+L*280},{sourceIds:[e,...ge.items.flatMap(vn=>vn.reference?.nodeId?[vn.reference.nodeId]:[])]});return dt.getState().toast(a("Đã đưa ảnh shot vào Canvas"),"ok"),Ut}else{const pt=URL.createObjectURL(De),St=document.createElement("a");St.href=pt,St.download=qe,St.click(),setTimeout(()=>URL.revokeObjectURL(pt),1e3)}}catch(De){if(ye(De.message),!P)throw De}finally{Ge!==fe.id&&Ce.current.sync(Ae.current,J),P&&me(!1)}}async function xm(){if(de.motion!=="static"){me(!0),ye("");try{const c=await is(!0,de,0,!1,0," · Start"),x=await is(!0,de,1,!1,1," · End");c&&x&&(_t()?.updateNodeData(c,{pairedShotNodeId:x}),_t()?.updateNodeData(x,{pairedShotNodeId:c})),dt.getState().toast(a("Đã tạo cặp Start/End cho Seedance"),"ok")}catch(c){ye(c.message)}finally{Ce.current?.sync(Ae.current,J),me(!1)}}}async function bm(){let c=!1;me(!0),ye("");try{Fa.includes(de.aspect)||dt.getState().toast(Ou(de).aspect.at(-1)||"","error");const x=await is(!0,de,0,!1,Ie," · Previs");if(!x)return;const L=[x,...Ae.current.items.flatMap(B=>B.reference?.nodeId?[B.reference.nodeId]:[]),...(Ae.current.styleRefs||[]).map(B=>B.nodeId)],P=_t()?.getNode(e);c=!0,mn(),dt.getState().openComposer({mode:"image",generator:"openai:gpt-image",refs:Array.from(new Set(L)),prompt:C0(Ae.current),count:1,aspectRatio:Fa.includes(de.aspect)?de.aspect:ar(de.aspect,Fa),resolution:"2K",quality:"high",anchor:P?{x:P.position.x+760,y:P.position.y}:null}),dt.getState().toast(a("Khung previs đã sẵn sàng để tạo ảnh thật"),"ok")}catch(x){ye(x.message)}finally{c||Ce.current?.sync(Ae.current,J),me(!1)}}async function ym(){if(Ce.current){me(!0),ye("");try{const c=await Ce.current.exportPng(Ie,!0),x=URL.createObjectURL(c),L=document.createElement("a");L.href=x,L.download=`${de.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-ghi-chu.png`,L.click(),setTimeout(()=>URL.revokeObjectURL(x),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}async function vm(){me(!0),ye("");try{for(let c=0;c<Ae.current.shots.length;c++)await is(!0,Ae.current.shots[c],c,!1);dt.getState().toast(a("Đã xuất {0} shot vào Canvas",[Ae.current.shots.length]),"ok")}catch(c){ye(c.message)}finally{me(!1)}}async function jm(){if(Ce.current){me(!0);try{const c=Ae.current.shots.find(B=>B.id===Ae.current.activeShot),x=await Ce.current.exportDepth(Ie),L=URL.createObjectURL(x),P=document.createElement("a");P.href=L,P.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-depth.png`,P.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}async function km(){if(Ce.current){me(!0);try{const c=Ae.current.shots.find(B=>B.id===Ae.current.activeShot),x=await Ce.current.exportPoseMask(Ie),L=URL.createObjectURL(x),P=document.createElement("a");P.href=L,P.download=`${c.name.replace(/[^\p{L}\p{N}_-]/gu,"_")}-pose-mask.png`,P.click(),setTimeout(()=>URL.revokeObjectURL(L),1e3)}catch(c){ye(c.message)}finally{me(!1)}}}const Ss=(c,x,L,P=-100)=>t.jsxs("div",{className:"shot-vector",children:[t.jsx("small",{children:a(c)}),x.map((B,X)=>t.jsx(es,{label:`${a(c)} ${["X","Y","Z"][X]}`,value:B,min:P,onChange:se=>{const ge=[...x];ge[X]=se,L(ge)}},X))]});R.useEffect(()=>{try{localStorage.setItem("clipoox.shot.layout",JSON.stringify(ue))}catch{}},[ue]);const Vn=c=>{ve(c);try{localStorage.setItem("clipoox.shot.panel",c||"")}catch{}},wm=c=>Vn(Q===c?null:c),$l=c=>{q(c);try{localStorage.setItem("clipoox.shot.railWide",c?"1":"0")}catch{}},[no,ha]=R.useState(null),Dl=c=>{const x=c.target.closest("button"),L=x?.querySelector(".lbl");if(!x||!L||getComputedStyle(L).display!=="none"){ha(null);return}const P=x.getBoundingClientRect(),B=c.currentTarget.getBoundingClientRect().right,X=x.getAttribute("aria-label")||"";ha(se=>se&&se.label===X&&se.top===P.top+P.height/2?se:{label:X,left:B+8,top:P.top+P.height/2})},Mm=()=>{pe(Qi),$l(!1);try{localStorage.removeItem("clipoox.shot.layout")}catch{}},gi=(c,x)=>{if(c.button!==0)return;c.preventDefault();const L=c.currentTarget,P={x:c.clientX,y:c.clientY,value:ue[x]},B=c.pointerId;L.setPointerCapture(B),L.classList.add("dragging");const X=fe=>x==="timeline"?Math.max(120,Math.min(window.innerHeight*.55,fe)):x==="drawer"?Math.max(240,Math.min(window.innerWidth*.2,fe)):Math.max(260,Math.min(window.innerWidth*.22,fe)),se=fe=>{const Ge=x==="timeline"?P.y-fe.clientY:x==="drawer"?fe.clientX-P.x:P.x-fe.clientX;pe(De=>({...De,[x]:Math.round(X(P.value+Ge))}))},ge=()=>{L.removeEventListener("pointermove",se),L.removeEventListener("pointerup",ge),L.removeEventListener("pointercancel",ge),L.classList.remove("dragging")};L.addEventListener("pointermove",se),L.addEventListener("pointerup",ge),L.addEventListener("pointercancel",ge)};return t.jsxs("div",{className:"shot-workspace",role:"dialog","aria-modal":"true","aria-label":a("3D Shot Composer"),children:[Oe&&t.jsx(hj,{count:cn.length,start:Ie*de.duration,left:(1-Ie)*de.duration,busy:re,onRun:c=>{Zu(c)},onClose:()=>Re(!1)}),ae&&t.jsx(rj,{x:ae.x,y:ae.y,renaming:!!ae.renaming,items:ae.scene?[]:cn.map(c=>z.items.find(x=>x.id===c)).filter(Boolean),canPaste:!!Za(),hiddenCount:z.items.filter(c=>c.hidden).length,blenderKeys:Ve,onBlenderKeys:Ye,onAction:Qu,onRename:c=>{const x=cn[0];ke(null),x&&tt(x,{name:c})},onClose:He}),We.on&&(()=>{const c=$e.current?.getBoundingClientRect(),x=We.from,L=We.to;if(!c)return null;const P=B=>{if(!x)return;const X=L&&Math.hypot(L[0]-x[0],L[1]-x[1])>3?Ce.current?.objectsInRect(x[0],x[1],B.clientX,B.clientY)??[]:[];Zt(B.shiftKey?[...Ft.current,...X.filter(se=>!Ft.current.includes(se))]:X),et({on:!1})};return t.jsxs("div",{className:"shot-boxsel",role:"presentation","aria-label":a("Kéo để chọn theo vùng"),style:{left:c.left,top:c.top,width:c.width,height:c.height},onMouseDown:B=>{B.button===0&&et({on:!0,from:[B.clientX,B.clientY],to:[B.clientX,B.clientY]})},onMouseMove:B=>{x&&et({on:!0,from:x,to:[B.clientX,B.clientY]})},onMouseUp:P,onContextMenu:B=>{B.preventDefault(),et({on:!1})},children:[t.jsx("span",{className:"shot-boxsel-hint",children:a("Kéo để chọn theo vùng · Shift: chọn thêm · Esc: thôi")}),x&&L&&t.jsx("i",{style:{left:Math.min(x[0],L[0])-c.left,top:Math.min(x[1],L[1])-c.top,width:Math.abs(L[0]-x[0]),height:Math.abs(L[1]-x[1])}})]})})(),E&&t.jsx(_1,{shot:de,engine:Ce.current||null,onClose:()=>N(!1),onBusy:me,onReady:fi,timelineTarget:(()=>{const c=_t()?.getNode(e)?.data?.timelineClipId;return typeof c=="string"?dt.getState().clips.find(x=>x.id===c)?.label:void 0})(),vfx:z.plate?{layers:new Set(z.items.filter(c=>c.kind==="fx"&&!c.hidden).map(pd)).size,target:dt.getState().clips.find(c=>c.id===z.plate?.timelineClipId)?.label,run:async(c,x,L)=>{const P=await pi(c,x,L),B=dt.getState();if(!P.placed){B.toast(a("Đã 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 đó.",[P.passes.length]),"info");return}mn(),B.setView("timeline"),B.toast(P.pendingMatte?a("Đã đặt {0} lớp hiệu ứng lên Timeline. Timeline đang tách người để đặt lớp sau người ra sau.",[P.passes.length]):a("Đã đặt {0} lớp hiệu ứng lên Timeline.",[P.passes.length]),"ok")}}:void 0}),t.jsxs("header",{children:[t.jsxs("button",{disabled:re,onClick:mn,children:[t.jsx(Ne.back,{}),a("← Canvas").replace("← ","")]}),t.jsxs("strong",{children:[a("3D Shot Composer"),t.jsx("em",{children:a("BETA")})]}),t.jsx("span",{className:"shot-save","data-save-state":Ht,title:Ht==="error"&&Et?Et:void 0,children:Ht==="saved"?a("Đã lưu"):Ht==="error"?t.jsxs(t.Fragment,{children:[a("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:a("Thử lại")})]}):a("Đang lưu…")}),t.jsx("button",{"aria-label":a("Hoàn tác"),title:a("Hoàn tác (⌘Z)"),disabled:!Dt.current.length||re,onClick:()=>eo(),children:t.jsx(Ne.undo,{})}),t.jsx("button",{"aria-label":a("Làm lại"),title:a("Làm lại (⇧⌘Z)"),disabled:!Kt.current.length||re,onClick:()=>eo(!0),children:t.jsx(Ne.redo,{})}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),is(!1,de,0,!0,Ie)},title:a("Tải PNG"),children:[t.jsx(Ne.image,{}),t.jsx("span",{className:"lbl",children:a("Tải PNG")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at,onClick:jm,title:a("Depth map"),children:[t.jsx(Ne.depth,{}),t.jsx("span",{className:"lbl",children:a("Depth map")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at,onClick:km,title:a("Pose mask"),children:[t.jsx(Ne.mask,{}),t.jsx("span",{className:"lbl",children:a("Pose mask")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at||z.shots.length<2,onClick:vm,title:a("Xuất tất cả shot"),children:[t.jsx(Ne.layers,{}),t.jsx("span",{className:"lbl",children:a("Xuất tất cả shot")})]}),t.jsxs("button",{className:"shot-hdr-aux",disabled:re||!at||de.motion==="static",onClick:xm,title:a("Start + End"),children:[t.jsx(Ne.frames,{}),t.jsx("span",{className:"lbl",children:a("Start + End")})]}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),bm()},title:a("Biến khung xám thành ảnh thật (giữ nguyên bố cục)"),children:[t.jsx(Ne.image,{}),t.jsx("span",{className:"lbl",children:a("Ảnh thật")})]}),t.jsxs("button",{className:"shot-primary",disabled:re||!at,onClick:()=>{D(!1),N(!0)},title:a("Xuất MP4"),children:[t.jsx(Ne.video,{}),a("Xuất MP4")]}),t.jsxs("button",{disabled:re||!at,onClick:()=>{D(!1),is(!0,de,0,!0,Ie)},children:[t.jsx(Ne.plus,{}),re?a("Đang xuất…"):a("Đưa vào Canvas")]})]}),Xn&&Xn.canvasId===Nn&&Xn.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(Xn.by)?a("Cảnh 3D này có phiên bản mới từ trợ lý AI của bạn."):a("Cảnh 3D này có phiên bản mới.")})," ",a("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:ws,onClick:()=>void Hf(Xn.canvasId,Xn.nodeId).then(()=>dt.getState().toast(a("Đã tải phiên bản mới nhất của cảnh 3D."),"ok")),children:a("Tải phiên bản mới")}),t.jsx("button",{disabled:ws,onClick:Wf,children:a("Giữ bản của tôi")})]}),Pe&&t.jsx("div",{className:"shot-error",role:"alert",children:a(Pe)}),$&&t.jsx(Gf,{characters:$==="characters",onClose:()=>{W(!1),$t(null)},onSelect:si}),A&&t.jsx("div",{className:"shot-trial-shield",role:"dialog","aria-label":a("Xem thử đề xuất AI"),children:t.jsxs("div",{className:"shot-trial-controls",children:[t.jsx("b",{children:a("Xem thử · chưa lưu")}),t.jsx("button",{onClick:()=>{Ie>=1&&ot(0),D(!H)},children:H?a("Tạm dừng"):a("Phát lại")}),t.jsx("input",{"aria-label":a("Thời gian xem thử"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(2),a("s")]}),t.jsx("button",{onClick:()=>ai(!1),children:a("Bỏ bản xem thử")}),t.jsx("button",{className:"shot-primary",onClick:()=>ai(!0),children:a("Giữ thay đổi")})]})}),t.jsxs("div",{className:`shot-layout ${Q?"has-drawer":""} ${xe?"rail-wide":""}`,style:{"--drawer-w":`${ue.drawer}px`,"--right-w":`${ue.right}px`},children:[t.jsxs("nav",{className:"shot-rail","aria-label":a("Công cụ dựng cảnh"),onMouseOver:Dl,onFocus:Dl,onMouseLeave:()=>ha(null),onBlur:()=>ha(null),onScroll:()=>ha(null),children:[So.map(([c,x,L])=>t.jsxs("button",{type:"button",className:Q===c?"active":"","aria-pressed":Q===c,"aria-label":a(x),onClick:()=>wm(c),children:[L,t.jsx("span",{className:"lbl",children:a(x)}),c==="objects"&&t.jsx("small",{className:"shot-rail-count",children:z.items.length}),c==="shots"&&z.shots.length>1&&t.jsx("small",{className:"shot-rail-count",children:z.shots.length}),c==="notes"&&$s.length>0&&t.jsx("small",{className:"shot-rail-count",children:$s.length})]},c)),t.jsx("span",{className:"shot-rail-gap"}),t.jsxs("button",{type:"button","aria-label":xe?a("Thu gọn thanh công cụ"):a("Mở rộng thanh công cụ"),onClick:()=>$l(!xe),children:[xe?t.jsx(Ne.collapse,{}):t.jsx(Ne.expand,{}),t.jsx("span",{className:"lbl",children:a("Thu gọn")})]}),t.jsxs("button",{type:"button","aria-label":a("Khôi phục bố cục"),onClick:Mm,children:[t.jsx(Ne.reset,{}),t.jsx("span",{className:"lbl",children:a("Khôi phục bố cục")})]})]}),no&&gd.createPortal(t.jsx("span",{className:"shot-rail-tip",role:"tooltip",style:{left:no.left,top:no.top},children:no.label}),document.querySelector(".shot-workspace")||document.body),Q&&t.jsxs("aside",{className:"shot-drawer shot-inspector","aria-label":a(So.find(c=>c[0]===Q)[1]),children:[t.jsxs("div",{className:"shot-drawer-head",children:[t.jsxs("h3",{children:[a(So.find(c=>c[0]===Q)[1]),Q==="objects"?t.jsxs("small",{className:"shot-total",children:[" · ",z.items.length]}):Q==="shots"?t.jsxs("small",{className:"shot-total",children:[" · ",z.shots.length," · ",Ai(Ml.at(-1)?.end||0)]}):Q==="notes"?t.jsxs("small",{className:"shot-total",children:[" · ",$s.length]}):Q==="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":a("Đóng bảng"),title:a("Đóng bảng (Esc)"),onClick:()=>Vn(null),children:t.jsx(Ne.close,{})})]}),t.jsxs("div",{className:"shot-drawer-body shot-inspector-scroll",tabIndex:0,children:[Q==="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:yt,type:"file",accept:".glb",hidden:!0,onChange:c=>{pm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{onClick:()=>W("all"),children:[t.jsx(Ne.library,{}),a("Kho 3D chung")]}),t.jsxs("button",{onClick:()=>void Fl(),children:[t.jsx(Ne.user,{}),a("Model của tôi")]}),rt.length>0&&t.jsxs("select",{"aria-label":a("Model 3D đã lưu"),value:"",onChange:c=>{const x=rt.find(P=>P.id===c.target.value);if(!x)return;const L={...Mn("model",Ae.current.items.length),name:x.name,model:{gcsUri:x.gcsUri,name:x.name}};we(P=>({...P,items:[...P.items,L]})),xt(L.id)},children:[t.jsx("option",{value:"",children:a("Chọn model đã lưu…")}),rt.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),qt&&t.jsx("button",{onClick:()=>void Fl(qt),children:a("Thêm model đã lưu")}),t.jsxs("button",{disabled:lt,onClick:()=>yt.current?.click(),children:[t.jsx(Ne.cube,{}),lt?a("Đang tải…"):"Model GLB"]}),t.jsx("input",{ref:yn,type:"file",accept:".spz,.ply,.splat,.ksplat,.sog",hidden:!0,onChange:c=>{fm(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:lt,title:a("Bản quét 3D địa điểm thật từ app điện thoại (Scaniverse, Polycam, Luma…)"),onClick:()=>yn.current?.click(),children:[t.jsx(Ne.image,{}),a("Bối cảnh thật")]}),mi.length>0&&t.jsxs("select",{"aria-label":a("Dùng 3D World trên Canvas"),value:"",onChange:c=>{const x=mi.find(P=>P.id===c.target.value);if(!x)return;const L=x.data;Pl(L.label||"3D World",{name:L.label||"3D World",url:L.splatUrl,source:"world",flip:!0,...L.worldId?{worldId:L.worldId}:{}})},children:[t.jsx("option",{value:"",children:a("Dùng 3D World trên Canvas…")}),mi.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"3D World")},c.id))]}),Yi.map(([c,x])=>t.jsxs("button",{disabled:re,onClick:()=>gm(c),children:[dj[c],a(x)]},c))]}),t.jsx(es,{label:"Số người mỗi lần thêm",value:Ct,min:1,max:50,step:1,onChange:c=>gt(Math.floor(c))})]})}),Q==="fx"&&t.jsx(t1,{onEdit:()=>Vn("fxedit"),onPlayClip:(c,x)=>{ri(c,x)},stage:z,selected:J,playhead:Ie*de.duration,change:we,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],anchor:(c,x,L)=>Ce.current?.partPointAt(de,L,c,x)??null,engine:Ce.current,setError:ye}),Q==="material"&&t.jsx(f1,{stage:z,selected:J,change:we,engine:Ce.current,setError:ye,scope:qn,setScope:Un}),Q==="rigging"&&t.jsx($1,{stage:z,shot:de,selected:J,engine:at?Ce.current:null,playhead:Ie,busy:re,change:we,patchItem:tt,onSelect:xt,resync:()=>Ce.current?.sync(Ae.current,J),setError:ye,addPoseKey:nl,onPlayClip:ri,motionLoop:oi,motionMirror:ii,onMotionLoop:cl,onMotionMirror:hl,keys:Cn}),Q==="fxedit"&&t.jsx(n1,{stage:z,selected:J,playhead:Ie*de.duration,change:we,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],engine:Ce.current}),Q==="mixfx"&&t.jsx(l1,{stage:z,selected:J,progress:Ie,change:we,onSelect:xt,engine:Ce.current,setError:ye}),Q==="modeling"&&t.jsx(Bx,{stage:z,selected:J,change:we,getStage:()=>Ae.current,onSelect:xt,ground:()=>Ce.current?.groundAtScreenCentre()??[0,0,0],engine:Ce.current,setError:ye}),Q==="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:a("Nhân vật có xương: thêm vào cảnh là chạy mocap / chuyển động ngay"),children:[t.jsx(Ne.person,{}),t.jsx("span",{children:a("Thư viện nhân vật")})]})}),t.jsx("div",{className:"shot-list",children:z.items.map(c=>t.jsxs("div",{className:J===c.id?"active":K.includes(c.id)?"picked":"",onContextMenu:x=>{x.preventDefault(),di(c.id,x.clientX,x.clientY)},children:[t.jsxs("button",{"aria-pressed":cn.includes(c.id),title:a("Shift/Ctrl+click: chọn thêm · chuột phải: menu"),onClick:x=>bn(c.id,x.shiftKey||x.ctrlKey||x.metaKey),children:[c.kind==="person"?"♙":c.kind==="set"?"⌂":"◇"," ",c.name,c.kind==="set"&&c.set?.parts?t.jsxs("small",{className:"shot-list-meta",children:[" · ",c.set.parts," ",a("khối")]}):null]}),t.jsx("button",{title:c.hidden?a("Hiện"):a("Ẩn"),onClick:()=>tt(c.id,{hidden:!c.hidden}),children:c.hidden?"○":"●"}),t.jsx("button",{title:c.locked?a("Mở khóa"):a("Khóa"),onClick:()=>tt(c.id,{locked:!c.locked}),children:c.locked?"▣":"□"}),t.jsx("button",{className:"shot-delete-item","aria-label":a("Xóa {0}",[c.name]),title:c.locked?a("Mở khóa đối tượng trước khi xóa"):a("Xóa {0} (Delete)",[c.name]),disabled:re||c.locked,onClick:()=>ml(c.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"})})})]},c.id))})]}),ne&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("CHỈNH ĐỐI TƯỢNG")}),t.jsxs("fieldset",{disabled:ne.locked||re,children:[t.jsx("input",{"aria-label":a("Tên đối tượng"),value:ne.name,onChange:c=>tt(ne.id,{name:c.target.value})}),t.jsxs("label",{className:"shot-field",children:[a("Màu"),t.jsx("input",{"aria-label":a("Màu đối tượng"),type:"color",value:ne.color,onChange:c=>tt(ne.id,{color:c.target.value})})]}),t.jsxs("select",{"aria-label":a("Đặt lên bề mặt"),value:"",onChange:c=>{c.target.value&&Ce.current?.placeOnSurface(c.target.value)},children:[t.jsx("option",{value:"",children:a("Đặt lên bề mặt…")}),t.jsx("option",{value:"ground",children:a("Mặt đất")}),z.items.filter(c=>c.kind!=="person"&&c.id!==ne.id&&!c.hidden).map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))]}),Ss(a("Vị trí"),ne.position,c=>tt(ne.id,{position:c})),Ss("Xoay °",ne.rotation,c=>tt(ne.id,{rotation:c}),-360),Ss(a("Tỷ lệ"),ne.scale,c=>tt(ne.id,{scale:c}),.05),ne.kind==="model"&&ne.model&&t.jsxs("div",{className:"shot-model-size",children:[t.jsx(es,{label:"Chiều cao thật (m)",value:Number((Ce.current?.modelHeight(ne)??2).toFixed(2)),min:.02,max:500,step:.01,onChange:c=>tt(ne.id,{model:{...ne.model,height:c}})}),t.jsx("small",{className:"shot-hint",children:ne.model.height?a("Kích thước thật"):a("Tự động: cạnh dài nhất 2 m")}),ne.model.height&&t.jsx("button",{onClick:()=>{const{height:c,...x}=ne.model;tt(ne.id,{model:x})},children:a("Về tự động")})]}),ne.hold&&(()=>{const c=z.items.find(x=>x.id===ne.hold.by);return t.jsxs("div",{className:"shot-held",children:[t.jsx("small",{className:"shot-hint",children:a("Đang được {0} cầm ở {1}",[c?.name||"?",ne.hold.hand==="R"?a("tay phải"):a("tay trái")])}),t.jsx("button",{onClick:()=>c&&dl(c.id,ne.hold.hand,""),children:a("Thả xuống")})]})})(),ne.kind==="splat"&&ne.splat&&(()=>{const c=Ce.current?.splatExtent(ne.splat);return t.jsxs("div",{className:"shot-splat",children:[t.jsx("h3",{children:a("BỐI CẢNH THẬT")}),t.jsxs("small",{className:"shot-hint",children:[ne.splat.source==="world"?a("3D World do AI tạo"):a("Bản quét địa điểm thật"),c?` · ${(c.max[0]-c.min[0]).toFixed(1)} × ${(c.max[2]-c.min[2]).toFixed(1)} m`:` · ${a("đang tải…")}`]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.splat.flip!==!1,onChange:x=>{const L={...ne.splat,flip:x.target.checked},P=Ce.current?.splatExtent(L);tt(ne.id,P?{splat:{...L,bounds:{min:P.min,max:P.max},floor:P.floor},position:[ne.position[0],-P.floor*ne.scale[1],ne.position[2]]}:{splat:L})}}),a("Lật trục (file quét kiểu OpenCV)")]}),t.jsx(es,{label:"Tỷ lệ bản quét",value:ne.scale[0],min:.05,step:.05,onChange:x=>tt(ne.id,{scale:[x,x,x]})}),t.jsx("button",{disabled:!c,onClick:()=>{c&&tt(ne.id,{position:[ne.position[0],-c.floor*ne.scale[1],ne.position[2]],splat:{...ne.splat,bounds:{min:c.min,max:c.max},floor:c.floor}})},children:a("Căn sàn về mặt đất")}),t.jsx("small",{className:"shot-hint",children:a('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.')})]})})(),g1.includes(ne.kind)&&t.jsx(b1,{item:z.items.find(c=>c.id===ne.id)??ne,shot:de,playhead:Ie,patchItem:tt,change:we}),ne.kind==="person"&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{children:a("NHẬN DIỆN NHÂN VẬT")}),t.jsxs("select",{"aria-label":a("Ảnh tham chiếu nhân vật"),value:ne.reference?.nodeId||"",onChange:c=>{const x=to.find(P=>P.id===c.target.value),L=x?.data;tt(ne.id,{reference:x&&L?.url?{nodeId:x.id,url:L.url,name:L.label||"Character reference"}:null})},children:[t.jsx("option",{value:"",children:a("Không dùng ảnh nhận diện")}),to.map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]}),ne.reference&&t.jsx("img",{className:"shot-character-ref",src:ne.reference.url,alt:ne.reference.name}),t.jsx("h3",{children:a("NHÂN VẬT")}),t.jsx("button",{type:"button",className:"shot-char-open",title:a("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:()=>{$t(ne.id),W("characters")},children:a("Chọn nhân vật từ thư viện…")}),ne.look||ne.figure&&["legs","shoulders","hips","chest","waist","weight","muscle","posture","skin","face"].some(c=>ne.figure[c]!==void 0)?t.jsx("button",{type:"button",onClick:()=>tt(ne.id,{figure:ne.figure?{height:ne.figure.height,head:ne.figure.head,build:ne.figure.build}:void 0,look:void 0,character:void 0}),children:a("Về mannequin trơn")}):null,t.jsx("h3",{children:a("VÓC DÁNG")}),t.jsx("div",{className:"shot-add shot-figure-presets",children:qf.map(c=>{const x=Wt(ne.figure);return t.jsx("button",{className:x.height===c.figure.height&&x.head===c.figure.head&&x.build===c.figure.build?"active":"",onClick:()=>tt(ne.id,{figure:{...c.figure}}),children:a(c.name)},c.name)})}),t.jsx(es,{label:"Chiều cao (m)",value:Wt(ne.figure).height,min:.3,max:3,step:.01,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),height:c})})}),t.jsxs("label",{className:"shot-joint",children:[a("Cỡ đầu")," ",t.jsxs("span",{children:[Wt(ne.figure).head.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Cỡ đầu"),type:"range",min:.7,max:2,step:.05,value:Wt(ne.figure).head,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),head:+c.target.value})})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Vai / hông")," ",t.jsxs("span",{children:[Wt(ne.figure).build.toFixed(2),"×"]}),t.jsx("input",{"aria-label":a("Vai / hông"),type:"range",min:.6,max:1.6,step:.05,value:Wt(ne.figure).build,onChange:c=>tt(ne.id,{figure:Wt({...Wt(ne.figure),build:+c.target.value})})})]}),t.jsx("h3",{children:a("ĐẠO CỤ TRÊN TAY")}),t.jsxs("div",{className:"shot-props",children:[["R","L"].map(c=>{const x=z.items.find(P=>P.hold?.by===ne.id&&P.hold.hand===c),L=z.items.filter(P=>P.id!==ne.id&&!["person","splat","set","floor","wall"].includes(P.kind)&&!(P.hold&&P.hold.by!==ne.id));return t.jsxs("div",{className:"shot-prop-hand",children:[t.jsxs("label",{className:"shot-field",children:[c==="R"?a("Tay phải"):a("Tay trái"),t.jsxs("select",{"aria-label":c==="R"?a("Đạo cụ tay phải"):a("Đạo cụ tay trái"),value:x?`item:${x.id}`:"",onChange:P=>dl(ne.id,c,P.target.value),children:[t.jsx("option",{value:"",children:a("— Tay không —")}),x&&t.jsx("option",{value:`item:${x.id}`,children:x.name}),t.jsx("optgroup",{label:a("Đạo cụ dựng sẵn"),children:Uf.map(P=>t.jsx("option",{value:`prop:${P}`,children:a(La[P].label)},P))}),L.filter(P=>P.id!==x?.id).length>0&&t.jsx("optgroup",{label:a("Vật trong cảnh"),children:L.filter(P=>P.id!==x?.id).map(P=>t.jsx("option",{value:`item:${P.id}`,children:P.name},P.id))})]})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Gập cổ tay")," ",t.jsxs("span",{children:[x.hold.tilt??(x.prop?La[x.prop.kind].tilt??0:0),"°"]}),t.jsx("input",{"aria-label":a("Gập cổ tay"),type:"range",min:-90,max:90,step:5,value:x.hold.tilt??(x.prop?La[x.prop.kind].tilt??0:0),onChange:P=>we(B=>({...B,items:B.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,tilt:+P.target.value}}:X)}))})]}),x&&t.jsxs("label",{className:"shot-joint",children:[a("Xoay quanh cổ tay")," ",t.jsxs("span",{children:[x.hold.angle??0,"°"]}),t.jsx("input",{"aria-label":a("Xoay đạo cụ quanh cổ tay"),type:"range",min:-180,max:180,step:5,value:x.hold.angle??0,onChange:P=>we(B=>({...B,items:B.items.map(X=>X.id===x.id?{...X,hold:{...X.hold,angle:+P.target.value}}:X)}))})]})]},c)}),t.jsx("small",{className:"shot-hint",children:a("Đạ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:a("CHUYỂN ĐỘNG NGƯỜI")}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ne.gait!=="off",onChange:c=>tt(ne.id,{gait:c.target.checked?"auto":"off"})}),a("Tự bước đi / chạy khi di chuyển")]}),(()=>{const c=de.objectKeys?.[ne.id]||[],x=c.filter(P=>P.pose),L=x.find(P=>Math.abs(P.time-Ie)<1e-6);return t.jsxs("div",{className:"shot-pose-keys",children:[t.jsx("button",{className:L?"active":"",onClick:()=>nl(ne.id),children:L?a("◆ Cập nhật key tư thế · {0}s",[(Ie*de.duration).toFixed(1)]):a("◇ Key tư thế tại {0}s",[(Ie*de.duration).toFixed(1)])}),L&&t.jsx("button",{onClick:()=>zu(ne.id),children:a("Bỏ key tư thế")}),L&&t.jsxs("label",{className:"shot-pose-ease",children:[a("Kiểu chuyển vào key")," ",t.jsx("select",{"aria-label":a("Kiểu chuyển vào key"),value:L.poseEase||"smooth",onChange:P=>Bu(ne.id,P.target.value),children:Xf.map(P=>t.jsx("option",{value:P.id,children:a(P.label)},P.id))})]}),t.jsx("small",{className:"shot-hint",children:x.length?a("{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.",[x.length]):a("Đặt key ở nhiều thời điểm (đứng → ngồi → giơ tay…) để tư thế chuyển động theo thời gian.")})]})})(),t.jsx(j1,{shot:de,item:ne,playhead:Ie*de.duration,change:we,engine:Ce.current,seek:c=>{D(!1),ot(Math.max(0,Math.min(1,c/de.duration)))}}),t.jsx(Fu,{disabled:re,loop:oi,mirror:ii,onLoop:cl,onMirror:hl,onPlay:c=>{ri(ne.id,c)},person:ne,playhead:Ie*de.duration}),t.jsxs("div",{className:"shot-mocap",children:[t.jsx("input",{ref:sl,type:"file",accept:".bvh,.fbx,.glb",hidden:!0,onChange:c=>{Wu(c.target.files?.[0]),c.target.value=""}}),t.jsxs("button",{disabled:il||re,onClick:()=>sl.current?.click(),title:a("Chuyển động người thật: Mixamo (.fbx), CMU (.bvh) hoặc GLB có animation"),children:[t.jsx(Ne.person,{}),il?a("Đang đọc…"):a("Nhập mocap (.bvh · .fbx · .glb)")]}),os&&t.jsxs("div",{className:"shot-mocap-card",children:[t.jsx("b",{children:os.name}),t.jsxs("small",{children:[os.duration.toFixed(1),a("s · khung xương người ✓")]}),t.jsxs("label",{className:"shot-field",children:[a("Tốc độ"),t.jsx("select",{"aria-label":a("Tốc độ mocap"),value:la,onChange:c=>Ku(+c.target.value),children:[.5,.75,1,1.25,1.5,2].map(c=>t.jsxs("option",{value:c,children:[c,"×"]},c))})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:ol,onChange:c=>Hu(c.target.checked)}),a("Di chuyển theo mocap (đi, chạy, nhảy)")]}),t.jsx("small",{className:"shot-hint",children:a("Bắt đầu tại {0}s · dùng {1}s (phần dài hơn shot bị cắt)",[(Ie*de.duration).toFixed(1),Math.min(os.duration/la,(1-Ie)*de.duration).toFixed(1)])}),t.jsx("button",{className:"shot-primary",disabled:re,onClick:()=>qu(ne.id),children:a("Áp dụng cho {0}",[ne.name])})]}),Vf(z,ne.id)&&t.jsx("button",{onClick:()=>{D(!1),we(c=>N0(c,ne.id))},children:a("Xoá mocap của {0}",[ne.name])})]}),t.jsxs("div",{className:"shot-hits",children:[t.jsx("button",{onClick:Xu,children:a("⚡ Tự tạo phản ứng trúng đòn")}),Yf(de)&&t.jsx("button",{onClick:Vu,children:a("Xoá phản ứng tự động")}),t.jsx("small",{className:"shot-hint",children:Uu||a('Đò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:[a("RIG PRESETS"),t.jsx("button",{className:"shot-pose-mirror",title:a("Lật tư thế trái ↔ phải"),onClick:()=>tt(ne.id,{pose:Qf(ne.pose)}),children:a("⇆ Lật trái/phải")})]}),t.jsx("div",{className:"shot-rig-library",children:zo.map(c=>t.jsxs("section",{children:[t.jsxs("header",{children:[t.jsx("span",{children:a(c.name)}),t.jsxs("small",{children:[c.presets.length," ",a("rig")]})]}),t.jsx("div",{className:"shot-rig-grid",children:c.presets.map(x=>t.jsxs("button",{className:pj(ne.pose,Kn[x])?"active":"",title:a("Áp dụng rig {0}",[x]),onClick:()=>_u(ne,x),children:[t.jsx(Jr,{pose:Kn[x]}),t.jsx("span",{children:a(x)})]},x))})]},a(c.name)))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thư viện pose cá nhân")}),t.jsxs("div",{className:"shot-pose-library",children:[z.poseLibrary.map(c=>t.jsxs("div",{children:[t.jsx("button",{onClick:()=>tt(ne.id,{pose:{...c.pose}}),children:c.name}),t.jsx("button",{"aria-label":a("Xóa {0}",[c.name]),onClick:()=>we(x=>({...x,poseLibrary:x.poseLibrary.filter(L=>L.id!==c.id)})),children:a("×")})]},c.id)),t.jsx("button",{onClick:()=>{const c=window.prompt(a("Tên pose"),`Pose ${z.poseLibrary.length+1}`)?.trim();c&&we(x=>({...x,poseLibrary:[...x.poseLibrary,{id:vt(),name:c,pose:structuredClone(ne.pose)}]}))},children:a("+ Lưu pose hiện tại")})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Kéo tay/chân IK")}),t.jsxs("div",{className:"shot-ik-grid",children:[t.jsx(Co,{label:"Tay trái",root:ne.pose.shoulderL,bend:ne.pose.elbowL,upper:.29,lower:.27,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,shoulderL:c,elbowL:x}})}),t.jsx(Co,{label:"Tay phải",root:ne.pose.shoulderR,bend:ne.pose.elbowR,upper:.29,lower:.27,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,shoulderR:c,elbowR:x}})}),t.jsx(Co,{label:"Chân trái",root:ne.pose.hipL,bend:ne.pose.kneeL,upper:.43,lower:.4,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,hipL:c,kneeL:x}})}),t.jsx(Co,{label:"Chân phải",root:ne.pose.hipR,bend:ne.pose.kneeR,upper:.43,lower:.4,onChange:(c,x)=>tt(ne.id,{pose:{...ne.pose,hipR:c,kneeR:x}})})]})]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Chỉnh từng khớp")}),Object.keys(Fo).map(c=>t.jsxs("label",{className:"shot-joint",children:[a(Fo[c])," ",t.jsxs("span",{children:[ne.pose[c]||0,"°"]}),t.jsx("input",{"aria-label":a(Fo[c]),type:"range",min:c.startsWith("knee")||c.startsWith("elbow")?0:-120,max:150,value:ne.pose[c]||0,onChange:x=>tt(ne.id,{pose:{...ne.pose,[c]:+x.target.value}})})]},c))]}),t.jsxs("details",{open:!0,children:[t.jsx("summary",{children:a("Tay · đầu · mắt")}),t.jsx("div",{className:"shot-hand-shapes",children:["R","L"].map(c=>t.jsxs("div",{children:[t.jsx("small",{children:c==="R"?a("Tay phải"):a("Tay trái")}),t.jsx("span",{children:nr.map(x=>t.jsx("button",{type:"button",className:Zf(ne.pose,c,x)?"active":"",onClick:()=>tt(ne.id,{pose:mj(ne.pose,c,x)}),children:a(x.label)},x.id))})]},c))}),t.jsxs("label",{className:"shot-field",children:[a("Mắt nhìn"),t.jsxs("select",{"aria-label":a("Mắt nhìn"),value:ne.gaze||"",onChange:c=>tt(ne.id,{gaze:c.target.value||void 0}),children:[t.jsx("option",{value:"",children:a("Theo tư thế")}),t.jsx("option",{value:"camera",children:a("Nhìn vào camera")}),z.items.filter(c=>c.id!==ne.id&&c.kind!=="splat"&&c.kind!=="set").map(c=>t.jsx("option",{value:c.id,children:a("Nhìn {0}",[c.name])},c.id))]})]}),Object.keys(Zi).map(c=>{const[x,L,P]=Jf[c],B=uj(ne.pose,c);return t.jsxs("label",{className:"shot-joint",children:[a(Zi[c])," ",t.jsxs("span",{children:[B,P]}),t.jsx("input",{"aria-label":a(Zi[c]),type:"range",min:x,max:L,value:B,disabled:(c==="eyeYaw"||c==="eyePitch")&&!!ne.gaze,onChange:X=>tt(ne.id,{pose:{...ne.pose,[c]:+X.target.value}})})]},c)})]})]}),t.jsx("button",{onClick:()=>{const c={...structuredClone(ne),id:vt(),name:`${ne.name} copy`,position:[ne.position[0]+1,...ne.position.slice(1)]};we(x=>({...x,items:[...x.items,c]})),xt(c.id)},children:a("Nhân bản")}),t.jsx("button",{onClick:()=>{ml(ne.id)},children:a("Xóa đối tượng")})]})]})]}),Q==="camera"&&t.jsxs(t.Fragment,{children:[t.jsx("input",{"aria-label":a("Tên shot"),value:de.name,onChange:c=>wt({name:c.target.value})}),t.jsxs("div",{className:"shot-camera-gizmo",role:"group","aria-label":a("Chỉnh camera trong cảnh 3D"),children:[t.jsxs("button",{type:"button",className:r?"active":"","aria-pressed":r,disabled:S,title:a("Bấm để chỉnh camera: kéo trục để di chuyển, vòng tròn để xoay"),onClick:()=>{xt(null),i(null),l(!r),ee(c=>c==="scale"?"translate":c)},children:[t.jsx(Ne.camera,{}),a("Chọn camera")]}),r&&["translate","rotate"].map(c=>t.jsxs("button",{type:"button",className:(_==="rotate"?"rotate":"translate")===c?"active":"","aria-pressed":(_==="rotate"?"rotate":"translate")===c,title:a(c==="translate"?"Di chuyển camera (W)":"Xoay camera (E): vòng xanh dương = nghiêng"),onClick:()=>ee(c),children:[c==="translate"?t.jsx(Ne.move,{}):t.jsx(Ne.rotate,{}),a(c==="translate"?"Di chuyển":"Xoay")]},c))]}),t.jsx("textarea",{className:"shot-note","aria-label":a("Ghi chú đạo diễn cho shot"),placeholder:a("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:de.note||"",onChange:c=>wt({note:c.target.value})}),t.jsxs("div",{className:"shot-row",children:[t.jsx("select",{"aria-label":a("Tỷ lệ ảnh"),value:de.aspect,onChange:c=>wt({aspect:c.target.value}),children:["16:9","9:16","1:1","21:9","4:3","2.39:1"].map(c=>t.jsx("option",{children:c},c))}),de.motion!=="path"&&t.jsx(es,{label:"Lens mm",value:de.lens,min:14,max:200,step:1,onChange:c=>wt({lens:c})})]}),t.jsxs("label",{className:"shot-field",children:[a("Thời lượng camera (giây)"),t.jsx(Sn,{"aria-label":a("Thời lượng camera (giây)"),min:.1,step:"0.1",value:de.duration,onCommit:c=>wt({duration:c})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Rung cầm tay")," ",t.jsxs("span",{children:[Math.round((de.handheld||0)*100),"%"]}),t.jsx("input",{"aria-label":a("Rung cầm tay"),type:"range",min:0,max:1,step:.05,value:de.handheld||0,onChange:c=>wt({handheld:+c.target.value||void 0})})]}),t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:de.impactShake!==!1,onChange:c=>{const x=c.target.checked;wt(x?{impactShake:void 0}:{impactShake:!1,impacts:void 0})}}),a("Rung camera khi trúng đòn")]}),t.jsx(Z1,{shot:de,patch:wt,progress:Ie,seek:c=>{D(!1),ot(c)},engine:Ce.current||null,selected:o,select:c=>{i(c),M(c?{row:"camera",id:c}:null)}}),de.motion==="path"&&t.jsx("button",{disabled:re||!at||!de.cameraKeys?.length,onClick:async()=>{D(!1),me(!0),ye("");try{for(const[c,x]of(de.cameraKeys||[]).entries())await is(!0,de,c,!1,x.time,` · Key ${c+1} · ${(x.time*de.duration).toFixed(1)}s`)}catch(c){ye(c.message)}finally{me(!1)}},children:a("Xuất các key thành ảnh tham chiếu")}),t.jsx("h3",{children:a("CHUYỂN ĐỘNG NHANH")}),t.jsxs("select",{"aria-label":a("Chuyển động camera"),value:de.motion,onChange:c=>mm(c.target.value),children:[t.jsx("option",{value:"path",disabled:!de.cameraKeys?.length,children:a("Đường chạy keyframe")}),t.jsx("option",{value:"static",children:a("Đứng yên")}),t.jsx("option",{value:"dolly-in",children:a("Dolly in")}),t.jsx("option",{value:"dolly-out",children:a("Dolly out")}),t.jsx("option",{value:"truck-left",children:a("Truck trái")}),t.jsx("option",{value:"truck-right",children:a("Truck phải")}),t.jsx("option",{value:"crane-up",children:a("Crane lên")}),t.jsx("option",{value:"crane-down",children:a("Crane xuống")}),t.jsx("option",{value:"orbit-left",children:a("Orbit trái")}),t.jsx("option",{value:"orbit-right",children:a("Orbit phải")}),t.jsx("option",{value:"custom",children:a("Tùy chỉnh")})]}),de.motion!=="static"&&de.motion!=="path"&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"shot-joint",children:[a("Xem chuyển động")," ",t.jsxs("span",{children:[Math.round(Ie*100),"%"]}),t.jsx("input",{"aria-label":a("Tiến trình camera"),type:"range",min:0,max:100,value:Ie*100,onChange:c=>ot(+c.target.value/100)})]}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Camera kết thúc")}),Ss(a("Vị trí cuối"),de.endPosition,c=>wt({endPosition:c,motion:"custom"})),Ss(a("Điểm nhìn cuối"),de.endTarget,c=>wt({endTarget:c,motion:"custom"})),t.jsx(es,{label:"Lens cuối mm",value:de.endLens,min:14,max:200,step:1,onChange:c=>wt({endLens:c,motion:"custom"})})]})]}),t.jsxs("fieldset",{disabled:de.motion==="path",style:{display:de.motion==="path"?"none":void 0},children:[t.jsx("button",{onClick:()=>wt(Ce.current?.captureCamera()||{}),children:a("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((c,x)=>t.jsx("button",{onClick:()=>{const L=ne?.position||[0,0,0];wt({position:[[3,2,6],[0,1.5,3],[0,1.7,1.2],[1,.3,3],[2,5,3],[.5,1.7,-1.5]][x].map((B,X)=>B+L[X]),target:[L[0],L[1]+(x===2?1.65:1.2),L[2]],roll:0})},children:a(c)},c))}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Thông số camera")}),Ss(a("Vị trí máy"),de.position,c=>wt({position:c})),Ss(a("Điểm nhìn"),de.target,c=>wt({target:c})),t.jsx(es,{label:"Nghiêng máy °",value:de.roll,min:-180,max:180,step:1,onChange:c=>wt({roll:c})}),t.jsx("button",{disabled:z.shots.length<2,onClick:()=>we(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera này")})]})]}),de.motion==="path"&&t.jsx("button",{disabled:z.shots.length<2,onClick:()=>we(c=>{const x=c.shots.filter(L=>L.id!==c.activeShot);return{...c,shots:x,activeShot:x[0].id}}),children:a("Xóa camera đường chạy")}),t.jsxs("details",{children:[t.jsx("summary",{children:a("Prompt bố cục")}),t.jsx("textarea",{"aria-label":a("Prompt bố cục"),readOnly:!0,value:Ti(z),rows:8}),t.jsx("button",{onClick:()=>navigator.clipboard.writeText(Ti(z)).then(()=>dt.getState().toast(a("Đã copy prompt"),"ok")).catch(()=>ye("Không truy cập được clipboard; hãy chọn và copy nội dung.")),children:a("Copy prompt")})]})]}),Q==="light"&&t.jsx("div",{className:"shot-light-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("select",{"aria-label":a("Thời điểm trong ngày"),value:kt.time,onChange:c=>{const x=c.target.value;An({time:x,elevation:cc[x].elevation})},children:e0.map(c=>t.jsx("option",{value:c,children:a(cc[c].label)},c))}),t.jsxs("label",{className:"shot-joint",children:[a("Hướng mặt trời")," ",t.jsxs("span",{children:[Math.round(kt.azimuth),"°"]}),t.jsx("input",{"aria-label":a("Hướng mặt trời"),type:"range",min:0,max:359,value:Math.round(kt.azimuth),onChange:c=>An({azimuth:+c.target.value})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Độ cao mặt trời")," ",t.jsxs("span",{children:[Math.round(kt.elevation),"°"]}),t.jsx("input",{"aria-label":a("Độ cao mặt trời"),type:"range",min:1,max:89,value:Math.round(kt.elevation),onChange:c=>An({elevation:+c.target.value})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Môi trường phản xạ")}),t.jsx("select",{"aria-label":a("Môi trường phản xạ"),value:kt.env??"auto",onChange:c=>An({env:c.target.value}),children:t0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),t.jsxs("label",{className:"shot-joint",children:[a("Xoay môi trường")," ",t.jsxs("span",{children:[Math.round(kt.envRotation??0),"°"]}),t.jsx("input",{"aria-label":a("Xoay môi trường"),type:"range",min:0,max:359,value:Math.round(kt.envRotation??0),onChange:c=>An({envRotation:+c.target.value})})]}),n0(kt)==="sky"&&t.jsxs("label",{className:"shot-joint",children:[a("Mây trên trời")," ",t.jsxs("span",{children:[Math.round(hc(kt)*100),"%"]}),t.jsx("input",{"aria-label":a("Mây trên trời"),type:"range",min:0,max:100,value:Math.round(hc(kt)*100),onChange:c=>An({clouds:+c.target.value/100})})]}),kt.time!=="interior"&&t.jsxs("label",{className:"shot-joint",title:a("Tia sáng từ mặt trời (đêm: mặt trăng) xuyên qua vật chắn — thấy ở chất lượng Cao và khi xuất video"),children:[a("Tia nắng mặt trời")," ",t.jsxs("span",{children:[Math.round((kt.sunRays??0)*100),"%"]}),t.jsx("input",{"aria-label":a("Tia nắng mặt trời"),type:"range",min:0,max:100,value:Math.round((kt.sunRays??0)*100),onChange:c=>An({sunRays:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-joint",children:[a("Ánh sáng viền (Rim)")," ",t.jsxs("span",{children:[Math.round((kt.rim??1)*100),"%"]}),t.jsx("input",{"aria-label":a("Ánh sáng viền (Rim)"),type:"range",min:0,max:200,value:Math.round((kt.rim??1)*100),onChange:c=>An({rim:+c.target.value/100})})]}),t.jsxs("label",{className:"shot-field",children:[t.jsx("span",{children:a("Xóa phông ống kính (DOF)")}),t.jsx("select",{"aria-label":a("Xóa phông ống kính (DOF)"),value:kt.dof??"off",onChange:c=>An({dof:c.target.value}),children:s0.map(c=>t.jsx("option",{value:c.id,children:a(c.label)},c.id))})]}),kt.dof&&t.jsxs("label",{className:"shot-joint",children:[a("Khoảng nét")," ",t.jsx("span",{children:kt.focusDistance?`${kt.focusDistance.toFixed(1)}m`:a("Tự động")}),t.jsx("input",{"aria-label":a("Khoảng nét"),type:"range",min:.5,max:40,step:.5,value:kt.focusDistance??Math.max(.5,Math.min(40,Math.hypot(de.position[0]-de.target[0],de.position[1]-de.target[1],de.position[2]-de.target[2]))),onChange:c=>An({focusDistance:+c.target.value})})]}),kt.dof&&kt.focusDistance!==void 0&&t.jsx("button",{type:"button",onClick:()=>An({focusDistance:void 0}),children:a("Lấy nét tự động theo mục tiêu")}),t.jsx("small",{className:"shot-hint",children:a("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.")}),kt.dof&&t.jsx(oj,{shot:de,items:z.items,progress:Ie,presetFstop:a0(kt.dof)??2.8,onChange:c=>wt({focus:c})}),t.jsxs("label",{className:"shot-field shot-render-style",children:[t.jsx("span",{children:a("Kiểu hình")}),t.jsxs("select",{"aria-label":a("Kiểu hình"),value:z.style?"clay":"natural",onChange:c=>{const x=c.target.value==="clay";we(L=>{const{style:P,...B}=L;return x?{...B,style:A0({...T0,...P||{},style:"clay"})}:B})},children:[t.jsx("option",{value:"natural",children:a("Tự nhiên")}),t.jsx("option",{value:"clay",children:a("Đất sét · phim tài liệu 3D")})]})]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.accents==="vivid",onChange:c=>{const x=c.target.checked?"vivid":"none";we(L=>L.style?{...L,style:{...L.style,accents:x}}:L)}}),a("Giữ màu nổi bật trên người (đồng phục đỏ, sọc vàng…)")]}),z.style&&t.jsxs("label",{className:"shot-check",children:[t.jsx("input",{type:"checkbox",checked:z.style.faceted,onChange:c=>{const x=c.target.checked;we(L=>L.style?{...L,style:{...L.style,faceted:x}}:L)}}),a("Mặt góc cạnh (low-poly)")]}),z.style&&t.jsx("small",{className:"shot-hint",children:a("Người và nhân vật thành tượng đất sét xám, bối cảnh và xe cộ giữ màu — kiểu phim tài liệu tội phạm 3D.")}),t.jsxs("label",{className:"shot-field shot-style-refs",children:[t.jsxs("span",{children:[a("Ảnh phong cách bối cảnh")," · ",ca.length,"/",Li]}),t.jsxs("select",{"aria-label":a("Thêm ảnh phong cách bối cảnh"),value:"",disabled:ca.length>=Li,onChange:c=>{const x=to.find(P=>P.id===c.target.value),L=x?.data;x&&L?.url&&we(P=>({...P,styleRefs:[...(P.styleRefs||[]).filter(B=>B.nodeId!==x.id),{nodeId:x.id,url:L.url,name:L.label||"Location look"}].slice(0,Li)}))},children:[t.jsx("option",{value:"",children:a("+ Chọn ảnh trên canvas…")}),to.filter(c=>!ca.some(x=>x.nodeId===c.id)).map(c=>t.jsx("option",{value:c.id,children:String(c.data.label||"Image")},c.id))]})]}),ca.length>0&&t.jsx("div",{className:"shot-style-strip",children:ca.map(c=>t.jsxs("span",{children:[t.jsx("img",{src:c.url,alt:c.name}),t.jsx("button",{"aria-label":a("Bỏ {0}",[c.name]),onClick:()=>we(x=>({...x,styleRefs:(x.styleRefs||[]).filter(L=>L.nodeId!==c.nodeId)})),children:"×"})]},c.nodeId))}),t.jsx("small",{className:"shot-hint",children:a("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.")})]})}),Q==="shots"&&t.jsx("div",{className:"shot-shots-section",children:t.jsx("ol",{className:"shot-shotlist",children:z.shots.map((c,x)=>{const L=Ml[x];return t.jsxs("li",{"data-shot":c.id,className:c.id===z.activeShot?"active":"",children:[t.jsxs("button",{className:"shot-shotlist-pick","aria-label":a("Chọn {0}",[c.name]),"aria-current":c.id===z.activeShot,disabled:!!A,onClick:()=>we(P=>({...P,activeShot:c.id})),children:[Rt[c.id]?t.jsx("img",{src:Rt[c.id],alt:""}):t.jsx("span",{className:"shot-thumb-empty","aria-hidden":"true"}),t.jsxs("span",{className:"shot-shotlist-meta",children:[t.jsx("b",{children:c.name}),t.jsxs("small",{children:[Ai(L.start),"–",Ai(L.end)," · ",Number(c.lens.toFixed(1)),"mm"]}),c.note?.trim()&&t.jsx("small",{className:"shot-shotlist-note",children:c.note.trim()})]})]}),t.jsxs("span",{className:"shot-shotlist-order",children:[t.jsx("button",{"aria-label":a("Đưa {0} lên",[c.name]),disabled:x===0||!!A,onClick:()=>Cl(c.id,-1),children:"↑"}),t.jsx("button",{"aria-label":a("Đưa {0} xuống",[c.name]),disabled:x===z.shots.length-1||!!A,onClick:()=>Cl(c.id,1),children:"↓"})]}),t.jsx("button",{className:"shot-shotlist-delete","aria-label":a("Xóa {0}",[c.name]),title:z.shots.length<2?a("Cảnh cần ít nhất một shot"):a("Xóa {0} (hoàn tác bằng ⌘Z)",[c.name]),disabled:z.shots.length<2||!!A,onClick:()=>Sl(c.id),children:t.jsx(Ne.trash,{})})]},c.id)})})}),Q==="notes"&&t.jsx("div",{className:"shot-notes-section",children:t.jsxs("div",{className:"shot-panel-body",children:[t.jsx("button",{className:it?"active":"","aria-pressed":it,disabled:!at||$s.length>=dc,onClick:sm,children:it?a("Bấm vào cảnh để ghim… (bấm lại để huỷ)"):a("+ Ghim ghi chú vào cảnh")}),t.jsx("ol",{className:"shot-note-list",children:$s.map((c,x)=>t.jsxs("li",{children:[t.jsx("span",{children:x+1}),t.jsx("input",{"aria-label":a("Ghi chú {0}",[x+1]),value:c.text,maxLength:uc,onChange:L=>am(c.id,L.target.value)}),t.jsx("button",{"aria-label":a("Xoá ghi chú {0}",[x+1]),onClick:()=>om(c.id),children:"×"})]},c.id))}),$s.length>0&&t.jsx("button",{disabled:re||!at,onClick:()=>void ym(),children:a("Tải PNG có ghi chú")}),t.jsx("small",{className:"shot-hint",children:a("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ú.")})]})}),Q==="series"&&t.jsx("div",{className:"shot-series-section",children:t.jsx("div",{className:"shot-panel-body",children:t.jsx(nj,{stage:z,nodeId:e,selected:z.items.find(c=>c.id===J)||null,disabled:re||!!A,change:we,onError:ye,onSelect:xt})})})]}),t.jsx("div",{className:"shot-resize shot-resize-x",role:"separator","aria-orientation":"vertical","aria-label":a("Kéo để đổi độ rộng bảng công cụ"),onPointerDown:c=>gi(c,"drawer")})]}),t.jsxs("main",{className:"shot-center",children:[t.jsxs("div",{className:"shot-monitor",children:[t.jsxs("div",{className:`shot-topbar ${U?"":"collapsed"}`,children:[t.jsxs("div",{className:"shot-shot-switcher",children:[t.jsx("select",{"aria-label":a("Chọn shot"),value:de.id,onChange:c=>we(x=>({...x,activeShot:c.target.value})),children:z.shots.map(c=>t.jsx("option",{value:c.id,children:c.name},c.id))}),t.jsxs("button",{onClick:()=>{const c={...structuredClone(de),id:vt(),name:`Shot ${z.shots.length+1}`};we(x=>({...x,shots:[...x.shots,c],activeShot:c.id}))},children:[t.jsx(Ne.save,{}),t.jsx("span",{className:"lbl",children:a("+ Lưu góc mới").replace("+ ","")})]}),t.jsx(ej,{shot:de,patch:wt,disabled:re||!!A})]}),t.jsxs("div",{className:"shot-viewtools",hidden:!U,children:[_==="scale"&&ne&&!ne.locked&&t.jsx(es,{label:"Tỷ lệ đồng đều",value:ne.scale[0],min:.05,step:ce?.1:.05,onChange:c=>tt(ne.id,{scale:ne.scale.map(x=>x*c/ne.scale[0])})}),t.jsxs("span",{className:"shot-tools-hint",children:[_==="scale"?a("Kéo ô vuông trên trục để đổi kích thước."):"",ce?a(" Bước: 1 m · 15° · tỷ lệ 0,1"):""]}),["translate","rotate","scale"].map((c,x)=>t.jsxs("button",{className:c===_?"active":"",title:a(["Di chuyển","Xoay","Kích thước"][x]),onClick:()=>ee(c),children:[[t.jsx(Ne.move,{},"m"),t.jsx(Ne.rotate,{},"r"),t.jsx(Ne.scale,{},"s")][x],t.jsx("span",{className:"lbl",children:a(["Di chuyển","Xoay","Kích thước"][x])})]},c)),t.jsxs("button",{className:ce?"active":"",title:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt"),onClick:()=>Le(!ce),children:[t.jsx(Ne.snap,{}),t.jsx("span",{className:"lbl",children:ce?a("Bám lưới: Bật"):a("Bám lưới: Tắt")})]}),t.jsxs("button",{className:je==="high"?"active":"","aria-pressed":je==="high",title:je==="high"?a("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."):a("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:()=>ie(je==="high"?"draft":"high"),children:[t.jsx(Ne.cinema,{}),t.jsx("span",{className:"lbl",children:je==="high"?a("Chất lượng cao"):a("Nháp")})]}),t.jsxs("button",{className:Me?"active":"","aria-pressed":Me,title:a("Path Trace (GPU Ray Tracing): ánh sáng nảy GI, bóng mềm & phản chiếu vật lý như Blender Cycles ngay trên trình duyệt"),onClick:()=>{D(!1),Be(null),Ee(c=>!c)},children:[t.jsx(Ne.spark,{}),t.jsx("span",{className:"lbl",children:a("Path Trace")})]}),t.jsxs("button",{className:ze?"active":"","aria-pressed":!!ze,title:a("Chụp nhanh lưới 6 góc máy điện ảnh từ cảnh hiện tại để chọn góc đẹp nhất chỉ bằng 1 bấm"),onClick:()=>{if(ze){Be(null);return}const c=Ce.current;if(!c)return;D(!1),Ee(!1);const x=ij(de.target,de.position,de.lens);Be(c.renderAngleSheet(x,360,202))},children:[t.jsx(Ne.camera,{}),t.jsx("span",{className:"lbl",children:a("6 góc máy")})]}),nd()&&t.jsxs("button",{className:Ze?"active":"","aria-pressed":Ze,title:Ze?a("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."):a("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 c=!Ze;cv(c),F(c)},children:[t.jsx(Ne.person,{}),t.jsx("span",{className:"lbl",children:Ze?a("Người thật"):a("Mannequin")})]}),t.jsxs("button",{title:a("Từ trên xuống"),onClick:()=>Ce.current?.view(!0),children:[t.jsx(Ne.top,{}),t.jsx("span",{className:"lbl",children:a("Từ trên xuống")})]}),t.jsxs("button",{title:a("Tập trung (F)"),"aria-keyshortcuts":"F",onClick:()=>Ce.current?.view(),children:[t.jsx(Ne.focus,{}),t.jsx("span",{className:"lbl",children:a("Tập trung")})]})]}),t.jsx("button",{className:"shot-tools-toggle","aria-expanded":U,title:U?a("Thu gọn công cụ"):a("Mở công cụ"),onClick:()=>{const c=!U;le(c);try{localStorage.setItem("clipoox.shot.tools",c?"1":"0")}catch{}},children:U?t.jsx(Ne.chevUp,{}):t.jsx(Ne.chevDown,{})})]}),t.jsxs("div",{className:"shot-viewport",ref:$e,onDragOver:c=>{(c.dataTransfer.types.includes(wr)||c.dataTransfer.types.includes(Ro))&&(c.preventDefault(),c.dataTransfer.dropEffect="copy")},onDrop:c=>{c.dataTransfer.types.includes(Ro)?tm(c):em(c)},children:[Me&&t.jsxs("div",{className:"shot-pt-overlay",children:[t.jsx("canvas",{ref:ln,className:"shot-pt-canvas"}),t.jsxs("div",{className:"shot-pt-hud",children:[t.jsx("span",{className:"shot-pt-status",children:be.done>=be.total?a("Path Trace · Xong ({0} mẫu)",[be.total]):a("Path Trace · {0}/{1} mẫu",[be.done,be.total])}),t.jsx("button",{type:"button",onClick:()=>he(c=>c==="shot"?"viewport":"shot"),children:Se==="shot"?a("Camera Shot"):a("Góc quan sát")}),t.jsx("button",{type:"button",onClick:()=>_e(c=>c+1),children:a("Vẽ lại")}),t.jsx("button",{type:"button",onClick:()=>{const c=Qt.current?.captureDataUrl();if(!c)return;const x=document.createElement("a");x.href=c,x.download=`clipoox-pathtrace-${Date.now()}.png`,x.click()},children:a("Lưu PNG")}),t.jsx("button",{type:"button",onClick:()=>Ee(!1),children:a("Đóng")})]})]}),ze&&t.jsxs("div",{className:"shot-angles-overlay",onPointerDown:c=>c.stopPropagation(),children:[t.jsxs("div",{className:"shot-angles-head",children:[t.jsx("b",{children:a("Chọn nhanh 6 góc máy điện ảnh")}),t.jsx("button",{type:"button",onClick:()=>Be(null),children:a("Đóng")})]}),t.jsx("div",{className:"shot-angles-grid",children:ze.map(c=>t.jsxs("button",{type:"button",className:"shot-angle-card",onClick:()=>{we(x=>({...x,shots:x.shots.map(L=>L.id===x.activeShot?{...L,position:[...c.camera],target:[...c.target],lens:c.lens}:L)})),Be(null)},children:[t.jsx("img",{src:c.dataUrl,alt:c.label}),t.jsxs("div",{className:"shot-angle-meta",children:[t.jsx("strong",{children:a(c.label)}),t.jsx("span",{children:a(c.subtitle)})]})]},c.id))})]})]}),t.jsx("span",{className:"shot-viewlabel",children:a("GÓC QUAN SÁT · không đổi camera xuất ảnh")}),ne&&fj(ne)&&!A&&(nn===ne.id?t.jsx(S1,{engine:at?Ce.current:null,stage:z,shot:de,item:ne,playhead:Ie*de.duration,change:we,onDone:()=>mt(null)}):t.jsxs("button",{type:"button",className:"shot-pose-chip",title:a("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:()=>{D(!1),mt(ne.id)},children:[t.jsx(Ne.person,{}),a("Chỉnh dáng")]})),ne&&Q!==(Ba(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects")&&t.jsxs("button",{type:"button",className:"shot-edit-chip",onClick:()=>Vn(Ba(ne)?"mixfx":ne.kind==="fx"?"fxedit":"objects"),children:[t.jsx(Ne.pen,{}),a("Chỉnh {0}",[ne.name])]})]}),t.jsx("div",{className:"shot-resize shot-resize-y",role:"separator","aria-orientation":"horizontal","aria-label":a("Kéo để đổi chiều cao timeline"),onPointerDown:c=>gi(c,"timeline")}),t.jsx(Yx,{loop:u,onLoop:()=>m(c=>!c),range:d,rangeOn:p,onRangeOn:()=>b(c=>!c),onEnd:()=>{D(!1),ot(1)},onKeyAll:Tl,onCopy:Ll,onPaste:El,canPaste:v,onEase:hm,onNudge:Il,stage:z,cameraActive:r,cameraHidden:k,cameraLocked:S,onToggle:lm,onProp:cm,height:ue.timeline,onHeight:c=>pe(x=>({...x,timeline:c})),shot:de,items:z.items,fxBars:nm,onParent:rm,onFxTiming:(c,x)=>we(L=>({...L,shots:L.shots.map(P=>P.id===L.activeShot?{...P,fxTiming:{...P.fxTiming,[c]:Pr({...Fn(L.items.find(B=>B.id===c),P),...x,off:!1},P.duration)}}:P)})),time:Ie,playing:H,selected:j,picked:T,onPick:Al,onSeek:c=>{D(!1),ot(c)},onPlay:()=>{!H&&Ie>=1&&ot(0),D(!H)},onRow:c=>{i(null),M(null),w([]),xt(c==="camera"?null:c),l(c==="camera"&&!S);{const x=z.items.find(L=>L.id===c);Ba(x)?Vn("mixfx"):x?.kind==="fx"&&Vn("fxedit")}},onSelect:im,onAdd:ui,onMove:um,onDelete:Rl})]}),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":a("Kéo để đổi độ rộng cột xem trước"),onPointerDown:c=>gi(c,"right")}),t.jsxs("section",{className:"shot-preview-pinned",children:[t.jsx("h3",{children:a("KHUNG CAMERA")}),t.jsx("div",{className:"shot-preview",style:{aspectRatio:Ei(de.aspect).join(" / "),width:`min(100%, ${30*Ei(de.aspect)[0]/Ei(de.aspect)[1]}dvh)`},ref:ks}),t.jsxs("div",{className:"shot-camera-player",children:[t.jsx("button",{"aria-label":H?a("Tạm dừng camera"):a("Phát camera"),onClick:()=>{!H&&Ie>=1&&ot(0),D(!H)},children:a(H?"Ⅱ Pause":"▶ Play")}),t.jsx("button",{"aria-label":a("Về đầu"),onClick:()=>{D(!1),ot(0)},children:"↤"}),t.jsxs("span",{children:[(Ie*de.duration).toFixed(1)," / ",de.duration,a("s")]}),t.jsx("input",{"aria-label":a("Thời gian camera"),type:"range",min:0,max:1,step:1e-4,value:Ie,onChange:c=>{D(!1),ot(+c.target.value)}})]}),z.plate&&t.jsxs("div",{className:"shot-plate-row",title:a("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":a("Hiện video nền"),checked:!z.plate.hidden,onChange:c=>{const x=c.target.checked;we(L=>L.plate?{...L,plate:{...L.plate,hidden:!x}}:L)}}),a("Hiện video nền")]})]}),z.plate&&t.jsxs("div",{className:"shot-plate-tools",children:[t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt||re,title:a("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 ll("follow"),children:Lt?.kind==="follow"?a("Đang đọc người… {0}%",[Lt.pct]):a("🧍 Bám theo người")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt||re,title:a("Camera của cảnh xoay / lia / zoom giống camera đã quay video."),onClick:()=>void ll("camera"),children:Lt?.kind==="camera"?a("Đang track camera… {0}%",[Lt.pct]):a("🎥 Lấy camera từ video")}),t.jsx("button",{type:"button",className:"pill-btn",disabled:!!Lt,title:a("Tải camera của shot thành script Python cho Blender, để dựng hiệu ứng khớp với video."),onClick:()=>void Gu(),children:a("⬇ Camera cho Blender")})]}),te.length>0&&t.jsxs("div",{className:"shot-placement",role:"status","aria-label":a("Cảnh báo vị trí nhân vật"),children:[t.jsx("ul",{children:te.map(c=>t.jsxs("li",{children:[t.jsxs("span",{children:["⚠ ",c.type==="floating"?a("{0} lơ lửng {1} m so với mặt đỡ",[c.name,String(c.amount)]):c.type==="sinking"?a("{0} chìm {1} m dưới mặt đỡ",[c.name,String(c.amount)]):c.type==="no_seat"?c.seat?a("{0} ngồi lơ lửng — có thể ngồi lên “{1}”",[c.name,c.seat]):a("{0} ngồi mà không có chỗ ngồi gần",[c.name]):a("{0} đang xuyên vào {1}",[c.name,(c.with||[]).join(", ")])]}),c.fix&&!c.locked&&t.jsx("button",{onClick:()=>tl([c]),children:c.type==="intersect"?a("Đẩy ra chỗ trống"):c.type==="no_seat"?a("Ngồi lên ghế gần nhất"):a("Đặt xuống mặt đỡ")})]},c.itemId+c.type))}),te.filter(c=>c.fix&&!c.locked).length>1&&t.jsx("button",{className:"shot-placement-all",onClick:()=>tl(te),children:a("Sửa tất cả ({0})",[String(te.filter(c=>c.fix&&!c.locked).length)])})]}),wl.length>0&&t.jsx("ul",{className:"shot-warnings",role:"status","aria-label":a("Cảnh báo liền mạch"),children:wl.map(c=>t.jsxs("li",{children:["⚠ ",a(c)]},c))})]}),t.jsx("section",{className:"shot-agent-card",children:t.jsx(q1,{stage:z,disabled:re||E||!!A,lock:{playhead:Math.round(Ie*de.duration*gn(de))/gn(de),onChange:c=>wt({lockUntil:o0(c,de.duration)||void 0})},agent:{selected:J,time:Ie,getBounds:()=>Ce.current?.objectBounds()||{},getColliders:()=>Ce.current?.placementColliders()||[],onPreview:(c,x)=>{D(!1);const L=$i(Ae.current,c);O({stage:L,plan:c,time:Ie,done:x}),ot(Math.min(...c.tracks.map(P=>P.keys[0].seconds))/c.duration),D(!0)},onApply:c=>{D(!1),we(x=>$i(x,c)),ot(0),i(null),M(null)}}})})]})]})]})}export{Hj as default};