clipoox-render 0.4.2 → 0.4.3

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 (105) hide show
  1. package/package.json +1 -1
  2. package/scripts/render-local.mjs +1322 -1320
  3. package/web/assets/{FxEmbed-CGqGi2Lw.js → FxEmbed-BCmj9Q5C.js} +1 -1
  4. package/web/assets/{MotionEmbed-C3CZ3_y_.js → MotionEmbed-CEmbcq8Z.js} +1 -1
  5. package/web/assets/PluginStore-C5hyahvG.js +3 -0
  6. package/web/assets/{ShotComposer-DFfaYLoV.js → ShotComposer-0DUtMTVI.js} +4 -4
  7. package/web/assets/{TemplateEmbed-C8pXcPsc.js → TemplateEmbed-ANxSs7H5.js} +1 -1
  8. package/web/assets/{TimelinePlugins-DnkV3i4G.js → TimelinePlugins-BYZ9y4m3.js} +4 -4
  9. package/web/assets/{TimelinePlugins-DYarX9RK.css → TimelinePlugins-D841ngau.css} +1 -1
  10. package/web/assets/{TimelineShotFx-foiuuogg.js → TimelineShotFx-q5PQwq-V.js} +2 -2
  11. package/web/assets/{TransitionEmbed-BueDilY0.js → TransitionEmbed-O6LInGWq.js} +1 -1
  12. package/web/assets/{Whiteboard-zBsNHh5h.js → Whiteboard-BP_DvIAV.js} +1 -1
  13. package/web/assets/{aerial-z34Nww_T.js → aerial-CGLDKKtP.js} +2 -2
  14. package/web/assets/{agentTools-ALxghYpf.js → agentTools-2Ghb80VH.js} +2 -2
  15. package/web/assets/{analyzerRun-DNwryAlU.js → analyzerRun-DRgxrcJA.js} +1 -1
  16. package/web/assets/{analyzerSandbox-A1oFsCrO.js → analyzerSandbox-DuIVFnsk.js} +1 -1
  17. package/web/assets/{api-DUp403BK.js → api-CJ8PdbfZ.js} +5 -5
  18. package/web/assets/{auraTrack-BKVZCwNt.js → auraTrack-DQw9sVU6.js} +1 -1
  19. package/web/assets/{breakthrough-Cwt8gEwK.js → breakthrough-BNj_iTDr.js} +2 -2
  20. package/web/assets/{cameraPresets-DSOPj4oy.js → cameraPresets-CYw0OdM3.js} +1 -1
  21. package/web/assets/{captionLayout-EuB59pN_.js → captionLayout-DvDPTwO9.js} +1 -1
  22. package/web/assets/{clientExport-BL1XMTF0.js → clientExport-xhoXY6Dh.js} +1 -1
  23. package/web/assets/conversion-4rhF3xRJ.js +17 -0
  24. package/web/assets/{depthEstimate-DOvsY8mn.js → depthEstimate-DEpeCojm.js} +1 -1
  25. package/web/assets/{directorTools-BkbNYbSq.js → directorTools-C5CpTmci.js} +1 -1
  26. package/web/assets/{distortFrames-Drch0LhT.js → distortFrames-Dia8O1NM.js} +2 -2
  27. package/web/assets/{distortGL-BlmBZKRU.js → distortGL-QalhICvi.js} +1 -1
  28. package/web/assets/{editTools-BcGinqHC.js → editTools-CY_JrQfw.js} +1 -1
  29. package/web/assets/engine-BedcnK45.js +1 -0
  30. package/web/assets/{exportEncode-MUwVTI52.js → exportEncode-QYsT9JBO.js} +1 -1
  31. package/web/assets/{exportGlb-SIXFRRJM.js → exportGlb-TSj09XoV.js} +1 -1
  32. package/web/assets/{faceTracker-DCbZbLMc.js → faceTracker-CnCWOwnJ.js} +1 -1
  33. package/web/assets/{fightDirector-hlF1JS_z.js → fightDirector-DCI_FWTh.js} +1 -1
  34. package/web/assets/{fightDrama-fHN5EXk3.js → fightDrama-Bg7uP_2Q.js} +2 -2
  35. package/web/assets/{frameSink-BvOXjLuw.js → frameSink-DeM8xC8_.js} +3 -3
  36. package/web/assets/{gpuCompose-CNkLwpbZ.js → gpuCompose-CA3UmOl4.js} +1 -1
  37. package/web/assets/{gpuExport-DQB6x4eh.js → gpuExport-D31azOQA.js} +13 -9
  38. package/web/assets/{handMatte-BD7OE3Zc.js → handMatte-Dl-xVXFR.js} +1 -1
  39. package/web/assets/{handTracker-BumGtRCW.js → handTracker-CplBsAFg.js} +2 -2
  40. package/web/assets/{id3-BCR9Bqgo.js → id3-arvEpAg7.js} +1 -1
  41. package/web/assets/{index-CuaB7Y0L.js → index-D5oyVCRl.js} +1 -1
  42. package/web/assets/index-_tSTJnL9.js +8 -0
  43. package/web/assets/layer-worker-DFuo32bk.js +5 -0
  44. package/web/assets/library-BufgA-Pl.js +1 -0
  45. package/web/assets/{lottieLayer-1ET89OUr.js → lottieLayer-DzbA3bHV.js} +4 -4
  46. package/web/assets/{lottie_light_canvas-DD9pkFL8.js → lottie_light_canvas-B-d7-ATe.js} +1 -1
  47. package/web/assets/main-VVYiW8XD.js +309 -0
  48. package/web/assets/{mapBake-DLoBt_k5.js → mapBake-BKOcEd0w.js} +1 -1
  49. package/web/assets/maskTrack-CHGXtBRy.js +1 -0
  50. package/web/assets/{matteFixRun-BdHKC3m5.js → matteFixRun-vgYrINet.js} +1 -1
  51. package/web/assets/{objectLocate-bZtc5AJo.js → objectLocate-BJltm8Ob.js} +1 -1
  52. package/web/assets/{output-BwZzMbp-.js → output-p-Q7qous.js} +1 -1
  53. package/web/assets/{pendingMatte-mlyLLZCT.js → pendingMatte-BPyzzx4y.js} +2 -2
  54. package/web/assets/{personAi-CUNQeseG.js → personAi-gJu03SjU.js} +2 -2
  55. package/web/assets/{plateCamera-_jP1xXnj.js → plateCamera-B2JvhjJw.js} +1 -1
  56. package/web/assets/{plateCameraMatch-rr0oUwQ2.js → plateCameraMatch-ByB9nVQT.js} +2 -2
  57. package/web/assets/{plateFollow-BjvtcT8q.js → plateFollow-C9S-l7RH.js} +2 -2
  58. package/web/assets/{plateMatte-BqyL8cQZ.js → plateMatte-J4qlNHnY.js} +2 -2
  59. package/web/assets/{pluginAutomation-Dp188qm7.js → pluginAutomation-CkP3tA9r.js} +1 -1
  60. package/web/assets/{poseTracker-DDGDhhMF.js → poseTracker-DGLbouqt.js} +1 -1
  61. package/web/assets/{productTools-CRgI88-O.js → productTools-CkaWF1bM.js} +2 -2
  62. package/web/assets/remote-C7J0Tqhb.js +1433 -0
  63. package/web/assets/{rigTrack-UYZU4P-e.js → rigTrack-urT3nDK0.js} +1 -1
  64. package/web/assets/{rotoMaskStore-BxyxB2bD.js → rotoMaskStore-DPziPKAN.js} +1 -1
  65. package/web/assets/{rotoMatte-BdYa8FSB.js → rotoMatte-C-2o3vv0.js} +1 -1
  66. package/web/assets/{rotoscope-DDixNQCt.js → rotoscope-GvPFRUBg.js} +1 -1
  67. package/web/assets/{shot-worker-D9sZS6bn.js → shot-worker-6dYkHPoL.js} +1 -1
  68. package/web/assets/{shotFxAgent-7RQNtEe4.js → shotFxAgent-BFLkqs8v.js} +1 -1
  69. package/web/assets/{skin-CVwmK130.js → skin-DY4QLaBI.js} +1 -1
  70. package/web/assets/{spark.module-B34aiScb.js → spark.module-DzziUgOj.js} +1 -1
  71. package/web/assets/{spellDuel-BkweL6pI.js → spellDuel-BD3m2ebA.js} +2 -2
  72. package/web/assets/store-Cug4GGcP.js +1 -0
  73. package/web/assets/{store-75tQUvPT.js → store-DW4E9xnW.js} +1 -1
  74. package/web/assets/{surfaceLight-DhU-zgNL.js → surfaceLight-aDSYU8Jg.js} +1 -1
  75. package/web/assets/surfacePin-m83hCgGP.js +2 -0
  76. package/web/assets/{textAnimators-nVSz_sZo.js → textAnimators-DUZjhVGO.js} +1 -1
  77. package/web/assets/{thumb-r6dlZprA.js → thumb-CS0ZuiGS.js} +1 -1
  78. package/web/assets/{timeline3d-246tBEJl.js → timeline3d-DOw-CpZI.js} +2 -2
  79. package/web/assets/{timeline3dExport-T57qnWi9.js → timeline3dExport-BtYLU1pw.js} +1 -1
  80. package/web/assets/{timelineComp-BcewYGR2.js → timelineComp-B4GtoH2f.js} +1 -1
  81. package/web/assets/{timelineProps-CJzzAWWO.js → timelineProps-D7MVutxu.js} +1 -1
  82. package/web/assets/{timelineText-BzUhNWPB.js → timelineText-BH09jfSM.js} +1 -1
  83. package/web/assets/{titleArt-B8DVR58F.js → titleArt-Drsrtfiv.js} +3 -3
  84. package/web/assets/{titleFrameBudget-BYRZAQPs.js → titleFrameBudget-CLZWaFHO.js} +1 -1
  85. package/web/assets/{titleFrames-BVgm601q.js → titleFrames-BI1DnLBn.js} +1 -1
  86. package/web/assets/{tool-CAGU3dUa.js → tool-DktQYmS6.js} +1 -1
  87. package/web/assets/{tools-DVaOkokV.js → tools-Co9aRDiT.js} +1 -1
  88. package/web/assets/{toonTools-CfGTR_H1.js → toonTools-CD9clJvN.js} +2 -2
  89. package/web/assets/{trackAnchor-DzUt1r5Q.js → trackAnchor-sOjTtd3I.js} +1 -1
  90. package/web/assets/{userFonts-DzY0A4bD.js → userFonts-CwlKh9NR.js} +1 -1
  91. package/web/assets/{vfxAlpha-DQJOaZ9v.js → vfxAlpha-71tSN86T.js} +2 -2
  92. package/web/assets/{vfxBackground-DiktQFOD.js → vfxBackground-Bq7lJvmZ.js} +2 -2
  93. package/web/assets/{videoExport-Ce0ElSQR.js → videoExport-D4KbireJ.js} +1 -1
  94. package/web/assets/{views-V3si1lOz.js → views-ozVF4ABO.js} +1 -1
  95. package/web/assets/{weaponDuel-D6sLVGmG.js → weaponDuel-ZhX-tjGZ.js} +1 -1
  96. package/web/assets/{windowFrames-D_2QJCJJ.js → windowFrames-CpqX3kOM.js} +1 -1
  97. package/web/layer-worker.html +3 -3
  98. package/web/assets/PluginStore-DKXZ-jBj.js +0 -3
  99. package/web/assets/index-DYa7fEK0.js +0 -24
  100. package/web/assets/layer-worker-DxPMMKIZ.js +0 -5
  101. package/web/assets/library-CyjJ8nGG.js +0 -1
  102. package/web/assets/main-BKjBWQik.js +0 -309
  103. package/web/assets/maskTrack-C2SJbDGO.js +0 -1
  104. package/web/assets/remote-Dva2qg58.js +0 -1241
  105. package/web/assets/surfacePin-ObK6QgDm.js +0 -2
@@ -1 +1 @@
1
- import{trackPose as S}from"./poseTracker-DDGDhhMF.js";import{i9 as v,ia as w,ib as T}from"./remote-Dva2qg58.js";import{c1 as q,c0 as x}from"./titleFrameBudget-BYRZAQPs.js";import{u as z}from"./store-75tQUvPT.js";import{t as l}from"./api-DUp403BK.js";import"./main-BKjBWQik.js";import"./three.module-Bx43vjkH.js";import"./spark.module-B34aiScb.js";import"./timelineComp-BcewYGR2.js";import"./rotoMaskStore-BxyxB2bD.js";import"./textAnimators-nVSz_sZo.js";import"./userFonts-DzY0A4bD.js";import"./lottieLayer-1ET89OUr.js";import"./rigTrack-UYZU4P-e.js";import"./timeline3d-246tBEJl.js";import"./GLTFLoader-BHWu1lKg.js";import"./RoomEnvironment-Dmv_G5ka.js";import"./exportEncode-MUwVTI52.js";import"./captionLayout-EuB59pN_.js";import"./timelineText-BzUhNWPB.js";import"./titleArt-B8DVR58F.js";import"./rotoMatte-BdYa8FSB.js";import"./distortGL-BlmBZKRU.js";import"./motionBlur-uAm030t9.js";async function _(p,f){const m=f.params??{},s=z.getState(),r=s.clips.find(t=>t.id===m.source);if(!r||r.kind!=="video")throw Error(l("Không tìm thấy clip video để bám dáng người"));const g=document.querySelector(`video[data-clip-media="${r.id}"]`)?.currentSrc||r.url,a=m.from??0,y=m.duration??p.duration,{frames:c,aspect:k}=await S({clip:r,url:g,from:a,duration:y,fps:v.fps,person:m.person??1});if(!c.some(t=>t.lm))throw Error(l("Không thấy người trong đoạn này để gắn aura"));const{width:u,height:d}=q(s.timelineFormat),b=Math.round(k*1e3),A=1e3,M=w(c.map(t=>({t:t.t,lm:t.lm})),([t,e])=>[t,e]).map(t=>{const e=a+t[0],n=[t[0]];for(let i=1;i<t.length;i+=2){if(t[i]<0){n.push(-1,-1);continue}const h=x(r,t[i],t[i+1],e,u,d,b,A);n.push(Math.round(h.px/u*1e3)/1e3,Math.round(h.py/d*1e3)/1e3)}return n}),o=p.motion?.params??{};return{motion:T(M,{look:o.look,color:o.color,hot:o.hot,size:o.size,intensity:o.intensity,wind:[Number(o.windX)||0,Number(o.windY)||0],speed:o.speed,stretch:o.stretch,taper:o.taper})}}export{_ as runAuraTrack};
1
+ import{trackPose as S}from"./poseTracker-DGLbouqt.js";import{iB as v,iC as w,iD as T}from"./remote-C7J0Tqhb.js";import{c1 as q,c0 as x}from"./titleFrameBudget-CLZWaFHO.js";import{u as z}from"./store-DW4E9xnW.js";import{t as l}from"./api-CJ8PdbfZ.js";import"./main-VVYiW8XD.js";import"./three.module-Bx43vjkH.js";import"./spark.module-DzziUgOj.js";import"./GLTFLoader-BHWu1lKg.js";import"./rotoMaskStore-DPziPKAN.js";import"./textAnimators-DUZjhVGO.js";import"./timelineComp-B4GtoH2f.js";import"./rigTrack-urT3nDK0.js";import"./userFonts-CwlKh9NR.js";import"./lottieLayer-DzbA3bHV.js";import"./timeline3d-DOw-CpZI.js";import"./RoomEnvironment-Dmv_G5ka.js";import"./exportEncode-QYsT9JBO.js";import"./captionLayout-DvDPTwO9.js";import"./timelineText-BH09jfSM.js";import"./titleArt-Drsrtfiv.js";import"./rotoMatte-C-2o3vv0.js";import"./distortGL-QalhICvi.js";import"./motionBlur-uAm030t9.js";async function _(p,f){const m=f.params??{},s=z.getState(),r=s.clips.find(t=>t.id===m.source);if(!r||r.kind!=="video")throw Error(l("Không tìm thấy clip video để bám dáng người"));const g=document.querySelector(`video[data-clip-media="${r.id}"]`)?.currentSrc||r.url,a=m.from??0,y=m.duration??p.duration,{frames:c,aspect:k}=await S({clip:r,url:g,from:a,duration:y,fps:v.fps,person:m.person??1});if(!c.some(t=>t.lm))throw Error(l("Không thấy người trong đoạn này để gắn aura"));const{width:u,height:d}=q(s.timelineFormat),b=Math.round(k*1e3),A=1e3,M=w(c.map(t=>({t:t.t,lm:t.lm})),([t,e])=>[t,e]).map(t=>{const e=a+t[0],n=[t[0]];for(let i=1;i<t.length;i+=2){if(t[i]<0){n.push(-1,-1);continue}const h=x(r,t[i],t[i+1],e,u,d,b,A);n.push(Math.round(h.px/u*1e3)/1e3,Math.round(h.py/d*1e3)/1e3)}return n}),o=p.motion?.params??{};return{motion:T(M,{look:o.look,color:o.color,hot:o.hot,size:o.size,intensity:o.intensity,wind:[Number(o.windX)||0,Number(o.windY)||0],speed:o.speed,stretch:o.stretch,taper:o.taper})}}export{_ as runAuraTrack};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/remote-Dva2qg58.js","assets/api-DUp403BK.js","assets/titleFrameBudget-BYRZAQPs.js","assets/three.module-Bx43vjkH.js","assets/GLTFLoader-BHWu1lKg.js","assets/store-75tQUvPT.js","assets/rotoMaskStore-BxyxB2bD.js","assets/textAnimators-nVSz_sZo.js","assets/timelineComp-BcewYGR2.js","assets/rigTrack-UYZU4P-e.js"])))=>i.map(i=>d[i]);
2
- import{_ as C}from"./titleFrameBudget-BYRZAQPs.js";import{iY as L,fq as B,gM as x,jt as F,iR as A,fF as G,ft as U,fs as z,hG as H}from"./remote-Dva2qg58.js";import{c as V}from"./cameraPresets-DSOPj4oy.js";import"./api-DUp403BK.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-75tQUvPT.js";import"./rotoMaskStore-BxyxB2bD.js";import"./textAnimators-nVSz_sZo.js";import"./timelineComp-BcewYGR2.js";import"./rigTrack-UYZU4P-e.js";const Y=()=>crypto.randomUUID(),s=i=>Math.round(i*100)/100,N={"luyen-khi":{color:"#e6f2ff",tiers:9,core:!1,name:"Luyện khí"},"truc-co":{color:"#5cff9a",tiers:3,core:!1,name:"Trúc cơ"},"ket-dan":{color:"#ffcf4a",tiers:9,core:!0,name:"Kết đan"},"nguyen-anh":{color:"#b066ff",tiers:12,core:!0,name:"Nguyên anh"},"hoa-than":{color:"#5cc8ff",tiers:12,core:!0,name:"Hoá thần"}};function J(i,c){const e=x(i),$=e.duration/c,u=n=>n?.map(f=>({...f,time:Math.min(1,f.time*$)})),m={...e,duration:c,cameraKeys:u(e.cameraKeys)??[],objectKeys:Object.fromEntries(Object.entries(e.objectKeys||{}).map(([n,f])=>[n,u(f)||[]])),...e.flight?{flight:Object.fromEntries(Object.entries(e.flight).map(([n,f])=>[n,u(f)||[]]))}:{}};return{...i,shots:i.shots.map(n=>n.id===e.id?m:n)}}async function nt(i,c){let e;try{e=L(c.getStage(),String(i.name??""))}catch(t){return{ok:!1,error:t.message}}if(!B(e))return{ok:!1,error:`'${e.name}' is not a person`};const $=String(i.realm??"ket-dan"),u=N[$];if(!u)return{ok:!1,error:`unknown realm; use one of ${Object.keys(N).join(", ")}`};const m=i.outcome==="fail",n=i.tribulation!==!1,f=Math.max(1,Math.min(9,Number(i.strikes??4)||4)),v=Math.max(.8,Math.min(12,Number(i.height??2)||2)),y=Math.max(0,Number(i.start??0)||0),P=String(i.color??u.color),M=y+2.6,g=M+3.2,T=g+1.2,j=n?1.6+f*1.05:0,R=g+2.4+j,h=R,p=h+1.6,_=p+2.2,w=m?h+2.6:_+2.6;let l=c.getStage();w+.5>x(l).duration&&(l=J(l,Math.min(300,Math.ceil((w+.6)*10)/10)));const S=[],O=[],k=(t,r,o=!1)=>{const a=z(t);if(!a){S.push(`${t} missing`);return}const d=H(l,e.id,a,{start:r/x(l).duration,newId:Y,loop:o});d.ok?(l=d.stage,O.push({motion:t,at_s:s(r)})):S.push(`${t}: ${d.error}`)};k("xx-seal-seated",y),k("xx-bt-gather",M,!0),k("xx-bt-strain",g,!0);const E=T,D=n?F(j+1.2,f).map(t=>E+t):[];for(const t of D)k("xx-bt-endure",Math.max(g,t-.12));if(m)k("xx-bt-backlash",h);else{const t=x(l),r=t.duration;let o=A(t.flight?.[e.id],{time:h/r,on:!0,height:v});o=A(o,{time:(_+1.4)/r,on:!1}),l={...l,shots:l.shots.map(a=>a.id===t.id?{...a,flight:{...a.flight,[e.id]:o}}:a)},k("xx-bt-lotus-air",h,!0),k("xx-bt-roar",p),k("xx-bt-settle",_)}c.setStage(()=>l);const{runTool:q}=await C(async()=>{const{runTool:t}=await import("./remote-Dva2qg58.js").then(r=>r.jA);return{runTool:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),I=[],b=async(t,r,o,a={})=>{const d=await q("add_effect",{effect:t,attach_to:e.name,start:s(r),duration:o,color:P,...a},c);d.ok?I.push({effect:t,start_s:s(r)}):S.push(`${t}: ${String(d.error)}`)};if(await b("linh-khi-quy-nguyen",y+.6,g-y+1),await b("kinh-mach-kim",M+.8,4),await b("canh-gioi-ket-dan",g-.4,2.4+j+.8,{params:{tiers:u.tiers}}),n&&await b(m?"kiep-van-huyet":"kiep-van-thien-loi",E,j+1.2,{params:{strikes:f},color:m?"#ff3040":"#9fd8ff"}),m)await b("huyet-vu",h+.5,1.6);else if(u.core&&await b("kim-dan-thanh",h+.2,1.8,{params:{seated:1,lift:v}}),await b("thien-quang-tru-kim",p+.62,3.2),await b("dot-pha-song-kim",p+.62,2.4,{params:{seated:1,lift:v}}),i.timing!==!1){const t=x(c.getStage()),r=G(U(t.timing,t.duration),p+.7,.45,.35,t.duration);c.setStage(o=>({...o,shots:o.shots.map(a=>a.id===t.id?{...a,timing:r??void 0}:a)}))}const K=[];if(i.camera!==!1){const t=[["orbit-180",y,g],["wide-track",g,T+.4],["low-hero",T+.4,m?w:p],...m?[]:[["wide-track",p,p+2.2],["orbit-180",_,w]]];for(const[r,o,a]of t){if(a-o<.4)continue;const d=V(c.getStage(),{preset:r,subject:e.id,start:o,end:a});d.ok&&(c.setStage(()=>d.stage),K.push(`${r} ${s(o)}–${s(a)} s`))}}return{ok:!0,name:e.name,realm:u.name,outcome:m?"fail":"success",start_s:s(y),gather_s:s(M),tribulation_s:n?s(E):null,strikes_s:D.map(s),...m?{backlash_s:s(h)}:{rise_s:s(h),burst_s:s(p+.62),landed_s:s(_+1.4)},end_s:s(w),moves:O,effects:I,...K.length?{camera:K}:{},...S.length?{notes:S}:{}}}export{N as REALMS,nt as stageBreakthrough};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/remote-C7J0Tqhb.js","assets/api-CJ8PdbfZ.js","assets/titleFrameBudget-CLZWaFHO.js","assets/three.module-Bx43vjkH.js","assets/GLTFLoader-BHWu1lKg.js","assets/store-DW4E9xnW.js","assets/rotoMaskStore-DPziPKAN.js","assets/textAnimators-DUZjhVGO.js","assets/timelineComp-B4GtoH2f.js","assets/rigTrack-urT3nDK0.js"])))=>i.map(i=>d[i]);
2
+ import{_ as C}from"./titleFrameBudget-CLZWaFHO.js";import{iY as L,fq as B,gM as x,jt as F,iR as A,fF as G,ft as U,fs as z,hG as H}from"./remote-C7J0Tqhb.js";import{c as V}from"./cameraPresets-CYw0OdM3.js";import"./api-CJ8PdbfZ.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-DW4E9xnW.js";import"./rotoMaskStore-DPziPKAN.js";import"./textAnimators-DUZjhVGO.js";import"./timelineComp-B4GtoH2f.js";import"./rigTrack-urT3nDK0.js";const Y=()=>crypto.randomUUID(),s=i=>Math.round(i*100)/100,N={"luyen-khi":{color:"#e6f2ff",tiers:9,core:!1,name:"Luyện khí"},"truc-co":{color:"#5cff9a",tiers:3,core:!1,name:"Trúc cơ"},"ket-dan":{color:"#ffcf4a",tiers:9,core:!0,name:"Kết đan"},"nguyen-anh":{color:"#b066ff",tiers:12,core:!0,name:"Nguyên anh"},"hoa-than":{color:"#5cc8ff",tiers:12,core:!0,name:"Hoá thần"}};function J(i,c){const e=x(i),$=e.duration/c,u=n=>n?.map(f=>({...f,time:Math.min(1,f.time*$)})),m={...e,duration:c,cameraKeys:u(e.cameraKeys)??[],objectKeys:Object.fromEntries(Object.entries(e.objectKeys||{}).map(([n,f])=>[n,u(f)||[]])),...e.flight?{flight:Object.fromEntries(Object.entries(e.flight).map(([n,f])=>[n,u(f)||[]]))}:{}};return{...i,shots:i.shots.map(n=>n.id===e.id?m:n)}}async function nt(i,c){let e;try{e=L(c.getStage(),String(i.name??""))}catch(t){return{ok:!1,error:t.message}}if(!B(e))return{ok:!1,error:`'${e.name}' is not a person`};const $=String(i.realm??"ket-dan"),u=N[$];if(!u)return{ok:!1,error:`unknown realm; use one of ${Object.keys(N).join(", ")}`};const m=i.outcome==="fail",n=i.tribulation!==!1,f=Math.max(1,Math.min(9,Number(i.strikes??4)||4)),v=Math.max(.8,Math.min(12,Number(i.height??2)||2)),y=Math.max(0,Number(i.start??0)||0),P=String(i.color??u.color),M=y+2.6,g=M+3.2,T=g+1.2,j=n?1.6+f*1.05:0,R=g+2.4+j,h=R,p=h+1.6,_=p+2.2,w=m?h+2.6:_+2.6;let l=c.getStage();w+.5>x(l).duration&&(l=J(l,Math.min(300,Math.ceil((w+.6)*10)/10)));const S=[],O=[],k=(t,r,o=!1)=>{const a=z(t);if(!a){S.push(`${t} missing`);return}const d=H(l,e.id,a,{start:r/x(l).duration,newId:Y,loop:o});d.ok?(l=d.stage,O.push({motion:t,at_s:s(r)})):S.push(`${t}: ${d.error}`)};k("xx-seal-seated",y),k("xx-bt-gather",M,!0),k("xx-bt-strain",g,!0);const E=T,D=n?F(j+1.2,f).map(t=>E+t):[];for(const t of D)k("xx-bt-endure",Math.max(g,t-.12));if(m)k("xx-bt-backlash",h);else{const t=x(l),r=t.duration;let o=A(t.flight?.[e.id],{time:h/r,on:!0,height:v});o=A(o,{time:(_+1.4)/r,on:!1}),l={...l,shots:l.shots.map(a=>a.id===t.id?{...a,flight:{...a.flight,[e.id]:o}}:a)},k("xx-bt-lotus-air",h,!0),k("xx-bt-roar",p),k("xx-bt-settle",_)}c.setStage(()=>l);const{runTool:q}=await C(async()=>{const{runTool:t}=await import("./remote-C7J0Tqhb.js").then(r=>r.jA);return{runTool:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),I=[],b=async(t,r,o,a={})=>{const d=await q("add_effect",{effect:t,attach_to:e.name,start:s(r),duration:o,color:P,...a},c);d.ok?I.push({effect:t,start_s:s(r)}):S.push(`${t}: ${String(d.error)}`)};if(await b("linh-khi-quy-nguyen",y+.6,g-y+1),await b("kinh-mach-kim",M+.8,4),await b("canh-gioi-ket-dan",g-.4,2.4+j+.8,{params:{tiers:u.tiers}}),n&&await b(m?"kiep-van-huyet":"kiep-van-thien-loi",E,j+1.2,{params:{strikes:f},color:m?"#ff3040":"#9fd8ff"}),m)await b("huyet-vu",h+.5,1.6);else if(u.core&&await b("kim-dan-thanh",h+.2,1.8,{params:{seated:1,lift:v}}),await b("thien-quang-tru-kim",p+.62,3.2),await b("dot-pha-song-kim",p+.62,2.4,{params:{seated:1,lift:v}}),i.timing!==!1){const t=x(c.getStage()),r=G(U(t.timing,t.duration),p+.7,.45,.35,t.duration);c.setStage(o=>({...o,shots:o.shots.map(a=>a.id===t.id?{...a,timing:r??void 0}:a)}))}const K=[];if(i.camera!==!1){const t=[["orbit-180",y,g],["wide-track",g,T+.4],["low-hero",T+.4,m?w:p],...m?[]:[["wide-track",p,p+2.2],["orbit-180",_,w]]];for(const[r,o,a]of t){if(a-o<.4)continue;const d=V(c.getStage(),{preset:r,subject:e.id,start:o,end:a});d.ok&&(c.setStage(()=>d.stage),K.push(`${r} ${s(o)}–${s(a)} s`))}}return{ok:!0,name:e.name,realm:u.name,outcome:m?"fail":"success",start_s:s(y),gather_s:s(M),tribulation_s:n?s(E):null,strikes_s:D.map(s),...m?{backlash_s:s(h)}:{rise_s:s(h),burst_s:s(p+.62),landed_s:s(_+1.4)},end_s:s(w),moves:O,effects:I,...K.length?{camera:K}:{},...S.length?{notes:S}:{}}}export{N as REALMS,nt as stageBreakthrough};
@@ -1 +1 @@
1
- import{fq as O,gM as K,iA as B,fu as L,hD as R,iB as W}from"./remote-Dva2qg58.js";const I=n=>n*Math.PI/180,y=(n,t,a)=>n<t?t:n>a?a:n,F=n=>{const t=y(n,0,1);return t*t*(3-2*t)},G={smooth:F,linear:n=>y(n,0,1),in:n=>{const t=y(n,0,1);return t*t*t},out:n=>{const t=1-y(n,0,1);return 1-t*t*t},snap:n=>1-Math.pow(1-y(n,0,1),4)},Z=Object.freeze([{id:"follow",name:"Bám theo",nameEn:"Follow"},{id:"reveal",name:"Quay vòng & lộ diện",nameEn:"Orbit & reveal"},{id:"impact",name:"Theo cú đánh",nameEn:"Impact"},{id:"director",name:"Đạo diễn hành động",nameEn:"Action director"},{id:"story",name:"Kể chuyện",nameEn:"Storytelling"}]),_=Object.freeze([{id:"side-track",cat:"follow",name:"Bám ngang",nameEn:"Side tracking",desc:"Máy quay chạy song song bên hông nhân vật, giữ khung trung cảnh — kiểu showreel game hành động.",descEn:"The camera runs alongside the subject at a medium framing — the action game showreel look.",lens:35,aim:.5,smooth:.35,path:[{u:0,offset:[4.2,.15,.4]},{u:1,offset:[4.2,.15,.4]}]},{id:"wide-track",cat:"follow",name:"Toàn cảnh bám ngang",nameEn:"Wide tracking",desc:"Toàn cảnh từ xa, ống kính rộng, thấy cả không gian và đường di chuyển.",descEn:"A wide shot from far off: the whole space and the path of the action.",lens:28,aim:.45,smooth:.6,path:[{u:0,offset:[7.5,.4,1.2]},{u:1,offset:[7.5,.4,1.2]}]},{id:"follow-behind",cat:"follow",name:"Bám sau lưng",nameEn:"Over-the-shoulder follow",desc:"Sau lưng, cao hơn đầu một chút — người xem đi cùng nhân vật.",descEn:"Behind and a little above the head — the audience moves with the subject.",lens:28,aim:.6,smooth:.3,handheld:.25,path:[{u:0,offset:[.7,.55,-2.6]},{u:1,offset:[.6,.5,-2.3]}]},{id:"low-hero",cat:"follow",name:"Góc thấp anh hùng",nameEn:"Low hero angle",desc:"Máy đặt thấp ngước lên, đẩy vào chậm — nhân vật trông mạnh mẽ.",descEn:"Low and looking up with a slow push in: the subject looks powerful.",lens:[24,28],aim:.62,smooth:.4,path:[{u:0,offset:[1.6,-.62,3.2]},{u:1,offset:[1.2,-.62,2.4],ease:"smooth"}]},{id:"worm-eye-dutch",cat:"follow",name:"Nhìn từ đất lên trời",nameEn:"Worm's-eye dutch",desc:"Máy sát đất ngước thẳng lên trời, ống kính rộng, khung nghiêng xoay dần — cảnh đấu trên không kiểu Dragon Ball.",descEn:"From the ground looking straight up, a wide lens and a slowly turning tilt — the sky battle of an anime.",lens:18,roll:[-14,10],aim:.85,smooth:.35,path:[{u:0,offset:[1.4,-.92,1.2]},{u:1,offset:[2,-.92,.4],ease:"smooth"}]},{id:"ground-level",cat:"follow",name:"Sát mặt đất",nameEn:"Ground level",desc:"Máy gần như nằm trên sàn — cho cú ngã, cú lộn, đòn quét chân.",descEn:"The camera almost on the floor: for falls, rolls and leg sweeps.",lens:22,aim:.3,smooth:.3,path:[{u:0,offset:[3,-.88,1.4]},{u:1,offset:[2.6,-.88,1]}]},{id:"orbit-180",cat:"reveal",name:"Quay vòng 180°",nameEn:"Orbit 180°",desc:"Vòng nửa quanh nhân vật từ hông sang mặt kia.",descEn:"Half a circle round the subject, from one side to the other.",lens:35,aim:.55,smooth:.4,path:[{u:0,offset:[3.6,.2,.6]},{u:1,offset:[-3.6,.2,.6],turn:180}]},{id:"bullet-time",cat:"reveal",name:"Bullet time",nameEn:"Bullet time",desc:"Vòng nhanh 270° quanh đòn đánh, sát và thấp — kiểu Ma trận.",descEn:"A fast 270° circle round the action, close and low — the Matrix look.",lens:30,aim:.55,smooth:.5,path:[{u:0,offset:[2.4,0,1.2]},{u:1,offset:[-2.4,.1,-1.2],turn:270,ease:"linear"}]},{id:"crane-down",cat:"reveal",name:"Cần cẩu hạ xuống",nameEn:"Crane down reveal",desc:"Từ trên cao hạ xuống ngang ngực, ống kính hẹp dần.",descEn:"From high above down to chest height, the lens tightening.",lens:[24,40],aim:.5,smooth:.5,path:[{u:0,offset:[2.2,3.6,4.2]},{u:1,offset:[1.6,.1,3]}]},{id:"dolly-zoom",cat:"reveal",name:"Dolly zoom (Vertigo)",nameEn:"Dolly zoom (Vertigo)",desc:"Máy lùi ra trong khi ống kính zoom vào: nhân vật giữ nguyên, hậu cảnh co giãn.",descEn:"The camera pulls back as the lens zooms in: the subject holds its size while the background warps.",lens:24,vertigo:!0,aim:.55,smooth:.4,path:[{u:0,offset:[.4,.1,2.2]},{u:1,offset:[.4,.1,6.5],ease:"smooth"}]},{id:"dutch-push",cat:"reveal",name:"Đẩy vào nghiêng",nameEn:"Dutch push-in",desc:"Đẩy vào với khung hình nghiêng dần — căng thẳng, bất an.",descEn:"A push in while the frame tilts — tension, unease.",lens:[32,45],roll:[0,14],aim:.62,smooth:.4,path:[{u:0,offset:[1.2,.2,4]},{u:1,offset:[.7,.15,2.4]}]},{id:"crash-zoom",cat:"impact",name:"Crash zoom vào đòn",nameEn:"Crash zoom on the hit",desc:"Toàn cảnh ngang, đúng đòn đầu tiên ống kính giật zoom vào cận và giữ.",descEn:"A wide side view; on the first strike the lens snaps in to a close-up and holds.",lens:26,aim:.55,smooth:.4,beats:{crash:2.6,shake:.7},path:[{u:0,offset:[5.2,.2,.6]},{u:1,offset:[5,.2,.6]}]},{id:"punch-beats",cat:"impact",name:"Punch-in theo nhịp đòn",nameEn:"Punch-in on every hit",desc:"Mỗi đòn trúng: ống kính giật vào 1 nhịp và rung — nhịp anime/game.",descEn:"Every strike kicks the lens in for a beat with a shake — the anime / game rhythm.",lens:32,aim:.55,smooth:.35,handheld:.15,beats:{punch:.35,shake:.55},path:[{u:0,offset:[3.6,.15,1]},{u:1,offset:[3.4,.15,.9]}]},{id:"whip-pan",cat:"impact",name:"Lia nhanh (whip pan)",nameEn:"Whip pan",desc:"Giữa cảnh máy lia vụt sang góc đối diện của nhân vật.",descEn:"Mid-shot the camera whips round to the opposite side of the subject.",lens:32,aim:.55,smooth:.3,path:[{u:0,offset:[3.4,.2,1.4]},{u:.46,offset:[3.4,.2,1.4]},{u:.56,offset:[-3,.25,1.8],turn:120,ease:"snap"},{u:1,offset:[-3,.25,1.6]}]},{id:"push-in",cat:"story",name:"Đẩy vào chậm",nameEn:"Slow push-in",desc:"Ngang tầm mắt, máy tiến chậm từ trung cảnh vào cận — nhấn một khoảnh khắc, một câu thoại.",descEn:"At eye level the camera creeps from a medium shot into a close-up — to stress a moment or a line.",lens:[32,45],aim:.62,smooth:.5,path:[{u:0,offset:[.5,.05,4]},{u:1,offset:[.3,.02,1.7],ease:"smooth"}]},{id:"pull-away",cat:"story",name:"Lùi xa lộ cảnh",nameEn:"Pull-away reveal",desc:"Từ cận mặt, máy lùi và nâng dần lên — lộ ra không gian quanh nhân vật, hợp cho cảnh kết.",descEn:"From a close-up the camera backs away and rises — the space around the subject is revealed, a fitting ending.",lens:[45,28],aim:.55,smooth:.5,path:[{u:0,offset:[.3,.05,1.6]},{u:1,offset:[1.6,1.8,7.5],ease:"smooth"}]},{id:"walk-lead",cat:"story",name:"Đi trước nhân vật",nameEn:"Walk-and-talk lead",desc:"Máy lùi phía trước, giữ mặt nhân vật trung cảnh khi họ bước tới — kiểu walk-and-talk.",descEn:"The camera backs up in front of the subject, holding a medium shot of the face as they walk — the walk-and-talk.",lens:35,aim:.62,smooth:.5,path:[{u:0,offset:[.35,.05,2.4]},{u:1,offset:[.3,.05,2.2]}]},{id:"slider",cat:"story",name:"Trượt ngang (slider)",nameEn:"Slider move",desc:"Máy trượt ngang chậm trước nhân vật, tiền cảnh và hậu cảnh lệch nhau tạo chiều sâu — hợp cảnh sản phẩm, phỏng vấn.",descEn:"A slow sideways slide in front of the subject; foreground and background shift for depth — product and interview shots.",lens:40,aim:.55,smooth:.5,path:[{u:0,offset:[-1.8,0,3]},{u:1,offset:[1.8,0,3],ease:"smooth"}]},{id:"arc-slow",cat:"story",name:"Vòng cung nhẹ",nameEn:"Gentle arc",desc:"Máy đi một cung 40° quanh nhân vật ở trung cảnh — cảnh thoại, cảnh suy tư có hồn hơn máy đứng yên.",descEn:"A 40° arc round the subject at a medium framing — dialogue or a thoughtful beat feels alive.",lens:40,aim:.6,smooth:.5,path:[{u:0,offset:[2.2,.05,2.6]},{u:1,offset:[.01,.05,3.4],turn:-40,ease:"smooth"}]},{id:"drone-rise",cat:"story",name:"Flycam bay lên",nameEn:"Drone rise",desc:"Từ ngang người, máy bay lên cao và lùi xa — mở cảnh hoặc kết cảnh toàn cảnh.",descEn:"From body height the camera climbs high and backs away — an establishing or closing wide shot.",lens:[28,24],aim:.5,smooth:.6,path:[{u:0,offset:[1.5,.2,3.2]},{u:1,offset:[2.5,5.5,8.5],ease:"smooth"}]},{id:"drone-dive",cat:"story",name:"Flycam bổ nhào",nameEn:"Drone dive",desc:"Từ trên cao máy lao xuống, dừng ngang tầm nhân vật — giới thiệu nhân vật giữa bối cảnh.",descEn:"From high above the camera dives down and settles at the subject's height — introduces them in their world.",lens:[24,32],aim:.55,smooth:.6,path:[{u:0,offset:[2,6.5,8]},{u:1,offset:[.6,.15,2.4],ease:"smooth"}]},{id:"fpv-sweep",cat:"story",name:"FPV lượn quanh",nameEn:"FPV sweep",desc:"Kiểu drone FPV: từ sau lưng sát thấp, lượn vòng qua hông lên trước mặt, ống kính rộng, hơi nghiêng.",descEn:"An FPV drone: low behind the subject, swooping round the side up to the front — wide lens, a slight bank.",lens:18,aim:.5,smooth:.4,handheld:.2,roll:[-10,8],path:[{u:0,offset:[.4,.3,-2.4]},{u:.5,offset:[2.6,.6,.2],turn:-85},{u:1,offset:[.3,1.2,2.6],turn:-79}]},{id:"action-director",cat:"director",name:"Đạo diễn hành động",nameEn:"Action director",desc:"Tự cắt góc theo nhịp đòn: toàn cảnh → cận góc thấp lúc trúng đòn → qua vai → toàn cảnh.",descEn:"Cuts on the beats by itself: wide → low close-up on the hit → over the shoulder → wide.",lens:28,aim:.5,smooth:.35,beats:{shake:.6},path:[{u:0,offset:[6,.3,1]},{u:1,offset:[5.6,.3,.8]}],cuts:[{offset:[6,.3,1],lens:28,aim:.5},{offset:[1.9,-.5,2.6],lens:30,aim:.55},{offset:[.7,.5,-2.4],lens:28,aim:.6},{offset:[-3.2,.1,1.6],lens:40,aim:.55}]}]),H=n=>_.find(t=>t.id===n),N=n=>Array.isArray(n)?n:[n,n];function V(n,t){if(t<=n[0].u)return n[0].offset;const a=n[n.length-1];if(t>=a.u)return a.offset;let o=0;for(;o<n.length-2&&t>=n[o+1].u;)o++;const l=n[o],s=n[o+1],h=(G[s.ease??"smooth"]??F)((t-l.u)/Math.max(1e-6,s.u-l.u)),i=l.offset,r=s.offset;if(s.turn==null)return[i[0]+(r[0]-i[0])*h,i[1]+(r[1]-i[1])*h,i[2]+(r[2]-i[2])*h];const m=Math.hypot(i[0],i[2]),u=Math.hypot(r[0],r[2]),d=Math.atan2(i[0],i[2]),f=d+Q(i,r,s.turn)*h,g=m+(u-m)*h;return[Math.sin(f)*g,i[1]+(r[1]-i[1])*h,Math.cos(f)*g]}function Q(n,t,a){const o=((Math.atan2(t[0],t[2])-Math.atan2(n[0],n[2]))*180/Math.PI+540)%360-180,l=Math.abs(a),s=Math.sign(a)||1;let h=o;for(const i of[o-360,o,o+360]){const r=Math.abs(Math.abs(i)-l),m=Math.abs(Math.abs(h)-l);(r<m-1e-9||Math.abs(r-m)<1e-9&&Math.sign(i)===s&&Math.sign(h)!==s)&&(h=i)}return I(h)}const D=(n,t)=>{const[a,o]=N(n??0);return a+(o-a)*F(t)},U=(n,t=.35)=>n<-.06?0:n<0?1+n/.06:Math.exp(-n/Math.max(.05,t)*2.2);function P(n,t,a){const o=Math.max(1e-6,a.end-a.start),l=y((t-a.start)/o,0,1),s=Math.max(.3,a.height/1.8),h=Math.max(0,n.smooth??.3),i=Math.max(1,Math.round(h*30)),r=[0,0,0];for(let e=-i;e<=i;e++){const c=a.centre(y(t+h*e/i,a.start,a.end));r[0]+=c[0],r[1]+=c[1],r[2]+=c[2]}r[0]/=2*i+1,r[1]/=2*i+1,r[2]/=2*i+1;const m=(a.beats||[]).filter(e=>e>=a.start-1e-6&&e<=a.end+1e-6);let u=V(n.path,l),d=D(n.lens,l),f=n.aim??.5,g=null;if(n.cuts?.length){g=m.filter(p=>t>=p-.05).length%n.cuts.length;const c=n.cuts[g];u=c.offset,d=c.lens??d,f=c.aim??f}const b=I(a.yaw||0),j=Math.cos(b),z=Math.sin(b),w=u[0]*s,E=u[1]*s,M=u[2]*s,k=[r[0],r[1]+a.height*f,r[2]],A=[k[0]+w*j+M*z,Math.max(.12,k[1]+E),k[2]-w*z+M*j];if(n.vertigo){const e=Math.hypot(...V(n.path,0)),c=Math.hypot(u[0],u[1],u[2]);d=d*(c/Math.max(.1,e))}const x=n.beats;if(x?.punch){let e=0;for(const c of m)e=Math.max(e,U(t-c));d*=1+x.punch*e}if(x?.crash&&m.length){const e=m[0];d*=1+(x.crash-1)*G.snap(y((t-(e-.08))/.12,0,1))}return{position:A,target:k,lens:y(d,12,200),roll:D(n.roll,l),cut:g}}function Y(n,t,a,o,l){const s=n.beats?.shake;return s?t.filter(h=>h>=a-1e-6&&h<=o+1e-6).map(h=>({time:Math.round(h/Math.max(1e-6,l)*1e4)/1e4,strength:s})):[]}const $=()=>crypto.randomUUID(),v=(n,t=1e3)=>Math.round(n*t)/t,J=n=>(O(n)?1.8*R(n):1.8)*(n.scale?.[1]||1);function nn(n,t){const a=t?n.items.find(o=>o.id===t):null;return a&&a.kind!=="fx"&&!a.hold&&!a.hidden?a:n.items.find(o=>o.kind==="person"&&!o.hidden)??n.items.find(o=>O(o)&&!o.hidden)??null}function tn(n,t){const a=typeof t.preset=="string"?H(t.preset):t.preset;if(!a)return{ok:!1,error:`unknown camera preset ${String(t.preset)}`};const o=K(n),l=n.items.find(e=>e.id===t.subject||e.name===t.subject);if(!l)return{ok:!1,error:"no subject to frame"};const s=Math.max(0,Math.min(o.duration,t.start??0)),h=Math.max(s,Math.min(o.duration,t.end??o.duration));if(h-s<.25)return{ok:!1,error:"not enough shot time after the playhead for a camera move (extend the shot)"};const i=J(l),r=B(n,l,s).rotation[1],m=L(n).filter(e=>e.who===l.id).map(e=>e.time),u={start:s,end:h,yaw:r,height:i,beats:m,centre:e=>B(n,l,e).position},d=Math.max(2,Math.round((h-s)*W)),f=[],g=(e,c)=>({id:$(),time:v(e/o.duration,1e5),position:c.position.map(p=>v(p)),target:c.target.map(p=>v(p)),lens:v(c.lens,100),roll:v(c.roll,100)});let b=null,j=0;for(let e=0;e<=d;e++){const c=s+(h-s)*(e/d),p=P(a,c,u);if(p.cut!=null&&b!=null&&p.cut!==b){let T=s+(h-s)*((e-1)/d),S=c;for(let q=0;q<12;q++){const C=(T+S)/2;P(a,C,u).cut===b?T=C:S=C}f.push(g(T,P(a,T,u)),g(S,P(a,S,u))),j++}f.push(g(c,p)),b=p.cut}const w=[...(o.cameraKeys||[]).filter(e=>e.time*o.duration<s-1e-6||e.time*o.duration>h+1e-6),...f].sort((e,c)=>e.time-c.time),E=w[0],M=w[w.length-1],k=Y(a,m,s,h,o.duration),A=k.length?[...(o.impacts||[]).filter(e=>e.time*o.duration<s-1e-6||e.time*o.duration>h+1e-6),...k].sort((e,c)=>e.time-c.time):o.impacts,x={...o,motion:"path",pathSmooth:!1,cameraMode:"track",cameraKeys:w,cameraSpec:void 0,position:E.position,target:E.target,lens:E.lens,roll:E.roll,endPosition:M.position,endTarget:M.target,endLens:M.lens,...a.handheld!=null?{handheld:a.handheld}:{},...A?{impacts:A}:{}};return{ok:!0,stage:{...n,shots:n.shots.map(e=>e.id===o.id?x:e)},preset:a.id,subject:l.name,start:v(s),end:v(h),keys:f.length,beats:m.filter(e=>e>=s&&e<=h).length,cuts:j}}export{_ as C,nn as a,Z as b,tn as c,P as p};
1
+ import{fq as O,gM as K,ix as V,fu as L,hD as R,iy as W}from"./remote-C7J0Tqhb.js";const I=n=>n*Math.PI/180,y=(n,t,a)=>n<t?t:n>a?a:n,F=n=>{const t=y(n,0,1);return t*t*(3-2*t)},G={smooth:F,linear:n=>y(n,0,1),in:n=>{const t=y(n,0,1);return t*t*t},out:n=>{const t=1-y(n,0,1);return 1-t*t*t},snap:n=>1-Math.pow(1-y(n,0,1),4)},Z=Object.freeze([{id:"follow",name:"Bám theo",nameEn:"Follow"},{id:"reveal",name:"Quay vòng & lộ diện",nameEn:"Orbit & reveal"},{id:"impact",name:"Theo cú đánh",nameEn:"Impact"},{id:"director",name:"Đạo diễn hành động",nameEn:"Action director"},{id:"story",name:"Kể chuyện",nameEn:"Storytelling"}]),_=Object.freeze([{id:"side-track",cat:"follow",name:"Bám ngang",nameEn:"Side tracking",desc:"Máy quay chạy song song bên hông nhân vật, giữ khung trung cảnh — kiểu showreel game hành động.",descEn:"The camera runs alongside the subject at a medium framing — the action game showreel look.",lens:35,aim:.5,smooth:.35,path:[{u:0,offset:[4.2,.15,.4]},{u:1,offset:[4.2,.15,.4]}]},{id:"wide-track",cat:"follow",name:"Toàn cảnh bám ngang",nameEn:"Wide tracking",desc:"Toàn cảnh từ xa, ống kính rộng, thấy cả không gian và đường di chuyển.",descEn:"A wide shot from far off: the whole space and the path of the action.",lens:28,aim:.45,smooth:.6,path:[{u:0,offset:[7.5,.4,1.2]},{u:1,offset:[7.5,.4,1.2]}]},{id:"follow-behind",cat:"follow",name:"Bám sau lưng",nameEn:"Over-the-shoulder follow",desc:"Sau lưng, cao hơn đầu một chút — người xem đi cùng nhân vật.",descEn:"Behind and a little above the head — the audience moves with the subject.",lens:28,aim:.6,smooth:.3,handheld:.25,path:[{u:0,offset:[.7,.55,-2.6]},{u:1,offset:[.6,.5,-2.3]}]},{id:"low-hero",cat:"follow",name:"Góc thấp anh hùng",nameEn:"Low hero angle",desc:"Máy đặt thấp ngước lên, đẩy vào chậm — nhân vật trông mạnh mẽ.",descEn:"Low and looking up with a slow push in: the subject looks powerful.",lens:[24,28],aim:.62,smooth:.4,path:[{u:0,offset:[1.6,-.62,3.2]},{u:1,offset:[1.2,-.62,2.4],ease:"smooth"}]},{id:"worm-eye-dutch",cat:"follow",name:"Nhìn từ đất lên trời",nameEn:"Worm's-eye dutch",desc:"Máy sát đất ngước thẳng lên trời, ống kính rộng, khung nghiêng xoay dần — cảnh đấu trên không kiểu Dragon Ball.",descEn:"From the ground looking straight up, a wide lens and a slowly turning tilt — the sky battle of an anime.",lens:18,roll:[-14,10],aim:.85,smooth:.35,path:[{u:0,offset:[1.4,-.92,1.2]},{u:1,offset:[2,-.92,.4],ease:"smooth"}]},{id:"ground-level",cat:"follow",name:"Sát mặt đất",nameEn:"Ground level",desc:"Máy gần như nằm trên sàn — cho cú ngã, cú lộn, đòn quét chân.",descEn:"The camera almost on the floor: for falls, rolls and leg sweeps.",lens:22,aim:.3,smooth:.3,path:[{u:0,offset:[3,-.88,1.4]},{u:1,offset:[2.6,-.88,1]}]},{id:"orbit-180",cat:"reveal",name:"Quay vòng 180°",nameEn:"Orbit 180°",desc:"Vòng nửa quanh nhân vật từ hông sang mặt kia.",descEn:"Half a circle round the subject, from one side to the other.",lens:35,aim:.55,smooth:.4,path:[{u:0,offset:[3.6,.2,.6]},{u:1,offset:[-3.6,.2,.6],turn:180}]},{id:"bullet-time",cat:"reveal",name:"Bullet time",nameEn:"Bullet time",desc:"Vòng nhanh 270° quanh đòn đánh, sát và thấp — kiểu Ma trận.",descEn:"A fast 270° circle round the action, close and low — the Matrix look.",lens:30,aim:.55,smooth:.5,path:[{u:0,offset:[2.4,0,1.2]},{u:1,offset:[-2.4,.1,-1.2],turn:270,ease:"linear"}]},{id:"crane-down",cat:"reveal",name:"Cần cẩu hạ xuống",nameEn:"Crane down reveal",desc:"Từ trên cao hạ xuống ngang ngực, ống kính hẹp dần.",descEn:"From high above down to chest height, the lens tightening.",lens:[24,40],aim:.5,smooth:.5,path:[{u:0,offset:[2.2,3.6,4.2]},{u:1,offset:[1.6,.1,3]}]},{id:"dolly-zoom",cat:"reveal",name:"Dolly zoom (Vertigo)",nameEn:"Dolly zoom (Vertigo)",desc:"Máy lùi ra trong khi ống kính zoom vào: nhân vật giữ nguyên, hậu cảnh co giãn.",descEn:"The camera pulls back as the lens zooms in: the subject holds its size while the background warps.",lens:24,vertigo:!0,aim:.55,smooth:.4,path:[{u:0,offset:[.4,.1,2.2]},{u:1,offset:[.4,.1,6.5],ease:"smooth"}]},{id:"dutch-push",cat:"reveal",name:"Đẩy vào nghiêng",nameEn:"Dutch push-in",desc:"Đẩy vào với khung hình nghiêng dần — căng thẳng, bất an.",descEn:"A push in while the frame tilts — tension, unease.",lens:[32,45],roll:[0,14],aim:.62,smooth:.4,path:[{u:0,offset:[1.2,.2,4]},{u:1,offset:[.7,.15,2.4]}]},{id:"crash-zoom",cat:"impact",name:"Crash zoom vào đòn",nameEn:"Crash zoom on the hit",desc:"Toàn cảnh ngang, đúng đòn đầu tiên ống kính giật zoom vào cận và giữ.",descEn:"A wide side view; on the first strike the lens snaps in to a close-up and holds.",lens:26,aim:.55,smooth:.4,beats:{crash:2.6,shake:.7},path:[{u:0,offset:[5.2,.2,.6]},{u:1,offset:[5,.2,.6]}]},{id:"punch-beats",cat:"impact",name:"Punch-in theo nhịp đòn",nameEn:"Punch-in on every hit",desc:"Mỗi đòn trúng: ống kính giật vào 1 nhịp và rung — nhịp anime/game.",descEn:"Every strike kicks the lens in for a beat with a shake — the anime / game rhythm.",lens:32,aim:.55,smooth:.35,handheld:.15,beats:{punch:.35,shake:.55},path:[{u:0,offset:[3.6,.15,1]},{u:1,offset:[3.4,.15,.9]}]},{id:"whip-pan",cat:"impact",name:"Lia nhanh (whip pan)",nameEn:"Whip pan",desc:"Giữa cảnh máy lia vụt sang góc đối diện của nhân vật.",descEn:"Mid-shot the camera whips round to the opposite side of the subject.",lens:32,aim:.55,smooth:.3,path:[{u:0,offset:[3.4,.2,1.4]},{u:.46,offset:[3.4,.2,1.4]},{u:.56,offset:[-3,.25,1.8],turn:120,ease:"snap"},{u:1,offset:[-3,.25,1.6]}]},{id:"push-in",cat:"story",name:"Đẩy vào chậm",nameEn:"Slow push-in",desc:"Ngang tầm mắt, máy tiến chậm từ trung cảnh vào cận — nhấn một khoảnh khắc, một câu thoại.",descEn:"At eye level the camera creeps from a medium shot into a close-up — to stress a moment or a line.",lens:[32,45],aim:.62,smooth:.5,path:[{u:0,offset:[.5,.05,4]},{u:1,offset:[.3,.02,1.7],ease:"smooth"}]},{id:"pull-away",cat:"story",name:"Lùi xa lộ cảnh",nameEn:"Pull-away reveal",desc:"Từ cận mặt, máy lùi và nâng dần lên — lộ ra không gian quanh nhân vật, hợp cho cảnh kết.",descEn:"From a close-up the camera backs away and rises — the space around the subject is revealed, a fitting ending.",lens:[45,28],aim:.55,smooth:.5,path:[{u:0,offset:[.3,.05,1.6]},{u:1,offset:[1.6,1.8,7.5],ease:"smooth"}]},{id:"walk-lead",cat:"story",name:"Đi trước nhân vật",nameEn:"Walk-and-talk lead",desc:"Máy lùi phía trước, giữ mặt nhân vật trung cảnh khi họ bước tới — kiểu walk-and-talk.",descEn:"The camera backs up in front of the subject, holding a medium shot of the face as they walk — the walk-and-talk.",lens:35,aim:.62,smooth:.5,path:[{u:0,offset:[.35,.05,2.4]},{u:1,offset:[.3,.05,2.2]}]},{id:"slider",cat:"story",name:"Trượt ngang (slider)",nameEn:"Slider move",desc:"Máy trượt ngang chậm trước nhân vật, tiền cảnh và hậu cảnh lệch nhau tạo chiều sâu — hợp cảnh sản phẩm, phỏng vấn.",descEn:"A slow sideways slide in front of the subject; foreground and background shift for depth — product and interview shots.",lens:40,aim:.55,smooth:.5,path:[{u:0,offset:[-1.8,0,3]},{u:1,offset:[1.8,0,3],ease:"smooth"}]},{id:"arc-slow",cat:"story",name:"Vòng cung nhẹ",nameEn:"Gentle arc",desc:"Máy đi một cung 40° quanh nhân vật ở trung cảnh — cảnh thoại, cảnh suy tư có hồn hơn máy đứng yên.",descEn:"A 40° arc round the subject at a medium framing — dialogue or a thoughtful beat feels alive.",lens:40,aim:.6,smooth:.5,path:[{u:0,offset:[2.2,.05,2.6]},{u:1,offset:[.01,.05,3.4],turn:-40,ease:"smooth"}]},{id:"drone-rise",cat:"story",name:"Flycam bay lên",nameEn:"Drone rise",desc:"Từ ngang người, máy bay lên cao và lùi xa — mở cảnh hoặc kết cảnh toàn cảnh.",descEn:"From body height the camera climbs high and backs away — an establishing or closing wide shot.",lens:[28,24],aim:.5,smooth:.6,path:[{u:0,offset:[1.5,.2,3.2]},{u:1,offset:[2.5,5.5,8.5],ease:"smooth"}]},{id:"drone-dive",cat:"story",name:"Flycam bổ nhào",nameEn:"Drone dive",desc:"Từ trên cao máy lao xuống, dừng ngang tầm nhân vật — giới thiệu nhân vật giữa bối cảnh.",descEn:"From high above the camera dives down and settles at the subject's height — introduces them in their world.",lens:[24,32],aim:.55,smooth:.6,path:[{u:0,offset:[2,6.5,8]},{u:1,offset:[.6,.15,2.4],ease:"smooth"}]},{id:"fpv-sweep",cat:"story",name:"FPV lượn quanh",nameEn:"FPV sweep",desc:"Kiểu drone FPV: từ sau lưng sát thấp, lượn vòng qua hông lên trước mặt, ống kính rộng, hơi nghiêng.",descEn:"An FPV drone: low behind the subject, swooping round the side up to the front — wide lens, a slight bank.",lens:18,aim:.5,smooth:.4,handheld:.2,roll:[-10,8],path:[{u:0,offset:[.4,.3,-2.4]},{u:.5,offset:[2.6,.6,.2],turn:-85},{u:1,offset:[.3,1.2,2.6],turn:-79}]},{id:"action-director",cat:"director",name:"Đạo diễn hành động",nameEn:"Action director",desc:"Tự cắt góc theo nhịp đòn: toàn cảnh → cận góc thấp lúc trúng đòn → qua vai → toàn cảnh.",descEn:"Cuts on the beats by itself: wide → low close-up on the hit → over the shoulder → wide.",lens:28,aim:.5,smooth:.35,beats:{shake:.6},path:[{u:0,offset:[6,.3,1]},{u:1,offset:[5.6,.3,.8]}],cuts:[{offset:[6,.3,1],lens:28,aim:.5},{offset:[1.9,-.5,2.6],lens:30,aim:.55},{offset:[.7,.5,-2.4],lens:28,aim:.6},{offset:[-3.2,.1,1.6],lens:40,aim:.55}]}]),H=n=>_.find(t=>t.id===n),N=n=>Array.isArray(n)?n:[n,n];function B(n,t){if(t<=n[0].u)return n[0].offset;const a=n[n.length-1];if(t>=a.u)return a.offset;let o=0;for(;o<n.length-2&&t>=n[o+1].u;)o++;const l=n[o],s=n[o+1],h=(G[s.ease??"smooth"]??F)((t-l.u)/Math.max(1e-6,s.u-l.u)),i=l.offset,r=s.offset;if(s.turn==null)return[i[0]+(r[0]-i[0])*h,i[1]+(r[1]-i[1])*h,i[2]+(r[2]-i[2])*h];const m=Math.hypot(i[0],i[2]),u=Math.hypot(r[0],r[2]),d=Math.atan2(i[0],i[2]),f=d+Q(i,r,s.turn)*h,g=m+(u-m)*h;return[Math.sin(f)*g,i[1]+(r[1]-i[1])*h,Math.cos(f)*g]}function Q(n,t,a){const o=((Math.atan2(t[0],t[2])-Math.atan2(n[0],n[2]))*180/Math.PI+540)%360-180,l=Math.abs(a),s=Math.sign(a)||1;let h=o;for(const i of[o-360,o,o+360]){const r=Math.abs(Math.abs(i)-l),m=Math.abs(Math.abs(h)-l);(r<m-1e-9||Math.abs(r-m)<1e-9&&Math.sign(i)===s&&Math.sign(h)!==s)&&(h=i)}return I(h)}const D=(n,t)=>{const[a,o]=N(n??0);return a+(o-a)*F(t)},U=(n,t=.35)=>n<-.06?0:n<0?1+n/.06:Math.exp(-n/Math.max(.05,t)*2.2);function P(n,t,a){const o=Math.max(1e-6,a.end-a.start),l=y((t-a.start)/o,0,1),s=Math.max(.3,a.height/1.8),h=Math.max(0,n.smooth??.3),i=Math.max(1,Math.round(h*30)),r=[0,0,0];for(let e=-i;e<=i;e++){const c=a.centre(y(t+h*e/i,a.start,a.end));r[0]+=c[0],r[1]+=c[1],r[2]+=c[2]}r[0]/=2*i+1,r[1]/=2*i+1,r[2]/=2*i+1;const m=(a.beats||[]).filter(e=>e>=a.start-1e-6&&e<=a.end+1e-6);let u=B(n.path,l),d=D(n.lens,l),f=n.aim??.5,g=null;if(n.cuts?.length){g=m.filter(p=>t>=p-.05).length%n.cuts.length;const c=n.cuts[g];u=c.offset,d=c.lens??d,f=c.aim??f}const b=I(a.yaw||0),j=Math.cos(b),z=Math.sin(b),w=u[0]*s,E=u[1]*s,M=u[2]*s,k=[r[0],r[1]+a.height*f,r[2]],A=[k[0]+w*j+M*z,Math.max(.12,k[1]+E),k[2]-w*z+M*j];if(n.vertigo){const e=Math.hypot(...B(n.path,0)),c=Math.hypot(u[0],u[1],u[2]);d=d*(c/Math.max(.1,e))}const x=n.beats;if(x?.punch){let e=0;for(const c of m)e=Math.max(e,U(t-c));d*=1+x.punch*e}if(x?.crash&&m.length){const e=m[0];d*=1+(x.crash-1)*G.snap(y((t-(e-.08))/.12,0,1))}return{position:A,target:k,lens:y(d,12,200),roll:D(n.roll,l),cut:g}}function Y(n,t,a,o,l){const s=n.beats?.shake;return s?t.filter(h=>h>=a-1e-6&&h<=o+1e-6).map(h=>({time:Math.round(h/Math.max(1e-6,l)*1e4)/1e4,strength:s})):[]}const $=()=>crypto.randomUUID(),v=(n,t=1e3)=>Math.round(n*t)/t,J=n=>(O(n)?1.8*R(n):1.8)*(n.scale?.[1]||1);function nn(n,t){const a=t?n.items.find(o=>o.id===t):null;return a&&a.kind!=="fx"&&!a.hold&&!a.hidden?a:n.items.find(o=>o.kind==="person"&&!o.hidden)??n.items.find(o=>O(o)&&!o.hidden)??null}function tn(n,t){const a=typeof t.preset=="string"?H(t.preset):t.preset;if(!a)return{ok:!1,error:`unknown camera preset ${String(t.preset)}`};const o=K(n),l=n.items.find(e=>e.id===t.subject||e.name===t.subject);if(!l)return{ok:!1,error:"no subject to frame"};const s=Math.max(0,Math.min(o.duration,t.start??0)),h=Math.max(s,Math.min(o.duration,t.end??o.duration));if(h-s<.25)return{ok:!1,error:"not enough shot time after the playhead for a camera move (extend the shot)"};const i=J(l),r=V(n,l,s).rotation[1],m=L(n).filter(e=>e.who===l.id).map(e=>e.time),u={start:s,end:h,yaw:r,height:i,beats:m,centre:e=>V(n,l,e).position},d=Math.max(2,Math.round((h-s)*W)),f=[],g=(e,c)=>({id:$(),time:v(e/o.duration,1e5),position:c.position.map(p=>v(p)),target:c.target.map(p=>v(p)),lens:v(c.lens,100),roll:v(c.roll,100)});let b=null,j=0;for(let e=0;e<=d;e++){const c=s+(h-s)*(e/d),p=P(a,c,u);if(p.cut!=null&&b!=null&&p.cut!==b){let T=s+(h-s)*((e-1)/d),S=c;for(let q=0;q<12;q++){const C=(T+S)/2;P(a,C,u).cut===b?T=C:S=C}f.push(g(T,P(a,T,u)),g(S,P(a,S,u))),j++}f.push(g(c,p)),b=p.cut}const w=[...(o.cameraKeys||[]).filter(e=>e.time*o.duration<s-1e-6||e.time*o.duration>h+1e-6),...f].sort((e,c)=>e.time-c.time),E=w[0],M=w[w.length-1],k=Y(a,m,s,h,o.duration),A=k.length?[...(o.impacts||[]).filter(e=>e.time*o.duration<s-1e-6||e.time*o.duration>h+1e-6),...k].sort((e,c)=>e.time-c.time):o.impacts,x={...o,motion:"path",pathSmooth:!1,cameraMode:"track",cameraKeys:w,cameraSpec:void 0,position:E.position,target:E.target,lens:E.lens,roll:E.roll,endPosition:M.position,endTarget:M.target,endLens:M.lens,...a.handheld!=null?{handheld:a.handheld}:{},...A?{impacts:A}:{}};return{ok:!0,stage:{...n,shots:n.shots.map(e=>e.id===o.id?x:e)},preset:a.id,subject:l.name,start:v(s),end:v(h),keys:f.length,beats:m.filter(e=>e>=s&&e<=h).length,cuts:j}}export{_ as C,nn as a,Z as b,tn as c,P as p};
@@ -1 +1 @@
1
- import{lq as w,i0 as W,nj as A,b0 as E,b1 as M,b2 as P,aP as $,a_ as O,aQ as L,aZ as b}from"./titleFrameBudget-BYRZAQPs.js";function j(n){const t=new DataView(n.buffer,n.byteOffset,n.byteLength),o={};for(let e=0,a=t.getUint16(4);e<a;e++){const l=12+e*16;o[String.fromCharCode(n[l],n[l+1],n[l+2],n[l+3])]=t.getUint32(l+8)}const s=t.getUint16(o.head+18),i=t.getUint16(o.hhea+34),g=e=>t.getUint16(o.hmtx+Math.min(e,i-1)*4),r=o.cmap,f=[];for(let e=0,a=t.getUint16(r+2);e<a;e++)f.push({platform:t.getUint16(r+4+e*8),encoding:t.getUint16(r+6+e*8),offset:r+t.getUint32(r+8+e*8)});const p=f.find(e=>e.platform===3&&e.encoding===10)||f.find(e=>e.platform===3&&e.encoding===1)||f.find(e=>e.platform===0);if(!p)throw Error("Font has no usable cmap");const h=t.getUint16(p.offset);return{unitsPerEm:s,glyphFor:e=>{if(h===4){const a=t.getUint16(p.offset+6)/2,l=p.offset+14,u=l+a*2+2,y=u+a*2,m=y+a*2;for(let d=0;d<a;d++){if(e>t.getUint16(l+d*2))continue;if(e<t.getUint16(u+d*2))return 0;const k=t.getUint16(m+d*2),x=t.getInt16(y+d*2);if(!k)return e+x&65535;const C=t.getUint16(m+d*2+k+(e-t.getUint16(u+d*2))*2);return C?C+x&65535:0}return 0}if(h===12){for(let a=0,l=t.getUint32(p.offset+12);a<l;a++){const u=p.offset+16+a*12,y=t.getUint32(u),m=t.getUint32(u+4);if(e>=y&&e<=m)return t.getUint32(u+8)+(e-y)}return 0}throw Error(`Unsupported cmap format ${h}`)},advanceOf:g}}const T=n=>({...j(n),advances:new Map});function B(n,t,o){let s=0;for(const i of String(t).normalize("NFC")){let g=n.advances.get(i);g===void 0&&(g=n.advanceOf(n.glyphFor(i.codePointAt(0))),n.advances.set(i,g)),s+=g}return s*o/n.unitsPerEm}let U=null;const S=new Map,v=new Map;function D(n){const t=w(n);if(S.has(t.id))return Promise.resolve();let o=v.get(t.id);return o||(o=Promise.all([fetch(`/fonts/${t.file}`).then(s=>{if(!s.ok)throw Error(String(s.status));return s.arrayBuffer()}).then(s=>{S.set(t.id,T(new Uint8Array(s)))}),document.fonts.load(`40px "${t.css}"`)]).then(()=>{}).catch(()=>{v.delete(t.id)}),v.set(t.id,o)),o}function N(n,t,o){const s=S.get(w(o).id);return s?B(s,n,t):(D(o),U??=document.createElement("canvas").getContext("2d"),U?(U.font=`${t}px "${w(o).css}"`,U.measureText(n).width):n.length*t*.55)}const F=new WeakMap,Q=n=>{const t=F.get(n.captionWords);if(t&&t.style===n.captionStyle&&t.cues===n.captions)return t.prepared;const o=b(n.captionWords,n.captionStyle,n.captions);return F.set(n.captionWords,{style:n.captionStyle,cues:n.captions,prepared:o}),o},R=(n,t)=>{const o=n.groups[t];let s=0;for(let i=o.from;i<=o.to;i++)s+=[...String(n.words[i].word)].length;return s};function Z(n,t,o,s,i,g=N){const r=W(n,t,o);if(!r)return null;const f=t-r.start;if(["social","karaoke"].includes(r.captionStyle?.style||"")&&r.captionWords?.length){const c=Q(r),e=A(c.groups,f);if(e<0)return null;const a=c.style.style==="karaoke",l=c.groups[e],u=E(c.style,f-l.start,R(c,e));return{clip:r,layout:P(c,e,s,i,g),style:c.style,scale:u.scale,motion:u.m,lit:a?M(c,e,f):void 0}}const p=$(r.captionStyle),h=O(r.captions,p.cueWords).find(c=>f>=c.start&&f<c.end);return h?{clip:r,layout:L({width:s,height:i,text:h.text,style:p,measure:g,second:h.tr}),style:p,scale:1}:null}export{D as captionFontReady,Z as captionFrameAt,R as groupLetters,N as measureCaption};
1
+ import{lq as w,i0 as W,ng as A,b0 as E,b1 as M,b2 as P,aP as $,a_ as O,aQ as L,aZ as b}from"./titleFrameBudget-CLZWaFHO.js";function T(n){const t=new DataView(n.buffer,n.byteOffset,n.byteLength),o={};for(let e=0,a=t.getUint16(4);e<a;e++){const l=12+e*16;o[String.fromCharCode(n[l],n[l+1],n[l+2],n[l+3])]=t.getUint32(l+8)}const s=t.getUint16(o.head+18),i=t.getUint16(o.hhea+34),u=e=>t.getUint16(o.hmtx+Math.min(e,i-1)*4),r=o.cmap,f=[];for(let e=0,a=t.getUint16(r+2);e<a;e++)f.push({platform:t.getUint16(r+4+e*8),encoding:t.getUint16(r+6+e*8),offset:r+t.getUint32(r+8+e*8)});const p=f.find(e=>e.platform===3&&e.encoding===10)||f.find(e=>e.platform===3&&e.encoding===1)||f.find(e=>e.platform===0);if(!p)throw Error("Font has no usable cmap");const h=t.getUint16(p.offset);return{unitsPerEm:s,glyphFor:e=>{if(h===4){const a=t.getUint16(p.offset+6)/2,l=p.offset+14,g=l+a*2+2,y=g+a*2,m=y+a*2;for(let d=0;d<a;d++){if(e>t.getUint16(l+d*2))continue;if(e<t.getUint16(g+d*2))return 0;const k=t.getUint16(m+d*2),x=t.getInt16(y+d*2);if(!k)return e+x&65535;const C=t.getUint16(m+d*2+k+(e-t.getUint16(g+d*2))*2);return C?C+x&65535:0}return 0}if(h===12){for(let a=0,l=t.getUint32(p.offset+12);a<l;a++){const g=p.offset+16+a*12,y=t.getUint32(g),m=t.getUint32(g+4);if(e>=y&&e<=m)return t.getUint32(g+8)+(e-y)}return 0}throw Error(`Unsupported cmap format ${h}`)},advanceOf:u}}const j=n=>({...T(n),advances:new Map});function B(n,t,o){let s=0;for(const i of String(t).normalize("NFC")){let u=n.advances.get(i);u===void 0&&(u=n.advanceOf(n.glyphFor(i.codePointAt(0))),n.advances.set(i,u)),s+=u}return s*o/n.unitsPerEm}let U=null;const S=new Map,v=new Map;function D(n){const t=w(n);if(S.has(t.id))return Promise.resolve();let o=v.get(t.id);return o||(o=Promise.all([fetch(`/fonts/${t.file}`).then(s=>{if(!s.ok)throw Error(String(s.status));return s.arrayBuffer()}).then(s=>{S.set(t.id,j(new Uint8Array(s)))}),document.fonts.load(`40px "${t.css}"`)]).then(()=>{}).catch(()=>{v.delete(t.id)}),v.set(t.id,o)),o}function N(n,t,o){const s=S.get(w(o).id);return s?B(s,n,t):(D(o),U??=document.createElement("canvas").getContext("2d"),U?(U.font=`${t}px "${w(o).css}"`,U.measureText(n).width):n.length*t*.55)}const F=new WeakMap,Q=n=>{const t=F.get(n.captionWords);if(t&&t.style===n.captionStyle&&t.cues===n.captions)return t.prepared;const o=b(n.captionWords,n.captionStyle,n.captions);return F.set(n.captionWords,{style:n.captionStyle,cues:n.captions,prepared:o}),o},R=(n,t)=>{const o=n.groups[t];let s=0;for(let i=o.from;i<=o.to;i++)s+=[...String(n.words[i].word)].length;return s};function Z(n,t,o,s,i,u=N){const r=W(n,t,o);if(!r)return null;const f=t-r.start;if(["social","karaoke"].includes(r.captionStyle?.style||"")&&r.captionWords?.length){const c=Q(r),e=A(c.groups,f);if(e<0)return null;const a=c.style.style==="karaoke",l=c.groups[e],g=E(c.style,f-l.start,R(c,e));return{clip:r,layout:P(c,e,s,i,u),style:c.style,scale:g.scale,motion:g.m,lit:a?M(c,e,f):void 0}}const p=$(r.captionStyle),h=O(r.captions,p.cueWords).find(c=>f>=c.start&&f<c.end);return h?{clip:r,layout:L({width:s,height:i,text:h.text,style:p,measure:u,second:h.tr}),style:p,scale:1}:null}export{D as captionFontReady,Z as captionFrameAt,R as groupLetters,N as measureCaption};
@@ -1 +1 @@
1
- import{c1 as p,f9 as b,fa as y,ll as x,eQ as w,cM as E,f0 as S,il as A,lm as O,fF as D,eI as _,eJ as v,eM as B,ec as u,ee as f,ln as T,U as I,W as L,lo as $,hU as F,bL as M}from"./titleFrameBudget-BYRZAQPs.js";import{e as P,a as R}from"./timelineComp-BcewYGR2.js";const j=new Set(["opacity","x","y","zoom","blur","exposure","dirBlur","zoomBlur","rgbSplit","invert","glitch","rot","spinBlur","dirBlurV"]),z=e=>!(e?.dirBlur&&(e.zoom||e.blur||e.zoomBlur))&&!(e?.zoomBlur&&(e.x||e.y||e.blur||e.dirBlur)),X=new Set(["id","name","category","duration","tags","version","sortOrder","a","b","flash","light","mask","zoomAt"]),J=["colorPerson","matte","shocks","impacts","smoothSlow","reverse","revealType","rotFit","is3D","space","bend","bendStrip","device","deviceScreen","join","audioFx","audioTools","muffle","trail","path","links","element","modelGround","modelRotation","modelSpin","modelAnim","modelDepth","spatialDepth","pendingPin","personPending","samPending","gen","clientJobs","mapAnno","seam","warped"],H={rx:0,ry:0,rz:0,depth:0,tiltX:0,tiltY:0},K=new Set(["rot","sx","sy","depth","tiltX","tiltY"]),N=new Set(["is3D","spatialDepth"]),U=new Set(["blur","glow","light-burst","rgb-split","pixelate","sepia","invert","mono","duotone","luma-invert",...Object.keys(M)]),c=e=>e!=null&&e!==!1&&!(Array.isArray(e)&&!e.length);function C(e,{camera:a=null,W:r=1280,H:m=720}={}){const t=[];if(E(e))return[];if(e.kind==="model")return[];if(!["image","video","audio"].includes(e.kind))return[`${e.kind} layer`];const i=e.kind!=="audio"&&b(a)&&y(e),l=!i&&e.is3D===!0&&!c(e.spatialDepth);for(const n of J){if(n==="clientJobs"){Array.isArray(e.clientJobs)&&e.clientJobs.some(o=>o?.state==="pending"||o?.state==="running")&&t.push(n);continue}c(e[n])&&!(i&&N.has(n))&&!(l&&n==="is3D")&&t.push(n)}if(e.pin?.scene&&t.push("scene pin"),e.timeRemap?.blend&&e.timeRemap.blend!=="none"&&t.push("time remap frame blending"),e.kind!=="audio"&&S(e,r||1280).some(n=>n.sigma>42)&&t.push("wide shadow"),A(e)&&O(e)&&t.push("shadow on an adjustment layer"),e.motionBlur&&e.kind!=="audio"&&((e.effects||[]).some(n=>!n.off)||e.pin||e.parentId||D(e)||e.layout!==void 0||e.rotFit||i)&&t.push("motion blur"),e.kind!=="audio"&&_(e)){const n=v(e),o=B(n);n.crackle?t.push("edge crackle"):Math.max(o.band,o.glow)>42&&t.push("wide edge")}const d=!i&&e.kind!=="audio"&&(u(e,"rot").length>1||Math.abs(f(e,"rot",0))>1e-9);d&&((e.effects||[]).some(n=>!n.off)||e.layout!==void 0||e.rotFit)&&t.push("rot"),!i&&e.kind!=="audio"&&["ax","ay"].some(n=>u(e,n).length>1||Math.abs(f(e,n,0))>1e-9)&&d&&t.push("anchor with rotation"),i&&(e.transition||e._txIn||e._txOut)&&t.push("transition on a 3D layer");for(const[n,o]of Object.entries(H))!(i&&K.has(n))&&(u(e,n).length>1||Math.abs(f(e,n,0)-o)>1e-9)&&t.push(n);e.grade&&!e.colorBypass&&(e.grade.lut||T(e.grade).length)&&t.push("grade"),e.grade&&!e.colorBypass&&I(e.grade).some(n=>L(n)&&(n.window?.type==="person"||n.qualifier&&(n.window?.type==="polygon"||n.motion||n.window?.type==="face")))&&t.push("grade window");for(const n of Array.isArray(e.effects)?e.effects:[])!n.off&&!U.has(n.type)&&t.push(`effect ${n.type}`);if($(e,"T")&&t.push("reveal"),e.transition){const n=e.transition.spec||{},o=s=>!!e.transition.ramp||z(s);(Object.keys(n).some(s=>!X.has(s))||["a","b"].some(s=>n[s]&&(Object.keys(n[s]).some(k=>!j.has(k))||!o(n[s]))))&&t.push(`transition ${e.transition.id}`)}return e.kind==="video"&&F(e)&&t.push("title on video"),t}function Y(e,a={}){const{reasons:r}=h(e,a);return{ok:r.length===0,reasons:r}}function G(e,a={}){return[...new Set(h(e,a).codes)].sort()}function h(e,{format:a,camera:r,look:m}={}){const t=[],i=[];e=P((e||[]).filter(n=>!n.disabled),{W:p(a).width,H:p(a).height});const l=b(r)?r:null,{width:d,height:g}=p(a);l&&(e||[]).some(n=>!n.disabled&&n.kind!=="audio"&&y(n))&&l.parentId&&(t.push("camera on a parent"),i.push("camera on a parent")),x(m)&&(t.push("look"),i.push("look"));for(const n of e||[]){if(n.disabled)continue;if(n._group&&n.comp){const s=h(R(n),{format:a});s.reasons.length&&(t.push(`${n.label||n.id} (comp): ${s.reasons.join("; ")}`),i.push(...s.codes))}const o=C(n,{camera:l,W:d,H:g});o.length&&(t.push(`${n.label||n.id}: ${o.join(", ")}`),i.push(...o))}if(!t.length)for(const n of w((e||[]).filter(o=>!o.disabled))){const o=s=>{t.push(`${n.label||n.id}: ${s}`),i.push(s)};n.timeRemap&&(n._txIn||n._txOut)&&!n._ramp&&o("time remap in a transition"),n.motionBlur&&(n._txIn||n._txOut)&&o("motion blur in a transition")}return{reasons:t,codes:i}}const q=(e,a,r)=>(a==="video encode"||a==="finalize")&&r?.codec!=="hevc"&&e?.name!=="AbortError"&&/^(OperationError|EncodingError)$/.test(e?.name||""),Q=e=>!(typeof DOMException<"u"&&e instanceof DOMException)&&!(e instanceof TypeError)&&!(e instanceof Error&&/^media \d{3}$/.test(e.message))?"":(e.message||"").replace(/\b(?:https?|blob|data):\S*/gi,"").replace(/\s+/g," ").trim();export{J as HEAVY_FIELDS,Y as clientExportCheck,G as clientExportCodes,C as clipBlockers,Q as gpuErrorText,q as softwareRetry};
1
+ import{c1 as p,f9 as b,fa as y,ll as x,eQ as w,cM as E,f0 as S,il as A,lm as O,fF as D,eI as _,eJ as v,eM as B,ec as u,ee as f,ln as T,U as I,W as L,lo as $,hU as F,bL as M}from"./titleFrameBudget-CLZWaFHO.js";import{e as P,a as R}from"./timelineComp-B4GtoH2f.js";const j=new Set(["opacity","x","y","zoom","blur","exposure","dirBlur","zoomBlur","rgbSplit","invert","glitch","rot","spinBlur","dirBlurV"]),z=e=>!(e?.dirBlur&&(e.zoom||e.blur||e.zoomBlur))&&!(e?.zoomBlur&&(e.x||e.y||e.blur||e.dirBlur)),X=new Set(["id","name","category","duration","tags","version","sortOrder","a","b","flash","light","mask","zoomAt"]),J=["colorPerson","matte","shocks","impacts","smoothSlow","reverse","revealType","rotFit","is3D","space","bend","bendStrip","device","deviceScreen","join","audioFx","audioTools","muffle","trail","path","links","element","modelGround","modelRotation","modelSpin","modelAnim","modelDepth","spatialDepth","pendingPin","personPending","samPending","gen","clientJobs","mapAnno","seam","warped"],H={rx:0,ry:0,rz:0,depth:0,tiltX:0,tiltY:0},K=new Set(["rot","sx","sy","depth","tiltX","tiltY"]),N=new Set(["is3D","spatialDepth"]),U=new Set(["blur","glow","light-burst","rgb-split","pixelate","sepia","invert","mono","duotone","luma-invert",...Object.keys(M)]),c=e=>e!=null&&e!==!1&&!(Array.isArray(e)&&!e.length);function C(e,{camera:a=null,W:r=1280,H:m=720}={}){const t=[];if(E(e))return[];if(e.kind==="model")return[];if(!["image","video","audio"].includes(e.kind))return[`${e.kind} layer`];const i=e.kind!=="audio"&&b(a)&&y(e),l=!i&&e.is3D===!0&&!c(e.spatialDepth);for(const n of J){if(n==="clientJobs"){Array.isArray(e.clientJobs)&&e.clientJobs.some(o=>o?.state==="pending"||o?.state==="running")&&t.push(n);continue}c(e[n])&&!(i&&N.has(n))&&!(l&&n==="is3D")&&t.push(n)}if(e.pin?.scene&&t.push("scene pin"),e.timeRemap?.blend&&e.timeRemap.blend!=="none"&&t.push("time remap frame blending"),e.kind!=="audio"&&S(e,r||1280).some(n=>n.sigma>42)&&t.push("wide shadow"),A(e)&&O(e)&&t.push("shadow on an adjustment layer"),e.motionBlur&&e.kind!=="audio"&&((e.effects||[]).some(n=>!n.off)||e.pin||e.parentId||D(e)||e.layout!==void 0||e.rotFit||i)&&t.push("motion blur"),e.kind!=="audio"&&_(e)){const n=v(e),o=B(n);n.crackle?t.push("edge crackle"):Math.max(o.band,o.glow)>42&&t.push("wide edge")}const d=!i&&e.kind!=="audio"&&(u(e,"rot").length>1||Math.abs(f(e,"rot",0))>1e-9);d&&((e.effects||[]).some(n=>!n.off)||e.layout!==void 0||e.rotFit)&&t.push("rot"),!i&&e.kind!=="audio"&&["ax","ay"].some(n=>u(e,n).length>1||Math.abs(f(e,n,0))>1e-9)&&d&&t.push("anchor with rotation"),i&&(e.transition||e._txIn||e._txOut)&&t.push("transition on a 3D layer");for(const[n,o]of Object.entries(H))!(i&&K.has(n))&&(u(e,n).length>1||Math.abs(f(e,n,0)-o)>1e-9)&&t.push(n);e.grade&&!e.colorBypass&&(e.grade.lut||T(e.grade).length)&&t.push("grade"),e.grade&&!e.colorBypass&&I(e.grade).some(n=>L(n)&&(n.window?.type==="person"||n.qualifier&&(n.window?.type==="polygon"||n.motion||n.window?.type==="face")))&&t.push("grade window");for(const n of Array.isArray(e.effects)?e.effects:[])!n.off&&!U.has(n.type)&&t.push(`effect ${n.type}`);if($(e,"T")&&t.push("reveal"),e.transition){const n=e.transition.spec||{},o=s=>!!e.transition.ramp||z(s);(Object.keys(n).some(s=>!X.has(s))||["a","b"].some(s=>n[s]&&(Object.keys(n[s]).some(k=>!j.has(k))||!o(n[s]))))&&t.push(`transition ${e.transition.id}`)}return e.kind==="video"&&F(e)&&t.push("title on video"),t}function Y(e,a={}){const{reasons:r}=h(e,a);return{ok:r.length===0,reasons:r}}function G(e,a={}){return[...new Set(h(e,a).codes)].sort()}function h(e,{format:a,camera:r,look:m}={}){const t=[],i=[];e=P((e||[]).filter(n=>!n.disabled),{W:p(a).width,H:p(a).height});const l=b(r)?r:null,{width:d,height:g}=p(a);l&&(e||[]).some(n=>!n.disabled&&n.kind!=="audio"&&y(n))&&l.parentId&&(t.push("camera on a parent"),i.push("camera on a parent")),x(m)&&(t.push("look"),i.push("look"));for(const n of e||[]){if(n.disabled)continue;if(n._group&&n.comp){const s=h(R(n),{format:a});s.reasons.length&&(t.push(`${n.label||n.id} (comp): ${s.reasons.join("; ")}`),i.push(...s.codes))}const o=C(n,{camera:l,W:d,H:g});o.length&&(t.push(`${n.label||n.id}: ${o.join(", ")}`),i.push(...o))}if(!t.length)for(const n of w((e||[]).filter(o=>!o.disabled))){const o=s=>{t.push(`${n.label||n.id}: ${s}`),i.push(s)};n.timeRemap&&(n._txIn||n._txOut)&&!n._ramp&&o("time remap in a transition"),n.motionBlur&&(n._txIn||n._txOut)&&o("motion blur in a transition")}return{reasons:t,codes:i}}const q=(e,a,r)=>(a==="video encode"||a==="finalize")&&r?.codec!=="hevc"&&e?.name!=="AbortError"&&/^(OperationError|EncodingError)$/.test(e?.name||""),Q=e=>!(typeof DOMException<"u"&&e instanceof DOMException)&&!(e instanceof TypeError)&&!(e instanceof Error&&/^media \d{3}$/.test(e.message))?"":(e.message||"").replace(/\b(?:https?|blob|data):\S*/gi,"").replace(/\s+/g," ").trim();export{J as HEAVY_FIELDS,Y as clientExportCheck,G as clientExportCodes,C as clipBlockers,Q as gpuErrorText,q as softwareRetry};
@@ -0,0 +1,17 @@
1
+ import{I as le,bz as Z,u as fe,g as S,a_ as K,X as $,ak as O,bC as pe,bD as V,bE as ee,b9 as te,bF as W,bG as me,V as se,bA as re,bH as ie,bx as X,b as we,bI as ge,a$ as ye,bm as be,b2 as ae,bJ as _e,b3 as oe}from"./id3-arvEpAg7.js";import{O as ne,E as Te,N as ve,a as Ee,V as de,b as Ce,c as Ae,d as L}from"./output-p-Q7qous.js";/*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */var G=function(s,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(d){return Promise.reject(d)}}),s.stack.push({value:e,dispose:r,async:t})}else t&&s.stack.push({async:!0});return e},H=(function(s){return function(e){function t(c){e.error=e.hasError?new s(c,e.error,"An error was suppressed during disposal."):c,e.hasError=!0}var r,i=0;function d(){for(;r=e.stack.pop();)try{if(!r.async&&i===1)return i=0,e.stack.push(r),Promise.resolve().then(d);if(r.dispose){var c=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(c).then(d,function(u){return t(u),d()})}else i|=1}catch(u){t(u)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return d()}})(typeof SuppressedError=="function"?SuppressedError:function(s,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=s,r.suppressed=e,r});const U=s=>{if(!s||typeof s!="object")throw new TypeError("options.video, when provided, must be an object.");if(s?.discard!==void 0&&typeof s.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(s?.forceTranscode!==void 0&&typeof s.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(s?.codec!==void 0&&!ae.includes(s.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ae.join(", ")}.`);const e=s?.bitrate;if(s?.quality!==void 0&&!(s.quality instanceof W))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(s?.quality!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof W)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(s?.width!==void 0&&(!Number.isInteger(s.width)||s.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(s?.height!==void 0&&(!Number.isInteger(s.height)||s.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(s?.fit!==void 0&&!["fill","contain","cover"].includes(s.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(s?.width!==void 0&&s.height!==void 0&&s.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(s?.rotate!==void 0&&![0,90,180,270].includes(s.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(s?.allowRotationMetadata!==void 0&&typeof s.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(s?.crop!==void 0&&_e(s.crop,"options.video."),s?.frameRate!==void 0&&(!Number.isFinite(s.frameRate)||s.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(s?.alpha!==void 0&&!["discard","keep"].includes(s.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(s?.keyFrameInterval!==void 0&&(!Number.isFinite(s.keyFrameInterval)||s.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(s?.process!==void 0&&typeof s.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(s?.processedWidth!==void 0&&(!Number.isInteger(s.processedWidth)||s.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(s?.processedHeight!==void 0&&(!Number.isInteger(s.processedHeight)||s.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(s?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(s.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(s?.group!==void 0&&!(s.group instanceof L||Array.isArray(s.group)&&s.group.every(t=>t instanceof L)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},B=s=>{if(!s||typeof s!="object")throw new TypeError("options.audio, when provided, must be an object.");if(s?.discard!==void 0&&typeof s.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(s?.forceTranscode!==void 0&&typeof s.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(s?.codec!==void 0&&!oe.includes(s.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${oe.join(", ")}.`);const e=s?.bitrate;if(s?.quality!==void 0&&!(s.quality instanceof W))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(s?.quality!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof W)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(s?.numberOfChannels!==void 0&&(!Number.isInteger(s.numberOfChannels)||s.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(s?.sampleRate!==void 0&&(!Number.isInteger(s.sampleRate)||s.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(s?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(s.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(s?.process!==void 0&&typeof s.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(s?.processedNumberOfChannels!==void 0&&(!Number.isInteger(s.processedNumberOfChannels)||s.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(s?.processedSampleRate!==void 0&&(!Number.isInteger(s.processedSampleRate)||s.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(s?.group!==void 0&&!(s.group instanceof L||Array.isArray(s.group)&&s.group.every(t=>t instanceof L)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},J=2,Y=48e3;class he{static async init(e){const t=new he(e);return await t._init(),t}constructor(e){if(this.state="idle",this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new Se(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof le))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof ne))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");const t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const r of e.video)U(r);else U(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const r of e.audio)B(r);else B(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&Z(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._composable=t,this.input=e.input,this.output=e.output}async _init(){const e=await this.input.getFormat();let t,r=this._options.tracks;if(r===void 0&&(r=e.name.includes("(HLS)")?"primary":"all"),r==="all")t=await this.input.getTracks();else if(r==="primary"){const o=await this.input.getPrimaryVideoTrack(),a=await this.input.getPrimaryAudioTrack();t=[o,a].filter(p=>p!==null)}else fe(r),S(!1);const i=this.output.format.getSupportedTrackCounts();let d=1,c=1;const u=[],x=[];for(const o of t){let a;if(o.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const n=await this._options.video(o,d)??{};if(Array.isArray(n))for(const h of n)U(h);else U(n);a=Array.isArray(n)?n:[n],d++}else a=Array.isArray(this._options.video)?this._options.video:[this._options.video];else a=[{}];else if(o.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const n=await this._options.audio(o,c)??{};if(Array.isArray(n))for(const h of n)B(h);else B(n);a=Array.isArray(n)?n:[n],c++}else a=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else a=[{}];else S(!1);const p=a.filter(n=>n.discard);for(const n of p)this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:n});if(a.length===p.length){a.length===0&&this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:{}});continue}const w=a.filter(n=>!n.discard);u.push(o),x.push(w)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(u),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let o=0;o<u.length;o++){const a=u[o],p=x[o];for(const w of p){if(this.output.tracks.length===i.total.max){this.discardedTracks.push({track:a,reason:"max_track_count_reached",trackOptions:w});continue}if(this.output.tracks.reduce((F,k)=>F+(k.type===a.type?1:0),0)===i[a.type].max){this.discardedTracks.push({track:a,reason:"max_track_count_of_type_reached",trackOptions:w});continue}const h=this._nextOutputTrackId++;a.isVideoTrack()?await this._processVideoTrack(a,w,h):a.isAudioTrack()?await this._processAudioTrack(a,w,h):S(!1)}}for(let o=0;o<this.utilizedTracks.length-1;o++)for(let a=o+1;a<this.utilizedTracks.length;a++){const p=this.utilizedTracks[o],w=this.utilizedTracks[a],n=this._outputOwnTrackGroups[o],h=this._outputOwnTrackGroups[a];S(n!==void 0),S(h!==void 0),n&&h&&p.canBePairedWith(w)&&n.pairWith(h)}if(!this._composable){const o=await this.input.getMetadataTags();let a;if(this._options.tags){const n=typeof this._options.tags=="function"?await this._options.tags(o):this._options.tags;Z(n),a=n}else a=o;const p=e.mimeType===this.output.format.mimeType,w=o.raw===a.raw;o.raw&&w&&!p&&delete a.raw,this.output.setMetadataTags(a)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){const o=[],a=this.discardedTracks.filter(p=>p.reason!=="discarded_by_user");a.length>0&&o.push("Some tracks had to be discarded from the conversion:",a),this.isValid||(o.length>0&&o.push(`
8
+
9
+ `),o.push(this._getInvalidityExplanation().join(""))),o.length>0&&K._warn(...o)}}_getInvalidityExplanation(){const e=[];if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const r=this.discardedTracks.flatMap(d=>{if(d.reason==="discarded_by_user")return[];let c;return d.track.type==="video"?c=this.output.format.getSupportedVideoCodecs():d.track.type==="audio"?c=this.output.format.getSupportedAudioCodecs():c=this.output.format.getSupportedSubtitleCodecs(),c.filter(u=>!d.trackOptions.codec||u===d.trackOptions.codec)}),i=[...new Set(r)];i.length===1?e.push(`
10
+ Tracks were discarded because your environment is not able to encode '${i[0]}' with the provided parameters.`):e.push(`
11
+ Tracks were discarded because your environment is not able to encode any of the codecs ${i.map(d=>`'${d}'`).join(", ")} with the provided parameters.`),i.includes("mp3")&&e.push(`
12
+ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),i.includes("aac")&&e.push(`
13
+ The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(i.includes("ac3")||i.includes("eac3"))&&e.push(`
14
+ The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),i.includes("flac")&&e.push(`
15
+ The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
16
+ Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.until!==void 0&&(typeof e.until!="number"||Number.isNaN(e.until)))throw new TypeError("options.until, when provided, must be a number.");if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
17
+ `+this._getInvalidityExplanation().join(""));if(this.state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this.state==="canceled")throw new ce;if(this.state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this.state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;const t=()=>{this.state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener("abort",t);for(const i of this._trackPumps)i.done||(i.resolvers=$());if(this._executed)for(const i of this._trackPumps)i.wake?.();else{this._executed=!0;for(const i of this._outputTrackIds)this._synchronizer.declareTrack(i);if(this.onProgress){const d=[...new Set(this.utilizedTracks)].map(async u=>await u.isLive()?1/0:await u.getDurationFromMetadata()??await u.computeDuration()),c=Math.max(0,...await Promise.all(d));this._computeProgress=!0,this._totalDuration=Math.min(c-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const u of this._outputTrackIds)this._maxTimestamps.set(u,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(const i of this._trackPumps)i.start()}try{await Promise.all(this._trackPumps.map(i=>i.resolvers.promise))}catch(i){throw this.state!=="canceled"&&this.cancel(),i}finally{e.pauseSignal?.removeEventListener("abort",t)}if(this.state==="canceled")throw new ce;const r=this._trackPumps.every(i=>i.done);if(this.state=r?"done":"idle",r&&(this._composable||await this.output.finalize(),this._computeProgress)){const i=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,i)}}async cancel(){if(this.state!=="done"){if(this.state==="canceled"){K._warn("Conversion already canceled.");return}this.state="canceled";for(const e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,r){const i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let d;const c=await e.getRotation(),u=O(c+(t.rotate??0));let x=u;const o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),a=await e.getSquarePixelWidth(),p=await e.getSquarePixelHeight(),[w,n]=u%180===0?[a,p]:[p,a];let h=t.crop;h&&(h=pe(h,w,n));const[F,k]=h?[h.width,h.height]:[w,n];let g=F,y=k;const j=g/y;t.width!==void 0&&t.height===void 0?(g=V(t.width),y=V(Math.round(g/j))):t.width===void 0&&t.height!==void 0?(y=V(t.height),g=V(Math.round(y*j))):t.width!==void 0&&t.height!==void 0&&(g=V(t.width),y=V(t.height));const P=await e.getFirstTimestamp();let C=this.output.format.getSupportedVideoCodecs();const _=!!t.forceTranscode||P<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!C.includes(i)||t.codec&&t.codec!==i||g!==F||y!==k||u!==0&&!o||!!h,b=t.alpha??"discard";if(_){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(C=C.filter(v=>v===t.codec));const l=te(t.quality,t.bitrate)??new W("high"),z=await me(C,{width:t.process&&t.processedWidth?t.processedWidth:g,height:t.process&&t.processedHeight?t.processedHeight:y,quality:l});if(!z){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const m={codec:z,quality:l,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:b,hardwareAcceleration:t.hardwareAcceleration,transform:{}};S(m.transform);let M=g!==F||y!==k||u!==0&&(!o||t.process!==void 0)||!!h||a!==await e.getCodedWidth()||p!==await e.getCodedHeight();if(!M){const v={stack:[],error:void 0,hasError:!1};try{const A=new ne({format:new Ee,target:new ve}),I=new de(m);A.addVideoTrack(I),await A.start();const D=new se(e),E=G(v,await D.getSample(P),!1);if(E)try{await I.add(E),E.close(),await A.finalize()}catch(Q){K._warn("An error occurred when probing encoder support. Falling back to rerender path.",Q),A.cancel(),M=!0,m.transform.force=!0}else await A.cancel()}catch(A){v.error=A,v.hasError=!0}finally{H(v)}}t.frameRate&&(m.transform.frameRate=t.frameRate),t.process&&(m.transform.process=t.process),M&&(x=0,m.transform.width=g,m.transform.height=y,m.transform.fit=t.fit??"fill",m.transform.rotate=O(u-c),m.transform.crop=h,m.transform.alpha=b);let T=null;m.onEncodedSample=v=>{T=v.timestamp};const f=new de(m);d=f,this._registerTrackPump(async v=>{const A=new se(e);for await(const I of A.samples(this._startTimestamp,this._endTimestamp)){const D={stack:[],error:void 0,hasError:!1};try{const E=G(D,I,!1);if(this.state==="canceled")break;const Q=Math.max(E.timestamp-this._startTimestamp,0);E.setTimestamp(Q),this._reportProgress(r,E.timestamp+E.duration),await f.add(E),E.close(),T!==null&&(this._synchronizer.shouldWait(r,T)&&await this._synchronizer.wait(T),await this._checkpoint(v,T))}catch(E){D.error=E,D.hasError=!0}finally{H(D)}}f.close(),this._synchronizer.closeTrack(r)})}else{const R=new Te(i);d=R,this._registerTrackPump(async l=>{const z=new ee(e),M={decoderConfig:await e.getDecoderConfig()??void 0};for await(const T of z.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this.state==="canceled"||T.timestamp>=this._endTimestamp)break;const f=T.clone({timestamp:T.timestamp-this._startTimestamp,sideData:b==="discard"?{}:T.sideData});S(f.timestamp>=0),this._reportProgress(r,f.timestamp+f.duration),await R.add(f,M),this._synchronizer.shouldWait(r,f.timestamp)&&await this._synchronizer.wait(f.timestamp),await this._checkpoint(l,f.timestamp)}R.close(),this._synchronizer.closeTrack(r)})}let N=null;!t.group&&!this._composable&&(N=new L);const q=await e.getLanguageCode();this.output.addVideoTrack(d,{frameRate:t.frameRate,languageCode:re(q)?q:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:x,group:N??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(N)}async _processAudioTrack(e,t,r){const i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let d;const c=await e.getNumberOfChannels(),u=await e.getSampleRate(),x=await e.getFirstTimestamp();let o=t.numberOfChannels??c,a=t.sampleRate??u;const p=x<this._startTimestamp;let w=x>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,n=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.quality&&!t.bitrate&&o===c&&a===u&&!p&&!w&&n.includes(i)&&(!t.codec||t.codec===i)&&!t.process&&t.sampleFormat===void 0){const k=new Ce(i);d=k,this._registerTrackPump(async g=>{const y=new ee(e),P={decoderConfig:await e.getDecoderConfig()??void 0};for await(const C of y.packets()){if(this.state==="canceled"||C.timestamp>=this._endTimestamp)break;const _=C.clone({timestamp:C.timestamp-this._startTimestamp});S(_.timestamp>=0),this._reportProgress(r,_.timestamp+_.duration),await k.add(_,P),this._synchronizer.shouldWait(r,_.timestamp)&&await this._synchronizer.wait(_.timestamp),await this._checkpoint(g,_.timestamp)}k.close(),this._synchronizer.closeTrack(r)})}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let g=null;t.codec&&(n=n.filter(b=>b===t.codec));const y=te(t.quality,t.bitrate)??new W("high"),j=await ie(n,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:o,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:a,quality:y});if(!j.some(b=>X.includes(b))&&n.some(b=>X.includes(b))&&(o!==J||a!==Y)){const N=(await ie(n,{numberOfChannels:J,sampleRate:Y,quality:y})).find(q=>X.includes(q));N&&(g=N,o=J,a=Y)}else g=j[0]??null;if(g===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const P={codec:g,quality:y,transform:{sampleFormat:t.sampleFormat,process:t.process}};S(P.transform),o!==c&&(P.transform.numberOfChannels=o),a!==u&&(P.transform.sampleRate=a);let C=null;P.onEncodedSample=b=>{C=b.timestamp};const _=new Ae(P);d=_,this._registerTrackPump(async b=>{const N=new we(e);for await(const q of N.samples(this._startTimestamp,this._endTimestamp)){const R={stack:[],error:void 0,hasError:!1};try{const l=G(R,q,!1);if(this.state==="canceled")break;if(w){const f={stack:[],error:void 0,hasError:!1};try{const v=x-this._startTimestamp,A=Math.round(v*u),I=ge(l.format),D=new Uint8Array(I*A*c);(l.format==="u8"||l.format==="u8-planar")&&D.fill(2**7);const E=G(f,new ye({data:D,format:l.format,numberOfChannels:c,sampleRate:u,timestamp:0}),!1);await this._registerAudioSample(b,E,_,r,()=>C),w=!1}catch(v){f.error=v,f.hasError=!0}finally{H(f)}}let z=0,m=l.numberOfFrames;l.timestamp<this._startTimestamp&&(z=Math.round((this._startTimestamp-l.timestamp)*l.sampleRate)),l.timestamp+l.duration>this._endTimestamp&&(m=Math.round((this._endTimestamp-l.timestamp)*l.sampleRate));let M;if(z>0||m<l.numberOfFrames){const f=l.trim(z,m);if(l.close(),M=f,f.numberOfFrames===0){f.close();continue}}else M=l;const T=G(R,M,!1);T.setTimestamp(T.timestamp-this._startTimestamp),await this._registerAudioSample(b,T,_,r,()=>C)}catch(l){R.error=l,R.hasError=!0}finally{H(R)}}_.close(),this._synchronizer.closeTrack(r)})}let h=null;!t.group&&!this._composable&&(h=new L);const F=await e.getLanguageCode();this.output.addAudioTrack(d,{languageCode:re(F)?F:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:h??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(h)}async _registerAudioSample(e,t,r,i,d){this._reportProgress(i,t.timestamp+t.duration),await r.add(t),t.close();const c=d();c!==null&&(this._synchronizer.shouldWait(i,c)&&await this._synchronizer.wait(c),await this._checkpoint(e,c))}_registerTrackPump(e){const t={done:!1,resolvers:$(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},r=>{t.resolvers.reject(r)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this.state!=="canceled"&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();const{promise:r,resolve:i}=$();e.wake=i,await r}}_reportProgress(e,t){if(!this._computeProgress)return;S(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const r=Math.min(...this._maxTimestamps.values()),i=be(r/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,this.onProgress?.(i,r))}}class ce extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const ue=1;class Se{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const r=this.maxTimestamps.get(e);S(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r));const i=this.computeMinAndMaybeResolve();return this.conversion.state==="canceled"||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-i>ue}wait(e){const{promise:t,resolve:r}=$();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(const e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const r=this.resolvers[t];r.timestamp-e<ue&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}}export{he as C,ce as a};
@@ -1 +1 @@
1
- import{nt as I,nu as y,nv as N,_ as B}from"./titleFrameBudget-BYRZAQPs.js";import{t as g}from"./api-DUp403BK.js";const C="1.31.1",H=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${C}/dist/`,u={url:"https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/4472b7362082ad9968fee890ca0f1e5aca36b93d/onnx/model_quantized.onnx",sha256:"fcf51f1b230362b28690bb9d1809bf0431f29cad20534e3f589bd7285547f20d",bytes:27258801,cache:"clipoox-depth-1"},K=[.485,.456,.406],L=[.229,.224,.225],x=378;let f=null;const U=o=>[...new Uint8Array(o)].map(i=>i.toString(16).padStart(2,"0")).join("");async function W(o){const i=await caches.open(u.cache).catch(()=>null),r=await i?.match(u.url);if(r){const c=new Uint8Array(await r.arrayBuffer());if(c.length===u.bytes)return c}const h=await fetch(u.url);if(!h.ok||!h.body)throw Error(g("Không tải được mô hình độ sâu (HTTP {0})",[h.status]));const t=h.body.getReader(),n=[];let a=0;for(;;){const{done:c,value:p}=await t.read();if(c)break;n.push(p),a+=p.length,o?.(Math.min(1,a/u.bytes))}const s=new Uint8Array(a);let m=0;for(const c of n)s.set(c,m),m+=c.length;if(U(await crypto.subtle.digest("SHA-256",s))!==u.sha256)throw Error(g("Mô hình độ sâu tải về bị lỗi (mã kiểm tra không khớp) — thử lại."));return await i?.put(u.url,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),s}function z(o){return f||(f=(async()=>{const i=await B(()=>import(`${H}ort.wasm.min.mjs`),[]);i.env.wasm.wasmPaths=H,i.env.wasm.numThreads=1;const r=await i.InferenceSession.create(await W(o),{executionProviders:["wasm"],graphOptimizationLevel:"all"});return Object.assign(r,{ort:i})})(),f.catch(()=>{f=null})),f}async function V(o,i){const r=document.createElement("canvas"),h=r.getContext("2d",{willReadFrequently:!0});if(o.kind==="image"){const n=new Image;return n.crossOrigin="anonymous",n.src=o.url,await new Promise((a,s)=>{n.onload=()=>a(),n.onerror=()=>s(Error(g("Không đọc được ảnh của clip")))}),r.width=n.naturalWidth,r.height=n.naturalHeight,h.drawImage(n,0,0),r}const t=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});t.src=o.url;try{await new Promise((a,s)=>{t.onloadeddata=()=>a(),t.onerror=()=>s(Error(g("Không đọc được video của clip (CORS / định dạng)")))});const n=Math.max(0,Math.min(t.duration-1/60,(o.inPoint||0)+i*(o.playbackRate||1)));return await new Promise((a,s)=>{const m=window.setTimeout(()=>s(Error(g("Seek video quá lâu"))),8e3);t.onseeked=()=>{window.clearTimeout(m),a()},t.currentTime=n}),r.width=t.videoWidth||1280,r.height=t.videoHeight||720,h.drawImage(t,0,0),r}finally{t.removeAttribute("src"),t.load()}}async function J(o,i,r){const h=Math.max(0,Math.min(o.duration,i));if(window.__depthStub){const e=window.__depthStub(o,h);return I(e.data,e.w,e.h,h)}const[t,n]=await Promise.all([z(e=>r?.("download",e)),V(o,h)]);r?.("run");const a=n.width/Math.max(1,n.height),s=e=>Math.max(14,Math.round(e/14)*14),m=a>=1?s(x*a):x,c=a>=1?x:s(x/a),p=Object.assign(document.createElement("canvas"),{width:m,height:c}),b=p.getContext("2d",{willReadFrequently:!0});b.imageSmoothingQuality="high",b.drawImage(n,0,0,m,c);const j=b.getImageData(0,0,m,c).data,M=m*c,O=new Float32Array(3*M);for(let e=0;e<M;e++)for(let d=0;d<3;d++)O[d*M+e]=(j[e*4+d]/255-K[d])/L[d];const v=(await t.run({[t.inputNames[0]]:new t.ort.Tensor("float32",O,[1,3,c,m])}))[t.outputNames[0]],T=v.dims.at(-2),S=v.dims.at(-1),l=a>=1?y.maxSide:Math.max(2,Math.round(y.maxSide*a)),w=a>=1?Math.max(2,Math.round(y.maxSide/a)):y.maxSide,P=new Float32Array(l*w);for(let e=0;e<w;e++)for(let d=0;d<l;d++){const k=Math.floor(d*S/l),q=Math.max(k+1,Math.floor((d+1)*S/l)),A=Math.floor(e*T/w),F=Math.max(A+1,Math.floor((e+1)*T/w));let R=0,D=0;for(let _=A;_<F;_++)for(let E=k;E<q;E++)R+=v.data[_*S+E],D++;P[e*l+d]=R/Math.max(1,D)}return I(N(P),l,w,h)}export{u as DEPTH_MODEL,J as estimateDepth};
1
+ import{nt as I,nu as y,nv as N,_ as B}from"./titleFrameBudget-CLZWaFHO.js";import{t as g}from"./api-CJ8PdbfZ.js";const C="1.31.1",H=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${C}/dist/`,u={url:"https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/4472b7362082ad9968fee890ca0f1e5aca36b93d/onnx/model_quantized.onnx",sha256:"fcf51f1b230362b28690bb9d1809bf0431f29cad20534e3f589bd7285547f20d",bytes:27258801,cache:"clipoox-depth-1"},K=[.485,.456,.406],L=[.229,.224,.225],x=378;let f=null;const U=o=>[...new Uint8Array(o)].map(i=>i.toString(16).padStart(2,"0")).join("");async function W(o){const i=await caches.open(u.cache).catch(()=>null),r=await i?.match(u.url);if(r){const c=new Uint8Array(await r.arrayBuffer());if(c.length===u.bytes)return c}const h=await fetch(u.url);if(!h.ok||!h.body)throw Error(g("Không tải được mô hình độ sâu (HTTP {0})",[h.status]));const t=h.body.getReader(),n=[];let a=0;for(;;){const{done:c,value:p}=await t.read();if(c)break;n.push(p),a+=p.length,o?.(Math.min(1,a/u.bytes))}const s=new Uint8Array(a);let m=0;for(const c of n)s.set(c,m),m+=c.length;if(U(await crypto.subtle.digest("SHA-256",s))!==u.sha256)throw Error(g("Mô hình độ sâu tải về bị lỗi (mã kiểm tra không khớp) — thử lại."));return await i?.put(u.url,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),s}function z(o){return f||(f=(async()=>{const i=await B(()=>import(`${H}ort.wasm.min.mjs`),[]);i.env.wasm.wasmPaths=H,i.env.wasm.numThreads=1;const r=await i.InferenceSession.create(await W(o),{executionProviders:["wasm"],graphOptimizationLevel:"all"});return Object.assign(r,{ort:i})})(),f.catch(()=>{f=null})),f}async function V(o,i){const r=document.createElement("canvas"),h=r.getContext("2d",{willReadFrequently:!0});if(o.kind==="image"){const n=new Image;return n.crossOrigin="anonymous",n.src=o.url,await new Promise((a,s)=>{n.onload=()=>a(),n.onerror=()=>s(Error(g("Không đọc được ảnh của clip")))}),r.width=n.naturalWidth,r.height=n.naturalHeight,h.drawImage(n,0,0),r}const t=Object.assign(document.createElement("video"),{muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous"});t.src=o.url;try{await new Promise((a,s)=>{t.onloadeddata=()=>a(),t.onerror=()=>s(Error(g("Không đọc được video của clip (CORS / định dạng)")))});const n=Math.max(0,Math.min(t.duration-1/60,(o.inPoint||0)+i*(o.playbackRate||1)));return await new Promise((a,s)=>{const m=window.setTimeout(()=>s(Error(g("Seek video quá lâu"))),8e3);t.onseeked=()=>{window.clearTimeout(m),a()},t.currentTime=n}),r.width=t.videoWidth||1280,r.height=t.videoHeight||720,h.drawImage(t,0,0),r}finally{t.removeAttribute("src"),t.load()}}async function J(o,i,r){const h=Math.max(0,Math.min(o.duration,i));if(window.__depthStub){const e=window.__depthStub(o,h);return I(e.data,e.w,e.h,h)}const[t,n]=await Promise.all([z(e=>r?.("download",e)),V(o,h)]);r?.("run");const a=n.width/Math.max(1,n.height),s=e=>Math.max(14,Math.round(e/14)*14),m=a>=1?s(x*a):x,c=a>=1?x:s(x/a),p=Object.assign(document.createElement("canvas"),{width:m,height:c}),b=p.getContext("2d",{willReadFrequently:!0});b.imageSmoothingQuality="high",b.drawImage(n,0,0,m,c);const j=b.getImageData(0,0,m,c).data,M=m*c,O=new Float32Array(3*M);for(let e=0;e<M;e++)for(let d=0;d<3;d++)O[d*M+e]=(j[e*4+d]/255-K[d])/L[d];const v=(await t.run({[t.inputNames[0]]:new t.ort.Tensor("float32",O,[1,3,c,m])}))[t.outputNames[0]],T=v.dims.at(-2),S=v.dims.at(-1),l=a>=1?y.maxSide:Math.max(2,Math.round(y.maxSide*a)),w=a>=1?Math.max(2,Math.round(y.maxSide/a)):y.maxSide,P=new Float32Array(l*w);for(let e=0;e<w;e++)for(let d=0;d<l;d++){const k=Math.floor(d*S/l),q=Math.max(k+1,Math.floor((d+1)*S/l)),A=Math.floor(e*T/w),F=Math.max(A+1,Math.floor((e+1)*T/w));let R=0,D=0;for(let _=A;_<F;_++)for(let E=k;E<q;E++)R+=v.data[_*S+E],D++;P[e*l+d]=R/Math.max(1,D)}return I(N(P),l,w,h)}export{u as DEPTH_MODEL,J as estimateDepth};
@@ -1 +1 @@
1
- import{C as D,c as F}from"./cameraPresets-DSOPj4oy.js";import{gM as g,iY as y,ft as k,fu as P,fE as S,fD as A,fF as N,fy as x,fz as C,fx as v,jo as I,fq as j,fG as R,fw as $}from"./remote-Dva2qg58.js";import{s as z}from"./weaponDuel-D6sLVGmG.js";import"./api-DUp403BK.js";import"./titleFrameBudget-BYRZAQPs.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-75tQUvPT.js";import"./rotoMaskStore-BxyxB2bD.js";import"./textAnimators-nVSz_sZo.js";import"./timelineComp-BcewYGR2.js";import"./rigTrack-UYZU4P-e.js";const L=["katana","spear","staff","fist"],M=D.map(e=>e.id),O=()=>crypto.randomUUID(),w=e=>Math.round(e*100)/100,b=(e,a)=>L.includes(e)?e:a,E=(e,a,m)=>({...e,shots:e.shots.map(f=>f.id===a?{...f,...m}:f)}),T=e=>{const a=g(e),m=k(a.timing,a.duration);return{hit_stops:m?.holds.length??0,slow_spans:m?.slows??[],scene_s:a.duration,video_s:w($(a)),...a.impactFrame?{impact_frame:a.impactFrame}:{}}};function Z(e,a){const m=a.getStage(),f=g(m),n=Array.isArray(e.fighters)?e.fighters.map(String):[];if(n.length!==2)return{ok:!1,error:"give fighters: [first attacker, opponent] (two person names)"};let r;try{r=n.map(t=>y(m,t))}catch(t){return{ok:!1,error:t.message}}for(const t of r)if(!j(t))return{ok:!1,error:`'${t.name}' is not a person (or a humanoid-rigged model)`};const p=Array.isArray(e.weapons)?e.weapons:[e.weapons??e.weapon,e.weapons??e.weapon],c=[b(p[0],"katana"),b(p[1]??p[0],b(p[0],"katana"))],h=Math.max(0,Math.min(f.duration,Number(e.start??0)||0)),i=z(m,{a:r[0].id,b:r[1].id,packs:c,exchanges:Number(e.exchanges??4)||4,seed:Number(e.seed)||1,start:h,hitStops:e.hit_stops!==!1},O);if(!i.ok)return{ok:!1,error:i.error};let s=i.stage;const l=Math.min(g(s).duration,i.end+.4),u=String(e.camera??"fight");let o={kept:"your own camera"};if(u==="fight")try{const t=R(s,{fighters:r.map(_=>_.name),start:h,end:l,focal_length_mm:Number(e.focal_length_mm)||32});s=t.stage,o={fight_camera:t.result}}catch(t){o={error:t.message}}else if(u!=="none"){const t=F(s,{preset:u,subject:r[0].id,start:h,end:l});t.ok?(s=t.stage,o={preset:t.preset,subject:t.subject,keys:t.keys,cuts:t.cuts}):o={error:t.error}}if(e.impact_frame&&e.impact_frame!=="none"){const t=v({style:e.impact_frame,strength:e.impact_strength??.8});t&&(s=E(s,g(s).id,{impactFrame:t}))}return a.setStage(()=>s),{ok:!0,fighters:r.map(t=>t.name),weapons:c,start:h,end:i.end,shot_duration_s:g(s).duration,exchange:i.plan.map(t=>({time_s:t.time,attacker:t.attackerName,attack:t.attack,defence:t.defence,result:t.result})),camera:o,timing:T(s),...i.notes.length?{notes:i.notes}:{},hint:"weapons are put in the hands with a trail (set_trail to restyle); re-run with another seed for another plan; add impact effects at the strike times of blocked / body results (none on a miss = a dodge) and set_timing for slow motion on the finisher"}}function ee(e,a){const m=a.getStage(),f=g(m);if(!M.includes(String(e.preset)))return{ok:!1,error:`unknown preset; use one of ${M.join(", ")}`};let n;try{n=y(m,String(e.subject??""))}catch(h){return{ok:!1,error:h.message}}const r=Math.max(0,Number(e.start??0)||0),p=e.end==null?f.duration:Number(e.end),c=F(m,{preset:String(e.preset),subject:n.id,start:r,end:p});return c.ok?(a.setStage(()=>c.stage),{ok:!0,preset:c.preset,subject:n.name,start:w(c.start),end:w(c.end),camera_keys:c.keys,hit_beats:c.beats,cuts:c.cuts,note:"camera keys inside the span are replaced; the preset tracks the subject's motion, so bake it AFTER the motion is final"}):{ok:!1,error:c.error}}function te(e,a){const m=a.getStage(),f=g(m),n=f.duration;let r=k(f.timing,n);const p=P(m).map(o=>o.time).filter(o=>o>.05&&o<n-.05),c=S[e.strength]??S.medium,h=String(e.hit_stops??"keep");if(h==="none"&&(r=k({holds:[],slows:r?.slows??[]},n)),h==="auto"){if(!p.length)return{ok:!1,error:"no strike in the shot to stop on (stage_fight / stage_duel / play_motion strikes first, or give hit_stops_at)"};r=A(r,p,c,n)}if(Array.isArray(e.hit_stops_at)&&(r=A(r,e.hit_stops_at.map(Number).filter(o=>Number.isFinite(o)&&o>=0&&o<=n),c,n)),e.clear_slow_motion&&(r=k({holds:r?.holds??[],slows:[]},n)),e.slow_finisher){if(!p.length)return{ok:!1,error:"no strike in the shot for slow_finisher"};r=N(r,p[p.length-1],.3,.3,n)}for(const o of Array.isArray(e.slow_motion)?e.slow_motion:[]){const t=Number(o?.at);if(!Number.isFinite(t))return{ok:!1,error:"slow_motion entries need at (scene seconds)"};r=N(r,t,Math.max(.05,Math.min(3,Number(o.half??.35)||.35)),Math.max(.1,Math.min(1,Number(o.speed??.3)||.3)),n)}const i=Number(e._from)||0;if(i>0){const o=k(f.timing,n);r=k({holds:[...(o?.holds??[]).filter(t=>t.at<i),...(r?.holds??[]).filter(t=>t.at>=i)],slows:[...(o?.slows??[]).filter(t=>t.start<i),...(r?.slows??[]).filter(t=>t.start>=i)]},n)}let s={timing:r??void 0},l=null;if(e.preset==="sakuga"){if(l=x({...f,timing:r??void 0},C(m).filter(_=>_.at>.05&&_.at<n-.05),{keepLook:!1}),!l)return{ok:!1,error:"no blow in the shot for preset sakuga (stage_fight / resolve_hits first)"};let o=l.shot.timing??null,t=l.shot.impacts;if(i>0){const _=k(f.timing,n);o=k({holds:[...(_?.holds??[]).filter(d=>d.at<i),...(o?.holds??[]).filter(d=>d.at>=i)],slows:[...(_?.slows??[]).filter(d=>d.start<i),...(o?.slows??[]).filter(d=>d.start>=i)]},n),t=[...(f.impacts??[]).filter(d=>d.time*n<i),...(t??[]).filter(d=>d.time*n>=i)]}s={timing:o??void 0,impacts:t,impactFrame:l.shot.impactFrame}}if(e.impact_frame==="none")s={...s,impactFrame:void 0};else if(e.impact_frame!=null){const o=v({style:e.impact_frame,strength:e.impact_strength??f.impactFrame?.strength??.8});if(!o)return{ok:!1,error:`impact_frame: one of ${I.join(", ")} or none`};s={...s,impactFrame:o}}const u=E(m,f.id,s);return a.setStage(()=>u),{ok:!0,...T(u),strike_beats:p.map(w).slice(0,30),...l?{sakuga:{blows:l.plan.kinds.length,kinds:l.plan.kinds.slice(0,30),finisher_s:l.plan.finisher==null?null:w(l.plan.finisher)}}:{},note:"a render-time warp: preview and export freeze / slow these scene instants; impact frames flash on every hit-stop"}}function se(e,a){const m=a.getStage(),f=Array.isArray(e.names)?e.names.map(String):e.name!=null?[String(e.name)]:[];if(!f.length)return{ok:!1,error:"give names: weapons, or people (their held weapons)"};const n=new Set;for(const i of f){let s;try{s=y(m,i)}catch(l){return{ok:!1,error:l.message}}if(s.kind==="prop"&&s.hold)n.add(s.id);else if(j(s)){const l=m.items.filter(u=>u.kind==="prop"&&u.hold?.by===s.id);if(!l.length)return{ok:!1,error:`${s.name} holds nothing (hold_prop / play_motion a weapon clip / stage_duel first)`};l.forEach(u=>n.add(u.id))}else return{ok:!1,error:`'${s.name}' is not a held weapon or a person`}}const r=e.on!==!1,p={},c=typeof e.color=="string"&&/^#[0-9a-f]{6}$/i.test(e.color)?e.color:void 0,h=e.length!=null&&Number.isFinite(Number(e.length))?Math.max(.03,Math.min(.5,Number(e.length))):void 0;return a.setStage(i=>({...i,items:i.items.map(s=>{if(!n.has(s.id))return s;if(!r){p[s.name]="off";const{trail:u,...o}=s;return o}const l={...s.trail||{},...e.style==="smear"||e.style==="ribbon"?{style:e.style}:{},...c?{color:c}:{},...h!=null?{length:h}:{}};return p[s.name]=l,{...s,trail:l}})})),{ok:!0,trails:p}}export{M as CAMERA_PRESET_IDS,L as DUEL_PACKS,ee as cameraPreset,te as setTiming,se as setTrail,Z as stageDuel};
1
+ import{C as D,c as F}from"./cameraPresets-CYw0OdM3.js";import{gM as g,iY as y,ft as k,fu as P,fE as S,fD as A,fF as N,fy as x,fz as C,fx as v,jo as I,fq as j,fG as R,fw as $}from"./remote-C7J0Tqhb.js";import{s as z}from"./weaponDuel-ZhX-tjGZ.js";import"./api-CJ8PdbfZ.js";import"./titleFrameBudget-CLZWaFHO.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-DW4E9xnW.js";import"./rotoMaskStore-DPziPKAN.js";import"./textAnimators-DUZjhVGO.js";import"./timelineComp-B4GtoH2f.js";import"./rigTrack-urT3nDK0.js";const L=["katana","spear","staff","fist"],M=D.map(e=>e.id),O=()=>crypto.randomUUID(),w=e=>Math.round(e*100)/100,b=(e,a)=>L.includes(e)?e:a,E=(e,a,m)=>({...e,shots:e.shots.map(f=>f.id===a?{...f,...m}:f)}),T=e=>{const a=g(e),m=k(a.timing,a.duration);return{hit_stops:m?.holds.length??0,slow_spans:m?.slows??[],scene_s:a.duration,video_s:w($(a)),...a.impactFrame?{impact_frame:a.impactFrame}:{}}};function Z(e,a){const m=a.getStage(),f=g(m),n=Array.isArray(e.fighters)?e.fighters.map(String):[];if(n.length!==2)return{ok:!1,error:"give fighters: [first attacker, opponent] (two person names)"};let r;try{r=n.map(t=>y(m,t))}catch(t){return{ok:!1,error:t.message}}for(const t of r)if(!j(t))return{ok:!1,error:`'${t.name}' is not a person (or a humanoid-rigged model)`};const p=Array.isArray(e.weapons)?e.weapons:[e.weapons??e.weapon,e.weapons??e.weapon],c=[b(p[0],"katana"),b(p[1]??p[0],b(p[0],"katana"))],h=Math.max(0,Math.min(f.duration,Number(e.start??0)||0)),i=z(m,{a:r[0].id,b:r[1].id,packs:c,exchanges:Number(e.exchanges??4)||4,seed:Number(e.seed)||1,start:h,hitStops:e.hit_stops!==!1},O);if(!i.ok)return{ok:!1,error:i.error};let s=i.stage;const l=Math.min(g(s).duration,i.end+.4),u=String(e.camera??"fight");let o={kept:"your own camera"};if(u==="fight")try{const t=R(s,{fighters:r.map(_=>_.name),start:h,end:l,focal_length_mm:Number(e.focal_length_mm)||32});s=t.stage,o={fight_camera:t.result}}catch(t){o={error:t.message}}else if(u!=="none"){const t=F(s,{preset:u,subject:r[0].id,start:h,end:l});t.ok?(s=t.stage,o={preset:t.preset,subject:t.subject,keys:t.keys,cuts:t.cuts}):o={error:t.error}}if(e.impact_frame&&e.impact_frame!=="none"){const t=v({style:e.impact_frame,strength:e.impact_strength??.8});t&&(s=E(s,g(s).id,{impactFrame:t}))}return a.setStage(()=>s),{ok:!0,fighters:r.map(t=>t.name),weapons:c,start:h,end:i.end,shot_duration_s:g(s).duration,exchange:i.plan.map(t=>({time_s:t.time,attacker:t.attackerName,attack:t.attack,defence:t.defence,result:t.result})),camera:o,timing:T(s),...i.notes.length?{notes:i.notes}:{},hint:"weapons are put in the hands with a trail (set_trail to restyle); re-run with another seed for another plan; add impact effects at the strike times of blocked / body results (none on a miss = a dodge) and set_timing for slow motion on the finisher"}}function ee(e,a){const m=a.getStage(),f=g(m);if(!M.includes(String(e.preset)))return{ok:!1,error:`unknown preset; use one of ${M.join(", ")}`};let n;try{n=y(m,String(e.subject??""))}catch(h){return{ok:!1,error:h.message}}const r=Math.max(0,Number(e.start??0)||0),p=e.end==null?f.duration:Number(e.end),c=F(m,{preset:String(e.preset),subject:n.id,start:r,end:p});return c.ok?(a.setStage(()=>c.stage),{ok:!0,preset:c.preset,subject:n.name,start:w(c.start),end:w(c.end),camera_keys:c.keys,hit_beats:c.beats,cuts:c.cuts,note:"camera keys inside the span are replaced; the preset tracks the subject's motion, so bake it AFTER the motion is final"}):{ok:!1,error:c.error}}function te(e,a){const m=a.getStage(),f=g(m),n=f.duration;let r=k(f.timing,n);const p=P(m).map(o=>o.time).filter(o=>o>.05&&o<n-.05),c=S[e.strength]??S.medium,h=String(e.hit_stops??"keep");if(h==="none"&&(r=k({holds:[],slows:r?.slows??[]},n)),h==="auto"){if(!p.length)return{ok:!1,error:"no strike in the shot to stop on (stage_fight / stage_duel / play_motion strikes first, or give hit_stops_at)"};r=A(r,p,c,n)}if(Array.isArray(e.hit_stops_at)&&(r=A(r,e.hit_stops_at.map(Number).filter(o=>Number.isFinite(o)&&o>=0&&o<=n),c,n)),e.clear_slow_motion&&(r=k({holds:r?.holds??[],slows:[]},n)),e.slow_finisher){if(!p.length)return{ok:!1,error:"no strike in the shot for slow_finisher"};r=N(r,p[p.length-1],.3,.3,n)}for(const o of Array.isArray(e.slow_motion)?e.slow_motion:[]){const t=Number(o?.at);if(!Number.isFinite(t))return{ok:!1,error:"slow_motion entries need at (scene seconds)"};r=N(r,t,Math.max(.05,Math.min(3,Number(o.half??.35)||.35)),Math.max(.1,Math.min(1,Number(o.speed??.3)||.3)),n)}const i=Number(e._from)||0;if(i>0){const o=k(f.timing,n);r=k({holds:[...(o?.holds??[]).filter(t=>t.at<i),...(r?.holds??[]).filter(t=>t.at>=i)],slows:[...(o?.slows??[]).filter(t=>t.start<i),...(r?.slows??[]).filter(t=>t.start>=i)]},n)}let s={timing:r??void 0},l=null;if(e.preset==="sakuga"){if(l=x({...f,timing:r??void 0},C(m).filter(_=>_.at>.05&&_.at<n-.05),{keepLook:!1}),!l)return{ok:!1,error:"no blow in the shot for preset sakuga (stage_fight / resolve_hits first)"};let o=l.shot.timing??null,t=l.shot.impacts;if(i>0){const _=k(f.timing,n);o=k({holds:[...(_?.holds??[]).filter(d=>d.at<i),...(o?.holds??[]).filter(d=>d.at>=i)],slows:[...(_?.slows??[]).filter(d=>d.start<i),...(o?.slows??[]).filter(d=>d.start>=i)]},n),t=[...(f.impacts??[]).filter(d=>d.time*n<i),...(t??[]).filter(d=>d.time*n>=i)]}s={timing:o??void 0,impacts:t,impactFrame:l.shot.impactFrame}}if(e.impact_frame==="none")s={...s,impactFrame:void 0};else if(e.impact_frame!=null){const o=v({style:e.impact_frame,strength:e.impact_strength??f.impactFrame?.strength??.8});if(!o)return{ok:!1,error:`impact_frame: one of ${I.join(", ")} or none`};s={...s,impactFrame:o}}const u=E(m,f.id,s);return a.setStage(()=>u),{ok:!0,...T(u),strike_beats:p.map(w).slice(0,30),...l?{sakuga:{blows:l.plan.kinds.length,kinds:l.plan.kinds.slice(0,30),finisher_s:l.plan.finisher==null?null:w(l.plan.finisher)}}:{},note:"a render-time warp: preview and export freeze / slow these scene instants; impact frames flash on every hit-stop"}}function se(e,a){const m=a.getStage(),f=Array.isArray(e.names)?e.names.map(String):e.name!=null?[String(e.name)]:[];if(!f.length)return{ok:!1,error:"give names: weapons, or people (their held weapons)"};const n=new Set;for(const i of f){let s;try{s=y(m,i)}catch(l){return{ok:!1,error:l.message}}if(s.kind==="prop"&&s.hold)n.add(s.id);else if(j(s)){const l=m.items.filter(u=>u.kind==="prop"&&u.hold?.by===s.id);if(!l.length)return{ok:!1,error:`${s.name} holds nothing (hold_prop / play_motion a weapon clip / stage_duel first)`};l.forEach(u=>n.add(u.id))}else return{ok:!1,error:`'${s.name}' is not a held weapon or a person`}}const r=e.on!==!1,p={},c=typeof e.color=="string"&&/^#[0-9a-f]{6}$/i.test(e.color)?e.color:void 0,h=e.length!=null&&Number.isFinite(Number(e.length))?Math.max(.03,Math.min(.5,Number(e.length))):void 0;return a.setStage(i=>({...i,items:i.items.map(s=>{if(!n.has(s.id))return s;if(!r){p[s.name]="off";const{trail:u,...o}=s;return o}const l={...s.trail||{},...e.style==="smear"||e.style==="ribbon"?{style:e.style}:{},...c?{color:c}:{},...h!=null?{length:h}:{}};return p[s.name]=l,{...s,trail:l}})})),{ok:!0,trails:p}}export{M as CAMERA_PRESET_IDS,L as DUEL_PACKS,ee as cameraPreset,te as setTiming,se as setTrail,Z as stageDuel};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rotoMatte-BdYa8FSB.js","assets/titleFrameBudget-BYRZAQPs.js","assets/api-DUp403BK.js","assets/store-75tQUvPT.js"])))=>i.map(i=>d[i]);
2
- import{f8 as J,hU as A,c1 as Y,eQ as Z,iQ as tt,_ as et,fi as ot}from"./titleFrameBudget-BYRZAQPs.js";import{c as at}from"./distortGL-BlmBZKRU.js";import{I as rt,A as nt,U as it,V as st}from"./id3-BCR9Bqgo.js";const lt=["crop","mask","person","personPending","matteFix","colorPerson","distort","playbackRate","speedRamp","reverse","freeze","smoothSlow","inPoint","sourceDuration","proxy","volume","audioFadeIn","audioFadeOut","duck","muffle","audioFx","audioTools","sfx","face","roto","planar","sceneTrack","hands"],ct=["url","gcsUri","label","nodeId","start","duration","inPoint","sourceDuration","playbackRate","reverse","volume","audioFadeIn","audioFadeOut","duck","muffle","audioFx"],dt=1920,ut=e=>new Promise((p,n)=>{const l=c=>{if(!c)return n(Error("Cannot encode distort frame"));const d=new FileReader;d.onload=()=>p(String(d.result).slice(String(d.result).indexOf(",")+1)),d.onerror=()=>n(d.error),d.readAsDataURL(c)};e instanceof HTMLCanvasElement?e.toBlob(l,"image/webp",.9):e.convertToBlob({type:"image/webp",quality:.9}).then(l,n)});function mt(e,p){const n=e.distort;if(e.kind!=="image"||e.mask||e.person||(n.mesh?.keys.length??0)>1||n.puppet?.pins.some(c=>(c.keys?.length??0)>1)||(n.displace?.keys?.length??0)>1)return!1;const l=n.displace?p.find(c=>c.id===n.displace.map):null;return!l||l.kind==="image"&&!A(l)&&l.start<=e.start&&l.start+l.duration>=e.start+e.duration}async function wt(e,p,n,l,c={}){const d=e.filter(t=>J(t)&&(t.kind==="video"||t.kind==="image")&&!A(t)&&!t.gen);if(!d.length)return{clips:e,tracks:c};const{fps:v}=Y(p),R=()=>{if(l?.aborted)throw new DOMException("Export cancelled","AbortError")},D=new Set(d.map(t=>t.id)),O={...c};let x=Math.max(0,...e.map(t=>t.track),...Object.keys(c).map(Number))+1;const h=[];for(const t of e){if(!D.has(t.id)){h.push(t);continue}const a={...t,kind:"image",warped:!0};for(const i of lt)delete a[i];if(h.push(a),t.kind==="video"&&!t.speedRamp&&!t.freeze&&(t.volume??1)>0){const i={id:`${t.id}~sound`,kind:"audio",track:x},k=t;for(const m of ct)k[m]!==void 0&&(i[m]=k[m]);c[t.track]&&(O[x]={...c[t.track]}),x++,h.push(i)}}const N=new Map(Z(e).filter(t=>t._virtual).map(t=>[t.id,t])),_=[];for(const t of d)_.push({clip:t,as:t});for(const t of tt(h))D.has(String(t._virtual))&&_.push({clip:N.get(t.id)??{...e.find(a=>a.id===t._virtual),...t,_still:!0},as:t});const w=d.some(t=>t.mask||t.person)?await et(()=>import("./rotoMatte-BdYa8FSB.js").then(t=>t.r),__vite__mapDeps([0,1,2,3])):null;w&&await w.prepareMattes(d.filter(t=>t.mask||t.person));const W=w?document.createElement("canvas"):null,T=at(),I=[],S=new Map,U=async t=>{const a=new rt({source:new it(t),formats:nt});I.push(a);const i=await a.getPrimaryVideoTrack();return i?new st(i):null},C=async t=>{let a=S.get(t);return a||(a=await createImageBitmap(await(await fetch(t,{signal:l})).blob(),{imageOrientation:"from-image",premultiplyAlpha:"none",colorSpaceConversion:"none"}),S.set(t,a)),a};try{for(const{clip:t,as:a}of _){R();const i=e.find(o=>o.id===(t._virtual??t.id)),k=Math.ceil(a.duration*v),m=i.distort,Q=!!(t._still||t.freeze),$=o=>{const r=o/v,u=t.playbackRate||1;return t.reverse?Math.max(0,(t.inPoint||0)+Math.max(0,t.duration-r-1/v)*u):ot(t,r,!1,Q).source};let g=null,b=null;if(t.kind==="video"){const o=await U(t.url);o&&(g=o.samplesAtTimestamps(Array.from({length:k},(r,u)=>$(u))))}else b=await C(t.url);const s=m.displace?e.find(o=>o.id===m.displace.map):void 0,V=s?.kind==="video"?await U(s.url):null,L=s?.kind==="image"&&s.url&&!A(s)?await C(s.url):null,q=async o=>{if(!s||o<s.start||o>=s.start+s.duration)return null;if(L)return{source:L};if(!V)return null;const r=await V.getSample((s.inPoint||0)+(o-s.start)*(s.playbackRate||1));if(!r)return null;const u=r.toVideoFrame();return r.close(),{source:u,close:()=>u.close()}},G=mt(i,e);for(let o=0;o<k;o++){R();const r=g?(await g.next()).value??null:null;if(G&&o>0){r?.close(),await n.push("titleFrames",a.id,"=");continue}const u=r?r.toVideoFrame():null,H=u??b,y=r?r.displayWidth:b?.width??0,M=r?r.displayHeight:b?.height??0;if(!H||!y||!M){if(u?.close(),r?.close(),o===0)throw Error(`No picture for ${i.label||i.id}`);await n.push("titleFrames",a.id,"=");continue}const f=t.crop||{left:0,right:0,top:0,bottom:0},K=Math.floor(y*f.left/2)*2,X=Math.floor(M*f.top/2)*2,E=Math.max(2,Math.floor(y*(1-f.left-f.right)/2)*2),F=Math.max(2,Math.floor(M*(1-f.top-f.bottom)/2)*2),z=Math.min(1,dt/Math.max(E,F)),P=o/v,B=await q(t.start+P),j=T.render({source:H,srcW:y,srcH:M,rect:[K,X,E,F],outW:Math.max(2,Math.round(E*z)),outH:Math.max(2,Math.round(F*z)),distort:m,local:t.start+P-i.start,map:B?.source??null,matte:w&&(t.mask||t.person)?w.matteCanvas(t,P,W,!1,e):null});B?.close?.(),u?.close(),r?.close(),await n.push("titleFrames",a.id,await ut(j))}g&&await g.return(void 0)}}finally{T.dispose();for(const t of S.values())t.close();for(const t of I)t.dispose?.()}return{clips:h,tracks:O}}export{wt as distortForServer};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/rotoMatte-C-2o3vv0.js","assets/titleFrameBudget-CLZWaFHO.js","assets/api-CJ8PdbfZ.js","assets/store-DW4E9xnW.js"])))=>i.map(i=>d[i]);
2
+ import{f8 as J,hU as A,c1 as Y,eQ as Z,iQ as tt,_ as et,fi as ot}from"./titleFrameBudget-CLZWaFHO.js";import{c as at}from"./distortGL-QalhICvi.js";import{I as rt,A as nt,U as it,V as st}from"./id3-arvEpAg7.js";const lt=["crop","mask","person","personPending","matteFix","colorPerson","distort","playbackRate","speedRamp","reverse","freeze","smoothSlow","inPoint","sourceDuration","proxy","volume","audioFadeIn","audioFadeOut","duck","muffle","audioFx","audioTools","sfx","face","roto","planar","sceneTrack","hands"],ct=["url","gcsUri","label","nodeId","start","duration","inPoint","sourceDuration","playbackRate","reverse","volume","audioFadeIn","audioFadeOut","duck","muffle","audioFx"],dt=1920,ut=e=>new Promise((p,n)=>{const l=c=>{if(!c)return n(Error("Cannot encode distort frame"));const d=new FileReader;d.onload=()=>p(String(d.result).slice(String(d.result).indexOf(",")+1)),d.onerror=()=>n(d.error),d.readAsDataURL(c)};e instanceof HTMLCanvasElement?e.toBlob(l,"image/webp",.9):e.convertToBlob({type:"image/webp",quality:.9}).then(l,n)});function mt(e,p){const n=e.distort;if(e.kind!=="image"||e.mask||e.person||(n.mesh?.keys.length??0)>1||n.puppet?.pins.some(c=>(c.keys?.length??0)>1)||(n.displace?.keys?.length??0)>1)return!1;const l=n.displace?p.find(c=>c.id===n.displace.map):null;return!l||l.kind==="image"&&!A(l)&&l.start<=e.start&&l.start+l.duration>=e.start+e.duration}async function wt(e,p,n,l,c={}){const d=e.filter(t=>J(t)&&(t.kind==="video"||t.kind==="image")&&!A(t)&&!t.gen);if(!d.length)return{clips:e,tracks:c};const{fps:v}=Y(p),R=()=>{if(l?.aborted)throw new DOMException("Export cancelled","AbortError")},D=new Set(d.map(t=>t.id)),O={...c};let x=Math.max(0,...e.map(t=>t.track),...Object.keys(c).map(Number))+1;const h=[];for(const t of e){if(!D.has(t.id)){h.push(t);continue}const a={...t,kind:"image",warped:!0};for(const i of lt)delete a[i];if(h.push(a),t.kind==="video"&&!t.speedRamp&&!t.freeze&&(t.volume??1)>0){const i={id:`${t.id}~sound`,kind:"audio",track:x},k=t;for(const m of ct)k[m]!==void 0&&(i[m]=k[m]);c[t.track]&&(O[x]={...c[t.track]}),x++,h.push(i)}}const N=new Map(Z(e).filter(t=>t._virtual).map(t=>[t.id,t])),_=[];for(const t of d)_.push({clip:t,as:t});for(const t of tt(h))D.has(String(t._virtual))&&_.push({clip:N.get(t.id)??{...e.find(a=>a.id===t._virtual),...t,_still:!0},as:t});const w=d.some(t=>t.mask||t.person)?await et(()=>import("./rotoMatte-C-2o3vv0.js").then(t=>t.r),__vite__mapDeps([0,1,2,3])):null;w&&await w.prepareMattes(d.filter(t=>t.mask||t.person));const W=w?document.createElement("canvas"):null,T=at(),I=[],S=new Map,U=async t=>{const a=new rt({source:new it(t),formats:nt});I.push(a);const i=await a.getPrimaryVideoTrack();return i?new st(i):null},C=async t=>{let a=S.get(t);return a||(a=await createImageBitmap(await(await fetch(t,{signal:l})).blob(),{imageOrientation:"from-image",premultiplyAlpha:"none",colorSpaceConversion:"none"}),S.set(t,a)),a};try{for(const{clip:t,as:a}of _){R();const i=e.find(o=>o.id===(t._virtual??t.id)),k=Math.ceil(a.duration*v),m=i.distort,Q=!!(t._still||t.freeze),$=o=>{const r=o/v,u=t.playbackRate||1;return t.reverse?Math.max(0,(t.inPoint||0)+Math.max(0,t.duration-r-1/v)*u):ot(t,r,!1,Q).source};let g=null,b=null;if(t.kind==="video"){const o=await U(t.url);o&&(g=o.samplesAtTimestamps(Array.from({length:k},(r,u)=>$(u))))}else b=await C(t.url);const s=m.displace?e.find(o=>o.id===m.displace.map):void 0,V=s?.kind==="video"?await U(s.url):null,L=s?.kind==="image"&&s.url&&!A(s)?await C(s.url):null,q=async o=>{if(!s||o<s.start||o>=s.start+s.duration)return null;if(L)return{source:L};if(!V)return null;const r=await V.getSample((s.inPoint||0)+(o-s.start)*(s.playbackRate||1));if(!r)return null;const u=r.toVideoFrame();return r.close(),{source:u,close:()=>u.close()}},G=mt(i,e);for(let o=0;o<k;o++){R();const r=g?(await g.next()).value??null:null;if(G&&o>0){r?.close(),await n.push("titleFrames",a.id,"=");continue}const u=r?r.toVideoFrame():null,H=u??b,y=r?r.displayWidth:b?.width??0,M=r?r.displayHeight:b?.height??0;if(!H||!y||!M){if(u?.close(),r?.close(),o===0)throw Error(`No picture for ${i.label||i.id}`);await n.push("titleFrames",a.id,"=");continue}const f=t.crop||{left:0,right:0,top:0,bottom:0},K=Math.floor(y*f.left/2)*2,X=Math.floor(M*f.top/2)*2,E=Math.max(2,Math.floor(y*(1-f.left-f.right)/2)*2),F=Math.max(2,Math.floor(M*(1-f.top-f.bottom)/2)*2),z=Math.min(1,dt/Math.max(E,F)),P=o/v,B=await q(t.start+P),j=T.render({source:H,srcW:y,srcH:M,rect:[K,X,E,F],outW:Math.max(2,Math.round(E*z)),outH:Math.max(2,Math.round(F*z)),distort:m,local:t.start+P-i.start,map:B?.source??null,matte:w&&(t.mask||t.person)?w.matteCanvas(t,P,W,!1,e):null});B?.close?.(),u?.close(),r?.close(),await n.push("titleFrames",a.id,await ut(j))}g&&await g.return(void 0)}}finally{T.dispose();for(const t of S.values())t.close();for(const t of I)t.dispose?.()}return{clips:h,tracks:O}}export{wt as distortForServer};
@@ -1,4 +1,4 @@
1
- import{lT as H,c4 as K,lU as $}from"./titleFrameBudget-BYRZAQPs.js";const z=`#version 300 es
1
+ import{lT as H,c4 as K,lU as $}from"./titleFrameBudget-CLZWaFHO.js";const z=`#version 300 es
2
2
  in vec4 a;uniform vec4 crop;out vec2 uv;out vec2 tc;
3
3
  void main(){tc=a.zw;uv=crop.xy+a.zw*crop.zw;gl_Position=vec4(a.x*2.-1.,a.y*2.-1.,0,1);}`,j=`#version 300 es
4
4
  precision highp float;in vec2 uv;in vec2 tc;uniform sampler2D src;uniform sampler2D matte;uniform float useMatte;out vec4 o;
@@ -1 +1 @@
1
- import{gM as gt,iY as tt,fq as te,g2 as Jt,iZ as Wt,dH as bt,g7 as kt,g8 as _t,i_ as zt,g4 as Ct,gg as ee,i$ as oe,j0 as Tt,gc as Ft,gf as wt,gk as ne,gd as Ut,gi as ae,gb as ie,j1 as re}from"./remote-Dva2qg58.js";import"./api-DUp403BK.js";import"./titleFrameBudget-BYRZAQPs.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-75tQUvPT.js";import"./rotoMaskStore-BxyxB2bD.js";import"./textAnimators-nVSz_sZo.js";import"./timelineComp-BcewYGR2.js";import"./rigTrack-UYZU4P-e.js";const Bt=t=>Math.round(t*100)/100,pt=(t,a)=>({id:t.id,label:t.label??"",scope:t.scope,start_s:t.start,end_s:t.scope==="after"?null:t.end,fade_s:t.fade,...t.fadeOut!=null?{fade_out_s:t.fadeOut}:{},...t.track?{track:{from_s:t.track.t[0],to_s:t.track.t[t.track.t.length-1],samples:t.track.t.length,joints:Object.keys(t.track.pose||{}),...t.track.turn?{turn_deg_max:Math.round(Math.max(...t.track.turn.map(Math.abs)))}:{}}}:{},...t.off?{off:!0}:{},weight_now:Bt(kt(t,a)),...t.pose?{joints:t.pose}:{},...t.stance?{stance:t.stance}:{},...t.preset?{preset:t.preset}:{},...t.move?{move_m:[t.move[0],t.move[2]]}:{},...t.turn?{turn_deg:t.turn}:{}});function Kt(t,a){const f=a.getStage(),c=gt(f),r=c.duration;let o;try{o=tt(f,String(t.name??""))}catch(h){return{ok:!1,error:h.message}}if(!te(o))return{ok:!1,error:`'${o.name}' is not a person (or a humanoid-rigged model)`};const s=c.motionEdits?.[o.id]||[],e=Math.max(0,Math.min(r,Number(t.at??0)||0)),g=h=>a.setStage(N=>({...N,shots:N.shots.map(y=>y.id===c.id?{...y,motionEdits:{...y.motionEdits,[o.id]:h}}:y)}));if(t.remove!=null){const h=String(t.remove),N=h==="all"?[]:s.filter(y=>y.id!==h);return N.length===s.length&&h!=="all"?{ok:!1,error:`no edit '${h}' on ${o.name}; edits: ${s.map(y=>y.id).join(", ")||"none"}`}:(g(N),{ok:!0,name:o.name,removed:h==="all"?s.length:1,edits:N.map(y=>pt(y,e))})}const p=t.id!=null?s.find(h=>h.id===String(t.id)):void 0;if(t.id!=null&&!p)return{ok:!1,error:`no edit '${String(t.id)}' on ${o.name}`};const n=["moment","span","after"].includes(String(t.scope))?String(t.scope):p?.scope??"moment",d=(c.clipSpans?.[o.id]||[]).find(h=>e>=h.start-.001&&e<=h.end+.001);let u=p?.start??e,i=p?.end??e;if((t.at!=null||!p)&&(u=e,i=e),n==="span"){if(t.start!=null||t.end!=null)u=Number(t.start??u),i=Number(t.end??i);else if(d)u=d.start,i=d.end;else if(!p)return{ok:!1,error:`no motion block at ${e} s on ${o.name}: give start and end for scope span`}}const m=Number(t.fade??p?.fade??Jt.default),k=t.fade_out!=null?Number(t.fade_out):p?.fadeOut;if(t.face_toward!=null){let h;try{h=tt(f,String(t.face_toward))}catch(O){return{ok:!1,error:O.message}}if(h.id===o.id)return{ok:!1,error:"face_toward another object"};const N=Math.max(0,Math.min(1,Number(t.face_strength??1))),y={scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{}},W=Math.max(0,u-m),ot=n==="after"?r:Math.min(r,i+(k??m)),ct=Math.min(Wt.samples,Math.max(2,Math.ceil((ot-W)*24)+1)),Mt=s.filter(O=>O.id!==p?.id),H={...c,motionEdits:{...c.motionEdits,[o.id]:Mt}},B=[],nt=[];for(let O=0;O<ct;O++){const J=W+(ot-W)*O/(ct-1),G=J/Math.max(1e-6,r),at=bt(o,H,G,f.items),T=bt(h,H,G,f.items),L=((Math.atan2(T.position[0]-at.position[0],T.position[2]-at.position[2])*180/Math.PI-(at.rotation[1]||0))%360+540)%360-180;B.push(Math.round(J*1e3)/1e3),nt.push(kt(y,J)*N*L)}const q={id:p?.id??crypto.randomUUID(),scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{},track:{t:B,turn:nt},label:String(t.label??`${o.name} faces ${h.name}`)},C=_t(s,q,r),Z=C.find(O=>O.id===q.id);return Z?(g(C),{ok:!0,name:o.name,edit:pt(Z,e),edits:C.length,...d?{motion_block:{label:d.label,start_s:d.start,end_s:d.end}}:{},note:"the heading follows the target frame by frame (keys untouched); inspect_pose to check, then move_joint for contact"}):{ok:!1,error:`${o.name} already faces ${h.name} there`}}const b={};for(const[h,N]of Object.entries(t.joints||{})){if(!(h in zt)&&!/^(grip|index|thumb)[LR]$|^(headPitch|headRoll)$/.test(h))return{ok:!1,error:`unknown joint '${h}'; joints: ${Object.keys(zt).join(", ")}`};Number.isFinite(Number(N))&&(b[h]=Number(N))}const P=t.preset!=null?t.preset==="none"?null:{id:String(t.preset),amount:Number(t.preset_amount??.7),...t.preset_arms?{arms:!0}:{}}:p?.preset;if(P&&!Ct.some(h=>h.id===P.id))return{ok:!1,error:`unknown preset; use one of ${Ct.map(h=>h.id).join(", ")}`};const $=Array.isArray(t.move_m)?[Number(t.move_m[0])||0,0,Number(t.move_m[1])||0]:p?.move,j={...p||{},id:p?.id??crypto.randomUUID(),scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{},...Object.keys(b).length?{pose:{...t.id!=null?p?.pose:{},...b}}:{},...t.stance?{stance:{...p?.stance||{},...t.stance}}:{},preset:P??void 0,move:$,...t.turn_deg!=null?{turn:Number(t.turn_deg)}:{},...typeof t.off=="boolean"?{off:t.off}:{},label:String(t.label??p?.label??"Agent")},E=_t(s,j,r),R=E.find(h=>h.id===j.id);return R?(g(E),{ok:!0,name:o.name,edit:pt(R,e),edits:E.length,...d?{motion_block:{label:d.label,start_s:d.start,end_s:d.end}}:{},note:"a correction on top of the motion (keys untouched); render_preview / check_shot to see it; edit_motion with id to refine, remove to drop it"}):{ok:!1,error:"the edit changes nothing: give joints, stance, preset, move_m or turn_deg"}}const S=t=>Math.round(t*1e3)/1e3;function qt(t,a){return(t.clipSpans?.[a]||[]).flatMap(f=>{const c=re(f.clip),r=c?.strike;return!r||!c?.duration?[]:[{at:S(f.start+r.t*(f.end-f.start)/c.duration),limb:r.limb,zone:r.zone,cls:r.cls,clip:f.clip}]})}function Ht(t,a){if(t.some(e=>!e)||t.length<4)return null;const f=t,c=(e,g)=>e.map((p,n)=>(p-g[n])/a),r=f.slice(1).map((e,g)=>c(e,f[g])),o=r.slice(1).map((e,g)=>c(e,r[g])),s=o.slice(1).map((e,g)=>c(e,o[g]));return{speed:Bt(Math.max(...r.map(e=>Math.hypot(...e)))),jerk:Math.round(Math.max(0,...s.map(e=>Math.hypot(...e))))}}const et={surface:t=>({head:.1,chest:.13,hips:.14})[t]??.05,tip:t=>t.startsWith("hand")?.08:t.startsWith("foot")?.06:0};function Yt(t,a,f,c){const r=[a[0]-c[0],a[2]-c[2]];return{forward:S(r[0]*t.facing[0]+r[1]*t.facing[2]),up:S(a[1]-f),side:S(r[0]*t.side[0]+r[1]*t.side[2])}}function se(t){const a=t.joints,f=[];if(!a.footL||!a.footR||!a.hips||!a.chest||!a.head)return{facts:f,ground:0,base:[0,0,0]};const c=.045*t.height,r=Math.min(t.ground,Math.min(a.footL[1],a.footR[1])-c),o=[a.hips[0],r,a.hips[2]],s=t.height,e=m=>m>a.head[1]+.08*s?"above the head":m>a.head[1]-.08*s?"at head height":m>a.chest[1]-.07*s?"at chest height":m>a.hips[1]-.05*s?"at waist height":m>r+.3*s?"at thigh height":"low, near the knees / floor";for(const m of["R","L"]){const k=a[`hand${m}`];if(!k)continue;const b=Yt(t,k,r,o);f.push(`hand${m} ${e(k[1])}, ${b.forward>.15?`${S(b.forward)} m in front`:b.forward<-.15?`${S(-b.forward)} m behind`:"beside the body"}`)}const g=[a.chest[0]-a.hips[0],a.chest[1]-a.hips[1],a.chest[2]-a.hips[2]],p=g[0]*t.facing[0]+g[2]*t.facing[2],n=Math.round(Math.atan2(p,g[1])*180/Math.PI);f.push(Math.abs(n)<8?"torso upright":`torso leans ${n>0?"forward":"back"} ${Math.abs(n)}°`),f.push(`feet ${S(Math.hypot(a.footL[0]-a.footR[0],a.footL[2]-a.footR[2]))} m apart`);const d=Math.min(a.footL[1],a.footR[1])-c-t.ground;d>.08?f.push(`airborne: feet ${S(d)} m off the ground`):Math.abs(a.footL[1]-a.footR[1])>.12&&f.push(`one foot raised ${S(Math.abs(a.footL[1]-a.footR[1]))} m (${a.footL[1]>a.footR[1]?"footL":"footR"})`),f.push(`hips ${S(a.hips[1]-r)} m above the feet (standing ≈ ${S(.5*s)})`);const u=(m,k)=>{const b=m[0]*t.facing[0]+m[2]*t.facing[2],P=m[1],$=(m[0]*t.side[0]+m[2]*t.side[2])*(k==="L"?-1:1),j=[[b,"forward"],[-b,"back"],[P,"up"],[-P,"down"],[$,k?"out":"to its R side"],[-$,k?"in":"to its L side"]];return j.sort((E,R)=>R[0]-E[0]),j[1][0]>.45?`${j[0][1]}-${j[1][1]}`:j[0][1]};for(const m of["R","L"]){const k=t.axes[`hand${m}`],b=t.fingers[m];if(!k)continue;const P=Object.entries(wt).map(([$,j])=>[$,Math.abs(j.grip-b.grip)+Math.abs(j.index-b.index)+.5*Math.abs(j.thumb-b.thumb)]).sort(($,j)=>$[1]-j[1])[0][0];f.push(`hand${m} ${P}: fingers point ${u(k.main,m)}, palm faces ${u(k.second,m)}`)}for(const m of["R","L"]){const k=t.axes[`foot${m}`];k&&f.push(`foot${m} toes point ${u(k.main,m)}`)}const i=t.axes.head;if(i){const m=Math.round(Math.asin(Math.max(-1,Math.min(1,i.second[0]*t.side[0]+i.second[2]*t.side[2])))*180/Math.PI);f.push(`face looks ${u(i.main)}${Math.abs(m)>8?`, head tilted ${Math.abs(m)}° toward its ${m>0?"R":"L"} shoulder`:""}`)}return{facts:f,ground:r,base:o}}function ge(t,a){const f=a.getStage(),c=gt(f),r=a.engine();let o;try{o=tt(f,String(t.name??""))}catch(n){return{ok:!1,error:n.message}}if(o.kind!=="person")return{ok:!1,error:`'${o.name}' is not a person`};if(!r)return{ok:!1,error:"the 3D view is not ready"};r.sync(f,null);const s=(Array.isArray(t.times)?t.times:[t.at??0]).slice(0,6).map(n=>Math.max(0,Math.min(c.duration,Number(n)||0))),e=f.items.filter(n=>n.kind==="person"&&n.id!==o.id),g=s.map(n=>{const d=r.jointsAt(n,o.id);if(!d)return{at_s:n,error:"not built"};const{facts:u,ground:i,base:m}=se(d),k=Object.fromEntries(Object.entries(d.joints).map(([$,j])=>[$,Yt(d,j,i,m)])),b=[];for(const $ of e){const j=r.jointsAt(n,$.id);if(j)for(const E of["handR","handL","footR","footL"])for(const R of["head","chest","hips"]){const h=d.joints[E],N=R==="head"?j.headCentre:j.joints[R];if(!h||!N)continue;const y=Math.hypot(h[0]-N[0],h[1]-N[1],h[2]-N[2])-et.tip(E)-et.surface(R)*j.height/1.8;y<.45&&b.push({joint:E,other:$.name,part:R,gap_m:S(Math.max(0,y))})}}b.sort(($,j)=>$.gap_m-j.gap_m);const P=Object.fromEntries(ee.map($=>[$.id,d.joints[$.part]]).filter(([,$])=>!!$));return{at_s:n,facing:d.facing,controls:P,joints_world:d.joints,head_centre:d.headCentre,joints_local:k,axes:d.axes,fingers:d.fingers,reads:u,...b.length?{near_others:b.slice(0,6)}:{}}}),p=qt(c,o.id);return{ok:!0,name:o.name,...p.length?{strikes:p}:{},frames:g,note:"joints_world = world metres (move_joint to); joints_local = metres in the person's frame: forward, up above its feet, side (+ toward its …R limbs). head = a point in front of the face (head_centre = the skull, for contact). near_others gap_m = the gap between the surfaces (0 = touching). axes: hand {main = fingers, second = palm}, foot {main = toes}, head {main = face, second = top of the head}, world unit vectors; fingers = curls 0..100. Check again after a fix."}}function de(t,a){const f=a.getStage(),c=gt(f),r=a.engine();let o;try{o=tt(f,String(t.name??""))}catch(l){return{ok:!1,error:l.message}}if(o.kind!=="person")return{ok:!1,error:`'${o.name}' is not a person`};const s=t.control!=null?oe(t.control):null;if(t.control!=null&&!s)return{ok:!1,error:`control must be one of ${Tt.join(", ")}`};const e=s?.part??String(t.part??"");if(!Ft.includes(e))return{ok:!1,error:`give control (${Tt.join(", ")}) or part (${Ft.join(", ")})`};if(!r)return{ok:!1,error:"the 3D view is not ready"};r.sync(f,null);const g=qt(c,o.id),p=t.at==="impact"?g.find(l=>l.limb===e)??g[0]:null;if(t.at==="impact"&&!p)return{ok:!1,error:`${o.name} plays no strike clip here: give at in seconds`};const n=p?p.at:Math.max(0,Math.min(c.duration,Number(t.at??0)||0)),d=r.jointsAt(n,o.id),u=d?.joints[e];if(!d||!u)return{ok:!1,error:`no ${e} on ${o.name}`};let i=null;if(Array.isArray(t.to)&&t.to.length===3)i=t.to.map(Number);else if(t.offset_m&&typeof t.offset_m=="object"){const l=t.offset_m,_=Number(l.forward)||0,M=Number(l.up)||0,v=Number(l.side)||0;i=[u[0]+_*d.facing[0]+v*d.side[0],u[1]+M,u[2]+_*d.facing[2]+v*d.side[2]]}else if(t.to_object&&typeof t.to_object=="object"){const l=t.to_object;let _;try{_=tt(f,String(l.name??""))}catch(z){return{ok:!1,error:z.message}}const M=String(l.part??"chest"),v=_.kind==="person"?r.jointsAt(n,_.id):null;if(i=v?(M==="head"?v.headCentre:v.joints[M])??null:r.worldPositionOf(_.id),!i)return{ok:!1,error:`no ${M} on ${_.name}`};const I=v?et.surface(M)*v.height/1.8:0,A=I+et.tip(e);if(A>0){const z=d.joints.chest??u,w=[z[0]-i[0],z[1]-i[1],z[2]-i[2]],x=Math.hypot(...w);x>.001&&(i=[i[0]+w[0]/x*A,i[1]+w[1]/x*A,i[2]+w[2]/x*A])}}if(i&&i.some(l=>!Number.isFinite(l)))return{ok:!1,error:"to must be 3 finite numbers"};const m=e.slice(-1),k=e==="handL"||e==="handR",b=e==="footL"||e==="footR",P=(l,_)=>{if(l==null)return null;if(Array.isArray(l)&&l.length===3&&l.every(A=>Number.isFinite(Number(A))))return l.map(Number);const M=String(l),v=m==="L"?-1:1,I={forward:d.facing,back:[-d.facing[0],0,-d.facing[2]],up:[0,1,0],down:[0,-1,0],out:[d.side[0]*v,0,d.side[2]*v],in:[-d.side[0]*v,0,-d.side[2]*v]};if(M==="target"){if(!i)return`${_} 'target' needs to / to_object`;const A=[i[0]-u[0],i[1]-u[1],i[2]-u[2]];return Math.hypot(...A)>.001?A:null}return I[M]??`${_} must be forward / back / up / down / in / out / target or [x, y, z]`},$=P(k?t.fingers:b?t.toes:e==="head"?t.face:void 0,k?"fingers":b?"toes":"face"),j=P(k?t.palm:void 0,"palm");for(const l of[$,j])if(typeof l=="string")return{ok:!1,error:l};if(!k&&!b&&e!=="head"&&(t.fingers||t.palm||t.toes||t.face))return{ok:!1,error:"fingers / palm are for a hand, toes for a foot, face for the head"};const E=t.hand_shape!=null?String(t.hand_shape):null;if(E&&(!k||!(E in wt)))return{ok:!1,error:`hand_shape is for a hand: ${Object.keys(wt).join(", ")}`};const R=$||j?{...$?{main:$}:{},...j?{second:j}:{}}:void 0,h=(e==="footL"||e==="footR")&&Number.isFinite(Number(t.roll_deg))&&Number(t.roll_deg)!==0?Math.max(-45,Math.min(70,Number(t.roll_deg))):0;if(!i&&!R&&!E&&!h)return{ok:!1,error:"give a target (to [x, y, z], offset_m {forward, up, side}, to_object {name, part}), a direction (fingers / palm, toes, face) or hand_shape"};const N=["moment","span","after"].includes(String(t.scope))?String(t.scope):e==="hips"?"after":"moment",y=c.duration,W=!!(c.objectKeys?.[o.id]?.length||c.clipSpans?.[o.id]?.length),ot=!!i&&W&&N==="moment"&&t.path!==!1&&(k||b),ct=Number(t.fade??.6),Mt=Number(t.fade_out??.5),H=Math.max(0,n-ct-.25),B=Math.min(y,n+Mt+.25),nt=Math.max(4,Math.round((B-H)*24)+1),q=Array.from({length:nt},(l,_)=>H+(B-H)*_/(nt-1)),C=Ht(r.jointPath(o.id,e,q),(B-H)/(q.length-1));let Z=null,O=u,J=0;if(ot&&t.align!==!1){const l=(c.clipSpans?.[o.id]||[]).find(x=>n>=x.start-.001&&n<=x.end+.001),_=l?l.start:Math.max(0,n-.7),M=Math.max(_+.05,Math.min(n,_+Number(t.warp_s??.6))),v=["footL","footR"].filter(x=>x!==e),I=[_,(_+M)/2,M,n],A=x=>{const U=r.jointPath(o.id,x,I);return U.every(Boolean)?U.slice(1).reduce((st,V,dt)=>st+Math.hypot(V[0]-U[dt][0],V[2]-U[dt][2]),0):1/0},z=v.sort((x,U)=>A(x)-A(U))[0],w=r.jointPath(o.id,z,[n])[0];if(w){const x=u[0]-w[0],U=u[2]-w[2],st=i[0]-w[0],V=i[2]-w[2],dt=Math.hypot(x,U),mt=Math.hypot(st,V);if(dt>.12&&mt>.12){const lt=Math.max(-120,Math.min(120,((Math.atan2(st,V)-Math.atan2(x,U))*180/Math.PI+540)%360-180)),$t=mt-dt,xt=Number(t.step_max_m??.05),X=Math.max(-xt,Math.min(xt,$t)),Zt=st/mt,Gt=V/mt;if(Math.abs($t-X)>.12&&(J=S($t-X)),Math.abs(lt)>2||Math.abs(X)>.02){const Nt={scope:"after",start:M,end:M,fade:Math.max(Jt.min,M-_)},Qt=Math.max(1/24,(y-_)/(Wt.samples-2)),Ot=[],Et=[],Lt=[],At=[],Vt={...c,motionEdits:{...c.motionEdits,[o.id]:c.motionEdits?.[o.id]||[]}};for(let D=_;D<=y+1e-6;D+=Qt){const K=kt(Nt,D),ht=K*lt*Math.PI/180,ut=bt(o,Vt,y?D/y:0,f.items).position,It=ut[0]-w[0],Dt=ut[2]-w[2];Ot.push(Math.round(D*1e3)/1e3),Et.push(K*lt),Lt.push(w[0]+It*Math.cos(ht)+Dt*Math.sin(ht)-ut[0]+K*X*Zt),At.push(w[2]-It*Math.sin(ht)+Dt*Math.cos(ht)-ut[2]+K*X*Gt)}const Xt=a.getStage().shots.find(D=>D.id===c.id)?.motionEdits?.[o.id]||[],Rt={id:crypto.randomUUID(),scope:"after",start:M,end:M,fade:Nt.fade,track:{t:Ot,turn:Et,mx:Lt,mz:At},label:`${e}: align the strike`},Pt=_t(Xt,Rt,y);Pt.some(D=>D.id===Rt.id)&&(a.setStage(D=>({...D,shots:D.shots.map(K=>K.id===c.id?{...K,motionEdits:{...K.motionEdits,[o.id]:Pt}}:K)})),Z={turn_deg:Math.round(lt),step_m:S(X),pivot:z},r.sync(a.getStage(),null),O=r.jointsAt(n,o.id)?.joints[e]??u)}}}}let G=0;if(ot&&t.level!==!1&&i&&O[1]-i[1]>.04){const l=(d?.height??1.8)/1.8,_=Math.min(.45,(O[1]-i[1])/(.45*l)),M=Number(t.fade??.5);Kt({name:o.name,at:n,scope:"moment",fade:M,fade_out:Math.max(.35,M*.8),stance:{crouch:Math.round(_*100)/100},label:`${e}: drop the level`},a).ok&&(G=Math.round(_*100)/100,r.sync(a.getStage(),null),O=r.jointsAt(n,o.id)?.joints[e]??O)}const at=i?Math.hypot(i[0]-O[0],i[1]-O[1],i[2]-O[2]):0,T=Number(t.fade??Math.min(.7,.45+.4*at)),it=Number(t.fade_out??Math.max(.35,T*.8)),L=h&&!i?(()=>{const l=r.rollFootAt(n,o.id,e,h,_=>({id:"__drag",scope:"moment",start:n,end:n,fade:T,..._}));return l?{fields:l.fields,miss:l.pivotMove,from:u,aimError:null}:null})():i||R?r.solveJointAt(n,o.id,e,i,l=>({id:"__drag",scope:"moment",start:n,end:n,fade:T,...l}),R,{lockFeet:t.lock_feet===!0}):{fields:{},miss:0,from:u,aimError:null};if(!L)return{ok:!1,error:`could not pose ${o.name} at ${n} s`};const Y=L.fields,yt=E?ne(bt(o,c,c.duration?n/c.duration:0,f.items).pose,m,E)??{}:{},vt={...Y.pose||{},...yt},St=[i?`→ ${i.map(l=>S(l)).join(", ")}`:"",R?"turned":"",E??""].filter(Boolean).join(" "),jt=!!i&&W&&N==="moment"&&t.path!==!1&&!["hips","head"].includes(e);let rt;if(jt){const l=Object.fromEntries(Object.entries(Y.pose||{}).filter(([w])=>/^(wrist|ankle)/.test(w))),_={scope:"moment",start:n,end:n,fade:T,fadeOut:it},M=r.bakeJointPath(n,o.id,e,i,w=>kt(_,w),[n-T,n+it],{...l,...yt});if(!M)return{ok:!1,error:`could not pose ${o.name} along its path`};const v=a.getStage().shots.find(w=>w.id===c.id)?.motionEdits?.[o.id]||[],I={id:crypto.randomUUID(),scope:"moment",start:n,end:n,fade:T,fadeOut:it,track:M.track,label:String(t.label??`${e} ${St} (path)`)},A=_t(v,I,y),z=A.find(w=>w.id===I.id);if(!z)return{ok:!1,error:"the move changes nothing"};a.setStage(w=>({...w,shots:w.shots.map(x=>x.id===c.id?{...x,motionEdits:{...x.motionEdits,[o.id]:A}}:x)})),L.miss=M.miss,rt={ok:!0,name:o.name,edit:pt(z,n),edits:A.length,note:"carried along the motion's own path (keys untouched); edit_motion remove to drop it"}}else rt=Kt({name:o.name,at:n,scope:N,fade:T,fade_out:it,...t.start!=null?{start:t.start}:{},...t.end!=null?{end:t.end}:{},...Object.keys(vt).length?{joints:vt}:{},...Y.move?{move_m:[Y.move[0],Y.move[2]]}:{},...Y.stance?{stance:Y.stance}:{},label:String(t.label??`${e} ${St}`)},a);if(!rt.ok)return rt;r.sync(a.getStage(),null);const Q=Ht(r.jointPath(o.id,e,q),(B-H)/(q.length-1));let F="";if(i&&L.miss>.04){const l=d.joints.hips??u,_=i[0]-l[0],M=i[2]-l[2],v=Math.hypot(_,M),I=v>.05?Math.round(Math.atan2(_*d.facing[2]-M*d.facing[0],_*d.facing[0]+M*d.facing[2])*180/Math.PI):0;F=`${e} stays ${L.miss} m short (out of reach or at a joint limit)`+(Math.abs(I)>50?`: ${o.name} faces ${Math.abs(I)}° away from the target — turn first (${W?"edit_motion face_toward the target, scope span":`edit_motion turn_deg ${I}, scope span`}), then move_joint again`:`: the target is ${S(v)} m from the hips — step closer: edit_motion move_m [${S(_/v*(L.miss+.03))}, ${S(M/v*(L.miss+.03))}] (scope span), then move_joint again; or pick another time`)}J&&(F+=`${F?"; ":""}the fighters stand ${Math.abs(J)} m too ${J>0?"far apart":"close"} for this blow as the clip throws it: re-block their marks (stand_at / set_transform before the motion) rather than stretching the limb`),L.aimError!=null&&L.aimError>12&&(F+=`${F?"; ":""}${k?"the hand":b?"the foot":"the face"} points ${L.aimError}° off the asked direction (the wrist / ankle / neck limit) — turn the forearm (move_joint elbow) or the body first`);const ft=C&&Q?{peak_speed_m_s:[C.speed,Q.speed],peak_jerk:[C.jerk,Q.jerk],jerk_change_pct:Math.round((Q.jerk-C.jerk)/Math.max(1,C.jerk)*100)}:null;return ft&&Q.jerk>C.jerk*1.5&&Q.jerk>800&&(F+=`${F?"; ":""}the fix makes ${e} ${ft.jerk_change_pct}% jerkier — ${jt?"lengthen fade / fade_out":"try path mode (a moving person, scope moment) or lengthen fade / fade_out"}, face_toward first so less is corrected, or fix the motion itself`),{...rt,part:e,...Ut(e)?{control:Ut(e).id}:{},from:L.from,...i?{to:i.map(S),miss_m:L.miss}:{},...L.aimError!=null?{aim_error_deg:L.aimError}:{},...jt?{mode:"path"}:{},...Z?{aligned:Z}:{},...G?{lowered_crouch:G}:{},...ft?{smoothness:ft}:{},...F?{warning:F}:{}}}function Me(t,a){const f=t.engine();if(!f)return null;const c=a.filter(s=>(s.planned==="head"||s.planned==="body")&&s.limb&&/^(hand|foot)[LR]$/.test(s.limb)).sort((s,e)=>s.time-e.time),r=s=>{f.sync(t.getStage(),null);const e=t.getStage(),g=e.items.find(m=>m.name===s.attacker),p=e.items.find(m=>m.name===s.target),n=g&&f.jointsAt(s.time,g.id),d=p&&f.jointsAt(s.time,p.id),u=n?.joints[s.limb],i=s.planned==="head"?d?.headCentre:d?.joints.chest;return!u||!i||!d?null:S(Math.hypot(u[0]-i[0],u[1]-i[1],u[2]-i[2])-et.tip(s.limb)-et.surface(s.planned==="head"?"head":"chest")*d.height/1.8)},o=[];for(const s of c){const e=r(s);let g=e;for(let p=0;p<2&&g!=null&&Math.abs(g)>.015;p++){const n=a.filter(b=>b.attacker===s.attacker&&b!==s).map(b=>b.time),d=Math.max(-1/0,...n.filter(b=>b<s.time)),u=Math.min(1/0,...n.filter(b=>b>s.time)),i=Math.max(.15,Math.min(.45,.8*(s.time-d))),m=Math.max(.15,Math.min(.4,.8*(u-s.time)));if(!de({name:s.attacker,part:s.limb,at:s.time,to_object:{name:s.target,part:s.planned==="head"?"head":"chest"},align:!1,level:!1,fade:i,fade_out:m,label:"land the blow"},t).ok)break;g=r(s)}o.push({time_s:S(s.time),attacker:s.attacker,limb:s.limb,zone:s.planned,gap_before_m:e,gap_after_m:g})}return o}function je(t,a){const f=a.getStage(),c=gt(f);let r;try{r=tt(f,String(t.name??""))}catch(n){return{ok:!1,error:n.message}}if(r.kind!=="person")return{ok:!1,error:`'${r.name}' is not a person`};const o=Math.max(0,Math.min(c.duration,Number(t.at)||0)),s=c.duration?o/c.duration:0,e=t.breakdown_bias==null?null:Math.max(0,Math.min(1,Number(t.breakdown_bias))),g=e==null?ae(c,r,s):ie(c,r,s,e);if(!g)return{ok:!1,error:`no pose keys on both sides of ${o} s for a breakdown — set keys first (pose_key / set_pose)`};a.setStage(n=>({...n,shots:n.shots.map(d=>d.id===c.id?g:d)}));const p=g.objectKeys?.[r.id]||[];return{ok:!0,name:r.name,at_s:o,kind:e==null?"key":"breakdown",...e!=null?{bias:e}:{},keys_s:p.filter(n=>n.pose).map(n=>S(n.time*c.duration)).slice(0,40)}}export{Kt as editMotion,ge as inspectPose,Me as landBlows,de as moveJoint,je as poseKey,qt as strikesOf};
1
+ import{gM as gt,iY as tt,fq as te,g2 as Jt,iZ as Wt,dH as bt,g7 as kt,g8 as _t,i_ as zt,g4 as Ct,gg as ee,i$ as oe,j0 as Tt,gc as Ft,gf as wt,gk as ne,gd as Ut,gi as ae,gb as ie,j1 as re}from"./remote-C7J0Tqhb.js";import"./api-CJ8PdbfZ.js";import"./titleFrameBudget-CLZWaFHO.js";import"./three.module-Bx43vjkH.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-DW4E9xnW.js";import"./rotoMaskStore-DPziPKAN.js";import"./textAnimators-DUZjhVGO.js";import"./timelineComp-B4GtoH2f.js";import"./rigTrack-urT3nDK0.js";const Bt=t=>Math.round(t*100)/100,pt=(t,a)=>({id:t.id,label:t.label??"",scope:t.scope,start_s:t.start,end_s:t.scope==="after"?null:t.end,fade_s:t.fade,...t.fadeOut!=null?{fade_out_s:t.fadeOut}:{},...t.track?{track:{from_s:t.track.t[0],to_s:t.track.t[t.track.t.length-1],samples:t.track.t.length,joints:Object.keys(t.track.pose||{}),...t.track.turn?{turn_deg_max:Math.round(Math.max(...t.track.turn.map(Math.abs)))}:{}}}:{},...t.off?{off:!0}:{},weight_now:Bt(kt(t,a)),...t.pose?{joints:t.pose}:{},...t.stance?{stance:t.stance}:{},...t.preset?{preset:t.preset}:{},...t.move?{move_m:[t.move[0],t.move[2]]}:{},...t.turn?{turn_deg:t.turn}:{}});function Kt(t,a){const f=a.getStage(),c=gt(f),r=c.duration;let o;try{o=tt(f,String(t.name??""))}catch(h){return{ok:!1,error:h.message}}if(!te(o))return{ok:!1,error:`'${o.name}' is not a person (or a humanoid-rigged model)`};const s=c.motionEdits?.[o.id]||[],e=Math.max(0,Math.min(r,Number(t.at??0)||0)),g=h=>a.setStage(N=>({...N,shots:N.shots.map(y=>y.id===c.id?{...y,motionEdits:{...y.motionEdits,[o.id]:h}}:y)}));if(t.remove!=null){const h=String(t.remove),N=h==="all"?[]:s.filter(y=>y.id!==h);return N.length===s.length&&h!=="all"?{ok:!1,error:`no edit '${h}' on ${o.name}; edits: ${s.map(y=>y.id).join(", ")||"none"}`}:(g(N),{ok:!0,name:o.name,removed:h==="all"?s.length:1,edits:N.map(y=>pt(y,e))})}const p=t.id!=null?s.find(h=>h.id===String(t.id)):void 0;if(t.id!=null&&!p)return{ok:!1,error:`no edit '${String(t.id)}' on ${o.name}`};const n=["moment","span","after"].includes(String(t.scope))?String(t.scope):p?.scope??"moment",d=(c.clipSpans?.[o.id]||[]).find(h=>e>=h.start-.001&&e<=h.end+.001);let u=p?.start??e,i=p?.end??e;if((t.at!=null||!p)&&(u=e,i=e),n==="span"){if(t.start!=null||t.end!=null)u=Number(t.start??u),i=Number(t.end??i);else if(d)u=d.start,i=d.end;else if(!p)return{ok:!1,error:`no motion block at ${e} s on ${o.name}: give start and end for scope span`}}const m=Number(t.fade??p?.fade??Jt.default),k=t.fade_out!=null?Number(t.fade_out):p?.fadeOut;if(t.face_toward!=null){let h;try{h=tt(f,String(t.face_toward))}catch(O){return{ok:!1,error:O.message}}if(h.id===o.id)return{ok:!1,error:"face_toward another object"};const N=Math.max(0,Math.min(1,Number(t.face_strength??1))),y={scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{}},W=Math.max(0,u-m),ot=n==="after"?r:Math.min(r,i+(k??m)),ct=Math.min(Wt.samples,Math.max(2,Math.ceil((ot-W)*24)+1)),Mt=s.filter(O=>O.id!==p?.id),H={...c,motionEdits:{...c.motionEdits,[o.id]:Mt}},B=[],nt=[];for(let O=0;O<ct;O++){const J=W+(ot-W)*O/(ct-1),G=J/Math.max(1e-6,r),at=bt(o,H,G,f.items),T=bt(h,H,G,f.items),L=((Math.atan2(T.position[0]-at.position[0],T.position[2]-at.position[2])*180/Math.PI-(at.rotation[1]||0))%360+540)%360-180;B.push(Math.round(J*1e3)/1e3),nt.push(kt(y,J)*N*L)}const q={id:p?.id??crypto.randomUUID(),scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{},track:{t:B,turn:nt},label:String(t.label??`${o.name} faces ${h.name}`)},C=_t(s,q,r),Z=C.find(O=>O.id===q.id);return Z?(g(C),{ok:!0,name:o.name,edit:pt(Z,e),edits:C.length,...d?{motion_block:{label:d.label,start_s:d.start,end_s:d.end}}:{},note:"the heading follows the target frame by frame (keys untouched); inspect_pose to check, then move_joint for contact"}):{ok:!1,error:`${o.name} already faces ${h.name} there`}}const b={};for(const[h,N]of Object.entries(t.joints||{})){if(!(h in zt)&&!/^(grip|index|thumb)[LR]$|^(headPitch|headRoll)$/.test(h))return{ok:!1,error:`unknown joint '${h}'; joints: ${Object.keys(zt).join(", ")}`};Number.isFinite(Number(N))&&(b[h]=Number(N))}const P=t.preset!=null?t.preset==="none"?null:{id:String(t.preset),amount:Number(t.preset_amount??.7),...t.preset_arms?{arms:!0}:{}}:p?.preset;if(P&&!Ct.some(h=>h.id===P.id))return{ok:!1,error:`unknown preset; use one of ${Ct.map(h=>h.id).join(", ")}`};const $=Array.isArray(t.move_m)?[Number(t.move_m[0])||0,0,Number(t.move_m[1])||0]:p?.move,j={...p||{},id:p?.id??crypto.randomUUID(),scope:n,start:u,end:i,fade:m,...k!=null?{fadeOut:k}:{},...Object.keys(b).length?{pose:{...t.id!=null?p?.pose:{},...b}}:{},...t.stance?{stance:{...p?.stance||{},...t.stance}}:{},preset:P??void 0,move:$,...t.turn_deg!=null?{turn:Number(t.turn_deg)}:{},...typeof t.off=="boolean"?{off:t.off}:{},label:String(t.label??p?.label??"Agent")},E=_t(s,j,r),R=E.find(h=>h.id===j.id);return R?(g(E),{ok:!0,name:o.name,edit:pt(R,e),edits:E.length,...d?{motion_block:{label:d.label,start_s:d.start,end_s:d.end}}:{},note:"a correction on top of the motion (keys untouched); render_preview / check_shot to see it; edit_motion with id to refine, remove to drop it"}):{ok:!1,error:"the edit changes nothing: give joints, stance, preset, move_m or turn_deg"}}const S=t=>Math.round(t*1e3)/1e3;function qt(t,a){return(t.clipSpans?.[a]||[]).flatMap(f=>{const c=re(f.clip),r=c?.strike;return!r||!c?.duration?[]:[{at:S(f.start+r.t*(f.end-f.start)/c.duration),limb:r.limb,zone:r.zone,cls:r.cls,clip:f.clip}]})}function Ht(t,a){if(t.some(e=>!e)||t.length<4)return null;const f=t,c=(e,g)=>e.map((p,n)=>(p-g[n])/a),r=f.slice(1).map((e,g)=>c(e,f[g])),o=r.slice(1).map((e,g)=>c(e,r[g])),s=o.slice(1).map((e,g)=>c(e,o[g]));return{speed:Bt(Math.max(...r.map(e=>Math.hypot(...e)))),jerk:Math.round(Math.max(0,...s.map(e=>Math.hypot(...e))))}}const et={surface:t=>({head:.1,chest:.13,hips:.14})[t]??.05,tip:t=>t.startsWith("hand")?.08:t.startsWith("foot")?.06:0};function Yt(t,a,f,c){const r=[a[0]-c[0],a[2]-c[2]];return{forward:S(r[0]*t.facing[0]+r[1]*t.facing[2]),up:S(a[1]-f),side:S(r[0]*t.side[0]+r[1]*t.side[2])}}function se(t){const a=t.joints,f=[];if(!a.footL||!a.footR||!a.hips||!a.chest||!a.head)return{facts:f,ground:0,base:[0,0,0]};const c=.045*t.height,r=Math.min(t.ground,Math.min(a.footL[1],a.footR[1])-c),o=[a.hips[0],r,a.hips[2]],s=t.height,e=m=>m>a.head[1]+.08*s?"above the head":m>a.head[1]-.08*s?"at head height":m>a.chest[1]-.07*s?"at chest height":m>a.hips[1]-.05*s?"at waist height":m>r+.3*s?"at thigh height":"low, near the knees / floor";for(const m of["R","L"]){const k=a[`hand${m}`];if(!k)continue;const b=Yt(t,k,r,o);f.push(`hand${m} ${e(k[1])}, ${b.forward>.15?`${S(b.forward)} m in front`:b.forward<-.15?`${S(-b.forward)} m behind`:"beside the body"}`)}const g=[a.chest[0]-a.hips[0],a.chest[1]-a.hips[1],a.chest[2]-a.hips[2]],p=g[0]*t.facing[0]+g[2]*t.facing[2],n=Math.round(Math.atan2(p,g[1])*180/Math.PI);f.push(Math.abs(n)<8?"torso upright":`torso leans ${n>0?"forward":"back"} ${Math.abs(n)}°`),f.push(`feet ${S(Math.hypot(a.footL[0]-a.footR[0],a.footL[2]-a.footR[2]))} m apart`);const d=Math.min(a.footL[1],a.footR[1])-c-t.ground;d>.08?f.push(`airborne: feet ${S(d)} m off the ground`):Math.abs(a.footL[1]-a.footR[1])>.12&&f.push(`one foot raised ${S(Math.abs(a.footL[1]-a.footR[1]))} m (${a.footL[1]>a.footR[1]?"footL":"footR"})`),f.push(`hips ${S(a.hips[1]-r)} m above the feet (standing ≈ ${S(.5*s)})`);const u=(m,k)=>{const b=m[0]*t.facing[0]+m[2]*t.facing[2],P=m[1],$=(m[0]*t.side[0]+m[2]*t.side[2])*(k==="L"?-1:1),j=[[b,"forward"],[-b,"back"],[P,"up"],[-P,"down"],[$,k?"out":"to its R side"],[-$,k?"in":"to its L side"]];return j.sort((E,R)=>R[0]-E[0]),j[1][0]>.45?`${j[0][1]}-${j[1][1]}`:j[0][1]};for(const m of["R","L"]){const k=t.axes[`hand${m}`],b=t.fingers[m];if(!k)continue;const P=Object.entries(wt).map(([$,j])=>[$,Math.abs(j.grip-b.grip)+Math.abs(j.index-b.index)+.5*Math.abs(j.thumb-b.thumb)]).sort(($,j)=>$[1]-j[1])[0][0];f.push(`hand${m} ${P}: fingers point ${u(k.main,m)}, palm faces ${u(k.second,m)}`)}for(const m of["R","L"]){const k=t.axes[`foot${m}`];k&&f.push(`foot${m} toes point ${u(k.main,m)}`)}const i=t.axes.head;if(i){const m=Math.round(Math.asin(Math.max(-1,Math.min(1,i.second[0]*t.side[0]+i.second[2]*t.side[2])))*180/Math.PI);f.push(`face looks ${u(i.main)}${Math.abs(m)>8?`, head tilted ${Math.abs(m)}° toward its ${m>0?"R":"L"} shoulder`:""}`)}return{facts:f,ground:r,base:o}}function ge(t,a){const f=a.getStage(),c=gt(f),r=a.engine();let o;try{o=tt(f,String(t.name??""))}catch(n){return{ok:!1,error:n.message}}if(o.kind!=="person")return{ok:!1,error:`'${o.name}' is not a person`};if(!r)return{ok:!1,error:"the 3D view is not ready"};r.sync(f,null);const s=(Array.isArray(t.times)?t.times:[t.at??0]).slice(0,6).map(n=>Math.max(0,Math.min(c.duration,Number(n)||0))),e=f.items.filter(n=>n.kind==="person"&&n.id!==o.id),g=s.map(n=>{const d=r.jointsAt(n,o.id);if(!d)return{at_s:n,error:"not built"};const{facts:u,ground:i,base:m}=se(d),k=Object.fromEntries(Object.entries(d.joints).map(([$,j])=>[$,Yt(d,j,i,m)])),b=[];for(const $ of e){const j=r.jointsAt(n,$.id);if(j)for(const E of["handR","handL","footR","footL"])for(const R of["head","chest","hips"]){const h=d.joints[E],N=R==="head"?j.headCentre:j.joints[R];if(!h||!N)continue;const y=Math.hypot(h[0]-N[0],h[1]-N[1],h[2]-N[2])-et.tip(E)-et.surface(R)*j.height/1.8;y<.45&&b.push({joint:E,other:$.name,part:R,gap_m:S(Math.max(0,y))})}}b.sort(($,j)=>$.gap_m-j.gap_m);const P=Object.fromEntries(ee.map($=>[$.id,d.joints[$.part]]).filter(([,$])=>!!$));return{at_s:n,facing:d.facing,controls:P,joints_world:d.joints,head_centre:d.headCentre,joints_local:k,axes:d.axes,fingers:d.fingers,reads:u,...b.length?{near_others:b.slice(0,6)}:{}}}),p=qt(c,o.id);return{ok:!0,name:o.name,...p.length?{strikes:p}:{},frames:g,note:"joints_world = world metres (move_joint to); joints_local = metres in the person's frame: forward, up above its feet, side (+ toward its …R limbs). head = a point in front of the face (head_centre = the skull, for contact). near_others gap_m = the gap between the surfaces (0 = touching). axes: hand {main = fingers, second = palm}, foot {main = toes}, head {main = face, second = top of the head}, world unit vectors; fingers = curls 0..100. Check again after a fix."}}function de(t,a){const f=a.getStage(),c=gt(f),r=a.engine();let o;try{o=tt(f,String(t.name??""))}catch(l){return{ok:!1,error:l.message}}if(o.kind!=="person")return{ok:!1,error:`'${o.name}' is not a person`};const s=t.control!=null?oe(t.control):null;if(t.control!=null&&!s)return{ok:!1,error:`control must be one of ${Tt.join(", ")}`};const e=s?.part??String(t.part??"");if(!Ft.includes(e))return{ok:!1,error:`give control (${Tt.join(", ")}) or part (${Ft.join(", ")})`};if(!r)return{ok:!1,error:"the 3D view is not ready"};r.sync(f,null);const g=qt(c,o.id),p=t.at==="impact"?g.find(l=>l.limb===e)??g[0]:null;if(t.at==="impact"&&!p)return{ok:!1,error:`${o.name} plays no strike clip here: give at in seconds`};const n=p?p.at:Math.max(0,Math.min(c.duration,Number(t.at??0)||0)),d=r.jointsAt(n,o.id),u=d?.joints[e];if(!d||!u)return{ok:!1,error:`no ${e} on ${o.name}`};let i=null;if(Array.isArray(t.to)&&t.to.length===3)i=t.to.map(Number);else if(t.offset_m&&typeof t.offset_m=="object"){const l=t.offset_m,_=Number(l.forward)||0,M=Number(l.up)||0,v=Number(l.side)||0;i=[u[0]+_*d.facing[0]+v*d.side[0],u[1]+M,u[2]+_*d.facing[2]+v*d.side[2]]}else if(t.to_object&&typeof t.to_object=="object"){const l=t.to_object;let _;try{_=tt(f,String(l.name??""))}catch(z){return{ok:!1,error:z.message}}const M=String(l.part??"chest"),v=_.kind==="person"?r.jointsAt(n,_.id):null;if(i=v?(M==="head"?v.headCentre:v.joints[M])??null:r.worldPositionOf(_.id),!i)return{ok:!1,error:`no ${M} on ${_.name}`};const I=v?et.surface(M)*v.height/1.8:0,A=I+et.tip(e);if(A>0){const z=d.joints.chest??u,w=[z[0]-i[0],z[1]-i[1],z[2]-i[2]],x=Math.hypot(...w);x>.001&&(i=[i[0]+w[0]/x*A,i[1]+w[1]/x*A,i[2]+w[2]/x*A])}}if(i&&i.some(l=>!Number.isFinite(l)))return{ok:!1,error:"to must be 3 finite numbers"};const m=e.slice(-1),k=e==="handL"||e==="handR",b=e==="footL"||e==="footR",P=(l,_)=>{if(l==null)return null;if(Array.isArray(l)&&l.length===3&&l.every(A=>Number.isFinite(Number(A))))return l.map(Number);const M=String(l),v=m==="L"?-1:1,I={forward:d.facing,back:[-d.facing[0],0,-d.facing[2]],up:[0,1,0],down:[0,-1,0],out:[d.side[0]*v,0,d.side[2]*v],in:[-d.side[0]*v,0,-d.side[2]*v]};if(M==="target"){if(!i)return`${_} 'target' needs to / to_object`;const A=[i[0]-u[0],i[1]-u[1],i[2]-u[2]];return Math.hypot(...A)>.001?A:null}return I[M]??`${_} must be forward / back / up / down / in / out / target or [x, y, z]`},$=P(k?t.fingers:b?t.toes:e==="head"?t.face:void 0,k?"fingers":b?"toes":"face"),j=P(k?t.palm:void 0,"palm");for(const l of[$,j])if(typeof l=="string")return{ok:!1,error:l};if(!k&&!b&&e!=="head"&&(t.fingers||t.palm||t.toes||t.face))return{ok:!1,error:"fingers / palm are for a hand, toes for a foot, face for the head"};const E=t.hand_shape!=null?String(t.hand_shape):null;if(E&&(!k||!(E in wt)))return{ok:!1,error:`hand_shape is for a hand: ${Object.keys(wt).join(", ")}`};const R=$||j?{...$?{main:$}:{},...j?{second:j}:{}}:void 0,h=(e==="footL"||e==="footR")&&Number.isFinite(Number(t.roll_deg))&&Number(t.roll_deg)!==0?Math.max(-45,Math.min(70,Number(t.roll_deg))):0;if(!i&&!R&&!E&&!h)return{ok:!1,error:"give a target (to [x, y, z], offset_m {forward, up, side}, to_object {name, part}), a direction (fingers / palm, toes, face) or hand_shape"};const N=["moment","span","after"].includes(String(t.scope))?String(t.scope):e==="hips"?"after":"moment",y=c.duration,W=!!(c.objectKeys?.[o.id]?.length||c.clipSpans?.[o.id]?.length),ot=!!i&&W&&N==="moment"&&t.path!==!1&&(k||b),ct=Number(t.fade??.6),Mt=Number(t.fade_out??.5),H=Math.max(0,n-ct-.25),B=Math.min(y,n+Mt+.25),nt=Math.max(4,Math.round((B-H)*24)+1),q=Array.from({length:nt},(l,_)=>H+(B-H)*_/(nt-1)),C=Ht(r.jointPath(o.id,e,q),(B-H)/(q.length-1));let Z=null,O=u,J=0;if(ot&&t.align!==!1){const l=(c.clipSpans?.[o.id]||[]).find(x=>n>=x.start-.001&&n<=x.end+.001),_=l?l.start:Math.max(0,n-.7),M=Math.max(_+.05,Math.min(n,_+Number(t.warp_s??.6))),v=["footL","footR"].filter(x=>x!==e),I=[_,(_+M)/2,M,n],A=x=>{const U=r.jointPath(o.id,x,I);return U.every(Boolean)?U.slice(1).reduce((st,V,dt)=>st+Math.hypot(V[0]-U[dt][0],V[2]-U[dt][2]),0):1/0},z=v.sort((x,U)=>A(x)-A(U))[0],w=r.jointPath(o.id,z,[n])[0];if(w){const x=u[0]-w[0],U=u[2]-w[2],st=i[0]-w[0],V=i[2]-w[2],dt=Math.hypot(x,U),mt=Math.hypot(st,V);if(dt>.12&&mt>.12){const lt=Math.max(-120,Math.min(120,((Math.atan2(st,V)-Math.atan2(x,U))*180/Math.PI+540)%360-180)),$t=mt-dt,xt=Number(t.step_max_m??.05),X=Math.max(-xt,Math.min(xt,$t)),Zt=st/mt,Gt=V/mt;if(Math.abs($t-X)>.12&&(J=S($t-X)),Math.abs(lt)>2||Math.abs(X)>.02){const Nt={scope:"after",start:M,end:M,fade:Math.max(Jt.min,M-_)},Qt=Math.max(1/24,(y-_)/(Wt.samples-2)),Ot=[],Et=[],Lt=[],At=[],Vt={...c,motionEdits:{...c.motionEdits,[o.id]:c.motionEdits?.[o.id]||[]}};for(let D=_;D<=y+1e-6;D+=Qt){const K=kt(Nt,D),ht=K*lt*Math.PI/180,ut=bt(o,Vt,y?D/y:0,f.items).position,It=ut[0]-w[0],Dt=ut[2]-w[2];Ot.push(Math.round(D*1e3)/1e3),Et.push(K*lt),Lt.push(w[0]+It*Math.cos(ht)+Dt*Math.sin(ht)-ut[0]+K*X*Zt),At.push(w[2]-It*Math.sin(ht)+Dt*Math.cos(ht)-ut[2]+K*X*Gt)}const Xt=a.getStage().shots.find(D=>D.id===c.id)?.motionEdits?.[o.id]||[],Rt={id:crypto.randomUUID(),scope:"after",start:M,end:M,fade:Nt.fade,track:{t:Ot,turn:Et,mx:Lt,mz:At},label:`${e}: align the strike`},Pt=_t(Xt,Rt,y);Pt.some(D=>D.id===Rt.id)&&(a.setStage(D=>({...D,shots:D.shots.map(K=>K.id===c.id?{...K,motionEdits:{...K.motionEdits,[o.id]:Pt}}:K)})),Z={turn_deg:Math.round(lt),step_m:S(X),pivot:z},r.sync(a.getStage(),null),O=r.jointsAt(n,o.id)?.joints[e]??u)}}}}let G=0;if(ot&&t.level!==!1&&i&&O[1]-i[1]>.04){const l=(d?.height??1.8)/1.8,_=Math.min(.45,(O[1]-i[1])/(.45*l)),M=Number(t.fade??.5);Kt({name:o.name,at:n,scope:"moment",fade:M,fade_out:Math.max(.35,M*.8),stance:{crouch:Math.round(_*100)/100},label:`${e}: drop the level`},a).ok&&(G=Math.round(_*100)/100,r.sync(a.getStage(),null),O=r.jointsAt(n,o.id)?.joints[e]??O)}const at=i?Math.hypot(i[0]-O[0],i[1]-O[1],i[2]-O[2]):0,T=Number(t.fade??Math.min(.7,.45+.4*at)),it=Number(t.fade_out??Math.max(.35,T*.8)),L=h&&!i?(()=>{const l=r.rollFootAt(n,o.id,e,h,_=>({id:"__drag",scope:"moment",start:n,end:n,fade:T,..._}));return l?{fields:l.fields,miss:l.pivotMove,from:u,aimError:null}:null})():i||R?r.solveJointAt(n,o.id,e,i,l=>({id:"__drag",scope:"moment",start:n,end:n,fade:T,...l}),R,{lockFeet:t.lock_feet===!0}):{fields:{},miss:0,from:u,aimError:null};if(!L)return{ok:!1,error:`could not pose ${o.name} at ${n} s`};const Y=L.fields,yt=E?ne(bt(o,c,c.duration?n/c.duration:0,f.items).pose,m,E)??{}:{},vt={...Y.pose||{},...yt},St=[i?`→ ${i.map(l=>S(l)).join(", ")}`:"",R?"turned":"",E??""].filter(Boolean).join(" "),jt=!!i&&W&&N==="moment"&&t.path!==!1&&!["hips","head"].includes(e);let rt;if(jt){const l=Object.fromEntries(Object.entries(Y.pose||{}).filter(([w])=>/^(wrist|ankle)/.test(w))),_={scope:"moment",start:n,end:n,fade:T,fadeOut:it},M=r.bakeJointPath(n,o.id,e,i,w=>kt(_,w),[n-T,n+it],{...l,...yt});if(!M)return{ok:!1,error:`could not pose ${o.name} along its path`};const v=a.getStage().shots.find(w=>w.id===c.id)?.motionEdits?.[o.id]||[],I={id:crypto.randomUUID(),scope:"moment",start:n,end:n,fade:T,fadeOut:it,track:M.track,label:String(t.label??`${e} ${St} (path)`)},A=_t(v,I,y),z=A.find(w=>w.id===I.id);if(!z)return{ok:!1,error:"the move changes nothing"};a.setStage(w=>({...w,shots:w.shots.map(x=>x.id===c.id?{...x,motionEdits:{...x.motionEdits,[o.id]:A}}:x)})),L.miss=M.miss,rt={ok:!0,name:o.name,edit:pt(z,n),edits:A.length,note:"carried along the motion's own path (keys untouched); edit_motion remove to drop it"}}else rt=Kt({name:o.name,at:n,scope:N,fade:T,fade_out:it,...t.start!=null?{start:t.start}:{},...t.end!=null?{end:t.end}:{},...Object.keys(vt).length?{joints:vt}:{},...Y.move?{move_m:[Y.move[0],Y.move[2]]}:{},...Y.stance?{stance:Y.stance}:{},label:String(t.label??`${e} ${St}`)},a);if(!rt.ok)return rt;r.sync(a.getStage(),null);const Q=Ht(r.jointPath(o.id,e,q),(B-H)/(q.length-1));let F="";if(i&&L.miss>.04){const l=d.joints.hips??u,_=i[0]-l[0],M=i[2]-l[2],v=Math.hypot(_,M),I=v>.05?Math.round(Math.atan2(_*d.facing[2]-M*d.facing[0],_*d.facing[0]+M*d.facing[2])*180/Math.PI):0;F=`${e} stays ${L.miss} m short (out of reach or at a joint limit)`+(Math.abs(I)>50?`: ${o.name} faces ${Math.abs(I)}° away from the target — turn first (${W?"edit_motion face_toward the target, scope span":`edit_motion turn_deg ${I}, scope span`}), then move_joint again`:`: the target is ${S(v)} m from the hips — step closer: edit_motion move_m [${S(_/v*(L.miss+.03))}, ${S(M/v*(L.miss+.03))}] (scope span), then move_joint again; or pick another time`)}J&&(F+=`${F?"; ":""}the fighters stand ${Math.abs(J)} m too ${J>0?"far apart":"close"} for this blow as the clip throws it: re-block their marks (stand_at / set_transform before the motion) rather than stretching the limb`),L.aimError!=null&&L.aimError>12&&(F+=`${F?"; ":""}${k?"the hand":b?"the foot":"the face"} points ${L.aimError}° off the asked direction (the wrist / ankle / neck limit) — turn the forearm (move_joint elbow) or the body first`);const ft=C&&Q?{peak_speed_m_s:[C.speed,Q.speed],peak_jerk:[C.jerk,Q.jerk],jerk_change_pct:Math.round((Q.jerk-C.jerk)/Math.max(1,C.jerk)*100)}:null;return ft&&Q.jerk>C.jerk*1.5&&Q.jerk>800&&(F+=`${F?"; ":""}the fix makes ${e} ${ft.jerk_change_pct}% jerkier — ${jt?"lengthen fade / fade_out":"try path mode (a moving person, scope moment) or lengthen fade / fade_out"}, face_toward first so less is corrected, or fix the motion itself`),{...rt,part:e,...Ut(e)?{control:Ut(e).id}:{},from:L.from,...i?{to:i.map(S),miss_m:L.miss}:{},...L.aimError!=null?{aim_error_deg:L.aimError}:{},...jt?{mode:"path"}:{},...Z?{aligned:Z}:{},...G?{lowered_crouch:G}:{},...ft?{smoothness:ft}:{},...F?{warning:F}:{}}}function Me(t,a){const f=t.engine();if(!f)return null;const c=a.filter(s=>(s.planned==="head"||s.planned==="body")&&s.limb&&/^(hand|foot)[LR]$/.test(s.limb)).sort((s,e)=>s.time-e.time),r=s=>{f.sync(t.getStage(),null);const e=t.getStage(),g=e.items.find(m=>m.name===s.attacker),p=e.items.find(m=>m.name===s.target),n=g&&f.jointsAt(s.time,g.id),d=p&&f.jointsAt(s.time,p.id),u=n?.joints[s.limb],i=s.planned==="head"?d?.headCentre:d?.joints.chest;return!u||!i||!d?null:S(Math.hypot(u[0]-i[0],u[1]-i[1],u[2]-i[2])-et.tip(s.limb)-et.surface(s.planned==="head"?"head":"chest")*d.height/1.8)},o=[];for(const s of c){const e=r(s);let g=e;for(let p=0;p<2&&g!=null&&Math.abs(g)>.015;p++){const n=a.filter(b=>b.attacker===s.attacker&&b!==s).map(b=>b.time),d=Math.max(-1/0,...n.filter(b=>b<s.time)),u=Math.min(1/0,...n.filter(b=>b>s.time)),i=Math.max(.15,Math.min(.45,.8*(s.time-d))),m=Math.max(.15,Math.min(.4,.8*(u-s.time)));if(!de({name:s.attacker,part:s.limb,at:s.time,to_object:{name:s.target,part:s.planned==="head"?"head":"chest"},align:!1,level:!1,fade:i,fade_out:m,label:"land the blow"},t).ok)break;g=r(s)}o.push({time_s:S(s.time),attacker:s.attacker,limb:s.limb,zone:s.planned,gap_before_m:e,gap_after_m:g})}return o}function je(t,a){const f=a.getStage(),c=gt(f);let r;try{r=tt(f,String(t.name??""))}catch(n){return{ok:!1,error:n.message}}if(r.kind!=="person")return{ok:!1,error:`'${r.name}' is not a person`};const o=Math.max(0,Math.min(c.duration,Number(t.at)||0)),s=c.duration?o/c.duration:0,e=t.breakdown_bias==null?null:Math.max(0,Math.min(1,Number(t.breakdown_bias))),g=e==null?ae(c,r,s):ie(c,r,s,e);if(!g)return{ok:!1,error:`no pose keys on both sides of ${o} s for a breakdown — set keys first (pose_key / set_pose)`};a.setStage(n=>({...n,shots:n.shots.map(d=>d.id===c.id?g:d)}));const p=g.objectKeys?.[r.id]||[];return{ok:!0,name:r.name,at_s:o,kind:e==null?"key":"breakdown",...e!=null?{bias:e}:{},keys_s:p.filter(n=>n.pose).map(n=>S(n.time*c.duration)).slice(0,40)}}export{Kt as editMotion,ge as inspectPose,Me as landBlows,de as moveJoint,je as poseKey,qt as strikesOf};
@@ -0,0 +1 @@
1
+ import{_ as P}from"./titleFrameBudget-CLZWaFHO.js";import{readUpscaleModel as C}from"./store-Cug4GGcP.js";import{I as D,A as R,U as B,B as U,c as V,Q as X}from"./id3-arvEpAg7.js";import{O as Q,B as F,a as N}from"./output-p-Q7qous.js";import{C as Y}from"./conversion-4rhF3xRJ.js";const j=["photo","anime"],I=4,q=2048,z=8192,E=1080,G=256,K=12,x=n=>Math.max(2,Math.round(n/2)*2);function O({width:n,height:u,kind:c="image",scale:r=2,model:i="photo"}={}){const t=Math.round(Number(n)),o=Math.round(Number(u));if(!(t>0&&o>0))return{error:"no size"};if(!j.includes(i))return{error:"model"};if(c==="video"){const p=Math.min(t,o);if(p>=E)return{error:"already sharp"};const f=Math.min(2,E/p),a=x(t*f),m=x(o*f),w=Math.min(1,a/I/t);return{model:i,kind:c,inW:x(t*w),inH:x(o*w),outW:a,outH:m,scale:Math.round(a/t*100)/100}}const e=r===4?4:2,s=Math.min(1,z/(Math.max(t,o)*e)),h=Math.max(1,Math.round(t*e*s)),l=Math.max(1,Math.round(o*e*s)),d=Math.min(1,q/Math.max(t,o));return{model:i,kind:c,inW:Math.max(1,Math.round(t*d)),inH:Math.max(1,Math.round(o*d)),outW:h,outH:l,scale:Math.round(h/t*100)/100}}function $(n,u,c=G,r=K){const i=[];for(let t=0;t<u;t+=c)for(let o=0;o<n;o+=c){const e=Math.min(c,n-o),s=Math.min(c,u-t),h=Math.max(0,o-r),l=Math.max(0,t-r),d=Math.min(n,o+e+r),p=Math.min(u,t+s+r);i.push({x:h,y:l,w:d-h,h:p-l,keepX:o-h,keepY:t-l,keepW:e,keepH:s})}return i}const J="1.31.1",W=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${J}/dist/`;let _=null;const Z=()=>_??=(async()=>{const n=await P(()=>import(`${W}ort.webgpu.min.mjs`),[]);return n.env.wasm.wasmPaths=W,n.env.wasm.numThreads=globalThis.crossOriginIsolated?Math.min(4,navigator.hardwareConcurrency||1):1,n})().catch(n=>{throw _=null,n}),H=new Map;function T(n){const u=globalThis.__upscaleEngine;if(u)return Promise.resolve({run:(r,i,t)=>u.run(n,r,i,t),backend:"stub"});let c=H.get(n);return c||(c=(async()=>{const[r,i]=await Promise.all([Z(),C(n)]);let t=null,o="webgpu";return navigator.gpu&&(t=await r.InferenceSession.create(i,{executionProviders:["webgpu"],graphOptimizationLevel:"all"}).catch(()=>null)),t||(o="wasm",t=await r.InferenceSession.create(i,{executionProviders:["wasm"],graphOptimizationLevel:"all"})),{backend:o,async run(e,s,h){const l=new r.Tensor("float32",e,[1,3,h,s]),d=await t.run({input:l});try{return await d.output.getData()}finally{d.output.dispose?.()}}}})(),c.catch(()=>H.delete(n)),H.set(n,c)),c}const b=(n,u)=>new OffscreenCanvas(n,u),v=n=>n.getContext("2d",{willReadFrequently:!0});function tt(n,u,c){const r=u*c,i=new Float32Array(3*r);for(let t=0;t<r;t++)i[t]=n[4*t]/255,i[r+t]=n[4*t+1]/255,i[2*r+t]=n[4*t+2]/255;return i}function nt(n,u,c){const r=u*c,i=new ImageData(u,c),t=i.data;for(let o=0;o<r;o++)t[4*o]=n[o]*255+.5,t[4*o+1]=n[r+o]*255+.5,t[4*o+2]=n[2*r+o]*255+.5,t[4*o+3]=255;return i}async function S(n,u,c,r,i,t,o,e,s){const h=$(c,r),l=t/c,d=o/r;i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high";let p=null;for(let f=0;f<h.length;f++){if(s?.aborted)throw new DOMException("Upscale cancelled","AbortError");const a=h[f],m=I,w=await n.run(tt(u.getImageData(a.x,a.y,a.w,a.h).data,a.w,a.h),a.w,a.h);(!p||p.width!==a.w*m||p.height!==a.h*m)&&(p=b(a.w*m,a.h*m)),v(p).putImageData(nt(w,a.w*m,a.h*m),0,0);const k=a.x+a.keepX,M=a.y+a.keepY,y=Math.round(k*l),g=Math.round(M*d),A=Math.round((k+a.keepW)*l),L=Math.round((M+a.keepH)*d);i.drawImage(p,a.keepX*m,a.keepY*m,a.keepW*m,a.keepH*m,y,g,A-y,L-g),e?.(f+1,h.length)}}async function st(n,{scale:u=2,model:c="photo",onProgress:r,signal:i}={}){const t=performance.now(),o=typeof n=="string"?await(await fetch(n,{signal:i})).blob():n,e=await createImageBitmap(o),s=O({width:e.width,height:e.height,kind:"image",scale:u,model:c});if(s.error!==void 0)throw Error(s.error);const h=await T(c),l=b(s.inW,s.inH),d=v(l);d.imageSmoothingQuality="high",d.drawImage(e,0,0,s.inW,s.inH),e.close();const p=b(s.outW,s.outH);await S(h,d,s.inW,s.inH,v(p),s.outW,s.outH,(m,w)=>r?.({fraction:m/w}),i);const f=s.outW*s.outH>16e6;return{blob:await p.convertToBlob(f?{type:"image/jpeg",quality:.95}:{type:"image/png"}),width:s.outW,height:s.outH,backend:h.backend,seconds:(performance.now()-t)/1e3}}async function ct(n,{model:u="photo",onProgress:c,signal:r}={}){const i=performance.now(),t=new D({source:typeof n=="string"?new B(n):new U(n),formats:R});try{const o=await t.getPrimaryVideoTrack();if(!o)throw Error("no video track");const e=O({width:o.displayWidth,height:o.displayHeight,kind:"video",model:u});if(e.error!==void 0)throw Error(e.error);const s=await t.computeDuration(),h=await T(u),l=b(e.inW,e.inH),d=v(l),p=b(e.outW,e.outH),f=v(p);d.imageSmoothingQuality="high";const a=await V("avc",{width:e.outW,height:e.outH}).catch(()=>!1),m=new Q({format:new N({fastStart:"in-memory"}),target:new F}),w=await Y.init({input:t,output:m,video:{forceTranscode:!0,quality:X,...a?{codec:"avc"}:{},processedWidth:e.outW,processedHeight:e.outH,process:async g=>(g.draw(d,0,0,e.inW,e.inH),await S(h,d,e.inW,e.inH,f,e.outW,e.outH,void 0,r),p)}});if(!w.isValid)throw Error("This video cannot be converted here");const k=w.discardedTracks.some(g=>g.track.type==="audio");w.onProgress=g=>c?.({fraction:g});const M=()=>{w.cancel()};r?.addEventListener("abort",M,{once:!0});try{await w.execute()}finally{r?.removeEventListener("abort",M)}const y=m.target.buffer;if(!y)throw Error("no output");return{blob:new Blob([y],{type:"video/mp4"}),width:e.outW,height:e.outH,duration:s,backend:h.backend,seconds:(performance.now()-i)/1e3,soundDropped:k}}finally{t.dispose?.()}}export{J as UPSCALE_ORT_VERSION,nt as fromCHW,tt as toCHW,st as upscaleImage,T as upscaleRunner,ct as upscaleVideo};
@@ -1 +1 @@
1
- import{bT as C,bU as O}from"./api-DUp403BK.js";import{lN as S,lO as T,hI as q,hJ as _,lP as N,ai as D,lB as j}from"./titleFrameBudget-BYRZAQPs.js";const A=Object.freeze({fisheye:.45,dispersion:.018,burst:.5,streak:.32,taps:8}),H=t=>[1+2.2*t,.88+1.8*t,.55+.9*t].map(n=>+n.toFixed(4));function z(t,n,o){const e=Math.max(t,Math.trunc(t*o/2)*2),r=Math.max(n,Math.trunc(n*o/2)*2);return{sw:e,sh:r,ox:Math.trunc((e-t)/2),oy:Math.trunc((r-n)/2)}}const W=(t,n)=>({w:Math.max(2,Math.trunc(t/4)*2),h:Math.max(2,Math.trunc(n/4)*2)}),G=(t,n=A.taps)=>Array.from({length:n},(o,e)=>1+t*e/(n-1));function I(t){const n=+(A.fisheye*t).toFixed(4);let o=1+n;for(let e=0;e<20;e++)o-=(o*o*o-o*o-n)/(3*o*o-2*o);return{K:n,m:+o.toFixed(4)}}function b(t,n,o,e,r,a){const d=Math.max(0,Math.min(n-1.001,e)),l=Math.max(0,Math.min(o-1.001,r)),f=d|0,m=l|0,i=d-f,u=l-m,h=(m*n+f)*4+a,c=h+4,s=h+n*4,x=s+4;return(t[h]*(1-i)+t[c]*i)*(1-u)+(t[s]*(1-i)+t[x]*i)*u}const v=(t,n,o,e,r)=>[(e+t.ox+.5)*n/t.sw-.5,(r+t.oy+.5)*o/t.sh-.5];function J(t,n,o,e){const r=G(e).map(l=>z(n,o,l)),a=new Uint8ClampedArray(t.length),d=r.length;for(let l=0;l<o;l++)for(let f=0;f<n;f++){const m=(l*n+f)*4,i=[0,0,0,0];for(const u of r){const[h,c]=v(u,n,o,f,l);for(let s=0;s<4;s++)i[s]+=b(t,n,o,h,c,s)}for(let u=0;u<4;u++)a[m+u]=Math.round(i[u]/d)}return a}function tt(t,n,o,e,r){if(!(n>.001))return!1;const a=new Uint8ClampedArray(o);if(t==="fisheye"){const{K:d,m:l}=I(n),f=z(e,r,l),m=e/2,i=r/2,u=4/(e*e+r*r),h=new Uint8ClampedArray(a.length);for(let c=0;c<r;c++)for(let s=0;s<e;s++){const x=s-m,M=c-i,L=1+d*(x*x+M*M)*u,y=(c*e+s)*4,B=m+x*L+.5,E=i+M*L+.5;if(B>=0&&E>=0&&B<=e-1&&E<=r-1)for(let g=0;g<4;g++)h[y+g]=b(a,e,r,B,E,g)}for(let c=0;c<r;c++)for(let s=0;s<e;s++){const[x,M]=v(f,e,r,s,c),L=(c*e+s)*4;for(let y=0;y<4;y++)o[L+y]=b(h,e,r,x,M,y)}return!0}if(t==="dispersion"){const d=A.dispersion*n,l=z(e,r,1+2*d),f=z(e,r,1+d);for(let m=0;m<r;m++)for(let i=0;i<e;i++){const u=(m*e+i)*4,[h,c]=v(l,e,r,i,m),[s,x]=v(f,e,r,i,m);o[u]=b(a,e,r,h,c,0),o[u+1]=b(a,e,r,s,x,1)}return!0}return t==="zoom-streak"?(o.set(J(a,e,r,A.streak*n)),!0):!1}const w=new Map,P=new Map,k=new Map,F=new Set;async function et(t){if(t.size>4e7)throw Error("File LUT tối đa 40 MB");const n=q(_(await t.text())),o=(n.title||t.name.replace(/\.cube$/i,"")).slice(0,80),e=await O({name:o,...N(n)});return w.set(e.id,n),F.forEach(r=>r()),e}function K(t){if(w.has(t))return Promise.resolve(w.get(t));let n=P.get(t);return n||(n=C(t).then(o=>{const e=S(o);return w.set(t,e),F.forEach(r=>r()),e}).finally(()=>P.delete(t)),P.set(t,n)),n}function X(t){const n=w.get(t.id);if(!n)return K(t.id).catch(()=>{}),null;const o=`${t.id}:${t.mix??1}`;let e=k.get(o);return e||(e=T(n,t.mix??1),k.set(o,e)),e}const p=new Map;function nt(t){if(!t)return null;const n=t.lut?X(t.lut):null;if(t.lut&&!n)return null;if(!D(t.mixer))return n;const o=`${t.lut?`${t.lut.id}:${t.lut.mix??1}`:"-"}|${JSON.stringify(t.mixer)}`;let e=p.get(o);return e||(e=j(t.mixer,n),p.set(o,e),p.size>24&&p.delete(p.keys().next().value)),e}const $=Object.freeze({codec:"h264",quality:"recommended",container:"mp4"}),U={h264:{low:4,recommended:8,high:16},hevc:{low:2.5,recommended:5,high:10}};function Y(t,{width:n,height:o,fps:e}){const r=t??$,a=n*o/(1920*1080)*(e/30);return Math.round(U[r.codec][r.quality]*1e6*Math.max(.2,a))}const ot=(t,n,o)=>Math.round((Y(t,n)+16e4)*Math.max(0,o)/8),Q={low:.5,recommended:1,high:2};function rt(t,{width:n,height:o,fps:e},r){const a=t??$;return Math.round(Math.min(4e7,Math.max(5e5,r(n,o,e)*Q[a.quality]*(a.codec==="hevc"?U.hevc.recommended/U.h264.recommended:1))))}export{$ as D,A as L,tt as a,H as b,W as c,z as d,ot as e,rt as f,nt as g,K as h,et as i,X as l,G as z};
1
+ import{bT as C,bU as O}from"./api-CJ8PdbfZ.js";import{lN as S,lO as T,hI as q,hJ as _,lP as N,ai as D,lB as j}from"./titleFrameBudget-CLZWaFHO.js";const A=Object.freeze({fisheye:.45,dispersion:.018,burst:.5,streak:.32,taps:8}),H=t=>[1+2.2*t,.88+1.8*t,.55+.9*t].map(n=>+n.toFixed(4));function z(t,n,o){const e=Math.max(t,Math.trunc(t*o/2)*2),r=Math.max(n,Math.trunc(n*o/2)*2);return{sw:e,sh:r,ox:Math.trunc((e-t)/2),oy:Math.trunc((r-n)/2)}}const W=(t,n)=>({w:Math.max(2,Math.trunc(t/4)*2),h:Math.max(2,Math.trunc(n/4)*2)}),G=(t,n=A.taps)=>Array.from({length:n},(o,e)=>1+t*e/(n-1));function I(t){const n=+(A.fisheye*t).toFixed(4);let o=1+n;for(let e=0;e<20;e++)o-=(o*o*o-o*o-n)/(3*o*o-2*o);return{K:n,m:+o.toFixed(4)}}function b(t,n,o,e,r,a){const d=Math.max(0,Math.min(n-1.001,e)),l=Math.max(0,Math.min(o-1.001,r)),f=d|0,m=l|0,i=d-f,u=l-m,h=(m*n+f)*4+a,c=h+4,s=h+n*4,x=s+4;return(t[h]*(1-i)+t[c]*i)*(1-u)+(t[s]*(1-i)+t[x]*i)*u}const v=(t,n,o,e,r)=>[(e+t.ox+.5)*n/t.sw-.5,(r+t.oy+.5)*o/t.sh-.5];function J(t,n,o,e){const r=G(e).map(l=>z(n,o,l)),a=new Uint8ClampedArray(t.length),d=r.length;for(let l=0;l<o;l++)for(let f=0;f<n;f++){const m=(l*n+f)*4,i=[0,0,0,0];for(const u of r){const[h,c]=v(u,n,o,f,l);for(let s=0;s<4;s++)i[s]+=b(t,n,o,h,c,s)}for(let u=0;u<4;u++)a[m+u]=Math.round(i[u]/d)}return a}function tt(t,n,o,e,r){if(!(n>.001))return!1;const a=new Uint8ClampedArray(o);if(t==="fisheye"){const{K:d,m:l}=I(n),f=z(e,r,l),m=e/2,i=r/2,u=4/(e*e+r*r),h=new Uint8ClampedArray(a.length);for(let c=0;c<r;c++)for(let s=0;s<e;s++){const x=s-m,M=c-i,L=1+d*(x*x+M*M)*u,y=(c*e+s)*4,B=m+x*L+.5,E=i+M*L+.5;if(B>=0&&E>=0&&B<=e-1&&E<=r-1)for(let g=0;g<4;g++)h[y+g]=b(a,e,r,B,E,g)}for(let c=0;c<r;c++)for(let s=0;s<e;s++){const[x,M]=v(f,e,r,s,c),L=(c*e+s)*4;for(let y=0;y<4;y++)o[L+y]=b(h,e,r,x,M,y)}return!0}if(t==="dispersion"){const d=A.dispersion*n,l=z(e,r,1+2*d),f=z(e,r,1+d);for(let m=0;m<r;m++)for(let i=0;i<e;i++){const u=(m*e+i)*4,[h,c]=v(l,e,r,i,m),[s,x]=v(f,e,r,i,m);o[u]=b(a,e,r,h,c,0),o[u+1]=b(a,e,r,s,x,1)}return!0}return t==="zoom-streak"?(o.set(J(a,e,r,A.streak*n)),!0):!1}const w=new Map,P=new Map,k=new Map,F=new Set;async function et(t){if(t.size>4e7)throw Error("File LUT tối đa 40 MB");const n=q(_(await t.text())),o=(n.title||t.name.replace(/\.cube$/i,"")).slice(0,80),e=await O({name:o,...N(n)});return w.set(e.id,n),F.forEach(r=>r()),e}function K(t){if(w.has(t))return Promise.resolve(w.get(t));let n=P.get(t);return n||(n=C(t).then(o=>{const e=S(o);return w.set(t,e),F.forEach(r=>r()),e}).finally(()=>P.delete(t)),P.set(t,n)),n}function X(t){const n=w.get(t.id);if(!n)return K(t.id).catch(()=>{}),null;const o=`${t.id}:${t.mix??1}`;let e=k.get(o);return e||(e=T(n,t.mix??1),k.set(o,e)),e}const p=new Map;function nt(t){if(!t)return null;const n=t.lut?X(t.lut):null;if(t.lut&&!n)return null;if(!D(t.mixer))return n;const o=`${t.lut?`${t.lut.id}:${t.lut.mix??1}`:"-"}|${JSON.stringify(t.mixer)}`;let e=p.get(o);return e||(e=j(t.mixer,n),p.set(o,e),p.size>24&&p.delete(p.keys().next().value)),e}const $=Object.freeze({codec:"h264",quality:"recommended",container:"mp4"}),U={h264:{low:4,recommended:8,high:16},hevc:{low:2.5,recommended:5,high:10}};function Y(t,{width:n,height:o,fps:e}){const r=t??$,a=n*o/(1920*1080)*(e/30);return Math.round(U[r.codec][r.quality]*1e6*Math.max(.2,a))}const ot=(t,n,o)=>Math.round((Y(t,n)+16e4)*Math.max(0,o)/8),Q={low:.5,recommended:1,high:2};function rt(t,{width:n,height:o,fps:e},r){const a=t??$;return Math.round(Math.min(4e7,Math.max(5e5,r(n,o,e)*Q[a.quality]*(a.codec==="hevc"?U.hevc.recommended/U.h264.recommended:1))))}export{$ as D,A as L,tt as a,H as b,W as c,z as d,ot as e,rt as f,nt as g,K as h,et as i,X as l,G as z};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GLTFExporter-BuGYM-Ik.js","assets/three.module-Bx43vjkH.js"])))=>i.map(i=>d[i]);
2
- import{_ as T}from"./titleFrameBudget-BYRZAQPs.js";import{e0 as x}from"./remote-Dva2qg58.js";import{Mesh as g,Color as D,CanvasTexture as y,SRGBColorSpace as M,NoColorSpace as _}from"./three.module-Bx43vjkH.js";import"./api-DUp403BK.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-75tQUvPT.js";import"./rotoMaskStore-BxyxB2bD.js";import"./textAnimators-nVSz_sZo.js";import"./timelineComp-BcewYGR2.js";import"./rigTrack-UYZU4P-e.js";async function d(e,n=15e3){const i=performance.now();for(;!(e.image&&(e.image.complete??!0)&&(e.image.naturalWidth??e.image.width??0)>0);){if(performance.now()-i>n)return null;await new Promise(a=>setTimeout(a,50))}return e.image}function b(e){const n=e.naturalWidth||e.width,i=e.naturalHeight||e.height,a=document.createElement("canvas");a.width=n,a.height=i;const r=a.getContext("2d",{willReadFrequently:!0});return r.drawImage(e,0,0),{c:a,g:r,data:r.getImageData(0,0,n,i),w:n,h:i}}const f=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,w=(e,n,i)=>{const a=Math.min(1,Math.max(0,(i-e)/(n-e)));return a*a*(3-2*a)};function S(e,n){const{c:i,g:a,data:r}=b(e),u=new D(n),t=r.data;for(let s=0;s<t.length;s+=4){const c=f(t[s]/255)-u.r,l=f(t[s+1]/255)-u.g,o=f(t[s+2]/255)-u.b;Math.hypot(c,l,o)<.09&&(t[s+3]=0)}a.putImageData(r,0,0);const p=new y(i);return p.colorSpace=M,p.flipY=!0,p}function k(e){const{c:n,g:i,data:a}=b(e),r=a.data;for(let t=0;t<r.length;t+=4){const p=f(r[t]/255),s=f(r[t+1]/255),c=f(r[t+2]/255),l=.2126*p+.7152*s+.0722*c,o=Math.max(p,s,c),h=Math.min(p,s,c),m=w(.12,.32,l)*(1-w(.55,.85,o>0?(o-h)/o:0));r[t]=255,r[t+1]=Math.round((.07+(.62-.07)*m)*255),r[t+2]=0,r[t+3]=255}i.putImageData(a,0,0);const u=new y(n);return u.colorSpace=_,u.flipY=!0,u}async function R(e){const n=x(e),i=new Map,a=[];n.traverse(t=>{t instanceof g&&a.push(t)});for(const t of a){const p=Array.isArray(t.material)?t.material:[t.material],s=[];for(const c of p){let l=i.get(c);if(!l){l=c;const o=c;if(o.map&&(o.userData.keyout||o.userData.autoFinish)){const h=await d(o.map);if(h){const m=o.clone();m.onBeforeCompile=()=>{},o.userData.keyout&&(m.map=S(h,o.userData.keyout),m.alphaTest=.5,m.transparent=!1),o.userData.autoFinish&&(m.roughness=1,m.roughnessMap=k(h),m.clearcoat=.25),l=m}}else o.map&&await d(o.map);i.set(c,l)}s.push(l)}t.material=Array.isArray(t.material)?s:s[0]}const{GLTFExporter:r}=await T(async()=>{const{GLTFExporter:t}=await import("./GLTFExporter-BuGYM-Ik.js");return{GLTFExporter:t}},__vite__mapDeps([0,1])),u=await new r().parseAsync(n,{binary:!0,maxTextureSize:4096});return n.traverse(t=>{t instanceof g&&t.geometry.dispose()}),new Blob([u],{type:"model/gltf-binary"})}export{R as recipeGlb};
2
+ import{_ as T}from"./titleFrameBudget-CLZWaFHO.js";import{e0 as x}from"./remote-C7J0Tqhb.js";import{Mesh as g,Color as D,CanvasTexture as y,SRGBColorSpace as M,NoColorSpace as _}from"./three.module-Bx43vjkH.js";import"./api-CJ8PdbfZ.js";import"./GLTFLoader-BHWu1lKg.js";import"./store-DW4E9xnW.js";import"./rotoMaskStore-DPziPKAN.js";import"./textAnimators-DUZjhVGO.js";import"./timelineComp-B4GtoH2f.js";import"./rigTrack-urT3nDK0.js";async function d(e,n=15e3){const i=performance.now();for(;!(e.image&&(e.image.complete??!0)&&(e.image.naturalWidth??e.image.width??0)>0);){if(performance.now()-i>n)return null;await new Promise(a=>setTimeout(a,50))}return e.image}function b(e){const n=e.naturalWidth||e.width,i=e.naturalHeight||e.height,a=document.createElement("canvas");a.width=n,a.height=i;const r=a.getContext("2d",{willReadFrequently:!0});return r.drawImage(e,0,0),{c:a,g:r,data:r.getImageData(0,0,n,i),w:n,h:i}}const f=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,w=(e,n,i)=>{const a=Math.min(1,Math.max(0,(i-e)/(n-e)));return a*a*(3-2*a)};function S(e,n){const{c:i,g:a,data:r}=b(e),u=new D(n),t=r.data;for(let s=0;s<t.length;s+=4){const c=f(t[s]/255)-u.r,l=f(t[s+1]/255)-u.g,o=f(t[s+2]/255)-u.b;Math.hypot(c,l,o)<.09&&(t[s+3]=0)}a.putImageData(r,0,0);const p=new y(i);return p.colorSpace=M,p.flipY=!0,p}function k(e){const{c:n,g:i,data:a}=b(e),r=a.data;for(let t=0;t<r.length;t+=4){const p=f(r[t]/255),s=f(r[t+1]/255),c=f(r[t+2]/255),l=.2126*p+.7152*s+.0722*c,o=Math.max(p,s,c),h=Math.min(p,s,c),m=w(.12,.32,l)*(1-w(.55,.85,o>0?(o-h)/o:0));r[t]=255,r[t+1]=Math.round((.07+(.62-.07)*m)*255),r[t+2]=0,r[t+3]=255}i.putImageData(a,0,0);const u=new y(n);return u.colorSpace=_,u.flipY=!0,u}async function R(e){const n=x(e),i=new Map,a=[];n.traverse(t=>{t instanceof g&&a.push(t)});for(const t of a){const p=Array.isArray(t.material)?t.material:[t.material],s=[];for(const c of p){let l=i.get(c);if(!l){l=c;const o=c;if(o.map&&(o.userData.keyout||o.userData.autoFinish)){const h=await d(o.map);if(h){const m=o.clone();m.onBeforeCompile=()=>{},o.userData.keyout&&(m.map=S(h,o.userData.keyout),m.alphaTest=.5,m.transparent=!1),o.userData.autoFinish&&(m.roughness=1,m.roughnessMap=k(h),m.clearcoat=.25),l=m}}else o.map&&await d(o.map);i.set(c,l)}s.push(l)}t.material=Array.isArray(t.material)?s:s[0]}const{GLTFExporter:r}=await T(async()=>{const{GLTFExporter:t}=await import("./GLTFExporter-BuGYM-Ik.js");return{GLTFExporter:t}},__vite__mapDeps([0,1])),u=await new r().parseAsync(n,{binary:!0,maxTextureSize:4096});return n.traverse(t=>{t instanceof g&&t.geometry.dispose()}),new Blob([u],{type:"model/gltf-binary"})}export{R as recipeGlb};