framefields 2.13.1 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +5 -1
- package/dist/audio/index.d.mts +5 -5
- package/dist/audio/index.mjs +10 -10
- package/dist/{audio-DIvi6hTD.mjs → audio-6TfPlfl4.mjs} +3 -3
- package/dist/{audio-DIvi6hTD.mjs.map → audio-6TfPlfl4.mjs.map} +1 -1
- package/dist/{audio-C4B9p_yq.d.mts → audio-7oqTUi4G.d.mts} +3 -3
- package/dist/{audio-C4B9p_yq.d.mts.map → audio-7oqTUi4G.d.mts.map} +1 -1
- package/dist/cli/check-worker.mjs +44 -44
- package/dist/cli.mjs +1 -1
- package/dist/cloud/index.d.mts.map +1 -1
- package/dist/cloud/index.mjs +1 -1
- package/dist/{cloud-Cj1TIme8.mjs → cloud-jnk1hPYf.mjs} +2 -2
- package/dist/{cloud-Cj1TIme8.mjs.map → cloud-jnk1hPYf.mjs.map} +1 -1
- package/dist/components/index.d.mts +13 -13
- package/dist/components/index.mjs +43 -43
- package/dist/{dist-Kbf-JTry.mjs → dist-BtI6ukB5.mjs} +2 -2
- package/dist/{dist-Kbf-JTry.mjs.map → dist-BtI6ukB5.mjs.map} +1 -1
- package/dist/{dist-CCrYOkcc.mjs → dist-COOpgG9G.mjs} +4 -3
- package/dist/{dist-CCrYOkcc.mjs.map → dist-COOpgG9G.mjs.map} +1 -1
- package/dist/{dist-DtPPPsZV.mjs → dist-XqlFM2a8.mjs} +14063 -5308
- package/dist/dist-XqlFM2a8.mjs.map +1 -0
- package/dist/{dist-CiTgmfUw.mjs → dist-f1zkl69f.mjs} +4 -4
- package/dist/dist-f1zkl69f.mjs.map +1 -0
- package/dist/{dist-B_rSWeOz.mjs → dist-umQOWz0a.mjs} +1 -1
- package/dist/effects/index.d.mts +5 -5
- package/dist/effects/index.mjs +35 -35
- package/dist/{effects-B-L3rLs6.mjs → effects-DlRMovU5.mjs} +2 -2
- package/dist/{effects-B-L3rLs6.mjs.map → effects-DlRMovU5.mjs.map} +1 -1
- package/dist/fonts/index.d.mts +1 -1
- package/dist/fonts/index.mjs +2 -2
- package/dist/{fonts-k5ll8NTE.mjs → fonts-BWYcXjyK.mjs} +3 -3
- package/dist/fonts-BWYcXjyK.mjs.map +1 -0
- package/dist/{gpu-D2HT3KcE.mjs → gpu-CH1PdM4T.mjs} +2 -2
- package/dist/{gpu-D2HT3KcE.mjs.map → gpu-CH1PdM4T.mjs.map} +1 -1
- package/dist/{index-rtCXNxGO.d.mts → index-BHTycml5.d.mts} +2 -2
- package/dist/{index-rtCXNxGO.d.mts.map → index-BHTycml5.d.mts.map} +1 -1
- package/dist/{index-BFTtXosj.d.mts → index-BVd6nXd5.d.mts} +2 -2
- package/dist/{index-BFTtXosj.d.mts.map → index-BVd6nXd5.d.mts.map} +1 -1
- package/dist/{index-ByhlTwxh.d.mts → index-BcxxxwhV.d.mts} +5 -5
- package/dist/{index-ByhlTwxh.d.mts.map → index-BcxxxwhV.d.mts.map} +1 -1
- package/dist/{index-CnZhBlob.d.mts → index-BnB_Ou2y.d.mts} +2 -2
- package/dist/index-BnB_Ou2y.d.mts.map +1 -0
- package/dist/{index-a6JrbAK0.d.mts → index-C-V6CAhP.d.mts} +32 -2
- package/dist/index-C-V6CAhP.d.mts.map +1 -0
- package/dist/{index-DBh3WphX.d.mts → index-CMhkkc56.d.mts} +44 -12
- package/dist/index-CMhkkc56.d.mts.map +1 -0
- package/dist/{index-BGlaws7-.d.mts → index-CYVpYGM-.d.mts} +3 -3
- package/dist/{index-BGlaws7-.d.mts.map → index-CYVpYGM-.d.mts.map} +1 -1
- package/dist/{index-DQ1U3HC3.d.mts → index-DhL7ckvs.d.mts} +7 -7
- package/dist/index-DhL7ckvs.d.mts.map +1 -0
- package/dist/{index-CtKUQ2VG.d.mts → index-DkAjKnhW.d.mts} +1487 -533
- package/dist/index-DkAjKnhW.d.mts.map +1 -0
- package/dist/{index-B08eSpaI.d.mts → index-RILu3ULT.d.mts} +2 -2
- package/dist/{index-B08eSpaI.d.mts.map → index-RILu3ULT.d.mts.map} +1 -1
- package/dist/{index-C5sgRLlG.d.mts → index-TCtdSXd7.d.mts} +3 -1
- package/dist/index-TCtdSXd7.d.mts.map +1 -0
- package/dist/{index-C2yaponf.d.mts → index-s2qQ8ifZ.d.mts} +911 -57
- package/dist/index-s2qQ8ifZ.d.mts.map +1 -0
- package/dist/index.d.mts +15 -15
- package/dist/index.mjs +52 -52
- package/dist/preview/index.d.mts +5 -5
- package/dist/preview/index.mjs +10 -10
- package/dist/preview-BeGF1Bb1.mjs +1002 -0
- package/dist/preview-BeGF1Bb1.mjs.map +1 -0
- package/dist/preview-engine/audio.mjs +1 -1
- package/dist/preview-engine/{chunk-64L4GUOF.mjs → chunk-4F3DG6YB.mjs} +2 -2
- package/dist/preview-engine/chunk-A2OTOW3B.mjs +4694 -0
- package/dist/preview-engine/chunk-BR56TQBP.mjs +5 -0
- package/dist/preview-engine/{chunk-ADLIF544.mjs → chunk-H2XKXXAU.mjs} +1 -1
- package/dist/preview-engine/chunk-NDUODAY2.mjs +3 -0
- package/dist/preview-engine/{chunk-FZ4RD7HV.mjs → chunk-QAQJSWUT.mjs} +1 -1
- package/dist/preview-engine/chunk-SWRGQTVC.mjs +138 -0
- package/dist/preview-engine/{chunk-52X7SURQ.mjs → chunk-TEA3GVBJ.mjs} +1 -1
- package/dist/preview-engine/chunk-VM2ZBPLM.mjs +644 -0
- package/dist/preview-engine/{chunk-UBY2UYEL.mjs → chunk-XSHNQJ7L.mjs} +1 -1
- package/dist/preview-engine/components.mjs +1 -1
- package/dist/preview-engine/effects.mjs +1 -1
- package/dist/preview-engine/fonts.mjs +1 -1
- package/dist/preview-engine/framefields.mjs +1 -1
- package/dist/preview-engine/player.mjs +2 -2
- package/dist/preview-engine/{renderers-DU7KPFVV.mjs → renderers-6C7NWWDX.mjs} +1 -1
- package/dist/preview-engine/renderers-HHVGNMSJ.mjs +206 -0
- package/dist/preview-engine/{src-YXNX4MLK.mjs → src-RCNEKIRP.mjs} +1 -1
- package/dist/preview-page/index.html +19 -0
- package/dist/preview-page/main.css +1 -0
- package/dist/preview-page/main.js +327 -0
- package/dist/{program-BfiB9ttP.mjs → program-CMigyfso.mjs} +919 -58
- package/dist/program-CMigyfso.mjs.map +1 -0
- package/dist/renderer/index.d.mts +4 -4
- package/dist/renderer/index.mjs +2 -2
- package/dist/{renderer-CoC64eam.mjs → renderer-0GMEL_Zi.mjs} +3 -3
- package/dist/{renderer-CoC64eam.mjs.map → renderer-0GMEL_Zi.mjs.map} +1 -1
- package/dist/{renderer-CSu_vYPn.mjs → renderer-3Wv2ZBJG.mjs} +3 -3
- package/dist/{renderer-CSu_vYPn.mjs.map → renderer-3Wv2ZBJG.mjs.map} +1 -1
- package/dist/{renderer-Dv_iRIyx.mjs → renderer-4nXkaAWu.mjs} +1280 -285
- package/dist/renderer-4nXkaAWu.mjs.map +1 -0
- package/dist/{renderer-TfeohPxt.mjs → renderer-6SnfLXeg.mjs} +3 -3
- package/dist/{renderer-TfeohPxt.mjs.map → renderer-6SnfLXeg.mjs.map} +1 -1
- package/dist/{renderer-D0xM67cK.mjs → renderer-8gHw3O0P.mjs} +2 -2
- package/dist/{renderer-D0xM67cK.mjs.map → renderer-8gHw3O0P.mjs.map} +1 -1
- package/dist/{renderer-C64_B8It.mjs → renderer-AOBglZHC.mjs} +2 -2
- package/dist/{renderer-B10HDC13.mjs → renderer-B0bSARK3.mjs} +3 -3
- package/dist/{renderer-B10HDC13.mjs.map → renderer-B0bSARK3.mjs.map} +1 -1
- package/dist/{renderer-DWYmJSrl.mjs → renderer-B2_tuRfl.mjs} +2 -2
- package/dist/{renderer-DWYmJSrl.mjs.map → renderer-B2_tuRfl.mjs.map} +1 -1
- package/dist/{renderer-mDBoz0zT.mjs → renderer-B82FhkEr.mjs} +3 -3
- package/dist/{renderer-mDBoz0zT.mjs.map → renderer-B82FhkEr.mjs.map} +1 -1
- package/dist/{renderer-DYeNNc_G.mjs → renderer-B9lzA0PY.mjs} +3 -3
- package/dist/{renderer-DYeNNc_G.mjs.map → renderer-B9lzA0PY.mjs.map} +1 -1
- package/dist/{renderer-BGchUBW_.mjs → renderer-BBSIWSry.mjs} +2 -2
- package/dist/{renderer-BGchUBW_.mjs.map → renderer-BBSIWSry.mjs.map} +1 -1
- package/dist/{renderer-GIlQ9lZq.mjs → renderer-BEKDMxbi.mjs} +2 -2
- package/dist/{renderer-GIlQ9lZq.mjs.map → renderer-BEKDMxbi.mjs.map} +1 -1
- package/dist/renderer-BERGAxqA.mjs +5 -0
- package/dist/{renderer-Bw0O--gW.mjs → renderer-BF960HY8.mjs} +3 -3
- package/dist/{renderer-Bw0O--gW.mjs.map → renderer-BF960HY8.mjs.map} +1 -1
- package/dist/{renderer-BhcTYhaP.mjs → renderer-BFwyVxCu.mjs} +3 -3
- package/dist/{renderer-BhcTYhaP.mjs.map → renderer-BFwyVxCu.mjs.map} +1 -1
- package/dist/{renderer-DYlx7VHo.mjs → renderer-BNiwcI3-.mjs} +2 -2
- package/dist/{renderer-DYlx7VHo.mjs.map → renderer-BNiwcI3-.mjs.map} +1 -1
- package/dist/{renderer-B3_GddgJ.mjs → renderer-BPbVb2Q4.mjs} +2 -2
- package/dist/{renderer-B3_GddgJ.mjs.map → renderer-BPbVb2Q4.mjs.map} +1 -1
- package/dist/renderer-BQ_YkBMt.mjs +6 -0
- package/dist/{renderer-Y1kjtOto.mjs → renderer-BUWxlA8T.mjs} +3 -3
- package/dist/{renderer-Y1kjtOto.mjs.map → renderer-BUWxlA8T.mjs.map} +1 -1
- package/dist/renderer-BW0Tjsv9.mjs +5 -0
- package/dist/{renderer-DtFZbE1j.mjs → renderer-BX8liu-e.mjs} +2 -2
- package/dist/{renderer-BOlHW3Mi.mjs → renderer-BXIwDAr_.mjs} +2 -2
- package/dist/{renderer-BOlHW3Mi.mjs.map → renderer-BXIwDAr_.mjs.map} +1 -1
- package/dist/{renderer-DzON3wDZ.mjs → renderer-B_Hy1W-g.mjs} +3 -3
- package/dist/{renderer-DzON3wDZ.mjs.map → renderer-B_Hy1W-g.mjs.map} +1 -1
- package/dist/{renderer-BM19iK8v.mjs → renderer-Bb6cvSgh.mjs} +2 -2
- package/dist/{renderer-BM19iK8v.mjs.map → renderer-Bb6cvSgh.mjs.map} +1 -1
- package/dist/{renderer-D0h1hTOo.mjs → renderer-BdppwWC9.mjs} +2 -2
- package/dist/{renderer-D0h1hTOo.mjs.map → renderer-BdppwWC9.mjs.map} +1 -1
- package/dist/{renderer-BTwuM9u-.mjs → renderer-Bhc24HVe.mjs} +3 -3
- package/dist/{renderer-BTwuM9u-.mjs.map → renderer-Bhc24HVe.mjs.map} +1 -1
- package/dist/{renderer-BZX932Lj.mjs → renderer-BiNA2wF0.mjs} +2 -2
- package/dist/{renderer-BZX932Lj.mjs.map → renderer-BiNA2wF0.mjs.map} +1 -1
- package/dist/{renderer-CkTehyRX.mjs → renderer-BmoBgTp5.mjs} +3 -3
- package/dist/{renderer-CkTehyRX.mjs.map → renderer-BmoBgTp5.mjs.map} +1 -1
- package/dist/{renderer-B3un4Pdi.mjs → renderer-BmqFmCWS.mjs} +3 -3
- package/dist/{renderer-B3un4Pdi.mjs.map → renderer-BmqFmCWS.mjs.map} +1 -1
- package/dist/{renderer-CHCRcCKw.mjs → renderer-BnVwAObV.mjs} +2 -2
- package/dist/{renderer-CHCRcCKw.mjs.map → renderer-BnVwAObV.mjs.map} +1 -1
- package/dist/{renderer-Cv9CKKWG.mjs → renderer-BxttZHme.mjs} +2 -2
- package/dist/{renderer-Cv9CKKWG.mjs.map → renderer-BxttZHme.mjs.map} +1 -1
- package/dist/renderer-BzyPdUD1.mjs +5 -0
- package/dist/renderer-C0hM-mtY.mjs +5 -0
- package/dist/renderer-C6cyUTvk.mjs +5 -0
- package/dist/{renderer-B6bK9rXm.mjs → renderer-C8E4XsSg.mjs} +2 -2
- package/dist/{renderer-B6bK9rXm.mjs.map → renderer-C8E4XsSg.mjs.map} +1 -1
- package/dist/renderer-C8zY3pzk.mjs +5 -0
- package/dist/{renderer-4nsuReW2.mjs → renderer-C9U-LY50.mjs} +3 -3
- package/dist/{renderer-4nsuReW2.mjs.map → renderer-C9U-LY50.mjs.map} +1 -1
- package/dist/{renderer-BvBqTAtk.mjs → renderer-CB2JVu5x.mjs} +3 -3
- package/dist/{renderer-BvBqTAtk.mjs.map → renderer-CB2JVu5x.mjs.map} +1 -1
- package/dist/{renderer-CQ4h8n7p.mjs → renderer-CC4YBJ8Z.mjs} +3 -3
- package/dist/{renderer-CQ4h8n7p.mjs.map → renderer-CC4YBJ8Z.mjs.map} +1 -1
- package/dist/renderer-CEkSOyKu.mjs +5 -0
- package/dist/{renderer-zLi2qFGT.mjs → renderer-CIycc5O-.mjs} +2 -2
- package/dist/{renderer-zLi2qFGT.mjs.map → renderer-CIycc5O-.mjs.map} +1 -1
- package/dist/renderer-CJYtfa4x.mjs +5 -0
- package/dist/{renderer-yNWYqvvq.mjs → renderer-CJraQlV-.mjs} +2 -2
- package/dist/{renderer-yNWYqvvq.mjs.map → renderer-CJraQlV-.mjs.map} +1 -1
- package/dist/renderer-CKMtHGZh.mjs +5 -0
- package/dist/renderer-CLzicoiy.mjs +5 -0
- package/dist/renderer-CM2A4BHd.mjs +5 -0
- package/dist/{renderer-BrEeUw7T.mjs → renderer-COWGWtob.mjs} +2 -2
- package/dist/{renderer-BrEeUw7T.mjs.map → renderer-COWGWtob.mjs.map} +1 -1
- package/dist/{renderer-uER8kn7f.mjs → renderer-COxG2XGf.mjs} +2 -2
- package/dist/{renderer-uER8kn7f.mjs.map → renderer-COxG2XGf.mjs.map} +1 -1
- package/dist/{renderer-C4hd6Cqi.mjs → renderer-CQDCIsQm.mjs} +2 -2
- package/dist/{renderer-C4hd6Cqi.mjs.map → renderer-CQDCIsQm.mjs.map} +1 -1
- package/dist/{renderer-Cfx_FCSf.mjs → renderer-CRUeag8i.mjs} +3 -3
- package/dist/{renderer-Cfx_FCSf.mjs.map → renderer-CRUeag8i.mjs.map} +1 -1
- package/dist/{renderer-CXrnzihz.mjs → renderer-CWVput06.mjs} +3 -3
- package/dist/{renderer-CXrnzihz.mjs.map → renderer-CWVput06.mjs.map} +1 -1
- package/dist/renderer-CZlHjcxr.mjs +5 -0
- package/dist/{renderer-BmyFfvVA.mjs → renderer-CbbnBLOB.mjs} +3 -3
- package/dist/{renderer-BmyFfvVA.mjs.map → renderer-CbbnBLOB.mjs.map} +1 -1
- package/dist/renderer-CbimvSU8.mjs +5 -0
- package/dist/renderer-Ccvc63yd.mjs +5 -0
- package/dist/renderer-Cdp-SGfq.mjs +5 -0
- package/dist/renderer-CeTcSs3e.mjs +5 -0
- package/dist/{renderer-_J9JcCMR.mjs → renderer-CfLZein2.mjs} +3 -3
- package/dist/{renderer-_J9JcCMR.mjs.map → renderer-CfLZein2.mjs.map} +1 -1
- package/dist/{renderer-D-mX1EVA.mjs → renderer-Ch-q1O-q.mjs} +3 -3
- package/dist/{renderer-D-mX1EVA.mjs.map → renderer-Ch-q1O-q.mjs.map} +1 -1
- package/dist/{renderer-uzU6dsdR.mjs → renderer-Ch5JvJWl.mjs} +2 -2
- package/dist/{renderer-uzU6dsdR.mjs.map → renderer-Ch5JvJWl.mjs.map} +1 -1
- package/dist/{renderer-BZMh2io2.mjs → renderer-ChtEzq-R.mjs} +2 -2
- package/dist/{renderer-BZMh2io2.mjs.map → renderer-ChtEzq-R.mjs.map} +1 -1
- package/dist/{renderer-B2IUPjhw.mjs → renderer-Cj9nTC5l.mjs} +3 -3
- package/dist/{renderer-B2IUPjhw.mjs.map → renderer-Cj9nTC5l.mjs.map} +1 -1
- package/dist/{renderer-CdXBRdFf.mjs → renderer-CqT8HsSS.mjs} +2 -2
- package/dist/{renderer-CdXBRdFf.mjs.map → renderer-CqT8HsSS.mjs.map} +1 -1
- package/dist/{renderer-CldjJmRR.mjs → renderer-CuQjMhdV.mjs} +2 -2
- package/dist/renderer-CvNuu52U.mjs +5 -0
- package/dist/renderer-CwciC0oI.mjs +5 -0
- package/dist/renderer-CysLUbIr.mjs +5 -0
- package/dist/{renderer-BsrKj6Td.mjs → renderer-Cz30EVws.mjs} +2 -2
- package/dist/{renderer-BsrKj6Td.mjs.map → renderer-Cz30EVws.mjs.map} +1 -1
- package/dist/renderer-D3A22Vxb.mjs +5 -0
- package/dist/renderer-D5SY9EmA.mjs +5 -0
- package/dist/renderer-D8h3ZvaE.mjs +5 -0
- package/dist/renderer-DE-B6N9n.mjs +5 -0
- package/dist/renderer-DETZTI7t.mjs +5 -0
- package/dist/{renderer-CC22Djgi.mjs → renderer-DHoX-5U_.mjs} +3 -3
- package/dist/{renderer-CC22Djgi.mjs.map → renderer-DHoX-5U_.mjs.map} +1 -1
- package/dist/{renderer-HKv5cBdp.mjs → renderer-DOkm0Ycd.mjs} +2 -2
- package/dist/{renderer-HKv5cBdp.mjs.map → renderer-DOkm0Ycd.mjs.map} +1 -1
- package/dist/{renderer-fG8Jy8Rx.d.mts → renderer-DU3f6ZrS.d.mts} +2 -2
- package/dist/{renderer-fG8Jy8Rx.d.mts.map → renderer-DU3f6ZrS.d.mts.map} +1 -1
- package/dist/{renderer-C98XwEIr.mjs → renderer-DUzv-shq.mjs} +2 -2
- package/dist/{renderer-C98XwEIr.mjs.map → renderer-DUzv-shq.mjs.map} +1 -1
- package/dist/renderer-DWnDj0IM.mjs +5 -0
- package/dist/renderer-DcGUIbQF.mjs +5 -0
- package/dist/renderer-Dfq6FoNO.mjs +5 -0
- package/dist/renderer-DhasXW6S.mjs +3 -0
- package/dist/{renderer-BEuXJY-C.mjs → renderer-DhnOWnEA.mjs} +3 -3
- package/dist/{renderer-BEuXJY-C.mjs.map → renderer-DhnOWnEA.mjs.map} +1 -1
- package/dist/{renderer-BIKkxw_Z.mjs → renderer-Dhy1XHzz.mjs} +3 -3
- package/dist/{renderer-BIKkxw_Z.mjs.map → renderer-Dhy1XHzz.mjs.map} +1 -1
- package/dist/renderer-DjCvpsV_.mjs +5 -0
- package/dist/{renderer-pn52dzZz.mjs → renderer-DjJshz9Y.mjs} +2 -2
- package/dist/{renderer-pn52dzZz.mjs.map → renderer-DjJshz9Y.mjs.map} +1 -1
- package/dist/{renderer-DhGZ41hQ.mjs → renderer-DmTUIdus.mjs} +3 -3
- package/dist/{renderer-DhGZ41hQ.mjs.map → renderer-DmTUIdus.mjs.map} +1 -1
- package/dist/{renderer-D_m6Qbsi.mjs → renderer-Dq7AioJa.mjs} +2 -2
- package/dist/{renderer-D_m6Qbsi.mjs.map → renderer-Dq7AioJa.mjs.map} +1 -1
- package/dist/renderer-DrAaM6JD.mjs +5 -0
- package/dist/{renderer-D-GWBoVT.mjs → renderer-Dt4sqNEu.mjs} +2 -2
- package/dist/{renderer-D-GWBoVT.mjs.map → renderer-Dt4sqNEu.mjs.map} +1 -1
- package/dist/{renderer-DCrKEVjb.mjs → renderer-Dtcs4idV.mjs} +3 -3
- package/dist/{renderer-DCrKEVjb.mjs.map → renderer-Dtcs4idV.mjs.map} +1 -1
- package/dist/renderer-Dxlv8LYm.mjs +5 -0
- package/dist/{renderer-CO9vE3sd.mjs → renderer-Gj8SrE2W.mjs} +2 -2
- package/dist/{renderer-CO9vE3sd.mjs.map → renderer-Gj8SrE2W.mjs.map} +1 -1
- package/dist/{renderer-DvHi_wXE.mjs → renderer-KfnXDJS0.mjs} +3 -3
- package/dist/{renderer-DvHi_wXE.mjs.map → renderer-KfnXDJS0.mjs.map} +1 -1
- package/dist/{renderer-7xQmXXMH.mjs → renderer-MXVlg4p5.mjs} +3 -3
- package/dist/{renderer-7xQmXXMH.mjs.map → renderer-MXVlg4p5.mjs.map} +1 -1
- package/dist/{renderer-YONlI6W-.mjs → renderer-N2b6QZ1E.mjs} +3 -3
- package/dist/{renderer-YONlI6W-.mjs.map → renderer-N2b6QZ1E.mjs.map} +1 -1
- package/dist/renderer-Pb43OO2t.mjs +5 -0
- package/dist/{renderer-DNynPM6X.mjs → renderer-Q7gDzm8c.mjs} +2 -2
- package/dist/{renderer-DNynPM6X.mjs.map → renderer-Q7gDzm8c.mjs.map} +1 -1
- package/dist/{renderer-BEhZiOT4.mjs → renderer-RCiANtRV.mjs} +2 -2
- package/dist/{renderer-BEhZiOT4.mjs.map → renderer-RCiANtRV.mjs.map} +1 -1
- package/dist/{renderer-Dm57W73p.mjs → renderer-Sig9nZcI.mjs} +2 -2
- package/dist/renderer-VQbm-cGr.mjs +5 -0
- package/dist/{renderer-DiZkZ0Pr.mjs → renderer-fabBgwQX.mjs} +3 -3
- package/dist/{renderer-DiZkZ0Pr.mjs.map → renderer-fabBgwQX.mjs.map} +1 -1
- package/dist/{renderer-Bw-_GZVw.mjs → renderer-g-0PCNoo.mjs} +3 -3
- package/dist/{renderer-Bw-_GZVw.mjs.map → renderer-g-0PCNoo.mjs.map} +1 -1
- package/dist/{renderer-QbSrnPZU.mjs → renderer-gmHKIbKI.mjs} +3 -3
- package/dist/{renderer-QbSrnPZU.mjs.map → renderer-gmHKIbKI.mjs.map} +1 -1
- package/dist/{renderer-CU6WT5jW.mjs → renderer-kVZwiRoK.mjs} +3 -3
- package/dist/{renderer-CU6WT5jW.mjs.map → renderer-kVZwiRoK.mjs.map} +1 -1
- package/dist/renderer-oPMypDM1.mjs +5 -0
- package/dist/{renderer-CRhEGqW4.mjs → renderer-p7tgxP-A.mjs} +3 -3
- package/dist/{renderer-CRhEGqW4.mjs.map → renderer-p7tgxP-A.mjs.map} +1 -1
- package/dist/{renderer-CO4NGvAh.mjs → renderer-tvYj306A.mjs} +81 -78
- package/dist/renderer-tvYj306A.mjs.map +1 -0
- package/dist/renderer-xvWGpVyp.mjs +5 -0
- package/dist/renderer-zafZbD6Q.mjs +5 -0
- package/dist/{renderers-CP8CFWDs-BufiCyn7.mjs → renderers-CP8CFWDs-DLjtjrwx.mjs} +2 -2
- package/dist/{renderers-CP8CFWDs-BufiCyn7.mjs.map → renderers-CP8CFWDs-DLjtjrwx.mjs.map} +1 -1
- package/dist/sam/index.d.mts +3 -3
- package/dist/sam/index.mjs +1 -1
- package/dist/signals/index.d.mts +5 -5
- package/dist/signals/index.mjs +4 -4
- package/dist/{src-BU6vm9sP-DdTHmCr4.mjs → src-B23p_eh7-Cj6-lvV6.mjs} +293 -6
- package/dist/src-B23p_eh7-Cj6-lvV6.mjs.map +1 -0
- package/dist/{src-DrP7fGJX.mjs → src-CoHAjviq.mjs} +1355 -178
- package/dist/src-CoHAjviq.mjs.map +1 -0
- package/dist/storage/index.mjs +1 -1
- package/package.json +63 -60
- package/dist/dist-CiTgmfUw.mjs.map +0 -1
- package/dist/dist-DtPPPsZV.mjs.map +0 -1
- package/dist/fonts-k5ll8NTE.mjs.map +0 -1
- package/dist/index-C2yaponf.d.mts.map +0 -1
- package/dist/index-C5sgRLlG.d.mts.map +0 -1
- package/dist/index-CnZhBlob.d.mts.map +0 -1
- package/dist/index-CtKUQ2VG.d.mts.map +0 -1
- package/dist/index-DBh3WphX.d.mts.map +0 -1
- package/dist/index-DQ1U3HC3.d.mts.map +0 -1
- package/dist/index-a6JrbAK0.d.mts.map +0 -1
- package/dist/preview-engine/chunk-5ZS46EFB.mjs +0 -5
- package/dist/preview-engine/chunk-N3XTDAL6.mjs +0 -2227
- package/dist/preview-engine/chunk-NCQHOGZK.mjs +0 -3
- package/dist/preview-engine/chunk-PH3UUX6A.mjs +0 -138
- package/dist/preview-engine/chunk-XCPRRMMW.mjs +0 -2462
- package/dist/preview-engine/renderers-ZMMQ7S2A.mjs +0 -228
- package/dist/preview-lHH8Tv4j.mjs +0 -2446
- package/dist/preview-lHH8Tv4j.mjs.map +0 -1
- package/dist/program-BfiB9ttP.mjs.map +0 -1
- package/dist/renderer-0rLmztAv.mjs +0 -5
- package/dist/renderer-B0pjOXFY.mjs +0 -5
- package/dist/renderer-B7J13reL.mjs +0 -5
- package/dist/renderer-BPGIKGgl.mjs +0 -5
- package/dist/renderer-Bv-Artj1.mjs +0 -5
- package/dist/renderer-BvLjbhcL.mjs +0 -5
- package/dist/renderer-By6awWaf.mjs +0 -5
- package/dist/renderer-C0rvsz7m.mjs +0 -5
- package/dist/renderer-CDgud_HB.mjs +0 -5
- package/dist/renderer-CDiRF3bG.mjs +0 -6
- package/dist/renderer-CIIEQd4B.mjs +0 -5
- package/dist/renderer-CJblwOA9.mjs +0 -5
- package/dist/renderer-CNMOXtXE.mjs +0 -5
- package/dist/renderer-CO4NGvAh.mjs.map +0 -1
- package/dist/renderer-COeSeNGg.mjs +0 -5
- package/dist/renderer-CUfElmtZ.mjs +0 -5
- package/dist/renderer-CYh2lFoJ.mjs +0 -5
- package/dist/renderer-CYtVZYMH.mjs +0 -5
- package/dist/renderer-CjxZlkjb.mjs +0 -5
- package/dist/renderer-Cpd6TvTC.mjs +0 -5
- package/dist/renderer-D3ziOPhX.mjs +0 -5
- package/dist/renderer-D5yp74NL.mjs +0 -3
- package/dist/renderer-DL-phtL5.mjs +0 -5
- package/dist/renderer-DSnmYnHg.mjs +0 -5
- package/dist/renderer-DUGfsT-E.mjs +0 -5
- package/dist/renderer-DW5af9x1.mjs +0 -5
- package/dist/renderer-DYMrol1t.mjs +0 -5
- package/dist/renderer-DekeUHaz.mjs +0 -5
- package/dist/renderer-Dt5uyJdZ.mjs +0 -5
- package/dist/renderer-Dv_iRIyx.mjs.map +0 -1
- package/dist/renderer-DwLQAnaK.mjs +0 -5
- package/dist/renderer-IXQP2CWM.mjs +0 -5
- package/dist/renderer-K-Pkw63O.mjs +0 -5
- package/dist/renderer-MPw2KH9P.mjs +0 -5
- package/dist/renderer-RPu8RMav.mjs +0 -5
- package/dist/renderer-dCqxd5N2.mjs +0 -5
- package/dist/renderer-lhjmE-Fp.mjs +0 -5
- package/dist/renderer-u9cmBuvM.mjs +0 -5
- package/dist/renderer-vH12jcpz.mjs +0 -5
- package/dist/src-BU6vm9sP-DdTHmCr4.mjs.map +0 -1
- package/dist/src-DrP7fGJX.mjs.map +0 -1
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import{a as If}from"./chunk-2YJ2EW2B.mjs";import{A as wo,Aa as rl,Da as Yn,Ea as Co,Ja as Xn,Ka as nl,W as Xu,X as Bf,Y as Zu,_ as qu,aa as Ku,ba as Qu,ca as Hn,d as se,ha as To,ua as Mo,va as Ao,w as $u,za as tl}from"./chunk-A2OTOW3B.mjs";import{a as Gn,b as Wn}from"./chunk-3F6JGYSP.mjs";import{a as vo,b as Gu}from"./chunk-JJ7D26WR.mjs";import{a as _r,d as el}from"./chunk-QAQJSWUT.mjs";import{r as Wu,t as Hu,u as Yu}from"./chunk-TEA3GVBJ.mjs";import{$ as Jo,E as Ho,G as qn,I as Yo,J as ur,K as Xo,O as Kn,R as Qn,T as lr,U as Ft,V as Zo,W as qo,X as lt,Y as Ko,_ as Qo,aa as Lt,b as jo,ba as ea,ca as ta,da as ra,ea as na,fa as Gr,ga as ia,ha as oa,ia as aa,ja as sa,ka as ua,l as zo,la as Wr,m as _o,ma as wt,n as Vo,na as la,oa as ca,p as $r,pa as ma,s as Uo,w as $o,x as Go,z as Wo}from"./chunk-XSHNQJ7L.mjs";import{$ as Zn,S as il,X as Oo,a as ir,d as Du,da as ol,e as Un,f as Nt,fa as sr,ga as No,ia as Fo,ja as Lo,ma as Vr,na as Eo,oa as Bo,pa as Ur}from"./chunk-SWRGQTVC.mjs";import{a as Ro}from"./chunk-OGSZZ4JO.mjs";import{a as Do}from"./chunk-LGQSJCKE.mjs";import{a as Po}from"./chunk-BREZX5L5.mjs";import{i as So}from"./chunk-6ISHV73H.mjs";import{c as ju}from"./chunk-CSLSWUUT.mjs";import{d as Io}from"./chunk-2CECZN67.mjs";import{a as ee}from"./chunk-3DXMWDQ3.mjs";import{d as Ju}from"./chunk-OBIJIQCZ.mjs";import{f as Ru,i as Ou,j as Nu,k as Fu,n as Lu}from"./chunk-HOV6DDBZ.mjs";import{h as Eu,j as Bu}from"./chunk-RECQ74RP.mjs";import{f as or}from"./chunk-UE7Y65C3.mjs";import{a as s}from"./chunk-6FULVULN.mjs";import{a as nr,l as Cu,t as jr}from"./chunk-ULOFDFHJ.mjs";import{a as _e}from"./chunk-NDUODAY2.mjs";import{j as ar,y as ko}from"./chunk-4F3DG6YB.mjs";import{a as _u,l as bo,m as zr}from"./chunk-VEDMJBJV.mjs";import{b as go,r as he,t as $n}from"./chunk-QEWDIPJ7.mjs";import{a as Iu}from"./chunk-OGPJTUAL.mjs";import{a as zu}from"./chunk-354GX6IB.mjs";import{c as fo,h as ho}from"./chunk-5RRKGN2U.mjs";import{a as Vu,d as yo,g as xo,j as Uu,o as H}from"./chunk-BDZ3TSOT.mjs";import{b as Vn,d as ut,f as S,g as h}from"./chunk-Y4NIR77Z.mjs";var hp=Vn((cC,fp)=>{h();var Zi=()=>new Proxy(function(){},{get:(e,t)=>t==="__esModule"?!0:t===Symbol.toPrimitive?()=>"":Zi(),apply:()=>Zi(),construct:()=>Zi()});fp.exports=Zi()});var Vp=Vn((SD,_p)=>{h();var no=()=>new Proxy(function(){},{get:(e,t)=>t==="__esModule"?!0:t===Symbol.toPrimitive?()=>"":no(),apply:()=>no(),construct:()=>no()});_p.exports=no()});var Hp=Vn((PD,Wp)=>{h();var oo=()=>new Proxy(function(){},{get:(e,t)=>t==="__esModule"?!0:t===Symbol.toPrimitive?()=>"":oo(),apply:()=>oo(),construct:()=>oo()});Wp.exports=oo()});var Xp=Vn((MD,Yp)=>{h();var ao=()=>new Proxy(function(){},{get:(e,t)=>t==="__esModule"?!0:t===Symbol.toPrimitive?()=>"":ao(),apply:()=>ao(),construct:()=>ao()});Yp.exports=ao()});h();h();h();h();var jf={rotationX:"rotateX",rotationY:"rotateY",rotationZ:"rotateZ"};function ct(e){return jf[e]??e}var zf=e=>!e.source||e.source.type==="keyframe";function Hr(e){let t=[],r=new Map;for(let n of e){if(!zf(n)){t.push(n);continue}let i=r.get(n.prop);if(!i){let a={...n,keyframes:[...n.keyframes??[]]};r.set(n.prop,a),t.push(a);continue}let o=new Map(i.keyframes.map(a=>[a.frame,a]));for(let a of n.keyframes??[])o.set(a.frame,a);i.keyframes=[...o.values()].sort((a,u)=>a.frame-u.frame)}return t}function al(e,t){if(!e)return t;let r=da(e);if(!r||r.name==="none")return t;let{name:n,dir:i,params:o}=r,a=Math.max(0,Math.min(1,t)),u=l=>i==="in"?l(a):i==="out"?1-l(1-a):a<.5?l(a*2)/2:1-l((1-a)*2)/2;switch(n){case"power1":return u(l=>l*l);case"power2":return u(l=>l*l*l);case"power3":return u(l=>l*l*l*l);case"sine":return u(l=>1-Math.cos(l*Math.PI/2));case"circ":return u(l=>1-Math.sqrt(Math.max(0,1-l*l)));case"expo":return u(l=>l===0?0:2**(10*(l-1)));case"back":{let l=o?.[0]??1.70158,c=l+1;return u(m=>c*m*m*m-l*m*m)}case"bounce":{let l=c=>{if(c<.36363636363636365)return 7.5625*c*c;if(c<.7272727272727273){let f=c-.5454545454545454;return 7.5625*f*f+.75}if(c<.9090909090909091){let f=c-.8181818181818182;return 7.5625*f*f+.9375}let p=c-2.625/2.75;return 7.5625*p*p+.984375};return i==="out"?l(a):i==="in"?1-l(1-a):a<.5?(1-l(1-2*a))/2:(1+l(2*a-1))/2}default:return a}}function da(e){if(e){if(typeof e=="object"&&"name"in e&&"dir"in e)return e;if(typeof e=="string"){let t=e.trim(),r=t.match(/^([a-zA-Z0-9]+)(?:\.([a-zA-Z]+))?(?:\(([^)]+)\))?$/);if(r){let l=r[1].toLowerCase(),c=l==="linear"?"none":l,m=(r[2]||"out").toLowerCase(),d="out";m==="in"?d="in":m==="out"?d="out":m==="inout"&&(d="inOut");let p;return r[3]&&(p=r[3].split(",").map(f=>Number.parseFloat(f.trim())).filter(f=>!Number.isNaN(f))),{name:c,dir:d,...p&&p.length>0?{params:p}:{}}}let n=t.indexOf(".");if(n===-1){let l=t.toLowerCase();return{name:l==="linear"?"none":l,dir:"out"}}let i=t.slice(0,n).toLowerCase(),o=i==="linear"?"none":i,a=t.slice(n+1).toLowerCase(),u="out";return a==="in"?u="in":a==="out"?u="out":a==="inout"&&(u="inOut"),{name:o,dir:u}}}}var Q=class e{tracks=[];frameStep;defaultRepeat;defaultYoyo;constructor(t=[]){this.tracks=[...t]}static create(){return new e}static stepped(t=2){return new e().stepped(t)}stepped(t=2){return this.frameStep=Math.max(1,Math.min(24,Math.round(t))),this}static fromTo(t,r,n,i={}){return new e().fromTo(t,r,n,i)}static keys(t,r,n){return new e().keys(t,r,n)}static signal(t,r,n={}){return new e().signal(t,r,n)}static colorSignal(t,r,n){return new e().colorSignal(t,r,n)}static kineticSweep(t=-1,r=1,n=0,i=24,o="power2.out"){return new e().kineticSweep(t,r,n,i,o)}static typewriter(t=0,r=30,n="linear"){return new e().typewriter(t,r,n)}static letterSpacing(t,r,n=0,i=24,o="power2.out"){return new e().letterSpacing(t,r,n,i,o)}static wiggle(t,r={}){return new e().wiggle(t,r)}static spring(t,r={}){return new e().spring(t,r)}static firstMargin(t,r,n={}){return new e().firstMargin(t,r,n)}static strokeWidth(t,r,n={}){return new e().fromTo("strokeWidth",t,r,n)}static rotateX(t,r,n={}){return new e().fromTo("rotateX",t,r,n)}static rotateY(t,r,n={}){return new e().fromTo("rotateY",t,r,n)}static rotateZ(t,r,n={}){return new e().fromTo("rotateZ",t,r,n)}static rotationX(t,r,n={}){return new e().fromTo("rotateX",t,r,n)}static rotationY(t,r,n={}){return new e().fromTo("rotateY",t,r,n)}static rotationZ(t,r,n={}){return new e().fromTo("rotateZ",t,r,n)}static rotation(t,r,n={}){return new e().fromTo("rotation",t,r,n)}static scale(t,r,n={}){return new e().fromTo("scale",t,r,n)}static scaleX(t,r,n={}){return new e().fromTo("scaleX",t,r,n)}static scaleY(t,r,n={}){return new e().fromTo("scaleY",t,r,n)}addTrack(t){return this.tracks.push(t),this}repeat(t=-1,r){let n=r?ct(r):void 0;this.defaultRepeat=t;for(let i of this.tracks)(!n||i.prop===n)&&(i.repeat=t);return this}yoyo(t=!0,r){let n=r?ct(r):void 0;this.defaultYoyo=t;for(let i of this.tracks)(!n||i.prop===n)&&(i.yoyo=t);return this}loop(t={},r){return this.repeat(-1,r),t.yoyo&&this.yoyo(!0,r),this}fromTo(t,r,n,i={}){let o=ct(t),a=i.from??i.start??i.fromFrame??0,u=i.to??i.end??i.toFrame??(i.durationFrames!==void 0?a+i.durationFrames:a+24),l=da(i.ease),c=this.tracks.find(d=>d.prop===o&&(!d.source||d.source.type==="keyframe"));if(!c){let d={id:`${o}_fromTo_${this.tracks.length}`,prop:o,keyframes:[],...this.defaultRepeat!==void 0&&{repeat:this.defaultRepeat},...this.defaultYoyo!==void 0&&{yoyo:this.defaultYoyo}};this.tracks.push(d),c=d}i.repeat!==void 0&&(c.repeat=i.repeat),i.yoyo!==void 0&&(c.yoyo=i.yoyo),i.durationFrames!==void 0&&(c.durationFrames=i.durationFrames);let m=c.id;return c.keyframes.length===0&&a>0&&c.keyframes.push({id:`${m}_k0`,frame:0,value:r}),(c.keyframes.length===0||c.keyframes[c.keyframes.length-1].frame<a)&&c.keyframes.push({id:`${m}_k_${a}`,frame:a,value:r}),c.keyframes.push({id:`${m}_k_${u}`,frame:u,value:n,...l&&{ease:l}}),c.keyframes.sort((d,p)=>d.frame-p.frame),this}keyframe(t,r,n,i){let o=ct(t),a=this.tracks.find(m=>m.prop===o&&(!m.source||m.source.type==="keyframe"));if(!a){let m={id:`${o}_track_${this.tracks.length}`,prop:o,keyframes:[],...this.defaultRepeat!==void 0&&{repeat:this.defaultRepeat},...this.defaultYoyo!==void 0&&{yoyo:this.defaultYoyo}};this.tracks.push(m),a=m}let u=da(i),l={id:`k_${a.keyframes.length}_f${r}`,frame:r,value:n,...u&&{ease:u}},c=a.keyframes.findIndex(m=>m.frame===r);return c>=0?a.keyframes[c]=l:a.keyframes.push(l),a.keyframes.sort((m,d)=>m.frame-d.frame),this}keys(t,r,n){let i=ct(t);for(let[o,a,u]of r)this.keyframe(i,Math.round(o),a,u);if(n){let o=this.tracks.find(a=>a.prop===i&&(!a.source||a.source.type==="keyframe"));o&&(n.repeat!==void 0&&(o.repeat=n.repeat),n.yoyo!==void 0&&(o.yoyo=n.yoyo),n.durationFrames!==void 0&&(o.durationFrames=n.durationFrames))}return this}fadeIn(t=0,r=20,n="power2.out"){return this.fromTo("opacity",0,1,{from:t,to:r,ease:n})}fadeOut(t,r,n="power2.in"){return this.fromTo("opacity",1,0,{from:t,to:r,ease:n})}slideInY(t,r,n=0,i=24,o="power2.out"){return this.fromTo("y",t,r,{from:n,to:i,ease:o})}slideInX(t,r,n=0,i=24,o="power2.out"){return this.fromTo("x",t,r,{from:n,to:i,ease:o})}kineticSweep(t=-1,r=1,n=0,i=24,o="power2.out"){return this.fromTo("offset",t,r,{from:n,to:i,ease:o})}typewriter(t=0,r=30,n="linear"){return this.fromTo("text",0,1,{from:t,to:r,ease:n})}letterSpacing(t,r,n=0,i=24,o="power2.out"){return this.fromTo("letterSpacing",t,r,{from:n,to:i,ease:o})}firstMargin(t,r,n={}){return this.fromTo("firstMargin",t,r,n)}lastMargin(t,r,n={}){return this.fromTo("lastMargin",t,r,n)}baselineShift(t,r,n={}){return this.fromTo("baselineShift",t,r,n)}rotateX(t,r,n={}){return this.fromTo("rotateX",t,r,n)}rotateY(t,r,n={}){return this.fromTo("rotateY",t,r,n)}rotateZ(t,r,n={}){return this.fromTo("rotateZ",t,r,n)}rotationX(t,r,n={}){return this.fromTo("rotateX",t,r,n)}rotationY(t,r,n={}){return this.fromTo("rotateY",t,r,n)}rotationZ(t,r,n={}){return this.fromTo("rotateZ",t,r,n)}scaleX(t,r,n={}){return this.fromTo("scaleX",t,r,n)}scaleY(t,r,n={}){return this.fromTo("scaleY",t,r,n)}scale(t,r,n={}){return this.fromTo("scale",t,r,n)}perspective(t,r,n={}){return this.fromTo("perspective",t,r,n)}translateZ(t,r,n={}){return this.fromTo("translateZ",t,r,n)}tilt3D(t){let r=t.start??t.fromFrame,n=t.end??t.toFrame,i=t.ease,o=t.from??{},a=t.to,u=["rotateX","rotateY","rotateZ","translateZ","perspective"];for(let l of u){let c=a[l];if(c!==void 0){let m=o[l]??0;this.fromTo(l,m,c,{from:r,to:n,fromFrame:r,toFrame:n,ease:i})}}return this}signal(t,r,n={}){let i=ct(t),{handleId:o,inline:a}=Mo(r),u=`${i}_sig_${o}_${this.tracks.length}`,l={type:"signal",inputHandleId:o,multiplier:n.multiplier??1,offset:n.offset??0,smoothingWindowFrames:n.smoothing??0,signalMode:n.mode??"continuous",threshold:n.threshold??.15,accumulateThreshold:n.threshold??.15,debounceFrames:n.debounceFrames??2,channel:n.channel??"primary",...n.clock&&{clock:n.clock}};return a&&Ao(l,a),this.tracks.push({id:u,prop:i,source:l,keyframes:[]}),this}colorSignal(t,r,n){let i=ct(t),{handleId:o,inline:a}=Mo(r),u=`${i}_colorSig_${o}_${this.tracks.length}`,l={type:"signal",inputHandleId:o,multiplier:n.multiplier??1,offset:n.offset??0,smoothingWindowFrames:n.smoothing??0,colorMode:n.colorMode??"interpolate",colorA:n.colorA,colorB:n.colorB,colorThreshold:n.threshold,channel:"primary"};return a&&Ao(l,a),this.tracks.push({id:u,prop:i,source:l,keyframes:[]}),this}wiggle(t,r={}){let n=ct(t),i=`${n}_wiggle_${this.tracks.length}`,o={type:"wiggle",frequency:r.frequency??2,amplitude:r.amplitude??20,octaves:r.octaves??1,seed:r.seed??1234};return this.tracks.push({id:i,prop:n,source:o,keyframes:[]}),this}spring(t,r={}){let n=ct(t),i=`${n}_spring_${this.tracks.length}`,o={type:"springOvershoot",damping:r.damping??12,stiffness:r.stiffness??180,mass:r.mass??1};return this.tracks.push({id:i,prop:n,source:o,keyframes:[]}),this}followPath(t,r={}){let n=r.start??r.fromFrame??0,i=r.end??r.toFrame??60,o=Math.max(1,i-n),a=r.samples??Math.max(8,Math.min(60,Math.round(o/2))),u=t.totalLength??1,l=r.fromProgress??0,c=r.toProgress??1;r.fromDistance!==void 0&&u>0&&(l=r.fromDistance/u),r.toDistance!==void 0&&u>0&&(c=r.toDistance/u);let m=r.autoOrient??!0,d=r.banking??0,p=r.pitchOffset??0,f=r.yawOffset??0,b=r.rollOffset??0,g=!1,y=!1,T=!1,M=[];for(let v=0;v<=a;v++){let x=v/a,A=al(r.ease,x),w=l+A*(c-l),R=Math.round(n+x*o),N=[0,0,0],V=[1,0,0],$=[0,0,0];if(typeof t.getFrameAt=="function"){let P=t.getFrameAt(w);N=P.position,V=P.tangent,$=P.rotation??[0,0,0]}else{let P=t.getPointAt(w);N=P.position,P.tangent&&(V=P.tangent);let G=Math.asin(Math.max(-1,Math.min(1,-V[1])))*(180/Math.PI),X=Math.atan2(V[0],V[2])*(180/Math.PI),U=Math.atan2(V[1],V[0])*(180/Math.PI);$=[G,X,U]}let I=$[0]+p,E=$[1]+f,k=(Math.abs(V[2])<1e-4?Math.atan2(V[1],V[0])*(180/Math.PI):$[2])+b;if(d!==0){let P=Math.min(1,w+.02),G=Math.max(0,w-.02),X=t.getPointAt(P),U=t.getPointAt(G),j=X.tangent??[1,0,0],Z=U.tangent??[1,0,0],ne=Math.atan2(j[0],j[2]),pe=Math.atan2(Z[0],Z[2]),ae=ne-pe;k-=ae*d*57.2958}Math.abs(N[2])>1e-4&&(g=!0),Math.abs(I)>1e-4&&(y=!0),Math.abs(E)>1e-4&&(T=!0),M.push({f:R,x:N[0],y:N[1],z:N[2],rx:I,ry:E,rz:k})}for(let v of M)this.keyframe("x",v.f,v.x),this.keyframe("y",v.f,v.y),g&&this.keyframe("z",v.f,v.z),m&&(this.keyframe("rotateZ",v.f,v.rz),y&&this.keyframe("rotateX",v.f,v.rx),T&&this.keyframe("rotateY",v.f,v.ry));return this}applyTo(t){return t.animation=this.toSpec(),t}merge(...t){return this.tracks=Hr([...this.tracks,...t.flatMap(r=>r.tracks)]),this}static merge(...t){let r=new e;return r.tracks=Hr(t.flatMap(n=>n.tracks)),r}toSpec(){return{tracks:this.tracks,...this.frameStep!==void 0&&{frameStep:this.frameStep}}}toJSON(){return this.toSpec()}},pa=class e extends Q{static camera(){return new e}dolly(t,r,n={}){if(typeof t=="object"){let i=t,o=i.start??i.fromFrame??0,a=i.end??i.toFrame??0;return this.fromTo("cameraZ",i.fromDistance,i.toDistance,{from:o,to:a,ease:i.ease})}return this.fromTo("cameraZ",t,r??t,n)}orbit(t){let r=t.start??t.fromFrame??0,n=t.end??t.toFrame??0;return t.azimuth&&this.fromTo("orbitAzimuth",t.azimuth.from??0,t.azimuth.to,{from:r,to:n,ease:t.ease}),t.elevation&&this.fromTo("orbitElevation",t.elevation.from??0,t.elevation.to,{from:r,to:n,ease:t.ease}),t.radius&&this.fromTo("orbitRadius",t.radius.from??1500,t.radius.to,{from:r,to:n,ease:t.ease}),this}truck(t,r,n={}){return this.fromTo("cameraX",t,r,n)}pedestal(t,r,n={}){return this.fromTo("cameraY",t,r,n)}pan(t,r,n={}){return this.fromTo("cameraYaw",t,r,n)}tilt(t,r,n={}){return this.fromTo("cameraPitch",t,r,n)}roll(t,r,n={}){return this.fromTo("cameraRoll",t,r,n)}rackFocus(t){let r=t.start??t.fromFrame??0,n=t.end??t.toFrame??0;return this.fromTo("focusDistance",t.fromDistance,t.toDistance,{from:r,to:n,ease:t.ease??"power2.inOut"}),t.toFStop!==void 0&&this.fromTo("fStop",t.fromFStop??2.8,t.toFStop,{from:r,to:n,ease:t.ease??"power2.inOut"}),this}handheld(t){let r=t.start??t.fromFrame??0,n=t.end??t.toFrame??0;return this.fromTo("shakeTranslation",0,t.translationAmplitude,{from:r,to:n}),this.fromTo("shakeRotation",0,t.rotationAmplitude,{from:r,to:n}),this}followPath3D(t,r={}){let n=r.start??r.fromFrame??0,i=r.end??r.toFrame??60,o=Math.max(1,i-n),a=r.samples??Math.max(8,Math.min(60,Math.round(o/2))),u=r.mode??(r.target?"lookAtTarget":"leadTarget"),l=r.fromProgress??0,c=r.toProgress??1,m=r.lookAhead??.05;for(let d=0;d<=a;d++){let p=d/a,f=al(r.ease,p),b=l+f*(c-l),g=Math.round(n+p*o),y=[0,0,0],T=[0,0,0];if(typeof t.getFrameAt=="function"){let M=t.getFrameAt(b);y=M.position,T=M.rotation??[0,0,0]}else y=t.getPointAt(b).position;if(this.keyframe("cameraX",g,y[0]),this.keyframe("cameraY",g,y[1]),this.keyframe("cameraZ",g,y[2]),u==="lookAtTarget"){let M=r.target??[y[0],y[1],0];this.keyframe("targetX",g,M[0]),this.keyframe("targetY",g,M[1]),this.keyframe("targetZ",g,M[2])}else if(u==="leadTarget"){let M=Math.min(1,b+m),v=t.getPointAt(M);this.keyframe("targetX",g,v.position[0]),this.keyframe("targetY",g,v.position[1]),this.keyframe("targetZ",g,v.position[2])}else u==="orientAlongPath"&&(this.keyframe("cameraPitch",g,T[0]),this.keyframe("cameraYaw",g,T[1]),this.keyframe("cameraRoll",g,T[2]))}return this}};h();var fa=s.tuple([s.number(),s.number(),s.number()]),sl=e=>typeof e=="function",_f=e=>typeof e=="object"&&e!==null&&typeof e.get=="function",Le=s.union([s.number(),s.array(s.tuple([s.number(),s.number()])).min(1),s.custom(sl),s.custom(_f)]),Jn=s.union([s.tuple([Le,Le,Le]),s.array(s.tuple([s.number(),s.number(),s.number(),s.number()])).min(1),s.custom(sl)]),ul=s.union([s.string(),s.number().int().min(0)]),ll=s.object({clip:ul,weight:Le.optional(),speed:s.number().optional(),timeOffset:s.number().optional(),mask:s.array(s.string()).optional(),loop:s.boolean().optional()}).strict(),cl=s.object({chain:s.tuple([s.string(),s.string(),s.string()]),target:Jn,poleTarget:Jn.optional(),weight:Le.optional()}).strict(),ml=s.object({joint:s.string(),target:Jn,weight:Le.optional(),maxAngleDeg:s.number().min(0).max(180).optional(),axis:fa.optional()}).strict(),dl=s.object({rotateX:Le.optional(),rotateY:Le.optional(),rotateZ:Le.optional(),x:Le.optional(),y:Le.optional(),z:Le.optional(),weight:Le.optional(),mode:s.enum(["additive","rest"]).optional()}).strict(),pl=s.object({joint:s.string(),direction:Jn,weight:Le.optional(),axis:fa.optional()}).strict(),fl=s.object({joint:s.string(),from:s.string(),rotate:s.object({x:s.number().optional(),y:s.number().optional(),z:s.number().optional()}).strict()}).strict(),hl=s.object({joints:s.array(s.string()).min(1),stiffness:s.number().min(0).optional(),damping:s.number().min(0).max(1).optional(),gravity:fa.optional()}).strict(),gl=s.object({clips:s.array(ul).min(1),fps:s.number().min(1).max(120).optional(),seed:s.number().optional(),speedRange:s.tuple([s.number().min(0),s.number().min(0)]).optional(),phase:s.enum(["random","sync"]).optional()}).strict();h();var ha=class e{name;props={};selectors=[];constructor(t){this.name=t}static create(t){return new e(t)}skew(t,r=0){return this.props.skew=t,this.props.skewAxis=r,this}anchor(t,r="character",n=0,i=0){return this.props.anchor={grouping:r,preset:t,anchorX:.5,anchorY:.5,offsetX:n,offsetY:i},this}anchorNormalized(t,r,n="character"){return this.props.anchor={grouping:n,preset:"custom",anchorX:t,anchorY:r,offsetX:0,offsetY:0},this}translateZ(t){return this.props.translateZ=t,this}tilt3D(t=0,r=0,n=0){return this.props.rotationX=t,this.props.rotationY=r,this.props.rotationZ=n,this}rotationX(t){return this.props.rotationX=t,this}rotationY(t){return this.props.rotationY=t,this}rotationZ(t){return this.props.rotationZ=t,this}volumetricFormation(t="cylinder",r=300,n=120,i=360,o=1200,a="y"){return this.props.formation={mode:t,radius:r,pitch:n,totalAngle:i,perspective:o,axis:a},this}lineSpacing(t,r=0){return this.props.lineSpacing=t,this.props.lineAnchor=r,this}lineAnchor(t){return this.props.lineAnchor=t,this}spring(t=180,r=12,n=1,i=0){return this.props.spring={stiffness:t,damping:r,mass:n,initialVelocity:i,overshootMultiplier:1},this}stroke(t,r="#ffffff",n=1){return this.props.stroke={strokeWidth:t,strokeColor:r,strokeAlign:"center",fillOpacity:n,dashOffset:0},this}variableFont(t){return this.props.variableAxes=t,this}chromaticGlitch(t,r=0,n=-t,i=0){return this.props.chromaticGlitch={redShiftX:t,redShiftY:r,blueShiftX:n,blueShiftY:i,sliceProbability:0,sliceAmplitude:0},this}audioSpectrum(t,r=60,n=16e3,i=2.5){return this.props.audioSpectrum={signalChannel:t,minFreqHz:r,maxFreqHz:n,scaleAxis:"scaleY",minScale:.2,maxScale:i,peakDecay:.8},this}longShadow(t=45,r=40,n="#000000",i=.8,o=0,a=16){return this.props.longShadow={angle:t,length:r,color:n,startOpacity:i,endOpacity:o,steps:a},this}particleDissolve(t=0,r=90,n=120){return this.props.particleDissolve={progress:t,dispersalAngle:r,maxDisplacement:n,turbulence:.5,particleSize:2},this}addExpressionSelector(t,r="add"){return this.selectors.push({type:"expression",expression:t,mode:r,amount:1}),this}expressionSelector(t,r="add"){return this.addExpressionSelector(t,r)}x(t){return this.props.x=t,this}y(t){return this.props.y=t,this}scale(t){return this.props.scale=t,this}scaleX(t){return this.props.scaleX=t,this}scaleY(t){return this.props.scaleY=t,this}rotation(t){return this.props.rotation=t,this}opacity(t){return this.props.opacity=t,this}blur(t){return this.props.blur=t,this}fillColor(t){return this.props.fillColor=t,this}build(){return{name:this.name,selectors:this.selectors,props:this.props}}};h();var bl=s.enum(["character","word","line","all"]),yl=s.enum(["center","baseline","bottom_left","bottom_center","bottom_right","top_left","top_center","top_right","custom"]),xl=s.object({grouping:bl.default("character"),preset:yl.default("center"),anchorX:s.number().default(.5),anchorY:s.number().default(.5),offsetX:s.number().default(0),offsetY:s.number().default(0)}),Vf=s.object({skew:s.number().min(-90).max(90),skewAxis:s.number().default(0)}),Uf=s.object({lineSpacing:s.number(),lineAnchor:s.number().min(0).max(1).default(0)}),Sl=s.enum(["planar","vortex","cylinder","helix"]),ga=s.object({mode:Sl.default("planar"),radius:s.number().default(300),pitch:s.number().default(120),totalAngle:s.number().default(360),axis:s.enum(["x","y","z"]).default("y"),perspective:s.number().positive().default(1200)}),$f=s.object({translateZ:s.number().optional(),rotationX:s.number().optional(),rotationY:s.number().optional(),rotationZ:s.number().optional(),formation:ga.optional()}),wl=s.object({stiffness:s.number().positive().default(180),damping:s.number().positive().default(12),mass:s.number().positive().default(1),initialVelocity:s.number().default(0),overshootMultiplier:s.number().min(.5).max(3).default(1)}),Gf=s.object({type:s.literal("expression"),name:s.string().optional(),expression:s.string(),mode:s.enum(["add","subtract","intersect","min","max","difference"]).default("add"),amount:s.number().default(1)}),vl=s.object({strokeWidth:s.number().min(0).default(0),strokeColor:s.string().default("#ffffff"),strokeAlign:s.enum(["center","inside","outside"]).default("center"),fillOpacity:s.number().min(0).max(1).default(1),dashArray:s.tuple([s.number(),s.number()]).optional(),dashOffset:s.number().default(0)}),ba=s.object({direction:s.enum(["left","right","up","down"]).default("left"),velocity:s.number().default(120),loop:s.boolean().default(!0),repeatGap:s.number().default(80),snap:s.object({enabled:s.boolean().default(!1),granularity:s.enum(["character","word","line"]).default("word"),stopIndex:s.number().default(0),decelEase:s.string().default("cubic.out")}).optional()}),kl=s.object({weight:s.number().min(100).max(1e3).optional(),width:s.number().min(50).max(200).optional(),slant:s.number().min(-25).max(25).optional(),italic:s.number().min(0).max(1).optional(),opticalSize:s.number().min(6).max(144).optional()}),Pl=s.object({redShiftX:s.number().default(0),redShiftY:s.number().default(0),blueShiftX:s.number().default(0),blueShiftY:s.number().default(0),sliceProbability:s.number().min(0).max(1).default(0),sliceAmplitude:s.number().default(0)}),Tl=s.object({signalChannel:s.string(),minFreqHz:s.number().default(60),maxFreqHz:s.number().default(16e3),scaleAxis:s.enum(["scaleY","scaleX","scale","y"]).default("scaleY"),minScale:s.number().default(.2),maxScale:s.number().default(2.5),peakDecay:s.number().min(0).max(.99).default(.8)}),Ml=s.object({angle:s.number().default(45),length:s.number().min(0).default(0),color:s.string().default("#000000"),startOpacity:s.number().min(0).max(1).default(.8),endOpacity:s.number().min(0).max(1).default(0),steps:s.number().int().min(4).max(64).default(16)}),Al=s.object({progress:s.number().min(0).max(1).default(0),dispersalAngle:s.number().default(90),maxDisplacement:s.number().default(120),turbulence:s.number().default(.5),particleSize:s.number().default(2)}),Cl=s.object({x:s.number().optional(),y:s.number().optional(),translateZ:s.number().optional(),scale:s.number().optional(),scaleX:s.number().optional(),scaleY:s.number().optional(),rotation:s.number().optional(),rotationX:s.number().optional(),rotationY:s.number().optional(),rotationZ:s.number().optional(),formation:ga.optional(),skew:s.number().optional(),skewAxis:s.number().optional(),tracking:s.number().optional(),lineSpacing:s.number().optional(),lineAnchor:s.number().optional(),anchor:xl.optional(),opacity:s.number().optional(),blur:s.number().optional(),fillColor:s.string().optional(),stroke:vl.optional(),variableAxes:kl.optional(),chromaticGlitch:Pl.optional(),longShadow:Ml.optional(),particleDissolve:Al.optional(),audioSpectrum:Tl.optional(),spring:wl.optional()}),ya=s.object({name:s.string().default("AdvancedAnimator"),selectors:s.array(s.record(s.string(),s.unknown())).default([]),props:Cl});h();h();var Yr=s.object({x:s.number(),y:s.number()}),Dl=s.object({p0:Yr,p1:Yr,p2:Yr,p3:Yr}),Rl=s.discriminatedUnion("type",[s.object({type:s.literal("svg"),d:s.string().min(1,"SVG path string cannot be empty")}),s.object({type:s.literal("bezier"),segments:s.array(Dl).min(1)}),s.object({type:s.literal("ellipse"),cx:s.number(),cy:s.number(),rx:s.number().positive(),ry:s.number().positive(),startAngleDeg:s.number().default(0),endAngleDeg:s.number().default(360)}),s.object({type:s.literal("wave"),startX:s.number(),startY:s.number(),length:s.number().positive(),amplitude:s.number(),frequency:s.number().positive(),phaseDeg:s.number().default(0)})]),cr=s.object({path:Rl,firstMargin:s.number().default(0),lastMargin:s.number().default(0),reversePath:s.boolean().default(!1),perpendicularToPath:s.boolean().default(!0),forceAlignment:s.boolean().default(!1),loop:s.boolean().default(!1),baselineOffset:s.enum(["baseline","center","ascender","descender"]).default("baseline"),baselineShift:s.number().default(0)}),Ol=s.enum(["bar","underscore","block","custom"]),Nl=s.object({enabled:s.boolean().default(!0),style:Ol.default("bar"),customChar:s.string().default("|"),color:s.string().optional(),blinkFrequency:s.number().min(0).default(2),hideOnComplete:s.boolean().default(!1),width:s.number().positive().default(2.5),spacing:s.number().default(3)}),Fl=s.discriminatedUnion("mode",[s.object({mode:s.literal("constant")}),s.object({mode:s.literal("human"),jitter:s.number().min(0).max(1).default(.35),commaPauseMultiplier:s.number().min(1).default(3),sentencePauseMultiplier:s.number().min(1).default(5.5),paragraphPauseMultiplier:s.number().min(1).default(7)})]),Ll=s.object({enabled:s.boolean().default(!1),charset:s.enum(["ascii","alphanumeric","matrix","binary","hex","custom"]).default("alphanumeric"),customCharset:s.string().optional(),scrambleFramesPerChar:s.number().int().min(1).default(8),highlightProbability:s.number().min(0).max(1).default(.25),scrambleColor:s.string().optional()}),ei=s.object({granularity:s.enum(["character","word","line"]).default("character"),cursor:Nl.default({enabled:!0,style:"bar",customChar:"|",blinkFrequency:2,hideOnComplete:!1,width:2.5,spacing:3}),cadence:Fl.default({mode:"human",jitter:.35,commaPauseMultiplier:3,sentencePauseMultiplier:5.5,paragraphPauseMultiplier:7}),scramble:Ll.default({enabled:!1,charset:"alphanumeric",scrambleFramesPerChar:8,highlightProbability:.25}),soundSync:s.boolean().default(!1)}),ti=s.enum(["characters","characters_excluding_spaces","words","lines"]),El=s.enum(["percentage","index"]),Bl=s.enum(["square","ramp_up","ramp_down","triangle","round","smooth"]),ri=s.enum(["add","subtract","intersect","min","max","difference"]),Il=s.object({type:s.literal("range"),start:s.number().default(0),end:s.number().default(1),offset:s.number().default(0),units:El.default("percentage"),basedOn:ti.default("characters"),shape:Bl.default("square"),mode:ri.default("add"),amount:s.number().min(-1).max(1).default(1),easeHigh:s.number().min(-1).max(1).default(0),easeLow:s.number().min(-1).max(1).default(0),randomizeOrder:s.boolean().default(!1),randomSeed:s.number().int().default(12345)}),jl=s.object({type:s.literal("wiggly"),wigglesPerSecond:s.number().positive().default(2),correlation:s.number().min(0).max(1).default(.5),temporalPhaseDeg:s.number().default(0),spatialPhaseDeg:s.number().default(0),minAmount:s.number().min(-1).max(1).default(-1),maxAmount:s.number().min(-1).max(1).default(1),randomSeed:s.number().int().default(42),basedOn:ti.default("characters"),mode:ri.default("intersect")}),zl=s.object({type:s.literal("signal"),signalId:s.string(),multiplier:s.number().default(1),offset:s.number().default(0),phaseSpread:s.number().default(0),basedOn:ti.default("characters"),mode:ri.default("add")}),_l=s.discriminatedUnion("type",[Il,jl,zl]),Vl=s.object({x:s.number().optional(),y:s.number().optional(),z:s.number().optional(),scale:s.number().optional(),scaleX:s.number().optional(),scaleY:s.number().optional(),rotation:s.number().optional(),rotationX:s.number().optional(),rotationY:s.number().optional(),skew:s.number().optional(),skewAxis:s.number().optional(),tracking:s.number().optional(),lineSpacing:s.number().optional(),opacity:s.number().min(0).max(1).optional(),fillColor:s.string().optional(),strokeColor:s.string().optional(),strokeWidth:s.number().min(0).optional(),blur:s.number().min(0).optional(),characterOffset:s.number().int().optional()}),Ul=s.enum(["character","word","line","all"]),$l=s.object({grouping:Ul.default("character"),anchorX:s.number().default(.5),anchorY:s.number().default(.8)}),mr=s.object({name:s.string().default("Animator"),selectors:s.array(_l).min(1),props:Vl,anchor:$l.default({grouping:"character",anchorX:.5,anchorY:.8})}),Wf=s.object({text:s.string(),fontFamily:s.string().default("Inter"),fontSize:s.number().positive().default(24),fontWeight:s.union([s.number(),s.string()]).default(400),fill:s.string().default("#ffffff"),letterSpacing:s.number().default(0),lineHeight:s.number().positive().default(1.2),textAlign:s.enum(["left","center","right"]).default("left"),pathOptions:cr.optional(),typewriter:ei.optional(),animators:s.array(mr).default([])});var xa=class e{options={firstMargin:0,lastMargin:0,reversePath:!1,perpendicularToPath:!0,forceAlignment:!1,loop:!1,baselineOffset:"baseline",baselineShift:0};static fromSvg(t){let r=new e;return r.options.path={type:"svg",d:t},r}static fromBezier(t){let r=new e;return r.options.path={type:"bezier",segments:t},r}static fromCurve(t){return e.fromBezier([t])}static circularBadge(t,r,n){let i=new e;return i.options.path={type:"ellipse",cx:t,cy:r,rx:n,ry:n,startAngleDeg:0,endAngleDeg:360},i.options.loop=!0,i}static ellipse(t,r,n,i,o=0,a=360){let u=new e;return u.options.path={type:"ellipse",cx:t,cy:r,rx:n,ry:i,startAngleDeg:o,endAngleDeg:a},u.options.loop=Math.abs(a-o)>=360,u}static wave(t,r,n,i,o,a=0){let u=new e;return u.options.path={type:"wave",startX:t,startY:r,length:n,amplitude:i,frequency:o,phaseDeg:a},u}firstMargin(t){return this.options.firstMargin=t,this}lastMargin(t){return this.options.lastMargin=t,this}reversePath(t){return this.options.reversePath=t,this}perpendicularToPath(t){return this.options.perpendicularToPath=t,this}forceAlignment(t){return this.options.forceAlignment=t,this}loop(t){return this.options.loop=t,this}baselineOffset(t){return this.options.baselineOffset=t,this}baselineShift(t){return this.options.baselineShift=t,this}build(){return cr.parse(this.options)}},Sa=class e{name="Animator";selectors=[];props={};anchor={grouping:"character",anchorX:.5,anchorY:.8};static create(t){let r=new e;return r.name=t,r}addRangeSelector(t){let r=t.easeHigh??0,n=Math.abs(r)>1?r/100:r,i=t.easeLow??0,o=Math.abs(i)>1?i/100:i;return this.selectors.push({type:"range",start:t.start??0,end:t.end??1,offset:t.offset??0,units:"percentage",basedOn:t.basedOn??"characters",shape:t.shape??"smooth",mode:t.mode??"add",amount:1,easeHigh:Math.max(-1,Math.min(1,n)),easeLow:Math.max(-1,Math.min(1,o)),randomizeOrder:t.randomizeOrder??!1,randomSeed:t.randomSeed??12345}),this}addWigglySelector(t){return this.selectors.push({type:"wiggly",wigglesPerSecond:t.wigglesPerSecond??2,correlation:t.correlation??.5,temporalPhaseDeg:0,spatialPhaseDeg:0,minAmount:t.minAmount??-1,maxAmount:t.maxAmount??1,randomSeed:t.randomSeed??42,basedOn:"characters",mode:t.mode??"intersect"}),this}addSignalSelector(t,r=1,n=0,i=0,o="add"){return this.selectors.push({type:"signal",signalId:t,multiplier:r,offset:i,phaseSpread:n,basedOn:"characters",mode:o}),this}x(t){return this.props.x=t,this}y(t){return this.props.y=t,this}z(t){return this.props.z=t,this}scale(t){return this.props.scale=t,this}scaleX(t){return this.props.scaleX=t,this}scaleY(t){return this.props.scaleY=t,this}rotation(t){return this.props.rotation=t,this}rotationX(t){return this.props.rotationX=t,this}rotationY(t){return this.props.rotationY=t,this}skew(t){return this.props.skew=t,this}skewAxis(t){return this.props.skewAxis=t,this}opacity(t){return this.props.opacity=t,this}blur(t){return this.props.blur=t,this}fill(t){return this.fillColor(t)}fillColor(t){return this.props.fillColor=t,this}strokeColor(t){return this.props.strokeColor=t,this}strokeWidth(t){return this.props.strokeWidth=t,this}tracking(t){return this.props.tracking=t,this}lineSpacing(t){return this.props.lineSpacing=t,this}characterOffset(t){return this.props.characterOffset=t,this}anchorGrouping(t,r=.5,n=.8){return this.anchor={grouping:t,anchorX:r,anchorY:n},this}build(){return mr.parse({name:this.name,selectors:this.selectors,props:this.props,anchor:this.anchor})}};h();h();var Gl=`
|
|
2
|
+
struct CameraUniforms {
|
|
3
|
+
viewMatrix: mat4x4<f32>,
|
|
4
|
+
projMatrix: mat4x4<f32>,
|
|
5
|
+
viewProjMatrix: mat4x4<f32>,
|
|
6
|
+
invViewProjMatrix: mat4x4<f32>,
|
|
7
|
+
cameraPos: vec3<f32>,
|
|
8
|
+
near: f32,
|
|
9
|
+
cameraDir: vec3<f32>,
|
|
10
|
+
far: f32,
|
|
11
|
+
dofParams: vec4<f32>,
|
|
12
|
+
screenParams: vec4<f32>,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
struct ModelUniforms {
|
|
16
|
+
modelMatrix: mat4x4<f32>,
|
|
17
|
+
normalMatrix: mat4x4<f32>,
|
|
18
|
+
colorTint: vec4<f32>,
|
|
19
|
+
params: vec4<f32>, // opacity, borderRadius, twoSided, unused
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
struct GlassUniforms {
|
|
23
|
+
// 0..15: ior, roughness, f0, transmission
|
|
24
|
+
ior: f32,
|
|
25
|
+
roughness: f32,
|
|
26
|
+
f0: f32,
|
|
27
|
+
transmission: f32,
|
|
28
|
+
// 16..31: dispersion, envIntensity, fresnelPower, unused
|
|
29
|
+
dispersion: f32,
|
|
30
|
+
envIntensity: f32,
|
|
31
|
+
fresnelPower: f32,
|
|
32
|
+
_pad0: f32,
|
|
33
|
+
// 32..47: viewportWidth, viewportHeight, unused, unused
|
|
34
|
+
viewportWidth: f32,
|
|
35
|
+
viewportHeight: f32,
|
|
36
|
+
_pad1: f32,
|
|
37
|
+
_pad2: f32,
|
|
38
|
+
// 48..63: tint (r, g, b, a)
|
|
39
|
+
tintColor: vec4<f32>,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
@group(0) @binding(0) var<uniform> camera: CameraUniforms;
|
|
43
|
+
@group(1) @binding(0) var<uniform> model: ModelUniforms;
|
|
44
|
+
@group(2) @binding(0) var<uniform> glass: GlassUniforms;
|
|
45
|
+
@group(3) @binding(0) var backdropSampler: sampler;
|
|
46
|
+
@group(3) @binding(1) var backdropTexture: texture_2d<f32>;
|
|
47
|
+
|
|
48
|
+
struct VertexInput {
|
|
49
|
+
@location(0) position: vec3<f32>,
|
|
50
|
+
@location(1) uv: vec2<f32>,
|
|
51
|
+
@location(2) normal: vec3<f32>,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
struct VertexOutput {
|
|
55
|
+
@builtin(position) clipPos: vec4<f32>,
|
|
56
|
+
@location(0) worldPos: vec3<f32>,
|
|
57
|
+
@location(1) worldNormal: vec3<f32>,
|
|
58
|
+
@location(2) uv: vec2<f32>,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
@vertex
|
|
62
|
+
fn vs_main(in: VertexInput) -> VertexOutput {
|
|
63
|
+
var out: VertexOutput;
|
|
64
|
+
let worldPos4 = model.modelMatrix * vec4<f32>(in.position, 1.0);
|
|
65
|
+
out.worldPos = worldPos4.xyz;
|
|
66
|
+
let normal4 = model.normalMatrix * vec4<f32>(in.normal, 0.0);
|
|
67
|
+
out.worldNormal = normalize(normal4.xyz);
|
|
68
|
+
out.uv = in.uv;
|
|
69
|
+
out.clipPos = camera.viewProjMatrix * worldPos4;
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
@fragment
|
|
74
|
+
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
|
75
|
+
let V = normalize(camera.cameraPos - in.worldPos);
|
|
76
|
+
var N = normalize(in.worldNormal);
|
|
77
|
+
|
|
78
|
+
// Dynamic normal flip for two-sided surfaces viewed from behind
|
|
79
|
+
if (dot(N, V) < 0.0) {
|
|
80
|
+
N = -N;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let NdotV = max(dot(N, V), 0.0001);
|
|
84
|
+
|
|
85
|
+
// 1. Schlick Fresnel Reflectance
|
|
86
|
+
let F = glass.f0 + (1.0 - glass.f0) * pow(1.0 - NdotV, max(1.0, glass.fresnelPower));
|
|
87
|
+
|
|
88
|
+
// 2. Refraction Ray Direction with Chromatic Dispersion
|
|
89
|
+
let ior = max(1.0, glass.ior);
|
|
90
|
+
let disp = max(0.0, glass.dispersion);
|
|
91
|
+
let eta_g = 1.0 / ior;
|
|
92
|
+
let eta_r = 1.0 / max(1.0, ior - disp);
|
|
93
|
+
let eta_b = 1.0 / (ior + disp);
|
|
94
|
+
|
|
95
|
+
let R_refl = reflect(-V, N);
|
|
96
|
+
let R_refr_r = refract(-V, N, eta_r);
|
|
97
|
+
let R_refr_g = refract(-V, N, eta_g);
|
|
98
|
+
let R_refr_b = refract(-V, N, eta_b);
|
|
99
|
+
|
|
100
|
+
let screenUv = in.clipPos.xy / vec2<f32>(glass.viewportWidth, glass.viewportHeight);
|
|
101
|
+
|
|
102
|
+
// 3. Screen-Space Refraction Lookup with Chromatic Aberration Offset
|
|
103
|
+
let refractOffsetScale = 0.035 * (1.0 - glass.roughness * 0.4);
|
|
104
|
+
let uv_r = clamp(screenUv + R_refr_r.xy * refractOffsetScale, vec2<f32>(0.001), vec2<f32>(0.999));
|
|
105
|
+
let uv_g = clamp(screenUv + R_refr_g.xy * refractOffsetScale, vec2<f32>(0.001), vec2<f32>(0.999));
|
|
106
|
+
let uv_b = clamp(screenUv + R_refr_b.xy * refractOffsetScale, vec2<f32>(0.001), vec2<f32>(0.999));
|
|
107
|
+
|
|
108
|
+
// Roughness mip/jitter level
|
|
109
|
+
let mipLevel = glass.roughness * 5.0;
|
|
110
|
+
let sampleR = textureSampleLevel(backdropTexture, backdropSampler, uv_r, mipLevel).r;
|
|
111
|
+
let sampleG = textureSampleLevel(backdropTexture, backdropSampler, uv_g, mipLevel).g;
|
|
112
|
+
let sampleB = textureSampleLevel(backdropTexture, backdropSampler, uv_b, mipLevel).b;
|
|
113
|
+
|
|
114
|
+
let transmittedColor = vec3<f32>(sampleR, sampleG, sampleB) * glass.tintColor.rgb * model.colorTint.rgb;
|
|
115
|
+
|
|
116
|
+
// 4. Procedural Studio HDRI Environment Reflection (Warm key + cool rim highlights)
|
|
117
|
+
let envAngle = atan2(R_refl.z, R_refl.x);
|
|
118
|
+
let envElevation = R_refl.y;
|
|
119
|
+
let studioKey = pow(max(0.0, dot(R_refl, normalize(vec3<f32>(0.6, 0.8, -0.5)))), 32.0) * 1.5;
|
|
120
|
+
let studioRim = pow(max(0.0, dot(R_refl, normalize(vec3<f32>(-0.7, 0.3, 0.6)))), 16.0) * 0.8;
|
|
121
|
+
let ambientSky = mix(vec3<f32>(0.92, 0.94, 0.98), vec3<f32>(0.98, 0.96, 0.92), envElevation * 0.5 + 0.5);
|
|
122
|
+
let envColor = (ambientSky * 0.6 + vec3<f32>(1.0, 0.98, 0.95) * studioKey + vec3<f32>(0.85, 0.92, 1.0) * studioRim) * glass.envIntensity;
|
|
123
|
+
|
|
124
|
+
// 5. Energy-Conserving Blend with Premultiplied Alpha
|
|
125
|
+
let blendedRGB = mix(transmittedColor, envColor, F);
|
|
126
|
+
let alpha = clamp((F + (1.0 - glass.transmission) * 0.6) * model.params.x, 0.0, 1.0);
|
|
127
|
+
|
|
128
|
+
return vec4<f32>(blendedRGB * alpha, alpha);
|
|
129
|
+
}
|
|
130
|
+
`;var wa=class{device;pipeline;cameraLayout;modelLayout;glassLayout;backdropLayout;modelPool;glassPool;vertexBuffer;indexBuffer;modelData=new Float32Array(40);glassData=new Float32Array(16);constructor(t,r,n="depth24plus",i){this.device=t,this.modelPool=new ko(160,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),this.glassPool=new ko(64,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST);let o=t.createShaderModule({label:"pbr-glass.wgsl",code:Gl});this.cameraLayout=i??t.createBindGroupLayout({label:"GlassCameraLayout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.modelLayout=t.createBindGroupLayout({label:"GlassModelLayout",entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.glassLayout=t.createBindGroupLayout({label:"GlassUniformLayout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.backdropLayout=t.createBindGroupLayout({label:"GlassBackdropLayout",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}]});let a=t.createPipelineLayout({bindGroupLayouts:[this.cameraLayout,this.modelLayout,this.glassLayout,this.backdropLayout]});this.pipeline=t.createRenderPipeline({label:"PBRGlassPipeline",layout:a,vertex:{module:o,entryPoint:"vs_main",buffers:[{arrayStride:32,attributes:[{shaderLocation:0,offset:0,format:"float32x3"},{shaderLocation:1,offset:12,format:"float32x2"},{shaderLocation:2,offset:20,format:"float32x3"}]}]},fragment:{module:o,entryPoint:"fs_main",targets:[{format:r,blend:Yu}]},depthStencil:{format:n,depthWriteEnabled:!0,depthCompare:"less-equal"},primitive:{topology:"triangle-list",cullMode:"none"}});let u=new Float32Array([-.5,-.5,0,0,0,0,0,-1,.5,-.5,0,1,0,0,0,-1,.5,.5,0,1,1,0,0,-1,-.5,.5,0,0,1,0,0,-1]),l=new Uint16Array([0,1,2,0,2,3]);this.vertexBuffer=t.createBuffer({size:u.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),new Float32Array(this.vertexBuffer.getMappedRange()).set(u),this.vertexBuffer.unmap(),this.indexBuffer=t.createBuffer({size:l.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),new Uint16Array(this.indexBuffer.getMappedRange()).set(l),this.indexBuffer.unmap()}resetPools(){this.modelPool.reset(),this.glassPool.reset()}draw(t,r,n,i,o){Xu(this.modelData,o.modelMatrix,o.normalMatrix,o.colorTint),this.modelData[36]=o.opacity??1,this.modelData[37]=0,this.modelData[38]=1,this.modelData[39]=0;let a=this.modelPool.getBuffer(this.device,this.modelData);this.glassData[0]=o.ior??1.49,this.glassData[1]=o.roughness??.15,this.glassData[2]=o.f0??.04,this.glassData[3]=o.transmission??.92,this.glassData[4]=o.dispersion??.015,this.glassData[5]=o.envIntensity??.65,this.glassData[6]=o.fresnelPower??5,this.glassData[7]=0,this.glassData[8]=o.viewportWidth,this.glassData[9]=o.viewportHeight,this.glassData[10]=0,this.glassData[11]=0;let u=o.tintColor??[1,1,1,1];this.glassData[12]=u[0],this.glassData[13]=u[1],this.glassData[14]=u[2],this.glassData[15]=u[3];let l=this.glassPool.getBuffer(this.device,this.glassData),c=this.device.createBindGroup({layout:this.modelLayout,entries:[{binding:0,resource:{buffer:a}}]}),m=this.device.createBindGroup({layout:this.glassLayout,entries:[{binding:0,resource:{buffer:l}}]}),d=this.device.createBindGroup({layout:this.backdropLayout,entries:[{binding:0,resource:i},{binding:1,resource:n.createView()}]});t.setPipeline(this.pipeline),t.setBindGroup(0,r),t.setBindGroup(1,c),t.setBindGroup(2,m),t.setBindGroup(3,d),t.setVertexBuffer(0,this.vertexBuffer),t.setIndexBuffer(this.indexBuffer,"uint16"),t.drawIndexed(6)}destroy(){this.modelPool.destroy(),this.glassPool.destroy(),this.vertexBuffer.destroy(),this.indexBuffer.destroy()}};h();var va=class{shadowDepthTexture;shadowDepthView;shadowComparisonSampler;lightViewProjMatrix;constructor(t,r=2048){this.lightViewProjMatrix=se.identity(),this.shadowDepthTexture=t.createTexture({label:"shadow-depth-map",size:[r,r,1],format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.shadowDepthView=this.shadowDepthTexture.createView({label:"shadow-depth-view"}),this.shadowComparisonSampler=t.createSampler({label:"shadow-pcf-sampler",compare:"less-equal",magFilter:"linear",minFilter:"linear"})}computeDirectionalLightMatrix(t,r,n=2e3,i=10,o=4e3){let a=se.lookAt(t,r,[0,1,0]),u=n*.5,l=se.orthographic(-u,u,-u,u,i,o);return this.lightViewProjMatrix=se.multiply(l,a),this.lightViewProjMatrix}destroy(){this.shadowDepthTexture.destroy()}};h();h();var Wl=`
|
|
131
|
+
struct SSAOUniforms {
|
|
132
|
+
projMatrix: mat4x4<f32>,
|
|
133
|
+
invProjMatrix: mat4x4<f32>,
|
|
134
|
+
viewMatrix: mat4x4<f32>,
|
|
135
|
+
radius: f32,
|
|
136
|
+
bias: f32,
|
|
137
|
+
intensity: f32,
|
|
138
|
+
sampleCount: u32,
|
|
139
|
+
viewportWidth: f32,
|
|
140
|
+
viewportHeight: f32,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
@group(0) @binding(0) var depthTexture: texture_depth_2d;
|
|
144
|
+
@group(0) @binding(1) var normalTexture: texture_2d<f32>;
|
|
145
|
+
@group(0) @binding(2) var noiseTexture: texture_2d<f32>;
|
|
146
|
+
@group(0) @binding(3) var colorSampler: sampler;
|
|
147
|
+
@group(0) @binding(4) var<storage, read> kernelSamples: array<vec4<f32>>;
|
|
148
|
+
@group(0) @binding(5) var<uniform> u: SSAOUniforms;
|
|
149
|
+
|
|
150
|
+
@vertex
|
|
151
|
+
fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4<f32> {
|
|
152
|
+
var pos = array<vec2<f32>, 4>(
|
|
153
|
+
vec2<f32>(-1.0, -1.0),
|
|
154
|
+
vec2<f32>( 1.0, -1.0),
|
|
155
|
+
vec2<f32>(-1.0, 1.0),
|
|
156
|
+
vec2<f32>( 1.0, 1.0)
|
|
157
|
+
);
|
|
158
|
+
return vec4<f32>(pos[vertexIndex], 0.0, 1.0);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
fn reconstructViewPos(uv: vec2<f32>, depth: f32) -> vec3<f32> {
|
|
162
|
+
let clipPos = vec4<f32>(uv.x * 2.0 - 1.0, (1.0 - uv.y) * 2.0 - 1.0, depth, 1.0);
|
|
163
|
+
let viewPos = u.invProjMatrix * clipPos;
|
|
164
|
+
return viewPos.xyz / viewPos.w;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
@fragment
|
|
168
|
+
fn fs_ssao(@builtin(position) pos: vec4<f32>) -> @location(0) f32 {
|
|
169
|
+
let uv = pos.xy / vec2<f32>(u.viewportWidth, u.viewportHeight);
|
|
170
|
+
let depth = textureSampleLevel(depthTexture, colorSampler, uv, 0);
|
|
171
|
+
|
|
172
|
+
if (depth >= 1.0) {
|
|
173
|
+
return 1.0;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
let rawNormal = textureSampleLevel(normalTexture, colorSampler, uv, 0.0).xyz;
|
|
177
|
+
let normal = normalize(rawNormal * 2.0 - 1.0);
|
|
178
|
+
let viewPos = reconstructViewPos(uv, depth);
|
|
179
|
+
|
|
180
|
+
let noiseUV = pos.xy / 4.0;
|
|
181
|
+
let randomVec = normalize(textureSampleLevel(noiseTexture, colorSampler, noiseUV, 0.0).xyz * 2.0 - 1.0);
|
|
182
|
+
|
|
183
|
+
let tangent = normalize(randomVec - normal * dot(randomVec, normal));
|
|
184
|
+
let bitangent = cross(normal, tangent);
|
|
185
|
+
let TBN = mat3x3<f32>(tangent, bitangent, normal);
|
|
186
|
+
|
|
187
|
+
var occlusion = 0.0;
|
|
188
|
+
let count = min(u.sampleCount, arrayLength(&kernelSamples));
|
|
189
|
+
|
|
190
|
+
for (var i = 0u; i < count; i = i + 1u) {
|
|
191
|
+
let sampleDir = TBN * kernelSamples[i].xyz;
|
|
192
|
+
let samplePos = viewPos + sampleDir * u.radius;
|
|
193
|
+
|
|
194
|
+
let offset = u.projMatrix * vec4<f32>(samplePos, 1.0);
|
|
195
|
+
var sampleUV = vec2<f32>(
|
|
196
|
+
(offset.x / offset.w) * 0.5 + 0.5,
|
|
197
|
+
(1.0 - (offset.y / offset.w)) * 0.5
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
if (sampleUV.x < 0.0 || sampleUV.x > 1.0 || sampleUV.y < 0.0 || sampleUV.y > 1.0) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let sampleDepthVal = textureSampleLevel(depthTexture, colorSampler, sampleUV, 0);
|
|
205
|
+
let sampleViewZ = reconstructViewPos(sampleUV, sampleDepthVal).z;
|
|
206
|
+
|
|
207
|
+
let rangeCheck = smoothstep(0.0, 1.0, u.radius / max(abs(viewPos.z - sampleViewZ), 0.001));
|
|
208
|
+
if (sampleViewZ >= samplePos.z + u.bias) {
|
|
209
|
+
occlusion += rangeCheck;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
let ao = 1.0 - (occlusion / f32(max(count, 1u))) * u.intensity;
|
|
214
|
+
return clamp(ao, 0.0, 1.0);
|
|
215
|
+
}
|
|
216
|
+
`,Hl=`
|
|
217
|
+
struct BlurUniforms {
|
|
218
|
+
viewportWidth: f32,
|
|
219
|
+
viewportHeight: f32,
|
|
220
|
+
blurRadius: i32,
|
|
221
|
+
depthThreshold: f32,
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
@group(0) @binding(0) var ssaoTexture: texture_2d<f32>;
|
|
225
|
+
@group(0) @binding(1) var depthTexture: texture_depth_2d;
|
|
226
|
+
@group(0) @binding(2) var colorSampler: sampler;
|
|
227
|
+
@group(0) @binding(3) var<uniform> u: BlurUniforms;
|
|
228
|
+
|
|
229
|
+
@vertex
|
|
230
|
+
fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4<f32> {
|
|
231
|
+
var pos = array<vec2<f32>, 4>(
|
|
232
|
+
vec2<f32>(-1.0, -1.0),
|
|
233
|
+
vec2<f32>( 1.0, -1.0),
|
|
234
|
+
vec2<f32>(-1.0, 1.0),
|
|
235
|
+
vec2<f32>( 1.0, 1.0)
|
|
236
|
+
);
|
|
237
|
+
return vec4<f32>(pos[vertexIndex], 0.0, 1.0);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
@fragment
|
|
241
|
+
fn fs_blur(@builtin(position) pos: vec4<f32>) -> @location(0) f32 {
|
|
242
|
+
let uv = pos.xy / vec2<f32>(u.viewportWidth, u.viewportHeight);
|
|
243
|
+
let centerDepth = textureSampleLevel(depthTexture, colorSampler, uv, 0);
|
|
244
|
+
let centerAO = textureSampleLevel(ssaoTexture, colorSampler, uv, 0.0).r;
|
|
245
|
+
|
|
246
|
+
if (centerDepth >= 1.0) {
|
|
247
|
+
return 1.0;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
var result = 0.0;
|
|
251
|
+
var totalWeight = 0.0;
|
|
252
|
+
let texelSize = 1.0 / vec2<f32>(u.viewportWidth, u.viewportHeight);
|
|
253
|
+
let r = u.blurRadius;
|
|
254
|
+
|
|
255
|
+
for (var x = -r; x <= r; x = x + 1) {
|
|
256
|
+
for (var y = -r; y <= r; y = y + 1) {
|
|
257
|
+
let offsetUV = uv + vec2<f32>(f32(x), f32(y)) * texelSize;
|
|
258
|
+
let sampleDepth = textureSampleLevel(depthTexture, colorSampler, offsetUV, 0);
|
|
259
|
+
let depthDelta = abs(sampleDepth - centerDepth);
|
|
260
|
+
|
|
261
|
+
let spatialW = exp(-f32(x * x + y * y) / f32(2 * r * r));
|
|
262
|
+
let depthW = clamp(1.0 - depthDelta / max(u.depthThreshold, 0.0001), 0.0, 1.0);
|
|
263
|
+
let w = spatialW * depthW;
|
|
264
|
+
|
|
265
|
+
let sampleAO = textureSampleLevel(ssaoTexture, colorSampler, offsetUV, 0.0).r;
|
|
266
|
+
result += sampleAO * w;
|
|
267
|
+
totalWeight += w;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (totalWeight <= 0.0) {
|
|
272
|
+
return centerAO;
|
|
273
|
+
}
|
|
274
|
+
return result / totalWeight;
|
|
275
|
+
}
|
|
276
|
+
`;var ka=class{device;ssaoPipeline;blurPipeline;ssaoBindGroupLayout;blurBindGroupLayout;ssaoUniformBuffer;blurUniformBuffer;kernelBuffer;noiseTexture;sampler;constructor(t){this.device=t,this.noiseTexture=t.createTexture({label:"ssao-noise-tex",size:[4,4,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});let r=new Uint8Array(64);for(let a=0;a<16;a++)r[a*4+0]=Math.floor(Math.random()*255),r[a*4+1]=Math.floor(Math.random()*255),r[a*4+2]=128,r[a*4+3]=255;t.queue.writeTexture({texture:this.noiseTexture},r,{bytesPerRow:16},[4,4,1]);let n=new Float32Array(128);for(let a=0;a<32;a++){let u=Math.random(),l=Math.random(),c=Math.acos(Math.sqrt(1-u)),m=2*Math.PI*l,d=(a+1)/32;d=.1+.9*(d*d),n[a*4+0]=Math.sin(c)*Math.cos(m)*d,n[a*4+1]=Math.sin(c)*Math.sin(m)*d,n[a*4+2]=Math.cos(c)*d,n[a*4+3]=0}this.kernelBuffer=t.createBuffer({label:"ssao-kernel-buffer",size:n.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this.kernelBuffer,0,n);let i=t.createShaderModule({label:"ssao-shader",code:Wl});this.ssaoBindGroupLayout=t.createBindGroupLayout({label:"ssao-bgl",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:4,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}},{binding:5,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.ssaoPipeline=t.createRenderPipeline({label:"ssao-eval-pipeline",layout:t.createPipelineLayout({bindGroupLayouts:[this.ssaoBindGroupLayout]}),vertex:{module:i,entryPoint:"vs_main"},fragment:{module:i,entryPoint:"fs_ssao",targets:[{format:"r8unorm"}]},primitive:{topology:"triangle-strip"}}),this.ssaoUniformBuffer=t.createBuffer({label:"ssao-uniforms",size:256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let o=t.createShaderModule({label:"ssao-blur-shader",code:Hl});this.blurBindGroupLayout=t.createBindGroupLayout({label:"ssao-blur-bgl",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this.blurPipeline=t.createRenderPipeline({label:"ssao-blur-pipeline",layout:t.createPipelineLayout({bindGroupLayouts:[this.blurBindGroupLayout]}),vertex:{module:o,entryPoint:"vs_main"},fragment:{module:o,entryPoint:"fs_blur",targets:[{format:"r8unorm"}]},primitive:{topology:"triangle-strip"}}),this.blurUniformBuffer=t.createBuffer({label:"ssao-blur-uniforms",size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.sampler=t.createSampler({label:"ssao-sampler",magFilter:"linear",minFilter:"linear",addressModeU:"repeat",addressModeV:"repeat"})}render(t,r,n,i,o,a){let u=a.invProjMatrix??se.invert(a.projMatrix)??se.identity(),l=new Float32Array(64);l.set(a.projMatrix,0),l.set(u,16),l.set(a.viewMatrix,32),l[48]=a.radius??45,l[49]=a.bias??.025,l[50]=a.intensity??1.5,new Uint32Array(l.buffer)[51]=a.kernelSamples??16,l[52]=a.width,l[53]=a.height,this.device.queue.writeBuffer(this.ssaoUniformBuffer,0,l);let c=this.device.createBindGroup({label:"ssao-eval-bg",layout:this.ssaoBindGroupLayout,entries:[{binding:0,resource:r},{binding:1,resource:n},{binding:2,resource:this.noiseTexture.createView()},{binding:3,resource:this.sampler},{binding:4,resource:{buffer:this.kernelBuffer}},{binding:5,resource:{buffer:this.ssaoUniformBuffer}}]}),m=t.beginRenderPass({label:"ssao-eval-pass",colorAttachments:[{view:i,loadOp:"clear",storeOp:"store",clearValue:{r:1,g:1,b:1,a:1}}]});m.setPipeline(this.ssaoPipeline),m.setBindGroup(0,c),m.draw(4),m.end();let d=new ArrayBuffer(32),p=new Float32Array(d),f=new Int32Array(d);p[0]=a.width,p[1]=a.height,f[2]=a.blurRadius??4,p[3]=a.depthThreshold??.05,this.device.queue.writeBuffer(this.blurUniformBuffer,0,d);let b=this.device.createBindGroup({label:"ssao-blur-bg",layout:this.blurBindGroupLayout,entries:[{binding:0,resource:i},{binding:1,resource:r},{binding:2,resource:this.sampler},{binding:3,resource:{buffer:this.blurUniformBuffer}}]}),g=t.beginRenderPass({label:"ssao-blur-pass",colorAttachments:[{view:o,loadOp:"clear",storeOp:"store",clearValue:{r:1,g:1,b:1,a:1}}]});g.setPipeline(this.blurPipeline),g.setBindGroup(0,b),g.draw(4),g.end()}destroy(){this.ssaoUniformBuffer.destroy(),this.blurUniformBuffer.destroy(),this.noiseTexture.destroy()}};h();var Hf=["background","fill","fillColor","strokeColor","borderColor","gradientEndColor","emissive","color"],Yl=2e3;function Yf(e){for(let{segment:t}of Xf().segment(e))if(Iu(t)==="emoji")return!0;return!1}var Xl;function Xf(){return Xl??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Xl}function Zf(e){let t=e.spans??[];return[e.text,...t.map(r=>r.text)].filter(r=>typeof r=="string").join("")}var qf=new Set(["directional","spot","point","rect"]),Zl=3;function Pa(e){return e.animation?.tracks??[]}var ii=(e,t)=>Pa(e).some(r=>t.includes(r.prop)),Kf=new Set(["box","flex","block","group"]);function ql(e){if(e.kind==="text"||e.kind==="light"||e.kind==="camera")return!1;if(!Kf.has(String(e.kind)))return!0;let t=e.background;return typeof t=="string"&&t!==""&&t!=="transparent"?!0:(e.children??[]).some(ql)}var Qf=e=>[...e].sort((t,r)=>(Number(t.zIndex)||0)-(Number(r.zIndex)||0));function ni(e){if(typeof e!="string"||e.includes("gradient("))return null;let t=fo(e);return t&&t[3]>.99?e:null}function Jf(e,t,r){let n=e.lens,i=n?.projection??"perspective";i==="perspective"&&(n?.fov??0)>160&&r("error","camera_fov_range",`'${t}' has a ${n?.fov}\xB0 perspective lens: perspective goes up to 160\xB0. Use projection "fisheye" for wider views.`,t);let o=e.relativity,a=i!=="perspective"||(o?.speed??0)>0||ii(e,["relativitySpeed"]),u=e.dof;return a&&(u?.enabled||ii(e,["focusDistance"]))&&r("error","camera_cube_dof",`'${t}' is a cube camera (${o?"relativity":i}) with depth of field: depth of field needs a single perspective view.`,t),a&&e.motionBlur&&r("error","camera_cube_motion_blur",`'${t}' is a cube camera (${o?"relativity":i}) with motionBlur: shutter motion blur needs a single perspective view.`,t),a}function Ta(e,t={}){let r=[],n=(v,x,A,w)=>r.push({severity:v,code:x,message:A,...w&&{layerId:w}}),i=e.width,o=e.height,a=!1,u=[],l=!1,c=[],m=[],d=new Set,p=0,f,b,g,y=(v,x,A)=>{let w=String(v.id??"?");typeof v.id=="string"&&(d.has(v.id)&&n("error","duplicate_id",`Two layers share the id '${w}': the renderer keeps one and drops the other. Give every layer its own id (scenes reused in one composition need their own prefix).`,w),d.add(v.id)),t.emojiFont===!1&&v.kind==="text"&&Yf(Zf(v))&&m.push(w);for(let k of Hf){let P=v[k];typeof P!="string"||P===""||P==="transparent"||(P.includes("gradient(")?ju(P)||n("error","invalid_gradient",`\`${k}\` on '${w}' is not a gradient this renderer reads: ${P}. It draws nothing.`,w):fo(P)||n("warning","unknown_color",`\`${k}: "${P}"\` on '${w}' is not a color (hex, rgb(), hsl(), oklch() or a CSS name). It draws transparent.`,w))}if(v.kind==="light"){let k=v.lightType??"directional";k==="environment"&&(a=!0),k==="ambient"&&u.push(w),qf.has(String(k))&&p++,k==="environment"&&v.volumetricFog&&(f=w),k==="environment"&&(v.ssr||v.gi)&&(g=w),v.castShadow&&k!=="directional"&&k!=="spot"&&k!=="point"&&k!=="rect"&&n("warning","shadow_unsupported_light",`'${w}' is a ${String(k)} light: only directional, spot, point, and rect lights cast shadows.`,w);return}if(v.kind==="camera"){Jf(v,w,n)&&(b=w);return}if(v.kind==="media"){let k=v.inputHandleId;typeof k=="string"&&(v.dataType??"Video")==="Image"&&(/\.(json|lottie)(\?.*)?$/i.test(k)?n("error","unsupported_image_format",`'${w}' is an image layer with source '${k}', which is a Lottie vector animation. Use Layer.lottie() instead.`,w):/\.(mp4|mov|webm|mkv)(\?.*)?$/i.test(k)?n("error","unsupported_image_format",`'${w}' is an image layer with video source '${k}'. Use Layer.video() instead.`,w):/\.(mp3|wav|ogg|m4a|aac)(\?.*)?$/i.test(k)&&n("error","unsupported_image_format",`'${w}' is an image layer with audio source '${k}'. Use Layer.audio() instead.`,w))}let R=!!v.is3D||typeof v.z=="number"&&v.z!==0;(R||v.kind==="model3d")&&(l=!0);let N=v.scatter3d;if(N&&N.count>0&&t.scatterCoverage?.(N)===0&&n("warning","scatter_filters_reject_all",`'${w}' scatters onto a surface its slopeRange / elevationRange filters reject entirely, so no instance is placed. Widen the ranges (slope is degrees from level, elevation 0..1 from the surface's lowest to highest point).`,w),(v.roughness!==void 0||v.metallic!==void 0||v.clearcoat!==void 0||v.anisotropy!==void 0)&&c.push(w),v.kind==="text"&&x&&!ii(v,["fill","color"])){let k=ni(v.fill??v.color),P=ni(v.background)??x;if(k){let G=ho.contrast(k,P);G<Zl&&n("warning","low_contrast_text",`Text '${w}' (${k}) on ${P} has contrast ${G.toFixed(2)}:1 (aim for \u2265 ${Zl}; ${ho.readableOn(P)} reads well).`,w)}}if(A&&!R&&v.position==="absolute"&&typeof v.x=="number"&&typeof v.y=="number"&&typeof v.width=="number"&&typeof v.height=="number"&&!ii(v,["x","y","translateX","translateY","scale","scaleX","scaleY","rotation"])){let{x:k,y:P,width:G,height:X}=v;(k+G<=0||P+X<=0||k>=i||P>=o)&&n("warning","offscreen_layer",`'${w}' sits entirely outside the ${i}\xD7${o} canvas (x ${k}, y ${P}) and never moves in.`,w)}let V=Pa(v).reduce((k,P)=>k+(P.keyframes?.length??0),0);V>Yl&&n("warning","large_animation",`'${w}' has ${V} keyframes across its tracks (over ${Yl}). Keying every frame is rarely needed: key the turning points and let eases fill in, or drive the prop from a signal.`,w);for(let k of Pa(v)){let P=k.keyframes??[];(!k.source||k.source.type==="keyframe")&&P.length>=2&&P.every(G=>JSON.stringify(G.value)===JSON.stringify(P[0].value))&&n("info","static_track",`'${w}' animates \`${k.prop}\` but every keyframe holds ${JSON.stringify(P[0].value)}.`,w)}let $=ni(v.background)??x,I=v.children,E=v.x===0&&v.y===0&&v.width===i&&v.height===o;T(I??[],$,A&&E)},T=(v,x,A)=>{let w=x;for(let R of Qf(v))y(R,w,A),ql(R)&&(w=null)},M=ni(e.backgroundColor)??null;if(T(e.layout,M,!0),m.length>0){let v=m.slice(0,3).map(x=>`'${x}'`).join(", ");n("warning","missing_emoji_font",`${m.length===1?"Text":`${m.length} text layers`} ${v}${m.length>3?", \u2026":""} ${m.length===1?"has":"have"} emoji, but no emoji font is registered, so the emoji draw nothing. Run \`npx framefields fonts add emoji\` and call the generated \`registerFonts()\`, or \`FontManager.registerEmojiFont(path)\` with a color emoji font.`,m[0])}return a&&u.length>0&&n("info","ambient_with_environment",`The environment already fills shadows with light; ambient light ${u.join(", ")} adds flat light on top (remove it, or lower it, if the scene looks washed out).`),b&&g&&n("error","camera_cube_screen_space",`'${b}' is a cube camera, and '${g}' turns on ssr / gi: screen-space reflections and GI need a single perspective view. Use the environment's floor for reflections.`,g),f&&p===0&&n("warning","volumetric_fog_without_lights",`'${f}' turns on volumetricFog, but the scene has no directional, spot, point or rect light: fog scatters only direct light, so there are no light shafts. Add a light (castShadow for shafts).`,f),l&&c.length>0&&!a&&n("info","pbr_without_environment",`roughness / metallic / clearcoat / anisotropy are set (${c.slice(0,3).join(", ")}${c.length>3?", \u2026":""}) but the scene has no Layer.environment(): add one for physically based shading, the coat and brushed-metal reflections, and tone mapping.`),r}h();var Ma=s.tuple([s.number(),s.number(),s.number()]),Aa=(e,t)=>s.tuple([s.number().min(e).max(t),s.number().min(e).max(t)]),eh=s.enum(["lit","unlit","toon"]),Kl={color:s.string().optional(),material:eh.optional(),shininess:s.number().min(0).optional(),roughness:s.number().min(0).max(1).optional(),metallic:s.number().min(0).max(1).optional()},th=s.object({seed:s.number().optional(),scale:s.number().positive().optional(),octaves:s.number().int().min(1).max(10).optional(),persistence:s.number().min(0).max(1).optional(),lacunarity:s.number().min(1).max(4).optional(),ridgeMode:s.enum(["fbm","ridged","terrace"]).optional(),terraceSteps:s.number().int().min(2).max(32).optional()}).strict(),rh=s.object({lowColor:s.string(),midColor:s.string().optional(),highColor:s.string(),cliffColor:s.string().optional(),cliffThreshold:s.number().min(0).max(1).optional(),bands:Aa(0,1).optional()}).strict(),nh=s.object({type:s.literal("terrain"),width:s.number().positive(),depth:s.number().positive(),height:s.number().min(0).optional(),segments:s.union([s.number().int().min(1).max(512),s.tuple([s.number().int().min(1).max(512),s.number().int().min(1).max(512)])]).optional(),noise:th.optional(),heights:s.array(s.number().min(0).max(1)).optional(),overhangWarp:s.number().min(0).optional(),colorByElevation:rh.optional(),flatShaded:s.boolean().optional(),base:s.number().min(0).optional(),...Kl}).strict(),dr={op:s.enum(["union","subtract","intersect"]).optional(),smoothness:s.number().min(0).optional(),center:Ma.optional(),rotation:Ma.optional(),color:s.string().optional()},ih=s.discriminatedUnion("shape",[s.object({...dr,shape:s.literal("sphere"),radius:s.number().positive()}).strict(),s.object({...dr,shape:s.literal("box"),size:s.tuple([s.number().positive(),s.number().positive(),s.number().positive()]),radius:s.number().min(0).optional()}).strict(),s.object({...dr,shape:s.literal("cylinder"),radius:s.number().positive(),height:s.number().positive()}).strict(),s.object({...dr,shape:s.literal("capsule"),radius:s.number().positive(),height:s.number().positive()}).strict(),s.object({...dr,shape:s.literal("torus"),radius:s.number().positive(),tube:s.number().positive()}).strict(),s.object({...dr,shape:s.literal("gyroid"),scale:s.number().positive(),thickness:s.number().positive()}).strict()]),oh=s.object({type:s.literal("sdf"),primitives:s.array(ih).min(1),bounds:s.tuple([s.number().positive(),s.number().positive(),s.number().positive()]),resolution:s.number().int().min(16).max(160).optional(),flatShaded:s.boolean().optional(),...Kl}).strict(),Ql=s.unknown().superRefine((e,t)=>{let r=e?.type,n=r==="terrain"?nh:r==="sdf"?oh:void 0;if(!n)return;let i=n.safeParse(e);if(!i.success)for(let o of i.error.issues)t.addIssue({...o,code:"custom",message:o.message})}),Jl=s.object({amplitudeDeg:s.number().min(0).max(90).optional(),frequency:s.number().min(0).max(20).optional(),direction:s.tuple([s.number(),s.number()]).optional(),waveScale:s.number().positive().optional()}).strict(),ah=s.object({x:s.number(),z:s.number(),radius:s.number().min(0),falloff:s.number().min(0).optional()}).strict(),ec=s.object({surface:s.custom(e=>typeof e=="object"&&e!==null),count:s.number().int().min(0).max(2e5),minDistance:s.number().min(0).optional(),seed:s.number().optional(),slopeRange:Aa(0,180).optional(),elevationRange:Aa(0,1).optional(),alignToNormal:s.number().min(0).max(1).optional(),scaleRange:s.tuple([s.number().positive(),s.number().positive()]).optional(),randomYaw:s.boolean().optional(),exclude:s.array(ah).optional(),sink:s.number().optional()}).strict(),tc=s.object({node:s.custom(e=>typeof e=="object"&&e!==null)}).strict(),rc=s.object({cells:s.number().int().min(2).max(256).optional(),seed:s.number().optional(),impactPoint:Ma.optional(),interiorColor:s.string().optional(),interiorRoughness:s.number().min(0).max(1).optional(),track:s.array(s.number()).optional()}).strict();h();var nc=s.union([s.number().min(0),s.enum(["auto","fit","fill"]),s.custom()]),sh=s.enum(["rect","circle","ellipse","polygon","star","arrow","path"]),ic=s.union([s.instanceof(ir),s.object({op:s.string().min(1)}).passthrough(),s.custom(e=>!!(e&&typeof e=="object"&&"op"in e&&typeof e.op=="string"))]),uh=s.enum(["x","y","scale","rotation","opacity","width","height","volume","hidden","muted","gap","padding","borderRadius","fontSize","text","fill","color","letterSpacing","d","trimStart","trimEnd","trimOffset","strokeWidth","strokeDashOffset","cornerRadius","starInnerRadiusRatio","fillColor","strokeColor","borderColor","borderWidth","motionBlurShutter","rangeStart","rangeEnd","offset","animatorRangeStart","animatorRangeEnd","animatorOffset","firstMargin","lastMargin","baselineShift","rotateX","rotateY","rotateZ","perspective","translateZ","perspectiveOriginX","perspectiveOriginY","cameraX","cameraY","cameraZ","targetX","targetY","targetZ","cameraPitch","cameraYaw","cameraRoll","cameraFov","cameraZoom","focalLength","focusDistance","fStop","maxBlurRadius","shakeTranslation","shakeRotation","relativitySpeed","orbitRadius","orbitAzimuth","orbitElevation","z","scaleZ","intensity","angle","radius","penumbra","decay","shininess","roughness","specularIntensity","ambientIntensity","metallic","ior","dispersion","transmission","fresnelPower","envIntensity","animationProgress","animationTime","animationSpeed","wireframe","scaleX","scaleY","emissive","emissiveIntensity","clearcoat","clearcoatRoughness","anisotropy","anisotropyRotation","subsurface","subsurfaceColor","sheen","sheenColor","sheenRoughness","iridescence","iridescenceThickness","iridescenceIor","triplanarScale","triplanarSharpness","exposure","volumetricFogDensity","volumetricFogAnisotropy","volumetricFogNoiseStrength"]),Ca=s.enum(["alpha","alpha-inverted","luma","luma-inverted"]),oc=s.enum(["lit","unlit","toon","glass","acrylic","frosted","metallic"]);var lh=s.enum(["interpolate","hueRotate","threshold"]),ch=s.object({name:s.enum(["none","power1","power2","power3","sine","circ","expo","back","elastic","bounce","spring","cubic","hold"]),dir:s.enum(["in","out","inOut"]),params:s.array(s.number()).optional()}).strict().superRefine((e,t)=>{if(e.name==="spring"&&e.params){let[r,n,i]=e.params;r!==void 0&&r<=0&&t.addIssue({code:s.ZodIssueCode.custom,message:"Spring damping must be greater than 0.",path:["params",0]}),n!==void 0&&n<=0&&t.addIssue({code:s.ZodIssueCode.custom,message:"Spring stiffness must be greater than 0.",path:["params",1]}),i!==void 0&&i<=0&&t.addIssue({code:s.ZodIssueCode.custom,message:"Spring mass must be greater than 0.",path:["params",2]})}}),mh=s.object({id:s.string().min(1),frame:s.number().int().min(0),value:s.union([s.number(),s.boolean(),s.string()]),ease:ch.optional(),presetGroupId:s.string().optional(),presetType:s.string().optional(),spatialTangentIn:s.object({x:s.number(),y:s.number()}).optional(),spatialTangentOut:s.object({x:s.number(),y:s.number()}).optional()}).strict(),dh=s.enum(["continuous","accumulate"]),ph=s.enum(["composition","layer"]),fh=s.discriminatedUnion("type",[s.object({type:s.literal("keyframe")}),s.object({type:s.literal("signal"),inputHandleId:s.string(),multiplier:s.number().default(1),offset:s.number().default(0),smoothingWindowFrames:s.number().min(0).default(0),colorMode:lh.optional(),colorA:s.string().optional(),colorB:s.string().optional(),colorThreshold:s.number().optional(),signalMode:dh.optional(),threshold:s.number().optional(),accumulateThreshold:s.number().optional(),debounceFrames:s.number().int().min(0).optional(),channel:s.string().optional(),clock:ph.optional()}),s.object({type:s.literal("wiggle"),frequency:s.number().default(2),amplitude:s.number().default(50),octaves:s.number().int().min(1).max(4).default(1),seed:s.number().default(1234)}),s.object({type:s.literal("springOvershoot"),damping:s.number().default(12),stiffness:s.number().default(180),mass:s.number().default(1)})]),hh=s.preprocess(e=>{if(!e||typeof e!="object")return e;let t=e;if(t.type==="signal"){let r=typeof t.threshold=="number"?t.threshold:typeof t.accumulateThreshold=="number"?t.accumulateThreshold:.15;return{type:"signal",inputHandleId:t.inputHandleId??t.handleId,multiplier:t.multiplier??t.amplitude??1,offset:t.offset??0,smoothingWindowFrames:t.smoothingWindowFrames??t.smoothing??0,colorMode:t.colorMode,colorA:t.colorA,colorB:t.colorB,colorThreshold:t.colorThreshold,signalMode:t.signalMode??"continuous",threshold:r,accumulateThreshold:r,debounceFrames:t.debounceFrames??2,channel:typeof t.channel=="string"?t.channel:"primary",...t.clock!==void 0&&{clock:t.clock}}}return e},fh),gh=(e,t)=>{if(e?.tracks)for(let r=0;r<e.tracks.length;r++){let n=e.tracks[r],i=n.keyframes??[];(!n.source||n.source.type==="keyframe")&&i.length<1&&t.addIssue({code:s.ZodIssueCode.custom,message:`Track for property '${n.prop}' must have at least 1 keyframe.`,path:["tracks",r,"keyframes"]});let a=n.prop==="hidden"||n.prop==="muted",u=n.prop==="fillColor"||n.prop==="strokeColor"||n.prop==="fill"||n.prop==="color",l=n.prop==="d";for(let c=0;c<i.length;c++){let m=i[c];if(c>0){let p=i[c-1];m.frame<p.frame?t.addIssue({code:s.ZodIssueCode.custom,message:"Keyframes must be sorted in ascending order of frame.",path:["tracks",r,"keyframes",c]}):m.frame===p.frame&&t.addIssue({code:s.ZodIssueCode.custom,message:"Duplicate keyframes at the same frame are not allowed.",path:["tracks",r,"keyframes",c]})}let d=typeof m.value;a?d!=="boolean"&&t.addIssue({code:s.ZodIssueCode.custom,message:`Keyframe value for discrete property '${n.prop}' must be a boolean.`,path:["tracks",r,"keyframes",c,"value"]}):u?d!=="string"&&t.addIssue({code:s.ZodIssueCode.custom,message:`Keyframe value for color property '${n.prop}' must be a string.`,path:["tracks",r,"keyframes",c,"value"]}):l?d!=="string"&&t.addIssue({code:s.ZodIssueCode.custom,message:"Keyframe value for 'd' must be SVG path data (a string).",path:["tracks",r,"keyframes",c,"value"]}):d!=="number"||Number.isNaN(m.value)||!Number.isFinite(m.value)?t.addIssue({code:s.ZodIssueCode.custom,message:`Keyframe value for numeric property '${n.prop}' must be a finite number.`,path:["tracks",r,"keyframes",c,"value"]}):(n.prop==="volume"||n.prop==="trimStart"||n.prop==="trimEnd")&&(m.value<0||m.value>1)&&t.addIssue({code:s.ZodIssueCode.custom,message:`Keyframe value for property '${n.prop}' must be between 0 and 1.`,path:["tracks",r,"keyframes",c,"value"]})}}},bh=s.object({id:s.string().min(1),prop:uh,source:hh.optional(),keyframes:s.array(mh).default([]),repeat:s.number().int().optional(),yoyo:s.boolean().optional(),durationFrames:s.number().int().min(1).optional()}).strict(),Da=s.object({tracks:s.array(bh).max(24),frameStep:s.number().int().min(1).max(24).optional()}).strict().superRefine(gh),ac=s.object({shadowColor:ee.optional(),lightColor:ee.optional(),threshold:s.number().min(-1).max(1).optional(),softness:s.number().min(0).max(2).optional(),diffuse:s.number().min(0).max(1).optional()}).strict(),sc=s.object({color:ee.optional(),width:s.number().min(0).max(32).optional(),referenceHeight:s.number().positive().optional(),creaseAngle:s.number().min(0).max(180).optional(),depthThreshold:s.number().positive().max(1).optional(),opacity:s.number().min(0).max(1).optional()}).strict(),yh=s.object({intensity:s.number().min(0).max(1).optional(),thickness:s.number().min(100).max(1200).optional(),ior:s.number().min(1.05).max(2.5).optional()}).strict(),xh=s.object({scale:s.number().min(0).optional(),sharpness:s.number().min(1).max(16).optional()}).strict(),Et={id:s.string().min(1),inputHandleId:s.string().optional(),position:s.enum(["relative","absolute"]).default("relative"),x:s.union([s.number(),s.custom()]).default(0),y:s.union([s.number(),s.custom()]).default(0),width:nc.optional(),height:nc.optional(),grow:s.number().min(0).optional(),flexShrink:s.number().min(0).optional(),flexBasis:s.number().min(0).optional(),alignSelf:s.enum(["auto","start","center","end","stretch","baseline"]).optional(),aspectRatio:s.number().positive().optional(),zIndex:s.number().int().default(0),hidden:s.boolean().default(!1),opacity:s.number().min(0).max(1).default(1),blendMode:s.string().optional(),effects:s.array(ic).optional(),rotation:s.number().default(0),scale:s.number().min(0).default(1),scaleX:s.number().default(1),scaleY:s.number().default(1),anchorX:s.number().min(0).max(1).default(.5),anchorY:s.number().min(0).max(1).default(.5),startFrame:s.number().int().min(0).default(0),durationFrames:s.number().int().min(1).optional(),motionBlurShutter:s.number().min(0).max(360).optional(),rotateX:s.number().default(0),rotateY:s.number().default(0),rotateZ:s.number().default(0),perspective:s.number().min(0).default(0),perspectiveOriginX:s.number().default(.5),perspectiveOriginY:s.number().default(.5),translateZ:s.number().default(0),backfaceVisibility:s.enum(["visible","hidden"]).default("visible"),transformStyle:s.enum(["flat","preserve-3d"]).default("flat"),is3D:s.boolean().default(!1),z:s.union([s.number(),s.custom()]).default(0),scaleZ:s.number().default(1),twoSided:s.boolean().default(!0),material:oc.default("lit"),ior:s.number().min(1).max(3).optional(),roughness:s.number().min(0).max(1).optional(),shininess:s.number().min(1).max(512).default(32),specularIntensity:s.number().min(0).default(.5),metallic:s.number().min(0).max(1).optional(),ambientIntensity:s.number().min(0).default(1),transmission:s.number().min(0).max(1).optional(),dispersion:s.number().min(0).max(1).optional(),fresnelPower:s.number().min(1).max(10).optional(),envIntensity:s.number().min(0).max(10).optional(),emissive:ee.optional(),emissiveIntensity:s.number().min(0).optional(),clearcoat:s.number().min(0).max(1).optional(),clearcoatRoughness:s.number().min(0).max(1).optional(),anisotropy:s.number().min(-1).max(1).optional(),anisotropyRotation:s.number().optional(),subsurface:s.number().min(0).max(1).optional(),subsurfaceColor:ee.optional(),sheen:s.number().min(0).max(1).optional(),sheenColor:ee.optional(),sheenRoughness:s.number().min(.05).max(1).optional(),iridescence:s.union([s.number().min(0).max(1),yh]).optional(),iridescenceThickness:s.number().min(100).max(1200).optional(),iridescenceIor:s.number().min(1.05).max(2.5).optional(),triplanar:s.union([s.boolean(),xh]).optional(),triplanarScale:s.number().min(0).optional(),triplanarSharpness:s.number().min(1).max(16).optional(),castShadow:s.boolean().optional(),toon:ac.optional(),outline:s.boolean().optional(),matte:s.object({node:s.custom(e=>typeof e=="object"&&e!==null),mode:Ca.optional()}).optional(),matteId:s.string().optional(),matteOf:s.string().optional(),matteMode:Ca.optional(),relief:s.object({node:s.custom(e=>typeof e=="object"&&e!==null),amount:s.number().optional()}).optional(),reliefId:s.string().optional(),reliefOf:s.string().optional(),reliefAmount:s.number().optional(),textureOf:s.string().optional(),animation:Da.default({tracks:[]}),vision:s.unknown().optional(),relighting:s.unknown().optional()},uc=s.object({color:ee,offset:s.object({x:s.number(),y:s.number()}).optional(),blurRadius:s.number().min(0).optional()}).strict(),Sh=s.object({x:s.number().optional(),y:s.number().optional(),scale:s.number().optional(),scaleX:s.number().optional(),scaleY:s.number().optional(),rotation:s.number().optional(),rotationX:s.number().optional(),rotationY:s.number().optional(),opacity:s.number().optional(),blur:s.number().optional(),color:s.string().optional()}).strict(),lc=s.object({id:s.string(),unit:s.enum(["character","word","line"]).default("character"),rangeStart:s.number().min(0).max(1).default(0),rangeEnd:s.number().min(0).max(1).default(1),offset:s.number().min(-1).max(1).default(0),easing:s.string().default("power2.out"),transform:Sh.optional()}),wh={waveRise(e={}){return{id:e.id??"wave-rise",unit:e.unit??"character",rangeStart:e.rangeStart??0,rangeEnd:e.rangeEnd??1,offset:e.offset??-1,easing:e.easing??"power2.out",transform:{y:e.y??40,rotationX:e.rotationX??45,opacity:e.opacity??0,blur:e.blur??0}}},wordPop(e={}){return{id:e.id??"word-pop",unit:"word",rangeStart:0,rangeEnd:1,offset:-1,easing:e.easing??"back.out(1.6)",transform:{scale:e.scale??0,y:e.y??20,opacity:0}}},blurIn(e={}){return{id:e.id??"blur-in",unit:e.unit??"character",rangeStart:0,rangeEnd:1,offset:-1,easing:e.easing??"power3.out",transform:{blur:e.blur??16,y:e.y??20,opacity:e.opacity??0}}},flip3D(e={}){return{id:e.id??"flip-3d",unit:e.unit??"character",rangeStart:0,rangeEnd:1,offset:-1,easing:e.easing??"back.out(1.4)",transform:{rotationX:e.rotationX??90,opacity:0}}},colorSweep(e){return{id:e.id??"color-sweep",unit:e.unit??"character",rangeStart:0,rangeEnd:.5,offset:-.5,easing:e.easing??"power2.inOut",transform:{color:e.color}}}},vh=s.enum(["perspective","equirectangular","fisheye"]),kh=s.object({focalLength:s.number().min(5).max(500).default(50),fov:s.number().min(5).max(360).optional(),sensorWidth:s.number().default(36),near:s.number().min(.1).default(1),far:s.number().min(10).default(5e4),zoom:s.number().min(.01).default(1),projection:vh.default("perspective"),cubeSize:s.number().int().min(64).max(8192).optional()}).strict(),Ph=s.object({enabled:s.boolean().default(!1),focusDistance:s.number().min(1).default(1e3),fStop:s.number().min(.5).max(64).default(2.8),maxBlurRadius:s.number().min(0).max(128).default(32),apertureBlades:s.number().int().min(0).max(12).default(0),anamorphicRatio:s.number().min(.5).max(3).default(1)}).strict(),Th=s.object({translationAmplitude:s.number().min(0).default(0),rotationAmplitude:s.number().min(0).default(0),frequency:s.number().min(.1).max(60).default(2.5),octaves:s.number().int().min(1).max(6).default(3),seed:s.number().default(42)}).strict(),Mh=s.object({shutter:s.number().min(1).max(720).default(180),samples:s.number().int().min(4).max(64).default(20),maxBlur:s.number().min(4).max(160).default(48)}).strict(),Ah=s.object({speed:s.number().min(0).max(.9999).default(0),direction:s.tuple([s.number(),s.number(),s.number()]).optional(),doppler:s.boolean().default(!0),beaming:s.boolean().default(!0),exposure:s.union([s.literal("auto"),s.number().min(-64).max(16)]).default("auto")}).strict(),cc=s.object({id:s.string().min(1),kind:s.literal("camera"),mode:s.enum(["lookAt","free","orbit"]).default("lookAt"),x:s.number().optional(),y:s.number().optional(),z:s.number().optional(),targetX:s.number().optional(),targetY:s.number().optional(),targetZ:s.number().optional(),pitch:s.number().default(0),yaw:s.number().default(0),roll:s.number().default(0),lens:kh.optional(),dof:Ph.optional(),shake:Th.optional(),motionBlur:s.union([s.boolean(),Mh]).optional(),relativity:Ah.optional(),startFrame:s.number().int().min(0).default(0),durationFrames:s.number().int().min(1).optional(),animation:Da.default({tracks:[]})}).strict(),mc=s.enum(["ambient","directional","point","spot","rect","environment"]),dc=s.enum(["studio","soft","warm","sunset","night","neon","neutral"]),pc=s.enum(["neutral","agx","aces","none"]),fc=s.object({color:ee,start:s.number().min(0),end:s.number().min(0),opacity:s.number().min(0).max(1).optional()}).strict(),hc=s.object({intensity:s.number().min(0).max(10).optional(),threshold:s.number().min(0).max(16).optional(),knee:s.number().min(0).max(1).optional(),radius:s.number().min(1).max(8).optional()}).strict(),gc=s.object({y:s.number(),color:ee.optional(),reflectivity:s.number().min(0).max(1).optional(),roughness:s.number().min(0).max(1).optional(),fadeDistance:s.number().min(0).optional(),opacity:s.number().min(0).max(1).optional()}).strict(),bc=s.object({scale:s.number().min(1e-4).optional(),strength:s.number().min(0).max(1).optional(),speed:s.tuple([s.number(),s.number(),s.number()]).optional(),octaves:s.number().int().min(1).max(3).optional()}).strict(),yc=s.object({density:s.number().min(0).optional(),color:ee.optional(),anisotropy:s.number().min(-.95).max(.95).optional(),heightFalloff:s.number().min(0).optional(),baseHeight:s.number().optional(),steps:s.number().int().min(8).max(64).optional(),maxDistance:s.number().min(100).optional(),lightIntensity:s.number().min(0).optional(),ambientIntensity:s.number().min(0).optional(),noise:s.union([s.boolean(),bc]).optional()}).strict(),xc=s.object({intensity:s.number().min(0).max(1).optional(),maxRoughness:s.number().min(0).max(1).optional(),thickness:s.number().min(1).optional(),steps:s.number().int().min(16).max(64).optional()}).strict(),Sc=s.object({intensity:s.number().min(0).max(4).optional(),radius:s.number().min(1).optional(),samples:s.number().int().min(4).max(16).optional()}).strict(),wc=s.object({id:s.string().min(1),kind:s.literal("light"),lightType:mc.default("directional"),color:ee.default("#ffffff"),intensity:s.number().default(1),x:s.number().optional(),y:s.number().optional(),z:s.number().optional(),targetX:s.number().optional(),targetY:s.number().optional(),targetZ:s.number().optional(),direction:s.tuple([s.number(),s.number(),s.number()]).optional(),radius:s.number().min(0).default(1e3),decay:s.number().min(0).default(2),angle:s.number().min(0).max(180).default(45),penumbra:s.number().min(0).max(1).default(.2),width:s.number().min(0).optional(),height:s.number().min(0).optional(),twoSided:s.boolean().optional(),castShadow:s.boolean().optional(),shadowSoftness:s.number().min(0).max(64).optional(),shadowDarkness:s.number().min(0).max(1).optional(),shadowMapSize:s.number().int().min(256).max(8192).optional(),preset:dc.optional(),hdri:s.union([s.string(),s.custom(e=>e instanceof Uint8Array)]).optional(),top:ee.optional(),horizon:ee.optional(),bottom:ee.optional(),softboxes:s.number().min(0).optional(),rotation:s.number().optional(),exposure:s.number().min(-16).max(16).optional(),toneMapping:pc.optional(),fog:fc.optional(),floor:gc.optional(),volumetricFog:s.union([s.boolean(),yc]).optional(),volumetricFogDensity:s.number().min(0).optional(),volumetricFogAnisotropy:s.number().min(-.95).max(.95).optional(),volumetricFogNoiseStrength:s.number().min(0).max(1).optional(),ssr:s.union([s.boolean(),xc]).optional(),gi:s.union([s.boolean(),Sc]).optional(),outlines:s.union([s.boolean(),sc]).optional(),bloom:s.union([s.boolean(),hc]).optional(),startFrame:s.number().int().min(0).default(0),durationFrames:s.number().int().min(1).optional(),animation:Da.default({tracks:[]})}).strict(),Ra=()=>s.array(s.lazy(()=>Oa)),vc=s.object({...Et,kind:s.literal("flex"),dir:s.enum(["row","column"]).default("row"),gap:s.number().min(0).default(0),padding:s.number().min(0).default(0),justify:s.enum(["start","center","end","space-between","space-around"]).default("start"),align:s.enum(["start","center","end","stretch"]).default("start"),wrap:s.boolean().default(!1),staggerFrames:s.number().min(0).default(0),staggerDirection:s.enum(["forward","reverse","center-out"]).default("forward"),overflow:s.enum(["visible","hidden"]).default("visible"),background:ee.optional(),borderRadius:s.number().min(0).optional(),borderColor:ee.optional(),borderWidth:s.number().min(0).optional(),strokeAlign:s.enum(["inside","center","outside"]).optional(),strokeRadius:s.number().min(0).optional(),children:Ra().optional()}).strict(),Ch=s.object({...Et,kind:s.literal("block"),gap:s.number().min(0).default(0),padding:s.number().min(0).default(0),align:s.enum(["start","center","end","stretch"]).default("start"),staggerFrames:s.number().min(0).default(0),staggerDirection:s.enum(["forward","reverse","center-out"]).default("forward"),overflow:s.enum(["visible","hidden"]).default("visible"),background:ee.optional(),borderRadius:s.number().min(0).optional(),borderColor:ee.optional(),borderWidth:s.number().min(0).optional(),strokeAlign:s.enum(["inside","center","outside"]).optional(),strokeRadius:s.number().min(0).optional(),children:Ra().optional()}).strict(),kc=s.object({...Et,kind:s.literal("box"),background:ee,borderRadius:s.number().min(0).optional(),padding:s.number().min(0).default(0),staggerFrames:s.number().min(0).default(0),staggerDirection:s.enum(["forward","reverse","center-out"]).default("forward"),overflow:s.enum(["visible","hidden"]).default("visible"),borderColor:ee.optional(),borderWidth:s.number().min(0).optional(),strokeAlign:s.enum(["inside","center","outside"]).optional(),strokeRadius:s.number().min(0).optional(),children:Ra().optional()}).strict(),Pc=s.object({background:ee,borderRadius:s.number().min(0).optional(),paddingX:s.number().min(0).optional(),paddingY:s.number().min(0).optional()}).strict(),Tc=s.object({text:s.union([s.string(),s.custom(e=>!!(e&&typeof e=="object"&&"get"in e))]),fontFamily:s.string().optional(),fontSize:s.union([s.number().positive(),s.custom(e=>!!(e&&typeof e=="object"&&"get"in e))]).optional(),fontWeight:s.union([s.number().int(),s.string()]).optional(),fontStyle:s.enum(["normal","italic"]).optional(),fill:s.union([ee,s.custom(e=>!!(e&&typeof e=="object"&&"get"in e))]).optional(),letterSpacing:s.number().optional(),baselineShift:s.number().optional(),opacity:s.union([s.number().min(0).max(1),s.custom(e=>!!(e&&typeof e=="object"&&"get"in e))]).optional(),mark:Pc.optional()}).strict(),Dh={text:s.string().default(""),spans:s.array(Tc).optional(),fontFamily:s.string().optional(),fontSize:s.number().positive().optional(),fontWeight:s.union([s.number().int(),s.string()]).optional(),fontStyle:s.string().optional(),fontVariations:s.record(s.string(),s.number()).optional(),fill:ee,align:s.enum(["start","center","end"]).optional(),direction:s.enum(["ltr","rtl","auto"]).optional(),verticalAlign:s.enum(["top","middle","bottom"]).optional(),lineHeight:s.number().positive().optional(),letterSpacing:s.number().optional(),background:ee,borderRadius:s.number().min(0).optional(),padding:s.number().min(0).optional(),stroke:ee,strokeWidth:s.number().min(0).optional(),strokeAlign:s.enum(["inside","center","outside"]).optional(),textShadow:s.string().optional(),shadows:s.array(uc).optional(),pathOptions:cr.optional(),typewriter:ei.optional(),marquee:ba.optional(),animators:s.array(s.union([lc,mr,ya])).optional()},Mc=s.object({...Et,...Dh,kind:s.literal("text")}).strict(),Ac=s.object({...Et,kind:s.literal("media"),inputHandleId:s.string().min(1),src:s.string().optional(),dataType:s.string().optional(),fit:s.enum(["cover","contain","fill","none"]).default("contain"),dpr:s.number().min(1).max(4).optional(),borderRadius:s.number().min(0).optional(),borderColor:ee.optional(),borderWidth:s.number().min(0).optional(),strokeAlign:s.enum(["inside","center","outside"]).optional(),strokeRadius:s.number().min(0).optional(),volume:s.number().min(0).max(1).default(1),muted:s.boolean().default(!1),trimStartSec:s.number().min(0).optional(),timeRemap:Ou.optional(),fontFamily:s.string().optional(),fontSize:s.number().positive().optional(),fontWeight:s.union([s.number().int(),s.string()]).optional(),fontStyle:s.string().optional(),fill:ee,align:s.enum(["start","center","end"]).optional(),direction:s.enum(["ltr","rtl","auto"]).optional(),verticalAlign:s.enum(["top","middle","bottom"]).optional(),lineHeight:s.number().positive().optional(),letterSpacing:s.number().optional(),background:ee,padding:s.number().min(0).optional(),stroke:ee,strokeWidth:s.number().min(0).optional(),textShadow:s.string().optional(),shadows:s.array(uc).optional(),maxWidth:s.number().optional()}).strict().superRefine((e,t)=>{if(!e.timeRemap)return;e.trimStartSec!==void 0&&t.addIssue({code:"custom",path:["timeRemap"],message:"timeRemap cannot be combined with trimStartSec"}),e.dataType!=="Video"&&e.dataType!=="Audio"&&t.addIssue({code:"custom",path:["timeRemap"],message:"timeRemap requires video or audio media"});let r=Nu(e.timeRemap,e.durationFrames??0);r&&t.addIssue({code:"custom",path:["timeRemap"],message:r})}),Rh={shapeType:sh.default("rect"),borderRadius:s.number().min(0).optional(),radiusTL:s.number().min(0).optional(),radiusTR:s.number().min(0).optional(),radiusBR:s.number().min(0).optional(),radiusBL:s.number().min(0).optional(),polygonSides:s.number().int().min(3).max(64).optional(),starPoints:s.number().int().min(3).max(64).optional(),starInnerRadiusRatio:s.number().min(.01).max(.99).optional(),arrowHeadWidth:s.number().min(0).optional(),arrowHeadLength:s.number().min(0).optional(),arrowShaftWidth:s.number().min(1).optional(),d:s.string().optional(),fillType:s.enum(["solid","linear","radial","none"]).default("solid"),fillColor:ee.default("#3b82f6"),gradientEndColor:ee.optional(),gradientAngle:s.number().default(0),strokeColor:ee.default("#ffffff"),strokeWidth:s.number().min(0).default(0),strokeDashArray:s.string().optional(),strokeDashOffset:s.number().default(0),strokeLineCap:s.enum(["butt","round","square"]).default("round"),strokeLineJoin:s.enum(["miter","round","bevel"]).default("round"),strokeAlign:s.enum(["inside","center","outside"]).optional(),trimStart:s.number().min(0).max(1).default(0),trimEnd:s.number().min(0).max(1).default(1),trimOffset:s.number().default(0)},Cc=s.object({...Et,...Rh,kind:s.literal("shape")}).strict(),Oh=s.object({offset:s.number().min(0).max(1),color:s.string()}),Dc=s.object({...Et,kind:s.literal("model3d"),src:s.string().default(""),modelFormat:s.enum(["obj","fbx","gltf","glb","stl","ply","vox","3ds","off","auto"]).default("auto"),modelData:s.unknown().optional(),animationName:s.string().optional(),animationProgress:s.number().min(0).max(1).default(0),animationTime:s.number().min(0).default(0),animationSpeed:s.number().default(1),loop:s.boolean().default(!0),wireframe:s.boolean().default(!1),texture:s.string().optional(),center:s.boolean().optional(),normalizeSize:s.number().optional(),scaleX:s.number().default(1),scaleY:s.number().default(1),audioDeform:s.record(s.string(),s.unknown()).optional(),color:ee.optional(),colorTint:ee.optional(),text3dOptions:s.unknown().optional(),primitive3d:Ql.optional(),instances3d:s.unknown().optional(),swarm3d:s.unknown().optional(),scatter3d:ec.optional(),fracture3d:rc.optional(),wind:Jl.optional(),textureLayer:tc.optional(),textureLayerId:s.string().optional(),animationLayers:s.array(ll).optional(),ik:s.array(cl).optional(),lookAt:s.array(ml).optional(),springBones:s.array(hl).optional(),pose:s.record(s.string(),dl).optional(),morphs:s.record(s.string(),Le).optional(),aim:s.array(pl).optional(),drive:s.array(fl).optional(),crowd:gl.optional()}).strict(),Oa=s.lazy(()=>s.discriminatedUnion("kind",[vc,Ch,kc,Mc,Ac,Cc,cc,wc,Dc])),Nh=s.object({width:s.number().int().min(1).max(4096),height:s.number().int().min(1).max(4096),backgroundColor:ee,volume:s.number().min(0).max(1).default(1),fps:s.number().int().min(1).max(120).default(24),mode:s.enum(["Video","Image"]).default("Video"),antialias3d:s.boolean().optional(),layout:s.array(Oa).default([]),fonts:s.array(s.string()).optional(),signals:s.record(s.string(),s.unknown()).optional(),effects:s.array(ic).optional(),vision:s.unknown().optional(),onRequestFrame:s.custom().optional()}).strict();h();var Rc=s.enum(["cut","carrierMatchCut","cameraWhip","focusPullDissolve","irisAperture","pushDirectional"]),Oc=s.object({sourceLayerId:s.string(),targetLayerId:s.string(),mode:s.enum(["exact","preserveVelocity","morph"]).default("preserveVelocity"),blendFrames:s.number().int().min(0).max(30).default(0)}).strict(),Nc=s.object({id:s.string(),chapter:s.enum(["hook","tension","solution","feature_spotlight","outro","custom"]).default("custom"),durationMs:s.number().positive().optional(),durationFrames:s.number().int().positive().optional(),transitionOut:s.object({type:Rc.default("cut"),durationFrames:s.number().int().min(0).default(0),carrier:Oc.optional(),whipDirection:s.enum(["left","right","up","down"]).default("left")}).default({type:"cut",durationFrames:0,whipDirection:"left"})}).passthrough();function Fh(e,t){return{x:e.x,y:e.y,scale:e.scale,vx:e.vx,vy:e.vy,...t}}function Fc(e,t=60){Un(t);let r=e.map(u=>Lh(u,t)),n=0,i=0,o=[];for(let[u,l]of e.entries()){let c=r[u],m=n+c;if(!Number.isSafeInteger(m))throw new Error(`Scene '${l.id}' exceeds the safe frame range`);o.push({sceneId:l.id,startFrame:n,durationFrames:c}),i=Math.max(i,m);let d=l.transitionOverlap??l.transitionOut?.durationFrames??0;if(!Number.isSafeInteger(d)||d<0)throw new Error(`Scene '${l.id}' overlap must be a nonnegative safe integer`);if(u+1<e.length&&d>Math.min(c,r[u+1]))throw new Error(`Scene '${l.id}' overlap exceeds an adjacent scene duration`);n=m-(u+1<e.length?d:0)}let a=Math.round(i/t*1e3);if(!Number.isFinite(a))throw new Error("Sequence duration exceeds the finite range");return{totalFrames:i,totalDurationMs:a,sceneOffsets:o}}function Lh(e,t){if(e.durationMs!==void 0&&(!Number.isFinite(e.durationMs)||e.durationMs<=0))throw new Error(`Scene '${e.id}' durationMs must be finite and positive`);let r=e.durationFrames??(e.durationMs===void 0?60:Math.round(e.durationMs/1e3*t));if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Scene '${e.id}' duration must resolve to a positive safe integer frame count`);return r}function Eh(e,t,r){let n=e.startFrame??0,i=e.durationFrames??r.durationFrames-n;if(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(i)||i<=0||n+i>r.durationFrames)throw new Error(`Scene '${t}', layer '${e.id}': window must fit within frames [0, ${r.durationFrames})`);return{...e,startFrame:r.startFrame+n,durationFrames:i}}var Xr=class e{id;chapter;durationMs;durationFrames;transitionOut;layout;constructor(t){Nc.parse(t),this.id=t.id,this.chapter=t.chapter??"custom",this.durationMs=t.durationMs,this.durationFrames=t.durationFrames,this.transitionOut={type:t.transitionOut?.type??"cut",durationFrames:t.transitionOut?.durationFrames??0,carrier:t.transitionOut?.carrier,whipDirection:t.transitionOut?.whipDirection??"left"},this.layout=t.layout??[]}static create(t){return new e(t)}},Na=class e{fps;width;height;backgroundColor;fonts;signals;scenes=[];constructor(t={}){if(this.fps=t.fps??60,this.width=t.width??1920,this.height=t.height??1080,this.backgroundColor=t.backgroundColor??"#ffffff",this.fonts=t.fonts,this.signals=t.signals,t.scenes)for(let r of t.scenes)this.addScene(r)}static create(t={}){return new e(t)}addScene(t){let r=t instanceof Xr?t:new Xr(t);return this.scenes.push(r),this}getScenes(){return this.scenes}calculateTimeline(){return Fc(this.scenes,this.fps)}toProgram(){let t=this.calculateTimeline(),r=[];for(let n=0;n<this.scenes.length;n++){let i=this.scenes[n],o=t.sceneOffsets[n];if(o)for(let a of i.layout)r.push(Eh(a,i.id,o))}return{width:this.width,height:this.height,backgroundColor:this.backgroundColor,fps:this.fps,volume:1,mode:"Video",layout:r,fonts:this.fonts,signals:this.signals}}};h();var oi=e=>e<0?0:e>1?1:e,Bh={none:()=>e=>e,linear:()=>e=>e,power1:()=>e=>e*e,power2:()=>e=>e*e*e,cubic:()=>e=>e*e*e,power3:()=>e=>e**4,sine:()=>e=>1-Math.cos(e*Math.PI/2),circ:()=>e=>1-Math.sqrt(Math.max(0,1-e*e)),expo:()=>e=>e===0?0:2**(10*(e-1)),back:([e=1.70158])=>t=>(e+1)*t*t*t-e*t*t,elastic:([e=1,t=.3])=>{let r=Math.max(1,e),n=t/(2*Math.PI)*Math.asin(1/r);return i=>i===0||i===1?i:-(r*2**(10*(i-1))*Math.sin((i-1-n)*(2*Math.PI)/t))},bounce:()=>e=>1-Ih(1-e)};function Ih(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-1.5/2.75)**2+.75:e<2.5/2.75?7.5625*(e-2.25/2.75)**2+.9375:7.5625*(e-2.625/2.75)**2+.984375}var Lc=new Map;function jh(e){if(!e)return u=>oi(u);let t=Lc.get(e);if(t)return t;let r=e.trim().match(/^([a-zA-Z0-9]+)(?:\.([a-zA-Z]+))?(?:\(([^)]*)\))?$/);if(!r)throw new Error(`Unknown ease "${e}"`);let n=(r[1]??"").toLowerCase(),i=(r[2]??"out").toLowerCase(),o=(r[3]??"").split(",").map(u=>Number.parseFloat(u)).filter(u=>!Number.isNaN(u)),a;if(n==="hold")a=u=>u>=1?1:0;else{let u=Bh[n];if(!u)throw new Error(`Unknown ease "${e}"`);let l=u(o);if(i==="in")a=c=>l(oi(c));else if(i==="inout")a=c=>{let m=oi(c);return m<.5?l(m*2)/2:1-l((1-m)*2)/2};else if(i==="out")a=c=>1-l(1-oi(c));else throw new Error(`Unknown ease direction in "${e}"`)}return Lc.set(e,a),a}function ai(e,t){return jh(e)(t)}var Zr=(e,t=3)=>{let r=10**t;return Math.round(e*r)/r},Fa=e=>e[e.length-1];function zh(e){let t=new Map;for(let r of e)t.set(r[0],r);return[...t.values()].sort((r,n)=>r[0]-n[0])}function _h(e){let t=[];for(let r of e){for(;t.length>0&&Fa(t)[0]>=r[0];)t.pop();t.push(r)}return t}function Sw(e,t){let r=e[0];if(!r)return 0;if(t<=r[0])return r[1];for(let n=1;n<e.length;n++){let[i,o]=e[n-1],[a,u,l]=e[n];if(t>a)continue;if(l==="hold")return t===a?u:o;let c=ai(typeof l=="string"?l:void 0,(t-i)/Math.max(1,a-i));return o+(u-o)*c}return Fa(e)[1]}var Ec=class{constructor(t){this.initial=t}initial;changes=[];to(t,r,n,i="power2.out"){return this.changes.push({start:t,end:Math.max(t,r),to:n,ease:i}),this}set(t,r){return this.to(t,t,r)}keys(){let t=[[0,this.initial]],r=this.initial;for(let n of[...this.changes].sort((i,o)=>i.start-o.start)){let i=Fa(t),o=Math.max(n.start,i[0]+(n.end===n.start?1:0));o>i[0]&&t.push([o,r]);let a=Math.max(n.end,o);a===o?t[t.length-1]=[o,n.to,"hold"]:t.push([a,n.to,n.ease]),r=n.to}return _h(t)}},Bc=class{book=new Map;key(t,r,n){let i=this.book.get(t)??new Map;return this.book.set(t,i),i.set(r,[...i.get(r)??[],...n]),this}apply(){for(let[t,r]of this.book){let n=Q.create();for(let[i,o]of r)n.keys(i,zh(o));t.animate(n)}}};var mt=2048,Vh=42,Uh=30,$h=48,Ic=-60;function Gh(e,t){let r=e.length;for(let n=1,i=0;n<r;n++){let o=r>>1;for(;i&o;o>>=1)i^=o;i^=o,n<i&&([e[n],e[i]]=[e[i],e[n]],[t[n],t[i]]=[t[i],t[n]])}for(let n=2;n<=r;n<<=1){let i=-2*Math.PI/n,o=Math.cos(i),a=Math.sin(i);for(let u=0;u<r;u+=n){let l=1,c=0;for(let m=0;m<n/2;m++){let d=u+m,p=d+n/2,f=e[p]*l-t[p]*c,b=e[p]*c+t[p]*l;e[p]=e[d]-f,t[p]=t[d]-b,e[d]=e[d]+f,t[d]=t[d]+b;let g=l*o-c*a;c=l*a+c*o,l=g}}}}function jc(e,t){if(e.length===0)return 0;let r=[...e].sort((n,i)=>n-i);return r[Math.min(r.length-1,Math.floor(t*r.length))]}var si=e=>20*Math.log10(e+1e-9),zc=e=>e<0?0:e>1?1:e;function Wh(e,t,r){return Array.from({length:e+1},(n,i)=>t*(r/t)**(i/e))}function _c(e,t,r={}){let n=r.fps??30,i=r.bands??32,o=r.minHz??50,a=Math.min(r.maxHz??12e3,t/2),u=Math.max(0,...e.map(I=>I.length)),l=new Float32Array(u);for(let I of e)for(let E=0;E<I.length;E++)l[E]=l[E]+I[E]/e.length;let c=Math.ceil(u/t*n),m=t/n,d=Float64Array.from({length:mt},(I,E)=>.5-.5*Math.cos(2*Math.PI*E/(mt-1))),p=Wh(i,o,a),f=t/mt,b=p.slice(0,-1).map((I,E)=>{let k=Math.max(1,Math.floor(I/f)),P=Math.max(k+1,Math.ceil(p[E+1]/f));return[k,Math.min(mt/2,P)]}),g=p.filter(I=>I<150).length,y=Array.from({length:i},()=>new Array(c)),T=new Array(c),M=new Array(c).fill(0),v=null,x=new Float64Array(mt),A=new Float64Array(mt);for(let I=0;I<c;I++){let k=Math.round((I+.5)*m)-mt/2;for(let j=0;j<mt;j++){let Z=l[k+j];x[j]=(Z??0)*d[j],A[j]=0}Gh(x,A);let P=[];b.forEach(([j,Z],ne)=>{let pe=0;for(let be=j;be<Z;be++)pe+=Math.hypot(x[be],A[be]);let ae=pe/(Z-j)*(4/mt);y[ne][I]=ae,ne<Math.max(1,g)&&P.push(ae)}),v&&(M[I]=P.reduce((j,Z,ne)=>j+Math.max(0,Z-(v[ne]??0)),0)),v=P;let G=Math.round(I*m),X=Math.min(u,Math.round((I+1)*m)),U=0;for(let j=G;j<X;j++)U+=l[j]**2;T[I]=Math.sqrt(U/Math.max(1,X-G))}let w=y.map(I=>jc(I.map(si),.98)),R=Math.max(...w),N=y.map((I,E)=>{let k=Math.max(w[E],R-Uh,Ic-20);return I.map(P=>Zr(zc(1-(k-si(P))/Vh)))}),V=Math.max(Ic,jc(T.map(si),.98)),$=T.map(I=>Zr(zc(1-(V-si(I))/$h)));return{fps:n,frames:c,bands:N,level:$,beats:Hh(M,n)}}function Hh(e,t){let r=Math.max(2,Math.round(t*.5)),n=Math.max(1,Math.round(t*.15)),i=Math.max(0,...e),o=[];for(let a=1;a<e.length;a++){let u=e[a];if(u<=i*.08||u<e[a-1]||u<(e[a+1]??0))continue;let l=e.slice(Math.max(0,a-r),a+r+1),c=l.reduce((p,f)=>p+f,0)/l.length,m=Math.sqrt(l.reduce((p,f)=>p+(f-c)**2,0)/l.length);if(u<c+1.5*m)continue;let d=o[o.length-1];d!==void 0&&a-d<n||o.push(a)}return o}function Tw(e,t){let r=e.length;if(r===0)return[];let n=e[0]?.length??0;return Array.from({length:t},(i,o)=>{let a=Math.floor(o*r/t),u=Math.max(a+1,Math.floor((o+1)*r/t));return Array.from({length:n},(l,c)=>{let m=0;for(let d=a;d<u;d++)m+=e[d][c]??0;return Zr(m/(u-a))})})}function Mw(e,t){if(t<=0)return[...e];let r=1/(t+1),n=0;return e.map(i=>(n=i>=n?i:n+(i-n)*r,Zr(n)))}function Aw(){return s.object({fps:s.number().positive(),frames:s.number().int().min(0),bands:s.array(s.array(s.number())),level:s.array(s.number()),beats:s.array(s.number().int())})}h();function Vc(e,t=0,r={}){let n=r.tolerance??.25;if(e.length===0)return[];if(e.length===1)return[[t,e[0]]];let i=new Uint8Array(e.length);i[0]=1,i[e.length-1]=1;let o=[[0,e.length-1]];for(;o.length>0;){let[u,l]=o.pop(),c=e[u],m=e[l],d=-1,p=n;for(let f=u+1;f<l;f++){let b=(f-u)/(l-u),g=Math.abs(e[f]-(c+(m-c)*b));g>p&&(p=g,d=f)}d!==-1&&(i[d]=1,o.push([u,d],[d,l]))}let a=[];for(let u=0;u<e.length;u++)i[u]&&a.push([t+u,e[u]]);return a}function Rw(e,t,r,n){let i=[];for(let o=t;o<=r;o++)i.push(e(o));return Vc(i,t,n)}function ui(e,{stiffness:t=170,damping:r=26,mass:n=1}={}){if(e<=0)return 0;let i=Math.sqrt(t/n),o=r/(2*Math.sqrt(t*n));if(o<1){let m=i*Math.sqrt(1-o*o);return 1-Math.exp(-o*i*e)*(Math.cos(m*e)+o*i/m*Math.sin(m*e))}if(o===1)return 1-Math.exp(-i*e)*(1+i*e);let a=-i*(o-Math.sqrt(o*o-1)),u=-i*(o+Math.sqrt(o*o-1)),l=a/(a-u);return 1-((1-l)*Math.exp(a*e)+l*Math.exp(u*e))}function Yh(e,t,r=.001,n=600){let i=0;for(let o=0;o<=n;o++)Math.abs(1-ui(o/e,t))>r&&(i=o);return Math.min(n,i+1)}function Ow(e,t,r,n,i,o=Math.max(1e-4,Math.abs(r-t)*.002)){let a=Yh(n,i),u=Array.from({length:a+1},(l,c)=>c===a?r:t+(r-t)*ui(c/n,i));return Vc(u,e,{tolerance:o})}function Nw(e,t,r,n,i={stiffness:230,damping:24}){let o=[...e].sort((d,p)=>d[0]-p[0]),a=new Array(r+1),u=t,l=t,c=0,m=0;for(let d=0;d<=r;d++){for(;m<o.length&&o[m][0]<=d;)u=u+(l-u)*ui((d-c)/n,i),l=o[m][1],c=o[m][0],m++;a[d]=u+(l-u)*ui((d-c)/n,i)}return a}h();var Xh={white:[255,255,255,1],black:[0,0,0,1],transparent:[0,0,0,0]};function qr(e){let t=e.trim().toLowerCase(),r=Xh[t];if(r)return[...r];let n=t.match(/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/);if(n?.[1]){let o=n[1].length<=4?[...n[1]].map(u=>u+u).join(""):n[1],a=u=>Number.parseInt(o.slice(u,u+2),16);return[a(0),a(2),a(4),o.length===8?a(6)/255:1]}let i=t.match(/^rgba?\(([^)]*)\)$/);if(i?.[1]){let o=i[1].split(/[\s,/]+/).filter(Boolean);if(o.length!==3&&o.length!==4)return null;let a=(d,p)=>d.endsWith("%")?Number.parseFloat(d)/100*p:Number(d),[u,l,c]=o.slice(0,3).map(d=>a(d,255)),m=o[3]===void 0?1:a(o[3],1);return[u,l,c,m].some(d=>d===void 0||Number.isNaN(d))?null:[u,l,c,m]}return null}var Ea=([e,t,r,n])=>`rgba(${Math.round(e)},${Math.round(t)},${Math.round(r)},${+n.toFixed(3)})`;function Ew(e,t){let r=qr(e);return r?Ea([r[0],r[1],r[2],t]):e}function Bw(e){let t=qr(e);return Ea(t?[t[0],t[1],t[2],0]:[0,0,0,0])}function Uc(e,t,r){let n=qr(e),i=qr(t);if(!n||!i)return e;let o=n.map((a,u)=>a+(i[u]-a)*r);return o[3]<1?Ea(o):`#${o.slice(0,3).map(a=>Math.round(a).toString(16).padStart(2,"0")).join("")}`}function La(e){let t=qr(e);if(!t)return null;let r=n=>{let i=n/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4};return .2126*r(t[0])+.7152*r(t[1])+.0722*r(t[2])}function li(e,t){let r=La(e),n=La(t);if(r===null||n===null)return null;let[i,o]=r>n?[r,n]:[n,r];return(i+.05)/(o+.05)}function $c(e){return(La(e)??0)>.179}function Iw(e,t="#ffffff",r="#0b0c0e"){return(li(t,e)??0)>=(li(r,e)??0)?t:r}h();h();h();h();function Ba(e){let t=e>>>0,r=()=>{t=t+2654435769>>>0;let n=t;return n=Math.imul(n^n>>>16,2246822507)>>>0,n=Math.imul(n^n>>>13,3266489909)>>>0,n=(n^n>>>16)>>>0,n/4294967296};return{next:r,range:(n,i)=>n+(i-n)*r(),int:(n,i)=>n+Math.floor(r()*(i-n+1)),pick:n=>{if(n.length===0)throw new Error("rng.pick: empty list");return n[Math.floor(r()*n.length)]},spread:n=>(r()*2-1)*n}}function Zh(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function Kr(e,t){return Ba((Math.imul(e>>>0,2654435761)^Zh(String(t)))>>>0)}function $w(e,t){return Ia(t),Math.round(e*t)}function Gw(e,t){return Ia(t),e/t}function Ww(e,t){return Math.round(e*t)}function Hw(e,t){return!t||t<=0?Math.round(e):Math.round(Math.round(e/t)*t)}function ci(e,t){return Ia(t),Math.max(1,Math.round(e*t/30))}function Yw(e,t,r="forward",n=1){return e<=0?[]:qh(e,r,n).map(o=>Math.round(o*t))}function qh(e,t,r=1){let n=Array.from({length:e},(o,a)=>a),i=(e-1)/2;switch(t){case"forward":return n;case"reverse":return n.map(o=>e-1-o);case"center":return n.map(o=>Math.abs(o-i));case"edges":return n.map(o=>i-Math.abs(o-i));case"random":{let o=Ba(r),a=[...n];for(let l=a.length-1;l>0;l--){let c=Math.floor(o.next()*(l+1));[a[l],a[c]]=[a[c],a[l]]}let u=new Array(e);return a.forEach((l,c)=>{u[l]=c}),u}}}var Kh=(e,t)=>({start:e,end:e+Math.max(0,t)}),Xw=(e,t)=>e>=t.start&&e<=t.end;function Zw(e){if(e.length===0)return{start:0,end:0};let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let n of e)t=Math.min(t,n.start),r=Math.max(r,n.end);return{start:t,end:r}}function qw(e,t=0,r=0){let n=[],i=t;for(let o of e)n.push(Kh(i,o)),i+=o+r;return n}function Ia(e){if(!(e>0)||!Number.isFinite(e))throw new Error(`fps must be a positive number, got ${e}`)}var Qr=["none","fade","rise","drop","scale","pop","slide-left","slide-right","slide-up","slide-down","tilt","mask-up","mask-down","mask-left","mask-right"];function ja(e,t,r,n=30){if(e===!1||e===void 0)return null;let i=typeof e=="string"?{preset:e}:e;if(i.preset==="none")return null;if(!Qr.includes(i.preset))throw new Error(`Unknown motion preset "${i.preset}". Use one of: ${Qr.join(", ")}.`);return{preset:i.preset,duration:Math.max(1,Math.round(i.duration??ci(r.motion.speed.base,n))),ease:i.ease??(i.preset==="pop"?r.motion.ease.snap:t==="enter"?r.motion.ease.enter:r.motion.ease.exit),distance:i.distance??(i.preset.startsWith("slide-")?120:40)*r.scale,delay:Math.max(0,Math.round(i.delay??0)),blur:Qh(i.blur??i.preset.startsWith("slide-"))}}var Qh=e=>e===!0?90:e===!1?0:Math.max(0,Math.min(360,e)),Gc=e=>e.preset.startsWith("mask-");function Wc(e,t){switch(e.preset){case"mask-up":return[0,t?.height??e.distance];case"mask-down":return[0,-(t?.height??e.distance)];case"mask-left":return[t?.width??e.distance,0];case"mask-right":return[-(t?.width??e.distance),0];case"rise":case"slide-up":return[0,e.distance];case"drop":case"slide-down":return[0,-e.distance];case"slide-left":return[e.distance,0];case"slide-right":return[-e.distance,0];default:return[0,0]}}function Hc(e,t=0,r){let n=t+e.delay,i=n+e.duration,o=Q.create();Gc(e)||o.keys("opacity",[[n,0],[i,1,e.ease]]);let[a,u]=Wc(e,r);return a!==0&&o.keys("x",[[n,a],[i,0,e.ease]]),u!==0&&o.keys("y",[[n,u],[i,0,e.ease]]),e.preset==="scale"&&o.keys("scale",[[n,.92],[i,1,e.ease]]),e.preset==="pop"&&o.keys("scale",[[n,.6],[i,1,e.ease]]),e.preset==="tilt"&&(o.keys("perspective",[[n,1200]]),o.keys("rotateX",[[n,28],[i,0,e.ease]]),o.keys("translateZ",[[n,-160],[i,0,e.ease]])),o}function Yc(e,t,r){let n=t-e.delay,i=Math.max(0,n-e.duration),o=Q.create();Gc(e)||o.keys("opacity",[[i,1],[n,0,e.ease]]);let[a,u]=Wc(e,r);return a!==0&&o.keys("x",[[i,0],[n,-a,e.ease]]),u!==0&&o.keys("y",[[i,0],[n,-u,e.ease]]),e.preset==="scale"&&o.keys("scale",[[i,1],[n,.92,e.ease]]),e.preset==="pop"&&o.keys("scale",[[i,1],[n,.6,e.ease]]),e.preset==="tilt"&&(o.keys("perspective",[[i,1200]]),o.keys("rotateX",[[i,0],[n,-28,e.ease]]),o.keys("translateZ",[[i,0],[n,-160,e.ease]])),o}h();var mi={ease:{enter:"expo.out",exit:"power2.in",move:"power3.inOut",snap:"back.out(1.6)"},speed:{fast:8,base:16,slow:30},spring:{settle:{stiffness:230,damping:24},base:{stiffness:260,damping:20},pop:{stiffness:320,damping:14}}},za={regular:400,medium:500,semibold:600,bold:700,heavy:800},Ua={low:{opacity:.32,distance:3,size:10,edge:.07},mid:{opacity:.4,distance:10,size:30,edge:.08},high:{opacity:.5,distance:22,size:60,edge:.1}},Xc={low:{opacity:.1,distance:2,size:8,edge:0},mid:{opacity:.14,distance:8,size:26,edge:0},high:{opacity:.2,distance:18,size:54,edge:0}},_a={radius:{sm:6,md:12,lg:24,pill:999},stroke:{hair:1,base:2,bold:4}},Va={display:"Inter",body:"Inter",mono:"JetBrains Mono"},Zc={graphite:{mode:"dark",color:{bg:"#0d0e11",surface:"#16181d",raised:"#1f2229",line:"#2b2f38",ink:"#f3f4f6",muted:"#8b909c",accent:"#5b8cff",accent2:"#b07cff",positive:"#3ecf8e",negative:"#ff5c5c",highlight:"#ffd23f",shadow:"#000000"},font:Va,weight:za,..._a,elevation:Ua,motion:mi,scale:1},paper:{mode:"light",color:{bg:"#f4f1ea",surface:"#fffdf8",raised:"#ffffff",line:"#dcd6c8",ink:"#1a1814",muted:"#6b665c",accent:"#e0451f",accent2:"#1f5fe0",positive:"#1f8a4c",negative:"#c8282d",highlight:"#ffe066",shadow:"#3b2f1e"},font:Va,weight:za,..._a,elevation:Xc,motion:mi,scale:1},signal:{mode:"dark",color:{bg:"#000000",surface:"#111111",raised:"#1c1c1c",line:"#333333",ink:"#ffffff",muted:"#a3a3a3",accent:"#c6ff00",accent2:"#ff2e88",positive:"#00e676",negative:"#ff1744",highlight:"#c6ff00",shadow:"#000000"},font:Va,weight:za,..._a,elevation:Ua,motion:{...mi,ease:{...mi.ease,enter:"back.out(1.8)"},speed:{fast:6,base:12,slow:24},spring:{settle:{stiffness:300,damping:26},base:{stiffness:340,damping:22},pop:{stiffness:400,damping:14}}},scale:1}};function Jr(e={},t=Zc.graphite){let r=qc(t,e);e.mode===void 0&&e.color?.bg!==void 0&&(r.mode=$c(r.color.bg)?"light":"dark",e.elevation===void 0&&(r.elevation=r.mode==="light"?Xc:Ua));let n=li(r.color.ink,r.color.surface);if(n!==null&&n<4.5)throw new Error(`Theme contrast too low: ink ${r.color.ink} on surface ${r.color.surface} is ${n.toFixed(2)}:1 (needs 4.5:1).`);return r}function ov(e,t,r=30){return ci(e.motion.speed[t],r)}function qc(e,t){if(t===void 0)return e;if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(e)||Array.isArray(t))return t;let r={...e};for(let[n,i]of Object.entries(t))r[n]=qc(r[n],i);return r}function Jh(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=i.map(o=>{let a={...o,frame:o.frame+t};return typeof o.end=="number"&&(a.end=o.end+t),a});return r}function eg(e,{rest:t=0,peak:r=1,attack:n=0,release:i=8,ease:o="power2.out"}={}){let a=e.map(l=>typeof l=="number"?l:l.frame).sort((l,c)=>l-c),u=new Map;for(let l of a){let c=Math.max(0,l-n);u.has(c)||u.set(c,[c,t]),u.set(l,[l,r]),u.set(l+i,[l+i,t,o])}return[...u.values()].sort((l,c)=>l[0]-c[0])}var tg=()=>s.custom(e=>typeof e=="function",{message:"Expected a function"});function Kc(){return s.union([s.enum(Qr),s.object({preset:s.enum(Qr),duration:s.number().int().positive().optional(),ease:s.string().optional(),distance:s.number().optional(),delay:s.number().int().min(0).optional(),blur:s.union([s.boolean(),s.number().min(0).max(360)]).optional()})])}var Qc;function rg(){return Qc??=ng(),Qc}function ng(){return s.object({id:s.string().min(1).optional(),at:s.number().int().min(0).optional(),duration:s.number().int().positive().optional(),hold:s.number().int().min(0).optional(),enter:s.union([Kc(),s.literal(!1)]).optional(),exit:s.union([Kc(),s.literal(!1)]).optional(),x:s.number().optional(),y:s.number().optional(),width:s.number().positive().optional(),height:s.number().positive().optional(),position:s.enum(["absolute","relative"]).optional(),theme:s.custom(e=>typeof e=="object"&&e!==null).optional(),seed:s.number().int().optional(),fps:s.number().positive().optional(),canvas:s.object({width:s.number().positive(),height:s.number().positive()}).strict().optional(),customize:tg().optional()})}function dv(e){return e}function ig(e){let t=e.theme?Jr(e.theme):void 0;return r=>n=>r({...e,...n,theme:n.theme&&t?Jr(n.theme,t):n.theme??t})}function og(e,t=0){if(!Number.isFinite(e.span.end))throw new Error("after(): this component is open-ended (it stays until its parent ends). Give it a `duration`, or use its cues.");return e.span.end+t}var ag=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();function Jc(e,t){let r;return n=>{r??=rg().extend(t.props()).strict();let i=r.safeParse(n??{});if(!i.success){let o=Object.keys(r.shape),a=i.error.issues.map(l=>{let c=l.path.join(".")||"(props)",m=l.code==="unrecognized_keys"&&l.path.length===0?sg(l.keys,o):"";return` - ${c}: ${l.message}${m}`}).join(`
|
|
277
|
+
`),u=typeof n?.id=="string"?`${t.name}#${n.id}`:t.name;throw new Error(`${u}: invalid props
|
|
278
|
+
${a}`)}return lg(e,t,i.data)}}function sg(e,t){let r=e.flatMap(n=>{let i,o=3;for(let a of t){let u=ug(n.toLowerCase(),a.toLowerCase());u<o&&([i,o]=[a,u])}return i?[`"${n}" \u2192 "${i}"`]:[]});return r.length>0?` (did you mean ${r.join(", ")}?)`:""}function ug(e,t){let r=Array.from({length:t.length+1},(n,i)=>i);for(let n=1;n<=e.length;n++){let i=[n];for(let o=1;o<=t.length;o++)i[o]=Math.min(r[o]+1,i[o-1]+1,r[o-1]+(e[n-1]===t[o-1]?0:1));r=i}return r[t.length]}function lg(e,t,r){let n=Jr(r.theme??{}),i=r.fps??30,o=r.seed??1,a=r.id??e.autoId(ag(t.name)),u=t.defaults??{},l=r.hold??u.hold??0,c={host:e,theme:n,fps:i,seed:o,id:a,partId:k=>`${a}-${k}`,rng:k=>Kr(o,k),requested:{width:r.width,height:r.height,duration:r.duration,at:r.at??0},hold:l,canvas:r.canvas??{width:1920*n.scale,height:1080*n.scale}},m=t.build(c,r),d=ja(r.enter===void 0?u.enter:r.enter,"enter",n,i),p=ja(r.exit===void 0?u.exit:r.exit,"exit",n,i),f=m.duration===null||m.openEnded===!0&&!p&&!m.afterHold,b=r.duration??(f||m.duration===null?null:Math.max(1,m.duration+l+(m.afterHold??0)+(p?p.duration+p.delay:0)));if(b===null&&p)throw new Error(`${t.name}: an exit needs a known end. Give \`duration\`, or drop \`exit\`.`);let g=r.width??m.width,y=r.height??m.height,T=Math.max(d?.blur??0,p?.blur??0),M=d?.preset.startsWith("mask-")||p?.preset.startsWith("mask-"),v=e.box({id:c.partId("stage"),position:"absolute",x:0,y:0,width:g,height:y,overflow:"visible",...T>0&&{motionBlurShutter:T},children:m.children}),x={width:g,height:y};d&&v.animate(Hc(d,0,x)),p&&b!==null&&v.animate(Yc(p,b,x));let A=r.x===void 0&&r.y===void 0&&!r.position?m.origin:void 0,w=r.x!==void 0||r.y!==void 0||A!==void 0,R=r.x??A?.[0]??0,N=r.y??A?.[1]??0,V=e.box({id:a,...w?{position:"absolute",x:R,y:N}:r.position?{position:r.position}:{},width:g,height:y,overflow:M?"hidden":"visible",startFrame:r.at??0,...b!==null&&{durationFrames:b},children:[v]}),$={...m.parts,root:V,stage:v};r.customize?.($),$a(V);let I=r.at??0,E=Jh(m.cues,I);if(Object.defineProperties(V,{cues:{value:E,enumerable:!1},span:{value:{start:I,end:b===null?Number.POSITIVE_INFINITY:I+b,duration:b??Number.POSITIVE_INFINITY},enumerable:!1},part:{value:k=>$[k],enumerable:!1},partNames:{value:Object.keys($),enumerable:!1}}),m.api){let k=m.api({x:w?R:0,y:w?N:0,width:g,height:y,absolute:w,start:I});for(let[P,G]of Object.entries(k))Object.defineProperty(V,P,{value:G,enumerable:!1})}return V}function $a(e){let t=e;for(let r of t.animation?.tracks??[]){let n=r.keyframes?.[0];!n||n.frame<=0||r.repeat||r.keyframes?.unshift({id:`${n.id}-hold`,frame:0,value:n.value})}for(let r of t.children??[])$a(r);t.matte?.node&&$a(t.matte.node)}h();h();var em=(e,t)=>Math.hypot(t[0]-e[0],t[1]-e[1]),tm=(e,t,r)=>[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r];function rm(e,t=16){if(e.length<2)return e.map(n=>[n[0],n[1]]);let r=[[e[0][0],e[0][1]]];for(let n=0;n<e.length-1;n++){let i=e[Math.max(0,n-1)],o=e[n],a=e[n+1],u=e[Math.min(e.length-1,n+2)];for(let l=1;l<=t;l++)r.push(cg(i,o,a,u,l/t))}return r}function cg(e,t,r,n,i){let o=(T,M)=>Math.max(1e-6,Math.sqrt(em(T,M))),u=0+o(e,t),l=u+o(t,r),c=l+o(r,n),m=u+(l-u)*i,d=(T,M,v,x)=>x===v?T:tm(T,M,(m-v)/(x-v)),p=d(e,t,0,u),f=d(t,r,u,l),b=d(r,n,l,c),g=d(p,f,0,l),y=d(f,b,u,c);return d(g,y,u,l)}function hv(e){if(e.length===0)throw new Error("arcPath: no points");let t=[0];for(let i=1;i<e.length;i++)t.push(t[i-1]+em(e[i-1],e[i]));let r=t[t.length-1],n=i=>{if(e.length===1||r===0)return[0,0];let o=Math.min(1,Math.max(0,i))*r,a=0,u=t.length-1;for(;u-a>1;){let c=a+u>>1;t[c]<=o?a=c:u=c}let l=t[u]-t[a];return[a,l>0?(o-t[a])/l:0]};return{points:e,length:r,at(i){let[o,a]=n(i);return e.length===1?[e[0][0],e[0][1]]:tm(e[o],e[Math.min(o+1,e.length-1)],a)},angleAt(i){let[o]=n(i),a=e[Math.min(o,e.length-2)]??e[0],u=e[Math.min(o+1,e.length-1)];return Math.atan2(u[1]-a[1],u[0]-a[0])}}}function dt(e,t=!1){if(e.length===0)return"";let r=a=>Math.round(a*100)/100,[n,...i]=e,o=[`M${r(n[0])} ${r(n[1])}`];for(let a of i)o.push(`L${r(a[0])} ${r(a[1])}`);return t&&o.push("Z"),o.join(" ")}function gv(e,t,r=0,n=0){let i=c=>Math.round(c*1e3)/1e3,o=e.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi)??[],a=[],u="",l=0;for(let c of o){if(/^[a-zA-Z]$/.test(c)){u=c,l=0,a.push(u);continue}let m=Number(c),d=u.toUpperCase(),p=u!==d;if(d==="A"){let f=l%7;l++,f===2||f===3||f===4?a.push(String(m)):f<2||p?a.push(String(i(m*t))):a.push(String(i(m*t+(f===5?r:n))));continue}p?a.push(String(i(m*t))):d==="H"?a.push(String(i(m*t+r))):d==="V"?a.push(String(i(m*t+n))):(a.push(String(i(m*t+(l%2===0?r:n)))),l++)}return a.join(" ").replace(/ ?([a-zA-Z]) ?/g,"$1")}function wv(e,t,r="power2.inOut"){return[[e,0],[e+Math.max(1,t),1,r]]}function en(e,{wobble:t=0,seed:r=1}={},n=0){if(t<=0||e.length===0)return e.map(c=>[c[0],c[1]]);let i=Kr(r,`wobble:${n}`),o=Math.max(2,Math.min(8,Math.ceil(e.length/6))),a=Array.from({length:o},()=>i.spread(t)),u=Array.from({length:o},()=>i.spread(t)),l=(c,m)=>{let d=m*(c.length-1),p=Math.min(c.length-2,Math.floor(d)),f=d-p,b=f*f*(3-2*f);return c[p]*(1-b)+c[p+1]*b};return e.map((c,m)=>{let d=e.length===1?0:m/(e.length-1);return[c[0]+l(a,d),c[1]+l(u,d)]})}function vv(e,{padding:t=0,wobble:r=0,seed:n=1}={},i=0){let o=e.x+e.width/2,a=e.y+e.height/2,u=e.width/2+t,l=e.height/2+t,c=Kr(n,`ellipse:${i}`),m=r>0?-Math.PI*.6+c.spread(.3):0,d=r>0?Math.PI*2*1.08:Math.PI*2,p=64,f=[];for(let b=0;b<=p;b++){let g=m+d*b/p,y=r>0?1+(b/p-.5)*.06:1;f.push([o+Math.cos(g)*u*y,a+Math.sin(g)*l*y])}return dt(en(f,{wobble:r,seed:n},i),r<=0)}function kv(e,{padding:t=0,wobble:r=0,seed:n=1}={},i=0){let o=e.x-t,a=e.y-t,u=e.x+e.width+t,l=e.y+e.height+t,c=[[o,a],[u,a],[u,l],[o,l],[o,a]];if(r<=0)return dt(c.slice(0,4),!0);let m=u-o,d=[[o+m*.06,a]];for(let p=0;p<4;p++){let f=c[p],b=c[p+1];for(let g=1;g<=8;g++){let y=g/8;p===0&&f[0]+(b[0]-f[0])*y<o+m*.06||d.push([f[0]+(b[0]-f[0])*y,f[1]+(b[1]-f[1])*y])}}return d.push([o+m*.14,a+(l-a)*.01]),dt(en(d,{wobble:r,seed:n},i))}function Pv(e,t,{wobble:r=0,seed:n=1}={},i=0){let o=r>0?16:1,a=[];for(let u=0;u<=o;u++){let l=u/o;a.push([e[0]+(t[0]-e[0])*l,e[1]+(t[1]-e[1])*l])}return dt(en(a,{wobble:r,seed:n},i))}function Tv(e,t,{amplitude:r=6,waves:n,wobble:i=0,seed:o=1}={},a=0){let u=Math.hypot(t[0]-e[0],t[1]-e[1]),l=n??Math.max(2,Math.round(u/28)),c=Math.atan2(t[1]-e[1],t[0]-e[0]),m=-Math.sin(c),d=Math.cos(c),p=l*8,f=[];for(let b=0;b<=p;b++){let g=b/p,y=Math.sin(g*l*Math.PI*2)*r;f.push([e[0]+(t[0]-e[0])*g+m*y,e[1]+(t[1]-e[1])*g+d*y])}return dt(en(f,{wobble:i,seed:o},a))}var mg=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)};function dg(e,t){let r=t;for(let n=e.length-1;n>0;n--){let i=e[n],o=e[n-1],a=Math.hypot(i[0]-o[0],i[1]-o[1]);if(a>=r&&a>0){let u=r/a;return[i[0]+(o[0]-i[0])*u,i[1]+(o[1]-i[1])*u]}r-=a}return e[0]}function Mv(e,t,{curve:r="arc",headSize:n=18,wobble:i=0,seed:o=1}={},a=0){let u=t[0]-e[0],l=t[1]-e[1],c=Math.hypot(u,l)||1,m=-l/c,d=u/c,p=r==="straight"?0:r==="arc"?.18:.35,f=r==="swoop"?[e,[e[0]+u*.3+m*c*p,e[1]+l*.3+d*c*p],[e[0]+u*.75-m*c*p*.4,e[1]+l*.75-d*c*p*.4],t]:[e,[e[0]+u*.5+m*c*p,e[1]+l*.5+d*c*p],t],b=p===0?[e,t]:rm(f,12),g=en(b,{wobble:i,seed:o},a).map((A,w)=>{let R=b.length===1?0:w/(b.length-1),N=R<=.75?1:1-mg((R-.75)/.25),V=b[w];return[V[0]+(A[0]-V[0])*N,V[1]+(A[1]-V[1])*N]}),y=dg(b,n),T=Math.atan2(t[1]-y[1],t[0]-y[0]),M=A=>[t[0]-Math.cos(T+A*.5)*n,t[1]-Math.sin(T+A*.5)*n],v=M(1),x=M(-1);return{shaft:dt(g),head:`${dt([v,t])} ${dt([t,x]).replace(/^M/,"L")}`}}function Av(e,{start:t,end:r,every:n,variants:i=3}){let o=Array.from({length:Math.max(1,i)},(l,c)=>e(c));if(n<=0||o.length===1)return[[t,o[0]]];let a=[],u=0;for(let l=t;l<=r;l+=n)a.push([l,o[u%o.length],"hold"]),u++;return a}h();var di={char:"textIndex",word:"wordIndex",line:"lineIndex"},pg=e=>String(Math.round(e*1e4)/1e4),vt=e=>`[${e.map(pg).join(",")}]`;function Ov(e,t,r,n){let i=Math.max(1,Math.round(t.duration)),o=Array.from({length:i+1},(m,d)=>ai(t.ease,d/i)),a=di[e],u=m=>`(${m}[${a}]??${m}[${m}.length-1])`,l=r==="enter"?"1-v":"v",c=n?`(${l})*${u("F")}`:l;return["((S,L,F)=>{",`const t=frame-${u("S")};`,"const k=floor(t);",`const v=t<=0?L[0]:t>=${i}?L[${i}]:L[k]+(L[k+1]-L[k])*(t-k);`,`return ${c};`,`})(${vt(t.starts)},${vt(o)},${n?vt(n):"0"})`].join("")}function Nv(e,t,r,n){let i=di[e],o=n?`*(${vt(n)}[${i}]??0)`:"";return`((S,E)=>{const s=S[${i}];return s!==undefined&&frame>=s&&frame<E[${i}]?1${o}:0;})(${vt(t)},${vt(r)})`}function Fv(e,t){return`((S)=>frame<(S[${di[e]}]??S[S.length-1])?1:0)(${vt(t)})`}function Lv(e,t){return t.filter((r,n)=>e[n]!==`
|
|
279
|
+
`)}function Ev(e,t){return`(${vt(t)}[${di[e]}]??0)`}function Bv(e,t,r){return{name:e,selectors:[{type:"expression",expression:t,mode:"add",amount:1}],props:r}}function Iv(e,t){let r={textIndex:t.textIndex??0,wordIndex:t.wordIndex??0,lineIndex:t.lineIndex??0,frame:t.frame,floor:Math.floor,clamp:(o,a,u)=>Math.max(a,Math.min(u,o)),abs:Math.abs,min:Math.min,max:Math.max},n=new Function(...Object.keys(r),`return (${e});`),i=Number(n(...Object.values(r)));return Number.isFinite(i)?Math.max(-1,Math.min(1,i)):0}h();var fg={titles:{landscape:{x:.06,top:.08,bottom:.1},portrait:{x:.08,top:.1,bottom:.24}},captions:{landscape:{x:.1,top:.08,bottom:.1},portrait:{x:.08,top:.12,bottom:.22}}};function _v(e,t,r=fg.titles){if(t&&typeof t=="object")return t;let{width:n,height:i}=e,a=(t?t==="portrait":i>n)?r.portrait:r.landscape;return{x:n*a.x,y:i*a.top,width:n*(1-2*a.x),height:i*(1-a.top-a.bottom)}}h();function $v(e){if(!/^[A-Z][A-Za-z0-9]+$/.test(e.name))throw new Error(`Component name must be PascalCase: "${e.name}"`);if(e.summary.length>200)throw new Error(`${e.name}: summary must be one sentence (\u2264 200 chars).`);return e}h();var nm;function Yv(){return nm??=s.custom(e=>e!=null&&(Array.isArray(e)||typeof e=="object"||typeof e=="function"),{message:"Expected a target: [x, y], a rect, { node }, { text }, { track } or (frame) => point"}),nm}h();function hg(e,t){let r=e.elevation[t],n=e.scale;return{...r.opacity>0&&{dropShadow:{color:e.color.shadow,opacity:r.opacity,angle:90,distance:r.distance*n,size:r.size*n}},...r.edge>0&&{innerShadow:{color:"#ffffff",opacity:r.edge,angle:270,distance:Math.max(1,n),size:0,blendMode:"normal"}}}}function Kv(e,t,r,n){if(n===!1)return t;let i=hg(r,n);return Object.keys(i).length>0?e.style(t,i):t}function Qv(e,t,r=.05){if(t.mode==="light"||r<=0)return e;let n=Uc(e,"#ffffff",r);return n===e?e:`linear-gradient(180deg, ${n} 0%, ${e} 100%)`}h();h();function t1(e){let t=[];for(let r of e.matchAll(/\S+/g)){let n=r.index??0;t.push({text:r[0],start:n,end:n+r[0].length,index:t.length})}return t}function im(e,t,r=0){if(typeof t=="string"){let o=0;for(let a=0;;a++){let u=e.indexOf(t,o);if(u<0)return null;if(a===r)return[u,u+t.length];o=u+Math.max(1,t.length)}}let n=t.flags.includes("g")?t.flags:`${t.flags}g`,i=0;for(let o of e.matchAll(new RegExp(t.source,n))){if(i===r)return[o.index??0,(o.index??0)+o[0].length];i++}return null}function gg(e,t,r){if(!r.width||!r.align||r.align==="left")return 0;let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let a of e.glyphs)a.line!==t||a.char.trim()===""||(n=Math.min(n,a.x),i=Math.max(i,a.x+a.width));if(!Number.isFinite(n))return 0;let o=r.width-(i-n);return(r.align==="center"?o/2:o)-n}function om(e,t,r,n){let i=new Map;for(let o of e.glyphs){if(o.index<t||o.index>=r||o.char.trim()==="")continue;let a=i.get(o.line)??{min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};a.min=Math.min(a.min,o.x),a.max=Math.max(a.max,o.x+o.width-(n.letterSpacing??0)),i.set(o.line,a)}return[...i.entries()].sort(([o],[a])=>o-a).map(([o,a])=>{let u=gg(e,o,n);return{x:a.min+u,y:o*e.lineHeight,width:a.max-a.min,height:e.lineHeight}})}var am=e=>Array.isArray(e)&&e.length===2&&e.every(t=>typeof t=="number"),bg=e=>typeof e=="object"&&e!==null&&["x","y","width","height"].every(t=>typeof e[t]=="number"),Ke=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0;function pi(e,t,r){if(typeof e=="function")return e(t);if(e&&typeof e.get=="function"){let n=t/r;return e.get({frame:t,fps:r,time:n,duration:0,durationMs:0,progress:0,deltaTime:1/r})}throw new Error("Tracked target values must be signals or (frame) => number.")}function o1(e,t={}){if(typeof e=="function")return{kind:"dynamic",anchor:"center",at:i=>{let o=e(i);return am(o)?{x:o[0],y:o[1],width:0,height:0}:o}};if(am(e))return{kind:"static",anchor:"center",rects:[{x:e[0],y:e[1],width:0,height:0}]};if(bg(e))return{kind:"static",anchor:"center",rects:[e]};if("track"in e){let i=e.track,o=t.fps??30;return{kind:"dynamic",anchor:e.anchor??"center",at:a=>({x:pi(i.x,a,o),y:pi(i.y,a,o),width:pi(i.width,a,o),height:pi(i.height,a,o)})}}if("text"in e)return{kind:"static",anchor:e.anchor??"tip",rects:Sg(e,t)};let r=e.node,n=yg(r);if(!n)throw new Error(`Target node "${r.id??"?"}" has no absolute geometry. Give it numeric x, y, width and height, or target a rect.`);return{kind:"static",anchor:e.anchor??"center",rects:[n]}}function yg(e){let t=Ke(e.x),r=Ke(e.y),n=Ke(e.width),i=Ke(e.height);return t===void 0||r===void 0||n===void 0||i===void 0?null:{x:t,y:r,width:n,height:i}}function xg(e,t){let r=e.text,n=typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:null;if(n===null)throw new Error("Text target node has no string content.");let i=Ke(r.x),o=Ke(r.y);if(i===void 0||o===void 0)throw new Error(`Text target "${r.id??"?"}" needs numeric x and y so its glyphs can be placed.`);if(!t.measure)throw new Error("Text targets need a measure function.");let a=r.fontFamily??t.textDefaults?.fontFamily;if(!a)throw new Error("Text target has no fontFamily.");let u={...t.textDefaults,fontFamily:a,fontSize:Ke(r.fontSize)??t.textDefaults?.fontSize,fontWeight:r.fontWeight??t.textDefaults?.fontWeight,letterSpacing:Ke(r.letterSpacing)??t.textDefaults?.letterSpacing,lineHeight:Ke(r.lineHeight)??t.textDefaults?.lineHeight,width:Ke(r.width),align:wg(r.align),direction:r.direction},l=e.range??(e.match!==void 0?im(n,e.match,e.nth??0):[0,n.length]);if(!l)throw new Error(`Text target: "${String(e.match)}" not found in "${n}".`);return{content:n,metrics:t.measure(n,u),options:u,range:[l[0],l[1]],x:i,y:o}}function Sg(e,t){let r=xg(e,t),n=om(r.metrics,r.range[0],r.range[1],r.options);if(n.length===0)throw new Error("Text target range covers no glyphs.");return n.map(i=>({...i,x:i.x+r.x,y:i.y+r.y}))}function wg(e){return e==="center"?"center":e==="end"||e==="right"?"right":"left"}function vg(e){if(e.length===0)return{x:0,y:0,width:0,height:0};let t=Number.POSITIVE_INFINITY,r=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let o of e)t=Math.min(t,o.x),r=Math.min(r,o.y),n=Math.max(n,o.x+o.width),i=Math.max(i,o.y+o.height);return{x:t,y:r,width:n-t,height:i-r}}function sm(e,t="center",r=!1){let{x:n,y:i,width:o,height:a}=e;switch(t){case"tip":return r?[n,i+a/2]:[n+o/2,i+a/2];case"center":return[n+o/2,i+a/2];case"top":return[n+o/2,i];case"bottom":return[n+o/2,i+a];case"left":return[n,i+a/2];case"right":return[n+o,i+a/2];case"top-left":return[n,i];case"top-right":return[n+o,i];case"bottom-left":return[n,i+a];case"bottom-right":return[n+o,i+a]}}function a1(e,t=0,r=!1){if(e.kind==="dynamic")return sm(e.at(t),e.anchor,r);let n=e.rects[0];return sm(e.anchor==="tip"?n:vg(e.rects),e.anchor,r)}h();function l1(e,t,r,n,i=0){let o=r/t,a=[],u=i;for(let l=0;l<e.length;l++){let c=e[l-1]??"",m=l===0?0:o*(1+n.spread(.3));c===" "&&(m+=o*.6),/[.,!?;:]/.test(c)&&(m+=o*3),u+=m,a.push(Math.max(i,Math.round(u)))}for(let l=1;l<a.length;l++)a[l]=Math.max(a[l],a[l-1]+1);return a}h();h();var tn=class{textures=new Map;set(t,r){this.textures.set(t,r)}get(t){return this.textures.get(t)}has(t){return this.textures.has(t)}getOutputs(){return{canny:this.textures.get("canny"),depth:this.textures.get("depth"),normals:this.textures.get("normals"),poseSkeleton:this.textures.get("poseSkeleton"),segmentationMask:this.textures.get("segmentationMask"),faceLandmarks:this.textures.get("faceLandmarks"),motionVectors:this.textures.get("motionVectors"),deflickered:this.textures.get("deflickered")}}createBindGroupEntry(t,r){let n=this.textures.get(t);if(!n)throw new Error(`[ControlNetMultiplexer] Cannot create bind group entry: conditioning texture "${t}" is not registered in VRAM.`);return{binding:r,resource:n.createView({label:`controlnet_${t}_view`})}}exportTensorView(t){let r=this.textures.get(t);if(!r)throw new Error(`[ControlNetMultiplexer] Conditioning tensor "${t}" not found in multiplexer.`);return{texture:r,width:r.width,height:r.height,format:r.format}}async readPixelsAsync(t,r){let n=this.textures.get(r);if(!n)throw new Error(`[ControlNetMultiplexer] Cannot read pixels: conditioning texture "${r}" is missing.`);let i=n.width,o=n.height,a=n.format,u=4;a==="rgba16float"||a==="rg32float"?u=8:a==="r32float"?u=4:a==="rgba32float"&&(u=16);let l=i*u,c=Math.ceil(l/256)*256,m=c*o,d=t.createBuffer({size:m,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:`controlnet_readback_staging_${r}`}),p=t.createCommandEncoder({label:`readback_encoder_${r}`});p.copyTextureToBuffer({texture:n},{buffer:d,bytesPerRow:c,rowsPerImage:o},[i,o,1]),t.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);let f=d.getMappedRange(),b=new Uint8Array(i*o*u),g=new Uint8Array(f);if(c===l)b.set(g.subarray(0,i*o*u));else for(let y=0;y<o;y++){let T=y*c,M=y*l;b.set(g.subarray(T,T+l),M)}return d.unmap(),d.destroy(),{width:i,height:o,format:a,data:b}}destroy(){for(let t of this.textures.values())try{t.destroy()}catch{}this.textures.clear()}};h();h();h();var um=`
|
|
280
|
+
struct CannyParams {
|
|
281
|
+
lowThreshold: f32,
|
|
282
|
+
highThreshold: f32,
|
|
283
|
+
width: u32,
|
|
284
|
+
height: u32,
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
@group(0) @binding(0) var inputTex: texture_2d<f32>;
|
|
288
|
+
@group(0) @binding(1) var magnitudeTex: texture_storage_2d<rgba16float, write>;
|
|
289
|
+
@group(0) @binding(2) var<uniform> params: CannyParams;
|
|
290
|
+
|
|
291
|
+
fn getLuma(coord: vec2<i32>, maxCoord: vec2<i32>) -> f32 {
|
|
292
|
+
let clamped = clamp(coord, vec2<i32>(0), maxCoord);
|
|
293
|
+
let c = textureLoad(inputTex, clamped, 0);
|
|
294
|
+
return dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
@compute @workgroup_size(16, 16)
|
|
298
|
+
fn computeSobel(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
299
|
+
if (id.x >= params.width || id.y >= params.height) { return; }
|
|
300
|
+
|
|
301
|
+
let x = i32(id.x);
|
|
302
|
+
let y = i32(id.y);
|
|
303
|
+
let maxCoord = vec2<i32>(i32(params.width) - 1, i32(params.height) - 1);
|
|
304
|
+
|
|
305
|
+
let p00 = getLuma(vec2<i32>(x - 1, y - 1), maxCoord);
|
|
306
|
+
let p10 = getLuma(vec2<i32>(x, y - 1), maxCoord);
|
|
307
|
+
let p20 = getLuma(vec2<i32>(x + 1, y - 1), maxCoord);
|
|
308
|
+
let p01 = getLuma(vec2<i32>(x - 1, y), maxCoord);
|
|
309
|
+
let p21 = getLuma(vec2<i32>(x + 1, y), maxCoord);
|
|
310
|
+
let p02 = getLuma(vec2<i32>(x - 1, y + 1), maxCoord);
|
|
311
|
+
let p12 = getLuma(vec2<i32>(x, y + 1), maxCoord);
|
|
312
|
+
let p22 = getLuma(vec2<i32>(x + 1, y + 1), maxCoord);
|
|
313
|
+
|
|
314
|
+
let gx = (p20 + 2.0 * p21 + p22) - (p00 + 2.0 * p01 + p02);
|
|
315
|
+
let gy = (p02 + 2.0 * p12 + p22) - (p00 + 2.0 * p10 + p20);
|
|
316
|
+
|
|
317
|
+
let mag = sqrt(gx * gx + gy * gy);
|
|
318
|
+
let angle = atan2(gy, gx);
|
|
319
|
+
|
|
320
|
+
// Quantize angle into 4 sectors (0: 0 deg, 1: 45 deg, 2: 90 deg, 3: 135 deg)
|
|
321
|
+
var sector: f32 = 0.0;
|
|
322
|
+
let a = (angle * 180.0 / 3.14159265 + 180.0) % 180.0;
|
|
323
|
+
if ((a >= 0.0 && a < 22.5) || (a >= 157.5 && a <= 180.0)) {
|
|
324
|
+
sector = 0.0;
|
|
325
|
+
} else if (a >= 22.5 && a < 67.5) {
|
|
326
|
+
sector = 1.0;
|
|
327
|
+
} else if (a >= 67.5 && a < 112.5) {
|
|
328
|
+
sector = 2.0;
|
|
329
|
+
} else {
|
|
330
|
+
sector = 3.0;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
textureStore(magnitudeTex, id.xy, vec4<f32>(mag, sector, 0.0, 1.0));
|
|
334
|
+
}
|
|
335
|
+
`,lm=`
|
|
336
|
+
struct CannyParams {
|
|
337
|
+
lowThreshold: f32,
|
|
338
|
+
highThreshold: f32,
|
|
339
|
+
width: u32,
|
|
340
|
+
height: u32,
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
@group(0) @binding(0) var magnitudeTex: texture_2d<f32>;
|
|
344
|
+
@group(0) @binding(1) var edgeTex: texture_storage_2d<rgba8unorm, write>;
|
|
345
|
+
@group(0) @binding(2) var<uniform> params: CannyParams;
|
|
346
|
+
|
|
347
|
+
@compute @workgroup_size(16, 16)
|
|
348
|
+
fn computeNonMaxSuppression(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
349
|
+
if (id.x >= params.width || id.y >= params.height) { return; }
|
|
350
|
+
|
|
351
|
+
let x = i32(id.x);
|
|
352
|
+
let y = i32(id.y);
|
|
353
|
+
let maxCoord = vec2<i32>(i32(params.width) - 1, i32(params.height) - 1);
|
|
354
|
+
|
|
355
|
+
let center = textureLoad(magnitudeTex, vec2<i32>(x, y), 0);
|
|
356
|
+
let mag = center.r;
|
|
357
|
+
let sector = u32(round(center.g));
|
|
358
|
+
|
|
359
|
+
var n1 = 0.0;
|
|
360
|
+
var n2 = 0.0;
|
|
361
|
+
|
|
362
|
+
switch (sector) {
|
|
363
|
+
case 0u: {
|
|
364
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y), vec2<i32>(0), maxCoord), 0).r;
|
|
365
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y), vec2<i32>(0), maxCoord), 0).r;
|
|
366
|
+
}
|
|
367
|
+
case 1u: {
|
|
368
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
369
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
370
|
+
}
|
|
371
|
+
case 2u: {
|
|
372
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
373
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
374
|
+
}
|
|
375
|
+
default: {
|
|
376
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
377
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
var edge = 0.0;
|
|
382
|
+
// Non-maximum suppression along gradient sector with directional tie-breaking
|
|
383
|
+
if (mag > n1 && mag >= n2 && mag > 0.0) {
|
|
384
|
+
if (mag >= params.highThreshold) {
|
|
385
|
+
edge = 1.0;
|
|
386
|
+
} else if (mag >= params.lowThreshold) {
|
|
387
|
+
edge = 0.5;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
textureStore(edgeTex, id.xy, vec4<f32>(edge, edge, edge, 1.0));
|
|
392
|
+
}
|
|
393
|
+
`,cm=`
|
|
394
|
+
struct CannyParams {
|
|
395
|
+
lowThreshold: f32,
|
|
396
|
+
highThreshold: f32,
|
|
397
|
+
width: u32,
|
|
398
|
+
height: u32,
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
@group(0) @binding(0) var magnitudeTex: texture_2d<f32>;
|
|
402
|
+
@group(0) @binding(1) var edgeTex: texture_storage_2d<r32float, write>;
|
|
403
|
+
@group(0) @binding(2) var<uniform> params: CannyParams;
|
|
404
|
+
|
|
405
|
+
@compute @workgroup_size(16, 16)
|
|
406
|
+
fn computeNonMaxSuppression(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
407
|
+
if (id.x >= params.width || id.y >= params.height) { return; }
|
|
408
|
+
|
|
409
|
+
let x = i32(id.x);
|
|
410
|
+
let y = i32(id.y);
|
|
411
|
+
let maxCoord = vec2<i32>(i32(params.width) - 1, i32(params.height) - 1);
|
|
412
|
+
|
|
413
|
+
let center = textureLoad(magnitudeTex, vec2<i32>(x, y), 0);
|
|
414
|
+
let mag = center.r;
|
|
415
|
+
let sector = u32(round(center.g));
|
|
416
|
+
|
|
417
|
+
var n1 = 0.0;
|
|
418
|
+
var n2 = 0.0;
|
|
419
|
+
|
|
420
|
+
switch (sector) {
|
|
421
|
+
case 0u: {
|
|
422
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y), vec2<i32>(0), maxCoord), 0).r;
|
|
423
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y), vec2<i32>(0), maxCoord), 0).r;
|
|
424
|
+
}
|
|
425
|
+
case 1u: {
|
|
426
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
427
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
428
|
+
}
|
|
429
|
+
case 2u: {
|
|
430
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
431
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
432
|
+
}
|
|
433
|
+
default: {
|
|
434
|
+
n1 = textureLoad(magnitudeTex, clamp(vec2<i32>(x - 1, y - 1), vec2<i32>(0), maxCoord), 0).r;
|
|
435
|
+
n2 = textureLoad(magnitudeTex, clamp(vec2<i32>(x + 1, y + 1), vec2<i32>(0), maxCoord), 0).r;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
var edge = 0.0;
|
|
440
|
+
// Non-maximum suppression along gradient sector with directional tie-breaking
|
|
441
|
+
if (mag > n1 && mag >= n2 && mag > 0.0) {
|
|
442
|
+
if (mag >= params.highThreshold) {
|
|
443
|
+
edge = 1.0;
|
|
444
|
+
} else if (mag >= params.lowThreshold) {
|
|
445
|
+
edge = 0.5;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
textureStore(edgeTex, id.xy, vec4<f32>(edge, 0.0, 0.0, 1.0));
|
|
450
|
+
}
|
|
451
|
+
`;var rn=class{constructor(t){this.device=t;let r=t.createShaderModule({label:"canny_sobel.wgsl",code:um});this.sobelPipeline=t.createComputePipeline({label:"CannySobelPipeline",layout:"auto",compute:{module:r,entryPoint:"computeSobel"}});let n=t.createShaderModule({label:"canny_nms_rgba8.wgsl",code:lm});this.nmsRgba8Pipeline=t.createComputePipeline({label:"CannyNmsRgba8Pipeline",layout:"auto",compute:{module:n,entryPoint:"computeNonMaxSuppression"}});let i=t.createShaderModule({label:"canny_nms_r32f.wgsl",code:cm});this.nmsR32fPipeline=t.createComputePipeline({label:"CannyNmsR32fPipeline",layout:"auto",compute:{module:i,entryPoint:"computeNonMaxSuppression"}}),this.uniformBuffer=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"canny_uniform_buffer"})}device;sobelPipeline;nmsRgba8Pipeline;nmsR32fPipeline;uniformBuffer;cachedIntermediateTexture;cachedOutputTexture;execute(t,r={}){let n=t.width,i=t.height,o=r.low??.1,a=r.high??.3,u=r.outputFormat??"rgba8unorm",l=new ArrayBuffer(16),c=new Float32Array(l),m=new Uint32Array(l);c[0]=o,c[1]=a,m[2]=n,m[3]=i,this.device.queue.writeBuffer(this.uniformBuffer,0,l),(!this.cachedIntermediateTexture||this.cachedIntermediateTexture.width!==n||this.cachedIntermediateTexture.height!==i)&&(this.cachedIntermediateTexture?.destroy(),this.cachedIntermediateTexture=this.device.createTexture({label:"canny_magnitude_intermediate",size:[n,i],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING})),(!this.cachedOutputTexture||this.cachedOutputTexture.width!==n||this.cachedOutputTexture.height!==i||this.cachedOutputTexture.format!==u)&&(this.cachedOutputTexture?.destroy(),this.cachedOutputTexture=this.device.createTexture({label:`canny_edge_output_${u}`,size:[n,i],format:u,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}));let d=this.device.createCommandEncoder({label:"canny_command_encoder"}),p=this.device.createBindGroup({layout:this.sobelPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:this.cachedIntermediateTexture.createView()},{binding:2,resource:{buffer:this.uniformBuffer}}]}),f=d.beginComputePass({label:"canny_sobel_pass"});f.setPipeline(this.sobelPipeline),f.setBindGroup(0,p),f.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(i/16)),f.end();let b=u==="r32float"?this.nmsR32fPipeline:this.nmsRgba8Pipeline,g=this.device.createBindGroup({layout:b.getBindGroupLayout(0),entries:[{binding:0,resource:this.cachedIntermediateTexture.createView()},{binding:1,resource:this.cachedOutputTexture.createView()},{binding:2,resource:{buffer:this.uniformBuffer}}]}),y=d.beginComputePass({label:"canny_nms_pass"});return y.setPipeline(b),y.setBindGroup(0,g),y.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(i/16)),y.end(),this.device.queue.submit([d.finish()]),this.cachedOutputTexture}destroy(){this.cachedIntermediateTexture?.destroy(),this.cachedOutputTexture?.destroy(),this.uniformBuffer.destroy()}};h();h();var mm=`
|
|
452
|
+
struct DepthNormalParams {
|
|
453
|
+
width: u32,
|
|
454
|
+
height: u32,
|
|
455
|
+
depthScale: f32,
|
|
456
|
+
_pad: f32,
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
@group(0) @binding(0) var depthTex: texture_2d<f32>;
|
|
460
|
+
@group(0) @binding(1) var normalTex: texture_storage_2d<rgba16float, write>;
|
|
461
|
+
@group(0) @binding(2) var<uniform> params: DepthNormalParams;
|
|
462
|
+
|
|
463
|
+
@compute @workgroup_size(16, 16)
|
|
464
|
+
fn computeNormals(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
465
|
+
if (id.x >= params.width || id.y >= params.height) { return; }
|
|
466
|
+
|
|
467
|
+
let c = id.xy;
|
|
468
|
+
let maxX = params.width - 1u;
|
|
469
|
+
let maxY = params.height - 1u;
|
|
470
|
+
|
|
471
|
+
let left = textureLoad(depthTex, vec2<u32>(max(c.x - 1u, 0u), c.y), 0).r;
|
|
472
|
+
let right = textureLoad(depthTex, vec2<u32>(min(c.x + 1u, maxX), c.y), 0).r;
|
|
473
|
+
let up = textureLoad(depthTex, vec2<u32>(c.x, max(c.y - 1u, 0u)), 0).r;
|
|
474
|
+
let down = textureLoad(depthTex, vec2<u32>(c.x, min(c.y + 1u, maxY)), 0).r;
|
|
475
|
+
|
|
476
|
+
let dx = (right - left) * 0.5 * params.depthScale;
|
|
477
|
+
let dy = (down - up) * 0.5 * params.depthScale;
|
|
478
|
+
|
|
479
|
+
let normal = normalize(vec3<f32>(-dx, -dy, 1.0));
|
|
480
|
+
// Pack [-1, 1] range to [0, 1]
|
|
481
|
+
let packedColor = vec4<f32>(normal * 0.5 + 0.5, 1.0);
|
|
482
|
+
textureStore(normalTex, id.xy, packedColor);
|
|
483
|
+
}
|
|
484
|
+
`,dm=`
|
|
485
|
+
struct DepthNormalParams {
|
|
486
|
+
width: u32,
|
|
487
|
+
height: u32,
|
|
488
|
+
depthScale: f32,
|
|
489
|
+
_pad: f32,
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
@group(0) @binding(0) var depthTex: texture_2d<f32>;
|
|
493
|
+
@group(0) @binding(1) var normalTex: texture_storage_2d<rgba8unorm, write>;
|
|
494
|
+
@group(0) @binding(2) var<uniform> params: DepthNormalParams;
|
|
495
|
+
|
|
496
|
+
@compute @workgroup_size(16, 16)
|
|
497
|
+
fn computeNormals(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
498
|
+
if (id.x >= params.width || id.y >= params.height) { return; }
|
|
499
|
+
|
|
500
|
+
let c = id.xy;
|
|
501
|
+
let maxX = params.width - 1u;
|
|
502
|
+
let maxY = params.height - 1u;
|
|
503
|
+
|
|
504
|
+
let left = textureLoad(depthTex, vec2<u32>(max(c.x - 1u, 0u), c.y), 0).r;
|
|
505
|
+
let right = textureLoad(depthTex, vec2<u32>(min(c.x + 1u, maxX), c.y), 0).r;
|
|
506
|
+
let up = textureLoad(depthTex, vec2<u32>(c.x, max(c.y - 1u, 0u)), 0).r;
|
|
507
|
+
let down = textureLoad(depthTex, vec2<u32>(c.x, min(c.y + 1u, maxY)), 0).r;
|
|
508
|
+
|
|
509
|
+
let dx = (right - left) * 0.5 * params.depthScale;
|
|
510
|
+
let dy = (down - up) * 0.5 * params.depthScale;
|
|
511
|
+
|
|
512
|
+
let normal = normalize(vec3<f32>(-dx, -dy, 1.0));
|
|
513
|
+
// Pack [-1, 1] range to [0, 1]
|
|
514
|
+
let packedColor = vec4<f32>(normal * 0.5 + 0.5, 1.0);
|
|
515
|
+
textureStore(normalTex, id.xy, packedColor);
|
|
516
|
+
}
|
|
517
|
+
`;var nn=class{constructor(t){this.device=t;let r=t.createShaderModule({label:"depth_normals_rgba16f.wgsl",code:mm});this.normalRgba16fPipeline=t.createComputePipeline({label:"DepthNormalsRgba16fPipeline",layout:"auto",compute:{module:r,entryPoint:"computeNormals"}});let n=t.createShaderModule({label:"depth_normals_rgba8.wgsl",code:dm});this.normalRgba8Pipeline=t.createComputePipeline({label:"DepthNormalsRgba8Pipeline",layout:"auto",compute:{module:n,entryPoint:"computeNormals"}}),this.uniformBuffer=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"depth_normals_uniform_buffer"})}device;normalRgba16fPipeline;normalRgba8Pipeline;uniformBuffer;cachedOutputTexture;execute(t,r={}){let n=t.width,i=t.height,o=r.depthScale??1,a=r.outputFormat??"rgba16float",u=new ArrayBuffer(16),l=new Uint32Array(u),c=new Float32Array(u);l[0]=n,l[1]=i,c[2]=o,c[3]=0,this.device.queue.writeBuffer(this.uniformBuffer,0,u),(!this.cachedOutputTexture||this.cachedOutputTexture.width!==n||this.cachedOutputTexture.height!==i||this.cachedOutputTexture.format!==a)&&(this.cachedOutputTexture?.destroy(),this.cachedOutputTexture=this.device.createTexture({label:`normal_output_${a}`,size:[n,i],format:a,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}));let m=a==="rgba8unorm"?this.normalRgba8Pipeline:this.normalRgba16fPipeline,d=this.device.createCommandEncoder({label:"depth_normals_command_encoder"}),p=this.device.createBindGroup({layout:m.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:this.cachedOutputTexture.createView()},{binding:2,resource:{buffer:this.uniformBuffer}}]}),f=d.beginComputePass({label:"depth_normals_compute_pass"});return f.setPipeline(m),f.setBindGroup(0,p),f.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(i/16)),f.end(),this.device.queue.submit([d.finish()]),this.cachedOutputTexture}destroy(){this.cachedOutputTexture?.destroy(),this.uniformBuffer.destroy()}};h();h();var pm=`
|
|
518
|
+
struct FaceSegment {
|
|
519
|
+
start: vec2<f32>,
|
|
520
|
+
end: vec2<f32>,
|
|
521
|
+
color: vec4<f32>,
|
|
522
|
+
radius: f32,
|
|
523
|
+
enabled: f32,
|
|
524
|
+
pad: vec2<f32>,
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
struct FaceParams {
|
|
528
|
+
width: u32,
|
|
529
|
+
height: u32,
|
|
530
|
+
numSegments: u32,
|
|
531
|
+
pad: u32,
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
@group(0) @binding(0) var outputTex: texture_storage_2d<rgba8unorm, write>;
|
|
535
|
+
@group(0) @binding(1) var<uniform> params: FaceParams;
|
|
536
|
+
@group(0) @binding(2) var<storage, read> segments: array<FaceSegment>;
|
|
537
|
+
|
|
538
|
+
@compute @workgroup_size(16, 16)
|
|
539
|
+
fn computeFaceLandmarks(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
540
|
+
if (id.x >= params.width || id.y >= params.height) {
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
let p = vec2<f32>(f32(id.x) + 0.5, f32(id.y) + 0.5);
|
|
545
|
+
var outColor = vec4<f32>(0.0, 0.0, 0.0, 1.0); // Solid black background for SDXL ControlNet
|
|
546
|
+
|
|
547
|
+
let count = params.numSegments;
|
|
548
|
+
for (var i = 0u; i < count; i = i + 1u) {
|
|
549
|
+
let seg = segments[i];
|
|
550
|
+
if (seg.enabled < 0.5) {
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
let ab = seg.end - seg.start;
|
|
555
|
+
let ap = p - seg.start;
|
|
556
|
+
let l2 = dot(ab, ab);
|
|
557
|
+
|
|
558
|
+
var t: f32 = 0.0;
|
|
559
|
+
if (l2 > 0.0001) {
|
|
560
|
+
t = clamp(dot(ap, ab) / l2, 0.0, 1.0);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
let closest = seg.start + t * ab;
|
|
564
|
+
let dist = length(p - closest);
|
|
565
|
+
|
|
566
|
+
if (dist <= seg.radius) {
|
|
567
|
+
let edgeAlpha = clamp(seg.radius - dist + 0.5, 0.0, 1.0);
|
|
568
|
+
outColor = vec4<f32>(mix(outColor.rgb, seg.color.rgb, edgeAlpha * seg.color.a), 1.0);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
textureStore(outputTex, id.xy, outColor);
|
|
573
|
+
}
|
|
574
|
+
`;function pt(e,t){let r=[];for(let n=0;n<e.length-1;n++)r.push({from:e[n],to:e[n+1],color:t});return r}var on=[...pt([70,63,105,66,107],[0,1,1,1]),...pt([300,293,334,296,336],[0,1,1,1]),...pt([33,160,158,133,153,144,33],[0,1,0,1]),...pt([263,387,385,362,380,373,263],[0,1,0,1]),...pt([168,6,197,195,4],[1,1,0,1]),...pt([98,97,2,326,327],[1,1,0,1]),...pt([61,185,40,39,37,0,267,269,270,409,291,375,321,405,314,17,84,181,91,146,61],[1,.2,.2,1]),...pt([78,95,88,178,87,14,317,402,318,324,308,415,310,311,312,13,82,81,80,191,78],[1,0,.8,1]),...pt([10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109,10],[.9,.9,.9,1])],fi=class{constructor(t){this.device=t;let r=t.createShaderModule({label:"face_landmarks.wgsl",code:pm});this.computePipeline=t.createComputePipeline({label:"FaceLandmarksComputePipeline",layout:"auto",compute:{module:r,entryPoint:"computeFaceLandmarks"}}),this.uniformBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"face_landmarks_uniform_buffer"});let n=Math.max(256,on.length*48);this.storageBuffer=t.createBuffer({size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"face_landmarks_storage_buffer"})}device;computePipeline;uniformBuffer;storageBuffer;cachedOutputTexture;execute(t,r={}){let n=r.width??1024,i=r.height??1024,o=r.lineWidth??4,a=Math.max(1,o/2),u=new Uint32Array(4);u[0]=n,u[1]=i,u[2]=on.length,u[3]=0,this.device.queue.writeBuffer(this.uniformBuffer,0,u);let l=new Float32Array(on.length*12);for(let p=0;p<on.length;p++){let f=on[p],b=t[f.from],g=t[f.to],y=p*12;if(!b||!g||(b.visibility??1)<.2||(g.visibility??1)<.2){l[y+9]=0;continue}l[y+0]=b.x*n,l[y+1]=b.y*i,l[y+2]=g.x*n,l[y+3]=g.y*i,l[y+4]=f.color[0],l[y+5]=f.color[1],l[y+6]=f.color[2],l[y+7]=f.color[3],l[y+8]=a,l[y+9]=1,l[y+10]=0,l[y+11]=0}this.device.queue.writeBuffer(this.storageBuffer,0,l),(!this.cachedOutputTexture||this.cachedOutputTexture.width!==n||this.cachedOutputTexture.height!==i)&&(this.cachedOutputTexture?.destroy(),this.cachedOutputTexture=this.device.createTexture({size:{width:n,height:i},format:"rgba8unorm",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,label:"face_landmarks_output_texture"}));let c=this.device.createBindGroup({label:"FaceLandmarksBindGroup",layout:this.computePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:this.cachedOutputTexture.createView()},{binding:1,resource:{buffer:this.uniformBuffer}},{binding:2,resource:{buffer:this.storageBuffer}}]}),m=this.device.createCommandEncoder({label:"FaceLandmarksCommandEncoder"}),d=m.beginComputePass({label:"FaceLandmarksComputePass"});return d.setPipeline(this.computePipeline),d.setBindGroup(0,c),d.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(i/16)),d.end(),this.device.queue.submit([m.finish()]),this.cachedOutputTexture}destroy(){this.uniformBuffer.destroy(),this.storageBuffer.destroy(),this.cachedOutputTexture?.destroy()}};h();h();var fm=`
|
|
575
|
+
struct SegParams {
|
|
576
|
+
threshold: f32,
|
|
577
|
+
feather: f32,
|
|
578
|
+
width: u32,
|
|
579
|
+
height: u32,
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
@group(0) @binding(0) var inputTex: texture_2d<f32>;
|
|
583
|
+
@group(0) @binding(1) var outputTex: texture_storage_2d<rgba8unorm, write>;
|
|
584
|
+
@group(0) @binding(2) var<uniform> params: SegParams;
|
|
585
|
+
|
|
586
|
+
@compute @workgroup_size(16, 16)
|
|
587
|
+
fn computeSegmentation(@builtin(global_invocation_id) id: vec3<u32>) {
|
|
588
|
+
if (id.x >= params.width || id.y >= params.height) {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
let coord = vec2<i32>(i32(id.x), i32(id.y));
|
|
593
|
+
let sample = textureLoad(inputTex, coord, 0);
|
|
594
|
+
|
|
595
|
+
// Luminance or alpha channel extraction
|
|
596
|
+
let rawAlpha = max(sample.a, dot(sample.rgb, vec3<f32>(0.299, 0.587, 0.114)));
|
|
597
|
+
|
|
598
|
+
let lower = max(0.0, params.threshold - params.feather);
|
|
599
|
+
let upper = min(1.0, params.threshold + params.feather);
|
|
600
|
+
let alpha = smoothstep(lower, upper, rawAlpha);
|
|
601
|
+
|
|
602
|
+
textureStore(outputTex, id.xy, vec4<f32>(alpha, alpha, alpha, 1.0));
|
|
603
|
+
}
|
|
604
|
+
`;var hi=class{constructor(t){this.device=t;let r=t.createShaderModule({label:"segmentation.wgsl",code:fm});this.computePipeline=t.createComputePipeline({label:"SegmentationComputePipeline",layout:"auto",compute:{module:r,entryPoint:"computeSegmentation"}}),this.uniformBuffer=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"segmentation_uniform_buffer"})}device;computePipeline;uniformBuffer;cachedOutputTexture;execute(t,r={}){let n=t.width,i=t.height,o=r.threshold??.5,a=r.feather??.05,u=new ArrayBuffer(16),l=new Float32Array(u),c=new Uint32Array(u);l[0]=o,l[1]=a,c[2]=n,c[3]=i,this.device.queue.writeBuffer(this.uniformBuffer,0,u),(!this.cachedOutputTexture||this.cachedOutputTexture.width!==n||this.cachedOutputTexture.height!==i)&&(this.cachedOutputTexture?.destroy(),this.cachedOutputTexture=this.device.createTexture({label:"segmentation_output_texture",size:[n,i],format:"rgba8unorm",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}));let m=this.device.createCommandEncoder({label:"segmentation_command_encoder"}),d=this.device.createBindGroup({label:"segmentation_bind_group",layout:this.computePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView({label:"segmentation_input_view"})},{binding:1,resource:this.cachedOutputTexture.createView({label:"segmentation_output_view"})},{binding:2,resource:{buffer:this.uniformBuffer}}]}),p=m.beginComputePass({label:"segmentation_compute_pass"});return p.setPipeline(this.computePipeline),p.setBindGroup(0,d),p.dispatchWorkgroups(Math.ceil(n/16),Math.ceil(i/16),1),p.end(),this.device.queue.submit([m.finish()]),this.cachedOutputTexture}destroy(){this.cachedOutputTexture?.destroy(),this.cachedOutputTexture=void 0,this.uniformBuffer.destroy()}};var pr=class e{constructor(t){this.source=t;this.id=`tensor-${Math.random().toString(36).slice(2,9)}`}source;id;cannyOptions;depthNormalsOptions;poseSkeletonOptions;faceLandmarksOptions;segmentationOptions;opticalFlowOptions;deflickerOptions;multiplexer=new tn;cannyPipeline;depthNormalsPipeline;posePipeline;facePipeline;segmentationPipeline;opticalFlowPipeline;deflickerPipeline;prevInputTexture;static from(t){return new e(t)}canny(t={}){return this.cannyOptions=t,this}depthNormals(t={}){return this.depthNormalsOptions=t,this}poseSkeleton(t={}){return this.poseSkeletonOptions=t,this}pose(t,r={}){return this.poseSkeletonOptions={...r,landmarks:t},this}faceLandmarks(t={}){return this.faceLandmarksOptions=t,this}face(t,r={}){return this.faceLandmarksOptions={...r,landmarks:t},this}segmentation(t={}){return this.segmentationOptions=t,this}opticalFlow(t={}){return this.opticalFlowOptions=t,this}deflicker(t={}){return this.deflickerOptions=t,this}getMultiplexer(){return this.multiplexer}async execute(t,r){let n=r;if(!n&&typeof this.source?.createView=="function"&&(n=this.source),!n)throw new Error("[TensorPipeline.execute] No GPUTexture available for tensor compute execution. Pass a valid GPUTexture to execute() or initialize with a GPUTexture source.");if(this.cannyOptions){this.cannyPipeline||(this.cannyPipeline=new rn(t));let i=this.cannyPipeline.execute(n,this.cannyOptions);this.multiplexer.set("canny",i)}if(this.depthNormalsOptions){this.depthNormalsPipeline||(this.depthNormalsPipeline=new nn(t));let i=this.depthNormalsPipeline.execute(n,this.depthNormalsOptions);this.multiplexer.set("normals",i)}if(this.poseSkeletonOptions?.landmarks){this.posePipeline||(this.posePipeline=new il(t));let i=this.posePipeline.execute(this.poseSkeletonOptions.landmarks,{width:this.poseSkeletonOptions.width??n.width,height:this.poseSkeletonOptions.height??n.height,lineWidth:this.poseSkeletonOptions.lineWidth});this.multiplexer.set("poseSkeleton",i)}if(this.faceLandmarksOptions?.landmarks){this.facePipeline||(this.facePipeline=new fi(t));let i=this.facePipeline.execute(this.faceLandmarksOptions.landmarks,{width:this.faceLandmarksOptions.width??n.width,height:this.faceLandmarksOptions.height??n.height,lineWidth:this.faceLandmarksOptions.lineWidth});this.multiplexer.set("faceLandmarks",i)}if(this.segmentationOptions){this.segmentationPipeline||(this.segmentationPipeline=new hi(t));let i=this.segmentationPipeline.execute(n,this.segmentationOptions);this.multiplexer.set("segmentationMask",i)}if(this.opticalFlowOptions){this.opticalFlowPipeline||(this.opticalFlowPipeline=new Do(t));let i=this.prevInputTexture??n,o=this.opticalFlowPipeline.execute(i,n,this.opticalFlowOptions);this.multiplexer.set("motionVectors",o)}if(this.deflickerOptions){this.deflickerPipeline||(this.deflickerPipeline=new Ro(t));let i=this.deflickerPipeline.execute(n,this.deflickerOptions);this.multiplexer.set("deflickered",i)}return this.prevInputTexture=n,this.multiplexer.getOutputs()}toConfig(){return{canny:this.cannyOptions,depthNormals:this.depthNormalsOptions,poseSkeleton:this.poseSkeletonOptions,faceLandmarks:this.faceLandmarksOptions,segmentation:this.segmentationOptions,opticalFlow:this.opticalFlowOptions,deflicker:this.deflickerOptions}}toNode(){return{id:this.id,kind:"tensor",source:this.source,config:this.toConfig()}}destroy(){this.cannyPipeline?.destroy(),this.depthNormalsPipeline?.destroy(),this.posePipeline?.destroy(),this.facePipeline?.destroy(),this.segmentationPipeline?.destroy(),this.opticalFlowPipeline?.destroy(),this.deflickerPipeline?.destroy(),this.multiplexer.destroy()}};h();var G1=e=>{if(!e)return"srcOver";switch(e){case"source-over":return"srcOver";case"source-in":return"srcIn";case"source-out":return"srcOut";case"source-atop":return"srcATop";case"destination-over":return"dstOver";case"destination-in":return"dstIn";case"destination-out":return"dstOut";case"destination-atop":return"dstATop";case"copy":return"src";case"xor":return"xor";case"multiply":return"multiply";case"screen":return"screen";case"overlay":return"overlay";case"darken":return"darken";case"lighten":case"lighter":return"lighten";case"color-dodge":return"colorDodge";case"color-burn":return"colorBurn";case"hard-light":return"hardLight";case"soft-light":return"softLight";case"difference":return"difference";case"exclusion":return"exclusion";case"hue":return"hue";case"saturation":return"saturation";case"color":return"color";case"luminosity":return"luminosity";default:return"srcOver"}},W1=e=>e==="destination-in"||e==="source-in";h();function X1(e,t,r,n,i="outside"){if(i==="inside"){let o=n/2;return{x:o,y:o,width:Math.max(0,e-n),height:Math.max(0,t-n),radius:r===0?0:Math.max(0,r-o)}}if(i==="outside"){let o=n/2;return{x:-o,y:-o,width:e+n,height:t+n,radius:r===0?0:r+o}}return{x:0,y:0,width:e,height:t,radius:r}}h();var hm=new Map;function Y(e){let t=(hm.get(e)??0)+1;return hm.set(e,t),`${e}-auto-${t}`}h();h();h();h();var Ge=class extends Error{status;body;requestId;type;constructor({message:t,status:r,body:n,requestId:i,type:o}){super(t),this.name="ApiError",this.status=r,this.body=n,this.requestId=i??"",this.type=o}},an=class extends Ge{constructor(t){super(t),this.name="ValidationError"}get fieldErrors(){return Array.isArray(this.body?.detail)?this.body.detail:[]}getFieldErrors(t){return this.fieldErrors.filter(r=>r.loc[r.loc.length-1]===t)}};function kg(e,t){if(e?.error?.message)return e.error.message;if(typeof e?.detail=="string")return e.detail;if(Array.isArray(e?.detail)){let r=e.detail[0];if(r?.msg)return`${r.msg} (${(r.loc??[]).join(".")})`}return typeof e?.message=="string"?e.message:t}async function gi(e){let t=await e.text().catch(()=>""),r=t||void 0;try{r=t?JSON.parse(t):void 0}catch{}let n=typeof r=="object"&&r!==null?r:void 0,i={message:kg(n,`${e.status} ${e.statusText}`.trim()),status:e.status,body:r,requestId:e.headers.get("x-framefields-request-id")??void 0,type:n?.error?.type};return e.status===422&&Array.isArray(n?.detail)?new an(i):new Ge(i)}h();h();var Ga="https://api.framefields.dev/v1/ai/proxy",gm,bm=e=>typeof S<"u"?S.env?.[e]:void 0;function ym(e){gm=e}function Pg(){let e=gm??bm("FRAMEFIELDS_API_KEY");if(!e)throw new Error("framefields ai: no API key. Set FRAMEFIELDS_API_KEY or call ai.config({ apiKey }). Create a key at https://framefields.dev/dashboard/keys");return e}function Tg({service:e,path:t,query:r}){let n=new URLSearchParams;for(let[o,a]of Object.entries(r??{}))a!==void 0&&n.set(o,a);let i=n.size?`?${n}`:"";return`${e}/${t.replace(/^\/+/,"")}${i}`}async function Wa(e){let t={Authorization:`Key ${Pg()}`,Accept:e.accept??"application/json","x-framefields-target":Tg(e)},r=e.body!==void 0;r&&(t["Content-Type"]="application/json");let n=await fetch(bm("FRAMEFIELDS_AI_PROXY_URL")??Ga,{method:e.method??(r?"POST":"GET"),headers:t,body:r?JSON.stringify(e.body):void 0,signal:e.signal});if(!n.ok)throw await gi(n);return n}async function ft(e){let t=await Wa(e);return{data:await t.json(),requestId:t.headers.get("x-framefields-request-id")??""}}var Mg=90*1024*1024,xm=10*1024*1024,Ag=3,Cg={"image/jpeg":"jpg","image/png":"png","image/webp":"webp","video/mp4":"mp4","audio/mpeg":"mp3","audio/wav":"wav"};function Dg(e,t){return"name"in e&&typeof e.name=="string"&&e.name?e.name:`${Date.now()}.${Cg[t]??"bin"}`}function Sm(e,t){let r=e.type||"application/octet-stream";return ft({service:"storage",path:t?"upload/initiate-multipart":"upload/initiate",body:{content_type:r,file_name:Dg(e,r)}}).then(n=>n.data)}async function Ya(e,t){let r=await fetch(e,t);if(!r.ok)throw await gi(r);return r}async function Rg(e,t){for(let r=1;;r++)try{return await(await Ya(e,{method:"PUT",body:t})).json()}catch(n){if(r>=Ag)throw n}}async function Og(e){let t=await Sm(e,!0),r=new URL(t.upload_url),n=o=>`${r.origin}${r.pathname}/${o}${r.search}`,i=[];for(let o=0;o<e.size;o+=xm){let a=e.slice(o,Math.min(o+xm,e.size));i.push(await Rg(n(i.length+1),a))}return await Ya(n("complete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:i.map(({partNumber:o,etag:a})=>({partNumber:o,etag:a}))})}),t.file_url}async function wm(e){if(e.size>Mg)return Og(e);let t=await Sm(e,!1);return await Ya(t.upload_url,{method:"PUT",body:e,headers:{"Content-Type":e.type||"application/octet-stream"}}),t.file_url}var Ng=e=>typeof e=="object"&&e!==null&&Object.getPrototypeOf(e)===Object.prototype;async function Ha(e){if(e instanceof Blob)return await wm(e);if(Array.isArray(e))return await Promise.all(e.map(t=>Ha(t)));if(Ng(e)){let t=await Promise.all(Object.entries(e).map(async([r,n])=>[r,await Ha(n)]));return Object.fromEntries(t)}return e}var Bt={upload:wm,transformInput:Ha};var Fg=new Set([429,502,503,504]),Lg=4,vm=(e,t)=>new Promise((r,n)=>{t?.throwIfAborted();let i=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(i),n(t.reason)},{once:!0})});async function km(e,t){for(let r=1;;r++)try{return await e()}catch(n){if(!(n instanceof Ge&&Fg.has(n.status))||r>=Lg)throw n;await vm(500*2**r,t)}}var Xa=(e,t,r="")=>`${e}/requests/${encodeURIComponent(t)}${r}`;async function Pm(e,{input:t,abortSignal:r}){let{data:n}=await ft({service:"queue",path:e,body:await Bt.transformInput(t)??{},signal:r});return n}function Tm(e,{requestId:t,logs:r,abortSignal:n}){return km(async()=>{let{data:i}=await ft({service:"queue",path:Xa(e,t,"/status"),query:{logs:r?"1":void 0},signal:n});return i},n)}function Mm(e,{requestId:t,abortSignal:r}){return km(async()=>{let{data:n}=await ft({service:"queue",path:Xa(e,t),signal:r});return{data:n,requestId:t}},r)}async function Eg(e,{requestId:t,abortSignal:r}){await ft({service:"queue",path:Xa(e,t,"/cancel"),method:"PUT",signal:r})}async function Am(e,t){let r=t.pollInterval??500;for(;;){let n=await Tm(e,t);if(t.onQueueUpdate?.(n),n.status==="COMPLETED")return n;await vm(r,t.abortSignal)}}var Cm={submit:Pm,status:Tm,result:Mm,cancel:Eg,subscribeToStatus:Am};async function Dm(e,t){let{request_id:r}=await Pm(e,t);return t.onEnqueue?.(r),await Am(e,{...t,requestId:r}),Mm(e,{requestId:r,abortSignal:t.abortSignal})}h();async function*Bg(e){let t=new TextDecoder,r="";for await(let i of e){r+=t.decode(i,{stream:!0}).replace(/\r\n?/g,`
|
|
605
|
+
`);let o=r.indexOf(`
|
|
606
|
+
|
|
607
|
+
`);for(;o!==-1;){let a=r.slice(0,o);r=r.slice(o+2);let u=Rm(a);u&&(yield u),o=r.indexOf(`
|
|
608
|
+
|
|
609
|
+
`)}}let n=Rm(r);n&&(yield n)}function Rm(e){let t="message",r=[];for(let n of e.split(`
|
|
610
|
+
`))n.startsWith("data:")?r.push(n.slice(5).replace(/^ /,"")):n.startsWith("event:")&&(t=n.slice(6).trim());return r.length?{event:t,data:r.join(`
|
|
611
|
+
`)}:null}async function*Ig(e,t){for await(let{event:r,data:n}of Bg(e)){let i=JSON.parse(n);if(r==="error")throw new Ge({message:"The model stream ended with an error",status:500,body:i,requestId:t});yield i}}async function Om(e,{input:t,abortSignal:r}){let n=new AbortController,i=r?AbortSignal.any([r,n.signal]):n.signal,o=await Wa({service:"run",path:`${e}/stream`,body:await Bt.transformInput(t)??{},accept:"text/event-stream",signal:i}),a=o.headers.get("x-framefields-request-id")??"";if(!o.body)throw new Ge({message:"Empty stream",status:502,requestId:a});let u=Ig(o.body,a),l,c;async function*m(){for await(let f of u)l=f,yield f}let d=m(),p=async()=>{let f=await d.next();for(;!f.done;)f=await d.next();if(l===void 0)throw new Ge({message:"Stream had no output",status:502,requestId:a});return l};return{requestId:a,[Symbol.asyncIterator]:()=>d,done:()=>(c??=p(),c),abort:()=>n.abort()}}async function jg(e,{input:t,abortSignal:r}){return ft({service:"run",path:e,body:await Bt.transformInput(t)??{},signal:r})}var zg={config(e){ym(e.apiKey)},run:jg,subscribe:Dm,stream:Om,queue:Cm,storage:Bt};h();function _g(e,...t){let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(i&&r.push({text:i}),n<t.length){let o=t[n];if(o==null)continue;if(Array.isArray(o))for(let a of o)typeof a=="string"?a&&r.push({text:a}):a&&typeof a=="object"&&"text"in a&&r.push(a);else typeof o=="object"&&"text"in o?r.push(o):typeof o=="object"&&"get"in o&&typeof o.get=="function"?r.push({text:o}):r.push({text:String(o)})}}return r}function Vg(e,t={}){return{text:e,...t}}function Ug(e,t={}){return{text:e,fontWeight:t.fontWeight??700,...t}}function $g(e,t={}){return{text:e,fontStyle:"italic",...t}}function Gg(e,t={}){return{text:e,fill:t.fill??"#6366f1",...t}}function Wg(e,t,r={}){return{text:e,fill:t,...r}}function Hg(e,t,r={}){return{text:e,fontSize:t,...r}}function Yg(e,t={}){let{bg:r,fill:n,radius:i,paddingX:o,paddingY:a,...u}=t;return{text:e,fill:n,mark:{background:r??"#6366f133",borderRadius:i??4,paddingX:o??6,paddingY:a??2},...u}}function Xg(e,t={}){return{text:e,baselineShift:t.baselineShift??-8,...t}}function Zg(e,t={}){return{text:e,baselineShift:t.baselineShift??6,...t}}function qg(e,t={}){return{text:e,fontFamily:t.fontFamily??"JetBrains Mono",mark:t.mark??{background:"#ffffff18",borderRadius:4,paddingX:6,paddingY:2},...t}}function bi(e){if(typeof e=="string")return{text:e};if(!Array.isArray(e))return{text:String(e)};let t=[],r="";for(let n of e)if(typeof n=="string")n&&(t.push({text:n}),r+=n);else if(n&&typeof n=="object"&&"text"in n){let i=n;t.push(i);let o=typeof i.text=="string"?i.text:i.text&&typeof i.text=="object"&&"get"in i.text&&typeof i.text.get=="function"?String(i.text.get()):String(i.text??"");r+=o}return{text:r,spans:t.length>0?t:void 0}}function Kg(e){if(!e||!e.includes("<"))return[{text:e}];let t=[],r=/<(\/?[a-zA-Z0-9_-]+)([^>]*)>/g,n=0,i=[],o=()=>{let u={};for(let l of i)Object.assign(u,l.style);return u};for(;;){let u=r.exec(e);if(!u)break;let l=e.slice(n,u.index);l&&t.push({text:l,...o()}),n=u.index+u[0].length;let c=u[1].toLowerCase(),m=u[2];if(c.startsWith("/")){let d=c.slice(1);for(let p=i.length-1;p>=0;p--)if(i[p].tag===d){i.splice(p,1);break}}else{let d={},p=/([a-zA-Z0-9_-]+)=["']([^"']*)["']/g;for(;;){let b=p.exec(m);if(!b)break;d[b[1].toLowerCase()]=b[2]}let f={};if(c==="b"||c==="strong")f.fontWeight=700,(d.color||d.fill)&&(f.fill=d.color??d.fill);else if(c==="i"||c==="em")f.fontStyle="italic",(d.color||d.fill)&&(f.fill=d.color??d.fill);else if(c==="accent")f.fill="#6366f1";else if(c==="color")f.fill=d.value??d.hex??d.fill;else if(c==="size"){let b=parseFloat(d.value??d.px??d.pt??"0");b>0&&(f.fontSize=b)}else if(c==="mark")f.mark={background:d.bg??d.background??"#6366f133",borderRadius:d.radius?parseFloat(d.radius):4,paddingX:d.paddingx?parseFloat(d.paddingx):6,paddingY:d.paddingy?parseFloat(d.paddingy):2},(d.color||d.fill)&&(f.fill=d.color??d.fill);else if(c==="sup")f.baselineShift=-8;else if(c==="sub")f.baselineShift=6;else if(c==="code")f.fontFamily="JetBrains Mono",f.mark={background:d.bg??"#ffffff18",borderRadius:4,paddingX:6,paddingY:2};else if(c==="span"){if((d.color||d.fill)&&(f.fill=d.color??d.fill),d.fontfamily&&(f.fontFamily=d.fontfamily),d.fontsize&&(f.fontSize=parseFloat(d.fontsize)),d.fontweight){let b=parseInt(d.fontweight,10);f.fontWeight=Number.isNaN(b)?d.fontweight:b}(d.fontstyle==="italic"||d.fontstyle==="normal")&&(f.fontStyle=d.fontstyle),d.letterspacing&&(f.letterSpacing=parseFloat(d.letterspacing)),d.baselineshift&&(f.baselineShift=parseFloat(d.baselineshift)),d.opacity&&(f.opacity=parseFloat(d.opacity))}i.push({tag:c,style:f})}}let a=e.slice(n);return a&&t.push({text:a,...o()}),t}h();h();h();h();h();h();function Nm(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function It(e,t){if(!isFinite(e)||e===0)return null;var r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function Qe(e){return e=It(Math.abs(e)),e?e[1]:NaN}h();function Fm(e,t){return function(r,n){for(var i=r.length,o=[],a=0,u=e[0],l=0;i>0&&u>0&&(l+u+1>n&&(u=Math.max(1,n-l)),o.push(r.substring(i-=u,i+u)),!((l+=u+1)>n));)u=e[a=(a+1)%e.length];return o.reverse().join(t)}}h();function Lm(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}h();var Qg=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function kt(e){if(!(t=Qg.exec(e)))throw new Error("invalid format: "+e);var t;return new yi({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}kt.prototype=yi.prototype;function yi(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}yi.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};h();function Em(e){e:for(var t=e.length,r=1,n=-1,i;r<t;++r)switch(e[r]){case".":n=i=r;break;case"0":n===0&&(n=r),i=r;break;default:if(!+e[r])break e;n>0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(i+1):e}h();h();var sn;function Bm(e,t){var r=It(e,t);if(!r)return sn=void 0,e.toPrecision(t);var n=r[0],i=r[1],o=i-(sn=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,a=n.length;return o===a?n:o>a?n+new Array(o-a+1).join("0"):o>0?n.slice(0,o)+"."+n.slice(o):"0."+new Array(1-o).join("0")+It(e,Math.max(0,t+o-1))[0]}h();function Za(e,t){var r=It(e,t);if(!r)return e+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}var qa={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:Nm,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>Za(e*100,t),r:Za,s:Bm,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};h();function Ka(e){return e}var Im=Array.prototype.map,jm=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function zm(e){var t=e.grouping===void 0||e.thousands===void 0?Ka:Fm(Im.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":e.decimal+"",o=e.numerals===void 0?Ka:Lm(Im.call(e.numerals,String)),a=e.percent===void 0?"%":e.percent+"",u=e.minus===void 0?"\u2212":e.minus+"",l=e.nan===void 0?"NaN":e.nan+"";function c(d,p){d=kt(d);var f=d.fill,b=d.align,g=d.sign,y=d.symbol,T=d.zero,M=d.width,v=d.comma,x=d.precision,A=d.trim,w=d.type;w==="n"?(v=!0,w="g"):qa[w]||(x===void 0&&(x=12),A=!0,w="g"),(T||f==="0"&&b==="=")&&(T=!0,f="0",b="=");var R=(p&&p.prefix!==void 0?p.prefix:"")+(y==="$"?r:y==="#"&&/[boxX]/.test(w)?"0"+w.toLowerCase():""),N=(y==="$"?n:/[%p]/.test(w)?a:"")+(p&&p.suffix!==void 0?p.suffix:""),V=qa[w],$=/[defgprs%]/.test(w);x=x===void 0?6:/[gprs]/.test(w)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function I(E){var k=R,P=N,G,X,U;if(w==="c")P=V(E)+P,E="";else{E=+E;var j=E<0||1/E<0;if(E=isNaN(E)?l:V(Math.abs(E),x),A&&(E=Em(E)),j&&+E==0&&g!=="+"&&(j=!1),k=(j?g==="("?g:u:g==="-"||g==="("?"":g)+k,P=(w==="s"&&!isNaN(E)&&sn!==void 0?jm[8+sn/3]:"")+P+(j&&g==="("?")":""),$){for(G=-1,X=E.length;++G<X;)if(U=E.charCodeAt(G),48>U||U>57){P=(U===46?i+E.slice(G+1):E.slice(G))+P,E=E.slice(0,G);break}}}v&&!T&&(E=t(E,1/0));var Z=k.length+E.length+P.length,ne=Z<M?new Array(M-Z+1).join(f):"";switch(v&&T&&(E=t(ne+E,ne.length?M-P.length:1/0),ne=""),b){case"<":E=k+E+P+ne;break;case"=":E=k+ne+E+P;break;case"^":E=ne.slice(0,Z=ne.length>>1)+k+E+P+ne.slice(Z);break;default:E=ne+k+E+P;break}return o(E)}return I.toString=function(){return d+""},I}function m(d,p){var f=Math.max(-8,Math.min(8,Math.floor(Qe(p)/3)))*3,b=Math.pow(10,-f),g=c((d=kt(d),d.type="f",d),{suffix:jm[8+f/3]});return function(y){return g(b*y)}}return{format:c,formatPrefix:m}}var xi,fr,Si;Qa({thousands:",",grouping:[3],currency:["$",""]});function Qa(e){return xi=zm(e),fr=xi.format,Si=xi.formatPrefix,xi}h();function Ja(e){return Math.max(0,-Qe(Math.abs(e)))}h();function es(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Qe(t)/3)))*3-Qe(Math.abs(e)))}h();function ts(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Qe(t)-Qe(e))+1}h();h();h();h();h();function jt(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}h();h();function rs(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function zt(e){let t,r,n;e.length!==2?(t=jt,r=(u,l)=>jt(e(u),l),n=(u,l)=>e(u)-l):(t=e===jt||e===rs?e:Jg,r=e,n=e);function i(u,l,c=0,m=u.length){if(c<m){if(t(l,l)!==0)return m;do{let d=c+m>>>1;r(u[d],l)<0?c=d+1:m=d}while(c<m)}return c}function o(u,l,c=0,m=u.length){if(c<m){if(t(l,l)!==0)return m;do{let d=c+m>>>1;r(u[d],l)<=0?c=d+1:m=d}while(c<m)}return c}function a(u,l,c=0,m=u.length){let d=i(u,l,c,m-1);return d>c&&n(u[d-1],l)>-n(u[d],l)?d-1:d}return{left:i,center:a,right:o}}function Jg(){return 0}h();function ns(e){return e===null?NaN:+e}var _m=zt(jt),Vm=_m.right,eb=_m.left,tb=zt(ns).center,is=Vm;h();var hr=class extends Map{constructor(t,r=ib){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(let[n,i]of t)this.set(n,i)}get(t){return super.get(Um(this,t))}has(t){return super.has(Um(this,t))}set(t,r){return super.set(rb(this,t),r)}delete(t){return super.delete(nb(this,t))}};function Um({_intern:e,_key:t},r){let n=t(r);return e.has(n)?e.get(n):r}function rb({_intern:e,_key:t},r){let n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function nb({_intern:e,_key:t},r){let n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function ib(e){return e!==null&&typeof e=="object"?e.valueOf():e}h();var ob=Math.sqrt(50),ab=Math.sqrt(10),sb=Math.sqrt(2);function wi(e,t,r){let n=(t-e)/Math.max(0,r),i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),a=o>=ob?10:o>=ab?5:o>=sb?2:1,u,l,c;return i<0?(c=Math.pow(10,-i)/a,u=Math.round(e*c),l=Math.round(t*c),u/c<e&&++u,l/c>t&&--l,c=-c):(c=Math.pow(10,i)*a,u=Math.round(e/c),l=Math.round(t/c),u*c<e&&++u,l*c>t&&--l),l<u&&.5<=r&&r<2?wi(e,t,r*2):[u,l,c]}function vi(e,t,r){if(t=+t,e=+e,r=+r,!(r>0))return[];if(e===t)return[e];let n=t<e,[i,o,a]=n?wi(t,e,r):wi(e,t,r);if(!(o>=i))return[];let u=o-i+1,l=new Array(u);if(n)if(a<0)for(let c=0;c<u;++c)l[c]=(o-c)/-a;else for(let c=0;c<u;++c)l[c]=(o-c)*a;else if(a<0)for(let c=0;c<u;++c)l[c]=(i+c)/-a;else for(let c=0;c<u;++c)l[c]=(i+c)*a;return l}function un(e,t,r){return t=+t,e=+e,r=+r,wi(e,t,r)[2]}function gr(e,t,r){t=+t,e=+e,r=+r;let n=t<e,i=n?un(t,e,r):un(e,t,r);return(n?-1:1)*(i<0?1/-i:i)}h();function ki(e,t,r){e=+e,t=+t,r=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((t-e)/r))|0,o=new Array(i);++n<i;)o[n]=e+n*r;return o}h();function Pt(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}h();var $m=Symbol("implicit");function Pi(){var e=new hr,t=[],r=[],n=$m;function i(o){let a=e.get(o);if(a===void 0){if(n!==$m)return n;e.set(o,a=t.push(o)-1)}return r[a%r.length]}return i.domain=function(o){if(!arguments.length)return t.slice();t=[],e=new hr;for(let a of o)e.has(a)||e.set(a,t.push(a)-1);return i},i.range=function(o){return arguments.length?(r=Array.from(o),i):r.slice()},i.unknown=function(o){return arguments.length?(n=o,i):n},i.copy=function(){return Pi(t,r).unknown(n)},Pt.apply(i,arguments),i}function ln(){var e=Pi().unknown(void 0),t=e.domain,r=e.range,n=0,i=1,o,a,u=!1,l=0,c=0,m=.5;delete e.unknown;function d(){var p=t().length,f=i<n,b=f?i:n,g=f?n:i;o=(g-b)/Math.max(1,p-l+c*2),u&&(o=Math.floor(o)),b+=(g-b-o*(p-l))*m,a=o*(1-l),u&&(b=Math.round(b),a=Math.round(a));var y=ki(p).map(function(T){return b+o*T});return r(f?y.reverse():y)}return e.domain=function(p){return arguments.length?(t(p),d()):t()},e.range=function(p){return arguments.length?([n,i]=p,n=+n,i=+i,d()):[n,i]},e.rangeRound=function(p){return[n,i]=p,n=+n,i=+i,u=!0,d()},e.bandwidth=function(){return a},e.step=function(){return o},e.round=function(p){return arguments.length?(u=!!p,d()):u},e.padding=function(p){return arguments.length?(l=Math.min(1,c=+p),d()):l},e.paddingInner=function(p){return arguments.length?(l=Math.min(1,p),d()):l},e.paddingOuter=function(p){return arguments.length?(c=+p,d()):c},e.align=function(p){return arguments.length?(m=Math.max(0,Math.min(1,p)),d()):m},e.copy=function(){return ln(t(),[n,i]).round(u).paddingInner(l).paddingOuter(c).align(m)},Pt.apply(d(),arguments)}h();h();h();h();h();h();h();function Ti(e,t,r){e.prototype=t.prototype=r,r.constructor=e}function os(e,t){var r=Object.create(e.prototype);for(var n in t)r[n]=t[n];return r}function dn(){}var cn=.7,Ci=1/cn,br="\\s*([+-]?\\d+)\\s*",mn="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Je="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ub=/^#([0-9a-f]{3,8})$/,lb=new RegExp(`^rgb\\(${br},${br},${br}\\)$`),cb=new RegExp(`^rgb\\(${Je},${Je},${Je}\\)$`),mb=new RegExp(`^rgba\\(${br},${br},${br},${mn}\\)$`),db=new RegExp(`^rgba\\(${Je},${Je},${Je},${mn}\\)$`),pb=new RegExp(`^hsl\\(${mn},${Je},${Je}\\)$`),fb=new RegExp(`^hsla\\(${mn},${Je},${Je},${mn}\\)$`),Gm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Ti(dn,Tt,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Wm,formatHex:Wm,formatHex8:hb,formatHsl:gb,formatRgb:Hm,toString:Hm});function Wm(){return this.rgb().formatHex()}function hb(){return this.rgb().formatHex8()}function gb(){return Qm(this).formatHsl()}function Hm(){return this.rgb().formatRgb()}function Tt(e){var t,r;return e=(e+"").trim().toLowerCase(),(t=ub.exec(e))?(r=t[1].length,t=parseInt(t[1],16),r===6?Ym(t):r===3?new ze(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Mi(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Mi(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=lb.exec(e))?new ze(t[1],t[2],t[3],1):(t=cb.exec(e))?new ze(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=mb.exec(e))?Mi(t[1],t[2],t[3],t[4]):(t=db.exec(e))?Mi(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=pb.exec(e))?qm(t[1],t[2]/100,t[3]/100,1):(t=fb.exec(e))?qm(t[1],t[2]/100,t[3]/100,t[4]):Gm.hasOwnProperty(e)?Ym(Gm[e]):e==="transparent"?new ze(NaN,NaN,NaN,0):null}function Ym(e){return new ze(e>>16&255,e>>8&255,e&255,1)}function Mi(e,t,r,n){return n<=0&&(e=t=r=NaN),new ze(e,t,r,n)}function bb(e){return e instanceof dn||(e=Tt(e)),e?(e=e.rgb(),new ze(e.r,e.g,e.b,e.opacity)):new ze}function yr(e,t,r,n){return arguments.length===1?bb(e):new ze(e,t,r,n??1)}function ze(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}Ti(ze,yr,os(dn,{brighter(e){return e=e==null?Ci:Math.pow(Ci,e),new ze(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?cn:Math.pow(cn,e),new ze(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ze(Vt(this.r),Vt(this.g),Vt(this.b),Di(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Xm,formatHex:Xm,formatHex8:yb,formatRgb:Zm,toString:Zm}));function Xm(){return`#${_t(this.r)}${_t(this.g)}${_t(this.b)}`}function yb(){return`#${_t(this.r)}${_t(this.g)}${_t(this.b)}${_t((isNaN(this.opacity)?1:this.opacity)*255)}`}function Zm(){let e=Di(this.opacity);return`${e===1?"rgb(":"rgba("}${Vt(this.r)}, ${Vt(this.g)}, ${Vt(this.b)}${e===1?")":`, ${e})`}`}function Di(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Vt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function _t(e){return e=Vt(e),(e<16?"0":"")+e.toString(16)}function qm(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new We(e,t,r,n)}function Qm(e){if(e instanceof We)return new We(e.h,e.s,e.l,e.opacity);if(e instanceof dn||(e=Tt(e)),!e)return new We;if(e instanceof We)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,i=Math.min(t,r,n),o=Math.max(t,r,n),a=NaN,u=o-i,l=(o+i)/2;return u?(t===o?a=(r-n)/u+(r<n)*6:r===o?a=(n-t)/u+2:a=(t-r)/u+4,u/=l<.5?o+i:2-o-i,a*=60):u=l>0&&l<1?0:a,new We(a,u,l,e.opacity)}function Jm(e,t,r,n){return arguments.length===1?Qm(e):new We(e,t,r,n??1)}function We(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}Ti(We,Jm,os(dn,{brighter(e){return e=e==null?Ci:Math.pow(Ci,e),new We(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?cn:Math.pow(cn,e),new We(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,i=2*r-n;return new ze(as(e>=240?e-240:e+120,i,n),as(e,i,n),as(e<120?e+240:e-120,i,n),this.opacity)},clamp(){return new We(Km(this.h),Ai(this.s),Ai(this.l),Di(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=Di(this.opacity);return`${e===1?"hsl(":"hsla("}${Km(this.h)}, ${Ai(this.s)*100}%, ${Ai(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Km(e){return e=(e||0)%360,e<0?e+360:e}function Ai(e){return Math.max(0,Math.min(1,e||0))}function as(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}h();h();function ss(e,t,r,n,i){var o=e*e,a=o*e;return((1-3*e+3*o-a)*t+(4-6*o+3*a)*r+(1+3*e+3*o-3*a)*n+a*i)/6}function ed(e){var t=e.length-1;return function(r){var n=r<=0?r=0:r>=1?(r=1,t-1):Math.floor(r*t),i=e[n],o=e[n+1],a=n>0?e[n-1]:2*i-o,u=n<t-1?e[n+2]:2*o-i;return ss((r-n/t)*t,a,i,o,u)}}h();function td(e){var t=e.length;return function(r){var n=Math.floor(((r%=1)<0?++r:r)*t),i=e[(n+t-1)%t],o=e[n%t],a=e[(n+1)%t],u=e[(n+2)%t];return ss((r-n/t)*t,i,o,a,u)}}h();h();var pn=e=>()=>e;function xb(e,t){return function(r){return e+r*t}}function Sb(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function rd(e){return(e=+e)==1?Ri:function(t,r){return r-t?Sb(t,r,e):pn(isNaN(t)?r:t)}}function Ri(e,t){var r=t-e;return r?xb(e,r):pn(isNaN(e)?t:e)}var us=(function e(t){var r=rd(t);function n(i,o){var a=r((i=yr(i)).r,(o=yr(o)).r),u=r(i.g,o.g),l=r(i.b,o.b),c=Ri(i.opacity,o.opacity);return function(m){return i.r=a(m),i.g=u(m),i.b=l(m),i.opacity=c(m),i+""}}return n.gamma=e,n})(1);function nd(e){return function(t){var r=t.length,n=new Array(r),i=new Array(r),o=new Array(r),a,u;for(a=0;a<r;++a)u=yr(t[a]),n[a]=u.r||0,i[a]=u.g||0,o[a]=u.b||0;return n=e(n),i=e(i),o=e(o),u.opacity=1,function(l){return u.r=n(l),u.g=i(l),u.b=o(l),u+""}}}var IT=nd(ed),jT=nd(td);h();h();function id(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),i;return function(o){for(i=0;i<r;++i)n[i]=e[i]*(1-o)+t[i]*o;return n}}function od(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ad(e,t){var r=t?t.length:0,n=e?Math.min(r,e.length):0,i=new Array(n),o=new Array(r),a;for(a=0;a<n;++a)i[a]=Ut(e[a],t[a]);for(;a<r;++a)o[a]=t[a];return function(u){for(a=0;a<n;++a)o[a]=i[a](u);return o}}h();function sd(e,t){var r=new Date;return e=+e,t=+t,function(n){return r.setTime(e*(1-n)+t*n),r}}h();function Mt(e,t){return e=+e,t=+t,function(r){return e*(1-r)+t*r}}h();function ud(e,t){var r={},n={},i;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(i in t)i in e?r[i]=Ut(e[i],t[i]):n[i]=t[i];return function(o){for(i in r)n[i]=r[i](o);return n}}h();var cs=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ls=new RegExp(cs.source,"g");function wb(e){return function(){return e}}function vb(e){return function(t){return e(t)+""}}function ld(e,t){var r=cs.lastIndex=ls.lastIndex=0,n,i,o,a=-1,u=[],l=[];for(e=e+"",t=t+"";(n=cs.exec(e))&&(i=ls.exec(t));)(o=i.index)>r&&(o=t.slice(r,o),u[a]?u[a]+=o:u[++a]=o),(n=n[0])===(i=i[0])?u[a]?u[a]+=i:u[++a]=i:(u[++a]=null,l.push({i:a,x:Mt(n,i)})),r=ls.lastIndex;return r<t.length&&(o=t.slice(r),u[a]?u[a]+=o:u[++a]=o),u.length<2?l[0]?vb(l[0].x):wb(t):(t=l.length,function(c){for(var m=0,d;m<t;++m)u[(d=l[m]).i]=d.x(c);return u.join("")})}function Ut(e,t){var r=typeof t,n;return t==null||r==="boolean"?pn(t):(r==="number"?Mt:r==="string"?(n=Tt(t))?(t=n,us):ld:t instanceof Tt?us:t instanceof Date?sd:od(t)?id:Array.isArray(t)?ad:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?ud:Mt)(e,t)}h();function ms(e,t){return e=+e,t=+t,function(r){return Math.round(e*(1-r)+t*r)}}h();function ds(e){return function(){return e}}h();function ps(e){return+e}var cd=[0,1];function xr(e){return e}function fs(e,t){return(t-=e=+e)?function(r){return(r-e)/t}:ds(isNaN(t)?NaN:.5)}function kb(e,t){var r;return e>t&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function Pb(e,t,r){var n=e[0],i=e[1],o=t[0],a=t[1];return i<n?(n=fs(i,n),o=r(a,o)):(n=fs(n,i),o=r(o,a)),function(u){return o(n(u))}}function Tb(e,t,r){var n=Math.min(e.length,t.length)-1,i=new Array(n),o=new Array(n),a=-1;for(e[n]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++a<n;)i[a]=fs(e[a],e[a+1]),o[a]=r(t[a],t[a+1]);return function(u){var l=is(e,u,1,n)-1;return o[l](i[l](u))}}function Oi(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Mb(){var e=cd,t=cd,r=Ut,n,i,o,a=xr,u,l,c;function m(){var p=Math.min(e.length,t.length);return a!==xr&&(a=kb(e[0],e[p-1])),u=p>2?Tb:Pb,l=c=null,d}function d(p){return p==null||isNaN(p=+p)?o:(l||(l=u(e.map(n),t,r)))(n(a(p)))}return d.invert=function(p){return a(i((c||(c=u(t,e.map(n),Mt)))(p)))},d.domain=function(p){return arguments.length?(e=Array.from(p,ps),m()):e.slice()},d.range=function(p){return arguments.length?(t=Array.from(p),m()):t.slice()},d.rangeRound=function(p){return t=Array.from(p),r=ms,m()},d.clamp=function(p){return arguments.length?(a=p?!0:xr,m()):a!==xr},d.interpolate=function(p){return arguments.length?(r=p,m()):r},d.unknown=function(p){return arguments.length?(o=p,d):o},function(p,f){return n=p,i=f,m()}}function fn(){return Mb()(xr,xr)}h();function hs(e,t,r,n){var i=gr(e,t,r),o;switch(n=kt(n??",f"),n.type){case"s":{var a=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(o=es(i,a))&&(n.precision=o),Si(n,a)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(o=ts(i,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=o-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(o=Ja(i))&&(n.precision=o-(n.type==="%")*2);break}}return fr(n)}function Ab(e){var t=e.domain;return e.ticks=function(r){var n=t();return vi(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var i=t();return hs(i[0],i[i.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),i=0,o=n.length-1,a=n[i],u=n[o],l,c,m=10;for(u<a&&(c=a,a=u,u=c,c=i,i=o,o=c);m-- >0;){if(c=un(a,u,r),c===l)return n[i]=a,n[o]=u,t(n);if(c>0)a=Math.floor(a/c)*c,u=Math.ceil(u/c)*c;else if(c<0)a=Math.ceil(a*c)/c,u=Math.floor(u*c)/c;else break;l=c}return e},e}function Sr(){var e=fn();return e.copy=function(){return Oi(e,Sr())},Pt.apply(e,arguments),Ab(e)}h();function gs(e,t){e=e.slice();var r=0,n=e.length-1,i=e[r],o=e[n],a;return o<i&&(a=r,r=n,n=a,a=i,i=o,o=a),e[r]=t.floor(i),e[n]=t.ceil(o),e}h();h();h();var bs=new Date,ys=new Date;function ce(e,t,r,n){function i(o){return e(o=arguments.length===0?new Date:new Date(+o)),o}return i.floor=o=>(e(o=new Date(+o)),o),i.ceil=o=>(e(o=new Date(o-1)),t(o,1),e(o),o),i.round=o=>{let a=i(o),u=i.ceil(o);return o-a<u-o?a:u},i.offset=(o,a)=>(t(o=new Date(+o),a==null?1:Math.floor(a)),o),i.range=(o,a,u)=>{let l=[];if(o=i.ceil(o),u=u==null?1:Math.floor(u),!(o<a)||!(u>0))return l;let c;do l.push(c=new Date(+o)),t(o,u),e(o);while(c<o&&o<a);return l},i.filter=o=>ce(a=>{if(a>=a)for(;e(a),!o(a);)a.setTime(a-1)},(a,u)=>{if(a>=a)if(u<0)for(;++u<=0;)for(;t(a,-1),!o(a););else for(;--u>=0;)for(;t(a,1),!o(a););}),r&&(i.count=(o,a)=>(bs.setTime(+o),ys.setTime(+a),e(bs),e(ys),Math.floor(r(bs,ys))),i.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?i.filter(n?a=>n(a)%o===0:a=>i.count(0,a)%o===0):i)),i}h();var hn=ce(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);hn.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?ce(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):hn);var WM=hn.range;h();var et=ce(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*1e3)},(e,t)=>(t-e)/1e3,e=>e.getUTCSeconds()),md=et.range;h();var Ni=ce(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*1e3)},(e,t)=>{e.setTime(+e+t*6e4)},(e,t)=>(t-e)/6e4,e=>e.getMinutes()),Cb=Ni.range,wr=ce(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*6e4)},(e,t)=>(t-e)/6e4,e=>e.getUTCMinutes()),Db=wr.range;h();var Fi=ce(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*1e3-e.getMinutes()*6e4)},(e,t)=>{e.setTime(+e+t*36e5)},(e,t)=>(t-e)/36e5,e=>e.getHours()),Rb=Fi.range,vr=ce(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*36e5)},(e,t)=>(t-e)/36e5,e=>e.getUTCHours()),Ob=vr.range;h();var Wt=ce(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/864e5,e=>e.getDate()-1),Nb=Wt.range,Ht=ce(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/864e5,e=>e.getUTCDate()-1),Fb=Ht.range,Li=ce(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/864e5,e=>Math.floor(e/864e5)),Lb=Li.range;h();function Yt(e){return ce(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/6048e5)}var Xt=Yt(0),kr=Yt(1),pd=Yt(2),fd=Yt(3),At=Yt(4),hd=Yt(5),gd=Yt(6),bd=Xt.range,Eb=kr.range,Bb=pd.range,Ib=fd.range,jb=At.range,zb=hd.range,_b=gd.range;function Zt(e){return ce(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/6048e5)}var ht=Zt(0),Pr=Zt(1),yd=Zt(2),xd=Zt(3),Ct=Zt(4),Sd=Zt(5),wd=Zt(6),vd=ht.range,Vb=Pr.range,Ub=yd.range,$b=xd.range,Gb=Ct.range,Wb=Sd.range,Hb=wd.range;h();var Ei=ce(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth()),Yb=Ei.range,Tr=ce(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth()),Xb=Tr.range;h();var He=ce(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());He.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:ce(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});var Zb=He.range,Ve=ce(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());Ve.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:ce(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});var qb=Ve.range;h();function Pd(e,t,r,n,i,o){let a=[[et,1,1e3],[et,5,5*1e3],[et,15,15*1e3],[et,30,30*1e3],[o,1,6e4],[o,5,5*6e4],[o,15,15*6e4],[o,30,30*6e4],[i,1,36e5],[i,3,3*36e5],[i,6,6*36e5],[i,12,12*36e5],[n,1,864e5],[n,2,2*864e5],[r,1,6048e5],[t,1,2592e6],[t,3,3*2592e6],[e,1,31536e6]];function u(c,m,d){let p=m<c;p&&([c,m]=[m,c]);let f=d&&typeof d.range=="function"?d:l(c,m,d),b=f?f.range(c,+m+1):[];return p?b.reverse():b}function l(c,m,d){let p=Math.abs(m-c)/d,f=zt(([,,y])=>y).right(a,p);if(f===a.length)return e.every(gr(c/31536e6,m/31536e6,d));if(f===0)return hn.every(Math.max(gr(c,m,d),1));let[b,g]=a[p/a[f-1][2]<a[f][2]/p?f-1:f];return b.every(g)}return[u,l]}var[xs,Ss]=Pd(Ve,Tr,ht,Li,vr,wr),[Qb,Jb]=Pd(He,Ei,Xt,Wt,Fi,Ni);h();h();h();function ws(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function vs(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function bn(e,t,r){return{y:e,m:t,d:r,H:0,M:0,S:0,L:0}}function ks(e){var t=e.dateTime,r=e.date,n=e.time,i=e.periods,o=e.days,a=e.shortDays,u=e.months,l=e.shortMonths,c=yn(i),m=xn(i),d=yn(o),p=xn(o),f=yn(a),b=xn(a),g=yn(u),y=xn(u),T=yn(l),M=xn(l),v={a:U,A:j,b:Z,B:ne,c:null,d:Rd,e:Rd,f:vy,g:Ny,G:Ly,H:xy,I:Sy,j:wy,L:Ed,m:ky,M:Py,p:pe,q:ae,Q:Fd,s:Ld,S:Ty,u:My,U:Ay,V:Cy,w:Dy,W:Ry,x:null,X:null,y:Oy,Y:Fy,Z:Ey,"%":Nd},x={a:be,A:Ce,b:me,B:L,c:null,d:Od,e:Od,f:zy,g:Zy,G:Ky,H:By,I:Iy,j:jy,L:Id,m:_y,M:Vy,p:z,q,Q:Fd,s:Ld,S:Uy,u:$y,U:Gy,V:Wy,w:Hy,W:Yy,x:null,X:null,y:Xy,Y:qy,Z:Qy,"%":Nd},A={a:$,A:I,b:E,B:k,c:P,d:Cd,e:Cd,f:hy,g:Ad,G:Md,H:Dd,I:Dd,j:my,L:fy,m:cy,M:dy,p:V,q:ly,Q:by,s:yy,S:py,u:iy,U:oy,V:ay,w:ny,W:sy,x:G,X,y:Ad,Y:Md,Z:uy,"%":gy};v.x=w(r,v),v.X=w(n,v),v.c=w(t,v),x.x=w(r,x),x.X=w(n,x),x.c=w(t,x);function w(F,O){return function(_){var C=[],le=-1,ue=0,De=F.length,Re,at,En;for(_ instanceof Date||(_=new Date(+_));++le<De;)F.charCodeAt(le)===37&&(C.push(F.slice(ue,le)),(at=Td[Re=F.charAt(++le)])!=null?Re=F.charAt(++le):at=Re==="e"?" ":"0",(En=O[Re])&&(Re=En(_,at)),C.push(Re),ue=le+1);return C.push(F.slice(ue,le)),C.join("")}}function R(F,O){return function(_){var C=bn(1900,void 0,1),le=N(C,F,_+="",0),ue,De;if(le!=_.length)return null;if("Q"in C)return new Date(C.Q);if("s"in C)return new Date(C.s*1e3+("L"in C?C.L:0));if(O&&!("Z"in C)&&(C.Z=0),"p"in C&&(C.H=C.H%12+C.p*12),C.m===void 0&&(C.m="q"in C?C.q:0),"V"in C){if(C.V<1||C.V>53)return null;"w"in C||(C.w=1),"Z"in C?(ue=vs(bn(C.y,0,1)),De=ue.getUTCDay(),ue=De>4||De===0?Pr.ceil(ue):Pr(ue),ue=Ht.offset(ue,(C.V-1)*7),C.y=ue.getUTCFullYear(),C.m=ue.getUTCMonth(),C.d=ue.getUTCDate()+(C.w+6)%7):(ue=ws(bn(C.y,0,1)),De=ue.getDay(),ue=De>4||De===0?kr.ceil(ue):kr(ue),ue=Wt.offset(ue,(C.V-1)*7),C.y=ue.getFullYear(),C.m=ue.getMonth(),C.d=ue.getDate()+(C.w+6)%7)}else("W"in C||"U"in C)&&("w"in C||(C.w="u"in C?C.u%7:"W"in C?1:0),De="Z"in C?vs(bn(C.y,0,1)).getUTCDay():ws(bn(C.y,0,1)).getDay(),C.m=0,C.d="W"in C?(C.w+6)%7+C.W*7-(De+5)%7:C.w+C.U*7-(De+6)%7);return"Z"in C?(C.H+=C.Z/100|0,C.M+=C.Z%100,vs(C)):ws(C)}}function N(F,O,_,C){for(var le=0,ue=O.length,De=_.length,Re,at;le<ue;){if(C>=De)return-1;if(Re=O.charCodeAt(le++),Re===37){if(Re=O.charAt(le++),at=A[Re in Td?O.charAt(le++):Re],!at||(C=at(F,_,C))<0)return-1}else if(Re!=_.charCodeAt(C++))return-1}return C}function V(F,O,_){var C=c.exec(O.slice(_));return C?(F.p=m.get(C[0].toLowerCase()),_+C[0].length):-1}function $(F,O,_){var C=f.exec(O.slice(_));return C?(F.w=b.get(C[0].toLowerCase()),_+C[0].length):-1}function I(F,O,_){var C=d.exec(O.slice(_));return C?(F.w=p.get(C[0].toLowerCase()),_+C[0].length):-1}function E(F,O,_){var C=T.exec(O.slice(_));return C?(F.m=M.get(C[0].toLowerCase()),_+C[0].length):-1}function k(F,O,_){var C=g.exec(O.slice(_));return C?(F.m=y.get(C[0].toLowerCase()),_+C[0].length):-1}function P(F,O,_){return N(F,t,O,_)}function G(F,O,_){return N(F,r,O,_)}function X(F,O,_){return N(F,n,O,_)}function U(F){return a[F.getDay()]}function j(F){return o[F.getDay()]}function Z(F){return l[F.getMonth()]}function ne(F){return u[F.getMonth()]}function pe(F){return i[+(F.getHours()>=12)]}function ae(F){return 1+~~(F.getMonth()/3)}function be(F){return a[F.getUTCDay()]}function Ce(F){return o[F.getUTCDay()]}function me(F){return l[F.getUTCMonth()]}function L(F){return u[F.getUTCMonth()]}function z(F){return i[+(F.getUTCHours()>=12)]}function q(F){return 1+~~(F.getUTCMonth()/3)}return{format:function(F){var O=w(F+="",v);return O.toString=function(){return F},O},parse:function(F){var O=R(F+="",!1);return O.toString=function(){return F},O},utcFormat:function(F){var O=w(F+="",x);return O.toString=function(){return F},O},utcParse:function(F){var O=R(F+="",!0);return O.toString=function(){return F},O}}}var Td={"-":"",_:" ",0:"0"},ke=/^\s*\d+/,ey=/^%/,ty=/[\\^$*+?|[\]().{}]/g;function oe(e,t,r){var n=e<0?"-":"",i=(n?-e:e)+"",o=i.length;return n+(o<r?new Array(r-o+1).join(t)+i:i)}function ry(e){return e.replace(ty,"\\$&")}function yn(e){return new RegExp("^(?:"+e.map(ry).join("|")+")","i")}function xn(e){return new Map(e.map((t,r)=>[t.toLowerCase(),r]))}function ny(e,t,r){var n=ke.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function iy(e,t,r){var n=ke.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function oy(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function ay(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function sy(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function Md(e,t,r){var n=ke.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function Ad(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function uy(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function ly(e,t,r){var n=ke.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function cy(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function Cd(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function my(e,t,r){var n=ke.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function Dd(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function dy(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function py(e,t,r){var n=ke.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function fy(e,t,r){var n=ke.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function hy(e,t,r){var n=ke.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function gy(e,t,r){var n=ey.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function by(e,t,r){var n=ke.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function yy(e,t,r){var n=ke.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function Rd(e,t){return oe(e.getDate(),t,2)}function xy(e,t){return oe(e.getHours(),t,2)}function Sy(e,t){return oe(e.getHours()%12||12,t,2)}function wy(e,t){return oe(1+Wt.count(He(e),e),t,3)}function Ed(e,t){return oe(e.getMilliseconds(),t,3)}function vy(e,t){return Ed(e,t)+"000"}function ky(e,t){return oe(e.getMonth()+1,t,2)}function Py(e,t){return oe(e.getMinutes(),t,2)}function Ty(e,t){return oe(e.getSeconds(),t,2)}function My(e){var t=e.getDay();return t===0?7:t}function Ay(e,t){return oe(Xt.count(He(e)-1,e),t,2)}function Bd(e){var t=e.getDay();return t>=4||t===0?At(e):At.ceil(e)}function Cy(e,t){return e=Bd(e),oe(At.count(He(e),e)+(He(e).getDay()===4),t,2)}function Dy(e){return e.getDay()}function Ry(e,t){return oe(kr.count(He(e)-1,e),t,2)}function Oy(e,t){return oe(e.getFullYear()%100,t,2)}function Ny(e,t){return e=Bd(e),oe(e.getFullYear()%100,t,2)}function Fy(e,t){return oe(e.getFullYear()%1e4,t,4)}function Ly(e,t){var r=e.getDay();return e=r>=4||r===0?At(e):At.ceil(e),oe(e.getFullYear()%1e4,t,4)}function Ey(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+oe(t/60|0,"0",2)+oe(t%60,"0",2)}function Od(e,t){return oe(e.getUTCDate(),t,2)}function By(e,t){return oe(e.getUTCHours(),t,2)}function Iy(e,t){return oe(e.getUTCHours()%12||12,t,2)}function jy(e,t){return oe(1+Ht.count(Ve(e),e),t,3)}function Id(e,t){return oe(e.getUTCMilliseconds(),t,3)}function zy(e,t){return Id(e,t)+"000"}function _y(e,t){return oe(e.getUTCMonth()+1,t,2)}function Vy(e,t){return oe(e.getUTCMinutes(),t,2)}function Uy(e,t){return oe(e.getUTCSeconds(),t,2)}function $y(e){var t=e.getUTCDay();return t===0?7:t}function Gy(e,t){return oe(ht.count(Ve(e)-1,e),t,2)}function jd(e){var t=e.getUTCDay();return t>=4||t===0?Ct(e):Ct.ceil(e)}function Wy(e,t){return e=jd(e),oe(Ct.count(Ve(e),e)+(Ve(e).getUTCDay()===4),t,2)}function Hy(e){return e.getUTCDay()}function Yy(e,t){return oe(Pr.count(Ve(e)-1,e),t,2)}function Xy(e,t){return oe(e.getUTCFullYear()%100,t,2)}function Zy(e,t){return e=jd(e),oe(e.getUTCFullYear()%100,t,2)}function qy(e,t){return oe(e.getUTCFullYear()%1e4,t,4)}function Ky(e,t){var r=e.getUTCDay();return e=r>=4||r===0?Ct(e):Ct.ceil(e),oe(e.getUTCFullYear()%1e4,t,4)}function Qy(){return"+0000"}function Nd(){return"%"}function Fd(e){return+e}function Ld(e){return Math.floor(+e/1e3)}var Mr,zd,_d,Bi,Vd;Ps({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Ps(e){return Mr=ks(e),zd=Mr.format,_d=Mr.parse,Bi=Mr.utcFormat,Vd=Mr.utcParse,Mr}function Jy(e){return new Date(e)}function e0(e){return e instanceof Date?+e:+new Date(+e)}function Ts(e,t,r,n,i,o,a,u,l,c){var m=fn(),d=m.invert,p=m.domain,f=c(".%L"),b=c(":%S"),g=c("%I:%M"),y=c("%I %p"),T=c("%a %d"),M=c("%b %d"),v=c("%B"),x=c("%Y");function A(w){return(l(w)<w?f:u(w)<w?b:a(w)<w?g:o(w)<w?y:n(w)<w?i(w)<w?T:M:r(w)<w?v:x)(w)}return m.invert=function(w){return new Date(d(w))},m.domain=function(w){return arguments.length?p(Array.from(w,e0)):p().map(Jy)},m.ticks=function(w){var R=p();return e(R[0],R[R.length-1],w??10)},m.tickFormat=function(w,R){return R==null?A:c(R)},m.nice=function(w){var R=p();return(!w||typeof w.range!="function")&&(w=t(R[0],R[R.length-1],w??10)),w?p(gs(R,w)):m},m.copy=function(){return Oi(m,Ts(e,t,r,n,i,o,a,u,l,c))},m}h();function Ii(){return Pt.apply(Ts(xs,Ss,Ve,Tr,ht,Ht,vr,wr,et,Bi).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}h();h();h();function K(e){return function(){return e}}h();var Ms=Math.abs,Ae=Math.atan2,Dt=Math.cos,Ud=Math.max,ji=Math.min,Ye=Math.sin,qt=Math.sqrt,Ie=1e-12,Ar=Math.PI,Sn=Ar/2,Cr=2*Ar;function $d(e){return e>1?0:e<-1?Ar:Math.acos(e)}function As(e){return e>=1?Sn:e<=-1?-Sn:Math.asin(e)}h();h();h();var Cs=Math.PI,Ds=2*Cs,Kt=1e-6,t0=Ds-Kt;function Gd(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=arguments[t]+e[t]}function r0(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return Gd;let r=10**t;return function(n){this._+=n[0];for(let i=1,o=n.length;i<o;++i)this._+=Math.round(arguments[i]*r)/r+n[i]}}var Qt=class{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?Gd:r0(t)}moveTo(t,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,r){this._append`L${this._x1=+t},${this._y1=+r}`}quadraticCurveTo(t,r,n,i){this._append`Q${+t},${+r},${this._x1=+n},${this._y1=+i}`}bezierCurveTo(t,r,n,i,o,a){this._append`C${+t},${+r},${+n},${+i},${this._x1=+o},${this._y1=+a}`}arcTo(t,r,n,i,o){if(t=+t,r=+r,n=+n,i=+i,o=+o,o<0)throw new Error(`negative radius: ${o}`);let a=this._x1,u=this._y1,l=n-t,c=i-r,m=a-t,d=u-r,p=m*m+d*d;if(this._x1===null)this._append`M${this._x1=t},${this._y1=r}`;else if(p>Kt)if(!(Math.abs(d*l-c*m)>Kt)||!o)this._append`L${this._x1=t},${this._y1=r}`;else{let f=n-a,b=i-u,g=l*l+c*c,y=f*f+b*b,T=Math.sqrt(g),M=Math.sqrt(p),v=o*Math.tan((Cs-Math.acos((g+p-y)/(2*T*M)))/2),x=v/M,A=v/T;Math.abs(x-1)>Kt&&this._append`L${t+x*m},${r+x*d}`,this._append`A${o},${o},0,0,${+(d*f>m*b)},${this._x1=t+A*l},${this._y1=r+A*c}`}}arc(t,r,n,i,o,a){if(t=+t,r=+r,n=+n,a=!!a,n<0)throw new Error(`negative radius: ${n}`);let u=n*Math.cos(i),l=n*Math.sin(i),c=t+u,m=r+l,d=1^a,p=a?i-o:o-i;this._x1===null?this._append`M${c},${m}`:(Math.abs(this._x1-c)>Kt||Math.abs(this._y1-m)>Kt)&&this._append`L${c},${m}`,n&&(p<0&&(p=p%Ds+Ds),p>t0?this._append`A${n},${n},0,1,${d},${t-u},${r-l}A${n},${n},0,1,${d},${this._x1=c},${this._y1=m}`:p>Kt&&this._append`A${n},${n},0,${+(p>=Cs)},${d},${this._x1=t+n*Math.cos(o)},${this._y1=r+n*Math.sin(o)}`)}rect(t,r,n,i){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}};function Wd(){return new Qt}Wd.prototype=Qt.prototype;function Dr(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{let n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new Qt(t)}function n0(e){return e.innerRadius}function i0(e){return e.outerRadius}function o0(e){return e.startAngle}function a0(e){return e.endAngle}function s0(e){return e&&e.padAngle}function u0(e,t,r,n,i,o,a,u){var l=r-e,c=n-t,m=a-i,d=u-o,p=d*l-m*c;if(!(p*p<Ie))return p=(m*(t-o)-d*(e-i))/p,[e+p*l,t+p*c]}function zi(e,t,r,n,i,o,a){var u=e-r,l=t-n,c=(a?o:-o)/qt(u*u+l*l),m=c*l,d=-c*u,p=e+m,f=t+d,b=r+m,g=n+d,y=(p+b)/2,T=(f+g)/2,M=b-p,v=g-f,x=M*M+v*v,A=i-o,w=p*g-b*f,R=(v<0?-1:1)*qt(Ud(0,A*A*x-w*w)),N=(w*v-M*R)/x,V=(-w*M-v*R)/x,$=(w*v+M*R)/x,I=(-w*M+v*R)/x,E=N-y,k=V-T,P=$-y,G=I-T;return E*E+k*k>P*P+G*G&&(N=$,V=I),{cx:N,cy:V,x01:-m,y01:-d,x11:N*(i/A-1),y11:V*(i/A-1)}}function _i(){var e=n0,t=i0,r=K(0),n=null,i=o0,o=a0,a=s0,u=null,l=Dr(c);function c(){var m,d,p=+e.apply(this,arguments),f=+t.apply(this,arguments),b=i.apply(this,arguments)-Sn,g=o.apply(this,arguments)-Sn,y=Ms(g-b),T=g>b;if(u||(u=m=l()),f<p&&(d=f,f=p,p=d),!(f>Ie))u.moveTo(0,0);else if(y>Cr-Ie)u.moveTo(f*Dt(b),f*Ye(b)),u.arc(0,0,f,b,g,!T),p>Ie&&(u.moveTo(p*Dt(g),p*Ye(g)),u.arc(0,0,p,g,b,T));else{var M=b,v=g,x=b,A=g,w=y,R=y,N=a.apply(this,arguments)/2,V=N>Ie&&(n?+n.apply(this,arguments):qt(p*p+f*f)),$=ji(Ms(f-p)/2,+r.apply(this,arguments)),I=$,E=$,k,P;if(V>Ie){var G=As(V/p*Ye(N)),X=As(V/f*Ye(N));(w-=G*2)>Ie?(G*=T?1:-1,x+=G,A-=G):(w=0,x=A=(b+g)/2),(R-=X*2)>Ie?(X*=T?1:-1,M+=X,v-=X):(R=0,M=v=(b+g)/2)}var U=f*Dt(M),j=f*Ye(M),Z=p*Dt(A),ne=p*Ye(A);if($>Ie){var pe=f*Dt(v),ae=f*Ye(v),be=p*Dt(x),Ce=p*Ye(x),me;if(y<Ar)if(me=u0(U,j,be,Ce,pe,ae,Z,ne)){var L=U-me[0],z=j-me[1],q=pe-me[0],F=ae-me[1],O=1/Ye($d((L*q+z*F)/(qt(L*L+z*z)*qt(q*q+F*F)))/2),_=qt(me[0]*me[0]+me[1]*me[1]);I=ji($,(p-_)/(O-1)),E=ji($,(f-_)/(O+1))}else I=E=0}R>Ie?E>Ie?(k=zi(be,Ce,U,j,f,E,T),P=zi(pe,ae,Z,ne,f,E,T),u.moveTo(k.cx+k.x01,k.cy+k.y01),E<$?u.arc(k.cx,k.cy,E,Ae(k.y01,k.x01),Ae(P.y01,P.x01),!T):(u.arc(k.cx,k.cy,E,Ae(k.y01,k.x01),Ae(k.y11,k.x11),!T),u.arc(0,0,f,Ae(k.cy+k.y11,k.cx+k.x11),Ae(P.cy+P.y11,P.cx+P.x11),!T),u.arc(P.cx,P.cy,E,Ae(P.y11,P.x11),Ae(P.y01,P.x01),!T))):(u.moveTo(U,j),u.arc(0,0,f,M,v,!T)):u.moveTo(U,j),!(p>Ie)||!(w>Ie)?u.lineTo(Z,ne):I>Ie?(k=zi(Z,ne,pe,ae,p,-I,T),P=zi(U,j,be,Ce,p,-I,T),u.lineTo(k.cx+k.x01,k.cy+k.y01),I<$?u.arc(k.cx,k.cy,I,Ae(k.y01,k.x01),Ae(P.y01,P.x01),!T):(u.arc(k.cx,k.cy,I,Ae(k.y01,k.x01),Ae(k.y11,k.x11),!T),u.arc(0,0,p,Ae(k.cy+k.y11,k.cx+k.x11),Ae(P.cy+P.y11,P.cx+P.x11),T),u.arc(P.cx,P.cy,I,Ae(P.y11,P.x11),Ae(P.y01,P.x01),!T))):u.arc(0,0,p,A,x,T)}if(u.closePath(),m)return u=null,m+""||null}return c.centroid=function(){var m=(+e.apply(this,arguments)+ +t.apply(this,arguments))/2,d=(+i.apply(this,arguments)+ +o.apply(this,arguments))/2-Ar/2;return[Dt(d)*m,Ye(d)*m]},c.innerRadius=function(m){return arguments.length?(e=typeof m=="function"?m:K(+m),c):e},c.outerRadius=function(m){return arguments.length?(t=typeof m=="function"?m:K(+m),c):t},c.cornerRadius=function(m){return arguments.length?(r=typeof m=="function"?m:K(+m),c):r},c.padRadius=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:K(+m),c):n},c.startAngle=function(m){return arguments.length?(i=typeof m=="function"?m:K(+m),c):i},c.endAngle=function(m){return arguments.length?(o=typeof m=="function"?m:K(+m),c):o},c.padAngle=function(m){return arguments.length?(a=typeof m=="function"?m:K(+m),c):a},c.context=function(m){return arguments.length?(u=m??null,c):u},c}h();h();var TA=Array.prototype.slice;function Rt(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}h();function Hd(e){this._context=e}Hd.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function Jt(e){return new Hd(e)}h();h();function Vi(e){return e[0]}function Ui(e){return e[1]}function wn(e,t){var r=K(!0),n=null,i=Jt,o=null,a=Dr(u);e=typeof e=="function"?e:e===void 0?Vi:K(e),t=typeof t=="function"?t:t===void 0?Ui:K(t);function u(l){var c,m=(l=Rt(l)).length,d,p=!1,f;for(n==null&&(o=i(f=a())),c=0;c<=m;++c)!(c<m&&r(d=l[c],c,l))===p&&((p=!p)?o.lineStart():o.lineEnd()),p&&o.point(+e(d,c,l),+t(d,c,l));if(f)return o=null,f+""||null}return u.x=function(l){return arguments.length?(e=typeof l=="function"?l:K(+l),u):e},u.y=function(l){return arguments.length?(t=typeof l=="function"?l:K(+l),u):t},u.defined=function(l){return arguments.length?(r=typeof l=="function"?l:K(!!l),u):r},u.curve=function(l){return arguments.length?(i=l,n!=null&&(o=i(n)),u):i},u.context=function(l){return arguments.length?(l==null?n=o=null:o=i(n=l),u):n},u}function Rs(e,t,r){var n=null,i=K(!0),o=null,a=Jt,u=null,l=Dr(c);e=typeof e=="function"?e:e===void 0?Vi:K(+e),t=typeof t=="function"?t:t===void 0?K(0):K(+t),r=typeof r=="function"?r:r===void 0?Ui:K(+r);function c(d){var p,f,b,g=(d=Rt(d)).length,y,T=!1,M,v=new Array(g),x=new Array(g);for(o==null&&(u=a(M=l())),p=0;p<=g;++p){if(!(p<g&&i(y=d[p],p,d))===T)if(T=!T)f=p,u.areaStart(),u.lineStart();else{for(u.lineEnd(),u.lineStart(),b=p-1;b>=f;--b)u.point(v[b],x[b]);u.lineEnd(),u.areaEnd()}T&&(v[p]=+e(y,p,d),x[p]=+t(y,p,d),u.point(n?+n(y,p,d):v[p],r?+r(y,p,d):x[p]))}if(M)return u=null,M+""||null}function m(){return wn().defined(i).curve(a).context(o)}return c.x=function(d){return arguments.length?(e=typeof d=="function"?d:K(+d),n=null,c):e},c.x0=function(d){return arguments.length?(e=typeof d=="function"?d:K(+d),c):e},c.x1=function(d){return arguments.length?(n=d==null?null:typeof d=="function"?d:K(+d),c):n},c.y=function(d){return arguments.length?(t=typeof d=="function"?d:K(+d),r=null,c):t},c.y0=function(d){return arguments.length?(t=typeof d=="function"?d:K(+d),c):t},c.y1=function(d){return arguments.length?(r=d==null?null:typeof d=="function"?d:K(+d),c):r},c.lineX0=c.lineY0=function(){return m().x(e).y(t)},c.lineY1=function(){return m().x(e).y(r)},c.lineX1=function(){return m().x(n).y(t)},c.defined=function(d){return arguments.length?(i=typeof d=="function"?d:K(!!d),c):i},c.curve=function(d){return arguments.length?(a=d,o!=null&&(u=a(o)),c):a},c.context=function(d){return arguments.length?(d==null?o=u=null:u=a(o=d),c):o},c}h();h();function Yd(e,t){return t<e?-1:t>e?1:t>=e?0:NaN}h();function Xd(e){return e}function Os(){var e=Xd,t=Yd,r=null,n=K(0),i=K(Cr),o=K(0);function a(u){var l,c=(u=Rt(u)).length,m,d,p=0,f=new Array(c),b=new Array(c),g=+n.apply(this,arguments),y=Math.min(Cr,Math.max(-Cr,i.apply(this,arguments)-g)),T,M=Math.min(Math.abs(y)/c,o.apply(this,arguments)),v=M*(y<0?-1:1),x;for(l=0;l<c;++l)(x=b[f[l]=l]=+e(u[l],l,u))>0&&(p+=x);for(t!=null?f.sort(function(A,w){return t(b[A],b[w])}):r!=null&&f.sort(function(A,w){return r(u[A],u[w])}),l=0,d=p?(y-c*v)/p:0;l<c;++l,g=T)m=f[l],x=b[m],T=g+(x>0?x*d:0)+v,b[m]={data:u[m],index:l,value:x,startAngle:g,endAngle:T,padAngle:M};return b}return a.value=function(u){return arguments.length?(e=typeof u=="function"?u:K(+u),a):e},a.sortValues=function(u){return arguments.length?(t=u,r=null,a):t},a.sort=function(u){return arguments.length?(r=u,t=null,a):r},a.startAngle=function(u){return arguments.length?(n=typeof u=="function"?u:K(+u),a):n},a.endAngle=function(u){return arguments.length?(i=typeof u=="function"?u:K(+u),a):i},a.padAngle=function(u){return arguments.length?(o=typeof u=="function"?u:K(+u),a):o},a}h();function Zd(e){return e<0?-1:1}function qd(e,t,r){var n=e._x1-e._x0,i=t-e._x1,o=(e._y1-e._y0)/(n||i<0&&-0),a=(r-e._y1)/(i||n<0&&-0),u=(o*i+a*n)/(n+i);return(Zd(o)+Zd(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function Kd(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function Ns(e,t,r){var n=e._x0,i=e._y0,o=e._x1,a=e._y1,u=(o-n)/3;e._context.bezierCurveTo(n+u,i+u*t,o-u,a-u*r,o,a)}function $i(e){this._context=e}$i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Ns(this,this._t0,Kd(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Ns(this,Kd(this,r=qd(this,e,t)),r);break;default:Ns(this,this._t0,r=qd(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function l0(e){this._context=new Qd(e)}(l0.prototype=Object.create($i.prototype)).point=function(e,t){$i.prototype.point.call(this,t,e)};function Qd(e){this._context=e}Qd.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,i,o){this._context.bezierCurveTo(t,e,n,r,o,i)}};function Fs(e){return new $i(e)}h();function Jd(e,t){this._context=e,this._t=t}Jd.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function Ls(e){return new Jd(e,1)}h();h();function Es(e,t){if((a=e.length)>1)for(var r=1,n,i,o=e[t[0]],a,u=o.length;r<a;++r)for(i=o,o=e[t[r]],n=0;n<u;++n)o[n][1]+=o[n][0]=isNaN(i[n][1])?i[n][0]:i[n][1]}h();function Bs(e){for(var t=e.length,r=new Array(t);--t>=0;)r[t]=t;return r}function c0(e,t){return e[t]}function m0(e){let t=[];return t.key=e,t}function Is(){var e=K([]),t=Bs,r=Es,n=c0;function i(o){var a=Array.from(e.apply(this,arguments),m0),u,l=a.length,c=-1,m;for(let d of o)for(u=0,++c;u<l;++u)(a[u][c]=[0,+n(d,a[u].key,c,o)]).data=d;for(u=0,m=Rt(t(a));u<l;++u)a[m[u]].index=u;return r(a,m),a}return i.keys=function(o){return arguments.length?(e=typeof o=="function"?o:K(Array.from(o)),i):e},i.value=function(o){return arguments.length?(n=typeof o=="function"?o:K(+o),i):n},i.order=function(o){return arguments.length?(t=o==null?Bs:typeof o=="function"?o:K(Array.from(o)),i):t},i.offset=function(o){return arguments.length?(r=o??Es,i):r},i}h();function js(e,t){if((l=e.length)>0)for(var r,n=0,i,o,a,u,l,c=e[t[0]].length;n<c;++n)for(a=u=0,r=0;r<l;++r)(o=(i=e[t[r]][n])[1]-i[0])>0?(i[0]=a,i[1]=a+=o):o<0?(i[1]=u,i[0]=u+=o):(i[0]=0,i[1]=o)}var np=["#6366f1","#22d3ee","#f59e0b","#ec4899","#10b981","#8b5cf6","#f97316","#3b82f6"],d0=e=>typeof e=="object"&&e!==null&&"open"in e&&"close"in e,p0=e=>typeof e=="object"&&e!==null&&"label"in e&&"value"in e;function f0(e){return e==="linear"?Jt:e==="step"?Ls:Fs}function zs(e,t){let r=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!r)return e;let n=r[1];n.length===3&&(n=[...n].map(o=>o+o).join(""));let i=parseInt(n,16);return`rgba(${i>>16&255}, ${i>>8&255}, ${i&255}, ${t})`}function ep(e){if(!e?.format)return null;if(typeof e.format=="function")return e.format;let t=fr(e.format);return r=>typeof r=="number"?t(r):String(r)}function J(e){return Math.round(e*100)/100}function Rr(e,t=0,r=e.duration){return Q.create().fromTo("opacity",0,1,{start:e.start+t,end:e.start+t+Math.max(1,r),ease:"power2.out"})}function ip(e,t,r){let n=t.id??Y("chart"),i=e.width??(typeof t.width=="number"?t.width:960),o=e.height??(typeof t.height=="number"?t.height:540),a=e.type??"line",u=e.fontSize??18,l=e.fontFamily??r,c=e.textColor??"#94a3b8",m=e.textColor??"#e2e8f0",d=e.gridColor??"rgba(148, 163, 184, 0.18)",p=e.colors?.length?e.colors:np,f=e.cornerRadius??4,b=e.animate===!1?void 0:e.animate??{},g={enabled:b!==void 0,start:b?.start??0,duration:b?.duration??30,stagger:b?.stagger??-1,ease:b?.ease??"power3.out"},y=[],T=(k,P,G,X={},U="")=>{let j=B.text(k,{id:`${n}-label-${U||y.length}`,position:"absolute",x:J(P.x),y:J(P.y),width:J(P.width),height:J(P.height),fontFamily:l,fontSize:u,fontWeight:X.weight??500,fill:X.color??c,align:G,verticalAlign:"middle"});g.enabled&&j.animate(Rr(g,X.delay??0)),y.push(j)},M=Math.ceil(u*1.4);a==="pie"||a==="donut"?v():A();for(let k of y)op(k);return B.box({background:e.background??"transparent",...t,id:n,width:i,height:o,children:y});function v(){let k=x(),P=k.reduce((L,z)=>L+Math.max(0,z.value),0),G=e.legend??!0,X=R({top:16,right:G?V(k.map(L=>L.label)):16,bottom:16,left:16}),U=N(X),j=Math.max(1,Math.min(U.width,U.height)/2),Z=j*(e.innerRadius??(a==="donut"?.6:0)),ne=U.x+U.width/2,pe=U.y+U.height/2,ae=4,be=Os().sort(null).value(L=>Math.max(0,L.value)).padAngle(k.length>1?.012:0)(k),Ce=_i().innerRadius(Z).outerRadius(j).cornerRadius(Math.min(f,(j-Z)/2)),me=w(be.length);be.forEach((L,z)=>{let q=Ce(L);if(!q)return;let F=k[z].color??p[z%p.length],O=B.shape("path",{id:`${n}-slice-${z}`,position:"absolute",x:J(ne-j-ae),y:J(pe-j-ae),width:J(2*(j+ae)),height:J(2*(j+ae)),d:h0(q,j+ae,j+ae),fillColor:F,anchorX:.5,anchorY:.5});if(g.enabled){let _=g.start+z*me;O.animate(Q.create().fromTo("opacity",0,1,{start:_,end:_+g.duration*.5}).fromTo("scale",.85,1,{start:_,end:_+g.duration,ease:g.ease}))}if(y.push(O),e.valueLabels&&P>0&&L.value>0){let[_,C]=_i().innerRadius(Z||j*.55).outerRadius(j).centroid(L),le=`${Math.round(L.value/P*100)}%`;T(le,{x:ne+_-60,y:pe+C-M/2,width:120,height:M},"center",{delay:z*me+g.duration*.5,color:"#ffffff",weight:700},`value-${z}`)}}),G&&$(k.map((L,z)=>({name:L.label,color:L.color??p[z%p.length]})),{x:U.x+U.width+24,y:U.y,height:U.height})}function x(){return(e.data??e.series?.[0]?.data??[]).map((P,G)=>{if(p0(P))return P;let X=typeof P=="number"?P:Array.isArray(P)?Number(P[1]):Number(P.y);return{label:e.categories?.[G]??(Array.isArray(P)?String(P[0]):typeof P=="object"&&P?String(P.x):`${G+1}`),value:X}})}function A(){let k=e.series?.length?[...e.series]:e.data?[{data:e.data}]:[];if(k.length===0)return;let P=D=>D.type??a??"line",G=(D,W)=>D.color??p[W%p.length],X=k.map(D=>D.data.map((W,re)=>d0(W)?{x:W.x,y:W.close}:typeof W=="number"?{x:e.categories?.[re]??re,y:W}:Array.isArray(W)?{x:W[0],y:Number(W[1])}:{x:W.x,y:Number(W.y)})),U=k.some(D=>P(D)==="bar"||P(D)==="candlestick"),j=X.flat().map(D=>D.x),Z=U||j.some(D=>typeof D=="string")?"band":j.some(D=>D instanceof Date)?"time":"linear",ne=D=>P(D)==="bar"||P(D)==="area",pe=!!e.stacked,ae=Z==="band"?[...new Set(j.map(String))]:[],be=new Map;if(pe){let D=k.map((fe,Te)=>Te).filter(fe=>ne(k[fe])),W=ae.length?ae:[...new Set(j.map(fe=>+fe))].sort((fe,Te)=>fe-Te).map(String),re=W.map(fe=>{let Te={};for(let Oe of D){let Ne=X[Oe].find(ve=>String(Z==="band"?ve.x:+ve.x)===fe);Te[Oe]=Ne?.y??0}return Te});Is().keys(D.map(String)).offset(js)(re).forEach(fe=>{let Te=Number(fe.key);be.set(Te,X[Te].map(Oe=>{let Ne=W.indexOf(String(Z==="band"?Oe.x:+Oe.x));return[fe[Ne][0],fe[Ne][1]]}))})}let Ce=[0];k.forEach((D,W)=>{let re=be.get(W);if(P(D)==="candlestick")for(let de of D.data)Ce.push(de.high,de.low);else if(re)for(let[de,fe]of re)Ce.push(de,fe);else for(let de of X[W])Ce.push(de.y)}),k.every(D=>P(D)==="candlestick"||P(D)==="scatter"||P(D)==="line")&&Ce.shift();let me=e.yAxis??{},L=e.xAxis??{},z=me.ticks??5,q=me.min??Math.min(...Ce),F=me.max??Math.max(...Ce);(!Number.isFinite(q)||!Number.isFinite(F))&&([q,F]=[0,1]),q===F&&([q,F]=[q-1,F+1]);let O=Sr().domain([q,F]);(me.min===void 0||me.max===void 0)&&O.nice(z);let _=ep(me)??(D=>O.tickFormat(z)(D)),C=O.ticks(z),le=k.map((D,W)=>({name:D.name??`Series ${W+1}`,color:G(D,W)})),ue=e.legend??k.length>1,De=me.show!==!1,Re=L.show!==!1,at=De?Math.max(...C.map(D=>_(D).length))*u*.7+20:0,En=R({top:(ue?M+20:0)+Math.ceil(M/2),right:20,bottom:Re?M+14:12,left:Math.max(16,Math.ceil(at))}),ie=N(En),xu=M+6,Su=e.valueLabels?k.flatMap((D,W)=>P(D)==="bar"?X[W].map(re=>re.y):[]):[],Of=Su.some(D=>D>0)?xu:0,Nf=Su.some(D=>D<0)?xu:0;O.range([ie.height-Nf,Of]);let st;if(Z==="band")st=ln().domain(ae).range([0,ie.width]).paddingInner(U?.28:0).paddingOuter(U?.14:.5);else if(Z==="time"){let D=j.map(W=>+new Date(W));st=Ii().domain([Math.min(...D),Math.max(...D)]).range([0,ie.width])}else{let D=j.map(Number);st=Sr().domain([L.min??Math.min(...D),L.max??Math.max(...D)]).range([0,ie.width])}let wu=D=>{if(Z==="band"){let W=st;return(W(String(D))??0)+W.bandwidth()/2}return st(Z==="time"?new Date(D):Number(D))},vu=0;me.grid!==!1&&C.forEach((D,W)=>{let re=B.box({id:`${n}-ygrid-${W}`,position:"absolute",x:ie.x,y:J(ie.y+O(D)-.5),width:ie.width,height:1,background:d});g.enabled&&re.animate(Rr(g,vu,g.duration/2)),y.push(re)}),De&&C.forEach((D,W)=>{T(_(D),{x:0,y:ie.y+O(D)-M/2,width:ie.x-12,height:M},"end",{},`y-${W}`)});let Er=[],Bn=ep(L);if(Z==="band"){let D=st,W=Math.max(1,Math.ceil(ae.length/Math.max(1,Math.floor(ie.width/(u*4)))));ae.forEach((re,de)=>{de%W===0&&Er.push({pos:(D(re)??0)+D.bandwidth()/2,text:Bn?Bn(re):re})})}else{let D=st,W=L.ticks??Math.max(2,Math.floor(ie.width/(u*6))),re=D.tickFormat(W);for(let de of D.ticks(W))Er.push({pos:D(de),text:Bn?Bn(Z==="time"?new Date(de):de):re(de)})}if(L.grid&&Er.forEach((D,W)=>{let re=B.box({id:`${n}-xgrid-${W}`,position:"absolute",x:J(ie.x+D.pos-.5),y:ie.y,width:1,height:ie.height,background:d});g.enabled&&re.animate(Rr(g,vu,g.duration/2)),y.push(re)}),Re){let D=Math.max(u*3,ie.width/Math.max(1,Er.length));Er.forEach((W,re)=>{T(W.text,{x:ie.x+W.pos-D/2,y:ie.y+ie.height+10,width:D,height:M},"center",{},`x-${re}`)})}let[Ff,Lf]=O.domain();if(Ff<=0&&Lf>=0&&U){let D=B.box({id:`${n}-zero`,position:"absolute",x:ie.x,y:J(ie.y+O(0)-1),width:ie.width,height:2,background:zs("#94a3b8",.45)});g.enabled&&D.animate(Rr(g,0,g.duration/2)),y.push(D)}let In=k.map((D,W)=>W).filter(D=>P(k[D])==="bar"),Ef=[...In,...k.map((D,W)=>W).filter(D=>P(k[D])==="candlestick"),...k.map((D,W)=>W).filter(D=>P(k[D])==="area"),...k.map((D,W)=>W).filter(D=>P(k[D])==="line"),...k.map((D,W)=>W).filter(D=>P(k[D])==="scatter")],xt=Z==="band"?st:null,ku=xt?w(ae.length):0,Pu=D=>xt?ae.indexOf(String(D)):0;Ef.forEach((D,W)=>{let re=k[D],de=G(re,D),fe=P(re),Te=X[D],Oe=be.get(D);if(fe==="bar"&&xt){let Ne=pe?1:In.length,ve=pe?0:In.indexOf(D),Fe=xt.bandwidth()/Ne,ye=Ne>1?Math.min(4,Fe*.12):0;Te.forEach((Ee,qe)=>{let[St,Me]=Oe?Oe[qe]:[0,Ee.y],Se=ie.y+O(Math.max(St,Me)),jn=ie.y+O(Math.min(St,Me)),Be=Math.max(0,jn-Se),Br=ie.x+(xt(String(Ee.x))??0)+ve*Fe+ye/2,Ot=Ee.y>=0?"up":"down",zn=B.box({id:`${n}-bar-${D}-${qe}`,position:"absolute",x:J(Br),y:J(Se),width:J(Math.max(1,Fe-ye)),height:J(Be),background:de,borderRadius:Math.min(f,(Fe-ye)/2,Be/2)}),Mu=Pu(Ee.x)*ku+(pe?In.indexOf(D)*g.duration*.6:0);if(g.enabled){let Ir=g.start+Mu,_n=Ir+g.duration,Au=Q.create().fromTo("height",0,J(Be),{start:Ir,end:_n,ease:g.ease});Ot==="up"&&Au.fromTo("y",J(Se+Be),J(Se),{start:Ir,end:_n,ease:g.ease}),zn.animate(Au)}if(y.push(zn),e.valueLabels){let Ir=_(Ee.y),_n=Ot==="up"?Se-M-4:Se+Be+4;T(Ir,{x:Br-30,y:_n,width:Fe-ye+60,height:M},"center",{delay:Mu+g.duration*.6,color:m,weight:600},`value-${D}-${qe}`)}});return}if(fe==="candlestick"&&xt){let Ne=e.upColor??"#22c55e",ve=e.downColor??"#ef4444",Fe=xt.bandwidth();re.data.forEach((ye,Ee)=>{let qe=ye.close>=ye.open?Ne:ve,St=ie.x+(xt(String(ye.x))??0)+Fe/2,Me=Pu(ye.x)*ku,Se=[["wick",{x:St-Math.max(1,Fe*.06),y:ie.y+O(ye.high),width:Math.max(2,Fe*.12),height:Math.max(1,O(ye.low)-O(ye.high))}],["body",{x:St-Fe/2,y:ie.y+O(Math.max(ye.open,ye.close)),width:Fe,height:Math.max(2,Math.abs(O(ye.open)-O(ye.close)))}]];for(let[jn,Be]of Se){let Br=B.box({id:`${n}-candle-${D}-${Ee}-${jn}`,position:"absolute",x:J(Be.x),y:J(Be.y),width:J(Be.width),height:J(Be.height),background:qe,borderRadius:jn==="body"?Math.min(f/2,Be.width/2):0});if(g.enabled){let Ot=g.start+Me,zn=Be.y+Be.height/2;Br.animate(Q.create().fromTo("height",0,J(Be.height),{start:Ot,end:Ot+g.duration,ease:g.ease}).fromTo("y",J(zn),J(Be.y),{start:Ot,end:Ot+g.duration,ease:g.ease}))}y.push(Br)}});return}if(fe==="line"||fe==="area"){let Ne=re.strokeWidth??3,ve=Math.ceil(Ne*2+(re.pointRadius??0)+2),Fe=Te.map((Me,Se)=>({x:wu(Me.x)+ve,top:O(Oe?Oe[Se][1]:Me.y)+ve,base:O(Oe?Oe[Se][0]:Math.max(O.domain()[0],Math.min(0,O.domain()[1])))+ve})),ye=f0(re.curve),Ee={x:ie.x-ve,y:ie.y-ve,width:ie.width+2*ve,height:ie.height+2*ve},qe=W*(g.duration/3);if(fe==="area"){let Me=Rs().x(Se=>Se.x).y0(Se=>Se.base).y1(Se=>Se.top).curve(ye)(Fe);if(Me){let Se=B.shape("path",{id:`${n}-area-${D}`,position:"absolute",...tp(Ee),d:rp(Me),fillType:"linear",fillColor:zs(de,.45),gradientEndColor:zs(de,.02),gradientAngle:90});g.enabled&&Se.animate(Rr(g,qe+g.duration*.4,g.duration)),y.push(Se)}}let St=wn().x(Me=>Me.x).y(Me=>Me.top).curve(ye)(Fe);if(St&&Ne>0){let Me=B.shape("path",{id:`${n}-line-${D}`,position:"absolute",...tp(Ee),d:rp(St),fillType:"none",strokeColor:de,strokeWidth:Ne,strokeLineCap:"round",strokeLineJoin:"round"});g.enabled&&Me.animate(Q.create().fromTo("trimEnd",0,1,{start:g.start+qe,end:g.start+qe+g.duration*1.5,ease:"power2.inOut"})),y.push(Me)}(re.pointRadius??0)>0&&Tu(D,Te,de,re.pointRadius??0,qe+g.duration*.5,Oe);return}fe==="scatter"&&Tu(D,Te,de,re.pointRadius??6,W*(g.duration/3),Oe)}),ue&&I(le);function Tu(D,W,re,de,fe,Te){let Oe=w(W.length);W.forEach((Ne,ve)=>{let Fe=O(Te?Te[ve][1]:Ne.y),ye=B.shape("circle",{id:`${n}-point-${D}-${ve}`,position:"absolute",x:J(ie.x+wu(Ne.x)-de),y:J(ie.y+Fe-de),width:J(de*2),height:J(de*2),fillColor:re,anchorX:.5,anchorY:.5});if(g.enabled){let Ee=g.start+fe+ve*Oe;ye.animate(Q.create().fromTo("scale",0,1,{start:Ee,end:Ee+g.duration*.6,ease:"back.out(2)"}).fromTo("opacity",0,1,{start:Ee,end:Ee+6}))}y.push(ye)})}}function w(k){return!g.enabled||k<=1?0:g.stagger>=0?g.stagger:Math.min(4,g.duration/k)}function R(k){let P=e.padding;return typeof P=="number"?{top:P,right:P,bottom:P,left:P}:{top:P?.top??k.top,right:P?.right??k.right,bottom:P?.bottom??k.bottom,left:P?.left??k.left}}function N(k){return{x:k.left,y:k.top,width:Math.max(1,i-k.left-k.right),height:Math.max(1,o-k.top-k.bottom)}}function V(k){let P=Math.max(0,...k.map(G=>G.length));return Math.min(i*.4,P*u*.6+u+48)}function $(k,P){let G=M+8,X=P.y+Math.max(0,(P.height-k.length*G)/2);k.forEach((U,j)=>{E(U,P.x,X+j*G,j)})}function I(k){let P=k.map(U=>U.name.length*u*.6+u+28),G=P.reduce((U,j)=>U+j,0),X=Math.max(0,i-G-20);k.forEach((U,j)=>{E(U,X,4,j),X+=P[j]})}function E(k,P,G,X){let U=Math.round(u*.7),j=B.box({id:`${n}-legend-swatch-${X}`,position:"absolute",x:J(P),y:J(G+(M-U)/2),width:U,height:U,borderRadius:Math.round(U/4),background:k.color});g.enabled&&j.animate(Rr(g,0,g.duration/2)),y.push(j),T(k.name,{x:P+U+8,y:G,width:k.name.length*u*.6+12,height:M},"start",{color:e.textColor??"#cbd5e1"},`legend-${X}`)}}function op(e){for(let t of e.animation?.tracks??[])for(let r of t.keyframes??[])r.frame=Math.round(r.frame);for(let t of e.children??[])op(t)}function tp(e){return{x:J(e.x),y:J(e.y),width:J(e.width),height:J(e.height)}}function rp(e){return e.replace(/-?\d*\.\d{3,}(?:e-?\d+)?/gi,t=>String(J(Number(t))))}function h0(e,t,r){let n=[],i=/([MLAZ])([^MLAZ]*)/gi;for(let[,o,a]of e.matchAll(i)){let u=(a.match(/-?\d*\.?\d+(?:e-?\d+)?/gi)??[]).map(Number);if(o.toUpperCase()==="A")for(let l=0;l+6<u.length;l+=7)u[l+5]+=t,u[l+6]+=r;else if(o.toUpperCase()!=="Z")for(let l=0;l+1<u.length;l+=2)u[l]+=t,u[l+1]+=r;n.push(o+u.map(J).join(","))}return n.join("")}h();h();var ap={mixamo:{spine:"Spine",neck:"Neck",leftUpperArm:"LeftArm",leftLowerArm:"LeftForeArm",rightUpperArm:"RightArm",rightLowerArm:"RightForeArm",leftUpperLeg:"LeftUpLeg",leftLowerLeg:"LeftLeg",rightUpperLeg:"RightUpLeg",rightLowerLeg:"RightLeg"},humanoid:{spine:"Spine",neck:"Neck",leftUpperArm:"LeftUpperArm",leftLowerArm:"LeftLowerArm",rightUpperArm:"RightUpperArm",rightLowerArm:"RightLowerArm",leftUpperLeg:"LeftUpperLeg",leftLowerLeg:"LeftLowerLeg",rightUpperLeg:"RightUpperLeg",rightLowerLeg:"RightLowerLeg"},rigify:{spine:"spine",neck:"neck",leftUpperArm:"upper_arm.L",leftLowerArm:"forearm.L",rightUpperArm:"upper_arm.R",rightLowerArm:"forearm.R",leftUpperLeg:"thigh.L",leftLowerLeg:"shin.L",rightUpperLeg:"thigh.R",rightLowerLeg:"shin.R"}},g0=[["spine",["leftHip","rightHip"],["leftShoulder","rightShoulder"]],["neck",["leftShoulder","rightShoulder"],"nose"],["leftUpperArm","leftShoulder","leftElbow"],["leftLowerArm","leftElbow","leftWrist"],["rightUpperArm","rightShoulder","rightElbow"],["rightLowerArm","rightElbow","rightWrist"],["leftUpperLeg","leftHip","leftKnee"],["leftLowerLeg","leftKnee","leftAnkle"],["rightUpperLeg","rightHip","rightKnee"],["rightLowerLeg","rightKnee","rightAnkle"]],b0=e=>e.startsWith("left")?`right${e.slice(4)}`:e.startsWith("right")?`left${e.slice(5)}`:e;function Gi(e,t,r,n){let i=u=>n?b0(u):u;if(typeof t=="string")return e.point(i(t),r);let o=e.point(i(t[0]),r),a=e.point(i(t[1]),r);return{x:(o.x+a.x)/2,y:(o.y+a.y)/2,visibility:Math.min(o.visibility,a.visibility)}}var y0=(e,t,r)=>{let n=Math.min(1,Math.max(0,(r-e)/(t-e)));return n*n*(3-2*n)};function _s(e,t={}){let r=typeof t.rig=="object"?t.rig:ap[t.rig??"mixamo"],n=t.bones?new Set(t.bones):void 0,i=t.mirror??!1,o=t.minVisibility??.3;return g0.filter(([a])=>r[a]&&(!n||n.has(a))).map(([a,u,l])=>({joint:r[a],direction:c=>{let m=Gi(e,u,c,i),d=Gi(e,l,c,i);return[d.x-m.x,d.y-m.y,0]},weight:{get:c=>{let m=c,d=Gi(e,u,m.frame,i),p=Gi(e,l,m.frame,i);return y0(o,o+.2,Math.min(d.visibility,p.visibility))*nl(t.weight,m,1)}}}))}var sp=24,x0=1,S0=1,w0=1,v0="vitmatte-s",k0="depth-anything-v2-s",P0=48,up,T0=0;function M0(){return up??=import("./src-RCNEKIRP.mjs"),up}var kn=class{source;fps;compositionFps;startFrame;trimStartSec;smoothing;options;results=new Map;sourceWidth=0;sourceHeight=0;cellW=0;cellH=0;cell;queue=Promise.resolve();runner;sam2Tracker;sam2Frame=-1;sam3Tracker;sam3Frame=-1;sam;decoderId=`clip-vision#${++T0}#`;signalBundle;publishedSignals=new Set;signalMaskFrame=-1;signalMasks=new Map;trackCounts=new Map;cacheLoaded;unsaved=0;unsavedSubjects=0;blurred=new Map;smoothed=new Map;personView;subjects=new Map;wantSubjects=!1;subjectsLoaded;mattes=new Map;mattesLoaded;unsavedMattes=0;depths=new Map;depthsOnDisk=new Set;depthDir;depthDisk;constructor(t,r,n={}){if(this.source=t,n.sam2&&n.sam3)throw new Error("Choose one prompted backend: sam2 or sam3.");this.options=n.sam2?{...n,sam2:{...n.sam2,prompts:n.sam2.prompts.map(i=>({...i,points:i.points.map(o=>({...o}))}))}}:n.sam3?{...n,sam3:{...n.sam3,prompts:(n.sam3.prompts??(n.sam3.text?[{frame:0,text:n.sam3.text}]:[])).map(i=>({...i,...i.points?{points:i.points.map(o=>({...o}))}:{}}))}}:n,this.compositionFps=r,this.fps=n.fps??r,this.startFrame=Math.round(n.startFrame??0),this.trimStartSec=n.trimStartSec??0,this.smoothing=Math.max(0,Math.round(n.smoothing??(n.sam2||n.sam3?0:2))),this.cell=Math.max(1,Math.round(n.maskCell??8)),(n.sam2||n.sam3||this.tracksMatting)&&(this.wantSubjects=!0)}get exact(){return this.options.sam2!==void 0||this.options.sam3!==void 0}get signals(){return this.keepSubjects(),this.signalBundle??=new Vr({fps:this.compositionFps,totalFrames:Number.MAX_SAFE_INTEGER,maskSource:t=>this.trackIds(t).flatMap(r=>{let n=this.maskAt(t,r);return n&&n.area>0?[n]:[]}),matteSource:t=>{let r=this.maskAt(t);return r?{mask:r.mask,width:r.width,height:r.height,coverage:r.coverage}:void 0}}),this.signalBundle}decoder(){return _r.getVideo(this.source,!0,this.decoderId)}release(){_r.clearNode(this.decoderId),this.sam2Tracker?.release(),this.sam2Tracker=void 0,this.sam2Frame=-1,this.sam3Tracker?.release(),this.sam3Tracker=void 0,this.sam3Frame=-1,this.runner?.close(),this.runner=void 0,this.signalMaskFrame=-1,this.signalMasks.clear(),this.publishedSignals.clear()}get person(){return this.personView??=new Yi(this),this.personView}ready(t,r=t){let[n,i]=this.window(t,r),o=this.queue.then(async()=>{try{await this.compute(n,i)}catch(a){throw this.release(),a}this.signalBundle&&this.publishSignals(Math.min(t,r),Math.max(t,r))});return this.queue=o.catch(()=>{}),o}isReady(t){let[r,n]=this.window(t,t);for(let i=r;i<=n;i++)if(!this.analysed(i))return!1;return!0}keepSubjects(){this.wantSubjects=!0}subject(t,r){let n=this.sourceFrame(t,r);if(n===void 0)return;let i=this.subjects.get(n);if(i===void 0)return i;if(i===null||!this.sourceWidth)return null;let o=this.sourceWidth,a=this.sourceHeight,u=this.alpha(n,i);if(u)return{category:i.category,mask:u,width:o,height:a,area:i.area,coverage:i.area/(o*a),detectionIndex:-1}}pose(t,r){let n=this.sourceFrame(t,r);if(n===void 0||!this.tracksPose||!this.sourceWidth)return;for(let a=n-this.smoothing;a<=n+this.smoothing;a++)if(!this.results.has(Math.max(0,a)))return;if(!this.results.get(n)?.kp)return null;let i=this.sourceWidth,o=this.sourceHeight;return{width:i,height:o,keypoints:Array.from({length:17},(a,u)=>{let[l,c,m]=this.keypoint(u,n);return{x:l/i,y:c/o,visibility:m}})}}get tracksPose(){return this.exact?this.options.pose===!0:this.options.pose??!this.tracksDepth}get tracksMask(){return this.options.mask??!this.tracksDepth}get tracksMatting(){return this.options.matting!==void 0&&this.options.matting!==!1}get matteSettings(){let t=this.options.matting;if(!t)return;let r=t===!0?{}:t;return{band:r.band??(this.sourceWidth?ol(this.sourceWidth,this.sourceHeight):0),resolution:r.resolution??1024}}alpha(t,r,n){let i=this.sourceWidth*this.sourceHeight;if(!this.tracksMatting)return O0(r,i,n);let o=this.mattes.get(t);if(!o)return;let a=Hi(o.alpha,i);if(n===void 0||!o.labels)return a;let u=Hi(o.labels,i);for(let l=0;l<i;l++)u[l]!==n&&(a[l]=0);return a}get tracksDepth(){return this.options.depth===!0}depthMap(t){return this.depth(t,this.compositionFps)??void 0}depth(t,r){let n=this.sourceFrame(t,r);if(n===void 0||!this.tracksDepth)return;let i=this.storedDepth(n);if(!i)return i;let o=new Float32Array(i.data.length);for(let a=0;a<o.length;a++)o[a]=i.data[a]/65535;return{data:o,width:i.width,height:i.height}}sourceFrame(t,r){let n=t*this.fps/r;if(!(!this.exact&&!this.options.timeRemap&&Math.abs(n-Math.round(n))>1e-6))return this.options.timeRemap||this.exact?Math.floor(n+1e-6):Math.round(n)}clipFrame(t){return this.options.timeRemap?Fu(this.options.timeRemap,this.localFrame(t),this.compositionFps)*this.fps:((t-this.startFrame)/this.compositionFps+this.trimStartSec)*this.fps}localFrame(t){let r=Math.max(0,t-this.startFrame);return this.options.durationFrames===void 0?r:Math.min(r,Math.max(0,this.options.durationFrames-1))}window(t,r){let n=this.options.timeRemap?Lu(this.options.timeRemap,this.localFrame(Math.min(t,r)),this.localFrame(Math.max(t,r)),this.compositionFps):void 0,i=Math.floor(n?n.min*this.fps:this.clipFrame(Math.min(t,r))),o=Math.ceil(n?n.max*this.fps:this.clipFrame(Math.max(t,r)));return[Math.max(0,i-sp-this.smoothing),Math.max(0,o+this.smoothing)]}analysed(t){return this.analysedSubject(t)&&(!this.tracksDepth||this.hasDepth(t))&&(!this.tracksMatting||this.mattes.has(t))}analysedSubject(t){return this.results.has(t)&&(!this.wantSubjects||this.subjects.has(t))}prompted(){return this.sam??=M0().then(t=>(this.options.sam2&&t.validateSam2Prompts(this.options.sam2.prompts),this.options.sam3&&t.validateSam3Prompts(this.options.sam3),t)),this.sam}async compute(t,r){this.exact&&await this.prompted(),this.cacheLoaded??=this.loadCache(),await this.cacheLoaded,this.wantSubjects&&(this.subjectsLoaded??=this.loadSubjects(),await this.subjectsLoaded),this.tracksDepth&&await this.computeDepth(t,r),await this.computeSubjects(t,r),this.tracksMatting&&await this.computeMattes(t,r)}async computeSubjects(t,r){let n=!1;for(let l=t;l<=r;l++)this.analysedSubject(l)||(n=!0);if(!n)return;if(this.options.sam2){await this.computeSam2(r);return}if(this.options.sam3){await this.computeSam3(r);return}let i=this.tracksPose,o=this.tracksMask,a=this.visionRunner(),u=this.decoder();for(let l=t;l<=r;l++){if(this.analysedSubject(l))continue;let c=await vn(await u.getFrame(l/this.fps));if(!c){this.results.set(l,{kp:null,mask:null}),this.wantSubjects&&this.subjects.set(l,null);continue}this.sourceWidth||this.setSize(c.width,c.height);let m=this.results.get(l),d=m?.kp??null,p=m?.mask??null;if(i&&!m){let b=(await a.pose(c)).people[0];if(b){d=new Float32Array(51);for(let[g,y]of b.keypoints.entries())d.set([y.x,y.y,y.visibility],g*3)}}let f=o&&!m||this.wantSubjects?await a.segment(c):void 0;if(f&&this.wantSubjects){let b=Fo(f.masks);this.subjects.set(l,b?{category:b.category,area:b.area,...Wi(b.mask)}:null),this.unsavedSubjects++}if(f&&o&&!m){let b=C0(f);b&&(p=new Uint8Array(this.cellW*this.cellH),lp(b,c.width,c.height,this.cell,p,this.cellW,this.cellH))}this.results.set(l,{kp:d,mask:p}),m||this.unsaved++,this.unsaved>=24&&await this.saveCache(),this.unsavedSubjects>=24&&await this.saveSubjects()}this.unsaved>0&&await this.saveCache(),this.unsavedSubjects>0&&await this.saveSubjects()}visionRunner(){return this.runner??=sr.create({modelsDir:this.options.modelsDir,baseUrl:this.options.baseUrl,...this.options.confidence!==void 0&&{confidence:this.options.confidence},...this.options.variant!==void 0&&{variant:this.options.variant}}),this.runner}async computeMattes(t,r){if(!this.sourceWidth)return;this.mattesLoaded??=this.loadMattes(),await this.mattesLoaded;let n;for(let i=t;i<=r;i++){if(this.mattes.has(i))continue;let o=this.subjects.get(i);if(o===void 0)continue;if(o===null){this.mattes.set(i,null);continue}n??=this.decoder();let a=await vn(await n.getFrame(i/this.fps));if(!a){this.mattes.set(i,null);continue}let u=a.width*a.height,l=Hi(o,u),c=o.scores?l.map(p=>p?255:0):l,m=await this.visionRunner().refineMatte(a,c,this.matteSettings),d;if(o.scores){d=new Uint8Array(u);for(let p=0;p<u;p++){let f=m.nearest[p];m.mask[p]&&f>=0&&(d[p]=l[f])}}this.mattes.set(i,{alpha:Wi(m.mask),...d&&{labels:Wi(d)}}),this.signalMaskFrame=-1,++this.unsavedMattes>=24&&await this.saveMattes()}this.unsavedMattes>0&&await this.saveMattes()}async computeDepth(t,r){let n=await this.depthCacheDir(),i;for(let o=t;o<=r;o++){if(this.hasDepth(o))continue;i??=this.decoder();let a=await vn(await i.getFrame(o/this.fps));if(!a){this.depths.set(o,null);continue}this.sourceWidth||this.setSize(a.width,a.height);let u=await this.visionRunner().depth(a),l={width:u.width,height:u.height,data:Uint16Array.from(u.data,c=>Math.round(c*65535))};this.keepDepth(o,l),n&&await this.saveDepth(n,o,l)}}hasDepth(t){return this.depths.has(t)||this.depthsOnDisk.has(t)}keepDepth(t,r){if(this.depths.delete(t),this.depths.set(t,r),this.depthsOnDisk.size!==0)for(let n of this.depths.keys()){if(this.depths.size<=P0)break;this.depthsOnDisk.has(n)&&this.depths.delete(n)}}storedDepth(t){let r=this.depths.get(t);if(r!==void 0||!this.depthsOnDisk.has(t))return r;let n=this.depthDisk;if(!n)return;let i=F0(n.fs,n.path.join(n.dir,`${t}.bin`));return i&&this.keepDepth(t,i),i??void 0}depthCacheDir(){return this.depthDir??=(async()=>{let t=await Us();if(!t||this.options.cacheDir===!1)return null;let{fs:r,path:n,os:i,crypto:o}=t;try{let a=r.statSync(this.source),u=this.options.cacheDir??S.env.FRAMEFIELDS_VISION_CACHE_DIR??n.join(i.homedir(),".cache","framefields","vision"),l=JSON.stringify([S0,n.resolve(this.source),a.size,a.mtimeMs,this.fps,k0]),c=o.createHash("sha256").update(l).digest("hex").slice(0,24),m=n.join(u,`${n.basename(this.source)}.${c}.depth`);r.mkdirSync(m,{recursive:!0});for(let d of r.readdirSync(m)){let p=/^(\d+)\.bin$/.exec(d);p&&this.depthsOnDisk.add(Number(p[1]))}return this.depthDisk={dir:m,fs:r,path:n},m}catch{return null}})(),this.depthDir}async saveDepth(t,r,n){let i=await Us();if(!i)return;let o=new Uint32Array([n.width,n.height]),a=i.path.join(t,`${r}.bin`),u=`${a}.${S.pid}.tmp`;i.fs.writeFileSync(u,Buffer.concat([Buffer.from(o.buffer),Buffer.from(n.data.buffer,n.data.byteOffset,n.data.byteLength)])),i.fs.renameSync(u,a),this.depthsOnDisk.add(r),this.keepDepth(r,n)}async computeSam2(t){let r=this.options.sam2;if(!r)return;let n=r.prompts[0]?.frame??0;for(let o=0;o<Math.min(n,t+1);o++)this.results.set(o,{kp:null,mask:null,score:0}),this.subjects.set(o,null);if(t<n)return;let i=this.decoder();if(!this.sam2Tracker){let o=Math.max(1,Math.ceil(await i.durationSec()*this.fps-1e-6));if(r.prompts.some(u=>u.frame>=o))throw new Error("SAM 2 prompt frames must be inside the source video.");let{Sam2Tracker:a}=await this.prompted();this.sam2Tracker=await a.create({modelsDir:this.options.modelsDir,baseUrl:this.options.baseUrl,frameCount:o,model:r.model}),this.sam2Frame=n-1}for(let o=this.sam2Frame+1;o<=t;o++){let a=await vn(await i.getFrame(o/this.fps));if(!a)throw new Error(`Cannot decode SAM 2 source frame ${o}.`);this.sourceWidth||this.setSize(a.width,a.height);let u=r.prompts.find(m=>m.frame===o),l=await this.sam2Tracker.process(a,o,u?.points),c=this.tracksPose?await this.matchedPose(a,l.mask):null;this.storeSamFrame(o,l.width,l.height,[l],c),this.unsaved>=24&&(await this.saveCache(),await this.saveSubjects())}await this.saveCache(),await this.saveSubjects()}async computeSam3(t){let r=this.options.sam3;if(!r)return;let n=r.prompts[0]?.frame??0;for(let o=0;o<Math.min(n,t+1);o++)this.results.set(o,{kp:null,mask:null,score:0}),this.subjects.set(o,null);if(t<n)return;let i=this.decoder();if(!this.sam3Tracker){let o=Math.max(1,Math.ceil(await i.durationSec()*this.fps-1e-6));if(r.prompts.some(u=>u.frame>=o))throw new Error("SAM 3 prompt frames must be inside the source video.");let{Sam3Tracker:a}=await this.prompted();this.sam3Tracker=await a.create({modelsDir:this.options.modelsDir,baseUrl:this.options.baseUrl,frameCount:o,textThreshold:r.textThreshold,maxObjects:r.maxObjects,merge:r.merge,redetect:r.redetect,precision:r.precision,acceptLicense:this.options.acceptSamLicense??this.options.sam3?.acceptLicense}),this.sam3Frame=n-1}for(let o=this.sam3Frame+1;o<=t;o++){let a=await vn(await i.getFrame(o/this.fps));if(!a)throw new Error(`Cannot decode SAM 3 source frame ${o}.`);this.sourceWidth||this.setSize(a.width,a.height);let u=r.prompts.find(m=>m.frame===o),l=await this.sam3Tracker.process(a,o,u),c=this.tracksPose?await this.matchedPose(a,N0(l.objects,a)):null;this.storeSamFrame(o,l.width,l.height,l.objects,c),this.unsaved>=24&&(await this.saveCache(),await this.saveSubjects())}await this.saveCache(),await this.saveSubjects()}storeSamFrame(t,r,n,i,o){let a=new Uint8Array(r*n),u=[...i.keys()].sort((p,f)=>(i[p]?.score??0)-(i[f]?.score??0));for(let p of u){let f=i[p]?.mask;if(f)for(let b=0;b<f.length;b++)(f[b]??0)>=128&&(a[b]=p+1)}let l=Uint8Array.from(a,p=>p?255:0),c=new Uint8Array(this.cellW*this.cellH);lp(l,r,n,this.cell,c,this.cellW,this.cellH);let m=0;for(let p of a)p&&m++;let d=i.map(p=>1/(1+Math.exp(-p.score)));this.results.set(t,{kp:o,mask:c,score:Math.max(0,...d)}),this.subjects.set(t,m>0?{category:this.samCategory(),area:m,scores:d,...Wi(a)}:null),this.trackCounts.set(t,i.length),this.blurred.delete(t),this.options.sam3?this.sam3Frame=t:this.sam2Frame=t,this.unsaved++,this.unsavedSubjects++}samCategory(){return this.options.sam2?.category??this.options.sam3?.category??"object"}async matchedPose(t,r){this.runner??=sr.create({modelsDir:this.options.modelsDir,baseUrl:this.options.baseUrl,variant:this.options.variant});let{people:n}=await this.runner.pose(t),o=n.map(a=>({person:a,overlap:a.keypoints.reduce((u,l)=>{let c=Math.max(0,Math.min(t.width-1,Math.round(l.x))),m=Math.max(0,Math.min(t.height-1,Math.round(l.y)));return u+(r[m*t.width+c]??0)/255*l.visibility},0)})).sort((a,u)=>u.overlap-a.overlap)[0];return!o||o.overlap<2?null:Float32Array.from(o.person.keypoints.flatMap(a=>[a.x,a.y,a.visibility]))}trackIds(t){let r=Math.max(0,Math.floor(this.clipFrame(t))),n=this.subjects.get(r)?.scores?.length??this.trackCounts.get(r)??1;return Array.from({length:n},(i,o)=>o+1)}maskAt(t,r){let n=Math.max(0,Math.floor(this.clipFrame(t)));this.signalMaskFrame!==n&&(this.signalMaskFrame=n,this.signalMasks.clear());let i=this.signalMasks.get(r??0);if(i)return i;if(!this.results.has(n)||!this.sourceWidth)return;let o=this.subjects.get(n),a=this.sourceWidth*this.sourceHeight,u=o?this.alpha(n,o,r):new Uint8Array(a);if(!u)return;let l=u,c=o?.area??0;if(r!==void 0&&o?.scores){c=0;for(let d of l)d&&c++}let m={category:o?.category??this.samCategory(),mask:l,width:this.sourceWidth,height:this.sourceHeight,area:c,coverage:c/a,detectionIndex:(r??1)-1,trackId:r??1};return this.signalMasks.set(r??0,m),m}publishSignals(t,r){let n=this.signalBundle;if(!(!n||!this.sourceWidth)){n.setFrameSize(this.sourceWidth,this.sourceHeight);for(let i=t;i<=r;i++){if(this.publishedSignals.has(i))continue;this.publishedSignals.add(i);let o=Math.max(0,Math.floor(this.clipFrame(i))),a=this.maskAt(i);if(!a)continue;let u=n.getObjectResult(i-1).objects,l=this.subjects.get(o)?.scores,c=this.trackIds(i).flatMap(p=>{let f=this.maskAt(i,p);return f?[Lo(f,i,this.compositionFps,l?.[p-1]??this.results.get(o)?.score??1,u.find(b=>b.trackId===p))]:[]});n.setObjectResult(i,c);let m=c[0]??Lo(a,i,this.compositionFps,0),d=this.results.get(o)?.kp;n.setPoseResult(i,{people:d?[{score:m.score,boundingBox:m.boundingBox,trackId:1,keypoints:Array.from({length:17},(p,f)=>({x:(d[f*3]??0)/a.width,y:(d[f*3+1]??0)/a.height,visibility:d[f*3+2]??0}))}]:[]})}}}setSize(t,r){this.sourceWidth=t,this.sourceHeight=r,this.cellW=Math.ceil(t/this.cell),this.cellH=Math.ceil(r/this.cell)}size(){return{width:this.sourceWidth,height:this.sourceHeight}}result(t){return this.results.get(Math.max(0,t))}keypoint(t,r){r=Math.max(0,r);let n=`${t}:${r}`,i=this.smoothed.get(n);if(i)return i;let o=u=>{let l=0,c=0,m=0,d=0;for(let p=u-this.smoothing;p<=u+this.smoothing;p++){let f=this.mustHave(p<0?0:p);if(!f.kp)continue;let b=f.kp[t*3+2],g=(this.smoothing+1-Math.abs(p-u))*b*b;l+=f.kp[t*3]*g,c+=f.kp[t*3+1]*g,m+=b*g,d+=g}return d>1e-6?[l/d,c/d,m/d]:null},a=null;for(let u=0;u<=sp&&!a;u++)r-u>=0&&(a=o(r-u));return a??=[this.sourceWidth/2,this.sourceHeight/2,0],this.smoothed.set(n,a),a}blurredMask(t){if(t=Math.max(0,t),this.blurred.has(t))return this.blurred.get(t)??null;this.mustHave(t);let r=this.exact?this.results.get(t)?.mask??null:D0(this.results,t,this.smoothing),n=r?R0(r,this.cellW,this.cellH,2):null;return this.blurred.set(t,n),n}grid(){return{cell:this.cell,width:this.cellW,height:this.cellH}}mustHave(t){let r=this.results.get(t);if(r)return r;throw new Error(`ClipVision "${this.source}": frame ${t} is not analysed yet. Read it while rendering (the composition prepares each frame), in a live physics world, or after \`await clip.ready(frame)\`.`)}cacheFile;async cachePath(){if(this.cacheFile!==void 0)return this.cacheFile;if(this.cacheFile=null,this.options.cacheDir===!1||typeof S>"u"||!S.versions?.node)return null;try{let[t,r,n,i]=await Promise.all([import("./shims/fs.mjs"),import("./shims/path.mjs"),import("./shims/os.mjs"),import("./crypto-TRDUAUC5.mjs")]),o=t.statSync(this.source),a=this.options.cacheDir??S.env.FRAMEFIELDS_VISION_CACHE_DIR??r.join(n.homedir(),".cache","framefields","vision"),u=this.options,l=this.exact?await this.prompted():void 0,c=JSON.stringify([x0,r.resolve(this.source),o.size,o.mtimeMs,this.fps,this.tracksPose,this.tracksMask,this.cell,u.variant??"s",u.confidence??null,...u.sam2?[[l?.sam2Revision(u.sam2.model),u.sam2,3]]:[],...u.sam3&&l?[[l.sam3Revision(await l.sam3Precision(void 0,u.sam3.precision)),u.sam3,3]]:[]]),m=i.createHash("sha256").update(c).digest("hex").slice(0,24);t.mkdirSync(a,{recursive:!0}),this.cacheFile=r.join(a,`${r.basename(this.source)}.${m}.json`)}catch{this.cacheFile=null}return this.cacheFile}async loadCache(){let t=await this.cachePath();if(t)try{let r=await import("./shims/fs.mjs");if(!r.existsSync(t))return;let n=JSON.parse(r.readFileSync(t,"utf8"));if(n.cell!==this.cell)return;this.setSize(n.width,n.height);for(let[i,o]of Object.entries(n.frames))this.results.set(Number(i),{kp:o.kp?Float32Array.from(o.kp):null,score:o.score,mask:o.mask?new Uint8Array(Buffer.from(o.mask,"base64")):null})}catch{}}async saveCache(){this.unsaved=0;let t=await this.cachePath();if(!t||!this.sourceWidth)return;let r={};for(let[o,a]of this.results)r[o]={kp:a.kp?Array.from(a.kp,u=>Math.round(u*100)/100):null,mask:a.mask?Buffer.from(a.mask).toString("base64"):null,score:a.score};let n=await import("./shims/fs.mjs"),i=`${t}.${S.pid}.tmp`;n.writeFileSync(i,JSON.stringify({width:this.sourceWidth,height:this.sourceHeight,cell:this.cell,frames:r})),n.renameSync(i,t)}async subjectsPath(){let t=await this.cachePath();return t?t.replace(/\.json$/,".subjects.json"):null}async loadSubjects(){let t=await this.subjectsPath();if(t)try{let r=await import("./shims/fs.mjs");if(!r.existsSync(t))return;let n=JSON.parse(r.readFileSync(t,"utf8"));if(this.sourceWidth&&n.width!==this.sourceWidth)return;this.sourceWidth||this.setSize(n.width,n.height);for(let[i,o]of Object.entries(n.frames)){let a=Buffer.from(o?.lengths??"","base64");this.subjects.set(Number(i),o&&{category:o.category,area:o.area,...o.scores&&{scores:o.scores},values:new Uint8Array(Buffer.from(o.values,"base64")),lengths:new Uint32Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))})}}catch{}}async mattesPath(){let t=await this.cachePath(),r=await Us(),n=this.matteSettings;if(!t||!r||!n)return null;let i=r.crypto.createHash("sha256").update(JSON.stringify([w0,v0,n.band,n.resolution])).digest("hex").slice(0,12);return t.replace(/\.json$/,`.matte-${i}.json`)}async loadMattes(){let t=await this.mattesPath();if(t)try{let r=await import("./shims/fs.mjs");if(!r.existsSync(t))return;let n=JSON.parse(r.readFileSync(t,"utf8"));if(n.width!==this.sourceWidth||n.height!==this.sourceHeight)return;for(let[i,o]of Object.entries(n.frames))this.mattes.set(Number(i),o&&{alpha:mp(o.alpha),...o.labels&&{labels:mp(o.labels)}})}catch{}}async saveMattes(){this.unsavedMattes=0;let t=await this.mattesPath();if(!t||!this.sourceWidth)return;let r={};for(let[o,a]of this.mattes)r[o]=a&&{alpha:cp(a.alpha),...a.labels&&{labels:cp(a.labels)}};let n=await import("./shims/fs.mjs"),i=`${t}.${S.pid}.tmp`;n.writeFileSync(i,JSON.stringify({width:this.sourceWidth,height:this.sourceHeight,frames:r})),n.renameSync(i,t)}async saveSubjects(){this.unsavedSubjects=0;let t=await this.subjectsPath();if(!t||!this.sourceWidth)return;let r={};for(let[o,a]of this.subjects)r[o]=a&&{category:a.category,area:a.area,...a.scores&&{scores:a.scores},values:Buffer.from(a.values).toString("base64"),lengths:Buffer.from(a.lengths.buffer,a.lengths.byteOffset,a.lengths.byteLength).toString("base64")};let n=await import("./shims/fs.mjs"),i=`${t}.${S.pid}.tmp`;n.writeFileSync(i,JSON.stringify({width:this.sourceWidth,height:this.sourceHeight,frames:r})),n.renameSync(i,t)}},Yi=class e{constructor(t,r,n){this.clip=t;this.t=r;this.placement=n}clip;t;placement;place(t){return new e(this.clip,void 0,t)}transform(){if(this.t)return this.t;let t=this.placement,{width:r,height:n}=this.clip.size();if(!t||!r)return{sx:1,sy:1,ox:0,oy:0};let i=t.width/r,o=t.height/n;if(t.fit!=="fill"){let a=t.fit==="contain"?Math.min(i,o):Math.max(i,o);i=a,o=a}return{sx:i,sy:o,ox:(t.x??0)+(t.width-r*i)/2,oy:(t.y??0)+(t.height-n*o)/2}}point(t,r){let n=A0(t),i=this.clip.clipFrame(r),o=Math.floor(i),a=i-o,u=this.clip.keypoint(n,o),l=a>0?this.clip.keypoint(n,o+1):u,c=this.transform();return{x:(u[0]+(l[0]-u[0])*a)*c.sx+c.ox,y:(u[1]+(l[1]-u[1])*a)*c.sy+c.oy,visibility:u[2]+(l[2]-u[2])*a}}retarget(t){return _s(this,t)}signals(t){let r=n=>jr.builder({type:"custom",fn:i=>this.point(t,i.frame)[n]});return{x:r("x"),y:r("y"),visibility:r("visibility")}}silhouetteGrid(t){let r=this.clip.blurredMask(Math.round(this.clip.clipFrame(t)));if(!r)return null;let{cell:n,width:i,height:o}=this.clip.grid(),a=this.transform();return{data:r,width:i,height:o,originX:a.ox,originY:a.oy,scaleX:n*a.sx,scaleY:n*a.sy}}sample(t,r,n){let i=this.clip.blurredMask(Math.round(this.clip.clipFrame(t)));if(!i)return{alpha:0,gx:0,gy:0};let{cell:o,width:a,height:u}=this.clip.grid(),l=this.transform(),c=(r-l.ox)/l.sx/o-.5,m=(n-l.oy)/l.sy/o-.5,d=(f,b)=>f<0||b<0||f>=a||b>=u?0:i[b*a+f],p=(f,b)=>{let g=Math.floor(f),y=Math.floor(b),T=f-g,M=b-y,v=d(g,y)+(d(g+1,y)-d(g,y))*T,x=d(g,y+1)+(d(g+1,y+1)-d(g,y+1))*T;return v+(x-v)*M};return{alpha:p(c,m),gx:(p(c+1,m)-p(c-1,m))/(2*o*l.sx),gy:(p(c,m+1)-p(c,m-1))/(2*o*l.sy)}}};function A0(e){let t=Zn.indexOf(e);if(t<0)throw new Error(`Unknown keypoint "${e}". Use one of ${Zn.join(", ")}.`);return t}async function vn(e){if(!e||e.width<=0)return null;if(e.buffer)return{data:e.buffer,width:e.width,height:e.height};let r=e.canvas?.getContext("2d");return r?{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}:null}function C0(e){return Fo(e.masks,{classes:["person"],overlap:.2,maxGrowth:3.5})?.mask}function Vs(e){if(!e)return 0;let t=0;for(let r=0;r<e.length;r++)t+=e[r];return t}function D0(e,t,r){let n=e.get(t)?.mask??null;if(r<=0)return n;let i=Vs(n),o=-1,a=null,u=-1,l=null,c=Math.max(1e3,i*1.35);for(let p=1;p<=r+1;p++){if(o<0&&t-p>=0){let f=e.get(t-p)?.mask??null;Vs(f)>c&&(o=t-p,a=f)}if(u<0){let f=e.get(t+p)?.mask??null;Vs(f)>c&&(u=t+p,l=f)}}if(!a&&!l)return n;let m=a??l;if(!m)return n;let d=n?new Uint8Array(n):new Uint8Array(m.length);if(a&&l&&u>o){let p=(t-o)/(u-o);for(let f=0;f<d.length;f++){let b=Math.round(a[f]+(l[f]-a[f])*p);b>d[f]&&(d[f]=b)}}else for(let p=0;p<d.length;p++)m[p]>d[p]&&(d[p]=m[p]);return d}function lp(e,t,r,n,i,o,a){for(let u=0;u<a;u++)for(let l=0;l<o;l++){let c=0,m=0;for(let d=u*n;d<Math.min(r,(u+1)*n);d++)for(let p=l*n;p<Math.min(t,(l+1)*n);p++)c+=e[d*t+p],m++;i[u*o+l]=m?Math.round(c/m):0}}function cp(e){return{values:Buffer.from(e.values).toString("base64"),lengths:Buffer.from(e.lengths.buffer,e.lengths.byteOffset,e.lengths.byteLength).toString("base64")}}function mp(e){let t=Buffer.from(e.lengths,"base64");return{values:new Uint8Array(Buffer.from(e.values,"base64")),lengths:new Uint32Array(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))}}function Wi(e){let t=0;for(let a=1;a<=e.length;a++)(a===e.length||e[a]!==e[a-1])&&t++;let r=new Uint8Array(t),n=new Uint32Array(t),i=0,o=0;for(let a=1;a<=e.length;a++)(a===e.length||e[a]!==e[o])&&(r[i]=e[o],n[i++]=a-o,o=a);return{values:r,lengths:n}}function Hi(e,t){let r=new Uint8Array(t),n=0;for(let i=0;i<e.values.length;i++){let o=Math.min(t,n+e.lengths[i]);e.values[i]!==0&&r.fill(e.values[i],n,o),n=o}return r}function R0(e,t,r,n){let i=new Float32Array(t*r),o=new Float32Array(t*r);for(let a=0;a<r;a++)for(let u=0;u<t;u++){let l=0,c=0;for(let m=-n;m<=n;m++){let d=u+m;d>=0&&d<t&&(l+=e[a*t+d],c++)}i[a*t+u]=l/c/255}for(let a=0;a<r;a++)for(let u=0;u<t;u++){let l=0,c=0;for(let m=-n;m<=n;m++){let d=a+m;d>=0&&d<r&&(l+=i[d*t+u],c++)}o[a*t+u]=l/c}return o}function O0(e,t,r){let n=Hi(e,t);return e.scores?n.map(i=>(r===void 0?i>0:i===r)?255:0):n}function N0(e,t){let r=new Uint8Array(t.width*t.height);for(let{mask:n}of e)for(let i=0;i<r.length;i++)r[i]=Math.max(r[i]??0,n[i]??0);return r}var dp;function Us(){return dp??=typeof S>"u"||!S.versions?.node?Promise.resolve(null):Promise.all([import("./shims/fs.mjs"),import("./shims/path.mjs"),import("./shims/os.mjs"),import("./crypto-TRDUAUC5.mjs")]).then(([e,t,r,n])=>({fs:e,path:t,os:r,crypto:n})),dp}function F0(e,t){try{let r=e.readFileSync(t);if(r.byteLength<8)return null;let n=r.readUInt32LE(0),i=r.readUInt32LE(4);if(r.byteLength!==8+n*i*2)return null;let o=new Uint16Array(n*i);return Buffer.from(o.buffer).set(r.subarray(8)),{width:n,height:i,data:o}}catch{return null}}h();var Xi=class{constructor(t){this.fps=t}fps;entries=new Map;reached=-1;resolver(t){let{live:r,compositionDurationFrames:n}=t,i={fps:this.fps,compositionDurationFrames:n,signals:t.signals};return(o,a)=>{let u=`${a.id}\0${a.startFrame}\0${a.durationFrames}`,l=this.entries.get(u);if(l&&l.live===r&&l.compositionFrames===n&&L0(l.binding,o))return l.resolved;let c=r?{kind:"recorded",recorder:new Ru({mode:o.mode,fps:this.fps,startFrame:a.startFrame,durationFrames:a.durationFrames,sourceStartSec:o.sourceStartSec,sample:tl(o,i)})}:rl(o,a,i);return this.entries.set(u,{binding:o,live:r,compositionFrames:n,resolved:c}),c}}framesBefore(t){if(!this.recorders().some(i=>!i.complete&&i.nextFrame<t))return[];let n=[];for(let i=this.reached+1;i<t;i++)n.push(i);return n}advance(t){for(let r of this.recorders())r.advance(t)}reach(t){t>this.reached&&(this.reached=t);for(let[,r]of this.entries){if(r.resolved.kind!=="recorded")continue;let n=r.resolved.recorder;n.ensure(t),t>=r.compositionFrames-1&&!n.complete&&n.nextFrame>n.startFrame&&n.close()}}get pending(){return this.recorders().some(t=>!t.complete)}recorders(){let t=[];for(let{resolved:r}of this.entries.values())r.kind==="recorded"&&t.push(r.recorder);return t}};function L0(e,t){return e.signal===t.signal&&e.mode===t.mode&&e.sourceStartSec===t.sourceStartSec}function $s(e,t){let r=e.fps>0?t/e.fps:0;return{...e,frame:t,time:r,progress:e.duration>0?Math.max(0,Math.min(1,r/e.duration)):0}}var pp=new WeakMap,E0=0;function Or(e){if(!e)return"";if(e.kind==="rate"||e.kind==="keyframes")return JSON.stringify(e);let t=e.kind==="sampled"?e.history:e.recorder,r=pp.get(t);return r===void 0&&(r=++E0,pp.set(t,r)),`${e.kind}:${r}`}h();h();var B0={rotation:.2,rotateX:.2,rotateY:.2,rotateZ:.2};function Ue(e,t,r){if(typeof e=="number")return e;if(typeof e=="function")return e(t);let n=t/r;return e.get({frame:t,fps:r,time:n,duration:0,durationMs:0,progress:0,deltaTime:1/r})}function er(e,t){let r=t-e;return r-=Math.round(r/360)*360,e+r}function I0(e,t){let r=e.length;if(r===0)return[];let n=new Uint8Array(r);n[0]=1,n[r-1]=1;let i=[[0,r-1]];for(;i.length>0;){let[a,u]=i.pop(),l=-1,c=t;for(let m=a+1;m<u;m++){let d=(m-a)/(u-a),p=e[a]+(e[u]-e[a])*d,f=Math.abs(e[m]-p);f>c&&(c=f,l=m)}l>=0&&(n[l]=1,i.push([a,l],[l,u]))}let o=[];for(let a=0;a<r;a++)n[a]&&o.push([a,j0(e[a]),"none"]);return o.length===2&&o[0][1]===o[1][1]&&o.pop(),o}function j0(e){return Math.round(e*1e4)/1e4}var Gs=class{constructor(t,r,n){this.length=t;this.fps=r;this.ensure=n}length;fps;ensure;channels=new Map;signals=new Map;channel(t){let r=this.channels.get(t);return r||(r=new Float32Array(this.length),this.channels.set(t,r)),r}signal(t){let r=this.signals.get(t);if(!r){let n=this.channel(t),i=this.fps;r=jr.builder({type:"custom",fn:o=>{this.ensure();let a=o.fps&&o.fps!==i?o.frame/o.fps*i:o.frame,u=Math.max(0,Math.min(n.length-1,Math.round(a)));return n[u]}}),this.signals.set(t,r)}return r}},Nr=class{constructor(t,r,n){this.sim=t;this.gravity=r;if(!(n.fps>0))throw new Error("Physics: `fps` must be > 0.");if(!(n.frames>=1)||!Number.isInteger(n.frames))throw new Error("Physics: `frames` must be a positive integer.");this.fps=n.fps,this.frames=n.frames,this.startFrame=Math.max(0,Math.round(n.startFrame??0)),this.pixelsPerMeter=n.pixelsPerMeter??100,this.substeps=Math.max(1,Math.round(n.substeps??4)),this.impactDecay=Math.max(.5,n.impactDecay??8),this.impactReference=n.impactReference??1500,this.worldRecording=this.newRecording()}sim;gravity;fps;frames;startFrame;pixelsPerMeter;substeps;impactDecay;impactReference;bodies=[];forces=[];impulses=[];fields=[];stepHooks=[];simulatedHooks=[];worldRecording;allCollisions=[];locked=!1;liveMode=!1;stepper;chain=Promise.resolve();get collisions(){return this.ensureSimulated(),this.allCollisions}get impact(){return this.worldRecording.signal("impact")}simulate(){if(this.liveMode)throw new Error("Physics: this world is live; it steps as frames render.");return this.ensureSimulated(),this}bakeKeyframes(t={}){if(this.locked)throw new Error("Physics: bakeKeyframes() must come before simulate(), live() or reading any body signal.");return this.bakeDefault=t,this.ensureSimulated(),this}live(t,r={}){if(this.locked)throw new Error("Physics: live() must come before simulate() or reading any body signal.");if(this.simulatedHooks.length)throw new Error("Physics: fracture() needs the whole run up front; use simulate() instead of live().");this.locked=!0,this.liveMode=!0;let n=async i=>{await t.prepareVision?.(i);for(let o of r.inputs??[])await o.ready(i)};this.prepareInputs=n;for(let i of this.bodies)this.bind(i);return t.onPrepareFrame(i=>this.advanceTo(i.frame)),this}advanceTo(t){return this.chain=this.chain.then(async()=>{let r=Math.min(this.frames-1,Math.round(t)-this.startFrame);this.stepper||(await this.prepareInputs?.(this.startFrame),this.stepper=this.begin());let n=this.stepper;for(;n.current<r;){let i=n.current+1;await this.prepareInputs?.(this.startFrame+i),this.stepFrame(n,i)}n.current===this.frames-1&&!n.freed&&(n.freed=!0,this.sim.free())}),this.chain}prepareInputs;bakeDefault;newRecording(){return new Gs(this.startFrame+this.frames,this.fps,()=>this.ensureSimulated())}assertOpen(){if(this.locked)throw new Error("Physics: the world has already started; add every body, joint and force before simulate(), live() or reading signals.")}addBody(t){return this.assertOpen(),this.bodies.push(t),t}addForce(t,r){this.assertOpen(),this.forces.push({body:t,accel:r})}addField(t,r){this.assertOpen(),this.fields.push({accel:t,...r&&{targets:new Set(r)}})}addImpulse(t,r,n){this.assertOpen(),this.impulses.push({body:t,frame:Math.round(r),dv:n})}ensureSimulated(){if(this.locked)return;this.locked=!0;let t=this.begin();for(let r=1;r<this.frames;r++)this.stepFrame(t,r);t.freed=!0,this.sim.free();for(let r of this.bodies)this.bind(r);for(let r of this.simulatedHooks)r()}begin(){let{startFrame:t}=this,r=this.bodies,n=new Map;for(let o of r)n.set(o.sim,o);for(let o of r)o.startFrame>0&&o.sim.setEnabled(!1);let i=new Map;for(let o of r){o.record(t,-1),o.recording.channel("impact");let a=o.kinematicTarget?.(t);a&&i.set(o,a)}this.worldRecording.channel("impact");for(let o of[...r.map(a=>a.recording),this.worldRecording])for(let a of o.channels.values())a.fill(a[t]);return{current:0,freed:!1,bySim:n,kinematicFrom:i,level:new Map(r.map(o=>[o,0]))}}stepFrame(t,r){let{fps:n,startFrame:i,substeps:o}=this,a=1/(n*o),u=this.bodies,l=i+r,c=this.gravity.length,m=new Map;for(let x of u)x.startFrame>0&&r===x.startFrame+1&&x.sim.setEnabled(!0),m.set(x,x.sim.velocity());let d=x=>x.type==="dynamic"&&r>x.startFrame,p=new Map;for(let x of u)p.set(x,this.gravity.map(A=>d(x)?A*x.gravityScale/n:0));for(let x of this.impulses){if(x.frame!==r)continue;let A=x.body;if(!d(A))continue;let w=A.sim.mass();A.sim.applyImpulse(x.dv.map(N=>N*w));let R=p.get(A);for(let N=0;N<c;N++)R[N]+=x.dv[N]}let f=this.forces.filter(x=>d(x.body)).map(x=>{let A=x.body,w=x.accel(l),R=p.get(A);for(let N=0;N<c;N++)R[N]+=w[N]/n;return{body:A,a:w}}),b=new Map;for(let x of u){let A=x.kinematicTarget?.(l);A&&b.set(x,A)}let g=new Set,y=[];for(let x=1;x<=o;x++){for(let{body:A,a:w}of f){let R=A.sim.mass();A.sim.applyImpulse(w.map(N=>N*R*a))}for(let A of this.fields)for(let w of u){if(!d(w)||A.targets&&!A.targets.has(w))continue;let R=A.accel(w,l);if(!R)continue;let N=w.sim.mass();w.sim.applyImpulse(R.map($=>$*N*a));let V=p.get(w);for(let $=0;$<c;$++)V[$]+=R[$]*a}for(let[A,w]of b){let R=t.kinematicFrom.get(A)??w,N=x/o;A.sim.setKinematicTarget(z0(R.position,w.position,N),this.lerpRotation(R.rotation,w.rotation,N))}this.sim.step(a);for(let[A,w]of this.sim.drainCollisionStarts()){let R=t.bySim.get(A),N=t.bySim.get(w);if(!R||!N)continue;let V=`${u.indexOf(R)}:${u.indexOf(N)}`;g.has(V)||(g.add(V),y.push([R,N]))}}t.kinematicFrom=b;for(let x of u)x.record(l,l-1);let T=new Map;if(y.length>0){let x=this.pixelsPerMeter,A=w=>{if(w.type!=="dynamic")return 0;let R=w.sim.velocity(),N=m.get(w),V=p.get(w),$=0;for(let I=0;I<c;I++){let E=R[I]-(N[I]+V[I]);$+=E*E}return Math.sqrt($)*x};for(let[w,R]of y){let N=Math.max(A(w),A(R));for(let[V,$]of[[w,R],[R,w]]){T.set(V,Math.max(T.get(V)??0,N));let I={frame:l,with:$,speed:N};V.collisions.push(I),V===w&&this.allCollisions.push({...I,body:w})}}}let M=Math.exp(-1/this.impactDecay),v=0;for(let x of u){let A=Math.max((T.get(x)??0)/this.impactReference,(t.level.get(x)??0)*M);t.level.set(x,A),x.recording.channel("impact")[l]=A,A>v&&(v=A)}this.worldRecording.channel("impact")[l]=v;for(let x of this.stepHooks)x(r,y);t.current=r}bind(t){let r=t.layer,n=t.output??(this.bakeDefault?"keyframes":"signals");if(typeof r?.animate!="function"||n==="none"||t.type==="fixed")return;let i=t.boundChannels();if(n==="keyframes"&&this.liveMode)throw new Error('Physics: live worlds bind signals; drop `output: "keyframes"` or use simulate().');if(n==="signals"){let u=Q.create();for(let[l,c]of i)u.signal(l,t.recording.signal(c));r.animate(u);return}let o=this.bakeDefault?.tolerance??.25,a=Q.create();for(let[u,l]of i){let m=t.recording.channel(l).subarray(this.startFrame),d=B0[u]??1;a.keys(u,I0(m,o*d))}r.animate(a)}};function z0(e,t,r){return e.map((n,i)=>n+(t[i]-n)*r)}var Ws=(e,t)=>e===void 0?t:typeof e=="number"?[e,e]:e,Pn=class extends ir{op="Particles";particleStatic;particleState;options;constructor(t){super({}),this.options=t;let r=t.emitter??{},n=u=>typeof u=="number"?u:void 0,i=t.width,o=t.height,a=(Array.isArray(t.color)?t.color:[t.color??"#ffffff"]).map(u=>{let l=zu(u);return[l.r,l.g,l.b,l.a]});this.particleStatic={max:Math.max(1,Math.round(t.max??2e4)),seed:Math.round(t.seed??1)>>>0,layer:{x:t.x??0,y:t.y??0,width:i,height:o},emitter:{shape:r.shape??"rect",x:n(r.x)??(r.shape==="circle"||r.shape==="ring"||r.shape==="point"?i/2:0),y:n(r.y)??(r.shape==="circle"||r.shape==="ring"||r.shape==="point"?o/2:0),width:r.width??i,height:r.height??(r.shape==="line"?0:o),radius:r.radius??Math.min(i,o)/4,radial:r.radial??!1},lifetime:Ws(t.lifetime,[2,4]),speed:Ws(t.speed,[40,160]),direction:t.direction??-90,spread:t.spread??360,bounds:t.bounds??"none",floor:t.floor??null,bounce:t.bounce??.3,size:Ws(t.size,[6,0]),sizeJitter:t.sizeJitter??.5,fade:t.fade??[.1,.3],shape:t.shape??"circle",stretch:t.stretch??.04,blend:t.blend??"normal",colors:a.slice(0,8),colorBySpeed:t.colorBySpeed??null,opacity:t.opacity??1,substeps:t.substeps??2,prewarm:t.prewarm??0}}particleFrame(t,r){let n=this.options,i=(g,y)=>g===void 0?y:Ue(g,t,r),o=t-(n.startFrame??0),a=(n.emitter?.bursts??[]).filter(g=>Math.round(g.frame)===o).reduce((g,y)=>g+y.count,0),u=n.gravity,l=Array.isArray(u)?[i(u[0],0),i(u[1],0)]:[0,i(u,0)],c=null;n.push&&(c={strength:i(n.push.strength,6e3),sweep:i(n.push.sweep,6e4),mask:n.push.person.silhouetteGrid(t),previous:n.push.person.silhouetteGrid(Math.max(0,t-1))});let m=n.emitter?.x,d=n.emitter?.y,p=m!==void 0&&typeof m!="number"||d!==void 0&&typeof d!="number",f=g=>({x:m===void 0?this.particleStatic.emitter.x:Ue(m,g,r),y:d===void 0?this.particleStatic.emitter.y:Ue(d,g,r)}),b;if(p){let g=f(t),y=f(Math.max(0,t-1));b={x:g.x,y:g.y,previousX:y.x,previousY:y.y}}return{...b&&{emitter:b},rate:i(n.emitter?.rate,1e3),burst:a,gravity:l,drag:i(n.drag,.4),noise:{strength:i(n.noise?.strength,0),scale:n.noise?.scale??300,speed:n.noise?.speed??.3},attractors:(n.attractors??[]).map(g=>({x:i(g.x,0),y:i(g.y,0),strength:i(g.strength,0),radius:g.radius??200})),push:c}}};h();var ge=ut(hp(),1);h();var qi=ut(Bf(),1);function _0(e=64){if(!Number.isSafeInteger(e)||e<1)throw new Error("[FrameGrid] maxFrames must be a positive safe integer.");return Math.min(e,120)}function Hs(e,t){if(e>t)throw new Error(`[FrameGrid] Requested frames exceeds the safety threshold of ${t}. Increase stepFrames/stepMs or narrow the start/end range.`)}function gp(e,t,r,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<e)throw new Error(`[FrameGrid] Invalid ${i} range: start${i==="frame"?"Frame":"Ms"} must be <= end${i==="frame"?"Frame":"Ms"}; bounds must be finite and nonnegative.`);if(!Number.isFinite(r)||r<=0)throw new Error(`[FrameGrid] Invalid ${i==="frame"?"stepFrames":"stepMs"}: ${r}. Must be > 0 and finite.`);if(i==="frame"&&![e,t,r].every(Number.isSafeInteger))throw new Error("[FrameGrid] Frame bounds and stepFrames must be safe integers.");let o=[];for(let a=0;;a++){let u=e+a*r;if(!Number.isFinite(u))throw new Error("[FrameGrid] Range arithmetic overflow.");if(a>0&&u<=o[a-1])throw new Error("[FrameGrid] Step does not advance the sampling range.");if(u>t)break;Hs(a+1,n),o.push(u)}return o}function Ys(e,t=24,r){let n=e.fps??t;Un(n);let i=_0(e.maxFrames),o;if(e.frames?.length?(Hs(e.frames.length,i),o=e.frames.map(a=>Nt({frame:a},n))):e.timesMs?.length?(Hs(e.timesMs.length,i),o=e.timesMs.map(a=>Nt({atMs:a},n))):o=V0(e,n,r,i),!o.length)throw new Error("[FrameGrid] Zero frames were resolved for sampling.");return{samples:o,fps:n}}function V0(e,t,r,n){let i=r===void 0?void 0:Du(r,t)-1;if(e.startMs!==void 0||e.endMs!==void 0||e.stepMs!==void 0){let u=e.startMs??0,l=e.endMs??(i===void 0?u+1e3:i/t*1e3);return gp(u,l,e.stepMs??5e3/t,n,"millisecond").map(c=>Nt({atMs:c},t))}let o=e.startFrame??0,a=e.endFrame??Math.min(o+30,i??o+30);return gp(o,a,e.stepFrames??5,n,"frame").map(u=>Nt({frame:u},t))}function Xs(e,t,r){let n=r.gap??12,i=r.padding??16,a=r.showHeader??!0?54:0,u=r.maxGridWidth??4096,l=r.maxGridHeight??4096,c=r.columns;(!c||c<=0)&&(e<=4?c=e:e<=9?c=3:e<=16?c=4:e<=25?c=5:c=6),c=Math.min(c,e);let m=Math.ceil(e/c),d=Math.max(120,Math.min(r.cellWidth??320,960)),p=r.cellHeight??Math.round(d/(t>0?t:16/9)),f=c*d+(c-1)*n+i*2,b=m*p+(m-1)*n+i*2+a;if(f>u||b>l){let g=Math.min((u-(c-1)*n-i*2)/(c*d),(l-(m-1)*n-i*2-a)/(m*p));if(g<.25)throw new Error(`[FrameGrid] Cannot fit ${e} cells (${c}x${m}) into max dimensions [${u}x${l}]. Reduce cell count or decrease cellWidth.`);d=Math.max(100,Math.floor(d*g)),p=Math.round(d/(t>0?t:16/9)),f=c*d+(c-1)*n+i*2,b=m*p+(m-1)*n+i*2+a}return{columns:c,rows:m,cellWidth:d,cellHeight:p,totalWidth:f,totalHeight:b,headerHeight:a,gap:n,padding:i}}async function Tn(e,t={}){let r=e.fps??24,n=e.durationMs,{samples:i,fps:o}=Ys(t,r,n),a=e.width??1920,u=e.height??1080,l=a>0&&u>0?a/u:16/9,c=Xs(i.length,l,t),m=t.renderer??new ge.HeadlessMediaRenderer,d=[];for(let y of i){let T=await e.renderFrame({frame:y.frame,fps:o,renderer:m});d.push(T)}let p=new qi.Canvas(c.totalWidth,c.totalHeight),f=p.getContext("2d");if(f.fillStyle=t.backgroundColor??"#090a0f",f.fillRect(0,0,c.totalWidth,c.totalHeight),t.showHeader!==!1&&c.headerHeight>0){let y=t.headerText??`FrameGrid Conformance Review | Frames ${i[0].frame}\u2013${i[i.length-1].frame} (Count: ${i.length})`,T=`${a}\xD7${u} @ ${o} FPS | Cell: ${c.cellWidth}\xD7${c.cellHeight}px | Step: ${t.stepFrames?`${t.stepFrames}f`:t.stepMs?`${t.stepMs}ms`:"Custom"}`;f.fillStyle="#f8fafc",f.font="bold 15px sans-serif",f.fillText(y,c.padding,c.padding+18),f.fillStyle="#94a3b8",f.font="12px sans-serif",f.fillText(T,c.padding,c.padding+36),f.strokeStyle="#1e2433",f.lineWidth=1,f.beginPath(),f.moveTo(c.padding,c.padding+46),f.lineTo(c.totalWidth-c.padding,c.padding+46),f.stroke()}let b=t.showLabels??!0;for(let y=0;y<i.length;y++){let T=i[y],M=y%c.columns,v=Math.floor(y/c.columns),x=c.padding+M*(c.cellWidth+c.gap),A=c.padding+c.headerHeight+v*(c.cellHeight+c.gap),w=await(0,qi.loadImage)(d[y]);if(f.drawImage(w,x,A,c.cellWidth,c.cellHeight),f.strokeStyle="#262b3d",f.lineWidth=1,f.strokeRect(x,A,c.cellWidth,c.cellHeight),b){let R=`F:${T.frame} \u2022 ${Math.round(T.timeMs)}ms`;f.font="bold 11px sans-serif";let V=f.measureText(R).width+14,$=20,I=x+6,E=A+6;f.fillStyle="#090a0fee",f.beginPath(),f.roundRect(I,E,V,$,4),f.fill(),f.strokeStyle="#6366f155",f.lineWidth=1,f.stroke(),f.fillStyle="#e2e8f0",f.fillText(R,I+7,E+14)}}let g=await p.toBuffer("png");return t.outputPath&&await zr.writeFile(t.outputPath,g),g}h();h();function bp(e){let t=Math.PI/180,r=e.scale??1,n=se.translate(e.x??0,e.y??0,e.z??0);return e.rotateZ&&(n=se.multiply(n,se.rotateZ(e.rotateZ*t))),e.rotateY&&(n=se.multiply(n,se.rotateY(e.rotateY*t))),e.rotateX&&(n=se.multiply(n,se.rotateX(e.rotateX*t))),se.multiply(n,se.scale(r*(e.scaleX??1),r*(e.scaleY??1),r*(e.scaleZ??1)))}function yp(e,t){for(let[r,n]of Object.entries(t))Object.defineProperty(e,r,{value:n,enumerable:!1,configurable:!0})}function $0(e,t){let r=t.scale??1,n=r*(t.scaleX??1),i=r*(t.scaleY??1),o=r*(t.scaleZ??1),a=(u,l)=>[(u-(t.x??0))/n,(l-(t.z??0))/o];return{heightAt:(u,l)=>(t.y??0)+e.heightAt(...a(u,l))*i,elevationAt:(u,l)=>e.elevationAt(...a(u,l)),normalAt(u,l){let c=e.normalAt(...a(u,l)),m=[c[0]/n,c[1]/i,c[2]/o],d=Math.hypot(m[0],m[1],m[2])||1;return[m[0]/d,m[1]/d,m[2]/d]}}}function xp(e){let{heightFn:t,...r}=e,n={type:"terrain",width:r.width,depth:r.depth,height:r.height,segments:r.segments,noise:r.noise,heights:r.heights,overhangWarp:r.overhangWarp,colorByElevation:r.colorByElevation,flatShaded:r.flatShaded,base:r.base};if(t){let[o,a]=Ku(n),u=[];for(let l=0;l<=a;l++)for(let c=0;c<=o;c++)u.push(t(c/o,l/a));n.heights=u}let i=Pe("terrain",n,r);return yp(i,$0(Qu(n),e)),i}function Sp(e){return Pe("sdf",{type:"sdf",primitives:e.primitives,bounds:e.bounds,resolution:e.resolution,flatShaded:e.flatShaded},e)}var G0=["x","y","z","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","primitive3d","src","modelFormat","center","normalizeSize"];function W0(e){let t={};for(let r of G0)e[r]!==void 0&&(t[r]=e[r]);return!e.primitive3d&&!e.src&&e.modelData&&(t.modelData=e.modelData),t}function wp(e){let t=e.modelData;if(t&&"meshes"in t)return t;if(e.primitive3d)return Hn(e.primitive3d)}var H0=["count","minDistance","seed","slopeRange","elevationRange","alignToNormal","scaleRange","randomYaw","exclude","sink"];function vp(e){let{surface:t,wind:r,...n}=e,i={surface:W0(t)},o={...n};for(let l of H0)n[l]!==void 0&&(i[l]=n[l]),delete o[l];let a=we.instances(o),u=a;return u.scatter3d=i,r&&(u.wind=r),yp(a,{points:()=>{let l=wp(t);return l?To({model:l,matrix:bp(t)},i).points:[]}}),a}function kp(e){let t=e.surface,r=wp(t);if(r)return To({model:r,matrix:bp(t)},{...e,count:0}).acceptedArea}function Pp(e,t){return{node:typeof e=="string"?t(e):e}}h();function Tp(e){let t;if(Array.isArray(e.mesh))t=e.mesh;else if(e.mesh&&typeof e.mesh=="object"&&"kind"in e.mesh)t=[e.mesh];else if(e.mesh&&typeof e.mesh=="object"&&e.mesh.type==="shard"){let i=Math.max(1,e.mesh.variants??8);t=[];for(let o=0;o<i;o++)t.push(we.shard({radius:20,facets:e.mesh.facets??12+o%6,seed:(e.seed??1)*31+o*17,irregularity:e.mesh.irregularity??.35}))}else if(e.mesh==="sphere")t=[we.sphere({radius:20})];else if(e.mesh==="roundedBox")t=[we.roundedBox({size:[30,30,30]})];else if(e.mesh==="cylinder")t=[we.cylinder({radius:15,height:35})];else{t=[];for(let o=0;o<8;o++)t.push(we.shard({radius:20,facets:10+o%8*2,seed:(e.seed??42)+o*13,irregularity:.35+o%3*.1}))}let r={id:e.id??Y("swarm3d"),kind:"model3d",x:0,y:0,z:0,opacity:1,twoSided:!0,material:e.material??"lit",roughness:e.roughness??.35,metallic:e.metallic??.7,specularIntensity:e.specularIntensity??.5,ambientIntensity:e.ambientIntensity??1,startFrame:e.startFrame,durationFrames:e.durationFrames,swarm3d:{...e,meshVariants:t}},n=t[0];return n&&(n.modelData&&(r.modelData=n.modelData),n.primitive3d&&(r.primitive3d=n.primitive3d)),B.model(r)}var Y0=["toon","outline","material","shininess","roughness","specularIntensity","metallic","ambientIntensity","ior","transmission","dispersion","fresnelPower","envIntensity","emissive","emissiveIntensity","castShadow","clearcoat","clearcoatRoughness","anisotropy","anisotropyRotation","subsurface","subsurfaceColor","sheen","sheenColor","sheenRoughness","iridescence","iridescenceThickness","iridescenceIor","triplanar","triplanarScale","triplanarSharpness"];function rt(e){let t=e,r={};for(let n of Y0)t[n]!==void 0&&(r[n]=t[n]);return r}function X0(e){return e==="lit"||e==="unlit"||e==="toon"?e:void 0}function Zs(e){return e instanceof wo?e.getPoints(96):e}function Pe(e,t,r){let n=Object.fromEntries(Object.entries({...t,color:r.color,material:X0(r.material),shininess:r.shininess,roughness:r.roughness,metallic:r.metallic}).filter(([,i])=>i!==void 0));return B.model({id:r.id??Y(e),modelData:Hn(n),primitive3d:n,is3D:!0,x:r.x??0,y:r.y??0,z:r.z??0,rotateX:r.rotateX??r.rotationX??0,rotateY:r.rotateY??r.rotationY??0,rotateZ:r.rotateZ??r.rotationZ??0,scale:r.scale??1,scaleX:r.scaleX??1,scaleY:r.scaleY??1,scaleZ:r.scaleZ??1,opacity:r.opacity??1,color:r.tint,material:r.material,shininess:r.shininess??32,roughness:r.roughness,specularIntensity:r.specularIntensity??.5,ambientIntensity:r.ambientIntensity??1,metallic:r.metallic,...rt(r),twoSided:r.twoSided??!1,wireframe:r.wireframe,startFrame:r.startFrame,durationFrames:r.durationFrames,...r.wind&&{wind:r.wind},...r.texture!==void 0&&{textureLayer:Pp(r.texture,i=>B.image(i))}})}function Mn(e,t){let r=t.faces??t.items??[];for(let[n,i]of Object.entries(t))Object.defineProperty(e,n,{value:i,enumerable:!1,configurable:!0});return Object.defineProperty(e,Symbol.iterator,{value:function*(){yield*r},enumerable:!1,configurable:!0}),e}function Z0(e){let t=e.scale??1,r=Math.max(Math.abs(t*(e.scaleX??1)),Math.abs(t*(e.scaleY??1)));return r>0?r:1}var we={cube(e){let t=e.size,[r,n,i]=typeof t=="number"?[t,t,t]:t,o=e.twoSided??!0,a={front:"#3b82f6",back:"#1d4ed8",left:"#2563eb",right:"#1e40af",top:"#60a5fa",bottom:"#172554"},u=(f,b,g,y,T,M)=>{if(b&&typeof b=="object"&&"kind"in b){let x=b;return x.position="absolute",x.is3D=!0,x.twoSided=o,x.material=x.material??e.material??"lit",x.shininess=x.shininess??e.shininess??32,x.specularIntensity=x.specularIntensity??e.specularIntensity??.5,e.roughness!==void 0&&x.roughness===void 0&&(x.roughness=e.roughness),e.metallic!==void 0&&x.metallic===void 0&&(x.metallic=e.metallic),e.ambientIntensity!==void 0&&x.ambientIntensity===void 0&&(x.ambientIntensity=e.ambientIntensity),Object.assign(x,{...rt(e),...rt(x)},M),x}let v=typeof b=="string"?{background:b}:b??{background:g};return B.box({id:`${e.id??"cube"}-${f}`,position:"absolute",width:y,height:T,is3D:!0,twoSided:o,material:v.material??e.material??"lit",shininess:v.shininess??e.shininess??32,specularIntensity:v.specularIntensity??e.specularIntensity??.5,roughness:v.roughness??e.roughness,metallic:v.metallic??e.metallic,ambientIntensity:v.ambientIntensity??e.ambientIntensity??1,...rt({...e,...v}),background:v.background??g,borderRadius:v.borderRadius??0,borderWidth:v.borderWidth,borderColor:v.borderColor,opacity:v.opacity??1,children:v.children??[],...M})},l=r/2,c=n/2,m=i/2,d=[u("front",e.faces?.front,a.front,r,n,{x:0,y:0,z:-m,rotateX:0,rotateY:0,rotateZ:0}),u("back",e.faces?.back,a.back,r,n,{x:0,y:0,z:m,rotateX:0,rotateY:180,rotateZ:0}),u("left",e.faces?.left,a.left,i,n,{x:-l,y:0,z:0,rotateX:0,rotateY:90,rotateZ:0}),u("right",e.faces?.right,a.right,i,n,{x:l,y:0,z:0,rotateX:0,rotateY:-90,rotateZ:0}),u("top",e.faces?.top,a.top,r,i,{x:0,y:-c,z:0,rotateX:-90,rotateY:0,rotateZ:0}),u("bottom",e.faces?.bottom,a.bottom,r,i,{x:0,y:c,z:0,rotateX:90,rotateY:0,rotateZ:0})],p=B.box({id:e.id??Y("cube"),position:"absolute",x:e.x??0,y:e.y??0,z:e.z??0,width:r,height:n,is3D:!0,transformStyle:"preserve-3d",rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,opacity:e.opacity??1,background:"transparent",children:d});return Mn(p,{faces:d})},carousel(e){let{items:t,radius:r,faceInward:n=!1,twoSided:i=!0}=e,o=t.length,a=o>0?360/o:0,u=t.map((c,m)=>{let d=m*a,p=d*Math.PI/180,f=r*Math.sin(p),b=-r*Math.cos(p),g=n?180-d:-d,y=c;return y.position="absolute",y.is3D=!0,y.twoSided=i,y.x=f,y.y=0,y.z=b,y.rotateY=g,y}),l=B.box({id:e.id??Y("carousel"),position:"absolute",x:e.x??0,y:e.y??0,z:e.z??0,width:e.itemWidth??200,height:e.itemHeight??200,is3D:!0,transformStyle:"preserve-3d",rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,opacity:e.opacity??1,background:"transparent",children:u});return Mn(l,{items:u})},prism(e={}){let t=Math.max(3,Math.round(e.sides??6)),r=e.radius??60,n=e.height??100;if(e.sideConfigs&&e.sideConfigs.length>0){let{twoSided:o=!0}=e,a=2*r*Math.tan(Math.PI/t),u=360/t,l=[];for(let m=0;m<t;m++){let d=m*u,p=d*Math.PI/180,f=r*Math.sin(p),b=-r*Math.cos(p),g=e.sideConfigs[m],y=e.color??`hsl(${m*360/t}, 70%, 50%)`;if(g&&typeof g=="object"&&"kind"in g){let M=g;M.position="absolute",M.is3D=!0,M.twoSided=o,M.x=f,M.y=0,M.z=b,M.rotateY=-d,Object.assign(M,rt(e)),l.push(M);continue}let T=typeof g=="string"?{background:g}:g??{background:y};l.push(B.box({id:`${e.id??"prism"}-panel-${m}`,position:"absolute",width:a,height:n,is3D:!0,twoSided:o,x:f,y:0,z:b,rotateY:-d,background:T.background??y,borderRadius:T.borderRadius??0,borderWidth:T.borderWidth,borderColor:T.borderColor,opacity:T.opacity??e.opacity??1,material:T.material??e.material??"lit",shininess:T.shininess??e.shininess??32,specularIntensity:T.specularIntensity??e.specularIntensity??.5,ambientIntensity:T.ambientIntensity??e.ambientIntensity??1,...rt({...e,...T}),children:T.children??[]}))}let c=B.box({id:e.id??Y("prism"),position:"absolute",x:e.x??0,y:e.y??0,z:e.z??0,width:a,height:n,is3D:!0,transformStyle:"preserve-3d",rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,opacity:e.opacity??1,background:"transparent",children:l});return Mn(c,{faces:l,items:l})}let i=Pe("prism",{type:"cylinder",radius:r,radiusTop:e.radiusTop??e.topRadius??r,radiusBottom:e.radiusBottom??e.bottomRadius??r,height:n,segments:t,openEnded:e.openEnded??!1,flatShaded:e.flatShaded??!0},{...e,color:e.color??"#3b82f6",twoSided:e.twoSided??!!e.openEnded});return Mn(i,{faces:[i],items:[i]})},pyramid(e={}){let t=Math.max(3,Math.round(e.sides??4));return Pe("pyramid",{type:"cylinder",radius:e.radius??60,radiusTop:e.radiusTop??e.topRadius??0,radiusBottom:e.radius??60,height:e.height??100,segments:t,openEnded:e.openEnded??!1,flatShaded:e.flatShaded??!0},{...e,color:e.color??"#f59e0b",twoSided:e.twoSided??!!e.openEnded})},plane(e){return B.box({id:e.id??Y("plane"),position:"absolute",width:e.width,height:e.height,x:e.x??0,y:e.y??0,z:e.z??0,is3D:!0,twoSided:e.twoSided??!0,rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,background:e.background??"#3b82f6",borderRadius:e.borderRadius??0,opacity:e.opacity??1,...rt(e),children:e.children??[]})},grid(e){let{width:t,height:r}=e,n=e.id??Y("grid"),i=Math.max(1,Math.round(e.divisions??10)),o=e.lineWidth??2,a=e.color??"rgba(59, 130, 246, 0.5)",u=(p,f,b,g,y)=>B.box({id:`${n}-${p}`,position:"absolute",x:f,y:b,z:0,width:g,height:y,is3D:!0,twoSided:!0,material:"unlit",background:a}),l=4096,c=[],m=Math.ceil(r/l),d=Math.ceil(t/l);for(let p=0;p<=i;p++){let f=p/i-.5;for(let b=0;b<m;b++){let g=r/m,y=-r/2+g*(b+.5);c.push(u(`v${p}-${b}`,f*t,y,o,g))}for(let b=0;b<d;b++){let g=t/d,y=-t/2+g*(b+.5);c.push(u(`h${p}-${b}`,y,f*r,g,o))}}return B.box({id:n,position:"absolute",width:t,height:r,x:e.x??0,y:e.y??0,z:e.z??0,is3D:!0,transformStyle:"preserve-3d",rotateX:e.rotateX??e.rotationX??90,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,background:"transparent",opacity:e.opacity??1,children:c})},text(e){return e.extrusionDepth&&e.extrusionDepth>0?we.extrudedText({...e,depth:e.extrusionDepth}):B.text(e.text,{id:e.id??Y("text3d"),position:"absolute",x:e.x??0,y:e.y??0,z:e.z??0,is3D:!0,twoSided:e.twoSided??!0,rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,fontSize:e.fontSize??48,fontFamily:e.fontFamily,fontWeight:e.fontWeight??"bold",fontStyle:e.fontStyle,fill:e.fill??"#ffffff",align:e.align??"center",direction:e.direction,verticalAlign:e.verticalAlign??"middle",letterSpacing:e.letterSpacing,lineHeight:e.lineHeight,material:e.material??"lit",shininess:e.shininess??64,roughness:e.roughness,specularIntensity:e.specularIntensity??.8,ambientIntensity:e.ambientIntensity??1,metallic:e.metallic,...rt(e),opacity:e.opacity??1,background:e.background,borderRadius:e.borderRadius,padding:e.padding,stroke:e.stroke,strokeWidth:e.strokeWidth})},extrudedText(e){let{depth:t,text:r,fill:n="#ffffff",bevelColor:i}=e,o,a=(e.curveTolerance??.1)/Z0(e),u=(e.fontFamily?ar.getParsed(e.fontFamily):null)??ar.getParsed("Inter")??ar.getParsed("Unbounded")??ar.getFirstParsed();u&&(o=Zu({text:r,font:u,fontSize:e.fontSize??48,depth:t,fill:n,bevelColor:i,curveSegments:e.curveSegments,curveTolerance:a,align:e.align,direction:e.direction,verticalAlign:e.verticalAlign,letterSpacing:e.letterSpacing,material:e.material==="lit"||e.material==="unlit"||e.material==="toon"?e.material:void 0,shininess:e.shininess,roughness:e.roughness,metallic:e.metallic}).modelData);let l=B.model({id:e.id??Y("extruded-text"),modelData:o,is3D:!0,x:e.x??0,y:e.y??0,z:e.z??0,rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,scale:e.scale??1,scaleX:e.scaleX??1,scaleY:e.scaleY??1,scaleZ:e.scaleZ??1,opacity:e.opacity??1,material:e.material,shininess:e.shininess??32,roughness:e.roughness,specularIntensity:e.specularIntensity??.8,ambientIntensity:e.ambientIntensity??1,metallic:e.metallic,...rt(e),twoSided:e.twoSided??!0,text3dOptions:{...e,curveTolerance:a}});return Mn(l,{faces:[l],items:[l]})},roundedBox(e){return Pe("rounded-box",{type:"roundedBox",width:e.width,height:e.height,depth:e.depth,radius:e.radius??e.cornerRadius??e.borderRadius,segments:e.segments,taper:e.taper},e)},sphere(e){return Pe("sphere",{type:"sphere",radius:e.radius,segments:e.segments},e)},cylinder(e){return Pe("cylinder",{type:"cylinder",radius:e.radius,radiusTop:e.radiusTop??e.topRadius,radiusBottom:e.radiusBottom??e.bottomRadius,height:e.height,segments:e.segments,openEnded:e.openEnded,flatShaded:e.flatShaded},{...e,twoSided:e.twoSided??!!e.openEnded})},torus(e={}){return Pe("torus",{type:"torus",radius:e.radius??e.majorRadius,tube:e.tube??e.minorRadius??e.tubeRadius,radialSegments:e.radialSegments,tubularSegments:e.tubularSegments,arc:e.arc},e)},capsule(e={}){return Pe("capsule",{type:"capsule",radius:e.radius,length:e.length,capSegments:e.capSegments,radialSegments:e.radialSegments},e)},ring(e={}){return Pe("ring",{type:"ring",innerRadius:e.innerRadius,outerRadius:e.outerRadius,depth:e.depth,thetaSegments:e.thetaSegments,phiSegments:e.phiSegments,thetaStart:e.thetaStart,thetaLength:e.thetaLength},e)},polyhedron(e={}){let t=e.shape??e.type??"icosahedron";return Pe(t,{type:"polyhedron",shape:t,radius:e.radius,detail:e.detail,flatShaded:e.flatShaded},e)},icosahedron(e={}){return we.polyhedron({...e,shape:"icosahedron"})},icosphere(e={}){return we.polyhedron({...e,shape:"icosphere",detail:e.detail??2,flatShaded:e.flatShaded??!1})},extrude(e){return Pe("extrude",{type:"extrude",shape:e.shape,d:e.d,contour:e.contour,holes:e.holes,depth:e.depth,bevelThickness:e.bevelThickness,bevelSize:e.bevelSize,bevelSegments:e.bevelSegments,bevelColor:e.bevelColor,curveSegments:e.curveSegments,curveTolerance:e.curveTolerance,center:e.center},e)},lathe(e){let t=e.capped??e.closed;return Pe("lathe",{type:"lathe",points:e.points,segments:e.segments,phiStart:e.phiStart,phiLength:e.phiLength,capped:t,closed:e.closed,flatShaded:e.flatShaded},{...e,twoSided:e.twoSided??!(t??!1)})},tube(e){let t=e.path??e.points;if(!t)throw new Error("Layer3D.tube requires `path` or `points`");return Pe("tube",{type:"tube",path:Zs(t),radius:e.radius,innerRadius:e.innerRadius,radiusTaper:e.radiusTaper,tubularSegments:e.tubularSegments,radialSegments:e.radialSegments,closed:e.closed,capped:e.capped},{...e,twoSided:e.twoSided??e.capped===!1})},line(e){let t=e.points??e.path;if(!t)throw new Error("Layer3D.line requires `points` or `path`");return Pe("line3d",{type:"line3d",points:Zs(t),colors:e.colors,mode:e.mode,closed:e.closed,dashSize:e.dashSize,gapSize:e.gapSize},{...e,material:e.material??"unlit",castShadow:e.castShadow??!1})},points(e){let t=(e.pointSize??0)<=0;return Pe("points3d",{type:"points3d",points:Zs(e.points),colors:e.colors,pointSize:e.pointSize},{...e,material:e.material??(t?"unlit":"lit"),castShadow:e.castShadow??!t})},shard(e={}){return Pe("shard",{type:"shard",radius:e.radius,size:e.size,facets:e.facets,seed:e.seed,irregularity:e.irregularity},e)},terrain(e){return xp(e)},sdf(e){return Sp(e)},scatter(e){return vp(e)},instances(e){let t=Array.isArray(e.mesh)?e.mesh[0]:e.mesh,r={id:e.id??Y("instances3d"),kind:"model3d",x:e.x??0,y:e.y??0,z:e.z??0,rotateX:e.rotateX??e.rotationX??0,rotateY:e.rotateY??e.rotationY??0,rotateZ:e.rotateZ??e.rotationZ??0,scale:e.scale??1,color:e.color,colorTint:e.colorTint,opacity:e.opacity??1,twoSided:e.twoSided??!0,wireframe:e.wireframe??!1,material:e.material??"lit",roughness:e.roughness,metallic:e.metallic,specularIntensity:e.specularIntensity,ambientIntensity:e.ambientIntensity,startFrame:e.startFrame,durationFrames:e.durationFrames,instances3d:{...e},...e.wind&&{wind:e.wind},...e.crowd&&{crowd:e.crowd},...rt(e)};if(t){let n=t;n.modelData&&(r.modelData=n.modelData),n.primitive3d&&(r.primitive3d=n.primitive3d),n.src&&(r.src=n.src)}return B.model(r)},swarm(e={}){return Tp(e)},model(e={}){return B.model(e)},obj(e,t={}){return B.obj(e,t)},fbx(e,t={}){return B.fbx(e,t)},gltf(e,t={}){return B.gltf(e,t)},glb(e,t={}){return B.glb(e,t)},stl(e,t={}){return B.stl(e,t)},ply(e,t={}){return B.ply(e,t)},vox(e,t={}){return B.vox(e,t)},threeDS(e,t={}){return B.threeDS(e,t)},off(e,t={}){return B.off(e,t)}};h();var qs=(e,t,r)=>{switch(e){case"left":return{dx:-t,dy:0};case"right":return{dx:t,dy:0};case"up":return{dx:0,dy:-r};default:return{dx:0,dy:r}}};function gt(e,t,r){return{kind:e,frames:Math.max(0,Math.round(t)),build:r}}var Mp={cut:()=>gt("cut",0,()=>({})),crossfade:(e=15,t="sine.inOut")=>gt("crossfade",e,r=>({incoming:Q.keys("opacity",[[0,0],[r.frames,1,t]])})),fadeThrough:(e=20,t="sine.inOut")=>gt("fadeThrough",e,r=>{let n=Math.max(1,Math.floor(r.frames/2));return{outgoing:Q.keys("opacity",[[r.outStart,1],[r.outStart+n,0,t]]),incoming:Q.keys("opacity",[[0,0],[n,0],[r.frames,1,t]])}}),push:(e="left",t=18,r="power3.inOut")=>gt("push",t,n=>{let{dx:i,dy:o}=qs(e,n.width,n.height),a=Q.create(),u=Q.create();return i!==0?(a.keys("x",[[n.outStart,n.outRest.x],[n.outStart+n.frames,n.outRest.x+i,r]]),u.keys("x",[[0,n.inRest.x-i],[n.frames,n.inRest.x,r]])):(a.keys("y",[[n.outStart,n.outRest.y],[n.outStart+n.frames,n.outRest.y+o,r]]),u.keys("y",[[0,n.inRest.y-o],[n.frames,n.inRest.y,r]])),{outgoing:a,incoming:u}}),slide:(e="left",t=18,r="power3.out")=>gt("slide",t,n=>{let{dx:i,dy:o}=qs(e,n.width,n.height),a=i!==0?"x":"y",u=i!==0?n.inRest.x:n.inRest.y;return{outgoing:Q.keys("opacity",[[n.outStart,1],[n.outStart+n.frames,.6,r]]),incoming:Q.keys(a,[[0,u-(i||o)],[n.frames,u,r]])}}),zoom:(e=18,t="power2.inOut")=>gt("zoom",e,r=>({outgoing:Q.create().keys("scale",[[r.outStart,1],[r.outStart+r.frames,1.25,t]]).keys("opacity",[[r.outStart,1],[r.outStart+r.frames,0,t]]),incoming:Q.create().keys("scale",[[0,.85],[r.frames,1,t]]).keys("opacity",[[0,0],[r.frames,1,t]])})),whip:(e="left",t=10)=>{let r=Mp.push(e,t,"expo.inOut");return gt("whip",t,n=>({...r.build(n),sceneProps:{motionBlurShutter:360}}))},wipe:(e="left",t=18,r="power2.inOut")=>gt("wipe",t,n=>{let{dx:i,dy:o}=qs(e,n.width,n.height),a=i!==0?"x":"y",u=i!==0?n.inRest.x:n.inRest.y;return{incomingMatte:B.box({id:Y("wipe-matte"),position:"absolute",x:n.inRest.x,y:n.inRest.y,width:n.width,height:n.height,background:"#ffffff"}).animate(Q.keys(a,[[0,u-(i||o)],[n.frames,u,r]]))}}),iris:(e=20,t={})=>gt("iris",e,r=>{let[n,i]=t.at??[.5,.5],o=r.inRest.x+n*r.width,a=r.inRest.y+i*r.height,u=Math.hypot(Math.max(n,1-n)*r.width,Math.max(i,1-i)*r.height);return{incomingMatte:B.shape("circle",{id:Y("iris-matte"),position:"absolute",x:o-u,y:a-u,width:u*2,height:u*2,fillColor:"#ffffff"}).animate(Q.keys("scale",[[0,0],[r.frames,1,t.ease??"power2.inOut"]]))}})};function Ki(e,t,r){let n=e[t];return typeof n=="number"?n:r}function Ap(e,t={}){let r=[],n=[],i=0;e.forEach((a,u)=>{let l=u===0?void 0:a.transition,c=Math.min(l?.frames??0,e[u-1]?.duration??0),m=Math.max(0,i-c),d=Math.max(1,Math.round(a.duration));n.push(m);let p=a.scene;(p.position===void 0||p.position==="relative")&&(p.position="absolute",p.x??=0,p.y??=0),p.startFrame=m,p.durationFrames=d,r.push(p),i=m+d}),e.forEach((a,u)=>{if(u===0||!a.transition||a.transition.frames===0)return;let l=r[u-1],c=r[u],m=Math.min(a.transition.frames,e[u-1].duration),d=t.width??Ki(c,"width",1920),p=t.height??Ki(c,"height",1080),f=a.transition.build({width:d,height:p,frames:m,outStart:e[u-1].duration-m,outRest:{x:typeof l.x=="number"?l.x:0,y:typeof l.y=="number"?l.y:0},inRest:{x:typeof c.x=="number"?c.x:0,y:typeof c.y=="number"?c.y:0}}),b=(g,y)=>{if(!y)return;let T=g.animation?.tracks??[];g.animation=Q.merge({tracks:T},y).toSpec()};b(l,f.outgoing),b(c,f.incoming),f.sceneProps&&(Object.assign(l,f.sceneProps),Object.assign(c,f.sceneProps)),f.incomingMatte&&(c.matte={node:f.incomingMatte,mode:"alpha"})});let o=B.box({id:t.id??Y("sequence"),position:"absolute",x:0,y:0,width:t.width??Ki(r[0]??{},"width",1920),height:t.height??Ki(r[0]??{},"height",1080),startFrame:t.startFrame??0,durationFrames:Math.max(1,i),children:r});return Object.defineProperty(o,"totalFrames",{value:i,enumerable:!1}),Object.defineProperty(o,"sceneStarts",{value:n,enumerable:!1}),o}h();var q0={studio:{environment:"studio",envIntensity:1,key:{dir:[-.55,-1,-.7],color:"#fff6ec",intensity:1.1},rim:{dir:[.9,-.5,.9],color:"#dbe8ff",intensity:.9}},soft:{environment:"soft",envIntensity:1,key:{dir:[-.4,-1,-.8],color:"#ffffff",intensity:1}},sunset:{environment:"sunset",envIntensity:.9,key:{dir:[-1,-.35,-.3],color:"#ffb27a",intensity:2.2},fill:{dir:[.8,-.6,-.4],color:"#7f9cff",intensity:.35}},dramatic:{environment:"night",envIntensity:.8,key:{dir:[-.8,-1,-.35],color:"#ffffff",intensity:2.4},rim:{dir:[.7,-.4,1],color:"#8fb4ff",intensity:1.8}}};function K0([e,t,r],n){let i=n*Math.PI/180,o=Math.cos(i),a=Math.sin(i);return[o*e+a*r,t,-a*e+o*r]}function Cp(e,t,r,n){let[i,o,a]=K0(e,n),u=Math.hypot(i,o,a)||1;return{x:t[0]+i/u*r,y:t[1]+o/u*r,z:t[2]+a/u*r,targetX:t[0],targetY:t[1],targetZ:t[2]}}function Qi(e,t){let r=q0[e],n=t.target??[960,540,0],i=t.distance??1600,o=t.rotation??0,a=t.intensity??1,u=t.id??Y(`lighting-${e}`),l=[nt.environment(r.environment,{id:`${u}-environment`,intensity:r.envIntensity*a,rotation:o,exposure:t.exposure,toneMapping:t.toneMapping,fog:t.fog,volumetricFog:t.volumetricFog,ssr:t.ssr,gi:t.gi,bloom:t.bloom}),nt.directional({id:`${u}-key`,color:r.key.color,intensity:r.key.intensity*a,...Cp(r.key.dir,n,i,o),castShadow:t.shadows??!0,shadowSoftness:t.shadowSoftness??3})];for(let[c,m]of[["rim",r.rim],["fill",r.fill]])m&&l.push(nt.directional({id:`${u}-${c}`,color:m.color,intensity:m.intensity*a,...Cp(m.dir,n,i,o)}));return l}var Q0={studio:(e={})=>Qi("studio",e),soft:(e={})=>Qi("soft",e),sunset:(e={})=>Qi("sunset",e),dramatic:(e={})=>Qi("dramatic",e)};h();h();var J0="@dimforge/rapier2d-deterministic-compat",ex="@dimforge/rapier3d-deterministic-compat";async function Dp(e,t){let r;try{r=await t()}catch(i){throw new Error(`Physics needs the optional dependency "${e}". Install it with \`npm i ${e}\`.`,{cause:i})}let n=r.default??r;return await n.init(),n}var Rp,Op;async function Js(e){if(e===2){Rp??=Dp(J0,()=>import("./rapier-ZL2QGRPX.mjs"));let r=await Rp;return{createWorld2D:n=>new Ks(r,n),createWorld3D:()=>{throw new Error("This backend was loaded for 2D.")}}}Op??=Dp(ex,()=>import("./rapier-EQTGTIYW.mjs"));let t=await Op;return{createWorld2D:()=>{throw new Error("This backend was loaded for 3D.")},createWorld3D:r=>new Qs(t,r)}}var Ks=class{constructor(t,r){this.R=t;this.world=new t.World({x:r[0],y:r[1]}),this.events=new t.EventQueue(!0)}R;world;events;byCollider=new Map;started=[];addBody(t){let r=this.R,n=Np(r,t.type).setTranslation(t.position[0],t.position[1]).setRotation(t.angle).setLinvel(t.velocity[0],t.velocity[1]).setAngvel(t.angularVelocity).setLinearDamping(t.linearDamping).setAngularDamping(t.angularDamping).setGravityScale(t.gravityScale).setCcdEnabled(t.ccd).setEnabled(t.enabled);t.lockRotation&&n.lockRotations();let i=this.world.createRigidBody(n),o=this.world.createCollider(tx(r,t.shape).setDensity(t.density).setFriction(t.friction).setRestitution(t.restitution).setActiveEvents(r.ActiveEvents.COLLISION_EVENTS).setSensor(t.sensor??!1),i),a={raw:i,position:()=>{let u=i.translation();return[u.x,u.y]},rotation:()=>i.rotation(),velocity:()=>{let u=i.linvel();return[u.x,u.y]},angularVelocity:()=>i.angvel(),sleeping:()=>i.isSleeping(),mass:()=>i.mass(),setEnabled:u=>i.setEnabled(u),applyImpulse:([u,l])=>i.applyImpulse({x:u,y:l},!0),setPose:([u,l],c)=>{i.setTranslation({x:u,y:l},!0),i.setRotation(c,!0)},setVelocity:([u,l],c)=>{i.setLinvel({x:u,y:l},!0),i.setAngvel(c,!0)},setKinematicTarget:([u,l],c)=>{i.setNextKinematicTranslation({x:u,y:l}),i.setNextKinematicRotation(c)}};return this.byCollider.set(o.handle,a),a}addJoint(t,r,n){let i=this.R,o={x:n.anchorA[0],y:n.anchorA[1]},a={x:n.anchorB[0],y:n.anchorB[1]},u;switch(n.type){case"revolute":case"spherical":u=i.JointData.revolute(o,a);break;case"fixed":u=i.JointData.fixed(o,0,a,0);break;case"rope":u=i.JointData.rope(n.length,o,a);break;case"spring":u=i.JointData.spring(n.restLength,n.stiffness,n.damping,o,a);break}this.world.createImpulseJoint(u,Ji(t),Ji(r),!0).setContactsEnabled(!1)}step(t){this.world.timestep=t,this.world.step(this.events),this.events.drainCollisionEvents((r,n,i)=>{if(!i)return;let o=this.byCollider.get(r),a=this.byCollider.get(n);o&&a&&this.started.push([o,a])})}drainCollisionStarts(){return this.started.splice(0)}free(){this.events.free(),this.world.free()}},Qs=class{constructor(t,r){this.R=t;this.world=new t.World({x:r[0],y:r[1],z:r[2]}),this.events=new t.EventQueue(!0)}R;world;events;byCollider=new Map;started=[];addBody(t){let r=this.R,[n,i,o,a]=t.rotation,u=Np(r,t.type).setTranslation(t.position[0],t.position[1],t.position[2]).setRotation({x:n,y:i,z:o,w:a}).setLinvel(t.velocity[0],t.velocity[1],t.velocity[2]).setAngvel(bt(t.lockRotation?[0,0,0]:t.angularVelocity.map((p,f)=>t.enabledRotations&&!t.enabledRotations[f]?0:p))).setLinearDamping(t.linearDamping).setAngularDamping(t.angularDamping).setGravityScale(t.gravityScale).setCcdEnabled(t.ccd).setEnabled(t.enabled);t.lockRotation?u.lockRotations():t.enabledRotations&&u.enabledRotations(...t.enabledRotations);let l=this.world.createRigidBody(u),c=rx(r,t.shape),m=this.world.createCollider(c.setDensity(t.density).setFriction(t.friction).setRestitution(t.restitution).setActiveEvents(r.ActiveEvents.COLLISION_EVENTS).setSensor(t.sensor??!1),l),d={raw:l,position:()=>{let p=l.translation();return[p.x,p.y,p.z]},rotation:()=>{let p=l.rotation();return[p.x,p.y,p.z,p.w]},velocity:()=>{let p=l.linvel();return[p.x,p.y,p.z]},angularVelocity:()=>{let p=l.angvel();return[p.x,p.y,p.z]},sleeping:()=>l.isSleeping(),mass:()=>l.mass(),setEnabled:p=>l.setEnabled(p),applyImpulse:p=>l.applyImpulse(bt(p),!0),setPose:(p,[f,b,g,y])=>{l.setTranslation(bt(p),!0),l.setRotation({x:f,y:b,z:g,w:y},!0)},setVelocity:(p,f)=>{l.setLinvel(bt(p),!0),l.setAngvel(bt(f),!0)},setKinematicTarget:(p,[f,b,g,y])=>{l.setNextKinematicTranslation(bt(p)),l.setNextKinematicRotation({x:f,y:b,z:g,w:y})}};return this.byCollider.set(m.handle,d),d}addJoint(t,r,n){let i=this.R,o=bt(n.anchorA),a=bt(n.anchorB),u;switch(n.type){case"revolute":u=i.JointData.revolute(o,a,bt(n.axis??[0,0,1]));break;case"spherical":u=i.JointData.spherical(o,a);break;case"fixed":{let l={x:0,y:0,z:0,w:1};u=i.JointData.fixed(o,l,a,l);break}case"rope":u=i.JointData.rope(n.length,o,a);break;case"spring":u=i.JointData.spring(n.restLength,n.stiffness,n.damping,o,a);break}this.world.createImpulseJoint(u,Ji(t),Ji(r),!0).setContactsEnabled(!1)}step(t){this.world.timestep=t,this.world.step(this.events),this.events.drainCollisionEvents((r,n,i)=>{if(!i)return;let o=this.byCollider.get(r),a=this.byCollider.get(n);o&&a&&this.started.push([o,a])})}drainCollisionStarts(){return this.started.splice(0)}free(){this.events.free(),this.world.free()}};function bt([e,t,r]){return{x:e,y:t,z:r}}function Ji(e){return e.raw}function Np(e,t){let r=e.RigidBodyDesc;return t==="fixed"?r.fixed():t==="kinematic"?r.kinematicPositionBased():r.dynamic()}function tx(e,t){switch(t.kind){case"ball":return e.ColliderDesc.ball(t.radius);case"box":{let r=Math.min(t.radius??0,t.hx/2,t.hy/2);return r>0?e.ColliderDesc.roundCuboid(t.hx-r,t.hy-r,r):e.ColliderDesc.cuboid(t.hx,t.hy)}case"hull":{let r=e.ColliderDesc.convexHull(new Float32Array(t.points));if(!r)throw new Error("Physics: could not build a convex hull for this shape.");return r}}}function rx(e,t){switch(t.kind){case"ball":return e.ColliderDesc.ball(t.radius);case"box":{let r=Math.min(t.radius??0,t.hx/2,t.hy/2,t.hz/2);return r>0?e.ColliderDesc.roundCuboid(t.hx-r,t.hy-r,t.hz-r,r):e.ColliderDesc.cuboid(t.hx,t.hy,t.hz)}case"cylinder":return e.ColliderDesc.cylinder(t.halfHeight,t.radius);case"hull":{let r=e.ColliderDesc.convexHull(new Float32Array(t.points));if(!r)throw new Error("Physics: could not build a convex hull for this shape.");return r}case"trimesh":return e.ColliderDesc.trimesh(new Float32Array(t.vertices),new Uint32Array(t.indices))}}h();var An=class{constructor(t,r,n,i,o,a,u){this.world=t;this.type=n;this.layer=i;this.frame=o;this.options=a;this.sim=r,this.recording=u}world;type;layer;frame;options;collisions=[];recording;sim;get startFrame(){return Math.max(0,Math.round(this.options.startFrame??0))}get gravityScale(){return this.options.gravityScale??1}get output(){return this.options.output}get x(){return this.recording.signal("x")}get y(){return this.recording.signal("y")}get rotation(){return this.recording.signal("rotation")}get centerX(){return this.recording.signal("centerX")}get centerY(){return this.recording.signal("centerY")}get vx(){return this.recording.signal("vx")}get vy(){return this.recording.signal("vy")}get speed(){return this.recording.signal("speed")}get angularVelocity(){return this.recording.signal("angularVelocity")}get impact(){return this.recording.signal("impact")}get sleeping(){return this.recording.signal("sleeping")}kinematicTarget(t){let r=this.options.follow;if(this.type!=="kinematic"||!r)return;let n=this.frame,i=this.world.fps,o=r.x===void 0?void 0:Ue(r.x,t,i),a=r.y===void 0?void 0:Ue(r.y,t,i),u=r.rotation===void 0?n.rotation:Ue(r.rotation,t,i),l=this.initialLayerXY(),c=Ep(o??l[0],a??l[1],u,n),m=this.world.pixelsPerMeter;return{position:[c[0]/m,c[1]/m],rotation:u*Math.PI/180}}initialLayerXY(){let t=this.layer;return[Number(t?.x??0),Number(t?.y??0)]}record(t,r){let n=this.world.pixelsPerMeter,[i,o]=this.sim.position(),a=i*n,u=o*n,l=this.recording,c=l.channel("rotation"),m=this.sim.rotation()*180/Math.PI;c[t]=r<0?er(this.frame.rotation,m):er(c[r],m);let[d,p]=sx(a,u,c[t],this.frame);l.channel("x")[t]=d,l.channel("y")[t]=p,l.channel("centerX")[t]=a,l.channel("centerY")[t]=u;let[f,b]=this.sim.velocity();l.channel("vx")[t]=f*n,l.channel("vy")[t]=b*n,l.channel("speed")[t]=Math.hypot(f,b)*n,l.channel("angularVelocity")[t]=this.sim.angularVelocity()*180/Math.PI,l.channel("sleeping")[t]=this.sim.sleeping()?1:0}boundChannels(){let t=[["x","x"],["y","y"]];return this.options.lockRotation||t.push(["rotation","rotation"]),t}localAnchor(t){if(!t)return[0,0];let r=this.world.pixelsPerMeter,[n,i]=this.sim.position(),o=-this.sim.rotation(),a=t[0]/r-n,u=t[1]/r-i;return[a*Math.cos(o)-u*Math.sin(o),a*Math.sin(o)+u*Math.cos(o)]}center(){let t=this.world.pixelsPerMeter,[r,n]=this.sim.position();return[r*t,n*t]}},Fr=class extends Nr{constructor(t,r){let n=r.pixelsPerMeter??100,i=r.gravity??2400,o=typeof i=="number"?[0,i/n]:[i[0]/n,i[1]/n],a=t.createWorld2D(o);super(a,o,r)}body(t,r={}){this.assertOpen();let i=typeof t.kind=="string"?t:void 0,o=ix(t,r),a=this.pixelsPerMeter,u=r.type??"dynamic",[l,c]=Ep(o.x,o.y,o.rotation,o),m=r.velocity??[0,0],d={type:u,position:[l/a,c/a],angle:o.rotation*Math.PI/180,velocity:[m[0]/a,m[1]/a],angularVelocity:(r.angularVelocity??0)*Math.PI/180,linearDamping:r.linearDamping??0,angularDamping:r.angularDamping??0,gravityScale:r.gravityScale??1,lockRotation:r.lockRotation??!1,ccd:r.ccd??!1,enabled:!0,sensor:r.sensor??!1,density:r.density??1,friction:r.friction??.6,restitution:r.restitution??.3,shape:Fp(o.shape,1/a)},p=this.sim.addBody(d),f=new An(this,p,u,i,o,r,this.newRecording()),b=f.kinematicTarget(this.startFrame);return b&&p.setPose(b.position,b.rotation),this.addBody(f)}ground(t){return this.body({x:-1e6/2,y:t.y,width:1e6,height:2e3},{type:"fixed",friction:t.friction,restitution:t.restitution??.2})}walls(t){let{width:r,height:n}=t,i=t.x??0,o=t.y??0,a=t.thickness??400,u={type:"fixed",friction:t.friction,restitution:t.restitution??.2},l=n*4+a,c={floor:this.body({x:i-a,y:o+n,width:r+2*a,height:a},u),left:this.body({x:i-a,y:o+n-l,width:a,height:l},u),right:this.body({x:i+r,y:o+n-l,width:a,height:l},u),ceiling:void 0};return t.ceiling&&(c.ceiling=this.body({x:i-a,y:o-a,width:r+2*a,height:a},u)),c}pin(t,r){let n=r??t.center(),i=this.anchorBody(n);return this.joint(t,i,{type:"revolute",anchorA:t.localAnchor(n),anchorB:[0,0]}),this}hinge(t,r,n){return this.joint(t,r,{type:"revolute",anchorA:t.localAnchor(n),anchorB:r.localAnchor(n)}),this}weld(t,r){let n=t.center();return this.joint(t,r,{type:"fixed",anchorA:[0,0],anchorB:r.localAnchor(n)}),this}spring(t,r,n={}){let{other:i,pa:o,pb:a}=this.endpoints(t,r,n.anchorA,n.anchorB),u=this.pixelsPerMeter,l=(n.length??Math.hypot(a[0]-o[0],a[1]-o[1]))/u,c=nx(t,i),m=2*Math.PI*(n.frequency??2);return this.joint(t,i,{type:"spring",anchorA:t.localAnchor(o),anchorB:i.localAnchor(a),restLength:l,stiffness:c*m*m,damping:2*(n.dampingRatio??.2)*c*m}),this}rope(t,r,n={}){let{other:i,pa:o,pb:a}=this.endpoints(t,r,n.anchorA,n.anchorB),u=n.length??Math.hypot(a[0]-o[0],a[1]-o[1]);return this.joint(t,i,{type:"rope",anchorA:t.localAnchor(o),anchorB:i.localAnchor(a),length:u/this.pixelsPerMeter}),this}force(t,r){let n=this.pixelsPerMeter;return this.addForce(t,i=>[r.x===void 0?0:Ue(r.x,i,this.fps)/n,r.y===void 0?0:Ue(r.y,i,this.fps)/n]),this}field(t,r={}){let n=this.pixelsPerMeter;return this.addField((i,o)=>{let[a,u]=i.sim.position(),[l,c]=i.sim.velocity(),m=t({x:a*n,y:u*n,vx:l*n,vy:c*n,frame:o,body:i});return m?[m[0]/n,m[1]/n]:null},r.bodies),this}impulse(t,r,n){let i=this.pixelsPerMeter;return this.addImpulse(t,r,[n[0]/i,n[1]/i]),this}lerpRotation(t,r,n){return t+(r-t)*n}joint(t,r,n){this.assertOpen(),this.sim.addJoint(t.sim,r.sim,n)}anchorBody(t){return this.body({x:t[0]-.5,y:t[1]-.5,width:1,height:1},{type:"fixed",output:"none",sensor:!0})}endpoints(t,r,n,i){let o=n??t.center();if(Array.isArray(r)){let a=i??r;return{other:this.anchorBody(a),pa:o,pb:a}}return{other:r,pa:o,pb:i??r.center()}}};function nx(e,t){let r=e.type==="dynamic"?e.sim.mass():0,n=t.type==="dynamic"?t.sim.mass():0;return r>0&&n>0?r*n/(r+n):Math.max(r,n,.001)}function it(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function ix(e,t){let r=typeof e.id=="string"?` "${e.id}"`:"";if(typeof e.x!="number"||typeof e.y!="number")throw new Error(`Physics: layer${r} needs numeric \`x\` and \`y\` (absolute position) to become a body.`);let n=t.size?.[0]??(typeof e.width=="number"?e.width:void 0),i=t.size?.[1]??(typeof e.height=="number"?e.height:void 0);if((n===void 0||i===void 0)&&e.kind==="text"){let u=_e.measure(String(e.text??""),{fontFamily:String(e.fontFamily??"Inter"),fontSize:it(e.fontSize,48),fontWeight:e.fontWeight,letterSpacing:it(e.letterSpacing,0),lineHeight:typeof e.lineHeight=="number"?e.lineHeight:void 0});n??=u.width,i??=u.height}if(n===void 0||i===void 0||n<=0||i<=0)throw new Error(`Physics: layer${r} needs a numeric \`width\` and \`height\` (or the \`size\` option) to become a body.`);let o=it(e.scale,1);return{...{x:e.x,y:e.y,width:n,height:i,scale:o,anchorX:it(e.anchorX,.5),anchorY:it(e.anchorY,.5),rotation:it(e.rotation,0)},shape:Fp(ox(e,n,i,t.shape??"auto"),o)}}function ox(e,t,r,n){let o=e.kind==="shape"?String(e.shapeType??"rect"):"rect",a=it(e.borderRadius,it(e.cornerRadius,0)),u={kind:"box",hx:t/2,hy:r/2,radius:a};if(n==="box")return u;if(n==="circle"||n==="auto"&&o==="circle")return{kind:"ball",radius:Math.min(t,r)/2};if(n==="auto"&&o==="rect")return u;if(n==="hull"||n==="auto"){let l=ax(e,o,t,r);return l.length>=6?{kind:"hull",points:l}:u}return u}function ax(e,t,r,n){let i=t==="path"?String(e.d??""):Hu({shapeType:t,width:r,height:n,cornerRadius:it(e.cornerRadius,it(e.borderRadius,0)),polygonSides:e.polygonSides,starPoints:e.starPoints,starInnerRadiusRatio:e.starInnerRadiusRatio,arrowHeadWidth:e.arrowHeadWidth,arrowHeadLength:e.arrowHeadLength,arrowShaftWidth:e.arrowShaftWidth}),o=[];for(let a of Wu(i))o.push(a.p0.x-r/2,a.p0.y-n/2,a.p1.x-r/2,a.p1.y-n/2);return o}function Fp(e,t){switch(e.kind){case"ball":return{kind:"ball",radius:e.radius*t};case"box":return{kind:"box",hx:e.hx*t,hy:e.hy*t,radius:(e.radius??0)*t};case"hull":return{kind:"hull",points:e.points.map(r=>r*t)}}}function Lp(e,t){let r=e*Math.PI/180,n=(.5-t.anchorX)*t.width*t.scale,i=(.5-t.anchorY)*t.height*t.scale;return[n*Math.cos(r)-i*Math.sin(r),n*Math.sin(r)+i*Math.cos(r)]}function Ep(e,t,r,n){let[i,o]=Lp(r,n);return[e+n.anchorX*n.width+i,t+n.anchorY*n.height+o]}function sx(e,t,r,n){let[i,o]=Lp(r,n);return[e-i-n.anchorX*n.width,t-o-n.anchorY*n.height]}h();h();var Cn=class{constructor(t,r,n,i){this.node=t;this.pieces=r;this.intact=n;this.world=i}node;pieces;intact;world;brokeAt;get frame(){return this.brokeAt===void 0?void 0:this.world.startFrame+this.brokeAt}},ux=Number.MAX_SAFE_INTEGER,Xe=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t;function lx(e){let t=[Xe(e.x,0),Xe(e.y,0),Xe(e.z,0)],r=[Xe(e.rotateX,0),Xe(e.rotateY,0),Xe(e.rotateZ,Xe(e.rotation,0))],n=Xe(e.scale,1),i=[n*Xe(e.scaleX,1),n*Xe(e.scaleY,1),n*Xe(e.scaleZ,1)],o=u=>u*Math.PI/180,a=se.translate(...t);return a=se.multiply(a,se.rotateZ(o(r[2]))),a=se.multiply(a,se.rotateY(o(r[1]))),a=se.multiply(a,se.rotateX(o(r[0]))),a=se.multiply(a,se.scale(...i)),{position:t,rotation:r,scale:i,matrix:a}}var Bp=(e,t)=>[e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12],e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13],e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]],cx=["scale","scaleX","scaleY","scaleZ"];function eu(e,t){let r=e.animation?.tracks??[];return t.filter(n=>r.some(i=>i.prop===n))}function Ip(e){let t=eu(e,cx);if(!t.length)return;let r=typeof e.id=="string"?` "${e.id}"`:"";throw new Error(`Physics.fracture: layer${r} animates ${t.join(", ")}; rigid pieces cannot change size. Keep a fractured layer's scale still (position and rotation may animate).`)}function mx(e,t){let r=e,n=o=>a=>Xn(r,o,a,t),i=o=>eu(e,["rotateZ"]).length||typeof e.rotateZ=="number"?Xn(r,"rotateZ",o,t):Xn(r,"rotation",o,t);return{x:n("x"),y:n("y"),z:n("z"),rotateX:n("rotateX"),rotateY:n("rotateY"),rotateZ:i}}var dx=["x","y","z","rotateX","rotateY","rotateZ","rotation"];function jp(e,t,r){let n=t,i=n.modelData;if(!i?.meshes?.length){let b=typeof n.id=="string"?` "${n.id}"`:"";throw new Error(`Physics.fracture: layer${b} has no mesh. Fracture a Layer3D primitive, extruded text, or a model node that carries modelData.`)}Ip(n);let o=lx(n),a=se.invert(o.matrix)??se.identity(),u={cells:Math.max(2,Math.min(256,Math.round(r.cells??48))),seed:r.seed??1,...r.impactPoint&&{impactPoint:Bp(a,r.impactPoint)},...r.interiorColor&&{interiorColor:r.interiorColor},...r.interiorRoughness!==void 0&&{interiorRoughness:r.interiorRoughness}},{cells:l}=qu(i,u);n.fracture3d=u;let c=eu(n,dx).length>0,m=e.body(t,c?{type:"kinematic",output:"none",follow:mx(n,e.fps)}:{type:"fixed",output:"none"}),d=l.map(b=>e.shapedBody(void 0,Bp(o.matrix,b.centroid),o.rotation,{kind:"hull",points:b.hull.map((g,y)=>g*o.scale[y%3]*.97)},{type:"dynamic",startFrame:ux,output:"none",density:r.density,friction:r.friction,restitution:r.restitution??.2})),p=new Cn(t,d,m,e),f=i.bounds.boundingSphereRadius*Math.max(...o.scale);return e.onStep((b,g)=>{if(p.brokeAt!==void 0)return;let y=r.fractureFrame??"onImpact",T=g.find(([x,A])=>x===m&&A.type==="dynamic"||A===m&&x.type==="dynamic"),M=T?T[0]===m?T[1]:T[0]:void 0;(y==="onImpact"?M:b>=y-e.startFrame)&&(p.brokeAt=b,m.sim.setEnabled(!1),fx(e,d,r,f,m,o,M,b))}),e.onSimulated(()=>{Ip(n),u.track=hx(d,e.startFrame+e.frames)}),p}function px(e,t){let r=e.pixelsPerMeter;return{position:t.sim.position().map(n=>n*r),rotation:t.sim.rotation(),velocity:t.sim.velocity().map(n=>n*r),spin:t.sim.angularVelocity()}}function fx(e,t,r,n,i,o,a,u){let l=e.pixelsPerMeter,c=px(e,i),m=to(...o.rotation),d=[-m[0],-m[1],-m[2],m[3]],p=a?.sim.position().map(v=>v*l),f=r.momentumTransfer??.35,b=[0,0,0];if(a){let v=e.startFrame+u-1,x=a.recording;b[0]=x.channel("vx")[v]??0,b[1]=x.channel("vy")[v]??0,b[2]=x.channel("vz")[v]??0,a.sim.setVelocity(b.map(A=>A*(1-f)/l),a.sim.angularVelocity())}let g=r.impactPoint??p??c.position,y=r.explosionSpeed??0,T=r.spin??y/3,M=$u((r.seed??1)*7717+3);for(let v of t){let x=v.center(),A=eo([x[0]-o.position[0],x[1]-o.position[1],x[2]-o.position[2]],d),w=eo(A,c.rotation),R=[c.position[0]+w[0],c.position[1]+w[1],c.position[2]+w[2]],N=c.spin,V=[c.velocity[0]+N[1]*w[2]-N[2]*w[1],c.velocity[1]+N[2]*w[0]-N[0]*w[2],c.velocity[2]+N[0]*w[1]-N[1]*w[0]],$=[R[0]-g[0],R[1]-g[1],R[2]-g[2]],I=Math.hypot(...$)||1,E=1/(1+(I/Math.max(1,n))**2),k=$.map((U,j)=>V[j]+U/I*y*E+b[j]*f*E),P=[M()-.5,M()-.5,M()-.5],G=Math.hypot(...P)||1,X=P.map((U,j)=>U/G*T*(.5+M())+N[j]*180/Math.PI);v.wake(u,k,X,{position:R,rotation:c.rotation})}}function hx(e,t){let r=e.map(o=>["x","y","z","qx","qy","qz","qw"].map(a=>o.recording.channel(a))),n=new Array(t*e.length*7),i=0;for(let o=0;o<t;o++)for(let a of r)for(let u=0;u<7;u++){let l=a[u][o]??0;n[i++]=u<3?Math.round(l*1e5)/1e5:Math.round(l*1e7)/1e7}return n}var Ze=Math.PI/180;function to(e,t,r){let n=u=>u*Ze/2,i=[Math.sin(n(e)),0,0,Math.cos(n(e))],o=[0,Math.sin(n(t)),0,Math.cos(n(t))],a=[0,0,Math.sin(n(r)),Math.cos(n(r))];return ro(ro(a,o),i)}function ro(e,t){let[r,n,i,o]=e,[a,u,l,c]=t;return[o*a+r*c+n*l-i*u,o*u-r*l+n*c+i*a,o*l+r*u-n*a+i*c,o*c-r*a-n*u-i*l]}function gx(e,t){let[r,n,i,o]=e,a=1-2*(n*n+i*i),u=2*(r*n+o*i),l=2*(r*i-o*n),c=2*(n*i+o*r),m=1-2*(r*r+n*n),d=2*(r*n-o*i),p=1-2*(r*r+i*i),f=Math.max(-1,Math.min(1,-l)),b;if(Math.abs(f)>.999999){let A=Math.asin(f),w=t?t[0]*Ze:0,R=Math.atan2(-d,p)+(f>0?w:-w);b=[w,A,R]}else b=[Math.atan2(c,m),Math.asin(f),Math.atan2(u,a)];let g=[b[0]/Ze,b[1]/Ze,b[2]/Ze];if(!t)return g;let y=[g[0]+180,180-g[1],g[2]+180],T=A=>[er(t[0],A[0]),er(t[1],A[1]),er(t[2],A[2])],M=T(g),v=T(y),x=A=>Math.abs(A[0]-t[0])+Math.abs(A[1]-t[1])+Math.abs(A[2]-t[2]);return x(M)<=x(v)?M:v}var Dn=class{constructor(t,r,n,i,o,a,u){this.world=t;this.type=n;this.layer=i;this.start=o;this.options=a;this.sim=r,this.recording=u}world;type;layer;start;options;collisions=[];recording;sim;get startFrame(){return this.wokeAt??Math.max(0,Math.round(this.options.startFrame??0))}wokeAt;wake(t,r,n,i){this.wokeAt=t;let o=this.world.pixelsPerMeter;this.sim.setEnabled(!0),i&&this.sim.setPose([i.position[0]/o,i.position[1]/o,i.position[2]/o],i.rotation),this.sim.setVelocity([r[0]/o,r[1]/o,r[2]/o],[n[0]*Ze,n[1]*Ze,n[2]*Ze])}get gravityScale(){return this.options.gravityScale??1}get output(){return this.options.output}get x(){return this.recording.signal("x")}get y(){return this.recording.signal("y")}get z(){return this.recording.signal("z")}get rotateX(){return this.recording.signal("rotateX")}get rotateY(){return this.recording.signal("rotateY")}get rotateZ(){return this.recording.signal("rotateZ")}get vx(){return this.recording.signal("vx")}get vy(){return this.recording.signal("vy")}get vz(){return this.recording.signal("vz")}get speed(){return this.recording.signal("speed")}get impact(){return this.recording.signal("impact")}get sleeping(){return this.recording.signal("sleeping")}kinematicTarget(t){let r=this.options.follow;if(this.type!=="kinematic"||!r)return;let n=this.world.fps,i=(l,c)=>l===void 0?c:Ue(l,t,n),o=this.start.position,a=this.start.rotation,u=this.world.pixelsPerMeter;return{position:[i(r.x,o[0])/u,i(r.y,o[1])/u,i(r.z,o[2])/u],rotation:to(i(r.rotateX,a[0]),i(r.rotateY,a[1]),i(r.rotateZ,a[2]))}}record(t,r){let n=this.world.pixelsPerMeter,i=this.recording,[o,a,u]=this.sim.position();i.channel("x")[t]=o*n,i.channel("y")[t]=a*n,i.channel("z")[t]=u*n;let l=i.channel("rotateX"),c=i.channel("rotateY"),m=i.channel("rotateZ"),d=r<0?this.start.rotation:[l[r],c[r],m[r]],p=this.sim.rotation();i.channel("qx")[t]=p[0],i.channel("qy")[t]=p[1],i.channel("qz")[t]=p[2],i.channel("qw")[t]=p[3];let f=gx(p,d);l[t]=f[0],c[t]=f[1],m[t]=f[2];let[b,g,y]=this.sim.velocity();i.channel("vx")[t]=b*n,i.channel("vy")[t]=g*n,i.channel("vz")[t]=y*n,i.channel("speed")[t]=Math.hypot(b,g,y)*n,i.channel("sleeping")[t]=this.sim.sleeping()?1:0}boundChannels(){let t=[["x","x"],["y","y"],["z","z"]];return this.options.lockRotation!==!0&&t.push(["rotateX","rotateX"],["rotateY","rotateY"],["rotateZ","rotateZ"]),t}localAnchor(t){if(!t)return[0,0,0];let r=this.world.pixelsPerMeter,n=this.sim.position(),[i,o,a,u]=this.sim.rotation(),l=[t[0]/r-n[0],t[1]/r-n[1],t[2]/r-n[2]];return eo(l,[-i,-o,-a,u])}center(){let t=this.world.pixelsPerMeter,[r,n,i]=this.sim.position();return[r*t,n*t,i*t]}};function eo(e,t){let r=ro(ro(t,[e[0],e[1],e[2],0]),[-t[0],-t[1],-t[2],t[3]]);return[r[0],r[1],r[2]]}var Lr=class extends Nr{constructor(t,r){let n=r.pixelsPerMeter??100,i=r.gravity??2400,o=typeof i=="number"?[0,i/n,0]:[i[0]/n,i[1]/n,i[2]/n];super(t.createWorld3D(o),o,r)}body(t,r={}){this.assertOpen();let i=typeof t.kind=="string"?t:void 0,o=t,a=[te(r.x??o.x,0),te(r.y??o.y,0),te(r.z??o.z,0)],u=[te(r.rotateX??o.rotateX,0),te(r.rotateY??o.rotateY,0),te(r.rotateZ??o.rotateZ,0)];return this.shapedBody(i,a,u,bx(o,r),r)}shapedBody(t,r,n,i,o){this.assertOpen();let a=this.pixelsPerMeter,u=o.type??"dynamic",l=o.velocity??[0,0,0],c=o.angularVelocity??[0,0,0],m={type:u,position:[r[0]/a,r[1]/a,r[2]/a],rotation:to(n[0],n[1],n[2]),velocity:[l[0]/a,l[1]/a,l[2]/a],angularVelocity:[c[0]*Ze,c[1]*Ze,c[2]*Ze],linearDamping:o.linearDamping??0,angularDamping:o.angularDamping??0,gravityScale:o.gravityScale??1,lockRotation:o.lockRotation===!0,...typeof o.lockRotation=="object"&&{enabledRotations:[!o.lockRotation.x,!o.lockRotation.y,!o.lockRotation.z]},ccd:o.ccd??!1,enabled:!0,sensor:o.sensor??!1,density:o.density??1,friction:o.friction??.6,restitution:o.restitution??.3,shape:Sx(i,1/a)},d=this.sim.addBody(m),p=new Dn(this,d,u,t,{position:r,rotation:n},o,this.newRecording()),f=p.kinematicTarget(this.startFrame);return f&&d.setPose(f.position,f.rotation),this.addBody(p)}onStep(t){this.assertOpen(),this.stepHooks.push(t)}onSimulated(t){this.assertOpen(),this.simulatedHooks.push(t)}fracture(t,r={}){return jp(this,t,r)}ground(t){return this.body({x:0,y:t.y+2e3/2,z:0,width:1e6,height:2e3,depth:1e6},{type:"fixed",friction:t.friction,restitution:t.restitution??.2})}walls(t){let{width:r,height:n,depth:i}=t,[o,a,u]=[t.x??0,t.y??0,t.z??0],l=t.thickness??400,c={type:"fixed",friction:t.friction,restitution:t.restitution??.2},m=n*4,d=a+n/2-m/2;return[this.body({x:o,y:a+n/2+l/2,z:u,width:r+2*l,height:l,depth:i+2*l},c),this.body({x:o-r/2-l/2,y:d,z:u,width:l,height:m,depth:i+2*l},c),this.body({x:o+r/2+l/2,y:d,z:u,width:l,height:m,depth:i+2*l},c),this.body({x:o,y:d,z:u-i/2-l/2,width:r,height:m,depth:l},c),this.body({x:o,y:d,z:u+i/2+l/2,width:r,height:m,depth:l},c)]}pin(t,r){let n=r??t.center(),i=this.anchorBody(n);return this.joint(t,i,{type:"spherical",anchorA:t.localAnchor(n),anchorB:[0,0,0]}),this}hinge(t,r,n,i=[0,0,1]){return this.joint(t,r,{type:"revolute",anchorA:t.localAnchor(n),anchorB:r.localAnchor(n),axis:i}),this}weld(t,r){return this.joint(t,r,{type:"fixed",anchorA:[0,0,0],anchorB:r.localAnchor(t.center())}),this}spring(t,r,n={}){let{other:i,pa:o,pb:a}=this.endpoints(t,r,n.anchorA,n.anchorB),u=this.pixelsPerMeter,l=(n.length??zp(o,a))/u,c=t.type==="dynamic"?t.sim.mass():0,m=i.type==="dynamic"?i.sim.mass():0,d=c>0&&m>0?c*m/(c+m):Math.max(c,m,.001),p=2*Math.PI*(n.frequency??2);return this.joint(t,i,{type:"spring",anchorA:t.localAnchor(o),anchorB:i.localAnchor(a),restLength:l,stiffness:d*p*p,damping:2*(n.dampingRatio??.2)*d*p}),this}rope(t,r,n={}){let{other:i,pa:o,pb:a}=this.endpoints(t,r,n.anchorA,n.anchorB);return this.joint(t,i,{type:"rope",anchorA:t.localAnchor(o),anchorB:i.localAnchor(a),length:(n.length??zp(o,a))/this.pixelsPerMeter}),this}force(t,r){let n=this.pixelsPerMeter,i=(o,a)=>o===void 0?0:Ue(o,a,this.fps)/n;return this.addForce(t,o=>[i(r.x,o),i(r.y,o),i(r.z,o)]),this}field(t,r={}){let n=this.pixelsPerMeter;return this.addField((i,o)=>{let[a,u,l]=i.sim.position(),[c,m,d]=i.sim.velocity(),p=t({x:a*n,y:u*n,z:l*n,vx:c*n,vy:m*n,vz:d*n,frame:o,body:i});return p?[p[0]/n,p[1]/n,p[2]/n]:null},r.bodies),this}impulse(t,r,n){let i=this.pixelsPerMeter;return this.addImpulse(t,r,[n[0]/i,n[1]/i,n[2]/i]),this}lerpRotation(t,r,n){let i=t[0]*r[0]+t[1]*r[1]+t[2]*r[2]+t[3]*r[3]<0?-1:1,o=t.map((u,l)=>u+(r[l]*i-u)*n),a=Math.hypot(...o)||1;return o.map(u=>u/a)}joint(t,r,n){this.assertOpen(),this.sim.addJoint(t.sim,r.sim,n)}anchorBody(t){return this.body({x:t[0],y:t[1],z:t[2],width:1,height:1,depth:1},{type:"fixed",output:"none",sensor:!0})}endpoints(t,r,n,i){let o=n??t.center();if(Array.isArray(r)){let a=i??r;return{other:this.anchorBody(a),pa:o,pb:a}}return{other:r,pa:o,pb:i??r.center()}}};function zp(e,t){return Math.hypot(t[0]-e[0],t[1]-e[1],t[2]-e[2])}function te(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function bx(e,t){let r=typeof e.id=="string"?` "${e.id}"`:"",n=te(e.scale,1),i=[n*te(e.scaleX,1),n*te(e.scaleY,1),n*te(e.scaleZ,1)],o=i[0]===i[1]&&i[1]===i[2],a=e.primitive3d??{},u=t.shape??"auto",l=()=>{let y=xx(e.modelData);if(y)return{kind:"hull",points:y.map((T,M)=>T*i[M%3])}};if(u==="mesh"||u==="auto"&&(t.type??"dynamic")!=="dynamic"&&(a.type==="terrain"||a.type==="sdf")){let y=yx(e.modelData,i);if(y)return y}if(t.size||u==="box"){let[y,T,M]=t.size??tu(e,a)??[0,0,0];if(y>0&&T>0&&M>0)return{kind:"box",hx:y*i[0]/2,hy:T*i[1]/2,hz:M*i[2]/2,radius:a.type==="roundedBox"?te(a.radius,0)*Math.min(...i):0}}if(u==="hull"){let y=l();if(y)return y}if((u==="sphere"||u==="auto"&&(a.type==="sphere"||a.type==="polyhedron"&&a.shape==="icosphere"))&&(o||u==="sphere")){let y=te(a.radius,0)||Math.max(...tu(e,a)??[0])/2;if(y>0)return{kind:"ball",radius:y*Math.max(...i)}}let d=te(a.radiusTop,te(a.radius,0)),p=te(a.radiusBottom,te(a.radius,0));if((u==="cylinder"||u==="auto"&&a.type==="cylinder")&&d===p&&d>0&&i[0]===i[2])return{kind:"cylinder",halfHeight:te(a.height,0)*i[1]/2,radius:d*i[0]};if(u==="auto"&&a.type==="roundedBox"&&(a.taper??1)===1){let[y,T,M]=[te(a.width,0),te(a.height,0),te(a.depth,0)];return{kind:"box",hx:y*i[0]/2,hy:T*i[1]/2,hz:M*i[2]/2,radius:te(a.radius,0)*Math.min(...i)}}let b=l();if(b)return b;let g=tu(e,a);if(g)return{kind:"box",hx:g[0]*i[0]/2,hy:g[1]*i[1]/2,hz:g[2]*i[2]/2};throw new Error(`Physics: layer${r} has no mesh or size to build a 3D collider from; pass \`size: [w, h, d]\`.`)}function tu(e,t){if(t.type==="roundedBox")return[te(t.width,0),te(t.height,0),te(t.depth,0)];if(t.type==="sphere"||t.type==="polyhedron"){let r=te(t.radius,50)*2;return[r,r,r]}if(t.type==="capsule"){let r=te(t.radius,30),n=te(t.length,60);return[r*2,n+r*2,r*2]}if(t.type==="torus"){let r=te(t.radius,60),n=te(t.tube,20);return[(r+n)*2,(r+n)*2,n*2]}if(t.type==="ring"){let r=te(t.outerRadius,60),n=Math.max(2,te(t.depth,0));return[r*2,r*2,n]}if(t.type==="cylinder"){let r=Math.max(te(t.radiusTop,te(t.radius,0)),te(t.radiusBottom,te(t.radius,0)))*2;return[r,te(t.height,0),r]}if(typeof e.width=="number"&&typeof e.height=="number"&&typeof e.depth=="number")return[e.width,e.height,e.depth]}function yx(e,t){let r=e?.meshes;if(!r?.length)return;let n=[],i=[];for(let o of r){if(!o.positions||!o.indices||o.topology&&o.topology!=="triangle-list")continue;let a=n.length/3;for(let u=0;u<o.positions.length;u++)n.push(o.positions[u]*t[u%3]);for(let u=0;u<o.indices.length;u++)i.push(o.indices[u]+a)}return i.length>=3?{kind:"trimesh",vertices:n,indices:i}:void 0}function xx(e){let t=e?.meshes;if(!t?.length)return;let r=0;for(let a of t)r+=(a.positions?.length??0)/3;if(r<4)return;let n=Math.max(1,Math.floor(r/4096)),i=[],o=0;for(let a of t){let u=a.positions;if(u)for(let l=0;l<u.length;l+=3,o++)o%n===0&&i.push(u[l],u[l+1],u[l+2])}return i}function Sx(e,t){switch(e.kind){case"ball":return{kind:"ball",radius:e.radius*t};case"box":return{kind:"box",hx:e.hx*t,hy:e.hy*t,hz:e.hz*t,radius:(e.radius??0)*t};case"cylinder":return{kind:"cylinder",halfHeight:e.halfHeight*t,radius:e.radius*t};case"hull":return{kind:"hull",points:e.points.map(r=>r*t)};case"trimesh":return{kind:"trimesh",vertices:e.vertices.map(r=>r*t),indices:e.indices}}}var wx={async world2d(e){return new Fr(await Js(2),e)},async world3d(e){return new Lr(await Js(3),e)}};h();var xe=(...e)=>e,vx={pixelArt:(e={})=>xe(new ur({palette:e.palette??"pico8",pixelSize:e.pixelSize??6,dither:.4})),gameBoy:(e={})=>xe(new ur({palette:"gameboy",pixelSize:e.pixelSize??4,dither:.6})),teletext:(e={})=>xe(new ur({palette:"teletext",pixelSize:e.pixelSize??10})),ledWall:(e={})=>xe(new Yo({size:e.size??14,shape:"circle",gap:.18})),ascii:(e={})=>xe(new jo({cellSize:e.cellSize??10,colorMode:e.matrix?"green":"source",bg:e.matrix?"#020a04":"#0b0b0b"})),oneBit:(e={})=>xe(new Uo({mode:"bayer",scale:e.scale??2,dark:e.dark??"#111111",light:e.light??"#f2efe6"})),risograph:(e={})=>{let t=e.inkA??"#1d3fbb",r=e.inkB??"#ff5fa2",n=e.paper??"#f4efe4";return xe(new Lt({stops:[{position:0,color:t},{position:.55,color:r},{position:1,color:n}]}),new ur({palette:"custom",colors:[t,r,n],dither:.8,pixelSize:2}),new lt({strength:.2}))},cartoon:(e={})=>xe(new Qn({levels:e.levels??4,edgeColor:e.ink??"#111111",saturation:1.3})),comic:(e={})=>xe(new Qn({levels:4,edgeWidth:1.5,saturation:1.4}),new Gr({frequency:e.dotFrequency??70,opacity:.35})),thermal:()=>xe(new Lt({stops:[{position:0,color:"#000010"},{position:.25,color:"#3b0a7a"},{position:.5,color:"#c4205f"},{position:.75,color:"#ff9a1f"},{position:1,color:"#fffbe0"}]})),vhs:(e={})=>xe(new $r({tracking:e.tracking??.5,chroma:4,curvature:.04,scanlines:.25,mask:.05,noise:.15}),new Kn({amount:3})),crt:(e={})=>xe(new $r({curvature:e.curvature??.15,scanlines:.5,mask:.35})),glitch:(e={})=>xe(new Kn({amount:e.amount??18}),new $r({tracking:1,chroma:6,curvature:0,scanlines:.1,mask:0,vignette:0})),oilPainting:(e={})=>xe(new qn({style:"oil",radius:e.brush??5})),watercolor:(e={})=>xe(new qn({style:"watercolor",radius:e.brush??6,paper:.5})),topographic:(e={})=>xe(new Vo({levels:e.levels??16,fill:"flat",lineColor:e.ink??"#5a3a1a",fillColor:e.paper??"#f3ead8"})),kaleidoscope:(e={})=>xe(new Go({segments:e.segments??8,rotation:e.rotation??0})),opArt:(e={})=>xe(new Ho({pattern:e.pattern??"stripes",frequency:e.frequency??60})),holographic:(e={})=>xe(new $o({strength:e.strength??.7,shift:e.shift??0})),noir:()=>xe(new Lt({stops:[{position:0,color:"#000000"},{position:.55,color:"#8a8a8a"},{position:1,color:"#ffffff"}]}),new lt({strength:.35}),new lr({strength:.6})),film:()=>xe(new lt({strength:.25}),new lr({strength:.35}))};h();var Pf=ut(If(),1),po=ut(Po(),1);$n();var bu=ut(Vp(),1);h();h();var rf=ut(Po(),1);h();var nu=new TextEncoder,kx={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Px=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),io=class{constructor({accessKeyId:t,secretAccessKey:r,sessionToken:n,service:i,region:o,cache:a,retries:u,initRetryMs:l}){if(t==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=t,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=o,this.cache=a||new Map,this.retries=u??10,this.initRetryMs=l||50}async sign(t,r){if(t instanceof Request){let{method:o,url:a,headers:u,body:l}=t;r=Object.assign({method:o,url:a,headers:u},r),r.body==null&&u.has("Content-Type")&&(r.body=l!=null&&u.has("X-Amz-Content-Sha256")?l:await t.clone().arrayBuffer()),t=a}let n=new iu(Object.assign({url:t.toString()},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());delete i.aws;try{return new Request(i.url.toString(),i)}catch(o){if(o instanceof TypeError)return new Request(i.url.toString(),Object.assign({duplex:"half"},i));throw o}}async fetch(t,r){for(let n=0;n<=this.retries;n++){let i=fetch(await this.sign(t,r));if(n===this.retries)return i;let o=await i;if(o.status<500&&o.status!==429)return o;await new Promise(a=>setTimeout(a,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Error("An unknown error occurred, ensure retries is not negative")}},iu=class{constructor({method:t,url:r,headers:n,body:i,accessKeyId:o,secretAccessKey:a,sessionToken:u,service:l,region:c,cache:m,datetime:d,signQuery:p,appendSessionToken:f,allHeaders:b,singleEncode:g}){if(r==null)throw new TypeError("url is a required option");if(o==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=t||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=o,this.secretAccessKey=a,this.sessionToken=u;let y,T;(!l||!c)&&([y,T]=Tx(this.url,this.headers)),this.service=l||y||"",this.region=c||T||"us-east-1",this.cache=m||new Map,this.datetime=d||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=p,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let M=this.signQuery?this.url.searchParams:this.headers;if(M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&M.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(x=>b||!Px.has(x)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(x=>x+":"+(x==="host"?this.url.host:(this.headers.get(x)||"").replace(/\s+/g," "))).join(`
|
|
612
|
+
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!M.has("X-Amz-Expires")&&M.set("X-Amz-Expires","86400"),M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");g||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Gp(this.encodedPath);let v=new Set;this.encodedSearch=[...this.url.searchParams].filter(([x])=>{if(!x)return!1;if(this.service==="s3"){if(v.has(x))return!1;v.add(x)}return!0}).map(x=>x.map(A=>Gp(encodeURIComponent(A)))).sort(([x,A],[w,R])=>x<w?-1:x>w?1:A<R?-1:A>R?1:0).map(x=>x.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let t=this.datetime.slice(0,8),r=[this.secretAccessKey,t,this.region,this.service].join(),n=this.cache.get(r);if(!n){let i=await Rn("AWS4"+this.secretAccessKey,t),o=await Rn(i,this.region),a=await Rn(o,this.service);n=await Rn(a,"aws4_request"),this.cache.set(r,n)}return ru(await Rn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,ru(await Up(await this.canonicalString()))].join(`
|
|
613
|
+
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
614
|
+
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
615
|
+
`)}async hexBodyHash(){let t=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(t==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");t=ru(await Up(this.body||""))}return t}};async function Rn(e,t){let r=await crypto.subtle.importKey("raw",typeof e=="string"?nu.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,nu.encode(t))}async function Up(e){return crypto.subtle.digest("SHA-256",typeof e=="string"?nu.encode(e):e)}var $p=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function ru(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let i=t[n];r+=$p[i>>>4&15],r+=$p[i&15]}return r}function Gp(e){return e.replace(/[!'()*]/g,t=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function Tx(e,t){let{hostname:r,pathname:n}=e;if(r.endsWith(".on.aws")){let u=r.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return u!=null?["lambda",u[1]||""]:["",""]}if(r.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(r.endsWith(".backblazeb2.com")){let u=r.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return u!=null?["s3",u[1]||""]:["",""]}let i=r.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),o=i&&i[1]||"",a=i&&i[2];if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",o="s3";else if(o==="iot")r.startsWith("iot.")?o="execute-api":r.startsWith("data.jobs.iot.")?o="iot-jobs-data":o=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(o==="autoscaling"){let u=(t.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?o="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(o="autoscaling-plans")}else a==null&&o.startsWith("s3-")?(a=o.slice(3).replace(/^fips-|^external-1/,""),o="s3"):o.endsWith("-fips")?o=o.slice(0,-5):a&&/-\d$/.test(o)&&!/-\d$/.test(a)&&([o,a]=[a,o]);return[kx[o]||o,a||""]}h();var Zp=ut(Po(),1);var qp=ut(Hp(),1),Mx=ut(Xp(),1);var Ax={mp4:"video/mp4",m4v:"video/mp4",mov:"video/quicktime",webm:"video/webm",mkv:"video/x-matroska",mp3:"audio/mpeg",m4a:"audio/mp4",aac:"audio/aac",wav:"audio/wav",flac:"audio/flac",ogg:"audio/ogg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",avif:"image/avif",gif:"image/gif",svg:"image/svg+xml",json:"application/json",lottie:"application/zip",glb:"model/gltf-binary",gltf:"model/gltf+json",ttf:"font/ttf",otf:"font/otf",woff2:"font/woff2",cube:"text/plain",srt:"text/plain",vtt:"text/vtt"};function Kp(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return Ax[t]??"application/octet-stream"}h();var Cx=/^[A-Za-z0-9][\w-]{0,63}$/,Dx=/^[0-9a-f]{64}$/,yt="framefields.json",$e=class extends Error{name="ManifestError"};function Qp(e){if(!On(e)||!On(e.remotes))throw new $e(`${yt}: "storage" needs "remotes", e.g. { "remotes": { "media": { "endpoint": "https://<account>.r2.cloudflarestorage.com", "bucket": "films" } } }`);let t={};for(let[n,i]of Object.entries(e.remotes))t[n]=Rx(n,i);let r=Object.keys(t);if(r.length===0)throw new $e(`${yt}: "storage.remotes" is empty`);if(e.default!==void 0&&!r.includes(e.default))throw new $e(`${yt}: "storage.default" must name a remote (${r.join(", ")})`);return{...typeof e.default=="string"&&{default:e.default},remotes:t}}function Rx(e,t){let r=i=>{throw new $e(`${yt}: storage.remotes.${e} ${i}`)};Cx.test(e)||r("has an invalid name: use letters, digits, - and _ (at most 64)"),On(t)||r("must be an object with an endpoint and a bucket");let n=t;return ou(n.endpoint)||r('needs "endpoint": the S3 API URL, e.g. "https://<account>.r2.cloudflarestorage.com"'),(typeof n.bucket!="string"||!/^[a-z0-9][a-z0-9.-]{1,62}$/.test(n.bucket))&&r('needs "bucket": the bucket name'),n.region!==void 0&&typeof n.region!="string"&&r('"region" must be a string'),n.prefix!==void 0&&(typeof n.prefix!="string"||n.prefix.startsWith("/")||n.prefix.split("/").includes(".."))&&r('"prefix" must be a key prefix such as "films/launch/"'),n.publicUrl!==void 0&&!ou(n.publicUrl)&&r('"publicUrl" must be an http(s) URL, e.g. "https://media.example.com"'),{endpoint:n.endpoint,bucket:n.bucket,...n.region!==void 0&&{region:n.region},...typeof n.prefix=="string"&&n.prefix&&{prefix:Fx(n.prefix)},...n.publicUrl!==void 0&&{publicUrl:n.publicUrl}}}function Jp(e,t){if(!On(e))throw new $e(`${yt}: "assets" must map project paths to { "sha256", "size" }`);let r={};for(let[n,i]of Object.entries(e)){let o=u=>{throw new $e(`${yt}: assets["${n}"] ${u}`)};Nx(n)||o("must be a path inside the project, e.g. assets/footage/intro.mp4"),On(i)||o('must be { "sha256", "size" }');let a=i;(typeof a.sha256!="string"||!Dx.test(a.sha256))&&o('needs "sha256": 64 lowercase hex digits'),(typeof a.size!="number"||!Number.isSafeInteger(a.size)||a.size<0)&&o('needs "size" in bytes'),a.url!==void 0&&!ou(a.url)&&o('"url" must be an http(s) URL'),a.remote!==void 0?(typeof a.remote!="string"||!t?.remotes[a.remote])&&o('"remote" must name a remote in "storage.remotes"'):a.url===void 0&&!t&&o('needs a "url", or a "storage" section with a remote to hold it'),r[n]={sha256:a.sha256,size:a.size,...a.remote!==void 0&&{remote:a.remote},...a.url!==void 0&&{url:a.url}}}return r}function au(e,t){let r=Object.keys(e?.remotes??{}),n=t??e?.default??(r.length===1?r[0]:void 0);if(!e||r.length===0)throw new $e(`${yt} has no "storage" remotes: add one (an R2 or S3 bucket) first`);if(!n)throw new $e(`${yt}: name the remote (${r.join(", ")}), or set "storage.default"`);let i=e.remotes[n];if(!i)throw new $e(`${yt}: no remote named "${n}" (${r.join(", ")})`);return{name:n,remote:i}}function su(e,t=""){return`${t}sha256/${e.slice(0,2)}/${e}`}function Ox(e,t){if(e.publicUrl)return`${e.publicUrl.replace(/\/+$/,"")}/${su(t,e.prefix)}`}function ef(e,t,r){let n=r?.[e.sha256];if(n)return n;if(e.url)return e.url;if(t)return Ox(au(t,e.remote).remote,e.sha256)}function Nx(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").some(t=>t===""||t==="."||t==="..")}function Fx(e){return e.endsWith("/")?e:`${e}/`}function ou(e){if(typeof e!="string")return!1;try{let{protocol:t}=new URL(e);return t==="https:"||t==="http:"}catch{return!1}}function On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nf(e,t=S.env){let r=`FRAMEFIELDS_STORAGE_${e.toUpperCase().replace(/-/g,"_")}`,n=t[`${r}_ACCESS_KEY_ID`],i=t[`${r}_SECRET_ACCESS_KEY`];if(n&&i)return{accessKeyId:n,secretAccessKey:i};let o=t.AWS_ACCESS_KEY_ID,a=t.AWS_SECRET_ACCESS_KEY;if(!(!o||!a))return{accessKeyId:o,secretAccessKey:a,...t.AWS_SESSION_TOKEN&&{sessionToken:t.AWS_SESSION_TOKEN}}}var Nn=class extends Error{constructor(r,n){super(r);this.status=n}status;name="StorageError"},uu=1024*1024,Lx="public, max-age=31536000, immutable",so=class{constructor(t,r,n={}){this.remote=t;this.options=n;this.aws=new io({...r,service:"s3",region:t.region??"auto",retries:3}),this.fetch=n.fetch??fetch}remote;options;aws;fetch;keyFor(t){return su(t,this.remote.prefix)}async has(t,r){let n=await this.send(this.keyFor(t),{method:"HEAD"});if(n.status===404)return!1;if(!n.ok)throw await this.failure("HEAD",n);return Number(n.headers.get("content-length"))===r}async upload(t,r,n){let i=this.keyFor(r.sha256),o={"content-type":Kp(t),"cache-control":Lx},a=this.options.multipartThreshold??64*uu;if(r.size<=a){let u=await bo(t);try{let l=await u.readFile();await this.put(i,l,r.sha256,o)}finally{await u.close()}n?.({sent:r.size,total:r.size});return}await this.uploadParts(t,i,r.size,o,n)}async presign(t,r=86400){let n=new URL(this.url(this.keyFor(t)));return n.searchParams.set("X-Amz-Expires",String(Math.min(r,604800))),(await this.aws.sign(n,{method:"GET",aws:{signQuery:!0}})).url}async put(t,r,n,i,o=""){let a=await this.send(t,{method:"PUT",body:r,headers:{...i,"x-amz-content-sha256":n},query:o});if(!a.ok)throw await this.failure("PUT",a);return a}async uploadParts(t,r,n,i,o){let a=Math.max(this.options.partSize??16*uu,Math.ceil(n/1e4),5*uu),u=await this.send(r,{method:"POST",query:"uploads=",headers:i});if(!u.ok)throw await this.failure("CreateMultipartUpload",u);let l=/<UploadId>([^<]+)<\/UploadId>/.exec(await u.text())?.[1];if(!l)throw new Nn("CreateMultipartUpload returned no UploadId");let c=encodeURIComponent(l),m=Math.ceil(n/a),d=new Array(m),p=await bo(t),f=0,b=0,g=async()=>{for(;f<m;){let y=f++,T=Math.min(a,n-y*a),M=Buffer.alloc(T);await p.read(M,0,T,y*a);let v=(0,rf.createHash)("sha256").update(M).digest("hex"),x=await this.put(r,M,v,{},`partNumber=${y+1}&uploadId=${c}`);d[y]=x.headers.get("etag")??"",b+=T,o?.({sent:b,total:n})}};try{await Promise.all(Array.from({length:Math.min(this.options.concurrency??4,m)},g));let y=`<CompleteMultipartUpload>${d.map((v,x)=>`<Part><PartNumber>${x+1}</PartNumber><ETag>${Ex(v)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`,T=await this.send(r,{method:"POST",query:`uploadId=${c}`,body:y,headers:{"content-type":"application/xml"}}),M=await T.text();if(!T.ok||M.includes("<Error>"))throw new Nn(`CompleteMultipartUpload failed (${T.status}): ${tf(M)}`,T.status)}catch(y){throw await this.send(r,{method:"DELETE",query:`uploadId=${c}`}).catch(()=>{}),y}finally{await p.close()}}url(t,r=""){let n=this.remote.endpoint.replace(/\/+$/,""),i=t.split("/").map(encodeURIComponent).join("/");return`${n}/${this.remote.bucket}/${i}${r?`?${r}`:""}`}async send(t,r){let n=await this.aws.sign(this.url(t,r.query),{method:r.method,headers:r.headers,body:r.body});return this.fetch(n)}async failure(t,r){let n=await r.text().catch(()=>""),i=r.status===403?": check the remote's keys and that they may write to the bucket":r.status===404?": check the remote's endpoint and bucket":"";return new Nn(`${t} ${this.remote.bucket} failed (${r.status} ${tf(n)})${i}`,r.status)}};function tf(e){return/<Code>([^<]+)<\/Code>/.exec(e)?.[1]??"no error code"}function Ex(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""")}h();$n();var lu="framefields.json";function of(e){for(let t=e;;t=xo(t)){if(go(yo(t,lu)))return t;if(xo(t)===t)return}}async function af(e){let t=yo(e,lu);if(!go(t))return;let r;try{r=JSON.parse(await _u(t,"utf8"))}catch(i){throw new $e(`${lu} is not valid JSON: ${i.message}`)}if(r.assets===void 0)return;let n=r.storage===void 0?void 0:Qp(r.storage);return{storage:n,assets:Jp(r.assets,n)}}var Bx=6*3600,Ix=5*3600*1e3;async function cu(e,t={}){let r=of(e),n=r&&await af(r);if(!r||!n)return;let i=new Map,o=a=>{let u=Uu(r,a).split("/").join("/");return u.startsWith("../")?void 0:n.assets[u]};return{root:r,entry:o,async url(a){let u=o(a);if(!u)return;let l=ef(u,n.storage);if(l)return l;let c=i.get(u.sha256);if(c&&Date.now()-c.at<Ix)return c.url;let{name:m,remote:d}=au(n.storage,u.remote),p=nf(m,t.env);if(!p)return;let f=await new so(d,p,{fetch:t.fetch}).presign(u.sha256,Bx);return i.set(u.sha256,{url:f,at:Date.now()}),f}}}h();$n();var tr=H.dirname(Gn(import.meta.url)),sf=["import","meta","url"].join("."),jx=vo(import.meta.url),uo="/@framefields/engine",pu="/@framefields/ui",lf={framefields:"index.ts","framefields/effects":"effects/index.ts","framefields/audio":"audio/index.ts","framefields/signals":"signals/index.ts","framefields/fonts":"fonts/index.ts","framefields/components":"components/index.ts"},du={path:"path","path/posix":"path",url:"url",os:"os",fs:"fs","fs/promises":"fs-promises",module:"module"},uf=new Set(["sharp","skia-canvas","node-av","onnxruntime-node","@resvg/resvg-js","@napi-rs/webcodecs","@mediabunny/server","@mediabunny/mp3-encoder","webgpu","pino","pino-pretty","dotenv","esbuild","@framefields/renderer","framefields/renderer","framefields/preview"]),zx=`
|
|
616
|
+
const stub = () => new Proxy(function () {}, {
|
|
617
|
+
get: (_t, k) => (k === "__esModule" ? true : k === Symbol.toPrimitive ? () => "" : stub()),
|
|
618
|
+
apply: () => stub(),
|
|
619
|
+
construct: () => stub(),
|
|
620
|
+
});
|
|
621
|
+
module.exports = stub();
|
|
622
|
+
`;async function _x(e){let{build:t}=await import("./esbuild-DZUM7TEX.mjs"),r=H.resolve(tr,".."),n=H.join(tr,"shims"),i={player:H.join(tr,"player.ts")};for(let[o,a]of Object.entries(lf))i[bf(o)]=H.join(r,a);for(let o of new Set(Object.values(du)))i[`shims/${o}`]=H.join(n,`${o}.ts`);await he.promises.rm(e,{recursive:!0,force:!0}),await t({...fu,entryPoints:i,outdir:e,outExtension:{".js":".mjs"},splitting:!0,minify:!0,conditions:["development","browser","import"],define:{"process.env.NODE_ENV":'"production"',global:"globalThis"},inject:[H.join(n,"process.ts")],plugins:[{name:"framefields-engine",setup(o){o.onResolve({filter:/^framefields-preview:renderers$/},()=>({path:Wx()})),yf(o,a=>({path:H.join(n,`${a}.ts`)}))}}]})}async function cf(e){let{build:t}=await import("./esbuild-DZUM7TEX.mjs"),r=H.resolve(e.entry),n=u=>({path:`${uo}/${u}.mjs`,external:!0}),i={modelsDir:e.modelsDir,ortBase:e.ortBase},o=await t({...fu,entryPoints:["framefields-preview:entry"],write:!1,metafile:!0,sourcemap:"inline",plugins:[{name:"framefields-project",setup(u){u.onResolve({filter:/^framefields-preview:entry$/},()=>({path:"entry",namespace:"framefields-preview"})),u.onLoad({filter:/.*/,namespace:"framefields-preview"},()=>({contents:[`import { startAudioMixer, startPlayer } from ${JSON.stringify(`${uo}/player.mjs`)};`,`import * as mod from ${JSON.stringify(r)};`,`if (typeof document === "undefined") startAudioMixer(mod, ${JSON.stringify(e.exportName)});`,`else startPlayer(mod, ${JSON.stringify(e.exportName)}, ${JSON.stringify(i)});`].join(`
|
|
623
|
+
`),resolveDir:H.dirname(r),loader:"js"})),u.onResolve({filter:/^\/@framefields\/engine\//},l=>({path:l.path,external:!0})),u.onResolve({filter:/^framefields(\/|$)/},l=>lf[l.path]?n(bf(l.path)):void 0),yf(u,l=>n(`shims/${l}`)),Gx(u)}}]}),a=Object.keys(o.metafile?.inputs??{}).filter(u=>!u.includes(":")&&!u.includes("node_modules")).map(u=>H.resolve(u));return{code:o.outputFiles[0].text,inputs:a}}async function Vx(e,{dev:t=!1}={}){let{build:r}=await import("./esbuild-DZUM7TEX.mjs"),n=H.join(tr,"ui");await he.promises.rm(e,{recursive:!0,force:!0}),await r({...fu,entryPoints:{main:H.join(n,"main.ts")},outdir:e,minify:!t,sourcemap:t?"inline":!1,conditions:["browser","import"],plugins:[{name:"framefields-page",setup(i){i.onResolve({filter:/^(node:|@framefields\/)/},o=>({errors:[{text:`the preview page may not import ${o.path} (from ${o.importer})`}]}))}}]}),await he.promises.copyFile(H.join(n,"index.html"),H.join(e,"index.html"))}function mf(e,t,r){return[e,H.join(e,"..")].map(n=>H.join(n,t)).find(n=>he.existsSync(H.join(n,r)))}function Ux(e){return mf(e,"preview-engine","player.mjs")}var mu=new Map;function df(e,t,r){if(e)return Promise.resolve(e);let n=mu.get(t);if(!n){let i=H.join(So.tmpdir(),`framefields-${t}-${S.pid}`);n=r(i).then(()=>i),mu.set(t,n),n.catch(()=>mu.delete(t))}return n}function pf(){return df(Ux(tr),"preview-engine",_x)}function ff(){return df(mf(tr,"preview-page","main.js"),"preview-page",e=>Vx(e,{dev:!0}))}function hf(){return S.env.FRAMEFIELDS_MODELS_DIR?H.resolve(S.env.FRAMEFIELDS_MODELS_DIR):H.join(So.homedir(),".cache","framefields","models")}var $x="1.30.0";function gf(e){for(let t of[e,tr])try{let r=vo(H.join(t,"noop.js")).resolve("onnxruntime-web"),n=H.dirname(r);return{base:`/@fs${n}/`,dir:n}}catch{}return{base:`https://cdn.jsdelivr.net/npm/onnxruntime-web@${$x}/dist/`}}var fu={bundle:!0,format:"esm",platform:"browser",target:"es2022",mainFields:["browser","module","main"],logLevel:"silent"};function bf(e){return e==="framefields"?"framefields":e.slice(12)}function yf(e,t){e.onResolve({filter:/^(node:)?[a-z_/]+$/},r=>{let n=r.path.replace(/^node:/,"");if(du[n])return t(du[n]);if(r.path.startsWith("node:")||Gu(n))return{path:n,namespace:"framefields-stub"}}),e.onResolve({filter:/.*/},r=>{let n=Hx(r.path);if(n&&(uf.has(n)||uf.has(r.path)))return{path:r.path,namespace:"framefields-stub"}}),e.onLoad({filter:/.*/,namespace:"framefields-stub"},()=>({contents:zx,loader:"js"}))}function Gx(e){e.onLoad({filter:/\.[cm]?[jt]sx?$/},async t=>{if(t.path.includes(`${H.sep}node_modules${H.sep}`))return;let r=await he.promises.readFile(t.path,"utf8");if(r.includes(sf))return{contents:`const __framefieldsFileUrl = ${JSON.stringify(Wn(t.path).href)};
|
|
624
|
+
${r.replaceAll(sf,"__framefieldsFileUrl")}`,loader:Yx(t.path)}})}function Wx(){let e=jx.resolve("@framefields/renderer"),t=H.join(H.dirname(e),"..","src","generated","node-renderers.ts");if(!he.existsSync(t))throw new Error(`[framefields] node renderer list not found at ${t}`);return t}function Hx(e){if(e.startsWith(".")||e.startsWith("/"))return;let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function Yx(e){return e.endsWith(".tsx")?"tsx":e.endsWith(".jsx")?"jsx":/\.[cm]?ts$/.test(e)?"ts":"js"}h();$n();var co=class{constructor(t){this.dir=t;this.file=H.join(t,"notes.json")}dir;file;async list(){try{let t=JSON.parse(await he.promises.readFile(this.file,"utf8"));return Array.isArray(t)?t:[]}catch{return[]}}async add(t){let r=await this.list(),n=r.reduce((a,u)=>Math.max(a,u.id),0)+1,i={id:n,frame:Math.max(0,Math.round(Number(t.frame)||0)),time:Fn(Number(t.time)||0,3),x:Fn(lo(t.x),4),y:Fn(lo(t.y),4),...t.w!==void 0&&t.h!==void 0&&{w:Fn(lo(t.w),4),h:Fn(lo(t.h),4)},text:String(t.text??"").trim(),done:!1,created:new Date().toISOString()};await this.ensureDir();let o=/^data:image\/jpeg;base64,(.+)$/.exec(t.image??"");return o&&(i.image=H.join(this.dir,`note-${n}.jpg`),await he.promises.writeFile(i.image,Buffer.from(o[1],"base64"))),await this.save([...r,i]),i}async update(t,r){let n=await this.list(),i=n.find(o=>o.id===t);if(i)return typeof r.done=="boolean"&&(i.done=r.done),typeof r.text=="string"&&r.text.trim()&&(i.text=r.text.trim()),await this.save(n),i}async remove(t){let r=await this.list(),n=r.find(i=>i.id===t);if(n)return n.image&&await he.promises.rm(n.image,{force:!0}),await this.save(r.filter(i=>i!==n)),n}async save(t){await this.ensureDir();let r=`${this.file}.${S.pid}.tmp`;await he.promises.writeFile(r,`${JSON.stringify(t,null," ")}
|
|
625
|
+
`),await he.promises.rename(r,this.file)}async ensureDir(){await he.promises.mkdir(this.dir,{recursive:!0});let t=H.join(H.dirname(this.dir),".gitignore");he.existsSync(t)||await he.promises.writeFile(t,`*
|
|
626
|
+
`)}};function xf(e,t){let r=i=>`${Math.round(i*100)}%`,n=e.w!==void 0&&e.h!==void 0?`area ${r(e.x)},${r(e.y)} to ${r(e.x+e.w)},${r(e.y+e.h)}`:`spot ${r(e.x)},${r(e.y)}`;return`note ${e.id} at ${Xx(e.frame,t)} (frame ${e.frame}), ${n}: ${e.text}`}function Xx(e,t){let r=e/t,n=Math.floor(r/60);return`${n}:${(r-n*60).toFixed(2).padStart(5,"0")}`}function lo(e){let t=Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}function Fn(e,t){return Number(e.toFixed(t))}h();function Sf(e,t,r){let n=new Array(r).fill(0);if(e.length===0)return n;let i=e.length/r;for(let o=0;o<r;o++){let a=Math.floor(o*i),u=Math.min(e.length,Math.floor((o+1)*i)),l=0;for(let c=a;c<u;c++){let m=Math.max(Math.abs(e[c]??0),Math.abs(t[c]??0));m>l&&(l=m)}n[o]=Math.min(1,l)}return n}var wf=1200,vf=.001;var Tf="x-framefields-preview",Zx="/@framefields/player.js";async function qx(e,t={}){let r=e.entry instanceof URL||String(e.entry).startsWith("file:")?Gn(e.entry):H.resolve(String(e.entry)),n=e.export??"default",i=hf(),o=gf(H.dirname(r)),a=[...t.root===void 0?[Qx(H.dirname(r))]:Array.isArray(t.root)?t.root:[t.root],i,o.dir].filter(L=>!!L).map(L=>H.resolve(L)),u=new Set,l=t.idleCloseMs??5e3,c,m=t.title??"framefields preview",d=(0,po.randomUUID)(),p=t.log===!1?()=>{}:t.log??(L=>console.error(L)),f=L=>p(`[framefields preview] ${L}`),b=new Set,g=!1,y=t.notesDir===!1?void 0:new co(H.resolve(t.notesDir??H.join(S.cwd(),".framefields","preview-notes"))),T=Promise.resolve(),M=await cu(H.dirname(r)).catch(L=>{f(`pinned assets are off: ${L.message}`)});M&&or.setMissingMediaResolver(L=>M.url(L));let v=new Set,x=await Kx(r,n),A=await nS(x,m,d,y?.dir??null),w,R=()=>{if(!w){let L=cf({entry:r,exportName:n,modelsDir:i,ortBase:o.base}).then(z=>z.code);w=L,L.catch(z=>{f(`could not build ${H.relative(S.cwd(),r)}:
|
|
627
|
+
${eS(z)}`),w===L&&(w=void 0)})}return w},N=pf();N.catch(()=>{});let V=ff();V.catch(()=>{});let $={state:t.audio===!1?"none":"browser"},I;function E(L,z){for(let q of u)q.write(`event: ${L}
|
|
628
|
+
data: ${JSON.stringify(z)}
|
|
629
|
+
|
|
630
|
+
`)}function k(L){$=L,E("audio",$)}function P(){if($.state!=="mixing")return;if(!x.toVirtualMediaAsync&&!x.toVirtualMedia){k({state:"none"});return}let L=t.renderer??new ge.HeadlessMediaRenderer;(async()=>{let z=x.toVirtualMediaAsync?await x.toVirtualMediaAsync():x.toVirtualMedia();return await x.prepareMediaTime?.(),L.renderAudio(z,{fps:A.fps})})().then(({channels:z,sampleRate:q})=>{let F=z[0]??new Float32Array(0),O=z[1]??F,_=Sf(F,O,wf);if(F.length===0||Math.max(..._)<vf){k({state:"none"});return}I=Io([F,O],{sampleRate:q}),k({state:"ready",durationSec:F.length/q,peaks:_.map(C=>Math.round(C*1e3)/1e3)})},z=>{k({state:"error",error:z instanceof Error?z.message:String(z)})})}let G,X=new Promise(L=>{G=L}),U;function j(L="closed"){return U??=new Promise(z=>{clearTimeout(c),L==="idle"&&f("stopped: its tab was closed"),L==="replaced"&&f("stopped: a newer preview took over");for(let q of u)q.end();u.clear(),M&&or.setMissingMediaResolver(),Z.close(()=>{z(),G(L)}),Z.closeAllConnections()}),U}let Z=bu.default.createServer(async(L,z)=>{let q=new URL(L.url??"/","http://localhost");z.setHeader("cross-origin-opener-policy","same-origin"),z.setHeader("cross-origin-embedder-policy","credentialless");try{if(L.method==="GET"&&q.pathname==="/"){await mo(L,z,H.join(await V,"index.html"),!0);return}if(L.method==="GET"&&q.pathname==="/meta"){ot(z,200,{...A,audio:$});return}for(let[O,_]of[[uo,N],[pu,V]]){if(L.method!=="GET"||!q.pathname.startsWith(`${O}/`))continue;let C=await _,le=H.resolve(C,`.${q.pathname.slice(O.length)}`);hu(C,le)&&await gu(le)?await mo(L,z,le,O===pu):ot(z,404,{error:"not found"});return}if(L.method==="GET"&&q.pathname===Zx){let O;try{await N,O=await R()}catch(_){let C=_ instanceof Error?_.message:String(_);O=`throw new Error(${JSON.stringify(`Could not build the preview:
|
|
631
|
+
${C}`)});`}z.writeHead(200,{"content-type":"text/javascript; charset=utf-8","cache-control":"no-store"}),z.end(O);return}if(L.method==="GET"&&q.pathname==="/@framefields/stat"){let O=H.resolve(q.searchParams.get("path")??""),_=-1;a.some(C=>hu(C,O))&&(_=await he.promises.stat(O).then(C=>C.isFile()?C.size:-1,()=>M?.entry(O)?.size??-1)),ot(z,200,{exists:_>=0,size:Math.max(0,_)});return}if(L.method==="GET"&&q.pathname==="/events"){z.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store",connection:"keep-alive"}),z.write(`retry: 1000
|
|
632
|
+
`),z.write(`event: hello
|
|
633
|
+
data: ${JSON.stringify({session:A.session})}
|
|
634
|
+
|
|
635
|
+
`),u.add(z),clearTimeout(c),g||(g=!0,f(l===!1?"page opened":`page opened; the server stops ${Number((l/1e3).toFixed(1))} s after its last tab closes`)),ne?.(),L.on("close",()=>{u.delete(z),u.size===0&&l!==!1&&!U&&(c=setTimeout(()=>{u.size===0&&j("idle")},l))});return}if(L.method==="POST"&&q.pathname==="/takeover"&&L.headers[Tf]==="1"){ot(z,200,{ok:!0}),setImmediate(()=>{j("replaced")});return}if(L.method==="POST"&&q.pathname==="/@framefields/log"&&L.headers["content-type"]==="application/json"){let O=await kf(L,16384),{message:_,level:C}=JSON.parse(O),le=String(_??"").trim();le&&!b.has(le)&&b.size<200&&(b.add(le),f(`${C==="warning"?"warning":"error"} in the page: ${le}`)),z.writeHead(204).end();return}if(y&&q.pathname==="/@framefields/notes"){if(L.method==="GET"){ot(z,200,await y.list());return}if(L.method==="POST"&&L.headers["content-type"]==="application/json"){let O=JSON.parse(await kf(L,16777216)),_=T.then(()=>Jx(y,O,A.fps,f));T=_.catch(()=>{});let C=await _;E("notes",await y.list()),ot(z,C?200:404,C??{error:"no such note"});return}}if(L.method==="POST"&&q.pathname==="/audio/mix"){($.state==="browser"||$.state==="error")&&($={state:"mixing"},P()),ot(z,202,$);return}if(L.method==="GET"&&q.pathname==="/audio"){if($.state!=="ready"||!I){ot(z,404,{error:`audio is ${$.state}`});return}z.writeHead(200,{"content-type":"audio/wav","content-length":I.length,"cache-control":"no-store"}),z.end(I);return}let F=/^\/assets\/fonts\/([^/]+)$/.exec(q.pathname);if(F&&(L.method==="GET"||L.method==="HEAD")){let O=H.join(S.cwd(),"assets","fonts",decodeURIComponent(F[1]));if(await gu(O)){await mo(L,z,O);return}}if(L.method==="GET"||L.method==="HEAD"){let O=H.resolve(decodeURIComponent(q.pathname.replace(/^\/@fs(?=\/)/,"")));if(a.some(_=>hu(_,O))&&await gu(O)){await mo(L,z,O);return}if(M&&await rS(z,M,O,v,f))return}ot(z,404,{error:"not found"})}catch(F){z.headersSent?z.end():ot(z,500,{error:F instanceof Error?F.message:String(F)})}}),ne,pe=t.host??"127.0.0.1",ae=t.port??iS(),be=L=>new Promise((z,q)=>{let F=_=>{Z.off("listening",O),q(_)},O=()=>{Z.off("error",F),z()};Z.once("error",F),Z.once("listening",O),Z.listen(L,pe)});try{await be(ae)}catch(L){if(L.code!=="EADDRINUSE")throw L;if(await oS(pe,ae))await be(ae).catch(()=>be(0));else if(t.port===void 0)await be(0);else throw L}let{port:Ce}=Z.address(),me=`http://${pe.includes(":")?`[${pe}]`:pe}:${Ce}/`;if(R().catch(()=>{}),t.open===!0){let L=await new Promise(z=>{let q=setTimeout(()=>z(!1),2e3);ne=()=>{clearTimeout(q),z(!0)},u.size>0&&ne()});ne=void 0,L||aS(me)}return{url:me,closed:X,close:()=>j()}}async function Kx(e,t){let n=(await import(Wn(e).href))[t];if(n===void 0)throw new Error(`[framefields] ${e} has no export named "${t}" to preview.`);return typeof n=="function"?await n():n}function Qx(e){let t;for(let r=e;;r=H.dirname(r)){if(he.existsSync(H.join(r,".git")))return r;if(!t&&he.existsSync(H.join(r,"package.json"))&&(t=r),H.dirname(r)===r)return t??e}}async function Jx(e,t,r,n){if(t.op==="add"&&t.note&&String(t.note.text).trim()){let o=await e.add(t.note),a=[o.image&&`frame with the spot marked: ${o.image}`,`all notes: ${e.file}`];return n(`${xf(o,r)}
|
|
636
|
+
${a.filter(Boolean).join(" \xB7 ")}`),o}let i=Number(t.id);if(t.op==="update"){let o=await e.update(i,t);return o&&typeof t.done=="boolean"&&n(`note ${i} marked ${o.done?"done":"open"}`),o}if(t.op==="remove"){let o=await e.remove(i);return o&&n(`note ${i} deleted`),o}}function eS(e){return e instanceof Error?e.message:String(e)}function kf(e,t){return new Promise((r,n)=>{let i="";e.setEncoding("utf8"),e.on("data",o=>{i+=o,i.length>t&&(n(new Error("request body too large")),e.destroy())}),e.on("end",()=>r(i)),e.on("error",n)})}function hu(e,t){let r=H.relative(e,t);return!!r&&!r.startsWith("..")&&!H.isAbsolute(r)}async function gu(e){try{return(await he.promises.stat(e)).isFile()}catch{return!1}}var tS={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".json":"application/json",".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".map":"application/json",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".wasm":"application/wasm",".onnx":"application/octet-stream",".srt":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8"};async function rS(e,t,r,n,i){if(!t.entry(r))return!1;let o=await t.url(r);if(o)return e.writeHead(302,{location:o,"cache-control":"no-store"}),e.end(),!0;let a=H.relative(t.root,r);return n.has(a)||(n.add(a),i(`${a} is pinned on a private remote and there are no keys here: set its FRAMEFIELDS_STORAGE_* keys, give the remote a publicUrl, or \`npx framefields assets pull\``)),!1}async function mo(e,t,r,n=!1){let{size:i}=await he.promises.stat(r),o=tS[H.extname(r).toLowerCase()]??"application/octet-stream",a=/^bytes=(\d*)-(\d*)$/.exec(e.headers.range??""),u=0,l=i-1;if(a&&(a[1]||a[2])&&(a[1]?(u=Number(a[1]),a[2]&&(l=Math.min(l,Number(a[2])))):u=Math.max(0,i-Number(a[2])),u>l||u>=i)){t.writeHead(416,{"content-range":`bytes */${i}`}),t.end();return}if(t.writeHead(a?206:200,{"content-type":o,"content-length":l-u+1,"accept-ranges":"bytes","cache-control":n?"no-store":"no-cache",...a&&{"content-range":`bytes ${u}-${l}/${i}`}}),e.method==="HEAD"){t.end();return}he.createReadStream(r,{start:u,end:l}).pipe(t)}async function nS(e,t,r,n){let i=e.fps??24,o=e.durationMs??await e.computeDuration?.()??5e3;return{session:r,notesDir:n,title:t,fps:i,frameCount:Math.max(1,Math.round(o/1e3*i)),width:e.width??1920,height:e.height??1080}}function iS(){return 41e3+(0,po.createHash)("sha1").update(S.cwd()).digest().readUInt16BE(0)%900}async function oS(e,t){let r=await new Promise(n=>{let i=bu.default.request({host:e,port:t,method:"POST",path:"/takeover",agent:!1,headers:{[Tf]:"1"},timeout:1500},o=>{o.resume(),n(o.statusCode===200)});i.on("timeout",()=>i.destroy()),i.on("error",()=>n(!1)),i.end()});return r&&await new Promise(n=>setTimeout(n,150)),r}function ot(e,t,r){e.writeHead(t,{"content-type":"application/json","cache-control":"no-store"}),e.end(JSON.stringify(r))}function aS(e){let[t,r]=S.platform==="darwin"?["open",[e]]:S.platform==="win32"?["cmd",["/c","start","",e]]:["xdg-open",[e]];try{(0,Pf.spawn)(t,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}function yu(e,t){return e&&(t&&!e.source&&Object.defineProperty(e,"source",{value:t,enumerable:!0,writable:!0,configurable:!0}),typeof e.section!="function"&&Object.defineProperty(e,"section",{value:(r,n)=>{if(typeof r=="object"&&r!==null&&!("kind"in r)&&!("inputHandleId"in r)&&!("src"in r)){let o=r.source??e.source??t;return B.section(o,e,r)}let i=r??e.source??t;return B.section(i,e,n)},enumerable:!1,writable:!0,configurable:!0}),typeof e.blurEffect!="function"&&Object.defineProperty(e,"blurEffect",{value:r=>new Ft({track:e,...r}),enumerable:!1,writable:!0,configurable:!0}),typeof e.isolate!="function"&&Object.defineProperty(e,"isolate",{value:(r,n)=>B.section(r,e,n),enumerable:!1,writable:!0,configurable:!0}),e)}var uS=Ur.attach;Ur.attach=function(e,t,r){let n=uS.call(this,e,t,r);if(n?.objects){let i=e,o=n.objects.get.bind(n.objects);n.objects.get=u=>yu(o(u),i);let a=n.objects.byCategory.bind(n.objects);n.objects.byCategory=(u,l)=>yu(a(u,l),i),n.objects.primary&&yu(n.objects.primary,i)}return n};var Mf=class e{virtualMedia;constructor(t,r="Video"){this.virtualMedia=Eu(t,r)}static video(t,r){let n=new e(t,"Video");return r&&Object.assign(n.virtualMedia.metadata,r),n}static image(t,r){let n=new e(t,"Image");return r&&Object.assign(n.virtualMedia.metadata,r),n}static lottie(t,r){let n=new e(t,"Lottie");return r&&Object.assign(n.virtualMedia.metadata,r),n}static audio(t,r){let n=new e(t,"Audio");return r&&Object.assign(n.virtualMedia.metadata,r),n}apply(t,r={}){let n;t instanceof pS||typeof t=="object"&&t!==null&&"op"in t?n=t.toOperation():n={op:t,...r};let i=Bu(this.virtualMedia,{...n,dataType:this.virtualMedia.operation.dataType});return new e(i)}toVirtualMedia(){return this.virtualMedia}async renderFrame(t={}){return(t.renderer??new ge.HeadlessMediaRenderer).renderFrame(this.virtualMedia,t)}get fps(){return this.virtualMedia.metadata?.fps??void 0}get durationMs(){return this.virtualMedia.metadata?.durationMs??void 0}get width(){return this.virtualMedia.metadata?.width??void 0}get height(){return this.virtualMedia.metadata?.height??void 0}async renderFrameGrid(t={}){return Tn(this,t)}async renderVideo(t={},r={}){let n=typeof t=="string"?{...r,outputPath:t}:t,o=await(n.renderer??new ge.HeadlessMediaRenderer).renderVideo(this.virtualMedia,n);return Df(o,n.outputPath)}};async function Df(e,t){if(!t)return e;let r=H.resolve(t);return await zr.mkdir(H.dirname(r),{recursive:!0}),await zr.copyFile(e.filePath,r),await e.cleanup(),{...e,filePath:r,cleanup:async()=>{}}}var Af=class e{width;height;fps;durationMs;backgroundColor;antialias3d;fonts;children=[];audioTracks=[];signals={};_frameHooks=[];_prepareHooks=[];_clipVision=new Map;_linking=!1;_mediaSignals;_visionConfig;_visionBundle;_effects=[];apply(t){return t instanceof wt?(this.withVision(t),this):(this._effects.push(t),this)}withVision(t={}){this._visionBundle??=new Vr({width:this.width,height:this.height,fps:this.fps});let r=t instanceof wt?t.config:t;return this._visionConfig={...r,visionBundle:this._visionBundle},this._visionBundle}vision(t,r={}){let n=typeof t=="string"?t:t.src??t.inputHandleId;if(typeof t!="string"){let a=this.toVirtualMedia({resolveMediaSignal:this.mediaSignalResolver(!0)}),u=Co(a.children).find(({vm:c})=>c.operation.id===t.id),l=u&&{operation:{...u.vm.operation,startFrame:u.startFrame}};if(!l)throw new Error("Add the media layer to the composition before calling comp.vision(layer)");r={startFrame:l.operation.startFrame??t.startFrame,trimStartSec:t.trimStartSec,timeRemap:l.operation.timeRemap,durationFrames:t.durationFrames,...r}}let i=`${n}\0${JSON.stringify({...r,timeRemap:Or(r.timeRemap)})}`,o=this._clipVision.get(i);return o||(o=new kn(n,this.fps,r),this._clipVision.set(i,o)),o}async prepareVision(t){this.linkClipLayers(),await Promise.all([...this._clipVision.values()].map(r=>r.ready(0,t)))}linkClipLayers(){let t,r=n=>{if(!n||typeof n!="object")return;let i=n;if(i.kind==="media"&&i.dataType==="Video"&&typeof i.inputHandleId=="string"&&i.vision instanceof wt&&!(No in i.vision)){t??=new Map(Co(this.toVirtualMedia().children).map(({vm:u,startFrame:l})=>{let c=u.operation;return[c.id,{startFrame:l,timeRemap:c.timeRemap}]}));let o=t.get(i.id),a=this.clipForLayer(i.src??i.inputHandleId,i.vision,{trimStartSec:i.trimStartSec,startFrame:o?.startFrame??i.startFrame,timeRemap:o?.timeRemap});a&&(i.vision.mode!=="skeleton"&&i.vision.mode!=="depth"&&a.keepSubjects(),Object.defineProperty(i.vision,No,{value:a,enumerable:!1,configurable:!0}))}if(Array.isArray(i.children))for(let o of i.children)r(o);r(i.matte?.node),r(i.relief?.node)};for(let n of this.children)r(n)}clipForLayer(t,r,n){let i=r.mode??"passthrough";if(i==="depth")return this.depthClip(t,n);let o=i==="skeleton";if(!(i!=="matte"&&i!=="mask"&&i!=="crop"&&!o)&&!(r.classes!==void 0||r.enableMatte===!0||r.visionBundle!==void 0||!o&&(r.matteSource==="selfie"||r.keyBackground===!0||r.enablePose===!0||(r.maskThreshold??.5)!==.5||r.featherRadius!==void 0)))for(let a of this._clipVision.values()){let u=a.options;if(a.source===t&&a.startFrame===(n.startFrame??0)&&a.trimStartSec===(n.trimStartSec??0)&&Or(u.timeRemap)===Or(n.timeRemap)&&(u.variant??"s")===(r.variant??"s")&&(u.confidence??.3)===(r.confidence??.3)){if(o&&!a.tracksPose){if(a.exact)throw new Error("A skeleton layer of a prompted comp.vision clip needs `pose: true` on that clip.");continue}return a}}}depthClip(t,r){for(let n of this._clipVision.values())if(n.tracksDepth&&n.source===t&&n.startFrame===(r.startFrame??0)&&n.trimStartSec===(r.trimStartSec??0)&&Or(n.options.timeRemap)===Or(r.timeRemap))return n;return this.vision(t,{depth:!0,...r.startFrame!==void 0&&{startFrame:r.startFrame},...r.trimStartSec!==void 0&&{trimStartSec:r.trimStartSec},...r.timeRemap!==void 0&&{timeRemap:r.timeRemap}})}async analyzeVisionSequence(t,r={}){let n=r.fps??this.fps,i=this.durationMs??await this.computeDuration(),o=r.totalFrames??Math.max(1,Math.round(i/1e3*n)),a=sr.create({modelsDir:r.modelsDir,baseUrl:r.baseUrl,...r.confidence!==void 0?{confidence:r.confidence}:{},...r.variant!==void 0?{variant:r.variant}:{}}),u=_r.getVideo(t,!0);async function*l(){for(let c=0;c<o;c++){let m=await u.getFrame(c/n);m?.buffer&&m.width>0&&m.height>0&&(yield{data:m.buffer,width:m.width,height:m.height})}}try{return await Oo(l(),{runner:a,source:t,fps:n,...r.tasks!==void 0?{tasks:r.tasks}:{},...r.categories!==void 0?{categories:r.categories}:{},...r.pathStride!==void 0?{pathStride:r.pathStride}:{},...r.includeMasks!==void 0?{includeMasks:r.includeMasks}:{},...r.iouThreshold!==void 0?{iouThreshold:r.iouThreshold}:{}})}finally{a.close(),u.destroy()}}onRequestFrame(t){return this._frameHooks.push(t),this}onPrepareFrame(t){return this._prepareHooks.push(t),this}notifyFrame(t){let r=this._mediaSignals?.framesBefore(t.frame)??[];return r.length===0?this.runFrame(t):(async()=>{for(let n of r)await this.runFrame($s(t,n));await this.runFrame(t)})()}runFrame(t){for(let n of this._frameHooks)n(t);let r=this._mediaSignals;if(r?.advance(t.frame),this.linkClipLayers(),this._clipVision.size===0&&this._prepareHooks.length===0){r?.reach(t.frame);return}return(async()=>{await this.prepareVision(t.frame);for(let n of this._prepareHooks)await n(t);r?.reach(t.frame)})()}async prepareMediaTime(){let t=this.durationMs??await this.computeDuration(),r=Math.round(t/1e3*this.fps)-1;!this._mediaSignals?.pending||r<0||await this.notifyFrame($s({frame:0,fps:this.fps,time:0,duration:t/1e3,durationMs:t,progress:0,deltaTime:1/this.fps},r))}mediaSignalResolver(t=this.hasFrameHooks(),r=this.durationMs,n=this.signals){return this._mediaSignals??=new Xi(this.fps),this._mediaSignals.resolver({live:t,compositionDurationFrames:Math.round((r??0)/1e3*this.fps),signals:n})}hasFrameHooks(){return this._frameHooks.length>0||this._prepareHooks.length>0||this._clipVision.size>0}constructor(t){this.width=t.width,this.height=t.height,this.fps=t.fps??60,this.durationMs=t.durationMs??(t.durationFrames!==void 0?t.durationFrames/this.fps*1e3:void 0),this.backgroundColor=t.backgroundColor??"#000000",this.antialias3d=t.antialias3d,this.fonts=t.fonts??[],this.signals=t.signals??{}}static create(t){return new e(t)}addSignal(t,r){return this.signals[t]=r,this}add(t,...r){if(t instanceof pr)this.children.push(t.toNode());else if(t instanceof Ur)this.children.push(t.toNode());else{if(t&&typeof t=="object"&&"node"in t)return this.add(t.node,...r),this;if(Array.isArray(t))for(let n of t)this.add(n);else{let n=t,i=r[0];if(i&&!(i instanceof pr)&&!Array.isArray(i)&&(i instanceof Q||"tracks"in i))return n.animation=i instanceof Q?i.toSpec():i,this.children.push(n),this;this.children.push(n)}}for(let n of r)n&&!(n instanceof Q)&&!("tracks"in n)&&this.add(n);return this}addAudio(t){return this.audioTracks.push(t),this}addSubjectSandwich(t){let r=typeof t.source=="string"?t.source:t.source.inputHandleId??"",n=t.fit??"cover",i=t.feather??4,o=i>1?i/100:i,a=t.variant??"s",u=B.video(r,{width:this.width,height:this.height,position:"absolute",x:0,y:0,fit:n,muted:t.muted??!1,volume:t.muted?0:t.volume??1});this.add(u);for(let c of t.behind)this.add(c);let l=B.video(r,{width:this.width,height:this.height,position:"absolute",x:0,y:0,fit:n,muted:!0,volume:0}).withVision({mode:"matte",enableSegmentation:!0,variant:a,confidence:t.confidence??.25,featherRadius:o,keyBackground:t.keyBackground??!0,backgroundKeyThreshold:t.backgroundKeyThreshold});return this.add(l),this}addSmartFraming(t){let r=typeof t.source=="string"?t.source:t.source.inputHandleId??"",n=Math.max(0,Math.min(.99,t.damping??.8)),i=t.leadHeadroom??.18,o=this.width,a=this.height,u=t.sourceAspect??16/9,l=o/a,c=l<u?Math.round(a*u):o,m=l<u?a:Math.round(o/u),d=o-c,p=a-m,f=t.target,b=new nr(x=>{if(d>=0)return 0;let A=f.center?.x?f.center.x.get(x):f.bounds?.centerX?f.bounds.centerX.get(x)/o:f.center?.screenX?f.center.screenX.get(x)/o:.5,R=Math.max(0,Math.min(1,A))*c,N=o/2-R;return Math.max(d,Math.min(0,N))},{fps:this.fps,label:"smart_framing_pan_x"}),g=new nr(x=>{if(p>=0)return 0;let A=f.center?.y?f.center.y.get(x):f.bounds?.centerY?f.bounds.centerY.get(x)/a:f.center?.screenY?f.center.screenY.get(x)/a:.5,R=Math.max(0,Math.min(1,A))*m,N=a*i-R;return Math.max(p,Math.min(0,N))},{fps:this.fps,label:"smart_framing_pan_y"}),y=new nr(x=>{let A=x.frame;if(A<=0)return b.get(x);let w=b.get({...x,frame:0,time:0}),R=1-n;for(let N=1;N<=A;N++){let V=b.get({...x,frame:N,time:N/x.fps});w=w+R*(V-w)}return w},{fps:this.fps,label:"smart_framing_smooth_x"}),T=new nr(x=>{let A=x.frame;if(A<=0)return g.get(x);let w=g.get({...x,frame:0,time:0}),R=1-n;for(let N=1;N<=A;N++){let V=g.get({...x,frame:N,time:N/x.fps});w=w+R*(V-w)}return w},{fps:this.fps,label:"smart_framing_smooth_y"}),M=B.box({width:o,height:a,overflow:"hidden",position:"relative"}),v=B.video(r,{width:c,height:m,position:"absolute",x:y,y:T,fit:t.fit??"cover",muted:t.muted??!1,volume:t.muted?0:t.volume??1});return M.children||(M.children=[]),M.children.push(v),this.add(M),this}addSubjectOutline(t,r={}){let n=r.blur??12,i=this.width,o=this.height,a=r.pulseSignal,u=a?new nr(m=>Math.max(0,Math.min(1,Number(a.get(m))||0)),{fps:this.fps,label:"outline_pulse"}):1,l=typeof r.source=="string"?r.source:r.source?.inputHandleId??"",c=B.box({width:i,height:o,position:"absolute",x:0,y:0,opacity:u});if(l){let m=B.video(l,{width:i,height:o,position:"absolute",x:0,y:0,fit:"cover",muted:!0,volume:0}).withVision({mode:"mask",enableSegmentation:!0});c.children||(c.children=[]),c.children.push(m)}return c.apply(new Ft({strength:n,blurType:"Gaussian"})),this.add(c),this}section(t,r,n){let i,o,a={},u=t!==null&&typeof t=="object"&&"bounds"in t,l=typeof t=="string"||t!==null&&typeof t=="object"&&("kind"in t||"src"in t||"inputHandleId"in t);if(l&&r&&typeof r=="object"&&"bounds"in r?(i=t,o=r,a=n??{}):l&&r?(i=t,a=r):u?(o=t,a=r??{},i=a.source??o.source):t&&typeof t=="object"&&(a=t,i=a.source),!i){let c=this.children.find(m=>m.kind==="media"&&(m.dataType==="Video"||m.dataType==="Image"));c&&(i=c)}return B.section(i??"",o??a,{compositionWidth:this.width,compositionHeight:this.height,...a})}addSection(t,r,n){let i=this.section(t,r,n);return this.add(i),i}async computeDuration(){if(this.durationMs!==void 0)return this.durationMs;let t=0,r=[];for(let n of[...this.children,...this.audioTracks]){if(n.kind==="media"){let i=n.inputHandleId;typeof i=="string"&&(n.dataType==="Video"||n.dataType==="Audio")&&r.push(i)}if(typeof n.durationFrames=="number"){let o=((typeof n.startFrame=="number"?n.startFrame:0)+n.durationFrames)/this.fps*1e3;o>t&&(t=o)}}for(let n of r)try{let o=await(await or.acquire(n)).computeDuration();if(Number.isFinite(o)&&o>0){let a=Math.round(o*1e3);a>t&&(t=a)}}catch{}return t>0?t:5e3}async registerFont(t,r){let n=await _e.register(t,r);return n.filePath&&!this.fonts.includes(n.filePath)&&this.fonts.push(n.filePath),this}async registerEmojiFont(t){return await _e.registerEmojiFont(t),this}toSpec(){let t=[...this.children,...this.audioTracks],r=_e.getRegisteredFontPaths(),n=Array.from(new Set([...this.fonts,...r]));return{width:this.width,height:this.height,fps:this.fps,mode:"Video",backgroundColor:this.backgroundColor,...this.antialias3d!==void 0&&{antialias3d:this.antialias3d},layout:t,fonts:n,signals:this.signals,...this._effects.length>0&&{effects:this._effects},...this._visionConfig&&{vision:this._visionConfig},...this.hasFrameHooks()&&{onRequestFrame:i=>this.notifyFrame(i)}}}toVirtualMedia(t={}){if(!this._linking){this._linking=!0;try{this.linkClipLayers()}finally{this._linking=!1}}let r=t.durationMs??this.durationMs,n=t.signals??this.signals;return Yn(this.toSpec(),{isVideoMode:!0,fps:this.fps,durationMs:r,signals:n,resolveMediaSignal:this.mediaSignalResolver(void 0,r,n),...this._effects.length>0&&{effects:this._effects},...this._visionConfig&&{vision:this._visionConfig},...t})}async toVirtualMediaAsync(t={}){let r=t.durationMs??this.durationMs??await this.computeDuration();this.durationMs=r;let n=t.signals??this.signals,i=Yn(this.toSpec(),{isVideoMode:!0,fps:this.fps,durationMs:r,signals:n,resolveMediaSignal:this.mediaSignalResolver(void 0,r,n),...this._effects.length>0&&{effects:this._effects},...this._visionConfig&&{vision:this._visionConfig},...t});return await el(i,this.fps),i}async renderFrame(t={}){let r=typeof t=="number"?{frame:t}:t,{frame:n}=Nt(r,this.fps);if(r.fps!==void 0&&r.fps!==this.fps)throw new Error(`Composition fps is ${this.fps}; cannot render at fps ${r.fps}.`);let i=this.toVirtualMedia();if(this.hasFrameHooks()){let a=n;await this.notifyFrame({frame:a,fps:this.fps,time:this.fps>0?a/this.fps:0,duration:(this.durationMs??0)/1e3,durationMs:this.durationMs??0,progress:this.durationMs&&this.durationMs>0?Math.max(0,Math.min(1,a/this.fps*1e3/this.durationMs)):0,deltaTime:this.fps>0?1/this.fps:0})}return(r.renderer??new ge.HeadlessMediaRenderer).renderFrame(i,{fps:this.fps,frame:n,renderId:r.renderId,format:r.format})}async renderFrameGrid(t={}){return Tn(this,t)}async renderVideo(t={},r={}){let n=typeof t=="string"?{...r,outputPath:t}:t,o=await(n.renderer??new ge.HeadlessMediaRenderer).renderVideo(this.toVirtualMedia(),n);if(o.qa){let a=this.lint(),u=[...o.qa.issues,...a.map(l=>({severity:l.severity,code:l.code,message:l.message,...l.layerId!==void 0&&{layerId:l.layerId}}))];o.qa={...o.qa,issues:u,passed:o.qa.passed&&!a.some(l=>l.severity==="error")}}return Df(o,n.outputPath)}lint(){return Ta(this.toSpec(),{emojiFont:_e.hasEmojiFont(),scatterCoverage:kp})}};function je(e){let t=e,r=t;r.rotationX!==void 0&&(r.rotateX===void 0&&(r.rotateX=r.rotationX),delete r.rotationX),r.rotationY!==void 0&&(r.rotateY===void 0&&(r.rotateY=r.rotationY),delete r.rotationY),r.rotationZ!==void 0&&(r.rotateZ===void 0&&(r.rotateZ=r.rotationZ),delete r.rotationZ),t.animation instanceof Q&&(t.animation=t.animation.toSpec()),Object.defineProperty(t,"animate",{value:(...i)=>{let o=i.flat().flatMap(c=>c instanceof Q?c.tracks:c.tracks??[]),a=t.animation,u=a?.tracks??[],l=i.flat().map(c=>c.frameStep).filter(c=>c!==void 0).at(-1)??a?.frameStep;return t.animation={tracks:Hr([...u,...o]),...l!==void 0&&l>1&&{frameStep:l}},t},enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"pinToLandmark",{value:(i,o)=>(Eo(t,i,o),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"pinToObject",{value:(i,o)=>(Bo(t,i,o),t),enumerable:!1,writable:!0,configurable:!0});let n=(i,o)=>(t.matte={node:i,...o&&{mode:o}},t);for(let i of["withMatte","withMask"])Object.defineProperty(t,i,{value:n,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperty(t,"withRelief",{value:(i,o={})=>(t.relief={node:i,...o},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withPbrGlass",{value:i=>(t.glass=i??{},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"deformWithAudio",{value:i=>(t.audioDeform=i??{},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withCrop",{value:i=>(t.crop=i instanceof Wr?i:new Wr(i),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withVision",{value:i=>(t.vision=i instanceof wt?i:new wt(i),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withRelighting",{value:i=>(t.relighting=i??{},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"relight",{value:i=>(t.relighting=i??{},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withDeflicker",{value:i=>(t.deflicker=i??{},t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"apply",{value:i=>(t.effects||(t.effects=[]),t.effects.push(i),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withEffect",{value:i=>(t.effects||(t.effects=[]),t.effects.push(i),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withEffects",{value:i=>(t.effects||(t.effects=[]),t.effects.push(...i),t),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"section",{value:(i={},o)=>i!==null&&typeof i=="object"&&"bounds"in i?B.section(t,i,o):B.section(t,i),enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"blurRegion",{value:(i,o)=>{let a=new Ft({track:i,strength:o?.strength??25,shape:o?.shape??"ellipse",...o});return t.effects||(t.effects=[]),t.effects.push(a),t},enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(t,"withBlurRegion",{value:(i,o)=>t.blurRegion(i,o),enumerable:!1,writable:!0,configurable:!0}),cS(t),t}var lS=[{prop:"roughness",fallback:.5},{prop:"metallic",fallback:0},{prop:"emissiveIntensity",fallback:1},{prop:"clearcoat",fallback:0},{prop:"clearcoatRoughness",fallback:.08},{prop:"anisotropy",fallback:0},{prop:"anisotropyRotation",fallback:0},{prop:"subsurface",fallback:0},{prop:"sheen",fallback:0},{prop:"sheenRoughness",fallback:.5},{prop:"iridescence",fallback:0},{prop:"iridescenceThickness",fallback:400},{prop:"iridescenceIor",fallback:1.3},{prop:"triplanarScale",fallback:1},{prop:"triplanarSharpness",fallback:4}];function cS(e){let t=e,r;for(let{prop:n,fallback:i}of lS){let o=t[n];Ln(o)&&(r??=Q.create(),r.signal(n,o),t[n]=i)}r&&e.animate(r)}var B={video:(e,t={})=>je({id:t.id??Y("video"),kind:"media",inputHandleId:e,dataType:"Video",fit:t.fit??"cover",...t}),image:(e,t={})=>(typeof e=="string"&&(/\.(json|lottie)(\?.*)?$/i.test(e)||e.startsWith("data:application/json")?console.warn(`[Layer.image] '${e}' is a Lottie vector animation, not a static image. Use Layer.lottie('${e}', options) instead.`):/\.(mp4|mov|webm|mkv)(\?.*)?$/i.test(e)?console.warn(`[Layer.image] '${e}' is a video file, not a static image. Use Layer.video('${e}', options) instead.`):/\.(mp3|wav|ogg|m4a|aac)(\?.*)?$/i.test(e)&&console.warn(`[Layer.image] '${e}' is an audio file, not a static image. Use Layer.audio('${e}', options) instead.`)),je({id:t.id??Y("img"),kind:"media",inputHandleId:e,dataType:"Image",fit:t.fit??"cover",...t})),svg:(e,t={})=>je({id:t.id??Y("svg"),kind:"media",inputHandleId:e,dataType:"SVG",fit:t.fit??"contain",...t}),lottie:(e,t={})=>je({id:t.id??Y("lottie"),kind:"media",inputHandleId:e,dataType:"Lottie",fit:t.fit??"contain",...t}),audio:(e,t={})=>je({id:t.id??Y("audio"),kind:"media",inputHandleId:e,dataType:"Audio",volume:t.volume??1,...t}),text:(e,t={})=>{let r=Array.isArray(e),n=!r&&typeof e=="object"&&e!==null,i=n?e:t,o="",a=i.spans;if(r){let u=bi(e);o=u.text,a=u.spans}else n?i.spans&&!i.text?o=bi(i.spans).text:o=i.text??"":o=typeof e=="string"?e:String(e??"");return je({id:i.id??Y("text"),kind:"text",fontFamily:i.fontFamily??_e.getAll()[0]?.family??"Inter",fontSize:i.fontSize??48,fill:i.fill??"#ffffff",...i,text:i.text??o,spans:i.spans??a})},caption:(e,t={})=>je({id:t.id??Y("caption"),kind:"media",inputHandleId:e,dataType:t.dataType??"Caption",fontFamily:t.fontFamily??_e.getAll()[0]?.family??"Inter",fontSize:t.fontSize??48,fill:t.fill??"#ffffff",...t}),shape:(e="rect",t={})=>{let{fill:r,...n}=t;return je({id:n.id??Y("shape"),kind:"shape",shapeType:n.shapeType??e,...n,fillColor:n.fillColor??r??"#3b82f6"})},flex:(e={})=>je({id:e.id??Y("flex"),kind:"flex",dir:e.dir??"column",children:e.children??[],...e}),box:(e={})=>je({id:e.id??Y("box"),kind:"box",background:e.background??"transparent",children:e.children??[],...e}),particles:e=>{let t=new Pn(e),r={metadata:{width:e.width,height:e.height},operation:{...t.toOperation(),effect:t,dataType:"Video"},children:[]};return je({id:e.id??Y("particles"),kind:"media",dataType:"Video",src:r,position:"absolute",x:e.x??0,y:e.y??0,width:e.width,height:e.height,...e.startFrame!==void 0&&{startFrame:e.startFrame},...e.durationFrames!==void 0&&{durationFrames:e.durationFrames},...e.zIndex!==void 0&&{zIndex:e.zIndex}})},vfx:e=>{let{x:t,y:r,id:n,startFrame:i,durationFrames:o,zIndex:a,...u}=e,l=new Xo({outputType:"Video",...u}),c={metadata:{width:e.width,height:e.height},operation:{...l.toOperation(),effect:l,dataType:"Video"},children:[]};return je({id:n??Y("vfx"),kind:"media",dataType:"Video",src:c,position:"absolute",x:t??0,y:r??0,width:e.width,height:e.height,...i!==void 0&&{startFrame:i},...o!==void 0&&{durationFrames:o},...a!==void 0&&{zIndex:a}})},section:(e,t={},r={})=>{let n=e;if(e&&typeof e=="object"&&"toSpec"in e&&"children"in e){let w=(e.children||[]).find(R=>R.kind==="media"&&(R.dataType==="Video"||R.dataType==="Image"));w&&(n=w)}let i=t!==null&&typeof t=="object"&&"bounds"in t,o=i?r:t,a=i?t:void 0,u=o.padding??0,l=typeof n=="string"?n:n?.inputHandleId??n?.src??"",c=typeof n=="object"&&n?.dataType?n.dataType:"Video",m=o.compositionWidth??o.compWidth??(i?o.width:void 0)??1920,d=o.compositionHeight??o.compHeight??(i?o.height:void 0)??1080,p=Array.isArray(o.effects)?[...o.effects]:o.effects?[o.effects]:[],f=a?a.bounds.screenX.multiply(-1).add(u):typeof o.x=="number"?-o.x:o.x&&typeof o.x.multiply=="function"?o.x.multiply(-1):0,b=a?a.bounds.screenY.multiply(-1).add(u):typeof o.y=="number"?-o.y:o.y&&typeof o.y.multiply=="function"?o.y.multiply(-1):0,g=(c==="Image"?B.image(l,{position:"absolute",width:m,height:d,fit:o.fit??"cover",x:f,y:b}):B.video(l,{position:"absolute",width:m,height:d,fit:o.fit??"cover",x:f,y:b})).withEffects(p),y=a?a.bounds.screenWidth.add(u*2):o.width!==void 0?o.width:m,T=a?a.bounds.screenHeight.add(u*2):o.height!==void 0?o.height:d,M=[g,...o.children??[]],v=o.id??(a?Y(`section-track-${a.trackId}`):Y("section")),x=B.box({id:v,position:o.position??"absolute",width:y,height:T,x:a?void 0:o.x,y:a?void 0:o.y,borderRadius:o.borderRadius??0,borderColor:o.borderColor,borderWidth:o.borderWidth,opacity:o.opacity??1,overflow:"hidden",children:M});a&&(x=x.pinToObject(a,{anchor:"topLeft",offsetX:-u,offsetY:-u,hideWhenLost:o.hideWhenLost??!0,smoothFrames:o.smoothFrames}));let A=x;return Object.defineProperty(A,"innerMedia",{value:g,enumerable:!0,writable:!1}),Object.defineProperty(A,"effects",{get:()=>p,enumerable:!0}),Object.defineProperty(A,"addEffect",{value:w=>(p.push(w),g.effects=p,A),enumerable:!0,writable:!1}),Object.defineProperty(A,"withEffect",{value:w=>A.addEffect(w),enumerable:!0,writable:!1}),Object.defineProperty(A,"withEffects",{value:w=>{for(let R of w)A.addEffect(R);return A},enumerable:!0,writable:!1}),A},trackedRegion:(e,t,r={})=>B.section(e,t,r),blurTrackedRegion:(e,t,r={})=>{let{padding:n,borderRadius:i,borderColor:o,borderWidth:a,...u}=r;return B.section(e,t,{padding:n??8,borderRadius:i??12,borderColor:o,borderWidth:a,effects:[new Ft({strength:u.strength??25,blurType:u.blurType??"Gaussian",...u})]})},chart:(e,t={})=>ip(e,t,_e.getAll()[0]?.family??"Inter"),camera:(e={})=>{let{fov:t,focalLength:r,sensorWidth:n,near:i,far:o,zoom:a,lens:u,...l}=e,m=t!==void 0||r!==void 0||n!==void 0||i!==void 0||o!==void 0||a!==void 0||u!==void 0?{...u,...t!==void 0&&{fov:t},...r!==void 0&&{focalLength:r},...n!==void 0&&{sensorWidth:n},...i!==void 0&&{near:i},...o!==void 0&&{far:o},...a!==void 0&&{zoom:a}}:void 0;return je({id:l.id??Y("camera"),kind:"camera",mode:l.mode??"lookAt",pitch:l.pitch??0,yaw:l.yaw??0,roll:l.roll??0,...l,...m!==void 0&&{lens:m}})},light:(e={})=>rr({id:e.id??Y("light"),kind:"light",lightType:e.lightType??"point",color:e.color??"#ffffff",intensity:1},e),ambientLight:(e="#ffffff",t=.5,r={})=>nt.ambient(e,t,r),sequence:(e,t)=>Ap(e,t),environment:(e="studio",t={})=>nt.environment(e,t),directionalLight:(e={})=>nt.directional(e),pointLight:(e={})=>nt.point(e),spotLight:(e={})=>nt.spot(e),rectLight:(e={})=>nt.rect(e),cube:e=>we.cube(e),carousel3d:e=>we.carousel(e),plane3d:e=>we.plane(e),prism3d:(e={})=>we.prism(e),model:(e={})=>je({id:e.id??Y("model3d"),kind:"model3d",is3D:e.is3D??!0,modelFormat:e.modelFormat??"auto",loop:e.loop??!0,scale:e.scale??1,scaleX:e.scaleX??1,scaleY:e.scaleY??1,scaleZ:e.scaleZ??1,opacity:e.opacity??1,...e}),obj:(e,t={})=>B.model({src:e,modelFormat:"obj",...t}),fbx:(e,t={})=>B.model({src:e,modelFormat:"fbx",...t}),gltf:(e,t={})=>B.model({src:e,modelFormat:"gltf",...t}),glb:(e,t={})=>B.model({src:e,modelFormat:"glb",...t}),stl:(e,t={})=>B.model({src:e,modelFormat:"stl",...t}),ply:(e,t={})=>B.model({src:e,modelFormat:"ply",...t}),vox:(e,t={})=>B.model({src:e,modelFormat:"vox",...t}),threeDS:(e,t={})=>B.model({src:e,modelFormat:"3ds",...t}),off:(e,t={})=>B.model({src:e,modelFormat:"off",...t})};function mS(e){return/\.(hdr|exr)$/i.test(e)}var dS=[{prop:"intensity",fallback:1},{prop:"x",fallback:0},{prop:"y",fallback:0},{prop:"z",fallback:0},{prop:"targetX",fallback:0},{prop:"targetY",fallback:0},{prop:"targetZ",fallback:0},{prop:"radius",fallback:1e3},{prop:"angle",fallback:45},{prop:"penumbra",fallback:.2},{prop:"decay",fallback:1},{prop:"width",fallback:240},{prop:"height",fallback:140},{prop:"rotation",fallback:0},{prop:"exposure",fallback:0},{prop:"volumetricFogDensity",fallback:.02},{prop:"volumetricFogAnisotropy",fallback:.55},{prop:"volumetricFogNoiseStrength",fallback:.45}];function Ln(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.get=="function"||typeof t.inputHandleId=="string"||typeof t.gpuBinding=="object"}function rr(e,t){let r={...e,...t},n=[];for(let{prop:a,fallback:u}of dS){let l=r[a];if(Ln(l)){n.push([a,l]);let c=e[a];r[a]=typeof c=="number"?c:u}}let i=r.volumetricFog;if(i&&typeof i=="object"){let a={...i};if(Ln(a.density)&&(n.push(["volumetricFogDensity",a.density]),a.density=.02),Ln(a.anisotropy)&&(n.push(["volumetricFogAnisotropy",a.anisotropy]),a.anisotropy=.55),a.noise&&typeof a.noise=="object"){let u={...a.noise};Ln(u.strength)&&(n.push(["volumetricFogNoiseStrength",u.strength]),u.strength=.45),a.noise=u}r.volumetricFog=a}let o=je(r);if(n.length>0){let a=Q.create();for(let[u,l]of n)a.signal(u,l);o=o.animate(a)}return o}var nt={environment:(e="studio",t={})=>{let n={...typeof e!="string"?e:mS(e)?{hdri:e}:{preset:e},...t};return rr({id:n.id??Y("environment"),kind:"light",lightType:"environment",preset:"studio",intensity:1},n)},ambient:(e="#ffffff",t=.5,r={})=>{let n={color:typeof e=="string"?e:e.color??"#ffffff",intensity:t,...typeof e=="object"&&e,...r};return rr({id:n.id??Y("light-ambient"),kind:"light",lightType:"ambient",color:"#ffffff",intensity:.5},n)},directional:(e={})=>rr({id:e.id??Y("light-directional"),kind:"light",lightType:"directional",color:e.color??"#ffffff",intensity:1,x:0,y:-1e3,z:-1e3,targetX:0,targetY:0,targetZ:0},e),point:(e={})=>rr({id:e.id??Y("light-point"),kind:"light",lightType:"point",color:e.color??"#ffffff",intensity:1,x:0,y:0,z:-500,radius:1e3,decay:1},e),spot:(e={})=>rr({id:e.id??Y("light-spot"),kind:"light",lightType:"spot",color:e.color??"#ffffff",intensity:1,x:0,y:-500,z:-1e3,targetX:0,targetY:0,targetZ:0,angle:45,penumbra:.2,radius:2e3,decay:1},e),rect:(e={})=>rr({id:e.id??Y("light-rect"),kind:"light",lightType:"rect",color:e.color??"#ffffff",intensity:1,x:0,y:-300,z:-800,targetX:0,targetY:0,targetZ:0,width:240,height:140,twoSided:!1,radius:2e3,decay:1.5},e)};function LN(e,t={},r={}){return B.section(e,t,r)}function EN(e,t,r={}){return typeof e=="object"&&"blurRegion"in e?e.blurRegion(t,r):B.blurTrackedRegion(e,t,r)}function BN(e,t,r={}){return B.section(e,t,r)}var pS=Object.assign(ir,Zo,{blur:e=>new Ft(e),vignette:e=>new lr(e),colorBalance:e=>new zo(e),colorKey:e=>new _o(e),levels:e=>new qo(e),filmGrain:e=>new lt(e),curves:e=>new Qo(e),selectiveColor:e=>new Jo(e),gradientMap:e=>new Lt(e),shadowsHighlights:e=>new ea(e),applyLut:e=>new ta(e),unsharpMask:e=>new ra(e),highPass:e=>new na(e),halftoneScreen:e=>new Gr(e),tileOffset:e=>new ia(e),motionBlur:e=>new oa(e),ssao:e=>new aa(e),pbrGlass:e=>new sa(e),depthOfField:e=>new ua(e),crop:e=>new Wr(e),vision:e=>new wt(e),relight3d:e=>new la(e),modulate:e=>new ma(e),deflicker:e=>new ca(e),custom:(e,t={})=>new Ko(e,t)});var fS=/\.(png|jpe?g|webp|gif|avif|tiff?|bmp)(\?.*)?$/i,hS=/\.svg(\?.*)?$/i;function gS(e){let t=r=>r?{...r,enabled:!0}:void 0;return new Wo({...e.dropShadow&&{dropShadow:t(e.dropShadow)},...e.outerGlow&&{outerGlow:t(e.outerGlow)},...e.innerShadow&&{innerShadow:t(e.innerShadow)},...e.stroke&&{stroke:t(e.stroke)}})}function bS(e,t){let r=Math.max(16,Math.round(e)),n=Math.max(16,Math.round(t));return`data:image/svg+xml;utf8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${n}"><rect width="${r}" height="${n}" fill="#808080"/></svg>`)}`}var Rf={box:e=>B.box(e),flex:e=>B.flex(e),text:(e,t)=>B.text(e,t),shape:(e,t)=>B.shape(e,t),measure:(e,t)=>_e.measure(e,t),fonts:()=>_e.getAll().map(e=>e.family),autoId:Y,media:(e,t)=>hS.test(e)?B.svg(e,t):fS.test(e)?B.image(e,t):B.video(e,{muted:!0,...t}),style:(e,t)=>(e.withEffect(gS(t)),e),cutout:(e,{mode:t="person",...r})=>B.video(e,{muted:!0,volume:0,fit:"cover",...r}).withVision({mode:"matte",enableSegmentation:!0,variant:t==="subject"?"m":"s",confidence:.25,featherRadius:.04,keyBackground:!0}),particles:e=>B.particles(e),signal:(e,t)=>Cu([...e],t),grain:({id:e,x:t,y:r,width:n,height:i,strength:o,size:a})=>B.svg(bS(n,i),{id:e,position:"absolute",x:t,y:r,width:n,height:i,fit:"fill",blendMode:"soft-light"}).withEffect(new lt({strength:o,...a!==void 0&&{size:a},shadows:1,midtones:1,highlights:1})),extrudedText:({fontWeight:e,...t})=>we.extrudedText({...t,...e!==void 0&&{fontWeight:String(e)},align:"center",verticalAlign:"middle"}),matte:(e,t,r="alpha")=>(e.withMatte(t,r),e)};h();async function Cf(e,t={}){let r=await Ju(e);if(!r||r.channels.length===0)throw new Error(`analyzeAudio: could not decode audio from ${e}`);return _c(r.channels,r.sampleRate,t)}function sS(e){return Jc(Rf,e)}export{ha as a,bl as b,yl as c,xl as d,Vf as e,Uf as f,Sl as g,ga as h,$f as i,wl as j,Gf as k,vl as l,ba as m,kl as n,Pl as o,Tl as p,Ml as q,Al as r,Cl as s,ya as t,Yr as u,Dl as v,Rl as w,cr as x,Ol as y,Nl as z,Fl as A,Ll as B,ei as C,ti as D,El as E,Bl as F,ri as G,Il as H,jl as I,zl as J,_l as K,Vl as L,Ul as M,$l as N,mr as O,Wf as P,xa as Q,Sa as R,wa as S,va as T,ka as U,G1 as V,W1 as W,X1 as X,Hr as Y,Q as Z,pa as _,Ta as $,Ca as aa,oc as ba,ac as ca,sc as da,lc as ea,wh as fa,cc as ga,mc as ha,dc as ia,pc as ja,fc as ka,hc as la,gc as ma,bc as na,yc as oa,xc as pa,Sc as qa,wc as ra,vc as sa,kc as ta,Pc as ua,Tc as va,Mc as wa,Ac as xa,Cc as ya,Oh as za,Dc as Aa,Oa as Ba,Nh as Ca,Rc as Da,Oc as Ea,Nc as Fa,Fh as Ga,Fc as Ha,Xr as Ia,Na as Ja,tn as Ka,rn as La,nn as Ma,pr as Na,Ge as Oa,an as Pa,Ga as Qa,zg as Ra,_g as Sa,Vg as Ta,Ug as Ua,$g as Va,Gg as Wa,Wg as Xa,Hg as Ya,Yg as Za,Xg as _a,Zg as $a,qg as ab,bi as bb,Kg as cb,np as db,ap as eb,_s as fb,kn as gb,Yi as hb,Pn as ib,Ys as jb,Xs as kb,Tn as lb,ge as mb,we as nb,Mp as ob,Q0 as pb,An as qb,Fr as rb,Cn as sb,Dn as tb,Lr as ub,wx as vb,vx as wb,qx as xb,jh as yb,ai as zb,Zr as Ab,Fa as Bb,zh as Cb,_h as Db,Sw as Eb,Ec as Fb,Bc as Gb,Wh as Hb,_c as Ib,Tw as Jb,Mw as Kb,Aw as Lb,Vc as Mb,Rw as Nb,ui as Ob,Yh as Pb,Ow as Qb,Nw as Rb,qr as Sb,Ew as Tb,Bw as Ub,Uc as Vb,La as Wb,li as Xb,$c as Yb,Iw as Zb,Ba as _b,Zh as $b,Kr as ac,$w as bc,Gw as cc,Ww as dc,Hw as ec,ci as fc,Yw as gc,qh as hc,Kh as ic,Xw as jc,Zw as kc,qw as lc,Qr as mc,ja as nc,Hc as oc,Yc as pc,Zc as qc,Jr as rc,ov as sc,Jh as tc,eg as uc,rg as vc,dv as wc,ig as xc,og as yc,Jc as zc,$a as Ac,em as Bc,tm as Cc,rm as Dc,hv as Ec,dt as Fc,gv as Gc,wv as Hc,en as Ic,vv as Jc,kv as Kc,Pv as Lc,Tv as Mc,Mv as Nc,Av as Oc,di as Pc,Ov as Qc,Nv as Rc,Fv as Sc,Lv as Tc,Ev as Uc,Bv as Vc,Iv as Wc,fg as Xc,_v as Yc,$v as Zc,Yv as _c,hg as $c,Kv as ad,Qv as bd,t1 as cd,im as dd,gg as ed,om as fd,o1 as gd,xg as hd,vg as id,sm as jd,a1 as kd,l1 as ld,Cf as md,sS as nd,Mf as od,Af as pd,B as qd,nt as rd,LN as sd,EN as td,BN as ud,pS as vd};
|
|
637
|
+
/*! Bundled license information:
|
|
638
|
+
|
|
639
|
+
aws4fetch/dist/aws4fetch.esm.mjs:
|
|
640
|
+
(**
|
|
641
|
+
* @license MIT <https://opensource.org/licenses/MIT>
|
|
642
|
+
* @copyright Michael Hart 2024
|
|
643
|
+
*)
|
|
644
|
+
*/
|